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