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