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