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