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