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