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