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