handle cases where an empty array is provided by using this as default, also correctl...
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * Internationalisation code
4 *
5 * @file
6 * @ingroup Language
7 */
8
9 /**
10 * @defgroup Language Language
11 */
12
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
16 }
17
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
21
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
24 }
25
26 /**
27 * a fake language converter
28 *
29 * @ingroup Language
30 */
31 class FakeConverter {
32
33 /**
34 * @var Language
35 */
36 var $mLang;
37 function __construct( $langobj ) { $this->mLang = $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang->getCode() ); }
43 function getPreferredVariant() { return $this->mLang->getCode(); }
44 function getDefaultVariant() { return $this->mLang->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
54 }
55
56 /**
57 * Internationalisation code
58 * @ingroup Language
59 */
60 class Language {
61
62 /**
63 * @var LanguageConverter
64 */
65 var $mConverter;
66
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
70
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
73
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
75
76 /**
77 * ReplacementArray object caches
78 */
79 var $transformData = array();
80
81 /**
82 * @var LocalisationCache
83 */
84 static public $dataCache;
85
86 static public $mLangObjCache = array();
87
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
90 'friday', 'saturday'
91 );
92
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
95 );
96
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
100 'december'
101 );
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
105 'december-gen'
106 );
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
110 );
111
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
117 );
118
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
125 );
126
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
133 );
134
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
140 );
141
142 /**
143 * Get a cached language object for a given language code
144 * @param $code String
145 * @return Language
146 */
147 static function factory( $code ) {
148 if ( !isset( self::$mLangObjCache[$code] ) ) {
149 if ( count( self::$mLangObjCache ) > 10 ) {
150 // Don't keep a billion objects around, that's stupid.
151 self::$mLangObjCache = array();
152 }
153 self::$mLangObjCache[$code] = self::newFromCode( $code );
154 }
155 return self::$mLangObjCache[$code];
156 }
157
158 /**
159 * Create a language object for a given language code
160 * @param $code String
161 * @throws MWException
162 * @return Language
163 */
164 protected static function newFromCode( $code ) {
165 // Protect against path traversal below
166 if ( !Language::isValidCode( $code )
167 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
168 {
169 throw new MWException( "Invalid language code \"$code\"" );
170 }
171
172 if ( !Language::isValidBuiltInCode( $code ) ) {
173 // It's not possible to customise this code with class files, so
174 // just return a Language object. This is to support uselang= hacks.
175 $lang = new Language;
176 $lang->setCode( $code );
177 return $lang;
178 }
179
180 // Check if there is a language class for the code
181 $class = self::classFromCode( $code );
182 self::preloadLanguageClass( $class );
183 if ( MWInit::classExists( $class ) ) {
184 $lang = new $class;
185 return $lang;
186 }
187
188 // Keep trying the fallback list until we find an existing class
189 $fallbacks = Language::getFallbacksFor( $code );
190 foreach ( $fallbacks as $fallbackCode ) {
191 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
192 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
193 }
194
195 $class = self::classFromCode( $fallbackCode );
196 self::preloadLanguageClass( $class );
197 if ( MWInit::classExists( $class ) ) {
198 $lang = Language::newFromCode( $fallbackCode );
199 $lang->setCode( $code );
200 return $lang;
201 }
202 }
203
204 throw new MWException( "Invalid fallback sequence for language '$code'" );
205 }
206
207 /**
208 * Returns true if a language code string is of a valid form, whether or
209 * not it exists. This includes codes which are used solely for
210 * customisation via the MediaWiki namespace.
211 *
212 * @param $code string
213 *
214 * @return bool
215 */
216 public static function isValidCode( $code ) {
217 return
218 strcspn( $code, ":/\\\000" ) === strlen( $code )
219 && !preg_match( Title::getTitleInvalidRegex(), $code );
220 }
221
222 /**
223 * Returns true if a language code is of a valid form for the purposes of
224 * internal customisation of MediaWiki, via Messages*.php.
225 *
226 * @param $code string
227 *
228 * @since 1.18
229 * @return bool
230 */
231 public static function isValidBuiltInCode( $code ) {
232 return preg_match( '/^[a-z0-9-]+$/i', $code );
233 }
234
235 /**
236 * @param $code
237 * @return String Name of the language class
238 */
239 public static function classFromCode( $code ) {
240 if ( $code == 'en' ) {
241 return 'Language';
242 } else {
243 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
244 }
245 }
246
247 /**
248 * Includes language class files
249 *
250 * @param $class string Name of the language class
251 */
252 public static function preloadLanguageClass( $class ) {
253 global $IP;
254
255 if ( $class === 'Language' ) {
256 return;
257 }
258
259 if ( !defined( 'MW_COMPILED' ) ) {
260 // Preload base classes to work around APC/PHP5 bug
261 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
262 include_once( "$IP/languages/classes/$class.deps.php" );
263 }
264 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
265 include_once( "$IP/languages/classes/$class.php" );
266 }
267 }
268 }
269
270 /**
271 * Get the LocalisationCache instance
272 *
273 * @return LocalisationCache
274 */
275 public static function getLocalisationCache() {
276 if ( is_null( self::$dataCache ) ) {
277 global $wgLocalisationCacheConf;
278 $class = $wgLocalisationCacheConf['class'];
279 self::$dataCache = new $class( $wgLocalisationCacheConf );
280 }
281 return self::$dataCache;
282 }
283
284 function __construct() {
285 $this->mConverter = new FakeConverter( $this );
286 // Set the code to the name of the descendant
287 if ( get_class( $this ) == 'Language' ) {
288 $this->mCode = 'en';
289 } else {
290 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
291 }
292 self::getLocalisationCache();
293 }
294
295 /**
296 * Reduce memory usage
297 */
298 function __destruct() {
299 foreach ( $this as $name => $value ) {
300 unset( $this->$name );
301 }
302 }
303
304 /**
305 * Hook which will be called if this is the content language.
306 * Descendants can use this to register hook functions or modify globals
307 */
308 function initContLang() { }
309
310 /**
311 * Same as getFallbacksFor for current language.
312 * @return array|bool
313 * @deprecated in 1.19
314 */
315 function getFallbackLanguageCode() {
316 wfDeprecated( __METHOD__ );
317 return self::getFallbackFor( $this->mCode );
318 }
319
320 /**
321 * @return array
322 * @since 1.19
323 */
324 function getFallbackLanguages() {
325 return self::getFallbacksFor( $this->mCode );
326 }
327
328 /**
329 * Exports $wgBookstoreListEn
330 * @return array
331 */
332 function getBookstoreList() {
333 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
334 }
335
336 /**
337 * @return array
338 */
339 public function getNamespaces() {
340 if ( is_null( $this->namespaceNames ) ) {
341 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
342
343 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
344 $validNamespaces = MWNamespace::getCanonicalNamespaces();
345
346 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
347
348 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
349 if ( $wgMetaNamespaceTalk ) {
350 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
351 } else {
352 $talk = $this->namespaceNames[NS_PROJECT_TALK];
353 $this->namespaceNames[NS_PROJECT_TALK] =
354 $this->fixVariableInNamespace( $talk );
355 }
356
357 # Sometimes a language will be localised but not actually exist on this wiki.
358 foreach ( $this->namespaceNames as $key => $text ) {
359 if ( !isset( $validNamespaces[$key] ) ) {
360 unset( $this->namespaceNames[$key] );
361 }
362 }
363
364 # The above mixing may leave namespaces out of canonical order.
365 # Re-order by namespace ID number...
366 ksort( $this->namespaceNames );
367
368 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
369 }
370 return $this->namespaceNames;
371 }
372
373 /**
374 * Arbitrarily set all of the namespace names at once. Mainly used for testing
375 * @param $namespaces Array of namespaces (id => name)
376 */
377 public function setNamespaces( array $namespaces ) {
378 $this->namespaceNames = $namespaces;
379 }
380
381 /**
382 * A convenience function that returns the same thing as
383 * getNamespaces() except with the array values changed to ' '
384 * where it found '_', useful for producing output to be displayed
385 * e.g. in <select> forms.
386 *
387 * @return array
388 */
389 function getFormattedNamespaces() {
390 $ns = $this->getNamespaces();
391 foreach ( $ns as $k => $v ) {
392 $ns[$k] = strtr( $v, '_', ' ' );
393 }
394 return $ns;
395 }
396
397 /**
398 * Get a namespace value by key
399 * <code>
400 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
401 * echo $mw_ns; // prints 'MediaWiki'
402 * </code>
403 *
404 * @param $index Int: the array key of the namespace to return
405 * @return mixed, string if the namespace value exists, otherwise false
406 */
407 function getNsText( $index ) {
408 $ns = $this->getNamespaces();
409 return isset( $ns[$index] ) ? $ns[$index] : false;
410 }
411
412 /**
413 * A convenience function that returns the same thing as
414 * getNsText() except with '_' changed to ' ', useful for
415 * producing output.
416 *
417 * @param $index string
418 *
419 * @return array
420 */
421 function getFormattedNsText( $index ) {
422 $ns = $this->getNsText( $index );
423 return strtr( $ns, '_', ' ' );
424 }
425
426 /**
427 * Returns gender-dependent namespace alias if available.
428 * @param $index Int: namespace index
429 * @param $gender String: gender key (male, female... )
430 * @return String
431 * @since 1.18
432 */
433 function getGenderNsText( $index, $gender ) {
434 global $wgExtraGenderNamespaces;
435
436 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
437 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
438 }
439
440 /**
441 * Whether this language makes distinguishes genders for example in
442 * namespaces.
443 * @return bool
444 * @since 1.18
445 */
446 function needsGenderDistinction() {
447 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
448 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
449 // $wgExtraGenderNamespaces overrides everything
450 return true;
451 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
452 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
453 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
454 return false;
455 } else {
456 // Check what is in i18n files
457 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
458 return count( $aliases ) > 0;
459 }
460 }
461
462 /**
463 * Get a namespace key by value, case insensitive.
464 * Only matches namespace names for the current language, not the
465 * canonical ones defined in Namespace.php.
466 *
467 * @param $text String
468 * @return mixed An integer if $text is a valid value otherwise false
469 */
470 function getLocalNsIndex( $text ) {
471 $lctext = $this->lc( $text );
472 $ids = $this->getNamespaceIds();
473 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
474 }
475
476 /**
477 * @return array
478 */
479 function getNamespaceAliases() {
480 if ( is_null( $this->namespaceAliases ) ) {
481 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
482 if ( !$aliases ) {
483 $aliases = array();
484 } else {
485 foreach ( $aliases as $name => $index ) {
486 if ( $index === NS_PROJECT_TALK ) {
487 unset( $aliases[$name] );
488 $name = $this->fixVariableInNamespace( $name );
489 $aliases[$name] = $index;
490 }
491 }
492 }
493
494 global $wgExtraGenderNamespaces;
495 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
496 foreach ( $genders as $index => $forms ) {
497 foreach ( $forms as $alias ) {
498 $aliases[$alias] = $index;
499 }
500 }
501
502 $this->namespaceAliases = $aliases;
503 }
504 return $this->namespaceAliases;
505 }
506
507 /**
508 * @return array
509 */
510 function getNamespaceIds() {
511 if ( is_null( $this->mNamespaceIds ) ) {
512 global $wgNamespaceAliases;
513 # Put namespace names and aliases into a hashtable.
514 # If this is too slow, then we should arrange it so that it is done
515 # before caching. The catch is that at pre-cache time, the above
516 # class-specific fixup hasn't been done.
517 $this->mNamespaceIds = array();
518 foreach ( $this->getNamespaces() as $index => $name ) {
519 $this->mNamespaceIds[$this->lc( $name )] = $index;
520 }
521 foreach ( $this->getNamespaceAliases() as $name => $index ) {
522 $this->mNamespaceIds[$this->lc( $name )] = $index;
523 }
524 if ( $wgNamespaceAliases ) {
525 foreach ( $wgNamespaceAliases as $name => $index ) {
526 $this->mNamespaceIds[$this->lc( $name )] = $index;
527 }
528 }
529 }
530 return $this->mNamespaceIds;
531 }
532
533 /**
534 * Get a namespace key by value, case insensitive. Canonical namespace
535 * names override custom ones defined for the current language.
536 *
537 * @param $text String
538 * @return mixed An integer if $text is a valid value otherwise false
539 */
540 function getNsIndex( $text ) {
541 $lctext = $this->lc( $text );
542 $ns = MWNamespace::getCanonicalIndex( $lctext );
543 if ( $ns !== null ) {
544 return $ns;
545 }
546 $ids = $this->getNamespaceIds();
547 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
548 }
549
550 /**
551 * short names for language variants used for language conversion links.
552 *
553 * @param $code String
554 * @param $usemsg bool Use the "variantname-xyz" message if it exists
555 * @return string
556 */
557 function getVariantname( $code, $usemsg = true ) {
558 $msg = "variantname-$code";
559 list( $rootCode ) = explode( '-', $code );
560 if ( $usemsg && wfMessage( $msg )->exists() ) {
561 return $this->getMessageFromDB( $msg );
562 }
563 $name = self::fetchLanguageName( $code );
564 if ( $name ) {
565 return $name; # if it's defined as a language name, show that
566 } else {
567 # otherwise, output the language code
568 return $code;
569 }
570 }
571
572 /**
573 * @param $name string
574 * @return string
575 */
576 function specialPage( $name ) {
577 $aliases = $this->getSpecialPageAliases();
578 if ( isset( $aliases[$name][0] ) ) {
579 $name = $aliases[$name][0];
580 }
581 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
582 }
583
584 /**
585 * @return array
586 */
587 function getQuickbarSettings() {
588 return array(
589 $this->getMessage( 'qbsettings-none' ),
590 $this->getMessage( 'qbsettings-fixedleft' ),
591 $this->getMessage( 'qbsettings-fixedright' ),
592 $this->getMessage( 'qbsettings-floatingleft' ),
593 $this->getMessage( 'qbsettings-floatingright' ),
594 $this->getMessage( 'qbsettings-directionality' )
595 );
596 }
597
598 /**
599 * @return array
600 */
601 function getDatePreferences() {
602 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
603 }
604
605 /**
606 * @return array
607 */
608 function getDateFormats() {
609 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
610 }
611
612 /**
613 * @return array|string
614 */
615 function getDefaultDateFormat() {
616 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
617 if ( $df === 'dmy or mdy' ) {
618 global $wgAmericanDates;
619 return $wgAmericanDates ? 'mdy' : 'dmy';
620 } else {
621 return $df;
622 }
623 }
624
625 /**
626 * @return array
627 */
628 function getDatePreferenceMigrationMap() {
629 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
630 }
631
632 /**
633 * @param $image
634 * @return array|null
635 */
636 function getImageFile( $image ) {
637 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
638 }
639
640 /**
641 * @return array
642 */
643 function getExtraUserToggles() {
644 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
645 }
646
647 /**
648 * @param $tog
649 * @return string
650 */
651 function getUserToggle( $tog ) {
652 return $this->getMessageFromDB( "tog-$tog" );
653 }
654
655 /**
656 * Get native language names, indexed by code.
657 * Only those defined in MediaWiki, no other data like CLDR.
658 * If $customisedOnly is true, only returns codes with a messages file
659 *
660 * @param $customisedOnly bool
661 *
662 * @return array
663 * @deprecated in 1.20, use fetchLanguageNames()
664 */
665 public static function getLanguageNames( $customisedOnly = false ) {
666 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
667 }
668
669 /**
670 * Get translated language names. This is done on best effort and
671 * by default this is exactly the same as Language::getLanguageNames.
672 * The CLDR extension provides translated names.
673 * @param $code String Language code.
674 * @return Array language code => language name
675 * @since 1.18.0
676 * @deprecated in 1.20, use fetchLanguageNames()
677 */
678 public static function getTranslatedLanguageNames( $code ) {
679 return self::fetchLanguageNames( $code, 'all' );
680 }
681
682 /**
683 * Get an array of language names, indexed by code.
684 * @param $inLanguage null|string: Code of language in which to return the names
685 * Use null for autonyms (native names)
686 * @param $include string:
687 * 'all' all available languages
688 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames
689 * 'mwfile' only if the language is in 'mw' *and* has a message file
690 * @return array|bool: language code => language name, false if $include is wrong
691 * @since 1.20
692 */
693 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
694 global $wgExtraLanguageNames;
695 static $coreLanguageNames;
696
697 if ( $coreLanguageNames === null ) {
698 include( MWInit::compiledPath( 'languages/Names.php' ) );
699 }
700
701 $names = array();
702
703 if( $inLanguage ) {
704 # TODO: also include when $inLanguage is null, when this code is more efficient
705 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
706 }
707
708 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
709 foreach ( $mwNames as $mwCode => $mwName ) {
710 # - Prefer own MediaWiki native name when not using the hook
711 # TODO: prefer it always to make it consistent, but casing is different in CLDR
712 # - For other names just add if not added through the hook
713 if ( ( $mwCode === $inLanguage && !$inLanguage ) || !isset( $names[$mwCode] ) ) {
714 $names[$mwCode] = $mwName;
715 }
716 }
717
718 if ( $include === 'all' ) {
719 return $names;
720 }
721
722 $returnMw = array();
723 $coreCodes = array_keys( $mwNames );
724 foreach( $coreCodes as $coreCode ) {
725 $returnMw[$coreCode] = $names[$coreCode];
726 }
727
728 if( $include === 'mw' ) {
729 return $returnMw;
730 } elseif( $include === 'mwfile' ) {
731 $namesMwFile = array();
732 # We do this using a foreach over the codes instead of a directory
733 # loop so that messages files in extensions will work correctly.
734 foreach ( $returnMw as $code => $value ) {
735 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
736 $namesMwFile[$code] = $names[$code];
737 }
738 }
739 return $namesMwFile;
740 }
741 return false;
742 }
743
744 /**
745 * @param $code string: The code of the language for which to get the name
746 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
747 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
748 * @return string: Language name or empty
749 * @since 1.20
750 */
751 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
752 $array = self::fetchLanguageNames( $inLanguage, $include );
753 return !array_key_exists( $code, $array ) ? '' : $array[$code];
754 }
755
756 /**
757 * Get a message from the MediaWiki namespace.
758 *
759 * @param $msg String: message name
760 * @return string
761 */
762 function getMessageFromDB( $msg ) {
763 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
764 }
765
766 /**
767 * Get the native language name of $code.
768 * Only if defined in MediaWiki, no other data like CLDR.
769 * @param $code string
770 * @return string
771 * @deprecated in 1.20, use fetchLanguageName()
772 */
773 function getLanguageName( $code ) {
774 return self::fetchLanguageName( $code );
775 }
776
777 /**
778 * @param $key string
779 * @return string
780 */
781 function getMonthName( $key ) {
782 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
783 }
784
785 /**
786 * @return array
787 */
788 function getMonthNamesArray() {
789 $monthNames = array( '' );
790 for ( $i = 1; $i < 13; $i++ ) {
791 $monthNames[] = $this->getMonthName( $i );
792 }
793 return $monthNames;
794 }
795
796 /**
797 * @param $key string
798 * @return string
799 */
800 function getMonthNameGen( $key ) {
801 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
802 }
803
804 /**
805 * @param $key string
806 * @return string
807 */
808 function getMonthAbbreviation( $key ) {
809 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
810 }
811
812 /**
813 * @return array
814 */
815 function getMonthAbbreviationsArray() {
816 $monthNames = array( '' );
817 for ( $i = 1; $i < 13; $i++ ) {
818 $monthNames[] = $this->getMonthAbbreviation( $i );
819 }
820 return $monthNames;
821 }
822
823 /**
824 * @param $key string
825 * @return string
826 */
827 function getWeekdayName( $key ) {
828 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
829 }
830
831 /**
832 * @param $key string
833 * @return string
834 */
835 function getWeekdayAbbreviation( $key ) {
836 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
837 }
838
839 /**
840 * @param $key string
841 * @return string
842 */
843 function getIranianCalendarMonthName( $key ) {
844 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
845 }
846
847 /**
848 * @param $key string
849 * @return string
850 */
851 function getHebrewCalendarMonthName( $key ) {
852 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
853 }
854
855 /**
856 * @param $key string
857 * @return string
858 */
859 function getHebrewCalendarMonthNameGen( $key ) {
860 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
861 }
862
863 /**
864 * @param $key string
865 * @return string
866 */
867 function getHijriCalendarMonthName( $key ) {
868 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
869 }
870
871 /**
872 * This is a workalike of PHP's date() function, but with better
873 * internationalisation, a reduced set of format characters, and a better
874 * escaping format.
875 *
876 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
877 * PHP manual for definitions. There are a number of extensions, which
878 * start with "x":
879 *
880 * xn Do not translate digits of the next numeric format character
881 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
882 * xr Use roman numerals for the next numeric format character
883 * xh Use hebrew numerals for the next numeric format character
884 * xx Literal x
885 * xg Genitive month name
886 *
887 * xij j (day number) in Iranian calendar
888 * xiF F (month name) in Iranian calendar
889 * xin n (month number) in Iranian calendar
890 * xiy y (two digit year) in Iranian calendar
891 * xiY Y (full year) in Iranian calendar
892 *
893 * xjj j (day number) in Hebrew calendar
894 * xjF F (month name) in Hebrew calendar
895 * xjt t (days in month) in Hebrew calendar
896 * xjx xg (genitive month name) in Hebrew calendar
897 * xjn n (month number) in Hebrew calendar
898 * xjY Y (full year) in Hebrew calendar
899 *
900 * xmj j (day number) in Hijri calendar
901 * xmF F (month name) in Hijri calendar
902 * xmn n (month number) in Hijri calendar
903 * xmY Y (full year) in Hijri calendar
904 *
905 * xkY Y (full year) in Thai solar calendar. Months and days are
906 * identical to the Gregorian calendar
907 * xoY Y (full year) in Minguo calendar or Juche year.
908 * Months and days are identical to the
909 * Gregorian calendar
910 * xtY Y (full year) in Japanese nengo. Months and days are
911 * identical to the Gregorian calendar
912 *
913 * Characters enclosed in double quotes will be considered literal (with
914 * the quotes themselves removed). Unmatched quotes will be considered
915 * literal quotes. Example:
916 *
917 * "The month is" F => The month is January
918 * i's" => 20'11"
919 *
920 * Backslash escaping is also supported.
921 *
922 * Input timestamp is assumed to be pre-normalized to the desired local
923 * time zone, if any.
924 *
925 * @param $format String
926 * @param $ts String: 14-character timestamp
927 * YYYYMMDDHHMMSS
928 * 01234567890123
929 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
930 *
931 * @return string
932 */
933 function sprintfDate( $format, $ts ) {
934 $s = '';
935 $raw = false;
936 $roman = false;
937 $hebrewNum = false;
938 $unix = false;
939 $rawToggle = false;
940 $iranian = false;
941 $hebrew = false;
942 $hijri = false;
943 $thai = false;
944 $minguo = false;
945 $tenno = false;
946 for ( $p = 0; $p < strlen( $format ); $p++ ) {
947 $num = false;
948 $code = $format[$p];
949 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
950 $code .= $format[++$p];
951 }
952
953 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
954 $code .= $format[++$p];
955 }
956
957 switch ( $code ) {
958 case 'xx':
959 $s .= 'x';
960 break;
961 case 'xn':
962 $raw = true;
963 break;
964 case 'xN':
965 $rawToggle = !$rawToggle;
966 break;
967 case 'xr':
968 $roman = true;
969 break;
970 case 'xh':
971 $hebrewNum = true;
972 break;
973 case 'xg':
974 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
975 break;
976 case 'xjx':
977 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
978 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
979 break;
980 case 'd':
981 $num = substr( $ts, 6, 2 );
982 break;
983 case 'D':
984 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
985 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
986 break;
987 case 'j':
988 $num = intval( substr( $ts, 6, 2 ) );
989 break;
990 case 'xij':
991 if ( !$iranian ) {
992 $iranian = self::tsToIranian( $ts );
993 }
994 $num = $iranian[2];
995 break;
996 case 'xmj':
997 if ( !$hijri ) {
998 $hijri = self::tsToHijri( $ts );
999 }
1000 $num = $hijri[2];
1001 break;
1002 case 'xjj':
1003 if ( !$hebrew ) {
1004 $hebrew = self::tsToHebrew( $ts );
1005 }
1006 $num = $hebrew[2];
1007 break;
1008 case 'l':
1009 if ( !$unix ) {
1010 $unix = wfTimestamp( TS_UNIX, $ts );
1011 }
1012 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
1013 break;
1014 case 'N':
1015 if ( !$unix ) {
1016 $unix = wfTimestamp( TS_UNIX, $ts );
1017 }
1018 $w = gmdate( 'w', $unix );
1019 $num = $w ? $w : 7;
1020 break;
1021 case 'w':
1022 if ( !$unix ) {
1023 $unix = wfTimestamp( TS_UNIX, $ts );
1024 }
1025 $num = gmdate( 'w', $unix );
1026 break;
1027 case 'z':
1028 if ( !$unix ) {
1029 $unix = wfTimestamp( TS_UNIX, $ts );
1030 }
1031 $num = gmdate( 'z', $unix );
1032 break;
1033 case 'W':
1034 if ( !$unix ) {
1035 $unix = wfTimestamp( TS_UNIX, $ts );
1036 }
1037 $num = gmdate( 'W', $unix );
1038 break;
1039 case 'F':
1040 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1041 break;
1042 case 'xiF':
1043 if ( !$iranian ) {
1044 $iranian = self::tsToIranian( $ts );
1045 }
1046 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1047 break;
1048 case 'xmF':
1049 if ( !$hijri ) {
1050 $hijri = self::tsToHijri( $ts );
1051 }
1052 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1053 break;
1054 case 'xjF':
1055 if ( !$hebrew ) {
1056 $hebrew = self::tsToHebrew( $ts );
1057 }
1058 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1059 break;
1060 case 'm':
1061 $num = substr( $ts, 4, 2 );
1062 break;
1063 case 'M':
1064 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1065 break;
1066 case 'n':
1067 $num = intval( substr( $ts, 4, 2 ) );
1068 break;
1069 case 'xin':
1070 if ( !$iranian ) {
1071 $iranian = self::tsToIranian( $ts );
1072 }
1073 $num = $iranian[1];
1074 break;
1075 case 'xmn':
1076 if ( !$hijri ) {
1077 $hijri = self::tsToHijri ( $ts );
1078 }
1079 $num = $hijri[1];
1080 break;
1081 case 'xjn':
1082 if ( !$hebrew ) {
1083 $hebrew = self::tsToHebrew( $ts );
1084 }
1085 $num = $hebrew[1];
1086 break;
1087 case 't':
1088 if ( !$unix ) {
1089 $unix = wfTimestamp( TS_UNIX, $ts );
1090 }
1091 $num = gmdate( 't', $unix );
1092 break;
1093 case 'xjt':
1094 if ( !$hebrew ) {
1095 $hebrew = self::tsToHebrew( $ts );
1096 }
1097 $num = $hebrew[3];
1098 break;
1099 case 'L':
1100 if ( !$unix ) {
1101 $unix = wfTimestamp( TS_UNIX, $ts );
1102 }
1103 $num = gmdate( 'L', $unix );
1104 break;
1105 case 'o':
1106 if ( !$unix ) {
1107 $unix = wfTimestamp( TS_UNIX, $ts );
1108 }
1109 $num = gmdate( 'o', $unix );
1110 break;
1111 case 'Y':
1112 $num = substr( $ts, 0, 4 );
1113 break;
1114 case 'xiY':
1115 if ( !$iranian ) {
1116 $iranian = self::tsToIranian( $ts );
1117 }
1118 $num = $iranian[0];
1119 break;
1120 case 'xmY':
1121 if ( !$hijri ) {
1122 $hijri = self::tsToHijri( $ts );
1123 }
1124 $num = $hijri[0];
1125 break;
1126 case 'xjY':
1127 if ( !$hebrew ) {
1128 $hebrew = self::tsToHebrew( $ts );
1129 }
1130 $num = $hebrew[0];
1131 break;
1132 case 'xkY':
1133 if ( !$thai ) {
1134 $thai = self::tsToYear( $ts, 'thai' );
1135 }
1136 $num = $thai[0];
1137 break;
1138 case 'xoY':
1139 if ( !$minguo ) {
1140 $minguo = self::tsToYear( $ts, 'minguo' );
1141 }
1142 $num = $minguo[0];
1143 break;
1144 case 'xtY':
1145 if ( !$tenno ) {
1146 $tenno = self::tsToYear( $ts, 'tenno' );
1147 }
1148 $num = $tenno[0];
1149 break;
1150 case 'y':
1151 $num = substr( $ts, 2, 2 );
1152 break;
1153 case 'xiy':
1154 if ( !$iranian ) {
1155 $iranian = self::tsToIranian( $ts );
1156 }
1157 $num = substr( $iranian[0], -2 );
1158 break;
1159 case 'a':
1160 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1161 break;
1162 case 'A':
1163 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1164 break;
1165 case 'g':
1166 $h = substr( $ts, 8, 2 );
1167 $num = $h % 12 ? $h % 12 : 12;
1168 break;
1169 case 'G':
1170 $num = intval( substr( $ts, 8, 2 ) );
1171 break;
1172 case 'h':
1173 $h = substr( $ts, 8, 2 );
1174 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1175 break;
1176 case 'H':
1177 $num = substr( $ts, 8, 2 );
1178 break;
1179 case 'i':
1180 $num = substr( $ts, 10, 2 );
1181 break;
1182 case 's':
1183 $num = substr( $ts, 12, 2 );
1184 break;
1185 case 'c':
1186 if ( !$unix ) {
1187 $unix = wfTimestamp( TS_UNIX, $ts );
1188 }
1189 $s .= gmdate( 'c', $unix );
1190 break;
1191 case 'r':
1192 if ( !$unix ) {
1193 $unix = wfTimestamp( TS_UNIX, $ts );
1194 }
1195 $s .= gmdate( 'r', $unix );
1196 break;
1197 case 'U':
1198 if ( !$unix ) {
1199 $unix = wfTimestamp( TS_UNIX, $ts );
1200 }
1201 $num = $unix;
1202 break;
1203 case '\\':
1204 # Backslash escaping
1205 if ( $p < strlen( $format ) - 1 ) {
1206 $s .= $format[++$p];
1207 } else {
1208 $s .= '\\';
1209 }
1210 break;
1211 case '"':
1212 # Quoted literal
1213 if ( $p < strlen( $format ) - 1 ) {
1214 $endQuote = strpos( $format, '"', $p + 1 );
1215 if ( $endQuote === false ) {
1216 # No terminating quote, assume literal "
1217 $s .= '"';
1218 } else {
1219 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1220 $p = $endQuote;
1221 }
1222 } else {
1223 # Quote at end of string, assume literal "
1224 $s .= '"';
1225 }
1226 break;
1227 default:
1228 $s .= $format[$p];
1229 }
1230 if ( $num !== false ) {
1231 if ( $rawToggle || $raw ) {
1232 $s .= $num;
1233 $raw = false;
1234 } elseif ( $roman ) {
1235 $s .= self::romanNumeral( $num );
1236 $roman = false;
1237 } elseif ( $hebrewNum ) {
1238 $s .= self::hebrewNumeral( $num );
1239 $hebrewNum = false;
1240 } else {
1241 $s .= $this->formatNum( $num, true );
1242 }
1243 }
1244 }
1245 return $s;
1246 }
1247
1248 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1249 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1250
1251 /**
1252 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1253 * Gregorian dates to Iranian dates. Originally written in C, it
1254 * is released under the terms of GNU Lesser General Public
1255 * License. Conversion to PHP was performed by Niklas Laxström.
1256 *
1257 * Link: http://www.farsiweb.info/jalali/jalali.c
1258 *
1259 * @param $ts string
1260 *
1261 * @return string
1262 */
1263 private static function tsToIranian( $ts ) {
1264 $gy = substr( $ts, 0, 4 ) -1600;
1265 $gm = substr( $ts, 4, 2 ) -1;
1266 $gd = substr( $ts, 6, 2 ) -1;
1267
1268 # Days passed from the beginning (including leap years)
1269 $gDayNo = 365 * $gy
1270 + floor( ( $gy + 3 ) / 4 )
1271 - floor( ( $gy + 99 ) / 100 )
1272 + floor( ( $gy + 399 ) / 400 );
1273
1274 // Add days of the past months of this year
1275 for ( $i = 0; $i < $gm; $i++ ) {
1276 $gDayNo += self::$GREG_DAYS[$i];
1277 }
1278
1279 // Leap years
1280 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1281 $gDayNo++;
1282 }
1283
1284 // Days passed in current month
1285 $gDayNo += (int)$gd;
1286
1287 $jDayNo = $gDayNo - 79;
1288
1289 $jNp = floor( $jDayNo / 12053 );
1290 $jDayNo %= 12053;
1291
1292 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1293 $jDayNo %= 1461;
1294
1295 if ( $jDayNo >= 366 ) {
1296 $jy += floor( ( $jDayNo - 1 ) / 365 );
1297 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1298 }
1299
1300 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1301 $jDayNo -= self::$IRANIAN_DAYS[$i];
1302 }
1303
1304 $jm = $i + 1;
1305 $jd = $jDayNo + 1;
1306
1307 return array( $jy, $jm, $jd );
1308 }
1309
1310 /**
1311 * Converting Gregorian dates to Hijri dates.
1312 *
1313 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1314 *
1315 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1316 *
1317 * @param $ts string
1318 *
1319 * @return string
1320 */
1321 private static function tsToHijri( $ts ) {
1322 $year = substr( $ts, 0, 4 );
1323 $month = substr( $ts, 4, 2 );
1324 $day = substr( $ts, 6, 2 );
1325
1326 $zyr = $year;
1327 $zd = $day;
1328 $zm = $month;
1329 $zy = $zyr;
1330
1331 if (
1332 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1333 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1334 )
1335 {
1336 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1337 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1338 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1339 $zd - 32075;
1340 } else {
1341 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1342 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1343 }
1344
1345 $zl = $zjd -1948440 + 10632;
1346 $zn = (int)( ( $zl - 1 ) / 10631 );
1347 $zl = $zl - 10631 * $zn + 354;
1348 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1349 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1350 $zm = (int)( ( 24 * $zl ) / 709 );
1351 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1352 $zy = 30 * $zn + $zj - 30;
1353
1354 return array( $zy, $zm, $zd );
1355 }
1356
1357 /**
1358 * Converting Gregorian dates to Hebrew dates.
1359 *
1360 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1361 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1362 * to translate the relevant functions into PHP and release them under
1363 * GNU GPL.
1364 *
1365 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1366 * and Adar II is 14. In a non-leap year, Adar is 6.
1367 *
1368 * @param $ts string
1369 *
1370 * @return string
1371 */
1372 private static function tsToHebrew( $ts ) {
1373 # Parse date
1374 $year = substr( $ts, 0, 4 );
1375 $month = substr( $ts, 4, 2 );
1376 $day = substr( $ts, 6, 2 );
1377
1378 # Calculate Hebrew year
1379 $hebrewYear = $year + 3760;
1380
1381 # Month number when September = 1, August = 12
1382 $month += 4;
1383 if ( $month > 12 ) {
1384 # Next year
1385 $month -= 12;
1386 $year++;
1387 $hebrewYear++;
1388 }
1389
1390 # Calculate day of year from 1 September
1391 $dayOfYear = $day;
1392 for ( $i = 1; $i < $month; $i++ ) {
1393 if ( $i == 6 ) {
1394 # February
1395 $dayOfYear += 28;
1396 # Check if the year is leap
1397 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1398 $dayOfYear++;
1399 }
1400 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1401 $dayOfYear += 30;
1402 } else {
1403 $dayOfYear += 31;
1404 }
1405 }
1406
1407 # Calculate the start of the Hebrew year
1408 $start = self::hebrewYearStart( $hebrewYear );
1409
1410 # Calculate next year's start
1411 if ( $dayOfYear <= $start ) {
1412 # Day is before the start of the year - it is the previous year
1413 # Next year's start
1414 $nextStart = $start;
1415 # Previous year
1416 $year--;
1417 $hebrewYear--;
1418 # Add days since previous year's 1 September
1419 $dayOfYear += 365;
1420 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1421 # Leap year
1422 $dayOfYear++;
1423 }
1424 # Start of the new (previous) year
1425 $start = self::hebrewYearStart( $hebrewYear );
1426 } else {
1427 # Next year's start
1428 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1429 }
1430
1431 # Calculate Hebrew day of year
1432 $hebrewDayOfYear = $dayOfYear - $start;
1433
1434 # Difference between year's days
1435 $diff = $nextStart - $start;
1436 # Add 12 (or 13 for leap years) days to ignore the difference between
1437 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1438 # difference is only about the year type
1439 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1440 $diff += 13;
1441 } else {
1442 $diff += 12;
1443 }
1444
1445 # Check the year pattern, and is leap year
1446 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1447 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1448 # and non-leap years
1449 $yearPattern = $diff % 30;
1450 # Check if leap year
1451 $isLeap = $diff >= 30;
1452
1453 # Calculate day in the month from number of day in the Hebrew year
1454 # Don't check Adar - if the day is not in Adar, we will stop before;
1455 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1456 $hebrewDay = $hebrewDayOfYear;
1457 $hebrewMonth = 1;
1458 $days = 0;
1459 while ( $hebrewMonth <= 12 ) {
1460 # Calculate days in this month
1461 if ( $isLeap && $hebrewMonth == 6 ) {
1462 # Adar in a leap year
1463 if ( $isLeap ) {
1464 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1465 $days = 30;
1466 if ( $hebrewDay <= $days ) {
1467 # Day in Adar I
1468 $hebrewMonth = 13;
1469 } else {
1470 # Subtract the days of Adar I
1471 $hebrewDay -= $days;
1472 # Try Adar II
1473 $days = 29;
1474 if ( $hebrewDay <= $days ) {
1475 # Day in Adar II
1476 $hebrewMonth = 14;
1477 }
1478 }
1479 }
1480 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1481 # Cheshvan in a complete year (otherwise as the rule below)
1482 $days = 30;
1483 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1484 # Kislev in an incomplete year (otherwise as the rule below)
1485 $days = 29;
1486 } else {
1487 # Odd months have 30 days, even have 29
1488 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1489 }
1490 if ( $hebrewDay <= $days ) {
1491 # In the current month
1492 break;
1493 } else {
1494 # Subtract the days of the current month
1495 $hebrewDay -= $days;
1496 # Try in the next month
1497 $hebrewMonth++;
1498 }
1499 }
1500
1501 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1502 }
1503
1504 /**
1505 * This calculates the Hebrew year start, as days since 1 September.
1506 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1507 * Used for Hebrew date.
1508 *
1509 * @param $year int
1510 *
1511 * @return string
1512 */
1513 private static function hebrewYearStart( $year ) {
1514 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1515 $b = intval( ( $year - 1 ) % 4 );
1516 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1517 if ( $m < 0 ) {
1518 $m--;
1519 }
1520 $Mar = intval( $m );
1521 if ( $m < 0 ) {
1522 $m++;
1523 }
1524 $m -= $Mar;
1525
1526 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1527 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1528 $Mar++;
1529 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1530 $Mar += 2;
1531 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1532 $Mar++;
1533 }
1534
1535 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1536 return $Mar;
1537 }
1538
1539 /**
1540 * Algorithm to convert Gregorian dates to Thai solar dates,
1541 * Minguo dates or Minguo dates.
1542 *
1543 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1544 * http://en.wikipedia.org/wiki/Minguo_calendar
1545 * http://en.wikipedia.org/wiki/Japanese_era_name
1546 *
1547 * @param $ts String: 14-character timestamp
1548 * @param $cName String: calender name
1549 * @return Array: converted year, month, day
1550 */
1551 private static function tsToYear( $ts, $cName ) {
1552 $gy = substr( $ts, 0, 4 );
1553 $gm = substr( $ts, 4, 2 );
1554 $gd = substr( $ts, 6, 2 );
1555
1556 if ( !strcmp( $cName, 'thai' ) ) {
1557 # Thai solar dates
1558 # Add 543 years to the Gregorian calendar
1559 # Months and days are identical
1560 $gy_offset = $gy + 543;
1561 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1562 # Minguo dates
1563 # Deduct 1911 years from the Gregorian calendar
1564 # Months and days are identical
1565 $gy_offset = $gy - 1911;
1566 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1567 # Nengō dates up to Meiji period
1568 # Deduct years from the Gregorian calendar
1569 # depending on the nengo periods
1570 # Months and days are identical
1571 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1572 # Meiji period
1573 $gy_gannen = $gy - 1868 + 1;
1574 $gy_offset = $gy_gannen;
1575 if ( $gy_gannen == 1 ) {
1576 $gy_offset = '元';
1577 }
1578 $gy_offset = '明治' . $gy_offset;
1579 } elseif (
1580 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1581 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1582 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1583 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1584 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1585 )
1586 {
1587 # Taishō period
1588 $gy_gannen = $gy - 1912 + 1;
1589 $gy_offset = $gy_gannen;
1590 if ( $gy_gannen == 1 ) {
1591 $gy_offset = '元';
1592 }
1593 $gy_offset = '大正' . $gy_offset;
1594 } elseif (
1595 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1596 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1597 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1598 )
1599 {
1600 # Shōwa period
1601 $gy_gannen = $gy - 1926 + 1;
1602 $gy_offset = $gy_gannen;
1603 if ( $gy_gannen == 1 ) {
1604 $gy_offset = '元';
1605 }
1606 $gy_offset = '昭和' . $gy_offset;
1607 } else {
1608 # Heisei period
1609 $gy_gannen = $gy - 1989 + 1;
1610 $gy_offset = $gy_gannen;
1611 if ( $gy_gannen == 1 ) {
1612 $gy_offset = '元';
1613 }
1614 $gy_offset = '平成' . $gy_offset;
1615 }
1616 } else {
1617 $gy_offset = $gy;
1618 }
1619
1620 return array( $gy_offset, $gm, $gd );
1621 }
1622
1623 /**
1624 * Roman number formatting up to 3000
1625 *
1626 * @param $num int
1627 *
1628 * @return string
1629 */
1630 static function romanNumeral( $num ) {
1631 static $table = array(
1632 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1633 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1634 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1635 array( '', 'M', 'MM', 'MMM' )
1636 );
1637
1638 $num = intval( $num );
1639 if ( $num > 3000 || $num <= 0 ) {
1640 return $num;
1641 }
1642
1643 $s = '';
1644 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1645 if ( $num >= $pow10 ) {
1646 $s .= $table[$i][(int)floor( $num / $pow10 )];
1647 }
1648 $num = $num % $pow10;
1649 }
1650 return $s;
1651 }
1652
1653 /**
1654 * Hebrew Gematria number formatting up to 9999
1655 *
1656 * @param $num int
1657 *
1658 * @return string
1659 */
1660 static function hebrewNumeral( $num ) {
1661 static $table = array(
1662 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1663 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1664 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1665 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1666 );
1667
1668 $num = intval( $num );
1669 if ( $num > 9999 || $num <= 0 ) {
1670 return $num;
1671 }
1672
1673 $s = '';
1674 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1675 if ( $num >= $pow10 ) {
1676 if ( $num == 15 || $num == 16 ) {
1677 $s .= $table[0][9] . $table[0][$num - 9];
1678 $num = 0;
1679 } else {
1680 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1681 if ( $pow10 == 1000 ) {
1682 $s .= "'";
1683 }
1684 }
1685 }
1686 $num = $num % $pow10;
1687 }
1688 if ( strlen( $s ) == 2 ) {
1689 $str = $s . "'";
1690 } else {
1691 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1692 $str .= substr( $s, strlen( $s ) - 2, 2 );
1693 }
1694 $start = substr( $str, 0, strlen( $str ) - 2 );
1695 $end = substr( $str, strlen( $str ) - 2 );
1696 switch( $end ) {
1697 case 'כ':
1698 $str = $start . 'ך';
1699 break;
1700 case 'מ':
1701 $str = $start . 'ם';
1702 break;
1703 case 'נ':
1704 $str = $start . 'ן';
1705 break;
1706 case 'פ':
1707 $str = $start . 'ף';
1708 break;
1709 case 'צ':
1710 $str = $start . 'ץ';
1711 break;
1712 }
1713 return $str;
1714 }
1715
1716 /**
1717 * Used by date() and time() to adjust the time output.
1718 *
1719 * @param $ts Int the time in date('YmdHis') format
1720 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1721 * get user timecorrection setting)
1722 * @return int
1723 */
1724 function userAdjust( $ts, $tz = false ) {
1725 global $wgUser, $wgLocalTZoffset;
1726
1727 if ( $tz === false ) {
1728 $tz = $wgUser->getOption( 'timecorrection' );
1729 }
1730
1731 $data = explode( '|', $tz, 3 );
1732
1733 if ( $data[0] == 'ZoneInfo' ) {
1734 wfSuppressWarnings();
1735 $userTZ = timezone_open( $data[2] );
1736 wfRestoreWarnings();
1737 if ( $userTZ !== false ) {
1738 $date = date_create( $ts, timezone_open( 'UTC' ) );
1739 date_timezone_set( $date, $userTZ );
1740 $date = date_format( $date, 'YmdHis' );
1741 return $date;
1742 }
1743 # Unrecognized timezone, default to 'Offset' with the stored offset.
1744 $data[0] = 'Offset';
1745 }
1746
1747 $minDiff = 0;
1748 if ( $data[0] == 'System' || $tz == '' ) {
1749 #  Global offset in minutes.
1750 if ( isset( $wgLocalTZoffset ) ) {
1751 $minDiff = $wgLocalTZoffset;
1752 }
1753 } elseif ( $data[0] == 'Offset' ) {
1754 $minDiff = intval( $data[1] );
1755 } else {
1756 $data = explode( ':', $tz );
1757 if ( count( $data ) == 2 ) {
1758 $data[0] = intval( $data[0] );
1759 $data[1] = intval( $data[1] );
1760 $minDiff = abs( $data[0] ) * 60 + $data[1];
1761 if ( $data[0] < 0 ) {
1762 $minDiff = -$minDiff;
1763 }
1764 } else {
1765 $minDiff = intval( $data[0] ) * 60;
1766 }
1767 }
1768
1769 # No difference ? Return time unchanged
1770 if ( 0 == $minDiff ) {
1771 return $ts;
1772 }
1773
1774 wfSuppressWarnings(); // E_STRICT system time bitching
1775 # Generate an adjusted date; take advantage of the fact that mktime
1776 # will normalize out-of-range values so we don't have to split $minDiff
1777 # into hours and minutes.
1778 $t = mktime( (
1779 (int)substr( $ts, 8, 2 ) ), # Hours
1780 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1781 (int)substr( $ts, 12, 2 ), # Seconds
1782 (int)substr( $ts, 4, 2 ), # Month
1783 (int)substr( $ts, 6, 2 ), # Day
1784 (int)substr( $ts, 0, 4 ) ); # Year
1785
1786 $date = date( 'YmdHis', $t );
1787 wfRestoreWarnings();
1788
1789 return $date;
1790 }
1791
1792 /**
1793 * This is meant to be used by time(), date(), and timeanddate() to get
1794 * the date preference they're supposed to use, it should be used in
1795 * all children.
1796 *
1797 *<code>
1798 * function timeanddate([...], $format = true) {
1799 * $datePreference = $this->dateFormat($format);
1800 * [...]
1801 * }
1802 *</code>
1803 *
1804 * @param $usePrefs Mixed: if true, the user's preference is used
1805 * if false, the site/language default is used
1806 * if int/string, assumed to be a format.
1807 * @return string
1808 */
1809 function dateFormat( $usePrefs = true ) {
1810 global $wgUser;
1811
1812 if ( is_bool( $usePrefs ) ) {
1813 if ( $usePrefs ) {
1814 $datePreference = $wgUser->getDatePreference();
1815 } else {
1816 $datePreference = (string)User::getDefaultOption( 'date' );
1817 }
1818 } else {
1819 $datePreference = (string)$usePrefs;
1820 }
1821
1822 // return int
1823 if ( $datePreference == '' ) {
1824 return 'default';
1825 }
1826
1827 return $datePreference;
1828 }
1829
1830 /**
1831 * Get a format string for a given type and preference
1832 * @param $type string May be date, time or both
1833 * @param $pref string The format name as it appears in Messages*.php
1834 *
1835 * @return string
1836 */
1837 function getDateFormatString( $type, $pref ) {
1838 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1839 if ( $pref == 'default' ) {
1840 $pref = $this->getDefaultDateFormat();
1841 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1842 } else {
1843 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1844 if ( is_null( $df ) ) {
1845 $pref = $this->getDefaultDateFormat();
1846 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1847 }
1848 }
1849 $this->dateFormatStrings[$type][$pref] = $df;
1850 }
1851 return $this->dateFormatStrings[$type][$pref];
1852 }
1853
1854 /**
1855 * @param $ts Mixed: the time format which needs to be turned into a
1856 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1857 * @param $adj Bool: whether to adjust the time output according to the
1858 * user configured offset ($timecorrection)
1859 * @param $format Mixed: true to use user's date format preference
1860 * @param $timecorrection String|bool the time offset as returned by
1861 * validateTimeZone() in Special:Preferences
1862 * @return string
1863 */
1864 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1865 $ts = wfTimestamp( TS_MW, $ts );
1866 if ( $adj ) {
1867 $ts = $this->userAdjust( $ts, $timecorrection );
1868 }
1869 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1870 return $this->sprintfDate( $df, $ts );
1871 }
1872
1873 /**
1874 * @param $ts Mixed: the time format which needs to be turned into a
1875 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1876 * @param $adj Bool: whether to adjust the time output according to the
1877 * user configured offset ($timecorrection)
1878 * @param $format Mixed: true to use user's date format preference
1879 * @param $timecorrection String|bool the time offset as returned by
1880 * validateTimeZone() in Special:Preferences
1881 * @return string
1882 */
1883 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1884 $ts = wfTimestamp( TS_MW, $ts );
1885 if ( $adj ) {
1886 $ts = $this->userAdjust( $ts, $timecorrection );
1887 }
1888 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1889 return $this->sprintfDate( $df, $ts );
1890 }
1891
1892 /**
1893 * @param $ts Mixed: the time format which needs to be turned into a
1894 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1895 * @param $adj Bool: whether to adjust the time output according to the
1896 * user configured offset ($timecorrection)
1897 * @param $format Mixed: what format to return, if it's false output the
1898 * default one (default true)
1899 * @param $timecorrection String|bool the time offset as returned by
1900 * validateTimeZone() in Special:Preferences
1901 * @return string
1902 */
1903 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1904 $ts = wfTimestamp( TS_MW, $ts );
1905 if ( $adj ) {
1906 $ts = $this->userAdjust( $ts, $timecorrection );
1907 }
1908 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1909 return $this->sprintfDate( $df, $ts );
1910 }
1911
1912 /**
1913 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1914 *
1915 * @since 1.20
1916 *
1917 * @param integer $seconds The amount of seconds.
1918 * @param array $chosenIntervals The intervals to enable.
1919 *
1920 * @return string
1921 */
1922 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1923 $intervals = array(
1924 'millennia' => 1000 * 31557600,
1925 'centuries' => 100 * 31557600,
1926 'decades' => 10 * 31557600,
1927 'years' => 31557600, // 86400 * 365.25
1928 'weeks' => 604800,
1929 'days' => 86400,
1930 'hours' => 3600,
1931 'minutes' => 60,
1932 'seconds' => 1,
1933 );
1934
1935 if ( empty( $chosenIntervals ) ) {
1936 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1937 }
1938
1939 $intervals = array_intersect_key( $intervals, array_flip( $chosenIntervals ) );
1940 $sortedNames = array_keys( $intervals );
1941 $smallestInterval = array_pop( $sortedNames );
1942
1943 $segments = array();
1944
1945 foreach ( $intervals as $name => $length ) {
1946 $value = floor( $seconds / $length );
1947
1948 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
1949 $seconds -= $value * $length;
1950 $message = new Message( 'duration-' . $name, array( $value ) );
1951 $segments[] = $message->inLanguage( $this )->escaped();
1952 }
1953 }
1954
1955 return $this->listToText( $segments );
1956 }
1957
1958 /**
1959 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1960 *
1961 * @param $type String: can be 'date', 'time' or 'both'
1962 * @param $ts Mixed: the time format which needs to be turned into a
1963 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1964 * @param $user User object used to get preferences for timezone and format
1965 * @param $options Array, can contain the following keys:
1966 * - 'timecorrection': time correction, can have the following values:
1967 * - true: use user's preference
1968 * - false: don't use time correction
1969 * - integer: value of time correction in minutes
1970 * - 'format': format to use, can have the following values:
1971 * - true: use user's preference
1972 * - false: use default preference
1973 * - string: format to use
1974 * @since 1.19
1975 * @return String
1976 */
1977 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
1978 $ts = wfTimestamp( TS_MW, $ts );
1979 $options += array( 'timecorrection' => true, 'format' => true );
1980 if ( $options['timecorrection'] !== false ) {
1981 if ( $options['timecorrection'] === true ) {
1982 $offset = $user->getOption( 'timecorrection' );
1983 } else {
1984 $offset = $options['timecorrection'];
1985 }
1986 $ts = $this->userAdjust( $ts, $offset );
1987 }
1988 if ( $options['format'] === true ) {
1989 $format = $user->getDatePreference();
1990 } else {
1991 $format = $options['format'];
1992 }
1993 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
1994 return $this->sprintfDate( $df, $ts );
1995 }
1996
1997 /**
1998 * Get the formatted date for the given timestamp and formatted for
1999 * the given user.
2000 *
2001 * @param $ts Mixed: the time format which needs to be turned into a
2002 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2003 * @param $user User object used to get preferences for timezone and format
2004 * @param $options Array, can contain the following keys:
2005 * - 'timecorrection': time correction, can have the following values:
2006 * - true: use user's preference
2007 * - false: don't use time correction
2008 * - integer: value of time correction in minutes
2009 * - 'format': format to use, can have the following values:
2010 * - true: use user's preference
2011 * - false: use default preference
2012 * - string: format to use
2013 * @since 1.19
2014 * @return String
2015 */
2016 public function userDate( $ts, User $user, array $options = array() ) {
2017 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2018 }
2019
2020 /**
2021 * Get the formatted time for the given timestamp and formatted for
2022 * the given user.
2023 *
2024 * @param $ts Mixed: the time format which needs to be turned into a
2025 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2026 * @param $user User object used to get preferences for timezone and format
2027 * @param $options Array, can contain the following keys:
2028 * - 'timecorrection': time correction, can have the following values:
2029 * - true: use user's preference
2030 * - false: don't use time correction
2031 * - integer: value of time correction in minutes
2032 * - 'format': format to use, can have the following values:
2033 * - true: use user's preference
2034 * - false: use default preference
2035 * - string: format to use
2036 * @since 1.19
2037 * @return String
2038 */
2039 public function userTime( $ts, User $user, array $options = array() ) {
2040 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2041 }
2042
2043 /**
2044 * Get the formatted date and time for the given timestamp and formatted for
2045 * the given user.
2046 *
2047 * @param $ts Mixed: the time format which needs to be turned into a
2048 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2049 * @param $user User object used to get preferences for timezone and format
2050 * @param $options Array, can contain the following keys:
2051 * - 'timecorrection': time correction, can have the following values:
2052 * - true: use user's preference
2053 * - false: don't use time correction
2054 * - integer: value of time correction in minutes
2055 * - 'format': format to use, can have the following values:
2056 * - true: use user's preference
2057 * - false: use default preference
2058 * - string: format to use
2059 * @since 1.19
2060 * @return String
2061 */
2062 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2063 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2064 }
2065
2066 /**
2067 * @param $key string
2068 * @return array|null
2069 */
2070 function getMessage( $key ) {
2071 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2072 }
2073
2074 /**
2075 * @return array
2076 */
2077 function getAllMessages() {
2078 return self::$dataCache->getItem( $this->mCode, 'messages' );
2079 }
2080
2081 /**
2082 * @param $in
2083 * @param $out
2084 * @param $string
2085 * @return string
2086 */
2087 function iconv( $in, $out, $string ) {
2088 # This is a wrapper for iconv in all languages except esperanto,
2089 # which does some nasty x-conversions beforehand
2090
2091 # Even with //IGNORE iconv can whine about illegal characters in
2092 # *input* string. We just ignore those too.
2093 # REF: http://bugs.php.net/bug.php?id=37166
2094 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2095 wfSuppressWarnings();
2096 $text = iconv( $in, $out . '//IGNORE', $string );
2097 wfRestoreWarnings();
2098 return $text;
2099 }
2100
2101 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2102
2103 /**
2104 * @param $matches array
2105 * @return mixed|string
2106 */
2107 function ucwordbreaksCallbackAscii( $matches ) {
2108 return $this->ucfirst( $matches[1] );
2109 }
2110
2111 /**
2112 * @param $matches array
2113 * @return string
2114 */
2115 function ucwordbreaksCallbackMB( $matches ) {
2116 return mb_strtoupper( $matches[0] );
2117 }
2118
2119 /**
2120 * @param $matches array
2121 * @return string
2122 */
2123 function ucCallback( $matches ) {
2124 list( $wikiUpperChars ) = self::getCaseMaps();
2125 return strtr( $matches[1], $wikiUpperChars );
2126 }
2127
2128 /**
2129 * @param $matches array
2130 * @return string
2131 */
2132 function lcCallback( $matches ) {
2133 list( , $wikiLowerChars ) = self::getCaseMaps();
2134 return strtr( $matches[1], $wikiLowerChars );
2135 }
2136
2137 /**
2138 * @param $matches array
2139 * @return string
2140 */
2141 function ucwordsCallbackMB( $matches ) {
2142 return mb_strtoupper( $matches[0] );
2143 }
2144
2145 /**
2146 * @param $matches array
2147 * @return string
2148 */
2149 function ucwordsCallbackWiki( $matches ) {
2150 list( $wikiUpperChars ) = self::getCaseMaps();
2151 return strtr( $matches[0], $wikiUpperChars );
2152 }
2153
2154 /**
2155 * Make a string's first character uppercase
2156 *
2157 * @param $str string
2158 *
2159 * @return string
2160 */
2161 function ucfirst( $str ) {
2162 $o = ord( $str );
2163 if ( $o < 96 ) { // if already uppercase...
2164 return $str;
2165 } elseif ( $o < 128 ) {
2166 return ucfirst( $str ); // use PHP's ucfirst()
2167 } else {
2168 // fall back to more complex logic in case of multibyte strings
2169 return $this->uc( $str, true );
2170 }
2171 }
2172
2173 /**
2174 * Convert a string to uppercase
2175 *
2176 * @param $str string
2177 * @param $first bool
2178 *
2179 * @return string
2180 */
2181 function uc( $str, $first = false ) {
2182 if ( function_exists( 'mb_strtoupper' ) ) {
2183 if ( $first ) {
2184 if ( $this->isMultibyte( $str ) ) {
2185 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2186 } else {
2187 return ucfirst( $str );
2188 }
2189 } else {
2190 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2191 }
2192 } else {
2193 if ( $this->isMultibyte( $str ) ) {
2194 $x = $first ? '^' : '';
2195 return preg_replace_callback(
2196 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2197 array( $this, 'ucCallback' ),
2198 $str
2199 );
2200 } else {
2201 return $first ? ucfirst( $str ) : strtoupper( $str );
2202 }
2203 }
2204 }
2205
2206 /**
2207 * @param $str string
2208 * @return mixed|string
2209 */
2210 function lcfirst( $str ) {
2211 $o = ord( $str );
2212 if ( !$o ) {
2213 return strval( $str );
2214 } elseif ( $o >= 128 ) {
2215 return $this->lc( $str, true );
2216 } elseif ( $o > 96 ) {
2217 return $str;
2218 } else {
2219 $str[0] = strtolower( $str[0] );
2220 return $str;
2221 }
2222 }
2223
2224 /**
2225 * @param $str string
2226 * @param $first bool
2227 * @return mixed|string
2228 */
2229 function lc( $str, $first = false ) {
2230 if ( function_exists( 'mb_strtolower' ) ) {
2231 if ( $first ) {
2232 if ( $this->isMultibyte( $str ) ) {
2233 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2234 } else {
2235 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2236 }
2237 } else {
2238 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2239 }
2240 } else {
2241 if ( $this->isMultibyte( $str ) ) {
2242 $x = $first ? '^' : '';
2243 return preg_replace_callback(
2244 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2245 array( $this, 'lcCallback' ),
2246 $str
2247 );
2248 } else {
2249 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2250 }
2251 }
2252 }
2253
2254 /**
2255 * @param $str string
2256 * @return bool
2257 */
2258 function isMultibyte( $str ) {
2259 return (bool)preg_match( '/[\x80-\xff]/', $str );
2260 }
2261
2262 /**
2263 * @param $str string
2264 * @return mixed|string
2265 */
2266 function ucwords( $str ) {
2267 if ( $this->isMultibyte( $str ) ) {
2268 $str = $this->lc( $str );
2269
2270 // regexp to find first letter in each word (i.e. after each space)
2271 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2272
2273 // function to use to capitalize a single char
2274 if ( function_exists( 'mb_strtoupper' ) ) {
2275 return preg_replace_callback(
2276 $replaceRegexp,
2277 array( $this, 'ucwordsCallbackMB' ),
2278 $str
2279 );
2280 } else {
2281 return preg_replace_callback(
2282 $replaceRegexp,
2283 array( $this, 'ucwordsCallbackWiki' ),
2284 $str
2285 );
2286 }
2287 } else {
2288 return ucwords( strtolower( $str ) );
2289 }
2290 }
2291
2292 /**
2293 * capitalize words at word breaks
2294 *
2295 * @param $str string
2296 * @return mixed
2297 */
2298 function ucwordbreaks( $str ) {
2299 if ( $this->isMultibyte( $str ) ) {
2300 $str = $this->lc( $str );
2301
2302 // since \b doesn't work for UTF-8, we explicitely define word break chars
2303 $breaks = "[ \-\(\)\}\{\.,\?!]";
2304
2305 // find first letter after word break
2306 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2307
2308 if ( function_exists( 'mb_strtoupper' ) ) {
2309 return preg_replace_callback(
2310 $replaceRegexp,
2311 array( $this, 'ucwordbreaksCallbackMB' ),
2312 $str
2313 );
2314 } else {
2315 return preg_replace_callback(
2316 $replaceRegexp,
2317 array( $this, 'ucwordsCallbackWiki' ),
2318 $str
2319 );
2320 }
2321 } else {
2322 return preg_replace_callback(
2323 '/\b([\w\x80-\xff]+)\b/',
2324 array( $this, 'ucwordbreaksCallbackAscii' ),
2325 $str
2326 );
2327 }
2328 }
2329
2330 /**
2331 * Return a case-folded representation of $s
2332 *
2333 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2334 * and $s2 are the same except for the case of their characters. It is not
2335 * necessary for the value returned to make sense when displayed.
2336 *
2337 * Do *not* perform any other normalisation in this function. If a caller
2338 * uses this function when it should be using a more general normalisation
2339 * function, then fix the caller.
2340 *
2341 * @param $s string
2342 *
2343 * @return string
2344 */
2345 function caseFold( $s ) {
2346 return $this->uc( $s );
2347 }
2348
2349 /**
2350 * @param $s string
2351 * @return string
2352 */
2353 function checkTitleEncoding( $s ) {
2354 if ( is_array( $s ) ) {
2355 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2356 }
2357 # Check for non-UTF-8 URLs
2358 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2359 if ( !$ishigh ) {
2360 return $s;
2361 }
2362
2363 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2364 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2365 if ( $isutf8 ) {
2366 return $s;
2367 }
2368
2369 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2370 }
2371
2372 /**
2373 * @return array
2374 */
2375 function fallback8bitEncoding() {
2376 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2377 }
2378
2379 /**
2380 * Most writing systems use whitespace to break up words.
2381 * Some languages such as Chinese don't conventionally do this,
2382 * which requires special handling when breaking up words for
2383 * searching etc.
2384 *
2385 * @return bool
2386 */
2387 function hasWordBreaks() {
2388 return true;
2389 }
2390
2391 /**
2392 * Some languages such as Chinese require word segmentation,
2393 * Specify such segmentation when overridden in derived class.
2394 *
2395 * @param $string String
2396 * @return String
2397 */
2398 function segmentByWord( $string ) {
2399 return $string;
2400 }
2401
2402 /**
2403 * Some languages have special punctuation need to be normalized.
2404 * Make such changes here.
2405 *
2406 * @param $string String
2407 * @return String
2408 */
2409 function normalizeForSearch( $string ) {
2410 return self::convertDoubleWidth( $string );
2411 }
2412
2413 /**
2414 * convert double-width roman characters to single-width.
2415 * range: ff00-ff5f ~= 0020-007f
2416 *
2417 * @param $string string
2418 *
2419 * @return string
2420 */
2421 protected static function convertDoubleWidth( $string ) {
2422 static $full = null;
2423 static $half = null;
2424
2425 if ( $full === null ) {
2426 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2427 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2428 $full = str_split( $fullWidth, 3 );
2429 $half = str_split( $halfWidth );
2430 }
2431
2432 $string = str_replace( $full, $half, $string );
2433 return $string;
2434 }
2435
2436 /**
2437 * @param $string string
2438 * @param $pattern string
2439 * @return string
2440 */
2441 protected static function insertSpace( $string, $pattern ) {
2442 $string = preg_replace( $pattern, " $1 ", $string );
2443 $string = preg_replace( '/ +/', ' ', $string );
2444 return $string;
2445 }
2446
2447 /**
2448 * @param $termsArray array
2449 * @return array
2450 */
2451 function convertForSearchResult( $termsArray ) {
2452 # some languages, e.g. Chinese, need to do a conversion
2453 # in order for search results to be displayed correctly
2454 return $termsArray;
2455 }
2456
2457 /**
2458 * Get the first character of a string.
2459 *
2460 * @param $s string
2461 * @return string
2462 */
2463 function firstChar( $s ) {
2464 $matches = array();
2465 preg_match(
2466 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2467 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2468 $s,
2469 $matches
2470 );
2471
2472 if ( isset( $matches[1] ) ) {
2473 if ( strlen( $matches[1] ) != 3 ) {
2474 return $matches[1];
2475 }
2476
2477 // Break down Hangul syllables to grab the first jamo
2478 $code = utf8ToCodepoint( $matches[1] );
2479 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2480 return $matches[1];
2481 } elseif ( $code < 0xb098 ) {
2482 return "\xe3\x84\xb1";
2483 } elseif ( $code < 0xb2e4 ) {
2484 return "\xe3\x84\xb4";
2485 } elseif ( $code < 0xb77c ) {
2486 return "\xe3\x84\xb7";
2487 } elseif ( $code < 0xb9c8 ) {
2488 return "\xe3\x84\xb9";
2489 } elseif ( $code < 0xbc14 ) {
2490 return "\xe3\x85\x81";
2491 } elseif ( $code < 0xc0ac ) {
2492 return "\xe3\x85\x82";
2493 } elseif ( $code < 0xc544 ) {
2494 return "\xe3\x85\x85";
2495 } elseif ( $code < 0xc790 ) {
2496 return "\xe3\x85\x87";
2497 } elseif ( $code < 0xcc28 ) {
2498 return "\xe3\x85\x88";
2499 } elseif ( $code < 0xce74 ) {
2500 return "\xe3\x85\x8a";
2501 } elseif ( $code < 0xd0c0 ) {
2502 return "\xe3\x85\x8b";
2503 } elseif ( $code < 0xd30c ) {
2504 return "\xe3\x85\x8c";
2505 } elseif ( $code < 0xd558 ) {
2506 return "\xe3\x85\x8d";
2507 } else {
2508 return "\xe3\x85\x8e";
2509 }
2510 } else {
2511 return '';
2512 }
2513 }
2514
2515 function initEncoding() {
2516 # Some languages may have an alternate char encoding option
2517 # (Esperanto X-coding, Japanese furigana conversion, etc)
2518 # If this language is used as the primary content language,
2519 # an override to the defaults can be set here on startup.
2520 }
2521
2522 /**
2523 * @param $s string
2524 * @return string
2525 */
2526 function recodeForEdit( $s ) {
2527 # For some languages we'll want to explicitly specify
2528 # which characters make it into the edit box raw
2529 # or are converted in some way or another.
2530 global $wgEditEncoding;
2531 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2532 return $s;
2533 } else {
2534 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2535 }
2536 }
2537
2538 /**
2539 * @param $s string
2540 * @return string
2541 */
2542 function recodeInput( $s ) {
2543 # Take the previous into account.
2544 global $wgEditEncoding;
2545 if ( $wgEditEncoding != '' ) {
2546 $enc = $wgEditEncoding;
2547 } else {
2548 $enc = 'UTF-8';
2549 }
2550 if ( $enc == 'UTF-8' ) {
2551 return $s;
2552 } else {
2553 return $this->iconv( $enc, 'UTF-8', $s );
2554 }
2555 }
2556
2557 /**
2558 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2559 * also cleans up certain backwards-compatible sequences, converting them
2560 * to the modern Unicode equivalent.
2561 *
2562 * This is language-specific for performance reasons only.
2563 *
2564 * @param $s string
2565 *
2566 * @return string
2567 */
2568 function normalize( $s ) {
2569 global $wgAllUnicodeFixes;
2570 $s = UtfNormal::cleanUp( $s );
2571 if ( $wgAllUnicodeFixes ) {
2572 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2573 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2574 }
2575
2576 return $s;
2577 }
2578
2579 /**
2580 * Transform a string using serialized data stored in the given file (which
2581 * must be in the serialized subdirectory of $IP). The file contains pairs
2582 * mapping source characters to destination characters.
2583 *
2584 * The data is cached in process memory. This will go faster if you have the
2585 * FastStringSearch extension.
2586 *
2587 * @param $file string
2588 * @param $string string
2589 *
2590 * @throws MWException
2591 * @return string
2592 */
2593 function transformUsingPairFile( $file, $string ) {
2594 if ( !isset( $this->transformData[$file] ) ) {
2595 $data = wfGetPrecompiledData( $file );
2596 if ( $data === false ) {
2597 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2598 }
2599 $this->transformData[$file] = new ReplacementArray( $data );
2600 }
2601 return $this->transformData[$file]->replace( $string );
2602 }
2603
2604 /**
2605 * For right-to-left language support
2606 *
2607 * @return bool
2608 */
2609 function isRTL() {
2610 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2611 }
2612
2613 /**
2614 * Return the correct HTML 'dir' attribute value for this language.
2615 * @return String
2616 */
2617 function getDir() {
2618 return $this->isRTL() ? 'rtl' : 'ltr';
2619 }
2620
2621 /**
2622 * Return 'left' or 'right' as appropriate alignment for line-start
2623 * for this language's text direction.
2624 *
2625 * Should be equivalent to CSS3 'start' text-align value....
2626 *
2627 * @return String
2628 */
2629 function alignStart() {
2630 return $this->isRTL() ? 'right' : 'left';
2631 }
2632
2633 /**
2634 * Return 'right' or 'left' as appropriate alignment for line-end
2635 * for this language's text direction.
2636 *
2637 * Should be equivalent to CSS3 'end' text-align value....
2638 *
2639 * @return String
2640 */
2641 function alignEnd() {
2642 return $this->isRTL() ? 'left' : 'right';
2643 }
2644
2645 /**
2646 * A hidden direction mark (LRM or RLM), depending on the language direction
2647 *
2648 * @param $opposite Boolean Get the direction mark opposite to your language
2649 * @return string
2650 */
2651 function getDirMark( $opposite = false ) {
2652 $rtl = "\xE2\x80\x8F";
2653 $ltr = "\xE2\x80\x8E";
2654 if ( $opposite ) { return $this->isRTL() ? $ltr : $rtl; }
2655 return $this->isRTL() ? $rtl : $ltr;
2656 }
2657
2658 /**
2659 * @return array
2660 */
2661 function capitalizeAllNouns() {
2662 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2663 }
2664
2665 /**
2666 * An arrow, depending on the language direction
2667 *
2668 * @return string
2669 */
2670 function getArrow() {
2671 return $this->isRTL() ? '←' : '→';
2672 }
2673
2674 /**
2675 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2676 *
2677 * @return bool
2678 */
2679 function linkPrefixExtension() {
2680 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2681 }
2682
2683 /**
2684 * @return array
2685 */
2686 function getMagicWords() {
2687 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2688 }
2689
2690 protected function doMagicHook() {
2691 if ( $this->mMagicHookDone ) {
2692 return;
2693 }
2694 $this->mMagicHookDone = true;
2695 wfProfileIn( 'LanguageGetMagic' );
2696 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2697 wfProfileOut( 'LanguageGetMagic' );
2698 }
2699
2700 /**
2701 * Fill a MagicWord object with data from here
2702 *
2703 * @param $mw
2704 */
2705 function getMagic( $mw ) {
2706 $this->doMagicHook();
2707
2708 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2709 $rawEntry = $this->mMagicExtensions[$mw->mId];
2710 } else {
2711 $magicWords = $this->getMagicWords();
2712 if ( isset( $magicWords[$mw->mId] ) ) {
2713 $rawEntry = $magicWords[$mw->mId];
2714 } else {
2715 $rawEntry = false;
2716 }
2717 }
2718
2719 if ( !is_array( $rawEntry ) ) {
2720 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2721 } else {
2722 $mw->mCaseSensitive = $rawEntry[0];
2723 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2724 }
2725 }
2726
2727 /**
2728 * Add magic words to the extension array
2729 *
2730 * @param $newWords array
2731 */
2732 function addMagicWordsByLang( $newWords ) {
2733 $fallbackChain = $this->getFallbackLanguages();
2734 $fallbackChain = array_reverse( $fallbackChain );
2735 foreach ( $fallbackChain as $code ) {
2736 if ( isset( $newWords[$code] ) ) {
2737 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2738 }
2739 }
2740 }
2741
2742 /**
2743 * Get special page names, as an associative array
2744 * case folded alias => real name
2745 */
2746 function getSpecialPageAliases() {
2747 // Cache aliases because it may be slow to load them
2748 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2749 // Initialise array
2750 $this->mExtendedSpecialPageAliases =
2751 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2752 wfRunHooks( 'LanguageGetSpecialPageAliases',
2753 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2754 }
2755
2756 return $this->mExtendedSpecialPageAliases;
2757 }
2758
2759 /**
2760 * Italic is unsuitable for some languages
2761 *
2762 * @param $text String: the text to be emphasized.
2763 * @return string
2764 */
2765 function emphasize( $text ) {
2766 return "<em>$text</em>";
2767 }
2768
2769 /**
2770 * Normally we output all numbers in plain en_US style, that is
2771 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2772 * point twohundredthirtyfive. However this is not suitable for all
2773 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2774 * Icelandic just want to use commas instead of dots, and dots instead
2775 * of commas like "293.291,235".
2776 *
2777 * An example of this function being called:
2778 * <code>
2779 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2780 * </code>
2781 *
2782 * See LanguageGu.php for the Gujarati implementation and
2783 * $separatorTransformTable on MessageIs.php for
2784 * the , => . and . => , implementation.
2785 *
2786 * @todo check if it's viable to use localeconv() for the decimal
2787 * separator thing.
2788 * @param $number Mixed: the string to be formatted, should be an integer
2789 * or a floating point number.
2790 * @param $nocommafy Bool: set to true for special numbers like dates
2791 * @return string
2792 */
2793 public function formatNum( $number, $nocommafy = false ) {
2794 global $wgTranslateNumerals;
2795 if ( !$nocommafy ) {
2796 $number = $this->commafy( $number );
2797 $s = $this->separatorTransformTable();
2798 if ( $s ) {
2799 $number = strtr( $number, $s );
2800 }
2801 }
2802
2803 if ( $wgTranslateNumerals ) {
2804 $s = $this->digitTransformTable();
2805 if ( $s ) {
2806 $number = strtr( $number, $s );
2807 }
2808 }
2809
2810 return $number;
2811 }
2812
2813 /**
2814 * @param $number string
2815 * @return string
2816 */
2817 function parseFormattedNumber( $number ) {
2818 $s = $this->digitTransformTable();
2819 if ( $s ) {
2820 $number = strtr( $number, array_flip( $s ) );
2821 }
2822
2823 $s = $this->separatorTransformTable();
2824 if ( $s ) {
2825 $number = strtr( $number, array_flip( $s ) );
2826 }
2827
2828 $number = strtr( $number, array( ',' => '' ) );
2829 return $number;
2830 }
2831
2832 /**
2833 * Adds commas to a given number
2834 * @since 1.19
2835 * @param $_ mixed
2836 * @return string
2837 */
2838 function commafy( $_ ) {
2839 $digitGroupingPattern = $this->digitGroupingPattern();
2840 if ( $_ === null ) {
2841 return '';
2842 }
2843
2844 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2845 // default grouping is at thousands, use the same for ###,###,### pattern too.
2846 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2847 } else {
2848 // Ref: http://cldr.unicode.org/translation/number-patterns
2849 $sign = "";
2850 if ( intval( $_ ) < 0 ) {
2851 // For negative numbers apply the algorithm like positive number and add sign.
2852 $sign = "-";
2853 $_ = substr( $_, 1 );
2854 }
2855 $numberpart = array();
2856 $decimalpart = array();
2857 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2858 preg_match( "/\d+/", $_, $numberpart );
2859 preg_match( "/\.\d*/", $_, $decimalpart );
2860 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2861 if ( $groupedNumber === $_ ) {
2862 // the string does not have any number part. Eg: .12345
2863 return $sign . $groupedNumber;
2864 }
2865 $start = $end = strlen( $numberpart[0] );
2866 while ( $start > 0 ) {
2867 $match = $matches[0][$numMatches -1] ;
2868 $matchLen = strlen( $match );
2869 $start = $end - $matchLen;
2870 if ( $start < 0 ) {
2871 $start = 0;
2872 }
2873 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2874 $end = $start;
2875 if ( $numMatches > 1 ) {
2876 // use the last pattern for the rest of the number
2877 $numMatches--;
2878 }
2879 if ( $start > 0 ) {
2880 $groupedNumber = "," . $groupedNumber;
2881 }
2882 }
2883 return $sign . $groupedNumber;
2884 }
2885 }
2886 /**
2887 * @return String
2888 */
2889 function digitGroupingPattern() {
2890 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
2891 }
2892
2893 /**
2894 * @return array
2895 */
2896 function digitTransformTable() {
2897 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2898 }
2899
2900 /**
2901 * @return array
2902 */
2903 function separatorTransformTable() {
2904 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2905 }
2906
2907 /**
2908 * Take a list of strings and build a locale-friendly comma-separated
2909 * list, using the local comma-separator message.
2910 * The last two strings are chained with an "and".
2911 *
2912 * @param $l Array
2913 * @return string
2914 */
2915 function listToText( array $l ) {
2916 $s = '';
2917 $m = count( $l ) - 1;
2918 if ( $m == 1 ) {
2919 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2920 } else {
2921 for ( $i = $m; $i >= 0; $i-- ) {
2922 if ( $i == $m ) {
2923 $s = $l[$i];
2924 } elseif ( $i == $m - 1 ) {
2925 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2926 } else {
2927 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2928 }
2929 }
2930 return $s;
2931 }
2932 }
2933
2934 /**
2935 * Take a list of strings and build a locale-friendly comma-separated
2936 * list, using the local comma-separator message.
2937 * @param $list array of strings to put in a comma list
2938 * @return string
2939 */
2940 function commaList( array $list ) {
2941 return implode(
2942 wfMsgExt(
2943 'comma-separator',
2944 array( 'parsemag', 'escapenoentities', 'language' => $this )
2945 ),
2946 $list
2947 );
2948 }
2949
2950 /**
2951 * Take a list of strings and build a locale-friendly semicolon-separated
2952 * list, using the local semicolon-separator message.
2953 * @param $list array of strings to put in a semicolon list
2954 * @return string
2955 */
2956 function semicolonList( array $list ) {
2957 return implode(
2958 wfMsgExt(
2959 'semicolon-separator',
2960 array( 'parsemag', 'escapenoentities', 'language' => $this )
2961 ),
2962 $list
2963 );
2964 }
2965
2966 /**
2967 * Same as commaList, but separate it with the pipe instead.
2968 * @param $list array of strings to put in a pipe list
2969 * @return string
2970 */
2971 function pipeList( array $list ) {
2972 return implode(
2973 wfMsgExt(
2974 'pipe-separator',
2975 array( 'escapenoentities', 'language' => $this )
2976 ),
2977 $list
2978 );
2979 }
2980
2981 /**
2982 * Truncate a string to a specified length in bytes, appending an optional
2983 * string (e.g. for ellipses)
2984 *
2985 * The database offers limited byte lengths for some columns in the database;
2986 * multi-byte character sets mean we need to ensure that only whole characters
2987 * are included, otherwise broken characters can be passed to the user
2988 *
2989 * If $length is negative, the string will be truncated from the beginning
2990 *
2991 * @param $string String to truncate
2992 * @param $length Int: maximum length (including ellipses)
2993 * @param $ellipsis String to append to the truncated text
2994 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2995 * $adjustLength was introduced in 1.18, before that behaved as if false.
2996 * @return string
2997 */
2998 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2999 # Use the localized ellipsis character
3000 if ( $ellipsis == '...' ) {
3001 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3002 }
3003 # Check if there is no need to truncate
3004 if ( $length == 0 ) {
3005 return $ellipsis; // convention
3006 } elseif ( strlen( $string ) <= abs( $length ) ) {
3007 return $string; // no need to truncate
3008 }
3009 $stringOriginal = $string;
3010 # If ellipsis length is >= $length then we can't apply $adjustLength
3011 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3012 $string = $ellipsis; // this can be slightly unexpected
3013 # Otherwise, truncate and add ellipsis...
3014 } else {
3015 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3016 if ( $length > 0 ) {
3017 $length -= $eLength;
3018 $string = substr( $string, 0, $length ); // xyz...
3019 $string = $this->removeBadCharLast( $string );
3020 $string = $string . $ellipsis;
3021 } else {
3022 $length += $eLength;
3023 $string = substr( $string, $length ); // ...xyz
3024 $string = $this->removeBadCharFirst( $string );
3025 $string = $ellipsis . $string;
3026 }
3027 }
3028 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3029 # This check is *not* redundant if $adjustLength, due to the single case where
3030 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3031 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3032 return $string;
3033 } else {
3034 return $stringOriginal;
3035 }
3036 }
3037
3038 /**
3039 * Remove bytes that represent an incomplete Unicode character
3040 * at the end of string (e.g. bytes of the char are missing)
3041 *
3042 * @param $string String
3043 * @return string
3044 */
3045 protected function removeBadCharLast( $string ) {
3046 if ( $string != '' ) {
3047 $char = ord( $string[strlen( $string ) - 1] );
3048 $m = array();
3049 if ( $char >= 0xc0 ) {
3050 # We got the first byte only of a multibyte char; remove it.
3051 $string = substr( $string, 0, -1 );
3052 } elseif ( $char >= 0x80 &&
3053 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3054 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3055 {
3056 # We chopped in the middle of a character; remove it
3057 $string = $m[1];
3058 }
3059 }
3060 return $string;
3061 }
3062
3063 /**
3064 * Remove bytes that represent an incomplete Unicode character
3065 * at the start of string (e.g. bytes of the char are missing)
3066 *
3067 * @param $string String
3068 * @return string
3069 */
3070 protected function removeBadCharFirst( $string ) {
3071 if ( $string != '' ) {
3072 $char = ord( $string[0] );
3073 if ( $char >= 0x80 && $char < 0xc0 ) {
3074 # We chopped in the middle of a character; remove the whole thing
3075 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3076 }
3077 }
3078 return $string;
3079 }
3080
3081 /**
3082 * Truncate a string of valid HTML to a specified length in bytes,
3083 * appending an optional string (e.g. for ellipses), and return valid HTML
3084 *
3085 * This is only intended for styled/linked text, such as HTML with
3086 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3087 * Also, this will not detect things like "display:none" CSS.
3088 *
3089 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3090 *
3091 * @param string $text HTML string to truncate
3092 * @param int $length (zero/positive) Maximum length (including ellipses)
3093 * @param string $ellipsis String to append to the truncated text
3094 * @return string
3095 */
3096 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3097 # Use the localized ellipsis character
3098 if ( $ellipsis == '...' ) {
3099 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3100 }
3101 # Check if there is clearly no need to truncate
3102 if ( $length <= 0 ) {
3103 return $ellipsis; // no text shown, nothing to format (convention)
3104 } elseif ( strlen( $text ) <= $length ) {
3105 return $text; // string short enough even *with* HTML (short-circuit)
3106 }
3107
3108 $dispLen = 0; // innerHTML legth so far
3109 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3110 $tagType = 0; // 0-open, 1-close
3111 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3112 $entityState = 0; // 0-not entity, 1-entity
3113 $tag = $ret = ''; // accumulated tag name, accumulated result string
3114 $openTags = array(); // open tag stack
3115 $maybeState = null; // possible truncation state
3116
3117 $textLen = strlen( $text );
3118 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3119 for ( $pos = 0; true; ++$pos ) {
3120 # Consider truncation once the display length has reached the maximim.
3121 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3122 # Check that we're not in the middle of a bracket/entity...
3123 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3124 if ( !$testingEllipsis ) {
3125 $testingEllipsis = true;
3126 # Save where we are; we will truncate here unless there turn out to
3127 # be so few remaining characters that truncation is not necessary.
3128 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3129 $maybeState = array( $ret, $openTags ); // save state
3130 }
3131 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3132 # String in fact does need truncation, the truncation point was OK.
3133 list( $ret, $openTags ) = $maybeState; // reload state
3134 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3135 $ret .= $ellipsis; // add ellipsis
3136 break;
3137 }
3138 }
3139 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3140
3141 # Read the next char...
3142 $ch = $text[$pos];
3143 $lastCh = $pos ? $text[$pos - 1] : '';
3144 $ret .= $ch; // add to result string
3145 if ( $ch == '<' ) {
3146 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3147 $entityState = 0; // for bad HTML
3148 $bracketState = 1; // tag started (checking for backslash)
3149 } elseif ( $ch == '>' ) {
3150 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3151 $entityState = 0; // for bad HTML
3152 $bracketState = 0; // out of brackets
3153 } elseif ( $bracketState == 1 ) {
3154 if ( $ch == '/' ) {
3155 $tagType = 1; // close tag (e.g. "</span>")
3156 } else {
3157 $tagType = 0; // open tag (e.g. "<span>")
3158 $tag .= $ch;
3159 }
3160 $bracketState = 2; // building tag name
3161 } elseif ( $bracketState == 2 ) {
3162 if ( $ch != ' ' ) {
3163 $tag .= $ch;
3164 } else {
3165 // Name found (e.g. "<a href=..."), add on tag attributes...
3166 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3167 }
3168 } elseif ( $bracketState == 0 ) {
3169 if ( $entityState ) {
3170 if ( $ch == ';' ) {
3171 $entityState = 0;
3172 $dispLen++; // entity is one displayed char
3173 }
3174 } else {
3175 if ( $neLength == 0 && !$maybeState ) {
3176 // Save state without $ch. We want to *hit* the first
3177 // display char (to get tags) but not *use* it if truncating.
3178 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3179 }
3180 if ( $ch == '&' ) {
3181 $entityState = 1; // entity found, (e.g. "&#160;")
3182 } else {
3183 $dispLen++; // this char is displayed
3184 // Add the next $max display text chars after this in one swoop...
3185 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3186 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3187 $dispLen += $skipped;
3188 $pos += $skipped;
3189 }
3190 }
3191 }
3192 }
3193 // Close the last tag if left unclosed by bad HTML
3194 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3195 while ( count( $openTags ) > 0 ) {
3196 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3197 }
3198 return $ret;
3199 }
3200
3201 /**
3202 * truncateHtml() helper function
3203 * like strcspn() but adds the skipped chars to $ret
3204 *
3205 * @param $ret
3206 * @param $text
3207 * @param $search
3208 * @param $start
3209 * @param $len
3210 * @return int
3211 */
3212 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3213 if ( $len === null ) {
3214 $len = -1; // -1 means "no limit" for strcspn
3215 } elseif ( $len < 0 ) {
3216 $len = 0; // sanity
3217 }
3218 $skipCount = 0;
3219 if ( $start < strlen( $text ) ) {
3220 $skipCount = strcspn( $text, $search, $start, $len );
3221 $ret .= substr( $text, $start, $skipCount );
3222 }
3223 return $skipCount;
3224 }
3225
3226 /**
3227 * truncateHtml() helper function
3228 * (a) push or pop $tag from $openTags as needed
3229 * (b) clear $tag value
3230 * @param &$tag string Current HTML tag name we are looking at
3231 * @param $tagType int (0-open tag, 1-close tag)
3232 * @param $lastCh string Character before the '>' that ended this tag
3233 * @param &$openTags array Open tag stack (not accounting for $tag)
3234 */
3235 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3236 $tag = ltrim( $tag );
3237 if ( $tag != '' ) {
3238 if ( $tagType == 0 && $lastCh != '/' ) {
3239 $openTags[] = $tag; // tag opened (didn't close itself)
3240 } elseif ( $tagType == 1 ) {
3241 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3242 array_pop( $openTags ); // tag closed
3243 }
3244 }
3245 $tag = '';
3246 }
3247 }
3248
3249 /**
3250 * Grammatical transformations, needed for inflected languages
3251 * Invoked by putting {{grammar:case|word}} in a message
3252 *
3253 * @param $word string
3254 * @param $case string
3255 * @return string
3256 */
3257 function convertGrammar( $word, $case ) {
3258 global $wgGrammarForms;
3259 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3260 return $wgGrammarForms[$this->getCode()][$case][$word];
3261 }
3262 return $word;
3263 }
3264
3265 /**
3266 * Provides an alternative text depending on specified gender.
3267 * Usage {{gender:username|masculine|feminine|neutral}}.
3268 * username is optional, in which case the gender of current user is used,
3269 * but only in (some) interface messages; otherwise default gender is used.
3270 *
3271 * If no forms are given, an empty string is returned. If only one form is
3272 * given, it will be returned unconditionally. These details are implied by
3273 * the caller and cannot be overridden in subclasses.
3274 *
3275 * If more than one form is given, the default is to use the neutral one
3276 * if it is specified, and to use the masculine one otherwise. These
3277 * details can be overridden in subclasses.
3278 *
3279 * @param $gender string
3280 * @param $forms array
3281 *
3282 * @return string
3283 */
3284 function gender( $gender, $forms ) {
3285 if ( !count( $forms ) ) {
3286 return '';
3287 }
3288 $forms = $this->preConvertPlural( $forms, 2 );
3289 if ( $gender === 'male' ) {
3290 return $forms[0];
3291 }
3292 if ( $gender === 'female' ) {
3293 return $forms[1];
3294 }
3295 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3296 }
3297
3298 /**
3299 * Plural form transformations, needed for some languages.
3300 * For example, there are 3 form of plural in Russian and Polish,
3301 * depending on "count mod 10". See [[w:Plural]]
3302 * For English it is pretty simple.
3303 *
3304 * Invoked by putting {{plural:count|wordform1|wordform2}}
3305 * or {{plural:count|wordform1|wordform2|wordform3}}
3306 *
3307 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3308 *
3309 * @param $count Integer: non-localized number
3310 * @param $forms Array: different plural forms
3311 * @return string Correct form of plural for $count in this language
3312 */
3313 function convertPlural( $count, $forms ) {
3314 if ( !count( $forms ) ) {
3315 return '';
3316 }
3317 $forms = $this->preConvertPlural( $forms, 2 );
3318
3319 return ( $count == 1 ) ? $forms[0] : $forms[1];
3320 }
3321
3322 /**
3323 * Checks that convertPlural was given an array and pads it to requested
3324 * amount of forms by copying the last one.
3325 *
3326 * @param $count Integer: How many forms should there be at least
3327 * @param $forms Array of forms given to convertPlural
3328 * @return array Padded array of forms or an exception if not an array
3329 */
3330 protected function preConvertPlural( /* Array */ $forms, $count ) {
3331 while ( count( $forms ) < $count ) {
3332 $forms[] = $forms[count( $forms ) - 1];
3333 }
3334 return $forms;
3335 }
3336
3337 /**
3338 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3339 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3340 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3341 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3342 * match up with it.
3343 *
3344 * @param $str String: the validated block duration in English
3345 * @return string Somehow translated block duration
3346 * @see LanguageFi.php for example implementation
3347 */
3348 function translateBlockExpiry( $str ) {
3349 $duration = SpecialBlock::getSuggestedDurations( $this );
3350 foreach ( $duration as $show => $value ) {
3351 if ( strcmp( $str, $value ) == 0 ) {
3352 return htmlspecialchars( trim( $show ) );
3353 }
3354 }
3355
3356 // Since usually only infinite or indefinite is only on list, so try
3357 // equivalents if still here.
3358 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3359 if ( in_array( $str, $indefs ) ) {
3360 foreach ( $indefs as $val ) {
3361 $show = array_search( $val, $duration, true );
3362 if ( $show !== false ) {
3363 return htmlspecialchars( trim( $show ) );
3364 }
3365 }
3366 }
3367 // If all else fails, return the original string.
3368 return $str;
3369 }
3370
3371 /**
3372 * languages like Chinese need to be segmented in order for the diff
3373 * to be of any use
3374 *
3375 * @param $text String
3376 * @return String
3377 */
3378 public function segmentForDiff( $text ) {
3379 return $text;
3380 }
3381
3382 /**
3383 * and unsegment to show the result
3384 *
3385 * @param $text String
3386 * @return String
3387 */
3388 public function unsegmentForDiff( $text ) {
3389 return $text;
3390 }
3391
3392 /**
3393 * Return the LanguageConverter used in the Language
3394 *
3395 * @since 1.19
3396 * @return LanguageConverter
3397 */
3398 public function getConverter() {
3399 return $this->mConverter;
3400 }
3401
3402 /**
3403 * convert text to all supported variants
3404 *
3405 * @param $text string
3406 * @return array
3407 */
3408 public function autoConvertToAllVariants( $text ) {
3409 return $this->mConverter->autoConvertToAllVariants( $text );
3410 }
3411
3412 /**
3413 * convert text to different variants of a language.
3414 *
3415 * @param $text string
3416 * @return string
3417 */
3418 public function convert( $text ) {
3419 return $this->mConverter->convert( $text );
3420 }
3421
3422 /**
3423 * Convert a Title object to a string in the preferred variant
3424 *
3425 * @param $title Title
3426 * @return string
3427 */
3428 public function convertTitle( $title ) {
3429 return $this->mConverter->convertTitle( $title );
3430 }
3431
3432 /**
3433 * Check if this is a language with variants
3434 *
3435 * @return bool
3436 */
3437 public function hasVariants() {
3438 return sizeof( $this->getVariants() ) > 1;
3439 }
3440
3441 /**
3442 * Check if the language has the specific variant
3443 *
3444 * @since 1.19
3445 * @param $variant string
3446 * @return bool
3447 */
3448 public function hasVariant( $variant ) {
3449 return (bool)$this->mConverter->validateVariant( $variant );
3450 }
3451
3452 /**
3453 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3454 *
3455 * @param $text string
3456 * @return string
3457 */
3458 public function armourMath( $text ) {
3459 return $this->mConverter->armourMath( $text );
3460 }
3461
3462 /**
3463 * Perform output conversion on a string, and encode for safe HTML output.
3464 * @param $text String text to be converted
3465 * @param $isTitle Bool whether this conversion is for the article title
3466 * @return string
3467 * @todo this should get integrated somewhere sane
3468 */
3469 public function convertHtml( $text, $isTitle = false ) {
3470 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3471 }
3472
3473 /**
3474 * @param $key string
3475 * @return string
3476 */
3477 public function convertCategoryKey( $key ) {
3478 return $this->mConverter->convertCategoryKey( $key );
3479 }
3480
3481 /**
3482 * Get the list of variants supported by this language
3483 * see sample implementation in LanguageZh.php
3484 *
3485 * @return array an array of language codes
3486 */
3487 public function getVariants() {
3488 return $this->mConverter->getVariants();
3489 }
3490
3491 /**
3492 * @return string
3493 */
3494 public function getPreferredVariant() {
3495 return $this->mConverter->getPreferredVariant();
3496 }
3497
3498 /**
3499 * @return string
3500 */
3501 public function getDefaultVariant() {
3502 return $this->mConverter->getDefaultVariant();
3503 }
3504
3505 /**
3506 * @return string
3507 */
3508 public function getURLVariant() {
3509 return $this->mConverter->getURLVariant();
3510 }
3511
3512 /**
3513 * If a language supports multiple variants, it is
3514 * possible that non-existing link in one variant
3515 * actually exists in another variant. this function
3516 * tries to find it. See e.g. LanguageZh.php
3517 *
3518 * @param $link String: the name of the link
3519 * @param $nt Mixed: the title object of the link
3520 * @param $ignoreOtherCond Boolean: to disable other conditions when
3521 * we need to transclude a template or update a category's link
3522 * @return null the input parameters may be modified upon return
3523 */
3524 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3525 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3526 }
3527
3528 /**
3529 * If a language supports multiple variants, converts text
3530 * into an array of all possible variants of the text:
3531 * 'variant' => text in that variant
3532 *
3533 * @deprecated since 1.17 Use autoConvertToAllVariants()
3534 *
3535 * @param $text string
3536 *
3537 * @return string
3538 */
3539 public function convertLinkToAllVariants( $text ) {
3540 return $this->mConverter->convertLinkToAllVariants( $text );
3541 }
3542
3543 /**
3544 * returns language specific options used by User::getPageRenderHash()
3545 * for example, the preferred language variant
3546 *
3547 * @return string
3548 */
3549 function getExtraHashOptions() {
3550 return $this->mConverter->getExtraHashOptions();
3551 }
3552
3553 /**
3554 * For languages that support multiple variants, the title of an
3555 * article may be displayed differently in different variants. this
3556 * function returns the apporiate title defined in the body of the article.
3557 *
3558 * @return string
3559 */
3560 public function getParsedTitle() {
3561 return $this->mConverter->getParsedTitle();
3562 }
3563
3564 /**
3565 * Enclose a string with the "no conversion" tag. This is used by
3566 * various functions in the Parser
3567 *
3568 * @param $text String: text to be tagged for no conversion
3569 * @param $noParse bool
3570 * @return string the tagged text
3571 */
3572 public function markNoConversion( $text, $noParse = false ) {
3573 return $this->mConverter->markNoConversion( $text, $noParse );
3574 }
3575
3576 /**
3577 * A regular expression to match legal word-trailing characters
3578 * which should be merged onto a link of the form [[foo]]bar.
3579 *
3580 * @return string
3581 */
3582 public function linkTrail() {
3583 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3584 }
3585
3586 /**
3587 * @return Language
3588 */
3589 function getLangObj() {
3590 return $this;
3591 }
3592
3593 /**
3594 * Get the RFC 3066 code for this language object
3595 *
3596 * @return string
3597 */
3598 public function getCode() {
3599 return $this->mCode;
3600 }
3601
3602 /**
3603 * Get the code in Bcp47 format which we can use
3604 * inside of html lang="" tags.
3605 * @since 1.19
3606 * @return string
3607 */
3608 public function getHtmlCode() {
3609 if ( is_null( $this->mHtmlCode ) ) {
3610 $this->mHtmlCode = wfBCP47( $this->getCode() );
3611 }
3612 return $this->mHtmlCode;
3613 }
3614
3615 /**
3616 * @param $code string
3617 */
3618 public function setCode( $code ) {
3619 $this->mCode = $code;
3620 // Ensure we don't leave an incorrect html code lying around
3621 $this->mHtmlCode = null;
3622 }
3623
3624 /**
3625 * Get the name of a file for a certain language code
3626 * @param $prefix string Prepend this to the filename
3627 * @param $code string Language code
3628 * @param $suffix string Append this to the filename
3629 * @throws MWException
3630 * @return string $prefix . $mangledCode . $suffix
3631 */
3632 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3633 // Protect against path traversal
3634 if ( !Language::isValidCode( $code )
3635 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3636 {
3637 throw new MWException( "Invalid language code \"$code\"" );
3638 }
3639
3640 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3641 }
3642
3643 /**
3644 * Get the language code from a file name. Inverse of getFileName()
3645 * @param $filename string $prefix . $languageCode . $suffix
3646 * @param $prefix string Prefix before the language code
3647 * @param $suffix string Suffix after the language code
3648 * @return string Language code, or false if $prefix or $suffix isn't found
3649 */
3650 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3651 $m = null;
3652 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3653 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3654 if ( !count( $m ) ) {
3655 return false;
3656 }
3657 return str_replace( '_', '-', strtolower( $m[1] ) );
3658 }
3659
3660 /**
3661 * @param $code string
3662 * @return string
3663 */
3664 public static function getMessagesFileName( $code ) {
3665 global $IP;
3666 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3667 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3668 return $file;
3669 }
3670
3671 /**
3672 * @param $code string
3673 * @return string
3674 */
3675 public static function getClassFileName( $code ) {
3676 global $IP;
3677 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3678 }
3679
3680 /**
3681 * Get the first fallback for a given language.
3682 *
3683 * @param $code string
3684 *
3685 * @return bool|string
3686 */
3687 public static function getFallbackFor( $code ) {
3688 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3689 return false;
3690 } else {
3691 $fallbacks = self::getFallbacksFor( $code );
3692 $first = array_shift( $fallbacks );
3693 return $first;
3694 }
3695 }
3696
3697 /**
3698 * Get the ordered list of fallback languages.
3699 *
3700 * @since 1.19
3701 * @param $code string Language code
3702 * @return array
3703 */
3704 public static function getFallbacksFor( $code ) {
3705 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3706 return array();
3707 } else {
3708 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3709 $v = array_map( 'trim', explode( ',', $v ) );
3710 if ( $v[count( $v ) - 1] !== 'en' ) {
3711 $v[] = 'en';
3712 }
3713 return $v;
3714 }
3715 }
3716
3717 /**
3718 * Get all messages for a given language
3719 * WARNING: this may take a long time. If you just need all message *keys*
3720 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3721 *
3722 * @param $code string
3723 *
3724 * @return array
3725 */
3726 public static function getMessagesFor( $code ) {
3727 return self::getLocalisationCache()->getItem( $code, 'messages' );
3728 }
3729
3730 /**
3731 * Get a message for a given language
3732 *
3733 * @param $key string
3734 * @param $code string
3735 *
3736 * @return string
3737 */
3738 public static function getMessageFor( $key, $code ) {
3739 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3740 }
3741
3742 /**
3743 * Get all message keys for a given language. This is a faster alternative to
3744 * array_keys( Language::getMessagesFor( $code ) )
3745 *
3746 * @since 1.19
3747 * @param $code string Language code
3748 * @return array of message keys (strings)
3749 */
3750 public static function getMessageKeysFor( $code ) {
3751 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3752 }
3753
3754 /**
3755 * @param $talk
3756 * @return mixed
3757 */
3758 function fixVariableInNamespace( $talk ) {
3759 if ( strpos( $talk, '$1' ) === false ) {
3760 return $talk;
3761 }
3762
3763 global $wgMetaNamespace;
3764 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3765
3766 # Allow grammar transformations
3767 # Allowing full message-style parsing would make simple requests
3768 # such as action=raw much more expensive than they need to be.
3769 # This will hopefully cover most cases.
3770 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3771 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3772 return str_replace( ' ', '_', $talk );
3773 }
3774
3775 /**
3776 * @param $m string
3777 * @return string
3778 */
3779 function replaceGrammarInNamespace( $m ) {
3780 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3781 }
3782
3783 /**
3784 * @throws MWException
3785 * @return array
3786 */
3787 static function getCaseMaps() {
3788 static $wikiUpperChars, $wikiLowerChars;
3789 if ( isset( $wikiUpperChars ) ) {
3790 return array( $wikiUpperChars, $wikiLowerChars );
3791 }
3792
3793 wfProfileIn( __METHOD__ );
3794 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3795 if ( $arr === false ) {
3796 throw new MWException(
3797 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3798 }
3799 $wikiUpperChars = $arr['wikiUpperChars'];
3800 $wikiLowerChars = $arr['wikiLowerChars'];
3801 wfProfileOut( __METHOD__ );
3802 return array( $wikiUpperChars, $wikiLowerChars );
3803 }
3804
3805 /**
3806 * Decode an expiry (block, protection, etc) which has come from the DB
3807 *
3808 * @FIXME: why are we returnings DBMS-dependent strings???
3809 *
3810 * @param $expiry String: Database expiry String
3811 * @param $format Bool|Int true to process using language functions, or TS_ constant
3812 * to return the expiry in a given timestamp
3813 * @return String
3814 */
3815 public function formatExpiry( $expiry, $format = true ) {
3816 static $infinity, $infinityMsg;
3817 if ( $infinity === null ) {
3818 $infinityMsg = wfMessage( 'infiniteblock' );
3819 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3820 }
3821
3822 if ( $expiry == '' || $expiry == $infinity ) {
3823 return $format === true
3824 ? $infinityMsg
3825 : $infinity;
3826 } else {
3827 return $format === true
3828 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3829 : wfTimestamp( $format, $expiry );
3830 }
3831 }
3832
3833 /**
3834 * @todo Document
3835 * @param $seconds int|float
3836 * @param $format Array Optional
3837 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3838 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3839 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3840 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3841 * @return string
3842 */
3843 function formatTimePeriod( $seconds, $format = array() ) {
3844 if ( !is_array( $format ) ) {
3845 $format = array( 'avoid' => $format ); // For backwards compatibility
3846 }
3847 if ( !isset( $format['avoid'] ) ) {
3848 $format['avoid'] = false;
3849 }
3850 if ( !isset( $format['noabbrevs' ] ) ) {
3851 $format['noabbrevs'] = false;
3852 }
3853 $secondsMsg = wfMessage(
3854 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3855 $minutesMsg = wfMessage(
3856 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3857 $hoursMsg = wfMessage(
3858 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
3859 $daysMsg = wfMessage(
3860 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
3861
3862 if ( round( $seconds * 10 ) < 100 ) {
3863 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3864 $s = $secondsMsg->params( $s )->text();
3865 } elseif ( round( $seconds ) < 60 ) {
3866 $s = $this->formatNum( round( $seconds ) );
3867 $s = $secondsMsg->params( $s )->text();
3868 } elseif ( round( $seconds ) < 3600 ) {
3869 $minutes = floor( $seconds / 60 );
3870 $secondsPart = round( fmod( $seconds, 60 ) );
3871 if ( $secondsPart == 60 ) {
3872 $secondsPart = 0;
3873 $minutes++;
3874 }
3875 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3876 $s .= ' ';
3877 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3878 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3879 $hours = floor( $seconds / 3600 );
3880 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3881 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3882 if ( $secondsPart == 60 ) {
3883 $secondsPart = 0;
3884 $minutes++;
3885 }
3886 if ( $minutes == 60 ) {
3887 $minutes = 0;
3888 $hours++;
3889 }
3890 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3891 $s .= ' ';
3892 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3893 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3894 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3895 }
3896 } else {
3897 $days = floor( $seconds / 86400 );
3898 if ( $format['avoid'] === 'avoidminutes' ) {
3899 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3900 if ( $hours == 24 ) {
3901 $hours = 0;
3902 $days++;
3903 }
3904 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3905 $s .= ' ';
3906 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3907 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3908 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3909 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3910 if ( $minutes == 60 ) {
3911 $minutes = 0;
3912 $hours++;
3913 }
3914 if ( $hours == 24 ) {
3915 $hours = 0;
3916 $days++;
3917 }
3918 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3919 $s .= ' ';
3920 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3921 $s .= ' ';
3922 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3923 } else {
3924 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3925 $s .= ' ';
3926 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3927 }
3928 }
3929 return $s;
3930 }
3931
3932 /**
3933 * Format a bitrate for output, using an appropriate
3934 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3935 *
3936 * This use base 1000. For base 1024 use formatSize(), for another base
3937 * see formatComputingNumbers()
3938 *
3939 * @param $bps int
3940 * @return string
3941 */
3942 function formatBitrate( $bps ) {
3943 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
3944 }
3945
3946 /**
3947 * @param $size int Size of the unit
3948 * @param $boundary int Size boundary (1000, or 1024 in most cases)
3949 * @param $messageKey string Message key to be uesd
3950 * @return string
3951 */
3952 function formatComputingNumbers( $size, $boundary, $messageKey ) {
3953 if ( $size <= 0 ) {
3954 return str_replace( '$1', $this->formatNum( $size ),
3955 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
3956 );
3957 }
3958 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
3959 $index = 0;
3960
3961 $maxIndex = count( $sizes ) - 1;
3962 while ( $size >= $boundary && $index < $maxIndex ) {
3963 $index++;
3964 $size /= $boundary;
3965 }
3966
3967 // For small sizes no decimal places necessary
3968 $round = 0;
3969 if ( $index > 1 ) {
3970 // For MB and bigger two decimal places are smarter
3971 $round = 2;
3972 }
3973 $msg = str_replace( '$1', $sizes[$index], $messageKey );
3974
3975 $size = round( $size, $round );
3976 $text = $this->getMessageFromDB( $msg );
3977 return str_replace( '$1', $this->formatNum( $size ), $text );
3978 }
3979
3980 /**
3981 * Format a size in bytes for output, using an appropriate
3982 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
3983 *
3984 * This method use base 1024. For base 1000 use formatBitrate(), for
3985 * another base see formatComputingNumbers()
3986 *
3987 * @param $size int Size to format
3988 * @return string Plain text (not HTML)
3989 */
3990 function formatSize( $size ) {
3991 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
3992 }
3993
3994 /**
3995 * Make a list item, used by various special pages
3996 *
3997 * @param $page String Page link
3998 * @param $details String Text between brackets
3999 * @param $oppositedm Boolean Add the direction mark opposite to your
4000 * language, to display text properly
4001 * @return String
4002 */
4003 function specialList( $page, $details, $oppositedm = true ) {
4004 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4005 $this->getDirMark();
4006 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4007 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4008 return $page . $details;
4009 }
4010
4011 /**
4012 * Generate (prev x| next x) (20|50|100...) type links for paging
4013 *
4014 * @param $title Title object to link
4015 * @param $offset Integer offset parameter
4016 * @param $limit Integer limit parameter
4017 * @param $query String optional URL query parameter string
4018 * @param $atend Bool optional param for specified if this is the last page
4019 * @return String
4020 */
4021 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4022 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4023
4024 # Make 'previous' link
4025 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4026 if ( $offset > 0 ) {
4027 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4028 $query, $prev, 'prevn-title', 'mw-prevlink' );
4029 } else {
4030 $plink = htmlspecialchars( $prev );
4031 }
4032
4033 # Make 'next' link
4034 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4035 if ( $atend ) {
4036 $nlink = htmlspecialchars( $next );
4037 } else {
4038 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4039 $query, $next, 'prevn-title', 'mw-nextlink' );
4040 }
4041
4042 # Make links to set number of items per page
4043 $numLinks = array();
4044 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4045 $numLinks[] = $this->numLink( $title, $offset, $num,
4046 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4047 }
4048
4049 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4050 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4051 }
4052
4053 /**
4054 * Helper function for viewPrevNext() that generates links
4055 *
4056 * @param $title Title object to link
4057 * @param $offset Integer offset parameter
4058 * @param $limit Integer limit parameter
4059 * @param $query Array extra query parameters
4060 * @param $link String text to use for the link; will be escaped
4061 * @param $tooltipMsg String name of the message to use as tooltip
4062 * @param $class String value of the "class" attribute of the link
4063 * @return String HTML fragment
4064 */
4065 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4066 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4067 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4068 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4069 'title' => $tooltip, 'class' => $class ), $link );
4070 }
4071
4072 /**
4073 * Get the conversion rule title, if any.
4074 *
4075 * @return string
4076 */
4077 public function getConvRuleTitle() {
4078 return $this->mConverter->getConvRuleTitle();
4079 }
4080 }