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