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