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