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