Merge "Let tablesUsed imply needsDB in MediaWikiTestCase."
[mediawiki.git] / languages / Language.php
blobe6feb45edf10375b82ab67d52d17482051628734
1 <?php
2 /**
3 * Internationalisation code
5 * @file
6 * @ingroup Language
7 */
9 /**
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
26 /**
27 * a fake language converter
29 * @ingroup Language
31 class FakeConverter {
33 /**
34 * @var Language
36 var $mLang;
37 function __construct( $langobj ) { $this->mLang = $langobj; }
38 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
39 function convert( $t ) { return $t; }
40 function convertTo( $text, $variant ) { return $text; }
41 function convertTitle( $t ) { return $t->getPrefixedText(); }
42 function getVariants() { return array( $this->mLang->getCode() ); }
43 function getPreferredVariant() { return $this->mLang->getCode(); }
44 function getDefaultVariant() { return $this->mLang->getCode(); }
45 function getURLVariant() { return ''; }
46 function getConvRuleTitle() { return false; }
47 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
48 function getExtraHashOptions() { return ''; }
49 function getParsedTitle() { return ''; }
50 function markNoConversion( $text, $noParse = false ) { return $text; }
51 function convertCategoryKey( $key ) { return $key; }
52 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
53 function armourMath( $text ) { return $text; }
56 /**
57 * Internationalisation code
58 * @ingroup Language
60 class Language {
62 /**
63 * @var LanguageConverter
65 var $mConverter;
67 var $mVariants, $mCode, $mLoaded = false;
68 var $mMagicExtensions = array(), $mMagicHookDone = false;
69 private $mHtmlCode = null;
71 var $dateFormatStrings = array();
72 var $mExtendedSpecialPageAliases;
74 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
76 /**
77 * ReplacementArray object caches
79 var $transformData = array();
81 /**
82 * @var LocalisationCache
84 static public $dataCache;
86 static public $mLangObjCache = array();
88 static public $mWeekdayMsgs = array(
89 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
90 'friday', 'saturday'
93 static public $mWeekdayAbbrevMsgs = array(
94 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
97 static public $mMonthMsgs = array(
98 'january', 'february', 'march', 'april', 'may_long', 'june',
99 'july', 'august', 'september', 'october', 'november',
100 'december'
102 static public $mMonthGenMsgs = array(
103 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
104 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
105 'december-gen'
107 static public $mMonthAbbrevMsgs = array(
108 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
109 'sep', 'oct', 'nov', 'dec'
112 static public $mIranianCalendarMonthMsgs = array(
113 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
114 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
115 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
116 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
119 static public $mHebrewCalendarMonthMsgs = array(
120 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
121 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
122 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
123 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
124 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
127 static public $mHebrewCalendarMonthGenMsgs = array(
128 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
129 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
130 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
131 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
132 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
135 static public $mHijriCalendarMonthMsgs = array(
136 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
137 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
138 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
139 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
143 * @since 1.20
144 * @var array
146 static public $durationIntervals = array(
147 'millennia' => 31557600000,
148 'centuries' => 3155760000,
149 'decades' => 315576000,
150 'years' => 31557600, // 86400 * 365.25
151 'weeks' => 604800,
152 'days' => 86400,
153 'hours' => 3600,
154 'minutes' => 60,
155 'seconds' => 1,
159 * Get a cached language object for a given language code
160 * @param $code String
161 * @return Language
163 static function factory( $code ) {
164 if ( !isset( self::$mLangObjCache[$code] ) ) {
165 if ( count( self::$mLangObjCache ) > 10 ) {
166 // Don't keep a billion objects around, that's stupid.
167 self::$mLangObjCache = array();
169 self::$mLangObjCache[$code] = self::newFromCode( $code );
171 return self::$mLangObjCache[$code];
175 * Create a language object for a given language code
176 * @param $code String
177 * @throws MWException
178 * @return Language
180 protected static function newFromCode( $code ) {
181 // Protect against path traversal below
182 if ( !Language::isValidCode( $code )
183 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
185 throw new MWException( "Invalid language code \"$code\"" );
188 if ( !Language::isValidBuiltInCode( $code ) ) {
189 // It's not possible to customise this code with class files, so
190 // just return a Language object. This is to support uselang= hacks.
191 $lang = new Language;
192 $lang->setCode( $code );
193 return $lang;
196 // Check if there is a language class for the code
197 $class = self::classFromCode( $code );
198 self::preloadLanguageClass( $class );
199 if ( MWInit::classExists( $class ) ) {
200 $lang = new $class;
201 return $lang;
204 // Keep trying the fallback list until we find an existing class
205 $fallbacks = Language::getFallbacksFor( $code );
206 foreach ( $fallbacks as $fallbackCode ) {
207 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
208 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
211 $class = self::classFromCode( $fallbackCode );
212 self::preloadLanguageClass( $class );
213 if ( MWInit::classExists( $class ) ) {
214 $lang = Language::newFromCode( $fallbackCode );
215 $lang->setCode( $code );
216 return $lang;
220 throw new MWException( "Invalid fallback sequence for language '$code'" );
224 * Returns true if a language code string is of a valid form, whether or
225 * not it exists. This includes codes which are used solely for
226 * customisation via the MediaWiki namespace.
228 * @param $code string
230 * @return bool
232 public static function isValidCode( $code ) {
233 return
234 strcspn( $code, ":/\\\000" ) === strlen( $code )
235 && !preg_match( Title::getTitleInvalidRegex(), $code );
239 * Returns true if a language code is of a valid form for the purposes of
240 * internal customisation of MediaWiki, via Messages*.php.
242 * @param $code string
244 * @since 1.18
245 * @return bool
247 public static function isValidBuiltInCode( $code ) {
248 return preg_match( '/^[a-z0-9-]+$/i', $code );
252 * @param $code
253 * @return String Name of the language class
255 public static function classFromCode( $code ) {
256 if ( $code == 'en' ) {
257 return 'Language';
258 } else {
259 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
264 * Includes language class files
266 * @param $class string Name of the language class
268 public static function preloadLanguageClass( $class ) {
269 global $IP;
271 if ( $class === 'Language' ) {
272 return;
275 if ( !defined( 'MW_COMPILED' ) ) {
276 // Preload base classes to work around APC/PHP5 bug
277 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
278 include_once( "$IP/languages/classes/$class.deps.php" );
280 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
281 include_once( "$IP/languages/classes/$class.php" );
287 * Get the LocalisationCache instance
289 * @return LocalisationCache
291 public static function getLocalisationCache() {
292 if ( is_null( self::$dataCache ) ) {
293 global $wgLocalisationCacheConf;
294 $class = $wgLocalisationCacheConf['class'];
295 self::$dataCache = new $class( $wgLocalisationCacheConf );
297 return self::$dataCache;
300 function __construct() {
301 $this->mConverter = new FakeConverter( $this );
302 // Set the code to the name of the descendant
303 if ( get_class( $this ) == 'Language' ) {
304 $this->mCode = 'en';
305 } else {
306 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
308 self::getLocalisationCache();
312 * Reduce memory usage
314 function __destruct() {
315 foreach ( $this as $name => $value ) {
316 unset( $this->$name );
321 * Hook which will be called if this is the content language.
322 * Descendants can use this to register hook functions or modify globals
324 function initContLang() { }
327 * Same as getFallbacksFor for current language.
328 * @return array|bool
329 * @deprecated in 1.19
331 function getFallbackLanguageCode() {
332 wfDeprecated( __METHOD__ );
333 return self::getFallbackFor( $this->mCode );
337 * @return array
338 * @since 1.19
340 function getFallbackLanguages() {
341 return self::getFallbacksFor( $this->mCode );
345 * Exports $wgBookstoreListEn
346 * @return array
348 function getBookstoreList() {
349 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
353 * @return array
355 public function getNamespaces() {
356 if ( is_null( $this->namespaceNames ) ) {
357 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
359 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
360 $validNamespaces = MWNamespace::getCanonicalNamespaces();
362 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
364 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
365 if ( $wgMetaNamespaceTalk ) {
366 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
367 } else {
368 $talk = $this->namespaceNames[NS_PROJECT_TALK];
369 $this->namespaceNames[NS_PROJECT_TALK] =
370 $this->fixVariableInNamespace( $talk );
373 # Sometimes a language will be localised but not actually exist on this wiki.
374 foreach ( $this->namespaceNames as $key => $text ) {
375 if ( !isset( $validNamespaces[$key] ) ) {
376 unset( $this->namespaceNames[$key] );
380 # The above mixing may leave namespaces out of canonical order.
381 # Re-order by namespace ID number...
382 ksort( $this->namespaceNames );
384 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
386 return $this->namespaceNames;
390 * Arbitrarily set all of the namespace names at once. Mainly used for testing
391 * @param $namespaces Array of namespaces (id => name)
393 public function setNamespaces( array $namespaces ) {
394 $this->namespaceNames = $namespaces;
398 * A convenience function that returns the same thing as
399 * getNamespaces() except with the array values changed to ' '
400 * where it found '_', useful for producing output to be displayed
401 * e.g. in <select> forms.
403 * @return array
405 function getFormattedNamespaces() {
406 $ns = $this->getNamespaces();
407 foreach ( $ns as $k => $v ) {
408 $ns[$k] = strtr( $v, '_', ' ' );
410 return $ns;
414 * Get a namespace value by key
415 * <code>
416 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
417 * echo $mw_ns; // prints 'MediaWiki'
418 * </code>
420 * @param $index Int: the array key of the namespace to return
421 * @return mixed, string if the namespace value exists, otherwise false
423 function getNsText( $index ) {
424 $ns = $this->getNamespaces();
425 return isset( $ns[$index] ) ? $ns[$index] : false;
429 * A convenience function that returns the same thing as
430 * getNsText() except with '_' changed to ' ', useful for
431 * producing output.
433 * @param $index string
435 * @return array
437 function getFormattedNsText( $index ) {
438 $ns = $this->getNsText( $index );
439 return strtr( $ns, '_', ' ' );
443 * Returns gender-dependent namespace alias if available.
444 * @param $index Int: namespace index
445 * @param $gender String: gender key (male, female... )
446 * @return String
447 * @since 1.18
449 function getGenderNsText( $index, $gender ) {
450 global $wgExtraGenderNamespaces;
452 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
453 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
457 * Whether this language makes distinguishes genders for example in
458 * namespaces.
459 * @return bool
460 * @since 1.18
462 function needsGenderDistinction() {
463 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
464 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
465 // $wgExtraGenderNamespaces overrides everything
466 return true;
467 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
468 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
469 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
470 return false;
471 } else {
472 // Check what is in i18n files
473 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
474 return count( $aliases ) > 0;
479 * Get a namespace key by value, case insensitive.
480 * Only matches namespace names for the current language, not the
481 * canonical ones defined in Namespace.php.
483 * @param $text String
484 * @return mixed An integer if $text is a valid value otherwise false
486 function getLocalNsIndex( $text ) {
487 $lctext = $this->lc( $text );
488 $ids = $this->getNamespaceIds();
489 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
493 * @return array
495 function getNamespaceAliases() {
496 if ( is_null( $this->namespaceAliases ) ) {
497 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
498 if ( !$aliases ) {
499 $aliases = array();
500 } else {
501 foreach ( $aliases as $name => $index ) {
502 if ( $index === NS_PROJECT_TALK ) {
503 unset( $aliases[$name] );
504 $name = $this->fixVariableInNamespace( $name );
505 $aliases[$name] = $index;
510 global $wgExtraGenderNamespaces;
511 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
512 foreach ( $genders as $index => $forms ) {
513 foreach ( $forms as $alias ) {
514 $aliases[$alias] = $index;
518 $this->namespaceAliases = $aliases;
520 return $this->namespaceAliases;
524 * @return array
526 function getNamespaceIds() {
527 if ( is_null( $this->mNamespaceIds ) ) {
528 global $wgNamespaceAliases;
529 # Put namespace names and aliases into a hashtable.
530 # If this is too slow, then we should arrange it so that it is done
531 # before caching. The catch is that at pre-cache time, the above
532 # class-specific fixup hasn't been done.
533 $this->mNamespaceIds = array();
534 foreach ( $this->getNamespaces() as $index => $name ) {
535 $this->mNamespaceIds[$this->lc( $name )] = $index;
537 foreach ( $this->getNamespaceAliases() as $name => $index ) {
538 $this->mNamespaceIds[$this->lc( $name )] = $index;
540 if ( $wgNamespaceAliases ) {
541 foreach ( $wgNamespaceAliases as $name => $index ) {
542 $this->mNamespaceIds[$this->lc( $name )] = $index;
546 return $this->mNamespaceIds;
550 * Get a namespace key by value, case insensitive. Canonical namespace
551 * names override custom ones defined for the current language.
553 * @param $text String
554 * @return mixed An integer if $text is a valid value otherwise false
556 function getNsIndex( $text ) {
557 $lctext = $this->lc( $text );
558 $ns = MWNamespace::getCanonicalIndex( $lctext );
559 if ( $ns !== null ) {
560 return $ns;
562 $ids = $this->getNamespaceIds();
563 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
567 * short names for language variants used for language conversion links.
569 * @param $code String
570 * @param $usemsg bool Use the "variantname-xyz" message if it exists
571 * @return string
573 function getVariantname( $code, $usemsg = true ) {
574 $msg = "variantname-$code";
575 if ( $usemsg && wfMessage( $msg )->exists() ) {
576 return $this->getMessageFromDB( $msg );
578 $name = self::fetchLanguageName( $code );
579 if ( $name ) {
580 return $name; # if it's defined as a language name, show that
581 } else {
582 # otherwise, output the language code
583 return $code;
588 * @param $name string
589 * @return string
591 function specialPage( $name ) {
592 $aliases = $this->getSpecialPageAliases();
593 if ( isset( $aliases[$name][0] ) ) {
594 $name = $aliases[$name][0];
596 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
600 * @return array
602 function getQuickbarSettings() {
603 return array(
604 $this->getMessage( 'qbsettings-none' ),
605 $this->getMessage( 'qbsettings-fixedleft' ),
606 $this->getMessage( 'qbsettings-fixedright' ),
607 $this->getMessage( 'qbsettings-floatingleft' ),
608 $this->getMessage( 'qbsettings-floatingright' ),
609 $this->getMessage( 'qbsettings-directionality' )
614 * @return array
616 function getDatePreferences() {
617 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
621 * @return array
623 function getDateFormats() {
624 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
628 * @return array|string
630 function getDefaultDateFormat() {
631 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
632 if ( $df === 'dmy or mdy' ) {
633 global $wgAmericanDates;
634 return $wgAmericanDates ? 'mdy' : 'dmy';
635 } else {
636 return $df;
641 * @return array
643 function getDatePreferenceMigrationMap() {
644 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
648 * @param $image
649 * @return array|null
651 function getImageFile( $image ) {
652 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
656 * @return array
658 function getExtraUserToggles() {
659 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
663 * @param $tog
664 * @return string
666 function getUserToggle( $tog ) {
667 return $this->getMessageFromDB( "tog-$tog" );
671 * Get native language names, indexed by code.
672 * Only those defined in MediaWiki, no other data like CLDR.
673 * If $customisedOnly is true, only returns codes with a messages file
675 * @param $customisedOnly bool
677 * @return array
678 * @deprecated in 1.20, use fetchLanguageNames()
680 public static function getLanguageNames( $customisedOnly = false ) {
681 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
685 * Get translated language names. This is done on best effort and
686 * by default this is exactly the same as Language::getLanguageNames.
687 * The CLDR extension provides translated names.
688 * @param $code String Language code.
689 * @return Array language code => language name
690 * @since 1.18.0
691 * @deprecated in 1.20, use fetchLanguageNames()
693 public static function getTranslatedLanguageNames( $code ) {
694 return self::fetchLanguageNames( $code, 'all' );
698 * Get an array of language names, indexed by code.
699 * @param $inLanguage null|string: Code of language in which to return the names
700 * Use null for autonyms (native names)
701 * @param $include string:
702 * 'all' all available languages
703 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames
704 * 'mwfile' only if the language is in 'mw' *and* has a message file
705 * @return array|bool: language code => language name, false if $include is wrong
706 * @since 1.20
708 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
709 global $wgExtraLanguageNames;
710 static $coreLanguageNames;
712 if ( $coreLanguageNames === null ) {
713 include( MWInit::compiledPath( 'languages/Names.php' ) );
716 $names = array();
718 if( $inLanguage ) {
719 # TODO: also include when $inLanguage is null, when this code is more efficient
720 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
723 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
724 foreach ( $mwNames as $mwCode => $mwName ) {
725 # - Prefer own MediaWiki native name when not using the hook
726 # TODO: prefer it always to make it consistent, but casing is different in CLDR
727 # - For other names just add if not added through the hook
728 if ( ( $mwCode === $inLanguage && !$inLanguage ) || !isset( $names[$mwCode] ) ) {
729 $names[$mwCode] = $mwName;
733 if ( $include === 'all' ) {
734 return $names;
737 $returnMw = array();
738 $coreCodes = array_keys( $mwNames );
739 foreach( $coreCodes as $coreCode ) {
740 $returnMw[$coreCode] = $names[$coreCode];
743 if( $include === 'mw' ) {
744 return $returnMw;
745 } elseif( $include === 'mwfile' ) {
746 $namesMwFile = array();
747 # We do this using a foreach over the codes instead of a directory
748 # loop so that messages files in extensions will work correctly.
749 foreach ( $returnMw as $code => $value ) {
750 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
751 $namesMwFile[$code] = $names[$code];
754 return $namesMwFile;
756 return false;
760 * @param $code string: The code of the language for which to get the name
761 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
762 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
763 * @return string: Language name or empty
764 * @since 1.20
766 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
767 $array = self::fetchLanguageNames( $inLanguage, $include );
768 return !array_key_exists( $code, $array ) ? '' : $array[$code];
772 * Get a message from the MediaWiki namespace.
774 * @param $msg String: message name
775 * @return string
777 function getMessageFromDB( $msg ) {
778 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
782 * Get the native language name of $code.
783 * Only if defined in MediaWiki, no other data like CLDR.
784 * @param $code string
785 * @return string
786 * @deprecated in 1.20, use fetchLanguageName()
788 function getLanguageName( $code ) {
789 return self::fetchLanguageName( $code );
793 * @param $key string
794 * @return string
796 function getMonthName( $key ) {
797 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
801 * @return array
803 function getMonthNamesArray() {
804 $monthNames = array( '' );
805 for ( $i = 1; $i < 13; $i++ ) {
806 $monthNames[] = $this->getMonthName( $i );
808 return $monthNames;
812 * @param $key string
813 * @return string
815 function getMonthNameGen( $key ) {
816 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
820 * @param $key string
821 * @return string
823 function getMonthAbbreviation( $key ) {
824 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
828 * @return array
830 function getMonthAbbreviationsArray() {
831 $monthNames = array( '' );
832 for ( $i = 1; $i < 13; $i++ ) {
833 $monthNames[] = $this->getMonthAbbreviation( $i );
835 return $monthNames;
839 * @param $key string
840 * @return string
842 function getWeekdayName( $key ) {
843 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
847 * @param $key string
848 * @return string
850 function getWeekdayAbbreviation( $key ) {
851 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
855 * @param $key string
856 * @return string
858 function getIranianCalendarMonthName( $key ) {
859 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
863 * @param $key string
864 * @return string
866 function getHebrewCalendarMonthName( $key ) {
867 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
871 * @param $key string
872 * @return string
874 function getHebrewCalendarMonthNameGen( $key ) {
875 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
879 * @param $key string
880 * @return string
882 function getHijriCalendarMonthName( $key ) {
883 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
887 * This is a workalike of PHP's date() function, but with better
888 * internationalisation, a reduced set of format characters, and a better
889 * escaping format.
891 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
892 * PHP manual for definitions. There are a number of extensions, which
893 * start with "x":
895 * xn Do not translate digits of the next numeric format character
896 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
897 * xr Use roman numerals for the next numeric format character
898 * xh Use hebrew numerals for the next numeric format character
899 * xx Literal x
900 * xg Genitive month name
902 * xij j (day number) in Iranian calendar
903 * xiF F (month name) in Iranian calendar
904 * xin n (month number) in Iranian calendar
905 * xiy y (two digit year) in Iranian calendar
906 * xiY Y (full year) in Iranian calendar
908 * xjj j (day number) in Hebrew calendar
909 * xjF F (month name) in Hebrew calendar
910 * xjt t (days in month) in Hebrew calendar
911 * xjx xg (genitive month name) in Hebrew calendar
912 * xjn n (month number) in Hebrew calendar
913 * xjY Y (full year) in Hebrew calendar
915 * xmj j (day number) in Hijri calendar
916 * xmF F (month name) in Hijri calendar
917 * xmn n (month number) in Hijri calendar
918 * xmY Y (full year) in Hijri calendar
920 * xkY Y (full year) in Thai solar calendar. Months and days are
921 * identical to the Gregorian calendar
922 * xoY Y (full year) in Minguo calendar or Juche year.
923 * Months and days are identical to the
924 * Gregorian calendar
925 * xtY Y (full year) in Japanese nengo. Months and days are
926 * identical to the Gregorian calendar
928 * Characters enclosed in double quotes will be considered literal (with
929 * the quotes themselves removed). Unmatched quotes will be considered
930 * literal quotes. Example:
932 * "The month is" F => The month is January
933 * i's" => 20'11"
935 * Backslash escaping is also supported.
937 * Input timestamp is assumed to be pre-normalized to the desired local
938 * time zone, if any.
940 * @param $format String
941 * @param $ts String: 14-character timestamp
942 * YYYYMMDDHHMMSS
943 * 01234567890123
944 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
946 * @return string
948 function sprintfDate( $format, $ts ) {
949 $s = '';
950 $raw = false;
951 $roman = false;
952 $hebrewNum = false;
953 $unix = false;
954 $rawToggle = false;
955 $iranian = false;
956 $hebrew = false;
957 $hijri = false;
958 $thai = false;
959 $minguo = false;
960 $tenno = false;
961 for ( $p = 0; $p < strlen( $format ); $p++ ) {
962 $num = false;
963 $code = $format[$p];
964 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
965 $code .= $format[++$p];
968 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
969 $code .= $format[++$p];
972 switch ( $code ) {
973 case 'xx':
974 $s .= 'x';
975 break;
976 case 'xn':
977 $raw = true;
978 break;
979 case 'xN':
980 $rawToggle = !$rawToggle;
981 break;
982 case 'xr':
983 $roman = true;
984 break;
985 case 'xh':
986 $hebrewNum = true;
987 break;
988 case 'xg':
989 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
990 break;
991 case 'xjx':
992 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
993 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
994 break;
995 case 'd':
996 $num = substr( $ts, 6, 2 );
997 break;
998 case 'D':
999 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
1000 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
1001 break;
1002 case 'j':
1003 $num = intval( substr( $ts, 6, 2 ) );
1004 break;
1005 case 'xij':
1006 if ( !$iranian ) {
1007 $iranian = self::tsToIranian( $ts );
1009 $num = $iranian[2];
1010 break;
1011 case 'xmj':
1012 if ( !$hijri ) {
1013 $hijri = self::tsToHijri( $ts );
1015 $num = $hijri[2];
1016 break;
1017 case 'xjj':
1018 if ( !$hebrew ) {
1019 $hebrew = self::tsToHebrew( $ts );
1021 $num = $hebrew[2];
1022 break;
1023 case 'l':
1024 if ( !$unix ) {
1025 $unix = wfTimestamp( TS_UNIX, $ts );
1027 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
1028 break;
1029 case 'N':
1030 if ( !$unix ) {
1031 $unix = wfTimestamp( TS_UNIX, $ts );
1033 $w = gmdate( 'w', $unix );
1034 $num = $w ? $w : 7;
1035 break;
1036 case 'w':
1037 if ( !$unix ) {
1038 $unix = wfTimestamp( TS_UNIX, $ts );
1040 $num = gmdate( 'w', $unix );
1041 break;
1042 case 'z':
1043 if ( !$unix ) {
1044 $unix = wfTimestamp( TS_UNIX, $ts );
1046 $num = gmdate( 'z', $unix );
1047 break;
1048 case 'W':
1049 if ( !$unix ) {
1050 $unix = wfTimestamp( TS_UNIX, $ts );
1052 $num = gmdate( 'W', $unix );
1053 break;
1054 case 'F':
1055 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1056 break;
1057 case 'xiF':
1058 if ( !$iranian ) {
1059 $iranian = self::tsToIranian( $ts );
1061 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1062 break;
1063 case 'xmF':
1064 if ( !$hijri ) {
1065 $hijri = self::tsToHijri( $ts );
1067 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1068 break;
1069 case 'xjF':
1070 if ( !$hebrew ) {
1071 $hebrew = self::tsToHebrew( $ts );
1073 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1074 break;
1075 case 'm':
1076 $num = substr( $ts, 4, 2 );
1077 break;
1078 case 'M':
1079 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1080 break;
1081 case 'n':
1082 $num = intval( substr( $ts, 4, 2 ) );
1083 break;
1084 case 'xin':
1085 if ( !$iranian ) {
1086 $iranian = self::tsToIranian( $ts );
1088 $num = $iranian[1];
1089 break;
1090 case 'xmn':
1091 if ( !$hijri ) {
1092 $hijri = self::tsToHijri ( $ts );
1094 $num = $hijri[1];
1095 break;
1096 case 'xjn':
1097 if ( !$hebrew ) {
1098 $hebrew = self::tsToHebrew( $ts );
1100 $num = $hebrew[1];
1101 break;
1102 case 't':
1103 if ( !$unix ) {
1104 $unix = wfTimestamp( TS_UNIX, $ts );
1106 $num = gmdate( 't', $unix );
1107 break;
1108 case 'xjt':
1109 if ( !$hebrew ) {
1110 $hebrew = self::tsToHebrew( $ts );
1112 $num = $hebrew[3];
1113 break;
1114 case 'L':
1115 if ( !$unix ) {
1116 $unix = wfTimestamp( TS_UNIX, $ts );
1118 $num = gmdate( 'L', $unix );
1119 break;
1120 case 'o':
1121 if ( !$unix ) {
1122 $unix = wfTimestamp( TS_UNIX, $ts );
1124 $num = gmdate( 'o', $unix );
1125 break;
1126 case 'Y':
1127 $num = substr( $ts, 0, 4 );
1128 break;
1129 case 'xiY':
1130 if ( !$iranian ) {
1131 $iranian = self::tsToIranian( $ts );
1133 $num = $iranian[0];
1134 break;
1135 case 'xmY':
1136 if ( !$hijri ) {
1137 $hijri = self::tsToHijri( $ts );
1139 $num = $hijri[0];
1140 break;
1141 case 'xjY':
1142 if ( !$hebrew ) {
1143 $hebrew = self::tsToHebrew( $ts );
1145 $num = $hebrew[0];
1146 break;
1147 case 'xkY':
1148 if ( !$thai ) {
1149 $thai = self::tsToYear( $ts, 'thai' );
1151 $num = $thai[0];
1152 break;
1153 case 'xoY':
1154 if ( !$minguo ) {
1155 $minguo = self::tsToYear( $ts, 'minguo' );
1157 $num = $minguo[0];
1158 break;
1159 case 'xtY':
1160 if ( !$tenno ) {
1161 $tenno = self::tsToYear( $ts, 'tenno' );
1163 $num = $tenno[0];
1164 break;
1165 case 'y':
1166 $num = substr( $ts, 2, 2 );
1167 break;
1168 case 'xiy':
1169 if ( !$iranian ) {
1170 $iranian = self::tsToIranian( $ts );
1172 $num = substr( $iranian[0], -2 );
1173 break;
1174 case 'a':
1175 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1176 break;
1177 case 'A':
1178 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1179 break;
1180 case 'g':
1181 $h = substr( $ts, 8, 2 );
1182 $num = $h % 12 ? $h % 12 : 12;
1183 break;
1184 case 'G':
1185 $num = intval( substr( $ts, 8, 2 ) );
1186 break;
1187 case 'h':
1188 $h = substr( $ts, 8, 2 );
1189 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1190 break;
1191 case 'H':
1192 $num = substr( $ts, 8, 2 );
1193 break;
1194 case 'i':
1195 $num = substr( $ts, 10, 2 );
1196 break;
1197 case 's':
1198 $num = substr( $ts, 12, 2 );
1199 break;
1200 case 'c':
1201 if ( !$unix ) {
1202 $unix = wfTimestamp( TS_UNIX, $ts );
1204 $s .= gmdate( 'c', $unix );
1205 break;
1206 case 'r':
1207 if ( !$unix ) {
1208 $unix = wfTimestamp( TS_UNIX, $ts );
1210 $s .= gmdate( 'r', $unix );
1211 break;
1212 case 'U':
1213 if ( !$unix ) {
1214 $unix = wfTimestamp( TS_UNIX, $ts );
1216 $num = $unix;
1217 break;
1218 case '\\':
1219 # Backslash escaping
1220 if ( $p < strlen( $format ) - 1 ) {
1221 $s .= $format[++$p];
1222 } else {
1223 $s .= '\\';
1225 break;
1226 case '"':
1227 # Quoted literal
1228 if ( $p < strlen( $format ) - 1 ) {
1229 $endQuote = strpos( $format, '"', $p + 1 );
1230 if ( $endQuote === false ) {
1231 # No terminating quote, assume literal "
1232 $s .= '"';
1233 } else {
1234 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1235 $p = $endQuote;
1237 } else {
1238 # Quote at end of string, assume literal "
1239 $s .= '"';
1241 break;
1242 default:
1243 $s .= $format[$p];
1245 if ( $num !== false ) {
1246 if ( $rawToggle || $raw ) {
1247 $s .= $num;
1248 $raw = false;
1249 } elseif ( $roman ) {
1250 $s .= self::romanNumeral( $num );
1251 $roman = false;
1252 } elseif ( $hebrewNum ) {
1253 $s .= self::hebrewNumeral( $num );
1254 $hebrewNum = false;
1255 } else {
1256 $s .= $this->formatNum( $num, true );
1260 return $s;
1263 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1264 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1267 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1268 * Gregorian dates to Iranian dates. Originally written in C, it
1269 * is released under the terms of GNU Lesser General Public
1270 * License. Conversion to PHP was performed by Niklas Laxström.
1272 * Link: http://www.farsiweb.info/jalali/jalali.c
1274 * @param $ts string
1276 * @return string
1278 private static function tsToIranian( $ts ) {
1279 $gy = substr( $ts, 0, 4 ) -1600;
1280 $gm = substr( $ts, 4, 2 ) -1;
1281 $gd = substr( $ts, 6, 2 ) -1;
1283 # Days passed from the beginning (including leap years)
1284 $gDayNo = 365 * $gy
1285 + floor( ( $gy + 3 ) / 4 )
1286 - floor( ( $gy + 99 ) / 100 )
1287 + floor( ( $gy + 399 ) / 400 );
1289 // Add days of the past months of this year
1290 for ( $i = 0; $i < $gm; $i++ ) {
1291 $gDayNo += self::$GREG_DAYS[$i];
1294 // Leap years
1295 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1296 $gDayNo++;
1299 // Days passed in current month
1300 $gDayNo += (int)$gd;
1302 $jDayNo = $gDayNo - 79;
1304 $jNp = floor( $jDayNo / 12053 );
1305 $jDayNo %= 12053;
1307 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1308 $jDayNo %= 1461;
1310 if ( $jDayNo >= 366 ) {
1311 $jy += floor( ( $jDayNo - 1 ) / 365 );
1312 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1315 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1316 $jDayNo -= self::$IRANIAN_DAYS[$i];
1319 $jm = $i + 1;
1320 $jd = $jDayNo + 1;
1322 return array( $jy, $jm, $jd );
1326 * Converting Gregorian dates to Hijri dates.
1328 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1330 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1332 * @param $ts string
1334 * @return string
1336 private static function tsToHijri( $ts ) {
1337 $year = substr( $ts, 0, 4 );
1338 $month = substr( $ts, 4, 2 );
1339 $day = substr( $ts, 6, 2 );
1341 $zyr = $year;
1342 $zd = $day;
1343 $zm = $month;
1344 $zy = $zyr;
1346 if (
1347 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1348 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1351 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1352 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1353 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1354 $zd - 32075;
1355 } else {
1356 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1357 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1360 $zl = $zjd -1948440 + 10632;
1361 $zn = (int)( ( $zl - 1 ) / 10631 );
1362 $zl = $zl - 10631 * $zn + 354;
1363 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1364 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1365 $zm = (int)( ( 24 * $zl ) / 709 );
1366 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1367 $zy = 30 * $zn + $zj - 30;
1369 return array( $zy, $zm, $zd );
1373 * Converting Gregorian dates to Hebrew dates.
1375 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1376 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1377 * to translate the relevant functions into PHP and release them under
1378 * GNU GPL.
1380 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1381 * and Adar II is 14. In a non-leap year, Adar is 6.
1383 * @param $ts string
1385 * @return string
1387 private static function tsToHebrew( $ts ) {
1388 # Parse date
1389 $year = substr( $ts, 0, 4 );
1390 $month = substr( $ts, 4, 2 );
1391 $day = substr( $ts, 6, 2 );
1393 # Calculate Hebrew year
1394 $hebrewYear = $year + 3760;
1396 # Month number when September = 1, August = 12
1397 $month += 4;
1398 if ( $month > 12 ) {
1399 # Next year
1400 $month -= 12;
1401 $year++;
1402 $hebrewYear++;
1405 # Calculate day of year from 1 September
1406 $dayOfYear = $day;
1407 for ( $i = 1; $i < $month; $i++ ) {
1408 if ( $i == 6 ) {
1409 # February
1410 $dayOfYear += 28;
1411 # Check if the year is leap
1412 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1413 $dayOfYear++;
1415 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1416 $dayOfYear += 30;
1417 } else {
1418 $dayOfYear += 31;
1422 # Calculate the start of the Hebrew year
1423 $start = self::hebrewYearStart( $hebrewYear );
1425 # Calculate next year's start
1426 if ( $dayOfYear <= $start ) {
1427 # Day is before the start of the year - it is the previous year
1428 # Next year's start
1429 $nextStart = $start;
1430 # Previous year
1431 $year--;
1432 $hebrewYear--;
1433 # Add days since previous year's 1 September
1434 $dayOfYear += 365;
1435 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1436 # Leap year
1437 $dayOfYear++;
1439 # Start of the new (previous) year
1440 $start = self::hebrewYearStart( $hebrewYear );
1441 } else {
1442 # Next year's start
1443 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1446 # Calculate Hebrew day of year
1447 $hebrewDayOfYear = $dayOfYear - $start;
1449 # Difference between year's days
1450 $diff = $nextStart - $start;
1451 # Add 12 (or 13 for leap years) days to ignore the difference between
1452 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1453 # difference is only about the year type
1454 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1455 $diff += 13;
1456 } else {
1457 $diff += 12;
1460 # Check the year pattern, and is leap year
1461 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1462 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1463 # and non-leap years
1464 $yearPattern = $diff % 30;
1465 # Check if leap year
1466 $isLeap = $diff >= 30;
1468 # Calculate day in the month from number of day in the Hebrew year
1469 # Don't check Adar - if the day is not in Adar, we will stop before;
1470 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1471 $hebrewDay = $hebrewDayOfYear;
1472 $hebrewMonth = 1;
1473 $days = 0;
1474 while ( $hebrewMonth <= 12 ) {
1475 # Calculate days in this month
1476 if ( $isLeap && $hebrewMonth == 6 ) {
1477 # Adar in a leap year
1478 if ( $isLeap ) {
1479 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1480 $days = 30;
1481 if ( $hebrewDay <= $days ) {
1482 # Day in Adar I
1483 $hebrewMonth = 13;
1484 } else {
1485 # Subtract the days of Adar I
1486 $hebrewDay -= $days;
1487 # Try Adar II
1488 $days = 29;
1489 if ( $hebrewDay <= $days ) {
1490 # Day in Adar II
1491 $hebrewMonth = 14;
1495 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1496 # Cheshvan in a complete year (otherwise as the rule below)
1497 $days = 30;
1498 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1499 # Kislev in an incomplete year (otherwise as the rule below)
1500 $days = 29;
1501 } else {
1502 # Odd months have 30 days, even have 29
1503 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1505 if ( $hebrewDay <= $days ) {
1506 # In the current month
1507 break;
1508 } else {
1509 # Subtract the days of the current month
1510 $hebrewDay -= $days;
1511 # Try in the next month
1512 $hebrewMonth++;
1516 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1520 * This calculates the Hebrew year start, as days since 1 September.
1521 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1522 * Used for Hebrew date.
1524 * @param $year int
1526 * @return string
1528 private static function hebrewYearStart( $year ) {
1529 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1530 $b = intval( ( $year - 1 ) % 4 );
1531 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1532 if ( $m < 0 ) {
1533 $m--;
1535 $Mar = intval( $m );
1536 if ( $m < 0 ) {
1537 $m++;
1539 $m -= $Mar;
1541 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1542 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1543 $Mar++;
1544 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1545 $Mar += 2;
1546 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1547 $Mar++;
1550 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1551 return $Mar;
1555 * Algorithm to convert Gregorian dates to Thai solar dates,
1556 * Minguo dates or Minguo dates.
1558 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1559 * http://en.wikipedia.org/wiki/Minguo_calendar
1560 * http://en.wikipedia.org/wiki/Japanese_era_name
1562 * @param $ts String: 14-character timestamp
1563 * @param $cName String: calender name
1564 * @return Array: converted year, month, day
1566 private static function tsToYear( $ts, $cName ) {
1567 $gy = substr( $ts, 0, 4 );
1568 $gm = substr( $ts, 4, 2 );
1569 $gd = substr( $ts, 6, 2 );
1571 if ( !strcmp( $cName, 'thai' ) ) {
1572 # Thai solar dates
1573 # Add 543 years to the Gregorian calendar
1574 # Months and days are identical
1575 $gy_offset = $gy + 543;
1576 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1577 # Minguo dates
1578 # Deduct 1911 years from the Gregorian calendar
1579 # Months and days are identical
1580 $gy_offset = $gy - 1911;
1581 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1582 # Nengō dates up to Meiji period
1583 # Deduct years from the Gregorian calendar
1584 # depending on the nengo periods
1585 # Months and days are identical
1586 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1587 # Meiji period
1588 $gy_gannen = $gy - 1868 + 1;
1589 $gy_offset = $gy_gannen;
1590 if ( $gy_gannen == 1 ) {
1591 $gy_offset = '元';
1593 $gy_offset = '明治' . $gy_offset;
1594 } elseif (
1595 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1596 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1597 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1598 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1599 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1602 # Taishō period
1603 $gy_gannen = $gy - 1912 + 1;
1604 $gy_offset = $gy_gannen;
1605 if ( $gy_gannen == 1 ) {
1606 $gy_offset = '元';
1608 $gy_offset = '大正' . $gy_offset;
1609 } elseif (
1610 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1611 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1612 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1615 # Shōwa period
1616 $gy_gannen = $gy - 1926 + 1;
1617 $gy_offset = $gy_gannen;
1618 if ( $gy_gannen == 1 ) {
1619 $gy_offset = '元';
1621 $gy_offset = '昭和' . $gy_offset;
1622 } else {
1623 # Heisei period
1624 $gy_gannen = $gy - 1989 + 1;
1625 $gy_offset = $gy_gannen;
1626 if ( $gy_gannen == 1 ) {
1627 $gy_offset = '元';
1629 $gy_offset = '平成' . $gy_offset;
1631 } else {
1632 $gy_offset = $gy;
1635 return array( $gy_offset, $gm, $gd );
1639 * Roman number formatting up to 3000
1641 * @param $num int
1643 * @return string
1645 static function romanNumeral( $num ) {
1646 static $table = array(
1647 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1648 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1649 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1650 array( '', 'M', 'MM', 'MMM' )
1653 $num = intval( $num );
1654 if ( $num > 3000 || $num <= 0 ) {
1655 return $num;
1658 $s = '';
1659 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1660 if ( $num >= $pow10 ) {
1661 $s .= $table[$i][(int)floor( $num / $pow10 )];
1663 $num = $num % $pow10;
1665 return $s;
1669 * Hebrew Gematria number formatting up to 9999
1671 * @param $num int
1673 * @return string
1675 static function hebrewNumeral( $num ) {
1676 static $table = array(
1677 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1678 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1679 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1680 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1683 $num = intval( $num );
1684 if ( $num > 9999 || $num <= 0 ) {
1685 return $num;
1688 $s = '';
1689 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1690 if ( $num >= $pow10 ) {
1691 if ( $num == 15 || $num == 16 ) {
1692 $s .= $table[0][9] . $table[0][$num - 9];
1693 $num = 0;
1694 } else {
1695 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1696 if ( $pow10 == 1000 ) {
1697 $s .= "'";
1701 $num = $num % $pow10;
1703 if ( strlen( $s ) == 2 ) {
1704 $str = $s . "'";
1705 } else {
1706 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1707 $str .= substr( $s, strlen( $s ) - 2, 2 );
1709 $start = substr( $str, 0, strlen( $str ) - 2 );
1710 $end = substr( $str, strlen( $str ) - 2 );
1711 switch( $end ) {
1712 case 'כ':
1713 $str = $start . 'ך';
1714 break;
1715 case 'מ':
1716 $str = $start . 'ם';
1717 break;
1718 case 'נ':
1719 $str = $start . 'ן';
1720 break;
1721 case 'פ':
1722 $str = $start . 'ף';
1723 break;
1724 case 'צ':
1725 $str = $start . 'ץ';
1726 break;
1728 return $str;
1732 * Used by date() and time() to adjust the time output.
1734 * @param $ts Int the time in date('YmdHis') format
1735 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1736 * get user timecorrection setting)
1737 * @return int
1739 function userAdjust( $ts, $tz = false ) {
1740 global $wgUser, $wgLocalTZoffset;
1742 if ( $tz === false ) {
1743 $tz = $wgUser->getOption( 'timecorrection' );
1746 $data = explode( '|', $tz, 3 );
1748 if ( $data[0] == 'ZoneInfo' ) {
1749 wfSuppressWarnings();
1750 $userTZ = timezone_open( $data[2] );
1751 wfRestoreWarnings();
1752 if ( $userTZ !== false ) {
1753 $date = date_create( $ts, timezone_open( 'UTC' ) );
1754 date_timezone_set( $date, $userTZ );
1755 $date = date_format( $date, 'YmdHis' );
1756 return $date;
1758 # Unrecognized timezone, default to 'Offset' with the stored offset.
1759 $data[0] = 'Offset';
1762 $minDiff = 0;
1763 if ( $data[0] == 'System' || $tz == '' ) {
1764 #  Global offset in minutes.
1765 if ( isset( $wgLocalTZoffset ) ) {
1766 $minDiff = $wgLocalTZoffset;
1768 } elseif ( $data[0] == 'Offset' ) {
1769 $minDiff = intval( $data[1] );
1770 } else {
1771 $data = explode( ':', $tz );
1772 if ( count( $data ) == 2 ) {
1773 $data[0] = intval( $data[0] );
1774 $data[1] = intval( $data[1] );
1775 $minDiff = abs( $data[0] ) * 60 + $data[1];
1776 if ( $data[0] < 0 ) {
1777 $minDiff = -$minDiff;
1779 } else {
1780 $minDiff = intval( $data[0] ) * 60;
1784 # No difference ? Return time unchanged
1785 if ( 0 == $minDiff ) {
1786 return $ts;
1789 wfSuppressWarnings(); // E_STRICT system time bitching
1790 # Generate an adjusted date; take advantage of the fact that mktime
1791 # will normalize out-of-range values so we don't have to split $minDiff
1792 # into hours and minutes.
1793 $t = mktime( (
1794 (int)substr( $ts, 8, 2 ) ), # Hours
1795 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1796 (int)substr( $ts, 12, 2 ), # Seconds
1797 (int)substr( $ts, 4, 2 ), # Month
1798 (int)substr( $ts, 6, 2 ), # Day
1799 (int)substr( $ts, 0, 4 ) ); # Year
1801 $date = date( 'YmdHis', $t );
1802 wfRestoreWarnings();
1804 return $date;
1808 * This is meant to be used by time(), date(), and timeanddate() to get
1809 * the date preference they're supposed to use, it should be used in
1810 * all children.
1812 *<code>
1813 * function timeanddate([...], $format = true) {
1814 * $datePreference = $this->dateFormat($format);
1815 * [...]
1817 *</code>
1819 * @param $usePrefs Mixed: if true, the user's preference is used
1820 * if false, the site/language default is used
1821 * if int/string, assumed to be a format.
1822 * @return string
1824 function dateFormat( $usePrefs = true ) {
1825 global $wgUser;
1827 if ( is_bool( $usePrefs ) ) {
1828 if ( $usePrefs ) {
1829 $datePreference = $wgUser->getDatePreference();
1830 } else {
1831 $datePreference = (string)User::getDefaultOption( 'date' );
1833 } else {
1834 $datePreference = (string)$usePrefs;
1837 // return int
1838 if ( $datePreference == '' ) {
1839 return 'default';
1842 return $datePreference;
1846 * Get a format string for a given type and preference
1847 * @param $type string May be date, time or both
1848 * @param $pref string The format name as it appears in Messages*.php
1850 * @return string
1852 function getDateFormatString( $type, $pref ) {
1853 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1854 if ( $pref == 'default' ) {
1855 $pref = $this->getDefaultDateFormat();
1856 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1857 } else {
1858 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1859 if ( is_null( $df ) ) {
1860 $pref = $this->getDefaultDateFormat();
1861 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1864 $this->dateFormatStrings[$type][$pref] = $df;
1866 return $this->dateFormatStrings[$type][$pref];
1870 * @param $ts Mixed: the time format which needs to be turned into a
1871 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1872 * @param $adj Bool: whether to adjust the time output according to the
1873 * user configured offset ($timecorrection)
1874 * @param $format Mixed: true to use user's date format preference
1875 * @param $timecorrection String|bool the time offset as returned by
1876 * validateTimeZone() in Special:Preferences
1877 * @return string
1879 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1880 $ts = wfTimestamp( TS_MW, $ts );
1881 if ( $adj ) {
1882 $ts = $this->userAdjust( $ts, $timecorrection );
1884 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1885 return $this->sprintfDate( $df, $ts );
1889 * @param $ts Mixed: the time format which needs to be turned into a
1890 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1891 * @param $adj Bool: whether to adjust the time output according to the
1892 * user configured offset ($timecorrection)
1893 * @param $format Mixed: true to use user's date format preference
1894 * @param $timecorrection String|bool the time offset as returned by
1895 * validateTimeZone() in Special:Preferences
1896 * @return string
1898 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1899 $ts = wfTimestamp( TS_MW, $ts );
1900 if ( $adj ) {
1901 $ts = $this->userAdjust( $ts, $timecorrection );
1903 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1904 return $this->sprintfDate( $df, $ts );
1908 * @param $ts Mixed: the time format which needs to be turned into a
1909 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1910 * @param $adj Bool: whether to adjust the time output according to the
1911 * user configured offset ($timecorrection)
1912 * @param $format Mixed: what format to return, if it's false output the
1913 * default one (default true)
1914 * @param $timecorrection String|bool the time offset as returned by
1915 * validateTimeZone() in Special:Preferences
1916 * @return string
1918 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1919 $ts = wfTimestamp( TS_MW, $ts );
1920 if ( $adj ) {
1921 $ts = $this->userAdjust( $ts, $timecorrection );
1923 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1924 return $this->sprintfDate( $df, $ts );
1928 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1930 * @since 1.20
1932 * @param integer $seconds The amount of seconds.
1933 * @param array $chosenIntervals The intervals to enable.
1935 * @return string
1937 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1938 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1940 $segments = array();
1942 foreach ( $intervals as $intervalName => $intervalValue ) {
1943 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1944 $segments[] = $message->inLanguage( $this )->escaped();
1947 return $this->listToText( $segments );
1951 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1952 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1954 * @since 1.20
1956 * @param integer $seconds The amount of seconds.
1957 * @param array $chosenIntervals The intervals to enable.
1959 * @return array
1961 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1962 if ( empty( $chosenIntervals ) ) {
1963 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1966 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
1967 $sortedNames = array_keys( $intervals );
1968 $smallestInterval = array_pop( $sortedNames );
1970 $segments = array();
1972 foreach ( $intervals as $name => $length ) {
1973 $value = floor( $seconds / $length );
1975 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
1976 $seconds -= $value * $length;
1977 $segments[$name] = $value;
1981 return $segments;
1985 * Internal helper function for userDate(), userTime() and userTimeAndDate()
1987 * @param $type String: can be 'date', 'time' or 'both'
1988 * @param $ts Mixed: the time format which needs to be turned into a
1989 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1990 * @param $user User object used to get preferences for timezone and format
1991 * @param $options Array, can contain the following keys:
1992 * - 'timecorrection': time correction, can have the following values:
1993 * - true: use user's preference
1994 * - false: don't use time correction
1995 * - integer: value of time correction in minutes
1996 * - 'format': format to use, can have the following values:
1997 * - true: use user's preference
1998 * - false: use default preference
1999 * - string: format to use
2000 * @since 1.19
2001 * @return String
2003 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2004 $ts = wfTimestamp( TS_MW, $ts );
2005 $options += array( 'timecorrection' => true, 'format' => true );
2006 if ( $options['timecorrection'] !== false ) {
2007 if ( $options['timecorrection'] === true ) {
2008 $offset = $user->getOption( 'timecorrection' );
2009 } else {
2010 $offset = $options['timecorrection'];
2012 $ts = $this->userAdjust( $ts, $offset );
2014 if ( $options['format'] === true ) {
2015 $format = $user->getDatePreference();
2016 } else {
2017 $format = $options['format'];
2019 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2020 return $this->sprintfDate( $df, $ts );
2024 * Get the formatted date for the given timestamp and formatted for
2025 * the given user.
2027 * @param $ts Mixed: the time format which needs to be turned into a
2028 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2029 * @param $user User object used to get preferences for timezone and format
2030 * @param $options Array, can contain the following keys:
2031 * - 'timecorrection': time correction, can have the following values:
2032 * - true: use user's preference
2033 * - false: don't use time correction
2034 * - integer: value of time correction in minutes
2035 * - 'format': format to use, can have the following values:
2036 * - true: use user's preference
2037 * - false: use default preference
2038 * - string: format to use
2039 * @since 1.19
2040 * @return String
2042 public function userDate( $ts, User $user, array $options = array() ) {
2043 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2047 * Get the formatted time for the given timestamp and formatted for
2048 * the given user.
2050 * @param $ts Mixed: the time format which needs to be turned into a
2051 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2052 * @param $user User object used to get preferences for timezone and format
2053 * @param $options Array, can contain the following keys:
2054 * - 'timecorrection': time correction, can have the following values:
2055 * - true: use user's preference
2056 * - false: don't use time correction
2057 * - integer: value of time correction in minutes
2058 * - 'format': format to use, can have the following values:
2059 * - true: use user's preference
2060 * - false: use default preference
2061 * - string: format to use
2062 * @since 1.19
2063 * @return String
2065 public function userTime( $ts, User $user, array $options = array() ) {
2066 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2070 * Get the formatted date and time for the given timestamp and formatted for
2071 * the given user.
2073 * @param $ts Mixed: the time format which needs to be turned into a
2074 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2075 * @param $user User object used to get preferences for timezone and format
2076 * @param $options Array, can contain the following keys:
2077 * - 'timecorrection': time correction, can have the following values:
2078 * - true: use user's preference
2079 * - false: don't use time correction
2080 * - integer: value of time correction in minutes
2081 * - 'format': format to use, can have the following values:
2082 * - true: use user's preference
2083 * - false: use default preference
2084 * - string: format to use
2085 * @since 1.19
2086 * @return String
2088 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2089 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2093 * @param $key string
2094 * @return array|null
2096 function getMessage( $key ) {
2097 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2101 * @return array
2103 function getAllMessages() {
2104 return self::$dataCache->getItem( $this->mCode, 'messages' );
2108 * @param $in
2109 * @param $out
2110 * @param $string
2111 * @return string
2113 function iconv( $in, $out, $string ) {
2114 # This is a wrapper for iconv in all languages except esperanto,
2115 # which does some nasty x-conversions beforehand
2117 # Even with //IGNORE iconv can whine about illegal characters in
2118 # *input* string. We just ignore those too.
2119 # REF: http://bugs.php.net/bug.php?id=37166
2120 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2121 wfSuppressWarnings();
2122 $text = iconv( $in, $out . '//IGNORE', $string );
2123 wfRestoreWarnings();
2124 return $text;
2127 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2130 * @param $matches array
2131 * @return mixed|string
2133 function ucwordbreaksCallbackAscii( $matches ) {
2134 return $this->ucfirst( $matches[1] );
2138 * @param $matches array
2139 * @return string
2141 function ucwordbreaksCallbackMB( $matches ) {
2142 return mb_strtoupper( $matches[0] );
2146 * @param $matches array
2147 * @return string
2149 function ucCallback( $matches ) {
2150 list( $wikiUpperChars ) = self::getCaseMaps();
2151 return strtr( $matches[1], $wikiUpperChars );
2155 * @param $matches array
2156 * @return string
2158 function lcCallback( $matches ) {
2159 list( , $wikiLowerChars ) = self::getCaseMaps();
2160 return strtr( $matches[1], $wikiLowerChars );
2164 * @param $matches array
2165 * @return string
2167 function ucwordsCallbackMB( $matches ) {
2168 return mb_strtoupper( $matches[0] );
2172 * @param $matches array
2173 * @return string
2175 function ucwordsCallbackWiki( $matches ) {
2176 list( $wikiUpperChars ) = self::getCaseMaps();
2177 return strtr( $matches[0], $wikiUpperChars );
2181 * Make a string's first character uppercase
2183 * @param $str string
2185 * @return string
2187 function ucfirst( $str ) {
2188 $o = ord( $str );
2189 if ( $o < 96 ) { // if already uppercase...
2190 return $str;
2191 } elseif ( $o < 128 ) {
2192 return ucfirst( $str ); // use PHP's ucfirst()
2193 } else {
2194 // fall back to more complex logic in case of multibyte strings
2195 return $this->uc( $str, true );
2200 * Convert a string to uppercase
2202 * @param $str string
2203 * @param $first bool
2205 * @return string
2207 function uc( $str, $first = false ) {
2208 if ( function_exists( 'mb_strtoupper' ) ) {
2209 if ( $first ) {
2210 if ( $this->isMultibyte( $str ) ) {
2211 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2212 } else {
2213 return ucfirst( $str );
2215 } else {
2216 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2218 } else {
2219 if ( $this->isMultibyte( $str ) ) {
2220 $x = $first ? '^' : '';
2221 return preg_replace_callback(
2222 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2223 array( $this, 'ucCallback' ),
2224 $str
2226 } else {
2227 return $first ? ucfirst( $str ) : strtoupper( $str );
2233 * @param $str string
2234 * @return mixed|string
2236 function lcfirst( $str ) {
2237 $o = ord( $str );
2238 if ( !$o ) {
2239 return strval( $str );
2240 } elseif ( $o >= 128 ) {
2241 return $this->lc( $str, true );
2242 } elseif ( $o > 96 ) {
2243 return $str;
2244 } else {
2245 $str[0] = strtolower( $str[0] );
2246 return $str;
2251 * @param $str string
2252 * @param $first bool
2253 * @return mixed|string
2255 function lc( $str, $first = false ) {
2256 if ( function_exists( 'mb_strtolower' ) ) {
2257 if ( $first ) {
2258 if ( $this->isMultibyte( $str ) ) {
2259 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2260 } else {
2261 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2263 } else {
2264 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2266 } else {
2267 if ( $this->isMultibyte( $str ) ) {
2268 $x = $first ? '^' : '';
2269 return preg_replace_callback(
2270 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2271 array( $this, 'lcCallback' ),
2272 $str
2274 } else {
2275 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2281 * @param $str string
2282 * @return bool
2284 function isMultibyte( $str ) {
2285 return (bool)preg_match( '/[\x80-\xff]/', $str );
2289 * @param $str string
2290 * @return mixed|string
2292 function ucwords( $str ) {
2293 if ( $this->isMultibyte( $str ) ) {
2294 $str = $this->lc( $str );
2296 // regexp to find first letter in each word (i.e. after each space)
2297 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2299 // function to use to capitalize a single char
2300 if ( function_exists( 'mb_strtoupper' ) ) {
2301 return preg_replace_callback(
2302 $replaceRegexp,
2303 array( $this, 'ucwordsCallbackMB' ),
2304 $str
2306 } else {
2307 return preg_replace_callback(
2308 $replaceRegexp,
2309 array( $this, 'ucwordsCallbackWiki' ),
2310 $str
2313 } else {
2314 return ucwords( strtolower( $str ) );
2319 * capitalize words at word breaks
2321 * @param $str string
2322 * @return mixed
2324 function ucwordbreaks( $str ) {
2325 if ( $this->isMultibyte( $str ) ) {
2326 $str = $this->lc( $str );
2328 // since \b doesn't work for UTF-8, we explicitely define word break chars
2329 $breaks = "[ \-\(\)\}\{\.,\?!]";
2331 // find first letter after word break
2332 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2334 if ( function_exists( 'mb_strtoupper' ) ) {
2335 return preg_replace_callback(
2336 $replaceRegexp,
2337 array( $this, 'ucwordbreaksCallbackMB' ),
2338 $str
2340 } else {
2341 return preg_replace_callback(
2342 $replaceRegexp,
2343 array( $this, 'ucwordsCallbackWiki' ),
2344 $str
2347 } else {
2348 return preg_replace_callback(
2349 '/\b([\w\x80-\xff]+)\b/',
2350 array( $this, 'ucwordbreaksCallbackAscii' ),
2351 $str
2357 * Return a case-folded representation of $s
2359 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2360 * and $s2 are the same except for the case of their characters. It is not
2361 * necessary for the value returned to make sense when displayed.
2363 * Do *not* perform any other normalisation in this function. If a caller
2364 * uses this function when it should be using a more general normalisation
2365 * function, then fix the caller.
2367 * @param $s string
2369 * @return string
2371 function caseFold( $s ) {
2372 return $this->uc( $s );
2376 * @param $s string
2377 * @return string
2379 function checkTitleEncoding( $s ) {
2380 if ( is_array( $s ) ) {
2381 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2383 # Check for non-UTF-8 URLs
2384 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2385 if ( !$ishigh ) {
2386 return $s;
2389 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2390 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2391 if ( $isutf8 ) {
2392 return $s;
2395 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2399 * @return array
2401 function fallback8bitEncoding() {
2402 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2406 * Most writing systems use whitespace to break up words.
2407 * Some languages such as Chinese don't conventionally do this,
2408 * which requires special handling when breaking up words for
2409 * searching etc.
2411 * @return bool
2413 function hasWordBreaks() {
2414 return true;
2418 * Some languages such as Chinese require word segmentation,
2419 * Specify such segmentation when overridden in derived class.
2421 * @param $string String
2422 * @return String
2424 function segmentByWord( $string ) {
2425 return $string;
2429 * Some languages have special punctuation need to be normalized.
2430 * Make such changes here.
2432 * @param $string String
2433 * @return String
2435 function normalizeForSearch( $string ) {
2436 return self::convertDoubleWidth( $string );
2440 * convert double-width roman characters to single-width.
2441 * range: ff00-ff5f ~= 0020-007f
2443 * @param $string string
2445 * @return string
2447 protected static function convertDoubleWidth( $string ) {
2448 static $full = null;
2449 static $half = null;
2451 if ( $full === null ) {
2452 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2453 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2454 $full = str_split( $fullWidth, 3 );
2455 $half = str_split( $halfWidth );
2458 $string = str_replace( $full, $half, $string );
2459 return $string;
2463 * @param $string string
2464 * @param $pattern string
2465 * @return string
2467 protected static function insertSpace( $string, $pattern ) {
2468 $string = preg_replace( $pattern, " $1 ", $string );
2469 $string = preg_replace( '/ +/', ' ', $string );
2470 return $string;
2474 * @param $termsArray array
2475 * @return array
2477 function convertForSearchResult( $termsArray ) {
2478 # some languages, e.g. Chinese, need to do a conversion
2479 # in order for search results to be displayed correctly
2480 return $termsArray;
2484 * Get the first character of a string.
2486 * @param $s string
2487 * @return string
2489 function firstChar( $s ) {
2490 $matches = array();
2491 preg_match(
2492 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2493 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2495 $matches
2498 if ( isset( $matches[1] ) ) {
2499 if ( strlen( $matches[1] ) != 3 ) {
2500 return $matches[1];
2503 // Break down Hangul syllables to grab the first jamo
2504 $code = utf8ToCodepoint( $matches[1] );
2505 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2506 return $matches[1];
2507 } elseif ( $code < 0xb098 ) {
2508 return "\xe3\x84\xb1";
2509 } elseif ( $code < 0xb2e4 ) {
2510 return "\xe3\x84\xb4";
2511 } elseif ( $code < 0xb77c ) {
2512 return "\xe3\x84\xb7";
2513 } elseif ( $code < 0xb9c8 ) {
2514 return "\xe3\x84\xb9";
2515 } elseif ( $code < 0xbc14 ) {
2516 return "\xe3\x85\x81";
2517 } elseif ( $code < 0xc0ac ) {
2518 return "\xe3\x85\x82";
2519 } elseif ( $code < 0xc544 ) {
2520 return "\xe3\x85\x85";
2521 } elseif ( $code < 0xc790 ) {
2522 return "\xe3\x85\x87";
2523 } elseif ( $code < 0xcc28 ) {
2524 return "\xe3\x85\x88";
2525 } elseif ( $code < 0xce74 ) {
2526 return "\xe3\x85\x8a";
2527 } elseif ( $code < 0xd0c0 ) {
2528 return "\xe3\x85\x8b";
2529 } elseif ( $code < 0xd30c ) {
2530 return "\xe3\x85\x8c";
2531 } elseif ( $code < 0xd558 ) {
2532 return "\xe3\x85\x8d";
2533 } else {
2534 return "\xe3\x85\x8e";
2536 } else {
2537 return '';
2541 function initEncoding() {
2542 # Some languages may have an alternate char encoding option
2543 # (Esperanto X-coding, Japanese furigana conversion, etc)
2544 # If this language is used as the primary content language,
2545 # an override to the defaults can be set here on startup.
2549 * @param $s string
2550 * @return string
2552 function recodeForEdit( $s ) {
2553 # For some languages we'll want to explicitly specify
2554 # which characters make it into the edit box raw
2555 # or are converted in some way or another.
2556 global $wgEditEncoding;
2557 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2558 return $s;
2559 } else {
2560 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2565 * @param $s string
2566 * @return string
2568 function recodeInput( $s ) {
2569 # Take the previous into account.
2570 global $wgEditEncoding;
2571 if ( $wgEditEncoding != '' ) {
2572 $enc = $wgEditEncoding;
2573 } else {
2574 $enc = 'UTF-8';
2576 if ( $enc == 'UTF-8' ) {
2577 return $s;
2578 } else {
2579 return $this->iconv( $enc, 'UTF-8', $s );
2584 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2585 * also cleans up certain backwards-compatible sequences, converting them
2586 * to the modern Unicode equivalent.
2588 * This is language-specific for performance reasons only.
2590 * @param $s string
2592 * @return string
2594 function normalize( $s ) {
2595 global $wgAllUnicodeFixes;
2596 $s = UtfNormal::cleanUp( $s );
2597 if ( $wgAllUnicodeFixes ) {
2598 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2599 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2602 return $s;
2606 * Transform a string using serialized data stored in the given file (which
2607 * must be in the serialized subdirectory of $IP). The file contains pairs
2608 * mapping source characters to destination characters.
2610 * The data is cached in process memory. This will go faster if you have the
2611 * FastStringSearch extension.
2613 * @param $file string
2614 * @param $string string
2616 * @throws MWException
2617 * @return string
2619 function transformUsingPairFile( $file, $string ) {
2620 if ( !isset( $this->transformData[$file] ) ) {
2621 $data = wfGetPrecompiledData( $file );
2622 if ( $data === false ) {
2623 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2625 $this->transformData[$file] = new ReplacementArray( $data );
2627 return $this->transformData[$file]->replace( $string );
2631 * For right-to-left language support
2633 * @return bool
2635 function isRTL() {
2636 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2640 * Return the correct HTML 'dir' attribute value for this language.
2641 * @return String
2643 function getDir() {
2644 return $this->isRTL() ? 'rtl' : 'ltr';
2648 * Return 'left' or 'right' as appropriate alignment for line-start
2649 * for this language's text direction.
2651 * Should be equivalent to CSS3 'start' text-align value....
2653 * @return String
2655 function alignStart() {
2656 return $this->isRTL() ? 'right' : 'left';
2660 * Return 'right' or 'left' as appropriate alignment for line-end
2661 * for this language's text direction.
2663 * Should be equivalent to CSS3 'end' text-align value....
2665 * @return String
2667 function alignEnd() {
2668 return $this->isRTL() ? 'left' : 'right';
2672 * A hidden direction mark (LRM or RLM), depending on the language direction.
2673 * Unlike getDirMark(), this function returns the character as an HTML entity.
2674 * This function should be used when the output is guaranteed to be HTML,
2675 * because it makes the output HTML source code more readable. When
2676 * the output is plain text or can be escaped, getDirMark() should be used.
2678 * @param $opposite Boolean Get the direction mark opposite to your language
2679 * @return string
2681 function getDirMarkEntity( $opposite = false ) {
2682 if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
2683 return $this->isRTL() ? '&rlm;' : '&lrm;';
2687 * A hidden direction mark (LRM or RLM), depending on the language direction.
2688 * This function produces them as invisible Unicode characters and
2689 * the output may be hard to read and debug, so it should only be used
2690 * when the output is plain text or can be escaped. When the output is
2691 * HTML, use getDirMarkEntity() instead.
2693 * @param $opposite Boolean Get the direction mark opposite to your language
2694 * @return string
2696 function getDirMark( $opposite = false ) {
2697 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2698 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2699 if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
2700 return $this->isRTL() ? $rlm : $lrm;
2704 * @return array
2706 function capitalizeAllNouns() {
2707 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2711 * An arrow, depending on the language direction
2713 * @return string
2715 function getArrow() {
2716 return $this->isRTL() ? '←' : '→';
2720 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2722 * @return bool
2724 function linkPrefixExtension() {
2725 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2729 * @return array
2731 function getMagicWords() {
2732 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2735 protected function doMagicHook() {
2736 if ( $this->mMagicHookDone ) {
2737 return;
2739 $this->mMagicHookDone = true;
2740 wfProfileIn( 'LanguageGetMagic' );
2741 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2742 wfProfileOut( 'LanguageGetMagic' );
2746 * Fill a MagicWord object with data from here
2748 * @param $mw
2750 function getMagic( $mw ) {
2751 $this->doMagicHook();
2753 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2754 $rawEntry = $this->mMagicExtensions[$mw->mId];
2755 } else {
2756 $magicWords = $this->getMagicWords();
2757 if ( isset( $magicWords[$mw->mId] ) ) {
2758 $rawEntry = $magicWords[$mw->mId];
2759 } else {
2760 $rawEntry = false;
2764 if ( !is_array( $rawEntry ) ) {
2765 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2766 } else {
2767 $mw->mCaseSensitive = $rawEntry[0];
2768 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2773 * Add magic words to the extension array
2775 * @param $newWords array
2777 function addMagicWordsByLang( $newWords ) {
2778 $fallbackChain = $this->getFallbackLanguages();
2779 $fallbackChain = array_reverse( $fallbackChain );
2780 foreach ( $fallbackChain as $code ) {
2781 if ( isset( $newWords[$code] ) ) {
2782 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2788 * Get special page names, as an associative array
2789 * case folded alias => real name
2791 function getSpecialPageAliases() {
2792 // Cache aliases because it may be slow to load them
2793 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2794 // Initialise array
2795 $this->mExtendedSpecialPageAliases =
2796 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2797 wfRunHooks( 'LanguageGetSpecialPageAliases',
2798 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2801 return $this->mExtendedSpecialPageAliases;
2805 * Italic is unsuitable for some languages
2807 * @param $text String: the text to be emphasized.
2808 * @return string
2810 function emphasize( $text ) {
2811 return "<em>$text</em>";
2815 * Normally we output all numbers in plain en_US style, that is
2816 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2817 * point twohundredthirtyfive. However this is not suitable for all
2818 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2819 * Icelandic just want to use commas instead of dots, and dots instead
2820 * of commas like "293.291,235".
2822 * An example of this function being called:
2823 * <code>
2824 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2825 * </code>
2827 * See LanguageGu.php for the Gujarati implementation and
2828 * $separatorTransformTable on MessageIs.php for
2829 * the , => . and . => , implementation.
2831 * @todo check if it's viable to use localeconv() for the decimal
2832 * separator thing.
2833 * @param $number Mixed: the string to be formatted, should be an integer
2834 * or a floating point number.
2835 * @param $nocommafy Bool: set to true for special numbers like dates
2836 * @return string
2838 public function formatNum( $number, $nocommafy = false ) {
2839 global $wgTranslateNumerals;
2840 if ( !$nocommafy ) {
2841 $number = $this->commafy( $number );
2842 $s = $this->separatorTransformTable();
2843 if ( $s ) {
2844 $number = strtr( $number, $s );
2848 if ( $wgTranslateNumerals ) {
2849 $s = $this->digitTransformTable();
2850 if ( $s ) {
2851 $number = strtr( $number, $s );
2855 return $number;
2859 * @param $number string
2860 * @return string
2862 function parseFormattedNumber( $number ) {
2863 $s = $this->digitTransformTable();
2864 if ( $s ) {
2865 $number = strtr( $number, array_flip( $s ) );
2868 $s = $this->separatorTransformTable();
2869 if ( $s ) {
2870 $number = strtr( $number, array_flip( $s ) );
2873 $number = strtr( $number, array( ',' => '' ) );
2874 return $number;
2878 * Adds commas to a given number
2879 * @since 1.19
2880 * @param $_ mixed
2881 * @return string
2883 function commafy( $_ ) {
2884 $digitGroupingPattern = $this->digitGroupingPattern();
2885 if ( $_ === null ) {
2886 return '';
2889 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2890 // default grouping is at thousands, use the same for ###,###,### pattern too.
2891 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2892 } else {
2893 // Ref: http://cldr.unicode.org/translation/number-patterns
2894 $sign = "";
2895 if ( intval( $_ ) < 0 ) {
2896 // For negative numbers apply the algorithm like positive number and add sign.
2897 $sign = "-";
2898 $_ = substr( $_, 1 );
2900 $numberpart = array();
2901 $decimalpart = array();
2902 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2903 preg_match( "/\d+/", $_, $numberpart );
2904 preg_match( "/\.\d*/", $_, $decimalpart );
2905 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2906 if ( $groupedNumber === $_ ) {
2907 // the string does not have any number part. Eg: .12345
2908 return $sign . $groupedNumber;
2910 $start = $end = strlen( $numberpart[0] );
2911 while ( $start > 0 ) {
2912 $match = $matches[0][$numMatches -1] ;
2913 $matchLen = strlen( $match );
2914 $start = $end - $matchLen;
2915 if ( $start < 0 ) {
2916 $start = 0;
2918 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2919 $end = $start;
2920 if ( $numMatches > 1 ) {
2921 // use the last pattern for the rest of the number
2922 $numMatches--;
2924 if ( $start > 0 ) {
2925 $groupedNumber = "," . $groupedNumber;
2928 return $sign . $groupedNumber;
2932 * @return String
2934 function digitGroupingPattern() {
2935 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
2939 * @return array
2941 function digitTransformTable() {
2942 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2946 * @return array
2948 function separatorTransformTable() {
2949 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2953 * Take a list of strings and build a locale-friendly comma-separated
2954 * list, using the local comma-separator message.
2955 * The last two strings are chained with an "and".
2957 * @param $l Array
2958 * @return string
2960 function listToText( array $l ) {
2961 $s = '';
2962 $m = count( $l ) - 1;
2963 if ( $m == 1 ) {
2964 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2965 } else {
2966 for ( $i = $m; $i >= 0; $i-- ) {
2967 if ( $i == $m ) {
2968 $s = $l[$i];
2969 } elseif ( $i == $m - 1 ) {
2970 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2971 } else {
2972 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2975 return $s;
2980 * Take a list of strings and build a locale-friendly comma-separated
2981 * list, using the local comma-separator message.
2982 * @param $list array of strings to put in a comma list
2983 * @return string
2985 function commaList( array $list ) {
2986 return implode(
2987 wfMsgExt(
2988 'comma-separator',
2989 array( 'parsemag', 'escapenoentities', 'language' => $this )
2991 $list
2996 * Take a list of strings and build a locale-friendly semicolon-separated
2997 * list, using the local semicolon-separator message.
2998 * @param $list array of strings to put in a semicolon list
2999 * @return string
3001 function semicolonList( array $list ) {
3002 return implode(
3003 wfMsgExt(
3004 'semicolon-separator',
3005 array( 'parsemag', 'escapenoentities', 'language' => $this )
3007 $list
3012 * Same as commaList, but separate it with the pipe instead.
3013 * @param $list array of strings to put in a pipe list
3014 * @return string
3016 function pipeList( array $list ) {
3017 return implode(
3018 wfMsgExt(
3019 'pipe-separator',
3020 array( 'escapenoentities', 'language' => $this )
3022 $list
3027 * Truncate a string to a specified length in bytes, appending an optional
3028 * string (e.g. for ellipses)
3030 * The database offers limited byte lengths for some columns in the database;
3031 * multi-byte character sets mean we need to ensure that only whole characters
3032 * are included, otherwise broken characters can be passed to the user
3034 * If $length is negative, the string will be truncated from the beginning
3036 * @param $string String to truncate
3037 * @param $length Int: maximum length (including ellipses)
3038 * @param $ellipsis String to append to the truncated text
3039 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3040 * $adjustLength was introduced in 1.18, before that behaved as if false.
3041 * @return string
3043 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3044 # Use the localized ellipsis character
3045 if ( $ellipsis == '...' ) {
3046 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3048 # Check if there is no need to truncate
3049 if ( $length == 0 ) {
3050 return $ellipsis; // convention
3051 } elseif ( strlen( $string ) <= abs( $length ) ) {
3052 return $string; // no need to truncate
3054 $stringOriginal = $string;
3055 # If ellipsis length is >= $length then we can't apply $adjustLength
3056 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3057 $string = $ellipsis; // this can be slightly unexpected
3058 # Otherwise, truncate and add ellipsis...
3059 } else {
3060 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3061 if ( $length > 0 ) {
3062 $length -= $eLength;
3063 $string = substr( $string, 0, $length ); // xyz...
3064 $string = $this->removeBadCharLast( $string );
3065 $string = $string . $ellipsis;
3066 } else {
3067 $length += $eLength;
3068 $string = substr( $string, $length ); // ...xyz
3069 $string = $this->removeBadCharFirst( $string );
3070 $string = $ellipsis . $string;
3073 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3074 # This check is *not* redundant if $adjustLength, due to the single case where
3075 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3076 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3077 return $string;
3078 } else {
3079 return $stringOriginal;
3084 * Remove bytes that represent an incomplete Unicode character
3085 * at the end of string (e.g. bytes of the char are missing)
3087 * @param $string String
3088 * @return string
3090 protected function removeBadCharLast( $string ) {
3091 if ( $string != '' ) {
3092 $char = ord( $string[strlen( $string ) - 1] );
3093 $m = array();
3094 if ( $char >= 0xc0 ) {
3095 # We got the first byte only of a multibyte char; remove it.
3096 $string = substr( $string, 0, -1 );
3097 } elseif ( $char >= 0x80 &&
3098 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3099 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3101 # We chopped in the middle of a character; remove it
3102 $string = $m[1];
3105 return $string;
3109 * Remove bytes that represent an incomplete Unicode character
3110 * at the start of string (e.g. bytes of the char are missing)
3112 * @param $string String
3113 * @return string
3115 protected function removeBadCharFirst( $string ) {
3116 if ( $string != '' ) {
3117 $char = ord( $string[0] );
3118 if ( $char >= 0x80 && $char < 0xc0 ) {
3119 # We chopped in the middle of a character; remove the whole thing
3120 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3123 return $string;
3127 * Truncate a string of valid HTML to a specified length in bytes,
3128 * appending an optional string (e.g. for ellipses), and return valid HTML
3130 * This is only intended for styled/linked text, such as HTML with
3131 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3132 * Also, this will not detect things like "display:none" CSS.
3134 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3136 * @param string $text HTML string to truncate
3137 * @param int $length (zero/positive) Maximum length (including ellipses)
3138 * @param string $ellipsis String to append to the truncated text
3139 * @return string
3141 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3142 # Use the localized ellipsis character
3143 if ( $ellipsis == '...' ) {
3144 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3146 # Check if there is clearly no need to truncate
3147 if ( $length <= 0 ) {
3148 return $ellipsis; // no text shown, nothing to format (convention)
3149 } elseif ( strlen( $text ) <= $length ) {
3150 return $text; // string short enough even *with* HTML (short-circuit)
3153 $dispLen = 0; // innerHTML legth so far
3154 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3155 $tagType = 0; // 0-open, 1-close
3156 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3157 $entityState = 0; // 0-not entity, 1-entity
3158 $tag = $ret = ''; // accumulated tag name, accumulated result string
3159 $openTags = array(); // open tag stack
3160 $maybeState = null; // possible truncation state
3162 $textLen = strlen( $text );
3163 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3164 for ( $pos = 0; true; ++$pos ) {
3165 # Consider truncation once the display length has reached the maximim.
3166 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3167 # Check that we're not in the middle of a bracket/entity...
3168 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3169 if ( !$testingEllipsis ) {
3170 $testingEllipsis = true;
3171 # Save where we are; we will truncate here unless there turn out to
3172 # be so few remaining characters that truncation is not necessary.
3173 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3174 $maybeState = array( $ret, $openTags ); // save state
3176 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3177 # String in fact does need truncation, the truncation point was OK.
3178 list( $ret, $openTags ) = $maybeState; // reload state
3179 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3180 $ret .= $ellipsis; // add ellipsis
3181 break;
3184 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3186 # Read the next char...
3187 $ch = $text[$pos];
3188 $lastCh = $pos ? $text[$pos - 1] : '';
3189 $ret .= $ch; // add to result string
3190 if ( $ch == '<' ) {
3191 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3192 $entityState = 0; // for bad HTML
3193 $bracketState = 1; // tag started (checking for backslash)
3194 } elseif ( $ch == '>' ) {
3195 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3196 $entityState = 0; // for bad HTML
3197 $bracketState = 0; // out of brackets
3198 } elseif ( $bracketState == 1 ) {
3199 if ( $ch == '/' ) {
3200 $tagType = 1; // close tag (e.g. "</span>")
3201 } else {
3202 $tagType = 0; // open tag (e.g. "<span>")
3203 $tag .= $ch;
3205 $bracketState = 2; // building tag name
3206 } elseif ( $bracketState == 2 ) {
3207 if ( $ch != ' ' ) {
3208 $tag .= $ch;
3209 } else {
3210 // Name found (e.g. "<a href=..."), add on tag attributes...
3211 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3213 } elseif ( $bracketState == 0 ) {
3214 if ( $entityState ) {
3215 if ( $ch == ';' ) {
3216 $entityState = 0;
3217 $dispLen++; // entity is one displayed char
3219 } else {
3220 if ( $neLength == 0 && !$maybeState ) {
3221 // Save state without $ch. We want to *hit* the first
3222 // display char (to get tags) but not *use* it if truncating.
3223 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3225 if ( $ch == '&' ) {
3226 $entityState = 1; // entity found, (e.g. "&#160;")
3227 } else {
3228 $dispLen++; // this char is displayed
3229 // Add the next $max display text chars after this in one swoop...
3230 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3231 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3232 $dispLen += $skipped;
3233 $pos += $skipped;
3238 // Close the last tag if left unclosed by bad HTML
3239 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3240 while ( count( $openTags ) > 0 ) {
3241 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3243 return $ret;
3247 * truncateHtml() helper function
3248 * like strcspn() but adds the skipped chars to $ret
3250 * @param $ret
3251 * @param $text
3252 * @param $search
3253 * @param $start
3254 * @param $len
3255 * @return int
3257 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3258 if ( $len === null ) {
3259 $len = -1; // -1 means "no limit" for strcspn
3260 } elseif ( $len < 0 ) {
3261 $len = 0; // sanity
3263 $skipCount = 0;
3264 if ( $start < strlen( $text ) ) {
3265 $skipCount = strcspn( $text, $search, $start, $len );
3266 $ret .= substr( $text, $start, $skipCount );
3268 return $skipCount;
3272 * truncateHtml() helper function
3273 * (a) push or pop $tag from $openTags as needed
3274 * (b) clear $tag value
3275 * @param &$tag string Current HTML tag name we are looking at
3276 * @param $tagType int (0-open tag, 1-close tag)
3277 * @param $lastCh string Character before the '>' that ended this tag
3278 * @param &$openTags array Open tag stack (not accounting for $tag)
3280 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3281 $tag = ltrim( $tag );
3282 if ( $tag != '' ) {
3283 if ( $tagType == 0 && $lastCh != '/' ) {
3284 $openTags[] = $tag; // tag opened (didn't close itself)
3285 } elseif ( $tagType == 1 ) {
3286 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3287 array_pop( $openTags ); // tag closed
3290 $tag = '';
3295 * Grammatical transformations, needed for inflected languages
3296 * Invoked by putting {{grammar:case|word}} in a message
3298 * @param $word string
3299 * @param $case string
3300 * @return string
3302 function convertGrammar( $word, $case ) {
3303 global $wgGrammarForms;
3304 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3305 return $wgGrammarForms[$this->getCode()][$case][$word];
3307 return $word;
3310 * Get the grammar forms for the content language
3311 * @return array of grammar forms
3312 * @since 1.20
3314 function getGrammarForms() {
3315 global $wgGrammarForms;
3316 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3317 return $wgGrammarForms[$this->getCode()];
3319 return array();
3322 * Provides an alternative text depending on specified gender.
3323 * Usage {{gender:username|masculine|feminine|neutral}}.
3324 * username is optional, in which case the gender of current user is used,
3325 * but only in (some) interface messages; otherwise default gender is used.
3327 * If no forms are given, an empty string is returned. If only one form is
3328 * given, it will be returned unconditionally. These details are implied by
3329 * the caller and cannot be overridden in subclasses.
3331 * If more than one form is given, the default is to use the neutral one
3332 * if it is specified, and to use the masculine one otherwise. These
3333 * details can be overridden in subclasses.
3335 * @param $gender string
3336 * @param $forms array
3338 * @return string
3340 function gender( $gender, $forms ) {
3341 if ( !count( $forms ) ) {
3342 return '';
3344 $forms = $this->preConvertPlural( $forms, 2 );
3345 if ( $gender === 'male' ) {
3346 return $forms[0];
3348 if ( $gender === 'female' ) {
3349 return $forms[1];
3351 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3355 * Plural form transformations, needed for some languages.
3356 * For example, there are 3 form of plural in Russian and Polish,
3357 * depending on "count mod 10". See [[w:Plural]]
3358 * For English it is pretty simple.
3360 * Invoked by putting {{plural:count|wordform1|wordform2}}
3361 * or {{plural:count|wordform1|wordform2|wordform3}}
3363 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3365 * @param $count Integer: non-localized number
3366 * @param $forms Array: different plural forms
3367 * @return string Correct form of plural for $count in this language
3369 function convertPlural( $count, $forms ) {
3370 if ( !count( $forms ) ) {
3371 return '';
3373 $forms = $this->preConvertPlural( $forms, 2 );
3375 return ( $count == 1 ) ? $forms[0] : $forms[1];
3379 * Checks that convertPlural was given an array and pads it to requested
3380 * amount of forms by copying the last one.
3382 * @param $count Integer: How many forms should there be at least
3383 * @param $forms Array of forms given to convertPlural
3384 * @return array Padded array of forms or an exception if not an array
3386 protected function preConvertPlural( /* Array */ $forms, $count ) {
3387 while ( count( $forms ) < $count ) {
3388 $forms[] = $forms[count( $forms ) - 1];
3390 return $forms;
3394 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3395 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3396 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3397 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3398 * match up with it.
3400 * @param $str String: the validated block duration in English
3401 * @return string Somehow translated block duration
3402 * @see LanguageFi.php for example implementation
3404 function translateBlockExpiry( $str ) {
3405 $duration = SpecialBlock::getSuggestedDurations( $this );
3406 foreach ( $duration as $show => $value ) {
3407 if ( strcmp( $str, $value ) == 0 ) {
3408 return htmlspecialchars( trim( $show ) );
3412 // Since usually only infinite or indefinite is only on list, so try
3413 // equivalents if still here.
3414 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3415 if ( in_array( $str, $indefs ) ) {
3416 foreach ( $indefs as $val ) {
3417 $show = array_search( $val, $duration, true );
3418 if ( $show !== false ) {
3419 return htmlspecialchars( trim( $show ) );
3423 // If all else fails, return the original string.
3424 return $str;
3428 * languages like Chinese need to be segmented in order for the diff
3429 * to be of any use
3431 * @param $text String
3432 * @return String
3434 public function segmentForDiff( $text ) {
3435 return $text;
3439 * and unsegment to show the result
3441 * @param $text String
3442 * @return String
3444 public function unsegmentForDiff( $text ) {
3445 return $text;
3449 * Return the LanguageConverter used in the Language
3451 * @since 1.19
3452 * @return LanguageConverter
3454 public function getConverter() {
3455 return $this->mConverter;
3459 * convert text to all supported variants
3461 * @param $text string
3462 * @return array
3464 public function autoConvertToAllVariants( $text ) {
3465 return $this->mConverter->autoConvertToAllVariants( $text );
3469 * convert text to different variants of a language.
3471 * @param $text string
3472 * @return string
3474 public function convert( $text ) {
3475 return $this->mConverter->convert( $text );
3479 * Convert a Title object to a string in the preferred variant
3481 * @param $title Title
3482 * @return string
3484 public function convertTitle( $title ) {
3485 return $this->mConverter->convertTitle( $title );
3489 * Check if this is a language with variants
3491 * @return bool
3493 public function hasVariants() {
3494 return sizeof( $this->getVariants() ) > 1;
3498 * Check if the language has the specific variant
3500 * @since 1.19
3501 * @param $variant string
3502 * @return bool
3504 public function hasVariant( $variant ) {
3505 return (bool)$this->mConverter->validateVariant( $variant );
3509 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3511 * @param $text string
3512 * @return string
3514 public function armourMath( $text ) {
3515 return $this->mConverter->armourMath( $text );
3519 * Perform output conversion on a string, and encode for safe HTML output.
3520 * @param $text String text to be converted
3521 * @param $isTitle Bool whether this conversion is for the article title
3522 * @return string
3523 * @todo this should get integrated somewhere sane
3525 public function convertHtml( $text, $isTitle = false ) {
3526 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3530 * @param $key string
3531 * @return string
3533 public function convertCategoryKey( $key ) {
3534 return $this->mConverter->convertCategoryKey( $key );
3538 * Get the list of variants supported by this language
3539 * see sample implementation in LanguageZh.php
3541 * @return array an array of language codes
3543 public function getVariants() {
3544 return $this->mConverter->getVariants();
3548 * @return string
3550 public function getPreferredVariant() {
3551 return $this->mConverter->getPreferredVariant();
3555 * @return string
3557 public function getDefaultVariant() {
3558 return $this->mConverter->getDefaultVariant();
3562 * @return string
3564 public function getURLVariant() {
3565 return $this->mConverter->getURLVariant();
3569 * If a language supports multiple variants, it is
3570 * possible that non-existing link in one variant
3571 * actually exists in another variant. this function
3572 * tries to find it. See e.g. LanguageZh.php
3574 * @param $link String: the name of the link
3575 * @param $nt Mixed: the title object of the link
3576 * @param $ignoreOtherCond Boolean: to disable other conditions when
3577 * we need to transclude a template or update a category's link
3578 * @return null the input parameters may be modified upon return
3580 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3581 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3585 * If a language supports multiple variants, converts text
3586 * into an array of all possible variants of the text:
3587 * 'variant' => text in that variant
3589 * @deprecated since 1.17 Use autoConvertToAllVariants()
3591 * @param $text string
3593 * @return string
3595 public function convertLinkToAllVariants( $text ) {
3596 return $this->mConverter->convertLinkToAllVariants( $text );
3600 * returns language specific options used by User::getPageRenderHash()
3601 * for example, the preferred language variant
3603 * @return string
3605 function getExtraHashOptions() {
3606 return $this->mConverter->getExtraHashOptions();
3610 * For languages that support multiple variants, the title of an
3611 * article may be displayed differently in different variants. this
3612 * function returns the apporiate title defined in the body of the article.
3614 * @return string
3616 public function getParsedTitle() {
3617 return $this->mConverter->getParsedTitle();
3621 * Enclose a string with the "no conversion" tag. This is used by
3622 * various functions in the Parser
3624 * @param $text String: text to be tagged for no conversion
3625 * @param $noParse bool
3626 * @return string the tagged text
3628 public function markNoConversion( $text, $noParse = false ) {
3629 return $this->mConverter->markNoConversion( $text, $noParse );
3633 * A regular expression to match legal word-trailing characters
3634 * which should be merged onto a link of the form [[foo]]bar.
3636 * @return string
3638 public function linkTrail() {
3639 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3643 * @return Language
3645 function getLangObj() {
3646 return $this;
3650 * Get the RFC 3066 code for this language object
3652 * @return string
3654 public function getCode() {
3655 return $this->mCode;
3659 * Get the code in Bcp47 format which we can use
3660 * inside of html lang="" tags.
3661 * @since 1.19
3662 * @return string
3664 public function getHtmlCode() {
3665 if ( is_null( $this->mHtmlCode ) ) {
3666 $this->mHtmlCode = wfBCP47( $this->getCode() );
3668 return $this->mHtmlCode;
3672 * @param $code string
3674 public function setCode( $code ) {
3675 $this->mCode = $code;
3676 // Ensure we don't leave an incorrect html code lying around
3677 $this->mHtmlCode = null;
3681 * Get the name of a file for a certain language code
3682 * @param $prefix string Prepend this to the filename
3683 * @param $code string Language code
3684 * @param $suffix string Append this to the filename
3685 * @throws MWException
3686 * @return string $prefix . $mangledCode . $suffix
3688 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3689 // Protect against path traversal
3690 if ( !Language::isValidCode( $code )
3691 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3693 throw new MWException( "Invalid language code \"$code\"" );
3696 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3700 * Get the language code from a file name. Inverse of getFileName()
3701 * @param $filename string $prefix . $languageCode . $suffix
3702 * @param $prefix string Prefix before the language code
3703 * @param $suffix string Suffix after the language code
3704 * @return string Language code, or false if $prefix or $suffix isn't found
3706 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3707 $m = null;
3708 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3709 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3710 if ( !count( $m ) ) {
3711 return false;
3713 return str_replace( '_', '-', strtolower( $m[1] ) );
3717 * @param $code string
3718 * @return string
3720 public static function getMessagesFileName( $code ) {
3721 global $IP;
3722 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3723 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3724 return $file;
3728 * @param $code string
3729 * @return string
3731 public static function getClassFileName( $code ) {
3732 global $IP;
3733 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3737 * Get the first fallback for a given language.
3739 * @param $code string
3741 * @return bool|string
3743 public static function getFallbackFor( $code ) {
3744 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3745 return false;
3746 } else {
3747 $fallbacks = self::getFallbacksFor( $code );
3748 $first = array_shift( $fallbacks );
3749 return $first;
3754 * Get the ordered list of fallback languages.
3756 * @since 1.19
3757 * @param $code string Language code
3758 * @return array
3760 public static function getFallbacksFor( $code ) {
3761 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3762 return array();
3763 } else {
3764 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3765 $v = array_map( 'trim', explode( ',', $v ) );
3766 if ( $v[count( $v ) - 1] !== 'en' ) {
3767 $v[] = 'en';
3769 return $v;
3774 * Get all messages for a given language
3775 * WARNING: this may take a long time. If you just need all message *keys*
3776 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3778 * @param $code string
3780 * @return array
3782 public static function getMessagesFor( $code ) {
3783 return self::getLocalisationCache()->getItem( $code, 'messages' );
3787 * Get a message for a given language
3789 * @param $key string
3790 * @param $code string
3792 * @return string
3794 public static function getMessageFor( $key, $code ) {
3795 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3799 * Get all message keys for a given language. This is a faster alternative to
3800 * array_keys( Language::getMessagesFor( $code ) )
3802 * @since 1.19
3803 * @param $code string Language code
3804 * @return array of message keys (strings)
3806 public static function getMessageKeysFor( $code ) {
3807 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3811 * @param $talk
3812 * @return mixed
3814 function fixVariableInNamespace( $talk ) {
3815 if ( strpos( $talk, '$1' ) === false ) {
3816 return $talk;
3819 global $wgMetaNamespace;
3820 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3822 # Allow grammar transformations
3823 # Allowing full message-style parsing would make simple requests
3824 # such as action=raw much more expensive than they need to be.
3825 # This will hopefully cover most cases.
3826 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3827 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3828 return str_replace( ' ', '_', $talk );
3832 * @param $m string
3833 * @return string
3835 function replaceGrammarInNamespace( $m ) {
3836 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3840 * @throws MWException
3841 * @return array
3843 static function getCaseMaps() {
3844 static $wikiUpperChars, $wikiLowerChars;
3845 if ( isset( $wikiUpperChars ) ) {
3846 return array( $wikiUpperChars, $wikiLowerChars );
3849 wfProfileIn( __METHOD__ );
3850 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3851 if ( $arr === false ) {
3852 throw new MWException(
3853 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3855 $wikiUpperChars = $arr['wikiUpperChars'];
3856 $wikiLowerChars = $arr['wikiLowerChars'];
3857 wfProfileOut( __METHOD__ );
3858 return array( $wikiUpperChars, $wikiLowerChars );
3862 * Decode an expiry (block, protection, etc) which has come from the DB
3864 * @FIXME: why are we returnings DBMS-dependent strings???
3866 * @param $expiry String: Database expiry String
3867 * @param $format Bool|Int true to process using language functions, or TS_ constant
3868 * to return the expiry in a given timestamp
3869 * @return String
3871 public function formatExpiry( $expiry, $format = true ) {
3872 static $infinity, $infinityMsg;
3873 if ( $infinity === null ) {
3874 $infinityMsg = wfMessage( 'infiniteblock' );
3875 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3878 if ( $expiry == '' || $expiry == $infinity ) {
3879 return $format === true
3880 ? $infinityMsg
3881 : $infinity;
3882 } else {
3883 return $format === true
3884 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3885 : wfTimestamp( $format, $expiry );
3890 * @todo Document
3891 * @param $seconds int|float
3892 * @param $format Array Optional
3893 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3894 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3895 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3896 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3897 * @return string
3899 function formatTimePeriod( $seconds, $format = array() ) {
3900 if ( !is_array( $format ) ) {
3901 $format = array( 'avoid' => $format ); // For backwards compatibility
3903 if ( !isset( $format['avoid'] ) ) {
3904 $format['avoid'] = false;
3906 if ( !isset( $format['noabbrevs' ] ) ) {
3907 $format['noabbrevs'] = false;
3909 $secondsMsg = wfMessage(
3910 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3911 $minutesMsg = wfMessage(
3912 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3913 $hoursMsg = wfMessage(
3914 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
3915 $daysMsg = wfMessage(
3916 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
3918 if ( round( $seconds * 10 ) < 100 ) {
3919 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3920 $s = $secondsMsg->params( $s )->text();
3921 } elseif ( round( $seconds ) < 60 ) {
3922 $s = $this->formatNum( round( $seconds ) );
3923 $s = $secondsMsg->params( $s )->text();
3924 } elseif ( round( $seconds ) < 3600 ) {
3925 $minutes = floor( $seconds / 60 );
3926 $secondsPart = round( fmod( $seconds, 60 ) );
3927 if ( $secondsPart == 60 ) {
3928 $secondsPart = 0;
3929 $minutes++;
3931 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3932 $s .= ' ';
3933 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3934 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3935 $hours = floor( $seconds / 3600 );
3936 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3937 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3938 if ( $secondsPart == 60 ) {
3939 $secondsPart = 0;
3940 $minutes++;
3942 if ( $minutes == 60 ) {
3943 $minutes = 0;
3944 $hours++;
3946 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3947 $s .= ' ';
3948 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3949 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3950 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3952 } else {
3953 $days = floor( $seconds / 86400 );
3954 if ( $format['avoid'] === 'avoidminutes' ) {
3955 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3956 if ( $hours == 24 ) {
3957 $hours = 0;
3958 $days++;
3960 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3961 $s .= ' ';
3962 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3963 } elseif ( $format['avoid'] === 'avoidseconds' ) {
3964 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3965 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3966 if ( $minutes == 60 ) {
3967 $minutes = 0;
3968 $hours++;
3970 if ( $hours == 24 ) {
3971 $hours = 0;
3972 $days++;
3974 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3975 $s .= ' ';
3976 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
3977 $s .= ' ';
3978 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3979 } else {
3980 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
3981 $s .= ' ';
3982 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3985 return $s;
3989 * Format a bitrate for output, using an appropriate
3990 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
3992 * This use base 1000. For base 1024 use formatSize(), for another base
3993 * see formatComputingNumbers()
3995 * @param $bps int
3996 * @return string
3998 function formatBitrate( $bps ) {
3999 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4003 * @param $size int Size of the unit
4004 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4005 * @param $messageKey string Message key to be uesd
4006 * @return string
4008 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4009 if ( $size <= 0 ) {
4010 return str_replace( '$1', $this->formatNum( $size ),
4011 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4014 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4015 $index = 0;
4017 $maxIndex = count( $sizes ) - 1;
4018 while ( $size >= $boundary && $index < $maxIndex ) {
4019 $index++;
4020 $size /= $boundary;
4023 // For small sizes no decimal places necessary
4024 $round = 0;
4025 if ( $index > 1 ) {
4026 // For MB and bigger two decimal places are smarter
4027 $round = 2;
4029 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4031 $size = round( $size, $round );
4032 $text = $this->getMessageFromDB( $msg );
4033 return str_replace( '$1', $this->formatNum( $size ), $text );
4037 * Format a size in bytes for output, using an appropriate
4038 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4040 * This method use base 1024. For base 1000 use formatBitrate(), for
4041 * another base see formatComputingNumbers()
4043 * @param $size int Size to format
4044 * @return string Plain text (not HTML)
4046 function formatSize( $size ) {
4047 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4051 * Make a list item, used by various special pages
4053 * @param $page String Page link
4054 * @param $details String Text between brackets
4055 * @param $oppositedm Boolean Add the direction mark opposite to your
4056 * language, to display text properly
4057 * @return String
4059 function specialList( $page, $details, $oppositedm = true ) {
4060 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4061 $this->getDirMark();
4062 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4063 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4064 return $page . $details;
4068 * Generate (prev x| next x) (20|50|100...) type links for paging
4070 * @param $title Title object to link
4071 * @param $offset Integer offset parameter
4072 * @param $limit Integer limit parameter
4073 * @param $query String optional URL query parameter string
4074 * @param $atend Bool optional param for specified if this is the last page
4075 * @return String
4077 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4078 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4080 # Make 'previous' link
4081 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4082 if ( $offset > 0 ) {
4083 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4084 $query, $prev, 'prevn-title', 'mw-prevlink' );
4085 } else {
4086 $plink = htmlspecialchars( $prev );
4089 # Make 'next' link
4090 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4091 if ( $atend ) {
4092 $nlink = htmlspecialchars( $next );
4093 } else {
4094 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4095 $query, $next, 'prevn-title', 'mw-nextlink' );
4098 # Make links to set number of items per page
4099 $numLinks = array();
4100 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4101 $numLinks[] = $this->numLink( $title, $offset, $num,
4102 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4105 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4106 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4110 * Helper function for viewPrevNext() that generates links
4112 * @param $title Title object to link
4113 * @param $offset Integer offset parameter
4114 * @param $limit Integer limit parameter
4115 * @param $query Array extra query parameters
4116 * @param $link String text to use for the link; will be escaped
4117 * @param $tooltipMsg String name of the message to use as tooltip
4118 * @param $class String value of the "class" attribute of the link
4119 * @return String HTML fragment
4121 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4122 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4123 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4124 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4125 'title' => $tooltip, 'class' => $class ), $link );
4129 * Get the conversion rule title, if any.
4131 * @return string
4133 public function getConvRuleTitle() {
4134 return $this->mConverter->getConvRuleTitle();