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