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