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