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