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