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