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