dd2fef6cb4e9f3dc7b86415bc43ef8a931effc49
[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 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 * @param $number string
3012 * @return string
3013 */
3014 function parseFormattedNumber( $number ) {
3015 $s = $this->digitTransformTable();
3016 if ( $s ) {
3017 $number = strtr( $number, array_flip( $s ) );
3018 }
3019
3020 $s = $this->separatorTransformTable();
3021 if ( $s ) {
3022 $number = strtr( $number, array_flip( $s ) );
3023 }
3024
3025 $number = strtr( $number, array( ',' => '' ) );
3026 return $number;
3027 }
3028
3029 /**
3030 * Adds commas to a given number
3031 * @since 1.19
3032 * @param $number mixed
3033 * @return string
3034 */
3035 function commafy( $number ) {
3036 $digitGroupingPattern = $this->digitGroupingPattern();
3037 if ( $number === null ) {
3038 return '';
3039 }
3040
3041 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3042 // default grouping is at thousands, use the same for ###,###,### pattern too.
3043 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3044 } else {
3045 // Ref: http://cldr.unicode.org/translation/number-patterns
3046 $sign = "";
3047 if ( intval( $number ) < 0 ) {
3048 // For negative numbers apply the algorithm like positive number and add sign.
3049 $sign = "-";
3050 $number = substr( $number, 1 );
3051 }
3052 $integerPart = array();
3053 $decimalPart = array();
3054 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3055 preg_match( "/\d+/", $number, $integerPart );
3056 preg_match( "/\.\d*/", $number, $decimalPart );
3057 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0]:"";
3058 if ( $groupedNumber === $number ) {
3059 // the string does not have any number part. Eg: .12345
3060 return $sign . $groupedNumber;
3061 }
3062 $start = $end = strlen( $integerPart[0] );
3063 while ( $start > 0 ) {
3064 $match = $matches[0][$numMatches -1] ;
3065 $matchLen = strlen( $match );
3066 $start = $end - $matchLen;
3067 if ( $start < 0 ) {
3068 $start = 0;
3069 }
3070 $groupedNumber = substr( $number , $start, $end -$start ) . $groupedNumber ;
3071 $end = $start;
3072 if ( $numMatches > 1 ) {
3073 // use the last pattern for the rest of the number
3074 $numMatches--;
3075 }
3076 if ( $start > 0 ) {
3077 $groupedNumber = "," . $groupedNumber;
3078 }
3079 }
3080 return $sign . $groupedNumber;
3081 }
3082 }
3083
3084 /**
3085 * @return String
3086 */
3087 function digitGroupingPattern() {
3088 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3089 }
3090
3091 /**
3092 * @return array
3093 */
3094 function digitTransformTable() {
3095 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3096 }
3097
3098 /**
3099 * @return array
3100 */
3101 function separatorTransformTable() {
3102 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3103 }
3104
3105 /**
3106 * Take a list of strings and build a locale-friendly comma-separated
3107 * list, using the local comma-separator message.
3108 * The last two strings are chained with an "and".
3109 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3110 *
3111 * @param $l Array
3112 * @return string
3113 */
3114 function listToText( array $l ) {
3115 $m = count( $l ) - 1;
3116 if ( $m < 0 ) {
3117 return '';
3118 }
3119 if ( $m > 0 ) {
3120 $and = $this->getMessageFromDB( 'and' );
3121 $space = $this->getMessageFromDB( 'word-separator' );
3122 if ( $m > 1 ) {
3123 $comma = $this->getMessageFromDB( 'comma-separator' );
3124 }
3125 }
3126 $s = $l[$m];
3127 for ( $i = $m - 1; $i >= 0; $i-- ) {
3128 if ( $i == $m - 1 ) {
3129 $s = $l[$i] . $and . $space . $s;
3130 } else {
3131 $s = $l[$i] . $comma . $s;
3132 }
3133 }
3134 return $s;
3135 }
3136
3137 /**
3138 * Take a list of strings and build a locale-friendly comma-separated
3139 * list, using the local comma-separator message.
3140 * @param $list array of strings to put in a comma list
3141 * @return string
3142 */
3143 function commaList( array $list ) {
3144 return implode(
3145 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3146 $list
3147 );
3148 }
3149
3150 /**
3151 * Take a list of strings and build a locale-friendly semicolon-separated
3152 * list, using the local semicolon-separator message.
3153 * @param $list array of strings to put in a semicolon list
3154 * @return string
3155 */
3156 function semicolonList( array $list ) {
3157 return implode(
3158 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3159 $list
3160 );
3161 }
3162
3163 /**
3164 * Same as commaList, but separate it with the pipe instead.
3165 * @param $list array of strings to put in a pipe list
3166 * @return string
3167 */
3168 function pipeList( array $list ) {
3169 return implode(
3170 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3171 $list
3172 );
3173 }
3174
3175 /**
3176 * Truncate a string to a specified length in bytes, appending an optional
3177 * string (e.g. for ellipses)
3178 *
3179 * The database offers limited byte lengths for some columns in the database;
3180 * multi-byte character sets mean we need to ensure that only whole characters
3181 * are included, otherwise broken characters can be passed to the user
3182 *
3183 * If $length is negative, the string will be truncated from the beginning
3184 *
3185 * @param $string String to truncate
3186 * @param $length Int: maximum length (including ellipses)
3187 * @param $ellipsis String to append to the truncated text
3188 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3189 * $adjustLength was introduced in 1.18, before that behaved as if false.
3190 * @return string
3191 */
3192 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3193 # Use the localized ellipsis character
3194 if ( $ellipsis == '...' ) {
3195 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3196 }
3197 # Check if there is no need to truncate
3198 if ( $length == 0 ) {
3199 return $ellipsis; // convention
3200 } elseif ( strlen( $string ) <= abs( $length ) ) {
3201 return $string; // no need to truncate
3202 }
3203 $stringOriginal = $string;
3204 # If ellipsis length is >= $length then we can't apply $adjustLength
3205 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3206 $string = $ellipsis; // this can be slightly unexpected
3207 # Otherwise, truncate and add ellipsis...
3208 } else {
3209 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3210 if ( $length > 0 ) {
3211 $length -= $eLength;
3212 $string = substr( $string, 0, $length ); // xyz...
3213 $string = $this->removeBadCharLast( $string );
3214 $string = $string . $ellipsis;
3215 } else {
3216 $length += $eLength;
3217 $string = substr( $string, $length ); // ...xyz
3218 $string = $this->removeBadCharFirst( $string );
3219 $string = $ellipsis . $string;
3220 }
3221 }
3222 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3223 # This check is *not* redundant if $adjustLength, due to the single case where
3224 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3225 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3226 return $string;
3227 } else {
3228 return $stringOriginal;
3229 }
3230 }
3231
3232 /**
3233 * Remove bytes that represent an incomplete Unicode character
3234 * at the end of string (e.g. bytes of the char are missing)
3235 *
3236 * @param $string String
3237 * @return string
3238 */
3239 protected function removeBadCharLast( $string ) {
3240 if ( $string != '' ) {
3241 $char = ord( $string[strlen( $string ) - 1] );
3242 $m = array();
3243 if ( $char >= 0xc0 ) {
3244 # We got the first byte only of a multibyte char; remove it.
3245 $string = substr( $string, 0, -1 );
3246 } elseif ( $char >= 0x80 &&
3247 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3248 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3249 {
3250 # We chopped in the middle of a character; remove it
3251 $string = $m[1];
3252 }
3253 }
3254 return $string;
3255 }
3256
3257 /**
3258 * Remove bytes that represent an incomplete Unicode character
3259 * at the start of string (e.g. bytes of the char are missing)
3260 *
3261 * @param $string String
3262 * @return string
3263 */
3264 protected function removeBadCharFirst( $string ) {
3265 if ( $string != '' ) {
3266 $char = ord( $string[0] );
3267 if ( $char >= 0x80 && $char < 0xc0 ) {
3268 # We chopped in the middle of a character; remove the whole thing
3269 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3270 }
3271 }
3272 return $string;
3273 }
3274
3275 /**
3276 * Truncate a string of valid HTML to a specified length in bytes,
3277 * appending an optional string (e.g. for ellipses), and return valid HTML
3278 *
3279 * This is only intended for styled/linked text, such as HTML with
3280 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3281 * Also, this will not detect things like "display:none" CSS.
3282 *
3283 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3284 *
3285 * @param string $text HTML string to truncate
3286 * @param int $length (zero/positive) Maximum length (including ellipses)
3287 * @param string $ellipsis String to append to the truncated text
3288 * @return string
3289 */
3290 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3291 # Use the localized ellipsis character
3292 if ( $ellipsis == '...' ) {
3293 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3294 }
3295 # Check if there is clearly no need to truncate
3296 if ( $length <= 0 ) {
3297 return $ellipsis; // no text shown, nothing to format (convention)
3298 } elseif ( strlen( $text ) <= $length ) {
3299 return $text; // string short enough even *with* HTML (short-circuit)
3300 }
3301
3302 $dispLen = 0; // innerHTML legth so far
3303 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3304 $tagType = 0; // 0-open, 1-close
3305 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3306 $entityState = 0; // 0-not entity, 1-entity
3307 $tag = $ret = ''; // accumulated tag name, accumulated result string
3308 $openTags = array(); // open tag stack
3309 $maybeState = null; // possible truncation state
3310
3311 $textLen = strlen( $text );
3312 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3313 for ( $pos = 0; true; ++$pos ) {
3314 # Consider truncation once the display length has reached the maximim.
3315 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3316 # Check that we're not in the middle of a bracket/entity...
3317 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3318 if ( !$testingEllipsis ) {
3319 $testingEllipsis = true;
3320 # Save where we are; we will truncate here unless there turn out to
3321 # be so few remaining characters that truncation is not necessary.
3322 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3323 $maybeState = array( $ret, $openTags ); // save state
3324 }
3325 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3326 # String in fact does need truncation, the truncation point was OK.
3327 list( $ret, $openTags ) = $maybeState; // reload state
3328 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3329 $ret .= $ellipsis; // add ellipsis
3330 break;
3331 }
3332 }
3333 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3334
3335 # Read the next char...
3336 $ch = $text[$pos];
3337 $lastCh = $pos ? $text[$pos - 1] : '';
3338 $ret .= $ch; // add to result string
3339 if ( $ch == '<' ) {
3340 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3341 $entityState = 0; // for bad HTML
3342 $bracketState = 1; // tag started (checking for backslash)
3343 } elseif ( $ch == '>' ) {
3344 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3345 $entityState = 0; // for bad HTML
3346 $bracketState = 0; // out of brackets
3347 } elseif ( $bracketState == 1 ) {
3348 if ( $ch == '/' ) {
3349 $tagType = 1; // close tag (e.g. "</span>")
3350 } else {
3351 $tagType = 0; // open tag (e.g. "<span>")
3352 $tag .= $ch;
3353 }
3354 $bracketState = 2; // building tag name
3355 } elseif ( $bracketState == 2 ) {
3356 if ( $ch != ' ' ) {
3357 $tag .= $ch;
3358 } else {
3359 // Name found (e.g. "<a href=..."), add on tag attributes...
3360 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3361 }
3362 } elseif ( $bracketState == 0 ) {
3363 if ( $entityState ) {
3364 if ( $ch == ';' ) {
3365 $entityState = 0;
3366 $dispLen++; // entity is one displayed char
3367 }
3368 } else {
3369 if ( $neLength == 0 && !$maybeState ) {
3370 // Save state without $ch. We want to *hit* the first
3371 // display char (to get tags) but not *use* it if truncating.
3372 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3373 }
3374 if ( $ch == '&' ) {
3375 $entityState = 1; // entity found, (e.g. "&#160;")
3376 } else {
3377 $dispLen++; // this char is displayed
3378 // Add the next $max display text chars after this in one swoop...
3379 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3380 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3381 $dispLen += $skipped;
3382 $pos += $skipped;
3383 }
3384 }
3385 }
3386 }
3387 // Close the last tag if left unclosed by bad HTML
3388 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3389 while ( count( $openTags ) > 0 ) {
3390 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3391 }
3392 return $ret;
3393 }
3394
3395 /**
3396 * truncateHtml() helper function
3397 * like strcspn() but adds the skipped chars to $ret
3398 *
3399 * @param $ret
3400 * @param $text
3401 * @param $search
3402 * @param $start
3403 * @param $len
3404 * @return int
3405 */
3406 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3407 if ( $len === null ) {
3408 $len = -1; // -1 means "no limit" for strcspn
3409 } elseif ( $len < 0 ) {
3410 $len = 0; // sanity
3411 }
3412 $skipCount = 0;
3413 if ( $start < strlen( $text ) ) {
3414 $skipCount = strcspn( $text, $search, $start, $len );
3415 $ret .= substr( $text, $start, $skipCount );
3416 }
3417 return $skipCount;
3418 }
3419
3420 /**
3421 * truncateHtml() helper function
3422 * (a) push or pop $tag from $openTags as needed
3423 * (b) clear $tag value
3424 * @param &$tag string Current HTML tag name we are looking at
3425 * @param $tagType int (0-open tag, 1-close tag)
3426 * @param $lastCh string Character before the '>' that ended this tag
3427 * @param &$openTags array Open tag stack (not accounting for $tag)
3428 */
3429 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3430 $tag = ltrim( $tag );
3431 if ( $tag != '' ) {
3432 if ( $tagType == 0 && $lastCh != '/' ) {
3433 $openTags[] = $tag; // tag opened (didn't close itself)
3434 } elseif ( $tagType == 1 ) {
3435 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3436 array_pop( $openTags ); // tag closed
3437 }
3438 }
3439 $tag = '';
3440 }
3441 }
3442
3443 /**
3444 * Grammatical transformations, needed for inflected languages
3445 * Invoked by putting {{grammar:case|word}} in a message
3446 *
3447 * @param $word string
3448 * @param $case string
3449 * @return string
3450 */
3451 function convertGrammar( $word, $case ) {
3452 global $wgGrammarForms;
3453 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3454 return $wgGrammarForms[$this->getCode()][$case][$word];
3455 }
3456 return $word;
3457 }
3458 /**
3459 * Get the grammar forms for the content language
3460 * @return array of grammar forms
3461 * @since 1.20
3462 */
3463 function getGrammarForms() {
3464 global $wgGrammarForms;
3465 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3466 return $wgGrammarForms[$this->getCode()];
3467 }
3468 return array();
3469 }
3470 /**
3471 * Provides an alternative text depending on specified gender.
3472 * Usage {{gender:username|masculine|feminine|neutral}}.
3473 * username is optional, in which case the gender of current user is used,
3474 * but only in (some) interface messages; otherwise default gender is used.
3475 *
3476 * If no forms are given, an empty string is returned. If only one form is
3477 * given, it will be returned unconditionally. These details are implied by
3478 * the caller and cannot be overridden in subclasses.
3479 *
3480 * If more than one form is given, the default is to use the neutral one
3481 * if it is specified, and to use the masculine one otherwise. These
3482 * details can be overridden in subclasses.
3483 *
3484 * @param $gender string
3485 * @param $forms array
3486 *
3487 * @return string
3488 */
3489 function gender( $gender, $forms ) {
3490 if ( !count( $forms ) ) {
3491 return '';
3492 }
3493 $forms = $this->preConvertPlural( $forms, 2 );
3494 if ( $gender === 'male' ) {
3495 return $forms[0];
3496 }
3497 if ( $gender === 'female' ) {
3498 return $forms[1];
3499 }
3500 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3501 }
3502
3503 /**
3504 * Plural form transformations, needed for some languages.
3505 * For example, there are 3 form of plural in Russian and Polish,
3506 * depending on "count mod 10". See [[w:Plural]]
3507 * For English it is pretty simple.
3508 *
3509 * Invoked by putting {{plural:count|wordform1|wordform2}}
3510 * or {{plural:count|wordform1|wordform2|wordform3}}
3511 *
3512 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3513 *
3514 * @param $count Integer: non-localized number
3515 * @param $forms Array: different plural forms
3516 * @return string Correct form of plural for $count in this language
3517 */
3518 function convertPlural( $count, $forms ) {
3519 if ( !count( $forms ) ) {
3520 return '';
3521 }
3522
3523 // Handle explicit 0= and 1= forms
3524 foreach ( $forms as $index => $form ) {
3525 if ( isset( $form[1] ) && $form[1] === '=' ) {
3526 if ( $form[0] === (string) $count ) {
3527 return substr( $form, 2 );
3528 }
3529 unset( $forms[$index] );
3530 }
3531 }
3532 $forms = array_values( $forms );
3533
3534 $pluralForm = $this->getPluralForm( $count );
3535 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3536 return $forms[$pluralForm];
3537 }
3538
3539 /**
3540 * Checks that convertPlural was given an array and pads it to requested
3541 * amount of forms by copying the last one.
3542 *
3543 * @param $count Integer: How many forms should there be at least
3544 * @param $forms Array of forms given to convertPlural
3545 * @return array Padded array of forms or an exception if not an array
3546 */
3547 protected function preConvertPlural( /* Array */ $forms, $count ) {
3548 while ( count( $forms ) < $count ) {
3549 $forms[] = $forms[count( $forms ) - 1];
3550 }
3551 return $forms;
3552 }
3553
3554 /**
3555 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3556 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3557 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3558 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3559 * match up with it.
3560 *
3561 * @param $str String: the validated block duration in English
3562 * @return string Somehow translated block duration
3563 * @see LanguageFi.php for example implementation
3564 */
3565 function translateBlockExpiry( $str ) {
3566 $duration = SpecialBlock::getSuggestedDurations( $this );
3567 foreach ( $duration as $show => $value ) {
3568 if ( strcmp( $str, $value ) == 0 ) {
3569 return htmlspecialchars( trim( $show ) );
3570 }
3571 }
3572
3573 // Since usually only infinite or indefinite is only on list, so try
3574 // equivalents if still here.
3575 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3576 if ( in_array( $str, $indefs ) ) {
3577 foreach ( $indefs as $val ) {
3578 $show = array_search( $val, $duration, true );
3579 if ( $show !== false ) {
3580 return htmlspecialchars( trim( $show ) );
3581 }
3582 }
3583 }
3584
3585 // If all else fails, return a standard duration or timestamp description.
3586 $time = strtotime( $str, 0 );
3587 if ( $time === false ) { // Unknown format. Return it as-is in case.
3588 return $str;
3589 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3590 // $time is relative to 0 so it's a duration length.
3591 return $this->formatDuration( $time );
3592 } else { // It's an absolute timestamp.
3593 if ( $time === 0 ) {
3594 // wfTimestamp() handles 0 as current time instead of epoch.
3595 return $this->timeanddate( '19700101000000' );
3596 } else {
3597 return $this->timeanddate( $time );
3598 }
3599 }
3600 }
3601
3602 /**
3603 * languages like Chinese need to be segmented in order for the diff
3604 * to be of any use
3605 *
3606 * @param $text String
3607 * @return String
3608 */
3609 public function segmentForDiff( $text ) {
3610 return $text;
3611 }
3612
3613 /**
3614 * and unsegment to show the result
3615 *
3616 * @param $text String
3617 * @return String
3618 */
3619 public function unsegmentForDiff( $text ) {
3620 return $text;
3621 }
3622
3623 /**
3624 * Return the LanguageConverter used in the Language
3625 *
3626 * @since 1.19
3627 * @return LanguageConverter
3628 */
3629 public function getConverter() {
3630 return $this->mConverter;
3631 }
3632
3633 /**
3634 * convert text to all supported variants
3635 *
3636 * @param $text string
3637 * @return array
3638 */
3639 public function autoConvertToAllVariants( $text ) {
3640 return $this->mConverter->autoConvertToAllVariants( $text );
3641 }
3642
3643 /**
3644 * convert text to different variants of a language.
3645 *
3646 * @param $text string
3647 * @return string
3648 */
3649 public function convert( $text ) {
3650 return $this->mConverter->convert( $text );
3651 }
3652
3653 /**
3654 * Convert a Title object to a string in the preferred variant
3655 *
3656 * @param $title Title
3657 * @return string
3658 */
3659 public function convertTitle( $title ) {
3660 return $this->mConverter->convertTitle( $title );
3661 }
3662
3663 /**
3664 * Convert a namespace index to a string in the preferred variant
3665 *
3666 * @param $ns int
3667 * @return string
3668 */
3669 public function convertNamespace( $ns ) {
3670 return $this->mConverter->convertNamespace( $ns );
3671 }
3672
3673 /**
3674 * Check if this is a language with variants
3675 *
3676 * @return bool
3677 */
3678 public function hasVariants() {
3679 return count( $this->getVariants() ) > 1;
3680 }
3681
3682 /**
3683 * Check if the language has the specific variant
3684 *
3685 * @since 1.19
3686 * @param $variant string
3687 * @return bool
3688 */
3689 public function hasVariant( $variant ) {
3690 return (bool)$this->mConverter->validateVariant( $variant );
3691 }
3692
3693 /**
3694 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3695 *
3696 * @param $text string
3697 * @return string
3698 */
3699 public function armourMath( $text ) {
3700 return $this->mConverter->armourMath( $text );
3701 }
3702
3703 /**
3704 * Perform output conversion on a string, and encode for safe HTML output.
3705 * @param $text String text to be converted
3706 * @param $isTitle Bool whether this conversion is for the article title
3707 * @return string
3708 * @todo this should get integrated somewhere sane
3709 */
3710 public function convertHtml( $text, $isTitle = false ) {
3711 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3712 }
3713
3714 /**
3715 * @param $key string
3716 * @return string
3717 */
3718 public function convertCategoryKey( $key ) {
3719 return $this->mConverter->convertCategoryKey( $key );
3720 }
3721
3722 /**
3723 * Get the list of variants supported by this language
3724 * see sample implementation in LanguageZh.php
3725 *
3726 * @return array an array of language codes
3727 */
3728 public function getVariants() {
3729 return $this->mConverter->getVariants();
3730 }
3731
3732 /**
3733 * @return string
3734 */
3735 public function getPreferredVariant() {
3736 return $this->mConverter->getPreferredVariant();
3737 }
3738
3739 /**
3740 * @return string
3741 */
3742 public function getDefaultVariant() {
3743 return $this->mConverter->getDefaultVariant();
3744 }
3745
3746 /**
3747 * @return string
3748 */
3749 public function getURLVariant() {
3750 return $this->mConverter->getURLVariant();
3751 }
3752
3753 /**
3754 * If a language supports multiple variants, it is
3755 * possible that non-existing link in one variant
3756 * actually exists in another variant. this function
3757 * tries to find it. See e.g. LanguageZh.php
3758 *
3759 * @param $link String: the name of the link
3760 * @param $nt Mixed: the title object of the link
3761 * @param $ignoreOtherCond Boolean: to disable other conditions when
3762 * we need to transclude a template or update a category's link
3763 * @return null the input parameters may be modified upon return
3764 */
3765 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3766 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3767 }
3768
3769 /**
3770 * If a language supports multiple variants, converts text
3771 * into an array of all possible variants of the text:
3772 * 'variant' => text in that variant
3773 *
3774 * @deprecated since 1.17 Use autoConvertToAllVariants()
3775 *
3776 * @param $text string
3777 *
3778 * @return string
3779 */
3780 public function convertLinkToAllVariants( $text ) {
3781 return $this->mConverter->convertLinkToAllVariants( $text );
3782 }
3783
3784 /**
3785 * returns language specific options used by User::getPageRenderHash()
3786 * for example, the preferred language variant
3787 *
3788 * @return string
3789 */
3790 function getExtraHashOptions() {
3791 return $this->mConverter->getExtraHashOptions();
3792 }
3793
3794 /**
3795 * For languages that support multiple variants, the title of an
3796 * article may be displayed differently in different variants. this
3797 * function returns the apporiate title defined in the body of the article.
3798 *
3799 * @return string
3800 */
3801 public function getParsedTitle() {
3802 return $this->mConverter->getParsedTitle();
3803 }
3804
3805 /**
3806 * Prepare external link text for conversion. When the text is
3807 * a URL, it shouldn't be converted, and it'll be wrapped in
3808 * the "raw" tag (-{R| }-) to prevent conversion.
3809 *
3810 * This function is called "markNoConversion" for historical
3811 * reasons.
3812 *
3813 * @param $text String: text to be used for external link
3814 * @param $noParse bool: wrap it without confirming it's a real URL first
3815 * @return string the tagged text
3816 */
3817 public function markNoConversion( $text, $noParse = false ) {
3818 // Excluding protocal-relative URLs may avoid many false positives.
3819 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3820 return $this->mConverter->markNoConversion( $text );
3821 } else {
3822 return $text;
3823 }
3824 }
3825
3826 /**
3827 * A regular expression to match legal word-trailing characters
3828 * which should be merged onto a link of the form [[foo]]bar.
3829 *
3830 * @return string
3831 */
3832 public function linkTrail() {
3833 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3834 }
3835
3836 /**
3837 * @return Language
3838 */
3839 function getLangObj() {
3840 return $this;
3841 }
3842
3843 /**
3844 * Get the RFC 3066 code for this language object
3845 *
3846 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3847 * htmlspecialchars() or similar
3848 *
3849 * @return string
3850 */
3851 public function getCode() {
3852 return $this->mCode;
3853 }
3854
3855 /**
3856 * Get the code in Bcp47 format which we can use
3857 * inside of html lang="" tags.
3858 *
3859 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3860 * htmlspecialchars() or similar.
3861 *
3862 * @since 1.19
3863 * @return string
3864 */
3865 public function getHtmlCode() {
3866 if ( is_null( $this->mHtmlCode ) ) {
3867 $this->mHtmlCode = wfBCP47( $this->getCode() );
3868 }
3869 return $this->mHtmlCode;
3870 }
3871
3872 /**
3873 * @param $code string
3874 */
3875 public function setCode( $code ) {
3876 $this->mCode = $code;
3877 // Ensure we don't leave an incorrect html code lying around
3878 $this->mHtmlCode = null;
3879 }
3880
3881 /**
3882 * Get the name of a file for a certain language code
3883 * @param $prefix string Prepend this to the filename
3884 * @param $code string Language code
3885 * @param $suffix string Append this to the filename
3886 * @throws MWException
3887 * @return string $prefix . $mangledCode . $suffix
3888 */
3889 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3890 // Protect against path traversal
3891 if ( !Language::isValidCode( $code )
3892 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3893 {
3894 throw new MWException( "Invalid language code \"$code\"" );
3895 }
3896
3897 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3898 }
3899
3900 /**
3901 * Get the language code from a file name. Inverse of getFileName()
3902 * @param $filename string $prefix . $languageCode . $suffix
3903 * @param $prefix string Prefix before the language code
3904 * @param $suffix string Suffix after the language code
3905 * @return string Language code, or false if $prefix or $suffix isn't found
3906 */
3907 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3908 $m = null;
3909 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3910 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3911 if ( !count( $m ) ) {
3912 return false;
3913 }
3914 return str_replace( '_', '-', strtolower( $m[1] ) );
3915 }
3916
3917 /**
3918 * @param $code string
3919 * @return string
3920 */
3921 public static function getMessagesFileName( $code ) {
3922 global $IP;
3923 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3924 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3925 return $file;
3926 }
3927
3928 /**
3929 * @param $code string
3930 * @return string
3931 */
3932 public static function getClassFileName( $code ) {
3933 global $IP;
3934 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3935 }
3936
3937 /**
3938 * Get the first fallback for a given language.
3939 *
3940 * @param $code string
3941 *
3942 * @return bool|string
3943 */
3944 public static function getFallbackFor( $code ) {
3945 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3946 return false;
3947 } else {
3948 $fallbacks = self::getFallbacksFor( $code );
3949 $first = array_shift( $fallbacks );
3950 return $first;
3951 }
3952 }
3953
3954 /**
3955 * Get the ordered list of fallback languages.
3956 *
3957 * @since 1.19
3958 * @param $code string Language code
3959 * @return array
3960 */
3961 public static function getFallbacksFor( $code ) {
3962 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3963 return array();
3964 } else {
3965 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3966 $v = array_map( 'trim', explode( ',', $v ) );
3967 if ( $v[count( $v ) - 1] !== 'en' ) {
3968 $v[] = 'en';
3969 }
3970 return $v;
3971 }
3972 }
3973
3974 /**
3975 * Get all messages for a given language
3976 * WARNING: this may take a long time. If you just need all message *keys*
3977 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3978 *
3979 * @param $code string
3980 *
3981 * @return array
3982 */
3983 public static function getMessagesFor( $code ) {
3984 return self::getLocalisationCache()->getItem( $code, 'messages' );
3985 }
3986
3987 /**
3988 * Get a message for a given language
3989 *
3990 * @param $key string
3991 * @param $code string
3992 *
3993 * @return string
3994 */
3995 public static function getMessageFor( $key, $code ) {
3996 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3997 }
3998
3999 /**
4000 * Get all message keys for a given language. This is a faster alternative to
4001 * array_keys( Language::getMessagesFor( $code ) )
4002 *
4003 * @since 1.19
4004 * @param $code string Language code
4005 * @return array of message keys (strings)
4006 */
4007 public static function getMessageKeysFor( $code ) {
4008 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4009 }
4010
4011 /**
4012 * @param $talk
4013 * @return mixed
4014 */
4015 function fixVariableInNamespace( $talk ) {
4016 if ( strpos( $talk, '$1' ) === false ) {
4017 return $talk;
4018 }
4019
4020 global $wgMetaNamespace;
4021 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4022
4023 # Allow grammar transformations
4024 # Allowing full message-style parsing would make simple requests
4025 # such as action=raw much more expensive than they need to be.
4026 # This will hopefully cover most cases.
4027 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4028 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4029 return str_replace( ' ', '_', $talk );
4030 }
4031
4032 /**
4033 * @param $m string
4034 * @return string
4035 */
4036 function replaceGrammarInNamespace( $m ) {
4037 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4038 }
4039
4040 /**
4041 * @throws MWException
4042 * @return array
4043 */
4044 static function getCaseMaps() {
4045 static $wikiUpperChars, $wikiLowerChars;
4046 if ( isset( $wikiUpperChars ) ) {
4047 return array( $wikiUpperChars, $wikiLowerChars );
4048 }
4049
4050 wfProfileIn( __METHOD__ );
4051 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4052 if ( $arr === false ) {
4053 throw new MWException(
4054 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4055 }
4056 $wikiUpperChars = $arr['wikiUpperChars'];
4057 $wikiLowerChars = $arr['wikiLowerChars'];
4058 wfProfileOut( __METHOD__ );
4059 return array( $wikiUpperChars, $wikiLowerChars );
4060 }
4061
4062 /**
4063 * Decode an expiry (block, protection, etc) which has come from the DB
4064 *
4065 * @todo FIXME: why are we returnings DBMS-dependent strings???
4066 *
4067 * @param $expiry String: Database expiry String
4068 * @param $format Bool|Int true to process using language functions, or TS_ constant
4069 * to return the expiry in a given timestamp
4070 * @return String
4071 * @since 1.18
4072 */
4073 public function formatExpiry( $expiry, $format = true ) {
4074 static $infinity, $infinityMsg;
4075 if ( $infinity === null ) {
4076 $infinityMsg = wfMessage( 'infiniteblock' );
4077 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4078 }
4079
4080 if ( $expiry == '' || $expiry == $infinity ) {
4081 return $format === true
4082 ? $infinityMsg
4083 : $infinity;
4084 } else {
4085 return $format === true
4086 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4087 : wfTimestamp( $format, $expiry );
4088 }
4089 }
4090
4091 /**
4092 * @todo Document
4093 * @param $seconds int|float
4094 * @param $format Array Optional
4095 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4096 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4097 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4098 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4099 * @return string
4100 */
4101 function formatTimePeriod( $seconds, $format = array() ) {
4102 if ( !is_array( $format ) ) {
4103 $format = array( 'avoid' => $format ); // For backwards compatibility
4104 }
4105 if ( !isset( $format['avoid'] ) ) {
4106 $format['avoid'] = false;
4107 }
4108 if ( !isset( $format['noabbrevs' ] ) ) {
4109 $format['noabbrevs'] = false;
4110 }
4111 $secondsMsg = wfMessage(
4112 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4113 $minutesMsg = wfMessage(
4114 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4115 $hoursMsg = wfMessage(
4116 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4117 $daysMsg = wfMessage(
4118 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4119
4120 if ( round( $seconds * 10 ) < 100 ) {
4121 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4122 $s = $secondsMsg->params( $s )->text();
4123 } elseif ( round( $seconds ) < 60 ) {
4124 $s = $this->formatNum( round( $seconds ) );
4125 $s = $secondsMsg->params( $s )->text();
4126 } elseif ( round( $seconds ) < 3600 ) {
4127 $minutes = floor( $seconds / 60 );
4128 $secondsPart = round( fmod( $seconds, 60 ) );
4129 if ( $secondsPart == 60 ) {
4130 $secondsPart = 0;
4131 $minutes++;
4132 }
4133 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4134 $s .= ' ';
4135 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4136 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4137 $hours = floor( $seconds / 3600 );
4138 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4139 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4140 if ( $secondsPart == 60 ) {
4141 $secondsPart = 0;
4142 $minutes++;
4143 }
4144 if ( $minutes == 60 ) {
4145 $minutes = 0;
4146 $hours++;
4147 }
4148 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4149 $s .= ' ';
4150 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4151 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4152 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4153 }
4154 } else {
4155 $days = floor( $seconds / 86400 );
4156 if ( $format['avoid'] === 'avoidminutes' ) {
4157 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4158 if ( $hours == 24 ) {
4159 $hours = 0;
4160 $days++;
4161 }
4162 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4163 $s .= ' ';
4164 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4165 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4166 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4167 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4168 if ( $minutes == 60 ) {
4169 $minutes = 0;
4170 $hours++;
4171 }
4172 if ( $hours == 24 ) {
4173 $hours = 0;
4174 $days++;
4175 }
4176 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4177 $s .= ' ';
4178 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4179 $s .= ' ';
4180 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4181 } else {
4182 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4183 $s .= ' ';
4184 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4185 }
4186 }
4187 return $s;
4188 }
4189
4190 /**
4191 * Format a bitrate for output, using an appropriate
4192 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4193 *
4194 * This use base 1000. For base 1024 use formatSize(), for another base
4195 * see formatComputingNumbers()
4196 *
4197 * @param $bps int
4198 * @return string
4199 */
4200 function formatBitrate( $bps ) {
4201 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4202 }
4203
4204 /**
4205 * @param $size int Size of the unit
4206 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4207 * @param $messageKey string Message key to be uesd
4208 * @return string
4209 */
4210 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4211 if ( $size <= 0 ) {
4212 return str_replace( '$1', $this->formatNum( $size ),
4213 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4214 );
4215 }
4216 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4217 $index = 0;
4218
4219 $maxIndex = count( $sizes ) - 1;
4220 while ( $size >= $boundary && $index < $maxIndex ) {
4221 $index++;
4222 $size /= $boundary;
4223 }
4224
4225 // For small sizes no decimal places necessary
4226 $round = 0;
4227 if ( $index > 1 ) {
4228 // For MB and bigger two decimal places are smarter
4229 $round = 2;
4230 }
4231 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4232
4233 $size = round( $size, $round );
4234 $text = $this->getMessageFromDB( $msg );
4235 return str_replace( '$1', $this->formatNum( $size ), $text );
4236 }
4237
4238 /**
4239 * Format a size in bytes for output, using an appropriate
4240 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4241 *
4242 * This method use base 1024. For base 1000 use formatBitrate(), for
4243 * another base see formatComputingNumbers()
4244 *
4245 * @param $size int Size to format
4246 * @return string Plain text (not HTML)
4247 */
4248 function formatSize( $size ) {
4249 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4250 }
4251
4252 /**
4253 * Make a list item, used by various special pages
4254 *
4255 * @param $page String Page link
4256 * @param $details String Text between brackets
4257 * @param $oppositedm Boolean Add the direction mark opposite to your
4258 * language, to display text properly
4259 * @return String
4260 */
4261 function specialList( $page, $details, $oppositedm = true ) {
4262 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4263 $this->getDirMark();
4264 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4265 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4266 return $page . $details;
4267 }
4268
4269 /**
4270 * Generate (prev x| next x) (20|50|100...) type links for paging
4271 *
4272 * @param $title Title object to link
4273 * @param $offset Integer offset parameter
4274 * @param $limit Integer limit parameter
4275 * @param $query array|String optional URL query parameter string
4276 * @param $atend Bool optional param for specified if this is the last page
4277 * @return String
4278 */
4279 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4280 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4281
4282 # Make 'previous' link
4283 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4284 if ( $offset > 0 ) {
4285 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4286 $query, $prev, 'prevn-title', 'mw-prevlink' );
4287 } else {
4288 $plink = htmlspecialchars( $prev );
4289 }
4290
4291 # Make 'next' link
4292 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4293 if ( $atend ) {
4294 $nlink = htmlspecialchars( $next );
4295 } else {
4296 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4297 $query, $next, 'prevn-title', 'mw-nextlink' );
4298 }
4299
4300 # Make links to set number of items per page
4301 $numLinks = array();
4302 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4303 $numLinks[] = $this->numLink( $title, $offset, $num,
4304 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4305 }
4306
4307 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4308 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4309 }
4310
4311 /**
4312 * Helper function for viewPrevNext() that generates links
4313 *
4314 * @param $title Title object to link
4315 * @param $offset Integer offset parameter
4316 * @param $limit Integer limit parameter
4317 * @param $query Array extra query parameters
4318 * @param $link String text to use for the link; will be escaped
4319 * @param $tooltipMsg String name of the message to use as tooltip
4320 * @param $class String value of the "class" attribute of the link
4321 * @return String HTML fragment
4322 */
4323 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4324 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4325 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4326 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4327 'title' => $tooltip, 'class' => $class ), $link );
4328 }
4329
4330 /**
4331 * Get the conversion rule title, if any.
4332 *
4333 * @return string
4334 */
4335 public function getConvRuleTitle() {
4336 return $this->mConverter->getConvRuleTitle();
4337 }
4338
4339 /**
4340 * Get the compiled plural rules for the language
4341 * @since 1.20
4342 * @return array Associative array with plural form, and plural rule as key-value pairs
4343 */
4344 public function getCompiledPluralRules() {
4345 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4346 $fallbacks = Language::getFallbacksFor( $this->mCode );
4347 if ( !$pluralRules ) {
4348 foreach ( $fallbacks as $fallbackCode ) {
4349 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4350 if ( $pluralRules ) {
4351 break;
4352 }
4353 }
4354 }
4355 return $pluralRules;
4356 }
4357
4358 /**
4359 * Get the plural rules for the language
4360 * @since 1.20
4361 * @return array Associative array with plural form, and plural rule as key-value pairs
4362 */
4363 public function getPluralRules() {
4364 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4365 $fallbacks = Language::getFallbacksFor( $this->mCode );
4366 if ( !$pluralRules ) {
4367 foreach ( $fallbacks as $fallbackCode ) {
4368 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4369 if ( $pluralRules ) {
4370 break;
4371 }
4372 }
4373 }
4374 return $pluralRules;
4375 }
4376
4377 /**
4378 * Find the plural form matching to the given number
4379 * It return the form index.
4380 * @return int The index of the plural form
4381 */
4382 private function getPluralForm( $number ) {
4383 $pluralRules = $this->getCompiledPluralRules();
4384 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4385 return $form;
4386 }
4387 }