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