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