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