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