e505b287e5f2cc2e054bb16217ee7ce0c366016c
[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 string $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 if ( $data[0] == 'System' || $tz == '' ) {
1912 # Global offset in minutes.
1913 $minDiff = $wgLocalTZoffset;
1914 } elseif ( $data[0] == 'Offset' ) {
1915 $minDiff = intval( $data[1] );
1916 } else {
1917 $data = explode( ':', $tz );
1918 if ( count( $data ) == 2 ) {
1919 $data[0] = intval( $data[0] );
1920 $data[1] = intval( $data[1] );
1921 $minDiff = abs( $data[0] ) * 60 + $data[1];
1922 if ( $data[0] < 0 ) {
1923 $minDiff = -$minDiff;
1924 }
1925 } else {
1926 $minDiff = intval( $data[0] ) * 60;
1927 }
1928 }
1929
1930 # No difference ? Return time unchanged
1931 if ( 0 == $minDiff ) {
1932 return $ts;
1933 }
1934
1935 wfSuppressWarnings(); // E_STRICT system time bitching
1936 # Generate an adjusted date; take advantage of the fact that mktime
1937 # will normalize out-of-range values so we don't have to split $minDiff
1938 # into hours and minutes.
1939 $t = mktime( (
1940 (int)substr( $ts, 8, 2 ) ), # Hours
1941 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1942 (int)substr( $ts, 12, 2 ), # Seconds
1943 (int)substr( $ts, 4, 2 ), # Month
1944 (int)substr( $ts, 6, 2 ), # Day
1945 (int)substr( $ts, 0, 4 ) ); # Year
1946
1947 $date = date( 'YmdHis', $t );
1948 wfRestoreWarnings();
1949
1950 return $date;
1951 }
1952
1953 /**
1954 * This is meant to be used by time(), date(), and timeanddate() to get
1955 * the date preference they're supposed to use, it should be used in
1956 * all children.
1957 *
1958 *<code>
1959 * function timeanddate([...], $format = true) {
1960 * $datePreference = $this->dateFormat($format);
1961 * [...]
1962 * }
1963 *</code>
1964 *
1965 * @param int|string|bool $usePrefs If true, the user's preference is used
1966 * if false, the site/language default is used
1967 * if int/string, assumed to be a format.
1968 * @return string
1969 */
1970 function dateFormat( $usePrefs = true ) {
1971 global $wgUser;
1972
1973 if ( is_bool( $usePrefs ) ) {
1974 if ( $usePrefs ) {
1975 $datePreference = $wgUser->getDatePreference();
1976 } else {
1977 $datePreference = (string)User::getDefaultOption( 'date' );
1978 }
1979 } else {
1980 $datePreference = (string)$usePrefs;
1981 }
1982
1983 // return int
1984 if ( $datePreference == '' ) {
1985 return 'default';
1986 }
1987
1988 return $datePreference;
1989 }
1990
1991 /**
1992 * Get a format string for a given type and preference
1993 * @param string $type May be date, time or both
1994 * @param string $pref The format name as it appears in Messages*.php
1995 *
1996 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1997 *
1998 * @return string
1999 */
2000 function getDateFormatString( $type, $pref ) {
2001 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
2002 if ( $pref == 'default' ) {
2003 $pref = $this->getDefaultDateFormat();
2004 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2005 } else {
2006 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2007
2008 if ( $type === 'pretty' && $df === null ) {
2009 $df = $this->getDateFormatString( 'date', $pref );
2010 }
2011
2012 if ( $df === null ) {
2013 $pref = $this->getDefaultDateFormat();
2014 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
2015 }
2016 }
2017 $this->dateFormatStrings[$type][$pref] = $df;
2018 }
2019 return $this->dateFormatStrings[$type][$pref];
2020 }
2021
2022 /**
2023 * @param string $ts The time format which needs to be turned into a
2024 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2025 * @param bool $adj Whether to adjust the time output according to the
2026 * user configured offset ($timecorrection)
2027 * @param mixed $format True to use user's date format preference
2028 * @param string|bool $timecorrection The time offset as returned by
2029 * validateTimeZone() in Special:Preferences
2030 * @return string
2031 */
2032 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2033 $ts = wfTimestamp( TS_MW, $ts );
2034 if ( $adj ) {
2035 $ts = $this->userAdjust( $ts, $timecorrection );
2036 }
2037 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2038 return $this->sprintfDate( $df, $ts );
2039 }
2040
2041 /**
2042 * @param string $ts The time format which needs to be turned into a
2043 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2044 * @param bool $adj Whether to adjust the time output according to the
2045 * user configured offset ($timecorrection)
2046 * @param mixed $format True to use user's date format preference
2047 * @param string|bool $timecorrection The time offset as returned by
2048 * validateTimeZone() in Special:Preferences
2049 * @return string
2050 */
2051 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2052 $ts = wfTimestamp( TS_MW, $ts );
2053 if ( $adj ) {
2054 $ts = $this->userAdjust( $ts, $timecorrection );
2055 }
2056 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2057 return $this->sprintfDate( $df, $ts );
2058 }
2059
2060 /**
2061 * @param string $ts The time format which needs to be turned into a
2062 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2063 * @param bool $adj Whether to adjust the time output according to the
2064 * user configured offset ($timecorrection)
2065 * @param mixed $format What format to return, if it's false output the
2066 * default one (default true)
2067 * @param string|bool $timecorrection The time offset as returned by
2068 * validateTimeZone() in Special:Preferences
2069 * @return string
2070 */
2071 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2072 $ts = wfTimestamp( TS_MW, $ts );
2073 if ( $adj ) {
2074 $ts = $this->userAdjust( $ts, $timecorrection );
2075 }
2076 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2077 return $this->sprintfDate( $df, $ts );
2078 }
2079
2080 /**
2081 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2082 *
2083 * @since 1.20
2084 *
2085 * @param int $seconds The amount of seconds.
2086 * @param array $chosenIntervals The intervals to enable.
2087 *
2088 * @return string
2089 */
2090 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2091 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2092
2093 $segments = array();
2094
2095 foreach ( $intervals as $intervalName => $intervalValue ) {
2096 // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
2097 // duration-years, duration-decades, duration-centuries, duration-millennia
2098 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2099 $segments[] = $message->inLanguage( $this )->escaped();
2100 }
2101
2102 return $this->listToText( $segments );
2103 }
2104
2105 /**
2106 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2107 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2108 *
2109 * @since 1.20
2110 *
2111 * @param int $seconds The amount of seconds.
2112 * @param array $chosenIntervals The intervals to enable.
2113 *
2114 * @return array
2115 */
2116 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2117 if ( empty( $chosenIntervals ) ) {
2118 $chosenIntervals = array(
2119 'millennia',
2120 'centuries',
2121 'decades',
2122 'years',
2123 'days',
2124 'hours',
2125 'minutes',
2126 'seconds'
2127 );
2128 }
2129
2130 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2131 $sortedNames = array_keys( $intervals );
2132 $smallestInterval = array_pop( $sortedNames );
2133
2134 $segments = array();
2135
2136 foreach ( $intervals as $name => $length ) {
2137 $value = floor( $seconds / $length );
2138
2139 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2140 $seconds -= $value * $length;
2141 $segments[$name] = $value;
2142 }
2143 }
2144
2145 return $segments;
2146 }
2147
2148 /**
2149 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2150 *
2151 * @param string $type Can be 'date', 'time' or 'both'
2152 * @param string $ts The time format which needs to be turned into a
2153 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2154 * @param User $user User object used to get preferences for timezone and format
2155 * @param array $options Array, can contain the following keys:
2156 * - 'timecorrection': time correction, can have the following values:
2157 * - true: use user's preference
2158 * - false: don't use time correction
2159 * - int: value of time correction in minutes
2160 * - 'format': format to use, can have the following values:
2161 * - true: use user's preference
2162 * - false: use default preference
2163 * - string: format to use
2164 * @since 1.19
2165 * @return string
2166 */
2167 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2168 $ts = wfTimestamp( TS_MW, $ts );
2169 $options += array( 'timecorrection' => true, 'format' => true );
2170 if ( $options['timecorrection'] !== false ) {
2171 if ( $options['timecorrection'] === true ) {
2172 $offset = $user->getOption( 'timecorrection' );
2173 } else {
2174 $offset = $options['timecorrection'];
2175 }
2176 $ts = $this->userAdjust( $ts, $offset );
2177 }
2178 if ( $options['format'] === true ) {
2179 $format = $user->getDatePreference();
2180 } else {
2181 $format = $options['format'];
2182 }
2183 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2184 return $this->sprintfDate( $df, $ts );
2185 }
2186
2187 /**
2188 * Get the formatted date for the given timestamp and formatted for
2189 * the given user.
2190 *
2191 * @param mixed $ts Mixed: the time format which needs to be turned into a
2192 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2193 * @param User $user User object used to get preferences for timezone and format
2194 * @param array $options Array, can contain the following keys:
2195 * - 'timecorrection': time correction, can have the following values:
2196 * - true: use user's preference
2197 * - false: don't use time correction
2198 * - int: value of time correction in minutes
2199 * - 'format': format to use, can have the following values:
2200 * - true: use user's preference
2201 * - false: use default preference
2202 * - string: format to use
2203 * @since 1.19
2204 * @return string
2205 */
2206 public function userDate( $ts, User $user, array $options = array() ) {
2207 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2208 }
2209
2210 /**
2211 * Get the formatted time for the given timestamp and formatted for
2212 * the given user.
2213 *
2214 * @param mixed $ts The time format which needs to be turned into a
2215 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2216 * @param User $user User object used to get preferences for timezone and format
2217 * @param array $options Array, can contain the following keys:
2218 * - 'timecorrection': time correction, can have the following values:
2219 * - true: use user's preference
2220 * - false: don't use time correction
2221 * - int: value of time correction in minutes
2222 * - 'format': format to use, can have the following values:
2223 * - true: use user's preference
2224 * - false: use default preference
2225 * - string: format to use
2226 * @since 1.19
2227 * @return string
2228 */
2229 public function userTime( $ts, User $user, array $options = array() ) {
2230 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2231 }
2232
2233 /**
2234 * Get the formatted date and time for the given timestamp and formatted for
2235 * the given user.
2236 *
2237 * @param mixed $ts the time format which needs to be turned into a
2238 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2239 * @param User $user User object used to get preferences for timezone and format
2240 * @param array $options Array, can contain the following keys:
2241 * - 'timecorrection': time correction, can have the following values:
2242 * - true: use user's preference
2243 * - false: don't use time correction
2244 * - int: value of time correction in minutes
2245 * - 'format': format to use, can have the following values:
2246 * - true: use user's preference
2247 * - false: use default preference
2248 * - string: format to use
2249 * @since 1.19
2250 * @return string
2251 */
2252 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2253 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2254 }
2255
2256 /**
2257 * Convert an MWTimestamp into a pretty human-readable timestamp using
2258 * the given user preferences and relative base time.
2259 *
2260 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2261 * on your timestamp object, which will then call this function. Calling
2262 * this function directly will cause hooks to be skipped over.
2263 *
2264 * @see MWTimestamp::getHumanTimestamp
2265 * @param MWTimestamp $ts Timestamp to prettify
2266 * @param MWTimestamp $relativeTo Base timestamp
2267 * @param User $user User preferences to use
2268 * @return string Human timestamp
2269 * @since 1.22
2270 */
2271 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2272 $diff = $ts->diff( $relativeTo );
2273 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
2274 (int)$relativeTo->timestamp->format( 'w' ) );
2275 $days = $diff->days ?: (int)$diffDay;
2276 if ( $diff->invert || $days > 5
2277 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
2278 ) {
2279 // Timestamps are in different years: use full timestamp
2280 // Also do full timestamp for future dates
2281 /**
2282 * @FIXME Add better handling of future timestamps.
2283 */
2284 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2285 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2286 } elseif ( $days > 5 ) {
2287 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2288 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2289 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2290 } elseif ( $days > 1 ) {
2291 // Timestamp within the past week: show the day of the week and time
2292 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2293 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2294 // Messages:
2295 // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
2296 $ts = wfMessage( "$weekday-at" )
2297 ->inLanguage( $this )
2298 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2299 ->text();
2300 } elseif ( $days == 1 ) {
2301 // Timestamp was yesterday: say 'yesterday' and the time.
2302 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2303 $ts = wfMessage( 'yesterday-at' )
2304 ->inLanguage( $this )
2305 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2306 ->text();
2307 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2308 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2309 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2310 $ts = wfMessage( 'today-at' )
2311 ->inLanguage( $this )
2312 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2313 ->text();
2314
2315 // From here on in, the timestamp was soon enough ago so that we can simply say
2316 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2317 } elseif ( $diff->h == 1 ) {
2318 // Less than 90 minutes, but more than an hour ago.
2319 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2320 } elseif ( $diff->i >= 1 ) {
2321 // A few minutes ago.
2322 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2323 } elseif ( $diff->s >= 30 ) {
2324 // Less than a minute, but more than 30 sec ago.
2325 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2326 } else {
2327 // Less than 30 seconds ago.
2328 $ts = wfMessage( 'just-now' )->text();
2329 }
2330
2331 return $ts;
2332 }
2333
2334 /**
2335 * @param string $key
2336 * @return array|null
2337 */
2338 function getMessage( $key ) {
2339 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2340 }
2341
2342 /**
2343 * @return array
2344 */
2345 function getAllMessages() {
2346 return self::$dataCache->getItem( $this->mCode, 'messages' );
2347 }
2348
2349 /**
2350 * @param string $in
2351 * @param string $out
2352 * @param string $string
2353 * @return string
2354 */
2355 function iconv( $in, $out, $string ) {
2356 # This is a wrapper for iconv in all languages except esperanto,
2357 # which does some nasty x-conversions beforehand
2358
2359 # Even with //IGNORE iconv can whine about illegal characters in
2360 # *input* string. We just ignore those too.
2361 # REF: http://bugs.php.net/bug.php?id=37166
2362 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2363 wfSuppressWarnings();
2364 $text = iconv( $in, $out . '//IGNORE', $string );
2365 wfRestoreWarnings();
2366 return $text;
2367 }
2368
2369 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2370
2371 /**
2372 * @param array $matches
2373 * @return mixed|string
2374 */
2375 function ucwordbreaksCallbackAscii( $matches ) {
2376 return $this->ucfirst( $matches[1] );
2377 }
2378
2379 /**
2380 * @param array $matches
2381 * @return string
2382 */
2383 function ucwordbreaksCallbackMB( $matches ) {
2384 return mb_strtoupper( $matches[0] );
2385 }
2386
2387 /**
2388 * @param array $matches
2389 * @return string
2390 */
2391 function ucCallback( $matches ) {
2392 list( $wikiUpperChars ) = self::getCaseMaps();
2393 return strtr( $matches[1], $wikiUpperChars );
2394 }
2395
2396 /**
2397 * @param array $matches
2398 * @return string
2399 */
2400 function lcCallback( $matches ) {
2401 list( , $wikiLowerChars ) = self::getCaseMaps();
2402 return strtr( $matches[1], $wikiLowerChars );
2403 }
2404
2405 /**
2406 * @param array $matches
2407 * @return string
2408 */
2409 function ucwordsCallbackMB( $matches ) {
2410 return mb_strtoupper( $matches[0] );
2411 }
2412
2413 /**
2414 * @param array $matches
2415 * @return string
2416 */
2417 function ucwordsCallbackWiki( $matches ) {
2418 list( $wikiUpperChars ) = self::getCaseMaps();
2419 return strtr( $matches[0], $wikiUpperChars );
2420 }
2421
2422 /**
2423 * Make a string's first character uppercase
2424 *
2425 * @param string $str
2426 *
2427 * @return string
2428 */
2429 function ucfirst( $str ) {
2430 $o = ord( $str );
2431 if ( $o < 96 ) { // if already uppercase...
2432 return $str;
2433 } elseif ( $o < 128 ) {
2434 return ucfirst( $str ); // use PHP's ucfirst()
2435 } else {
2436 // fall back to more complex logic in case of multibyte strings
2437 return $this->uc( $str, true );
2438 }
2439 }
2440
2441 /**
2442 * Convert a string to uppercase
2443 *
2444 * @param string $str
2445 * @param bool $first
2446 *
2447 * @return string
2448 */
2449 function uc( $str, $first = false ) {
2450 if ( function_exists( 'mb_strtoupper' ) ) {
2451 if ( $first ) {
2452 if ( $this->isMultibyte( $str ) ) {
2453 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2454 } else {
2455 return ucfirst( $str );
2456 }
2457 } else {
2458 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2459 }
2460 } else {
2461 if ( $this->isMultibyte( $str ) ) {
2462 $x = $first ? '^' : '';
2463 return preg_replace_callback(
2464 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2465 array( $this, 'ucCallback' ),
2466 $str
2467 );
2468 } else {
2469 return $first ? ucfirst( $str ) : strtoupper( $str );
2470 }
2471 }
2472 }
2473
2474 /**
2475 * @param string $str
2476 * @return mixed|string
2477 */
2478 function lcfirst( $str ) {
2479 $o = ord( $str );
2480 if ( !$o ) {
2481 return strval( $str );
2482 } elseif ( $o >= 128 ) {
2483 return $this->lc( $str, true );
2484 } elseif ( $o > 96 ) {
2485 return $str;
2486 } else {
2487 $str[0] = strtolower( $str[0] );
2488 return $str;
2489 }
2490 }
2491
2492 /**
2493 * @param string $str
2494 * @param bool $first
2495 * @return mixed|string
2496 */
2497 function lc( $str, $first = false ) {
2498 if ( function_exists( 'mb_strtolower' ) ) {
2499 if ( $first ) {
2500 if ( $this->isMultibyte( $str ) ) {
2501 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2502 } else {
2503 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2504 }
2505 } else {
2506 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2507 }
2508 } else {
2509 if ( $this->isMultibyte( $str ) ) {
2510 $x = $first ? '^' : '';
2511 return preg_replace_callback(
2512 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2513 array( $this, 'lcCallback' ),
2514 $str
2515 );
2516 } else {
2517 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2518 }
2519 }
2520 }
2521
2522 /**
2523 * @param string $str
2524 * @return bool
2525 */
2526 function isMultibyte( $str ) {
2527 return (bool)preg_match( '/[\x80-\xff]/', $str );
2528 }
2529
2530 /**
2531 * @param string $str
2532 * @return mixed|string
2533 */
2534 function ucwords( $str ) {
2535 if ( $this->isMultibyte( $str ) ) {
2536 $str = $this->lc( $str );
2537
2538 // regexp to find first letter in each word (i.e. after each space)
2539 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2540
2541 // function to use to capitalize a single char
2542 if ( function_exists( 'mb_strtoupper' ) ) {
2543 return preg_replace_callback(
2544 $replaceRegexp,
2545 array( $this, 'ucwordsCallbackMB' ),
2546 $str
2547 );
2548 } else {
2549 return preg_replace_callback(
2550 $replaceRegexp,
2551 array( $this, 'ucwordsCallbackWiki' ),
2552 $str
2553 );
2554 }
2555 } else {
2556 return ucwords( strtolower( $str ) );
2557 }
2558 }
2559
2560 /**
2561 * capitalize words at word breaks
2562 *
2563 * @param string $str
2564 * @return mixed
2565 */
2566 function ucwordbreaks( $str ) {
2567 if ( $this->isMultibyte( $str ) ) {
2568 $str = $this->lc( $str );
2569
2570 // since \b doesn't work for UTF-8, we explicitely define word break chars
2571 $breaks = "[ \-\(\)\}\{\.,\?!]";
2572
2573 // find first letter after word break
2574 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
2575 "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2576
2577 if ( function_exists( 'mb_strtoupper' ) ) {
2578 return preg_replace_callback(
2579 $replaceRegexp,
2580 array( $this, 'ucwordbreaksCallbackMB' ),
2581 $str
2582 );
2583 } else {
2584 return preg_replace_callback(
2585 $replaceRegexp,
2586 array( $this, 'ucwordsCallbackWiki' ),
2587 $str
2588 );
2589 }
2590 } else {
2591 return preg_replace_callback(
2592 '/\b([\w\x80-\xff]+)\b/',
2593 array( $this, 'ucwordbreaksCallbackAscii' ),
2594 $str
2595 );
2596 }
2597 }
2598
2599 /**
2600 * Return a case-folded representation of $s
2601 *
2602 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2603 * and $s2 are the same except for the case of their characters. It is not
2604 * necessary for the value returned to make sense when displayed.
2605 *
2606 * Do *not* perform any other normalisation in this function. If a caller
2607 * uses this function when it should be using a more general normalisation
2608 * function, then fix the caller.
2609 *
2610 * @param string $s
2611 *
2612 * @return string
2613 */
2614 function caseFold( $s ) {
2615 return $this->uc( $s );
2616 }
2617
2618 /**
2619 * @param string $s
2620 * @return string
2621 */
2622 function checkTitleEncoding( $s ) {
2623 if ( is_array( $s ) ) {
2624 throw new MWException( 'Given array to checkTitleEncoding.' );
2625 }
2626 if ( StringUtils::isUtf8( $s ) ) {
2627 return $s;
2628 }
2629
2630 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2631 }
2632
2633 /**
2634 * @return array
2635 */
2636 function fallback8bitEncoding() {
2637 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2638 }
2639
2640 /**
2641 * Most writing systems use whitespace to break up words.
2642 * Some languages such as Chinese don't conventionally do this,
2643 * which requires special handling when breaking up words for
2644 * searching etc.
2645 *
2646 * @return bool
2647 */
2648 function hasWordBreaks() {
2649 return true;
2650 }
2651
2652 /**
2653 * Some languages such as Chinese require word segmentation,
2654 * Specify such segmentation when overridden in derived class.
2655 *
2656 * @param string $string
2657 * @return string
2658 */
2659 function segmentByWord( $string ) {
2660 return $string;
2661 }
2662
2663 /**
2664 * Some languages have special punctuation need to be normalized.
2665 * Make such changes here.
2666 *
2667 * @param string $string
2668 * @return string
2669 */
2670 function normalizeForSearch( $string ) {
2671 return self::convertDoubleWidth( $string );
2672 }
2673
2674 /**
2675 * convert double-width roman characters to single-width.
2676 * range: ff00-ff5f ~= 0020-007f
2677 *
2678 * @param string $string
2679 *
2680 * @return string
2681 */
2682 protected static function convertDoubleWidth( $string ) {
2683 static $full = null;
2684 static $half = null;
2685
2686 if ( $full === null ) {
2687 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2688 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2689 $full = str_split( $fullWidth, 3 );
2690 $half = str_split( $halfWidth );
2691 }
2692
2693 $string = str_replace( $full, $half, $string );
2694 return $string;
2695 }
2696
2697 /**
2698 * @param string $string
2699 * @param string $pattern
2700 * @return string
2701 */
2702 protected static function insertSpace( $string, $pattern ) {
2703 $string = preg_replace( $pattern, " $1 ", $string );
2704 $string = preg_replace( '/ +/', ' ', $string );
2705 return $string;
2706 }
2707
2708 /**
2709 * @param array $termsArray
2710 * @return array
2711 */
2712 function convertForSearchResult( $termsArray ) {
2713 # some languages, e.g. Chinese, need to do a conversion
2714 # in order for search results to be displayed correctly
2715 return $termsArray;
2716 }
2717
2718 /**
2719 * Get the first character of a string.
2720 *
2721 * @param string $s
2722 * @return string
2723 */
2724 function firstChar( $s ) {
2725 $matches = array();
2726 preg_match(
2727 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2728 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2729 $s,
2730 $matches
2731 );
2732
2733 if ( isset( $matches[1] ) ) {
2734 if ( strlen( $matches[1] ) != 3 ) {
2735 return $matches[1];
2736 }
2737
2738 // Break down Hangul syllables to grab the first jamo
2739 $code = utf8ToCodepoint( $matches[1] );
2740 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2741 return $matches[1];
2742 } elseif ( $code < 0xb098 ) {
2743 return "\xe3\x84\xb1";
2744 } elseif ( $code < 0xb2e4 ) {
2745 return "\xe3\x84\xb4";
2746 } elseif ( $code < 0xb77c ) {
2747 return "\xe3\x84\xb7";
2748 } elseif ( $code < 0xb9c8 ) {
2749 return "\xe3\x84\xb9";
2750 } elseif ( $code < 0xbc14 ) {
2751 return "\xe3\x85\x81";
2752 } elseif ( $code < 0xc0ac ) {
2753 return "\xe3\x85\x82";
2754 } elseif ( $code < 0xc544 ) {
2755 return "\xe3\x85\x85";
2756 } elseif ( $code < 0xc790 ) {
2757 return "\xe3\x85\x87";
2758 } elseif ( $code < 0xcc28 ) {
2759 return "\xe3\x85\x88";
2760 } elseif ( $code < 0xce74 ) {
2761 return "\xe3\x85\x8a";
2762 } elseif ( $code < 0xd0c0 ) {
2763 return "\xe3\x85\x8b";
2764 } elseif ( $code < 0xd30c ) {
2765 return "\xe3\x85\x8c";
2766 } elseif ( $code < 0xd558 ) {
2767 return "\xe3\x85\x8d";
2768 } else {
2769 return "\xe3\x85\x8e";
2770 }
2771 } else {
2772 return '';
2773 }
2774 }
2775
2776 function initEncoding() {
2777 # Some languages may have an alternate char encoding option
2778 # (Esperanto X-coding, Japanese furigana conversion, etc)
2779 # If this language is used as the primary content language,
2780 # an override to the defaults can be set here on startup.
2781 }
2782
2783 /**
2784 * @param string $s
2785 * @return string
2786 */
2787 function recodeForEdit( $s ) {
2788 # For some languages we'll want to explicitly specify
2789 # which characters make it into the edit box raw
2790 # or are converted in some way or another.
2791 global $wgEditEncoding;
2792 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2793 return $s;
2794 } else {
2795 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2796 }
2797 }
2798
2799 /**
2800 * @param string $s
2801 * @return string
2802 */
2803 function recodeInput( $s ) {
2804 # Take the previous into account.
2805 global $wgEditEncoding;
2806 if ( $wgEditEncoding != '' ) {
2807 $enc = $wgEditEncoding;
2808 } else {
2809 $enc = 'UTF-8';
2810 }
2811 if ( $enc == 'UTF-8' ) {
2812 return $s;
2813 } else {
2814 return $this->iconv( $enc, 'UTF-8', $s );
2815 }
2816 }
2817
2818 /**
2819 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2820 * also cleans up certain backwards-compatible sequences, converting them
2821 * to the modern Unicode equivalent.
2822 *
2823 * This is language-specific for performance reasons only.
2824 *
2825 * @param string $s
2826 *
2827 * @return string
2828 */
2829 function normalize( $s ) {
2830 global $wgAllUnicodeFixes;
2831 $s = UtfNormal::cleanUp( $s );
2832 if ( $wgAllUnicodeFixes ) {
2833 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2834 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2835 }
2836
2837 return $s;
2838 }
2839
2840 /**
2841 * Transform a string using serialized data stored in the given file (which
2842 * must be in the serialized subdirectory of $IP). The file contains pairs
2843 * mapping source characters to destination characters.
2844 *
2845 * The data is cached in process memory. This will go faster if you have the
2846 * FastStringSearch extension.
2847 *
2848 * @param string $file
2849 * @param string $string
2850 *
2851 * @throws MWException
2852 * @return string
2853 */
2854 function transformUsingPairFile( $file, $string ) {
2855 if ( !isset( $this->transformData[$file] ) ) {
2856 $data = wfGetPrecompiledData( $file );
2857 if ( $data === false ) {
2858 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2859 }
2860 $this->transformData[$file] = new ReplacementArray( $data );
2861 }
2862 return $this->transformData[$file]->replace( $string );
2863 }
2864
2865 /**
2866 * For right-to-left language support
2867 *
2868 * @return bool
2869 */
2870 function isRTL() {
2871 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2872 }
2873
2874 /**
2875 * Return the correct HTML 'dir' attribute value for this language.
2876 * @return string
2877 */
2878 function getDir() {
2879 return $this->isRTL() ? 'rtl' : 'ltr';
2880 }
2881
2882 /**
2883 * Return 'left' or 'right' as appropriate alignment for line-start
2884 * for this language's text direction.
2885 *
2886 * Should be equivalent to CSS3 'start' text-align value....
2887 *
2888 * @return string
2889 */
2890 function alignStart() {
2891 return $this->isRTL() ? 'right' : 'left';
2892 }
2893
2894 /**
2895 * Return 'right' or 'left' as appropriate alignment for line-end
2896 * for this language's text direction.
2897 *
2898 * Should be equivalent to CSS3 'end' text-align value....
2899 *
2900 * @return string
2901 */
2902 function alignEnd() {
2903 return $this->isRTL() ? 'left' : 'right';
2904 }
2905
2906 /**
2907 * A hidden direction mark (LRM or RLM), depending on the language direction.
2908 * Unlike getDirMark(), this function returns the character as an HTML entity.
2909 * This function should be used when the output is guaranteed to be HTML,
2910 * because it makes the output HTML source code more readable. When
2911 * the output is plain text or can be escaped, getDirMark() should be used.
2912 *
2913 * @param bool $opposite Get the direction mark opposite to your language
2914 * @return string
2915 * @since 1.20
2916 */
2917 function getDirMarkEntity( $opposite = false ) {
2918 if ( $opposite ) {
2919 return $this->isRTL() ? '&lrm;' : '&rlm;';
2920 }
2921 return $this->isRTL() ? '&rlm;' : '&lrm;';
2922 }
2923
2924 /**
2925 * A hidden direction mark (LRM or RLM), depending on the language direction.
2926 * This function produces them as invisible Unicode characters and
2927 * the output may be hard to read and debug, so it should only be used
2928 * when the output is plain text or can be escaped. When the output is
2929 * HTML, use getDirMarkEntity() instead.
2930 *
2931 * @param bool $opposite Get the direction mark opposite to your language
2932 * @return string
2933 */
2934 function getDirMark( $opposite = false ) {
2935 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2936 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2937 if ( $opposite ) {
2938 return $this->isRTL() ? $lrm : $rlm;
2939 }
2940 return $this->isRTL() ? $rlm : $lrm;
2941 }
2942
2943 /**
2944 * @return array
2945 */
2946 function capitalizeAllNouns() {
2947 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2948 }
2949
2950 /**
2951 * An arrow, depending on the language direction.
2952 *
2953 * @param string $direction The direction of the arrow: forwards (default),
2954 * backwards, left, right, up, down.
2955 * @return string
2956 */
2957 function getArrow( $direction = 'forwards' ) {
2958 switch ( $direction ) {
2959 case 'forwards':
2960 return $this->isRTL() ? '←' : '→';
2961 case 'backwards':
2962 return $this->isRTL() ? '→' : '←';
2963 case 'left':
2964 return '←';
2965 case 'right':
2966 return '→';
2967 case 'up':
2968 return '↑';
2969 case 'down':
2970 return '↓';
2971 }
2972 }
2973
2974 /**
2975 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2976 *
2977 * @return bool
2978 */
2979 function linkPrefixExtension() {
2980 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2981 }
2982
2983 /**
2984 * Get all magic words from cache.
2985 * @return array
2986 */
2987 function getMagicWords() {
2988 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2989 }
2990
2991 /**
2992 * Run the LanguageGetMagic hook once.
2993 */
2994 protected function doMagicHook() {
2995 if ( $this->mMagicHookDone ) {
2996 return;
2997 }
2998 $this->mMagicHookDone = true;
2999 wfProfileIn( 'LanguageGetMagic' );
3000 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
3001 wfProfileOut( 'LanguageGetMagic' );
3002 }
3003
3004 /**
3005 * Fill a MagicWord object with data from here
3006 *
3007 * @param MagicWord $mw
3008 */
3009 function getMagic( $mw ) {
3010 // Saves a function call
3011 if ( ! $this->mMagicHookDone ) {
3012 $this->doMagicHook();
3013 }
3014
3015 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
3016 $rawEntry = $this->mMagicExtensions[$mw->mId];
3017 } else {
3018 $rawEntry = self::$dataCache->getSubitem(
3019 $this->mCode, 'magicWords', $mw->mId );
3020 }
3021
3022 if ( !is_array( $rawEntry ) ) {
3023 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
3024 } else {
3025 $mw->mCaseSensitive = $rawEntry[0];
3026 $mw->mSynonyms = array_slice( $rawEntry, 1 );
3027 }
3028 }
3029
3030 /**
3031 * Add magic words to the extension array
3032 *
3033 * @param array $newWords
3034 */
3035 function addMagicWordsByLang( $newWords ) {
3036 $fallbackChain = $this->getFallbackLanguages();
3037 $fallbackChain = array_reverse( $fallbackChain );
3038 foreach ( $fallbackChain as $code ) {
3039 if ( isset( $newWords[$code] ) ) {
3040 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3041 }
3042 }
3043 }
3044
3045 /**
3046 * Get special page names, as an associative array
3047 * case folded alias => real name
3048 * @return array
3049 */
3050 function getSpecialPageAliases() {
3051 // Cache aliases because it may be slow to load them
3052 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3053 // Initialise array
3054 $this->mExtendedSpecialPageAliases =
3055 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3056 wfRunHooks( 'LanguageGetSpecialPageAliases',
3057 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3058 }
3059
3060 return $this->mExtendedSpecialPageAliases;
3061 }
3062
3063 /**
3064 * Italic is unsuitable for some languages
3065 *
3066 * @param string $text The text to be emphasized.
3067 * @return string
3068 */
3069 function emphasize( $text ) {
3070 return "<em>$text</em>";
3071 }
3072
3073 /**
3074 * Normally we output all numbers in plain en_US style, that is
3075 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3076 * point twohundredthirtyfive. However this is not suitable for all
3077 * languages, some such as Punjabi want ੨੯੩,੨੯੫.੨੩੫ and others such as
3078 * Icelandic just want to use commas instead of dots, and dots instead
3079 * of commas like "293.291,235".
3080 *
3081 * An example of this function being called:
3082 * <code>
3083 * wfMessage( 'message' )->numParams( $num )->text()
3084 * </code>
3085 *
3086 * See $separatorTransformTable on MessageIs.php for
3087 * the , => . and . => , implementation.
3088 *
3089 * @todo check if it's viable to use localeconv() for the decimal separator thing.
3090 * @param int|float $number The string to be formatted, should be an integer
3091 * or a floating point number.
3092 * @param bool $nocommafy Set to true for special numbers like dates
3093 * @return string
3094 */
3095 public function formatNum( $number, $nocommafy = false ) {
3096 global $wgTranslateNumerals;
3097 if ( !$nocommafy ) {
3098 $number = $this->commafy( $number );
3099 $s = $this->separatorTransformTable();
3100 if ( $s ) {
3101 $number = strtr( $number, $s );
3102 }
3103 }
3104
3105 if ( $wgTranslateNumerals ) {
3106 $s = $this->digitTransformTable();
3107 if ( $s ) {
3108 $number = strtr( $number, $s );
3109 }
3110 }
3111
3112 return $number;
3113 }
3114
3115 /**
3116 * Front-end for non-commafied formatNum
3117 *
3118 * @param int|float $number The string to be formatted, should be an integer
3119 * or a floating point number.
3120 * @since 1.21
3121 * @return string
3122 */
3123 public function formatNumNoSeparators( $number ) {
3124 return $this->formatNum( $number, true );
3125 }
3126
3127 /**
3128 * @param string $number
3129 * @return string
3130 */
3131 public function parseFormattedNumber( $number ) {
3132 $s = $this->digitTransformTable();
3133 if ( $s ) {
3134 // eliminate empty array values such as ''. (bug 64347)
3135 $s = array_filter( $s );
3136 $number = strtr( $number, array_flip( $s ) );
3137 }
3138
3139 $s = $this->separatorTransformTable();
3140 if ( $s ) {
3141 // eliminate empty array values such as ''. (bug 64347)
3142 $s = array_filter( $s );
3143 $number = strtr( $number, array_flip( $s ) );
3144 }
3145
3146 $number = strtr( $number, array( ',' => '' ) );
3147 return $number;
3148 }
3149
3150 /**
3151 * Adds commas to a given number
3152 * @since 1.19
3153 * @param mixed $number
3154 * @return string
3155 */
3156 function commafy( $number ) {
3157 $digitGroupingPattern = $this->digitGroupingPattern();
3158 if ( $number === null ) {
3159 return '';
3160 }
3161
3162 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3163 // default grouping is at thousands, use the same for ###,###,### pattern too.
3164 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3165 } else {
3166 // Ref: http://cldr.unicode.org/translation/number-patterns
3167 $sign = "";
3168 if ( intval( $number ) < 0 ) {
3169 // For negative numbers apply the algorithm like positive number and add sign.
3170 $sign = "-";
3171 $number = substr( $number, 1 );
3172 }
3173 $integerPart = array();
3174 $decimalPart = array();
3175 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3176 preg_match( "/\d+/", $number, $integerPart );
3177 preg_match( "/\.\d*/", $number, $decimalPart );
3178 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3179 if ( $groupedNumber === $number ) {
3180 // the string does not have any number part. Eg: .12345
3181 return $sign . $groupedNumber;
3182 }
3183 $start = $end = strlen( $integerPart[0] );
3184 while ( $start > 0 ) {
3185 $match = $matches[0][$numMatches - 1];
3186 $matchLen = strlen( $match );
3187 $start = $end - $matchLen;
3188 if ( $start < 0 ) {
3189 $start = 0;
3190 }
3191 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3192 $end = $start;
3193 if ( $numMatches > 1 ) {
3194 // use the last pattern for the rest of the number
3195 $numMatches--;
3196 }
3197 if ( $start > 0 ) {
3198 $groupedNumber = "," . $groupedNumber;
3199 }
3200 }
3201 return $sign . $groupedNumber;
3202 }
3203 }
3204
3205 /**
3206 * @return string
3207 */
3208 function digitGroupingPattern() {
3209 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3210 }
3211
3212 /**
3213 * @return array
3214 */
3215 function digitTransformTable() {
3216 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3217 }
3218
3219 /**
3220 * @return array
3221 */
3222 function separatorTransformTable() {
3223 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3224 }
3225
3226 /**
3227 * Take a list of strings and build a locale-friendly comma-separated
3228 * list, using the local comma-separator message.
3229 * The last two strings are chained with an "and".
3230 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3231 *
3232 * @param string[] $l
3233 * @return string
3234 */
3235 function listToText( array $l ) {
3236 $m = count( $l ) - 1;
3237 if ( $m < 0 ) {
3238 return '';
3239 }
3240 if ( $m > 0 ) {
3241 $and = $this->getMessageFromDB( 'and' );
3242 $space = $this->getMessageFromDB( 'word-separator' );
3243 if ( $m > 1 ) {
3244 $comma = $this->getMessageFromDB( 'comma-separator' );
3245 }
3246 }
3247 $s = $l[$m];
3248 for ( $i = $m - 1; $i >= 0; $i-- ) {
3249 if ( $i == $m - 1 ) {
3250 $s = $l[$i] . $and . $space . $s;
3251 } else {
3252 $s = $l[$i] . $comma . $s;
3253 }
3254 }
3255 return $s;
3256 }
3257
3258 /**
3259 * Take a list of strings and build a locale-friendly comma-separated
3260 * list, using the local comma-separator message.
3261 * @param string[] $list Array of strings to put in a comma list
3262 * @return string
3263 */
3264 function commaList( array $list ) {
3265 return implode(
3266 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3267 $list
3268 );
3269 }
3270
3271 /**
3272 * Take a list of strings and build a locale-friendly semicolon-separated
3273 * list, using the local semicolon-separator message.
3274 * @param string[] $list Array of strings to put in a semicolon list
3275 * @return string
3276 */
3277 function semicolonList( array $list ) {
3278 return implode(
3279 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3280 $list
3281 );
3282 }
3283
3284 /**
3285 * Same as commaList, but separate it with the pipe instead.
3286 * @param string[] $list Array of strings to put in a pipe list
3287 * @return string
3288 */
3289 function pipeList( array $list ) {
3290 return implode(
3291 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3292 $list
3293 );
3294 }
3295
3296 /**
3297 * Truncate a string to a specified length in bytes, appending an optional
3298 * string (e.g. for ellipses)
3299 *
3300 * The database offers limited byte lengths for some columns in the database;
3301 * multi-byte character sets mean we need to ensure that only whole characters
3302 * are included, otherwise broken characters can be passed to the user
3303 *
3304 * If $length is negative, the string will be truncated from the beginning
3305 *
3306 * @param string $string String to truncate
3307 * @param int $length Maximum length (including ellipses)
3308 * @param string $ellipsis String to append to the truncated text
3309 * @param bool $adjustLength Subtract length of ellipsis from $length.
3310 * $adjustLength was introduced in 1.18, before that behaved as if false.
3311 * @return string
3312 */
3313 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3314 # Use the localized ellipsis character
3315 if ( $ellipsis == '...' ) {
3316 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3317 }
3318 # Check if there is no need to truncate
3319 if ( $length == 0 ) {
3320 return $ellipsis; // convention
3321 } elseif ( strlen( $string ) <= abs( $length ) ) {
3322 return $string; // no need to truncate
3323 }
3324 $stringOriginal = $string;
3325 # If ellipsis length is >= $length then we can't apply $adjustLength
3326 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3327 $string = $ellipsis; // this can be slightly unexpected
3328 # Otherwise, truncate and add ellipsis...
3329 } else {
3330 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3331 if ( $length > 0 ) {
3332 $length -= $eLength;
3333 $string = substr( $string, 0, $length ); // xyz...
3334 $string = $this->removeBadCharLast( $string );
3335 $string = rtrim( $string );
3336 $string = $string . $ellipsis;
3337 } else {
3338 $length += $eLength;
3339 $string = substr( $string, $length ); // ...xyz
3340 $string = $this->removeBadCharFirst( $string );
3341 $string = ltrim( $string );
3342 $string = $ellipsis . $string;
3343 }
3344 }
3345 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3346 # This check is *not* redundant if $adjustLength, due to the single case where
3347 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3348 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3349 return $string;
3350 } else {
3351 return $stringOriginal;
3352 }
3353 }
3354
3355 /**
3356 * Remove bytes that represent an incomplete Unicode character
3357 * at the end of string (e.g. bytes of the char are missing)
3358 *
3359 * @param string $string
3360 * @return string
3361 */
3362 protected function removeBadCharLast( $string ) {
3363 if ( $string != '' ) {
3364 $char = ord( $string[strlen( $string ) - 1] );
3365 $m = array();
3366 if ( $char >= 0xc0 ) {
3367 # We got the first byte only of a multibyte char; remove it.
3368 $string = substr( $string, 0, -1 );
3369 } elseif ( $char >= 0x80 &&
3370 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3371 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3372 ) {
3373 # We chopped in the middle of a character; remove it
3374 $string = $m[1];
3375 }
3376 }
3377 return $string;
3378 }
3379
3380 /**
3381 * Remove bytes that represent an incomplete Unicode character
3382 * at the start of string (e.g. bytes of the char are missing)
3383 *
3384 * @param string $string
3385 * @return string
3386 */
3387 protected function removeBadCharFirst( $string ) {
3388 if ( $string != '' ) {
3389 $char = ord( $string[0] );
3390 if ( $char >= 0x80 && $char < 0xc0 ) {
3391 # We chopped in the middle of a character; remove the whole thing
3392 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3393 }
3394 }
3395 return $string;
3396 }
3397
3398 /**
3399 * Truncate a string of valid HTML to a specified length in bytes,
3400 * appending an optional string (e.g. for ellipses), and return valid HTML
3401 *
3402 * This is only intended for styled/linked text, such as HTML with
3403 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3404 * Also, this will not detect things like "display:none" CSS.
3405 *
3406 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3407 *
3408 * @param string $text HTML string to truncate
3409 * @param int $length (zero/positive) Maximum length (including ellipses)
3410 * @param string $ellipsis String to append to the truncated text
3411 * @return string
3412 */
3413 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3414 # Use the localized ellipsis character
3415 if ( $ellipsis == '...' ) {
3416 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3417 }
3418 # Check if there is clearly no need to truncate
3419 if ( $length <= 0 ) {
3420 return $ellipsis; // no text shown, nothing to format (convention)
3421 } elseif ( strlen( $text ) <= $length ) {
3422 return $text; // string short enough even *with* HTML (short-circuit)
3423 }
3424
3425 $dispLen = 0; // innerHTML legth so far
3426 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3427 $tagType = 0; // 0-open, 1-close
3428 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3429 $entityState = 0; // 0-not entity, 1-entity
3430 $tag = $ret = ''; // accumulated tag name, accumulated result string
3431 $openTags = array(); // open tag stack
3432 $maybeState = null; // possible truncation state
3433
3434 $textLen = strlen( $text );
3435 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3436 for ( $pos = 0; true; ++$pos ) {
3437 # Consider truncation once the display length has reached the maximim.
3438 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3439 # Check that we're not in the middle of a bracket/entity...
3440 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3441 if ( !$testingEllipsis ) {
3442 $testingEllipsis = true;
3443 # Save where we are; we will truncate here unless there turn out to
3444 # be so few remaining characters that truncation is not necessary.
3445 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3446 $maybeState = array( $ret, $openTags ); // save state
3447 }
3448 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3449 # String in fact does need truncation, the truncation point was OK.
3450 list( $ret, $openTags ) = $maybeState; // reload state
3451 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3452 $ret .= $ellipsis; // add ellipsis
3453 break;
3454 }
3455 }
3456 if ( $pos >= $textLen ) {
3457 break; // extra iteration just for above checks
3458 }
3459
3460 # Read the next char...
3461 $ch = $text[$pos];
3462 $lastCh = $pos ? $text[$pos - 1] : '';
3463 $ret .= $ch; // add to result string
3464 if ( $ch == '<' ) {
3465 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3466 $entityState = 0; // for bad HTML
3467 $bracketState = 1; // tag started (checking for backslash)
3468 } elseif ( $ch == '>' ) {
3469 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3470 $entityState = 0; // for bad HTML
3471 $bracketState = 0; // out of brackets
3472 } elseif ( $bracketState == 1 ) {
3473 if ( $ch == '/' ) {
3474 $tagType = 1; // close tag (e.g. "</span>")
3475 } else {
3476 $tagType = 0; // open tag (e.g. "<span>")
3477 $tag .= $ch;
3478 }
3479 $bracketState = 2; // building tag name
3480 } elseif ( $bracketState == 2 ) {
3481 if ( $ch != ' ' ) {
3482 $tag .= $ch;
3483 } else {
3484 // Name found (e.g. "<a href=..."), add on tag attributes...
3485 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3486 }
3487 } elseif ( $bracketState == 0 ) {
3488 if ( $entityState ) {
3489 if ( $ch == ';' ) {
3490 $entityState = 0;
3491 $dispLen++; // entity is one displayed char
3492 }
3493 } else {
3494 if ( $neLength == 0 && !$maybeState ) {
3495 // Save state without $ch. We want to *hit* the first
3496 // display char (to get tags) but not *use* it if truncating.
3497 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3498 }
3499 if ( $ch == '&' ) {
3500 $entityState = 1; // entity found, (e.g. "&#160;")
3501 } else {
3502 $dispLen++; // this char is displayed
3503 // Add the next $max display text chars after this in one swoop...
3504 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3505 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3506 $dispLen += $skipped;
3507 $pos += $skipped;
3508 }
3509 }
3510 }
3511 }
3512 // Close the last tag if left unclosed by bad HTML
3513 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3514 while ( count( $openTags ) > 0 ) {
3515 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3516 }
3517 return $ret;
3518 }
3519
3520 /**
3521 * truncateHtml() helper function
3522 * like strcspn() but adds the skipped chars to $ret
3523 *
3524 * @param string $ret
3525 * @param string $text
3526 * @param string $search
3527 * @param int $start
3528 * @param null|int $len
3529 * @return int
3530 */
3531 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3532 if ( $len === null ) {
3533 $len = -1; // -1 means "no limit" for strcspn
3534 } elseif ( $len < 0 ) {
3535 $len = 0; // sanity
3536 }
3537 $skipCount = 0;
3538 if ( $start < strlen( $text ) ) {
3539 $skipCount = strcspn( $text, $search, $start, $len );
3540 $ret .= substr( $text, $start, $skipCount );
3541 }
3542 return $skipCount;
3543 }
3544
3545 /**
3546 * truncateHtml() helper function
3547 * (a) push or pop $tag from $openTags as needed
3548 * (b) clear $tag value
3549 * @param string &$tag Current HTML tag name we are looking at
3550 * @param int $tagType (0-open tag, 1-close tag)
3551 * @param string $lastCh Character before the '>' that ended this tag
3552 * @param array &$openTags Open tag stack (not accounting for $tag)
3553 */
3554 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3555 $tag = ltrim( $tag );
3556 if ( $tag != '' ) {
3557 if ( $tagType == 0 && $lastCh != '/' ) {
3558 $openTags[] = $tag; // tag opened (didn't close itself)
3559 } elseif ( $tagType == 1 ) {
3560 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3561 array_pop( $openTags ); // tag closed
3562 }
3563 }
3564 $tag = '';
3565 }
3566 }
3567
3568 /**
3569 * Grammatical transformations, needed for inflected languages
3570 * Invoked by putting {{grammar:case|word}} in a message
3571 *
3572 * @param string $word
3573 * @param string $case
3574 * @return string
3575 */
3576 function convertGrammar( $word, $case ) {
3577 global $wgGrammarForms;
3578 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3579 return $wgGrammarForms[$this->getCode()][$case][$word];
3580 }
3581
3582 return $word;
3583 }
3584 /**
3585 * Get the grammar forms for the content language
3586 * @return array Array of grammar forms
3587 * @since 1.20
3588 */
3589 function getGrammarForms() {
3590 global $wgGrammarForms;
3591 if ( isset( $wgGrammarForms[$this->getCode()] )
3592 && is_array( $wgGrammarForms[$this->getCode()] )
3593 ) {
3594 return $wgGrammarForms[$this->getCode()];
3595 }
3596
3597 return array();
3598 }
3599 /**
3600 * Provides an alternative text depending on specified gender.
3601 * Usage {{gender:username|masculine|feminine|unknown}}.
3602 * username is optional, in which case the gender of current user is used,
3603 * but only in (some) interface messages; otherwise default gender is used.
3604 *
3605 * If no forms are given, an empty string is returned. If only one form is
3606 * given, it will be returned unconditionally. These details are implied by
3607 * the caller and cannot be overridden in subclasses.
3608 *
3609 * If three forms are given, the default is to use the third (unknown) form.
3610 * If fewer than three forms are given, the default is to use the first (masculine) form.
3611 * These details can be overridden in subclasses.
3612 *
3613 * @param string $gender
3614 * @param array $forms
3615 *
3616 * @return string
3617 */
3618 function gender( $gender, $forms ) {
3619 if ( !count( $forms ) ) {
3620 return '';
3621 }
3622 $forms = $this->preConvertPlural( $forms, 2 );
3623 if ( $gender === 'male' ) {
3624 return $forms[0];
3625 }
3626 if ( $gender === 'female' ) {
3627 return $forms[1];
3628 }
3629 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3630 }
3631
3632 /**
3633 * Plural form transformations, needed for some languages.
3634 * For example, there are 3 form of plural in Russian and Polish,
3635 * depending on "count mod 10". See [[w:Plural]]
3636 * For English it is pretty simple.
3637 *
3638 * Invoked by putting {{plural:count|wordform1|wordform2}}
3639 * or {{plural:count|wordform1|wordform2|wordform3}}
3640 *
3641 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3642 *
3643 * @param int $count Non-localized number
3644 * @param array $forms Different plural forms
3645 * @return string Correct form of plural for $count in this language
3646 */
3647 function convertPlural( $count, $forms ) {
3648 // Handle explicit n=pluralform cases
3649 $forms = $this->handleExplicitPluralForms( $count, $forms );
3650 if ( is_string( $forms ) ) {
3651 return $forms;
3652 }
3653 if ( !count( $forms ) ) {
3654 return '';
3655 }
3656
3657 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3658 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3659 return $forms[$pluralForm];
3660 }
3661
3662 /**
3663 * Handles explicit plural forms for Language::convertPlural()
3664 *
3665 * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
3666 * If an explicitly defined plural form matches the $count, then
3667 * string value returned, otherwise array returned for further consideration
3668 * by CLDR rules or overridden convertPlural().
3669 *
3670 * @since 1.23
3671 *
3672 * @param int $count non-localized number
3673 * @param array $forms different plural forms
3674 *
3675 * @return array|string
3676 */
3677 protected function handleExplicitPluralForms( $count, array $forms ) {
3678 foreach ( $forms as $index => $form ) {
3679 if ( preg_match( '/\d+=/i', $form ) ) {
3680 $pos = strpos( $form, '=' );
3681 if ( substr( $form, 0, $pos ) === (string) $count ) {
3682 return substr( $form, $pos + 1 );
3683 }
3684 unset( $forms[$index] );
3685 }
3686 }
3687 return array_values( $forms );
3688 }
3689
3690 /**
3691 * Checks that convertPlural was given an array and pads it to requested
3692 * amount of forms by copying the last one.
3693 *
3694 * @param int $count How many forms should there be at least
3695 * @param array $forms Array of forms given to convertPlural
3696 * @return array Padded array of forms or an exception if not an array
3697 */
3698 protected function preConvertPlural( /* Array */ $forms, $count ) {
3699 while ( count( $forms ) < $count ) {
3700 $forms[] = $forms[count( $forms ) - 1];
3701 }
3702 return $forms;
3703 }
3704
3705 /**
3706 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3707 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3708 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3709 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3710 * match up with it.
3711 *
3712 * @param string $str The validated block duration in English
3713 * @return string Somehow translated block duration
3714 * @see LanguageFi.php for example implementation
3715 */
3716 function translateBlockExpiry( $str ) {
3717 $duration = SpecialBlock::getSuggestedDurations( $this );
3718 foreach ( $duration as $show => $value ) {
3719 if ( strcmp( $str, $value ) == 0 ) {
3720 return htmlspecialchars( trim( $show ) );
3721 }
3722 }
3723
3724 // Since usually only infinite or indefinite is only on list, so try
3725 // equivalents if still here.
3726 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3727 if ( in_array( $str, $indefs ) ) {
3728 foreach ( $indefs as $val ) {
3729 $show = array_search( $val, $duration, true );
3730 if ( $show !== false ) {
3731 return htmlspecialchars( trim( $show ) );
3732 }
3733 }
3734 }
3735
3736 // If all else fails, return a standard duration or timestamp description.
3737 $time = strtotime( $str, 0 );
3738 if ( $time === false ) { // Unknown format. Return it as-is in case.
3739 return $str;
3740 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3741 // $time is relative to 0 so it's a duration length.
3742 return $this->formatDuration( $time );
3743 } else { // It's an absolute timestamp.
3744 if ( $time === 0 ) {
3745 // wfTimestamp() handles 0 as current time instead of epoch.
3746 return $this->timeanddate( '19700101000000' );
3747 } else {
3748 return $this->timeanddate( $time );
3749 }
3750 }
3751 }
3752
3753 /**
3754 * languages like Chinese need to be segmented in order for the diff
3755 * to be of any use
3756 *
3757 * @param string $text
3758 * @return string
3759 */
3760 public function segmentForDiff( $text ) {
3761 return $text;
3762 }
3763
3764 /**
3765 * and unsegment to show the result
3766 *
3767 * @param string $text
3768 * @return string
3769 */
3770 public function unsegmentForDiff( $text ) {
3771 return $text;
3772 }
3773
3774 /**
3775 * Return the LanguageConverter used in the Language
3776 *
3777 * @since 1.19
3778 * @return LanguageConverter
3779 */
3780 public function getConverter() {
3781 return $this->mConverter;
3782 }
3783
3784 /**
3785 * convert text to all supported variants
3786 *
3787 * @param string $text
3788 * @return array
3789 */
3790 public function autoConvertToAllVariants( $text ) {
3791 return $this->mConverter->autoConvertToAllVariants( $text );
3792 }
3793
3794 /**
3795 * convert text to different variants of a language.
3796 *
3797 * @param string $text
3798 * @return string
3799 */
3800 public function convert( $text ) {
3801 return $this->mConverter->convert( $text );
3802 }
3803
3804 /**
3805 * Convert a Title object to a string in the preferred variant
3806 *
3807 * @param Title $title
3808 * @return string
3809 */
3810 public function convertTitle( $title ) {
3811 return $this->mConverter->convertTitle( $title );
3812 }
3813
3814 /**
3815 * Convert a namespace index to a string in the preferred variant
3816 *
3817 * @param int $ns
3818 * @return string
3819 */
3820 public function convertNamespace( $ns ) {
3821 return $this->mConverter->convertNamespace( $ns );
3822 }
3823
3824 /**
3825 * Check if this is a language with variants
3826 *
3827 * @return bool
3828 */
3829 public function hasVariants() {
3830 return count( $this->getVariants() ) > 1;
3831 }
3832
3833 /**
3834 * Check if the language has the specific variant
3835 *
3836 * @since 1.19
3837 * @param string $variant
3838 * @return bool
3839 */
3840 public function hasVariant( $variant ) {
3841 return (bool)$this->mConverter->validateVariant( $variant );
3842 }
3843
3844 /**
3845 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3846 *
3847 * @param string $text
3848 * @return string
3849 * @deprecated since 1.22 is no longer used
3850 */
3851 public function armourMath( $text ) {
3852 return $this->mConverter->armourMath( $text );
3853 }
3854
3855 /**
3856 * Perform output conversion on a string, and encode for safe HTML output.
3857 * @param string $text Text to be converted
3858 * @param bool $isTitle Whether this conversion is for the article title
3859 * @return string
3860 * @todo this should get integrated somewhere sane
3861 */
3862 public function convertHtml( $text, $isTitle = false ) {
3863 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3864 }
3865
3866 /**
3867 * @param string $key
3868 * @return string
3869 */
3870 public function convertCategoryKey( $key ) {
3871 return $this->mConverter->convertCategoryKey( $key );
3872 }
3873
3874 /**
3875 * Get the list of variants supported by this language
3876 * see sample implementation in LanguageZh.php
3877 *
3878 * @return array an array of language codes
3879 */
3880 public function getVariants() {
3881 return $this->mConverter->getVariants();
3882 }
3883
3884 /**
3885 * @return string
3886 */
3887 public function getPreferredVariant() {
3888 return $this->mConverter->getPreferredVariant();
3889 }
3890
3891 /**
3892 * @return string
3893 */
3894 public function getDefaultVariant() {
3895 return $this->mConverter->getDefaultVariant();
3896 }
3897
3898 /**
3899 * @return string
3900 */
3901 public function getURLVariant() {
3902 return $this->mConverter->getURLVariant();
3903 }
3904
3905 /**
3906 * If a language supports multiple variants, it is
3907 * possible that non-existing link in one variant
3908 * actually exists in another variant. this function
3909 * tries to find it. See e.g. LanguageZh.php
3910 *
3911 * @param string $link The name of the link
3912 * @param Title $nt The title object of the link
3913 * @param bool $ignoreOtherCond To disable other conditions when
3914 * we need to transclude a template or update a category's link
3915 * @return null the input parameters may be modified upon return
3916 */
3917 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3918 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3919 }
3920
3921 /**
3922 * returns language specific options used by User::getPageRenderHash()
3923 * for example, the preferred language variant
3924 *
3925 * @return string
3926 */
3927 function getExtraHashOptions() {
3928 return $this->mConverter->getExtraHashOptions();
3929 }
3930
3931 /**
3932 * For languages that support multiple variants, the title of an
3933 * article may be displayed differently in different variants. this
3934 * function returns the apporiate title defined in the body of the article.
3935 *
3936 * @return string
3937 */
3938 public function getParsedTitle() {
3939 return $this->mConverter->getParsedTitle();
3940 }
3941
3942 /**
3943 * Prepare external link text for conversion. When the text is
3944 * a URL, it shouldn't be converted, and it'll be wrapped in
3945 * the "raw" tag (-{R| }-) to prevent conversion.
3946 *
3947 * This function is called "markNoConversion" for historical
3948 * reasons.
3949 *
3950 * @param string $text Text to be used for external link
3951 * @param bool $noParse Wrap it without confirming it's a real URL first
3952 * @return string The tagged text
3953 */
3954 public function markNoConversion( $text, $noParse = false ) {
3955 // Excluding protocal-relative URLs may avoid many false positives.
3956 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3957 return $this->mConverter->markNoConversion( $text );
3958 } else {
3959 return $text;
3960 }
3961 }
3962
3963 /**
3964 * A regular expression to match legal word-trailing characters
3965 * which should be merged onto a link of the form [[foo]]bar.
3966 *
3967 * @return string
3968 */
3969 public function linkTrail() {
3970 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3971 }
3972
3973 /**
3974 * A regular expression character set to match legal word-prefixing
3975 * characters which should be merged onto a link of the form foo[[bar]].
3976 *
3977 * @return string
3978 */
3979 public function linkPrefixCharset() {
3980 return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
3981 }
3982
3983 /**
3984 * @deprecated since 1.24, will be removed in 1.25
3985 * @return Language
3986 */
3987 function getLangObj() {
3988 wfDeprecated( __METHOD__, '1.24' );
3989 return $this;
3990 }
3991
3992 /**
3993 * Get the "parent" language which has a converter to convert a "compatible" language
3994 * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
3995 *
3996 * @return Language|null
3997 * @since 1.22
3998 */
3999 public function getParentLanguage() {
4000 if ( $this->mParentLanguage !== false ) {
4001 return $this->mParentLanguage;
4002 }
4003
4004 $pieces = explode( '-', $this->getCode() );
4005 $code = $pieces[0];
4006 if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
4007 $this->mParentLanguage = null;
4008 return null;
4009 }
4010 $lang = Language::factory( $code );
4011 if ( !$lang->hasVariant( $this->getCode() ) ) {
4012 $this->mParentLanguage = null;
4013 return null;
4014 }
4015
4016 $this->mParentLanguage = $lang;
4017 return $lang;
4018 }
4019
4020 /**
4021 * Get the RFC 3066 code for this language object
4022 *
4023 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4024 * htmlspecialchars() or similar
4025 *
4026 * @return string
4027 */
4028 public function getCode() {
4029 return $this->mCode;
4030 }
4031
4032 /**
4033 * Get the code in Bcp47 format which we can use
4034 * inside of html lang="" tags.
4035 *
4036 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
4037 * htmlspecialchars() or similar.
4038 *
4039 * @since 1.19
4040 * @return string
4041 */
4042 public function getHtmlCode() {
4043 if ( is_null( $this->mHtmlCode ) ) {
4044 $this->mHtmlCode = wfBCP47( $this->getCode() );
4045 }
4046 return $this->mHtmlCode;
4047 }
4048
4049 /**
4050 * @param string $code
4051 */
4052 public function setCode( $code ) {
4053 $this->mCode = $code;
4054 // Ensure we don't leave incorrect cached data lying around
4055 $this->mHtmlCode = null;
4056 $this->mParentLanguage = false;
4057 }
4058
4059 /**
4060 * Get the name of a file for a certain language code
4061 * @param string $prefix Prepend this to the filename
4062 * @param string $code Language code
4063 * @param string $suffix Append this to the filename
4064 * @throws MWException
4065 * @return string $prefix . $mangledCode . $suffix
4066 */
4067 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
4068 if ( !self::isValidBuiltInCode( $code ) ) {
4069 throw new MWException( "Invalid language code \"$code\"" );
4070 }
4071
4072 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
4073 }
4074
4075 /**
4076 * Get the language code from a file name. Inverse of getFileName()
4077 * @param string $filename $prefix . $languageCode . $suffix
4078 * @param string $prefix Prefix before the language code
4079 * @param string $suffix Suffix after the language code
4080 * @return string Language code, or false if $prefix or $suffix isn't found
4081 */
4082 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
4083 $m = null;
4084 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
4085 preg_quote( $suffix, '/' ) . '/', $filename, $m );
4086 if ( !count( $m ) ) {
4087 return false;
4088 }
4089 return str_replace( '_', '-', strtolower( $m[1] ) );
4090 }
4091
4092 /**
4093 * @param string $code
4094 * @return string
4095 */
4096 public static function getMessagesFileName( $code ) {
4097 global $IP;
4098 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4099 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4100 return $file;
4101 }
4102
4103 /**
4104 * @param string $code
4105 * @return string
4106 * @since 1.23
4107 */
4108 public static function getJsonMessagesFileName( $code ) {
4109 global $IP;
4110
4111 if ( !self::isValidBuiltInCode( $code ) ) {
4112 throw new MWException( "Invalid language code \"$code\"" );
4113 }
4114
4115 return "$IP/languages/i18n/$code.json";
4116 }
4117
4118 /**
4119 * @param string $code
4120 * @return string
4121 */
4122 public static function getClassFileName( $code ) {
4123 global $IP;
4124 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4125 }
4126
4127 /**
4128 * Get the first fallback for a given language.
4129 *
4130 * @param string $code
4131 *
4132 * @return bool|string
4133 */
4134 public static function getFallbackFor( $code ) {
4135 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4136 return false;
4137 } else {
4138 $fallbacks = self::getFallbacksFor( $code );
4139 $first = array_shift( $fallbacks );
4140 return $first;
4141 }
4142 }
4143
4144 /**
4145 * Get the ordered list of fallback languages.
4146 *
4147 * @since 1.19
4148 * @param string $code Language code
4149 * @return array
4150 */
4151 public static function getFallbacksFor( $code ) {
4152 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4153 return array();
4154 } else {
4155 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4156 $v = array_map( 'trim', explode( ',', $v ) );
4157 if ( $v[count( $v ) - 1] !== 'en' ) {
4158 $v[] = 'en';
4159 }
4160 return $v;
4161 }
4162 }
4163
4164 /**
4165 * Get the ordered list of fallback languages, ending with the fallback
4166 * language chain for the site language.
4167 *
4168 * @since 1.22
4169 * @param string $code Language code
4170 * @return array array( fallbacks, site fallbacks )
4171 */
4172 public static function getFallbacksIncludingSiteLanguage( $code ) {
4173 global $wgLanguageCode;
4174
4175 // Usually, we will only store a tiny number of fallback chains, so we
4176 // keep them in static memory.
4177 $cacheKey = "{$code}-{$wgLanguageCode}";
4178
4179 if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
4180 $fallbacks = self::getFallbacksFor( $code );
4181
4182 // Append the site's fallback chain, including the site language itself
4183 $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
4184 array_unshift( $siteFallbacks, $wgLanguageCode );
4185
4186 // Eliminate any languages already included in the chain
4187 $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
4188
4189 self::$fallbackLanguageCache[$cacheKey] = array( $fallbacks, $siteFallbacks );
4190 }
4191 return self::$fallbackLanguageCache[$cacheKey];
4192 }
4193
4194 /**
4195 * Get all messages for a given language
4196 * WARNING: this may take a long time. If you just need all message *keys*
4197 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4198 *
4199 * @param string $code
4200 *
4201 * @return array
4202 */
4203 public static function getMessagesFor( $code ) {
4204 return self::getLocalisationCache()->getItem( $code, 'messages' );
4205 }
4206
4207 /**
4208 * Get a message for a given language
4209 *
4210 * @param string $key
4211 * @param string $code
4212 *
4213 * @return string
4214 */
4215 public static function getMessageFor( $key, $code ) {
4216 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4217 }
4218
4219 /**
4220 * Get all message keys for a given language. This is a faster alternative to
4221 * array_keys( Language::getMessagesFor( $code ) )
4222 *
4223 * @since 1.19
4224 * @param string $code Language code
4225 * @return array of message keys (strings)
4226 */
4227 public static function getMessageKeysFor( $code ) {
4228 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4229 }
4230
4231 /**
4232 * @param string $talk
4233 * @return mixed
4234 */
4235 function fixVariableInNamespace( $talk ) {
4236 if ( strpos( $talk, '$1' ) === false ) {
4237 return $talk;
4238 }
4239
4240 global $wgMetaNamespace;
4241 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4242
4243 # Allow grammar transformations
4244 # Allowing full message-style parsing would make simple requests
4245 # such as action=raw much more expensive than they need to be.
4246 # This will hopefully cover most cases.
4247 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4248 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4249 return str_replace( ' ', '_', $talk );
4250 }
4251
4252 /**
4253 * @param string $m
4254 * @return string
4255 */
4256 function replaceGrammarInNamespace( $m ) {
4257 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4258 }
4259
4260 /**
4261 * @throws MWException
4262 * @return array
4263 */
4264 static function getCaseMaps() {
4265 static $wikiUpperChars, $wikiLowerChars;
4266 if ( isset( $wikiUpperChars ) ) {
4267 return array( $wikiUpperChars, $wikiLowerChars );
4268 }
4269
4270 wfProfileIn( __METHOD__ );
4271 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4272 if ( $arr === false ) {
4273 throw new MWException(
4274 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4275 }
4276 $wikiUpperChars = $arr['wikiUpperChars'];
4277 $wikiLowerChars = $arr['wikiLowerChars'];
4278 wfProfileOut( __METHOD__ );
4279 return array( $wikiUpperChars, $wikiLowerChars );
4280 }
4281
4282 /**
4283 * Decode an expiry (block, protection, etc) which has come from the DB
4284 *
4285 * @todo FIXME: why are we returnings DBMS-dependent strings???
4286 *
4287 * @param string $expiry Database expiry String
4288 * @param bool|int $format True to process using language functions, or TS_ constant
4289 * to return the expiry in a given timestamp
4290 * @return string
4291 * @since 1.18
4292 */
4293 public function formatExpiry( $expiry, $format = true ) {
4294 static $infinity;
4295 if ( $infinity === null ) {
4296 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4297 }
4298
4299 if ( $expiry == '' || $expiry == $infinity ) {
4300 return $format === true
4301 ? $this->getMessageFromDB( 'infiniteblock' )
4302 : $infinity;
4303 } else {
4304 return $format === true
4305 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4306 : wfTimestamp( $format, $expiry );
4307 }
4308 }
4309
4310 /**
4311 * @todo Document
4312 * @param int|float $seconds
4313 * @param array $format Optional
4314 * If $format['avoid'] === 'avoidseconds': don't mention seconds if $seconds >= 1 hour.
4315 * If $format['avoid'] === 'avoidminutes': don't mention seconds/minutes if $seconds > 48 hours.
4316 * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
4317 * and friends.
4318 * For backwards compatibility, $format may also be one of the strings 'avoidseconds'
4319 * or 'avoidminutes'.
4320 * @return string
4321 */
4322 function formatTimePeriod( $seconds, $format = array() ) {
4323 if ( !is_array( $format ) ) {
4324 $format = array( 'avoid' => $format ); // For backwards compatibility
4325 }
4326 if ( !isset( $format['avoid'] ) ) {
4327 $format['avoid'] = false;
4328 }
4329 if ( !isset( $format['noabbrevs' ] ) ) {
4330 $format['noabbrevs'] = false;
4331 }
4332 $secondsMsg = wfMessage(
4333 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4334 $minutesMsg = wfMessage(
4335 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4336 $hoursMsg = wfMessage(
4337 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4338 $daysMsg = wfMessage(
4339 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4340
4341 if ( round( $seconds * 10 ) < 100 ) {
4342 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4343 $s = $secondsMsg->params( $s )->text();
4344 } elseif ( round( $seconds ) < 60 ) {
4345 $s = $this->formatNum( round( $seconds ) );
4346 $s = $secondsMsg->params( $s )->text();
4347 } elseif ( round( $seconds ) < 3600 ) {
4348 $minutes = floor( $seconds / 60 );
4349 $secondsPart = round( fmod( $seconds, 60 ) );
4350 if ( $secondsPart == 60 ) {
4351 $secondsPart = 0;
4352 $minutes++;
4353 }
4354 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4355 $s .= ' ';
4356 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4357 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4358 $hours = floor( $seconds / 3600 );
4359 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4360 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4361 if ( $secondsPart == 60 ) {
4362 $secondsPart = 0;
4363 $minutes++;
4364 }
4365 if ( $minutes == 60 ) {
4366 $minutes = 0;
4367 $hours++;
4368 }
4369 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4370 $s .= ' ';
4371 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4372 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4373 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4374 }
4375 } else {
4376 $days = floor( $seconds / 86400 );
4377 if ( $format['avoid'] === 'avoidminutes' ) {
4378 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4379 if ( $hours == 24 ) {
4380 $hours = 0;
4381 $days++;
4382 }
4383 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4384 $s .= ' ';
4385 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4386 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4387 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4388 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4389 if ( $minutes == 60 ) {
4390 $minutes = 0;
4391 $hours++;
4392 }
4393 if ( $hours == 24 ) {
4394 $hours = 0;
4395 $days++;
4396 }
4397 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4398 $s .= ' ';
4399 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4400 $s .= ' ';
4401 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4402 } else {
4403 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4404 $s .= ' ';
4405 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4406 }
4407 }
4408 return $s;
4409 }
4410
4411 /**
4412 * Format a bitrate for output, using an appropriate
4413 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
4414 * the magnitude in question.
4415 *
4416 * This use base 1000. For base 1024 use formatSize(), for another base
4417 * see formatComputingNumbers().
4418 *
4419 * @param int $bps
4420 * @return string
4421 */
4422 function formatBitrate( $bps ) {
4423 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4424 }
4425
4426 /**
4427 * @param int $size Size of the unit
4428 * @param int $boundary Size boundary (1000, or 1024 in most cases)
4429 * @param string $messageKey Message key to be uesd
4430 * @return string
4431 */
4432 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4433 if ( $size <= 0 ) {
4434 return str_replace( '$1', $this->formatNum( $size ),
4435 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4436 );
4437 }
4438 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4439 $index = 0;
4440
4441 $maxIndex = count( $sizes ) - 1;
4442 while ( $size >= $boundary && $index < $maxIndex ) {
4443 $index++;
4444 $size /= $boundary;
4445 }
4446
4447 // For small sizes no decimal places necessary
4448 $round = 0;
4449 if ( $index > 1 ) {
4450 // For MB and bigger two decimal places are smarter
4451 $round = 2;
4452 }
4453 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4454
4455 $size = round( $size, $round );
4456 $text = $this->getMessageFromDB( $msg );
4457 return str_replace( '$1', $this->formatNum( $size ), $text );
4458 }
4459
4460 /**
4461 * Format a size in bytes for output, using an appropriate
4462 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4463 *
4464 * This method use base 1024. For base 1000 use formatBitrate(), for
4465 * another base see formatComputingNumbers()
4466 *
4467 * @param int $size Size to format
4468 * @return string Plain text (not HTML)
4469 */
4470 function formatSize( $size ) {
4471 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4472 }
4473
4474 /**
4475 * Make a list item, used by various special pages
4476 *
4477 * @param string $page Page link
4478 * @param string $details Text between brackets
4479 * @param bool $oppositedm Add the direction mark opposite to your
4480 * language, to display text properly
4481 * @return string
4482 */
4483 function specialList( $page, $details, $oppositedm = true ) {
4484 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4485 $this->getDirMark();
4486 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4487 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4488 return $page . $details;
4489 }
4490
4491 /**
4492 * Generate (prev x| next x) (20|50|100...) type links for paging
4493 *
4494 * @param Title $title Title object to link
4495 * @param int $offset
4496 * @param int $limit
4497 * @param array|string $query Optional URL query parameter string
4498 * @param bool $atend Optional param for specified if this is the last page
4499 * @return string
4500 */
4501 public function viewPrevNext( Title $title, $offset, $limit,
4502 array $query = array(), $atend = false
4503 ) {
4504 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4505
4506 # Make 'previous' link
4507 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4508 if ( $offset > 0 ) {
4509 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4510 $query, $prev, 'prevn-title', 'mw-prevlink' );
4511 } else {
4512 $plink = htmlspecialchars( $prev );
4513 }
4514
4515 # Make 'next' link
4516 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4517 if ( $atend ) {
4518 $nlink = htmlspecialchars( $next );
4519 } else {
4520 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4521 $query, $next, 'nextn-title', 'mw-nextlink' );
4522 }
4523
4524 # Make links to set number of items per page
4525 $numLinks = array();
4526 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4527 $numLinks[] = $this->numLink( $title, $offset, $num,
4528 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4529 }
4530
4531 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4532 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4533 }
4534
4535 /**
4536 * Helper function for viewPrevNext() that generates links
4537 *
4538 * @param Title $title Title object to link
4539 * @param int $offset
4540 * @param int $limit
4541 * @param array $query Extra query parameters
4542 * @param string $link Text to use for the link; will be escaped
4543 * @param string $tooltipMsg Name of the message to use as tooltip
4544 * @param string $class Value of the "class" attribute of the link
4545 * @return string HTML fragment
4546 */
4547 private function numLink( Title $title, $offset, $limit, array $query, $link,
4548 $tooltipMsg, $class
4549 ) {
4550 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4551 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
4552 ->numParams( $limit )->text();
4553
4554 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4555 'title' => $tooltip, 'class' => $class ), $link );
4556 }
4557
4558 /**
4559 * Get the conversion rule title, if any.
4560 *
4561 * @return string
4562 */
4563 public function getConvRuleTitle() {
4564 return $this->mConverter->getConvRuleTitle();
4565 }
4566
4567 /**
4568 * Get the compiled plural rules for the language
4569 * @since 1.20
4570 * @return array Associative array with plural form, and plural rule as key-value pairs
4571 */
4572 public function getCompiledPluralRules() {
4573 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4574 $fallbacks = Language::getFallbacksFor( $this->mCode );
4575 if ( !$pluralRules ) {
4576 foreach ( $fallbacks as $fallbackCode ) {
4577 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4578 if ( $pluralRules ) {
4579 break;
4580 }
4581 }
4582 }
4583 return $pluralRules;
4584 }
4585
4586 /**
4587 * Get the plural rules for the language
4588 * @since 1.20
4589 * @return array Associative array with plural form number and plural rule as key-value pairs
4590 */
4591 public function getPluralRules() {
4592 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4593 $fallbacks = Language::getFallbacksFor( $this->mCode );
4594 if ( !$pluralRules ) {
4595 foreach ( $fallbacks as $fallbackCode ) {
4596 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4597 if ( $pluralRules ) {
4598 break;
4599 }
4600 }
4601 }
4602 return $pluralRules;
4603 }
4604
4605 /**
4606 * Get the plural rule types for the language
4607 * @since 1.22
4608 * @return array Associative array with plural form number and plural rule type as key-value pairs
4609 */
4610 public function getPluralRuleTypes() {
4611 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4612 $fallbacks = Language::getFallbacksFor( $this->mCode );
4613 if ( !$pluralRuleTypes ) {
4614 foreach ( $fallbacks as $fallbackCode ) {
4615 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4616 if ( $pluralRuleTypes ) {
4617 break;
4618 }
4619 }
4620 }
4621 return $pluralRuleTypes;
4622 }
4623
4624 /**
4625 * Find the index number of the plural rule appropriate for the given number
4626 * @return int The index number of the plural rule
4627 */
4628 public function getPluralRuleIndexNumber( $number ) {
4629 $pluralRules = $this->getCompiledPluralRules();
4630 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4631 return $form;
4632 }
4633
4634 /**
4635 * Find the plural rule type appropriate for the given number
4636 * For example, if the language is set to Arabic, getPluralType(5) should
4637 * return 'few'.
4638 * @since 1.22
4639 * @return string The name of the plural rule type, e.g. one, two, few, many
4640 */
4641 public function getPluralRuleType( $number ) {
4642 $index = $this->getPluralRuleIndexNumber( $number );
4643 $pluralRuleTypes = $this->getPluralRuleTypes();
4644 if ( isset( $pluralRuleTypes[$index] ) ) {
4645 return $pluralRuleTypes[$index];
4646 } else {
4647 return 'other';
4648 }
4649 }
4650 }