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