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