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