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