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