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