3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once( __DIR__
. '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
52 function __construct( $langobj ) { $this->mLang
= $langobj; }
53 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
54 function convert( $t ) { return $t; }
55 function convertTo( $text, $variant ) { return $text; }
56 function convertTitle( $t ) { return $t->getPrefixedText(); }
57 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
58 function getVariants() { return array( $this->mLang
->getCode() ); }
59 function getPreferredVariant() { return $this->mLang
->getCode(); }
60 function getDefaultVariant() { return $this->mLang
->getCode(); }
61 function getURLVariant() { return ''; }
62 function getConvRuleTitle() { return false; }
63 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
64 function getExtraHashOptions() { return ''; }
65 function getParsedTitle() { return ''; }
66 function markNoConversion( $text, $noParse = false ) { return $text; }
67 function convertCategoryKey( $key ) { return $key; }
68 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
69 function armourMath( $text ) { return $text; }
73 * Internationalisation code
79 * @var LanguageConverter
83 public $mVariants, $mCode, $mLoaded = false;
84 public $mMagicExtensions = array(), $mMagicHookDone = false;
85 private $mHtmlCode = null;
87 public $dateFormatStrings = array();
88 public $mExtendedSpecialPageAliases;
90 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
93 * ReplacementArray object caches
95 public $transformData = array();
98 * @var LocalisationCache
100 static public $dataCache;
102 static public $mLangObjCache = array();
104 static public $mWeekdayMsgs = array(
105 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
109 static public $mWeekdayAbbrevMsgs = array(
110 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
113 static public $mMonthMsgs = array(
114 'january', 'february', 'march', 'april', 'may_long', 'june',
115 'july', 'august', 'september', 'october', 'november',
118 static public $mMonthGenMsgs = array(
119 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
120 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
123 static public $mMonthAbbrevMsgs = array(
124 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
125 'sep', 'oct', 'nov', 'dec'
128 static public $mIranianCalendarMonthMsgs = array(
129 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
130 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
131 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
132 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
135 static public $mHebrewCalendarMonthMsgs = array(
136 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
137 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
138 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
139 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
140 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
143 static public $mHebrewCalendarMonthGenMsgs = array(
144 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
145 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
146 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
147 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
148 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
151 static public $mHijriCalendarMonthMsgs = array(
152 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
153 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
154 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
155 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
162 static public $durationIntervals = array(
163 'millennia' => 31557600000,
164 'centuries' => 3155760000,
165 'decades' => 315576000,
166 'years' => 31557600, // 86400 * 365.25
175 * Get a cached or new language object for a given language code
176 * @param $code String
179 static function factory( $code ) {
180 global $wgLangObjCacheSize;
182 // get the language object to process
183 $langObj = isset( self
::$mLangObjCache[$code] )
184 ? self
::$mLangObjCache[$code]
185 : self
::newFromCode( $code );
187 // merge the language object in to get it up front in the cache
188 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
189 // get rid of the oldest ones in case we have an overflow
190 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
196 * Create a language object for a given language code
197 * @param $code String
198 * @throws MWException
201 protected static function newFromCode( $code ) {
202 // Protect against path traversal below
203 if ( !Language
::isValidCode( $code )
204 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
206 throw new MWException( "Invalid language code \"$code\"" );
209 if ( !Language
::isValidBuiltInCode( $code ) ) {
210 // It's not possible to customise this code with class files, so
211 // just return a Language object. This is to support uselang= hacks.
212 $lang = new Language
;
213 $lang->setCode( $code );
217 // Check if there is a language class for the code
218 $class = self
::classFromCode( $code );
219 self
::preloadLanguageClass( $class );
220 if ( MWInit
::classExists( $class ) ) {
225 // Keep trying the fallback list until we find an existing class
226 $fallbacks = Language
::getFallbacksFor( $code );
227 foreach ( $fallbacks as $fallbackCode ) {
228 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
229 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
232 $class = self
::classFromCode( $fallbackCode );
233 self
::preloadLanguageClass( $class );
234 if ( MWInit
::classExists( $class ) ) {
235 $lang = Language
::newFromCode( $fallbackCode );
236 $lang->setCode( $code );
241 throw new MWException( "Invalid fallback sequence for language '$code'" );
245 * Returns true if a language code string is of a valid form, whether or
246 * not it exists. This includes codes which are used solely for
247 * customisation via the MediaWiki namespace.
249 * @param $code string
253 public static function isValidCode( $code ) {
255 // People think language codes are html safe, so enforce it.
256 // Ideally we should only allow a-zA-Z0-9-
257 // but, .+ and other chars are often used for {{int:}} hacks
258 // see bugs 37564, 37587, 36938
259 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
260 && !preg_match( Title
::getTitleInvalidRegex(), $code );
264 * Returns true if a language code is of a valid form for the purposes of
265 * internal customisation of MediaWiki, via Messages*.php.
267 * @param $code string
269 * @throws MWException
273 public static function isValidBuiltInCode( $code ) {
275 if ( !is_string( $code ) ) {
276 $type = gettype( $code );
277 if ( $type === 'object' ) {
278 $addmsg = " of class " . get_class( $code );
282 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
285 return (bool)preg_match( '/^[a-z0-9-]+$/i', $code );
290 * @return String Name of the language class
292 public static function classFromCode( $code ) {
293 if ( $code == 'en' ) {
296 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
301 * Includes language class files
303 * @param $class string Name of the language class
305 public static function preloadLanguageClass( $class ) {
308 if ( $class === 'Language' ) {
312 if ( !defined( 'MW_COMPILED' ) ) {
313 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
314 include_once( "$IP/languages/classes/$class.php" );
320 * Get the LocalisationCache instance
322 * @return LocalisationCache
324 public static function getLocalisationCache() {
325 if ( is_null( self
::$dataCache ) ) {
326 global $wgLocalisationCacheConf;
327 $class = $wgLocalisationCacheConf['class'];
328 self
::$dataCache = new $class( $wgLocalisationCacheConf );
330 return self
::$dataCache;
333 function __construct() {
334 $this->mConverter
= new FakeConverter( $this );
335 // Set the code to the name of the descendant
336 if ( get_class( $this ) == 'Language' ) {
339 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
341 self
::getLocalisationCache();
345 * Reduce memory usage
347 function __destruct() {
348 foreach ( $this as $name => $value ) {
349 unset( $this->$name );
354 * Hook which will be called if this is the content language.
355 * Descendants can use this to register hook functions or modify globals
357 function initContLang() { }
360 * Same as getFallbacksFor for current language.
362 * @deprecated in 1.19
364 function getFallbackLanguageCode() {
365 wfDeprecated( __METHOD__
, '1.19' );
366 return self
::getFallbackFor( $this->mCode
);
373 function getFallbackLanguages() {
374 return self
::getFallbacksFor( $this->mCode
);
378 * Exports $wgBookstoreListEn
381 function getBookstoreList() {
382 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
388 public function getNamespaces() {
389 if ( is_null( $this->namespaceNames
) ) {
390 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
392 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
393 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
395 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
397 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
398 if ( $wgMetaNamespaceTalk ) {
399 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
401 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
402 $this->namespaceNames
[NS_PROJECT_TALK
] =
403 $this->fixVariableInNamespace( $talk );
406 # Sometimes a language will be localised but not actually exist on this wiki.
407 foreach ( $this->namespaceNames
as $key => $text ) {
408 if ( !isset( $validNamespaces[$key] ) ) {
409 unset( $this->namespaceNames
[$key] );
413 # The above mixing may leave namespaces out of canonical order.
414 # Re-order by namespace ID number...
415 ksort( $this->namespaceNames
);
417 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
419 return $this->namespaceNames
;
423 * Arbitrarily set all of the namespace names at once. Mainly used for testing
424 * @param $namespaces Array of namespaces (id => name)
426 public function setNamespaces( array $namespaces ) {
427 $this->namespaceNames
= $namespaces;
428 $this->mNamespaceIds
= null;
432 * Resets all of the namespace caches. Mainly used for testing
434 public function resetNamespaces( ) {
435 $this->namespaceNames
= null;
436 $this->mNamespaceIds
= null;
437 $this->namespaceAliases
= null;
441 * A convenience function that returns the same thing as
442 * getNamespaces() except with the array values changed to ' '
443 * where it found '_', useful for producing output to be displayed
444 * e.g. in <select> forms.
448 function getFormattedNamespaces() {
449 $ns = $this->getNamespaces();
450 foreach ( $ns as $k => $v ) {
451 $ns[$k] = strtr( $v, '_', ' ' );
457 * Get a namespace value by key
459 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
460 * echo $mw_ns; // prints 'MediaWiki'
463 * @param $index Int: the array key of the namespace to return
464 * @return mixed, string if the namespace value exists, otherwise false
466 function getNsText( $index ) {
467 $ns = $this->getNamespaces();
468 return isset( $ns[$index] ) ?
$ns[$index] : false;
472 * A convenience function that returns the same thing as
473 * getNsText() except with '_' changed to ' ', useful for
477 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
478 * echo $mw_ns; // prints 'MediaWiki talk'
481 * @param int $index The array key of the namespace to return
482 * @return string Namespace name without underscores (empty string if namespace does not exist)
484 function getFormattedNsText( $index ) {
485 $ns = $this->getNsText( $index );
486 return strtr( $ns, '_', ' ' );
490 * Returns gender-dependent namespace alias if available.
491 * @param $index Int: namespace index
492 * @param $gender String: gender key (male, female... )
496 function getGenderNsText( $index, $gender ) {
497 global $wgExtraGenderNamespaces;
499 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
500 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
504 * Whether this language makes distinguishes genders for example in
509 function needsGenderDistinction() {
510 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
511 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
512 // $wgExtraGenderNamespaces overrides everything
514 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
515 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
516 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
519 // Check what is in i18n files
520 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
521 return count( $aliases ) > 0;
526 * Get a namespace key by value, case insensitive.
527 * Only matches namespace names for the current language, not the
528 * canonical ones defined in Namespace.php.
530 * @param $text String
531 * @return mixed An integer if $text is a valid value otherwise false
533 function getLocalNsIndex( $text ) {
534 $lctext = $this->lc( $text );
535 $ids = $this->getNamespaceIds();
536 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
542 function getNamespaceAliases() {
543 if ( is_null( $this->namespaceAliases
) ) {
544 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
548 foreach ( $aliases as $name => $index ) {
549 if ( $index === NS_PROJECT_TALK
) {
550 unset( $aliases[$name] );
551 $name = $this->fixVariableInNamespace( $name );
552 $aliases[$name] = $index;
557 global $wgExtraGenderNamespaces;
558 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
559 foreach ( $genders as $index => $forms ) {
560 foreach ( $forms as $alias ) {
561 $aliases[$alias] = $index;
565 $this->namespaceAliases
= $aliases;
567 return $this->namespaceAliases
;
573 function getNamespaceIds() {
574 if ( is_null( $this->mNamespaceIds
) ) {
575 global $wgNamespaceAliases;
576 # Put namespace names and aliases into a hashtable.
577 # If this is too slow, then we should arrange it so that it is done
578 # before caching. The catch is that at pre-cache time, the above
579 # class-specific fixup hasn't been done.
580 $this->mNamespaceIds
= array();
581 foreach ( $this->getNamespaces() as $index => $name ) {
582 $this->mNamespaceIds
[$this->lc( $name )] = $index;
584 foreach ( $this->getNamespaceAliases() as $name => $index ) {
585 $this->mNamespaceIds
[$this->lc( $name )] = $index;
587 if ( $wgNamespaceAliases ) {
588 foreach ( $wgNamespaceAliases as $name => $index ) {
589 $this->mNamespaceIds
[$this->lc( $name )] = $index;
593 return $this->mNamespaceIds
;
597 * Get a namespace key by value, case insensitive. Canonical namespace
598 * names override custom ones defined for the current language.
600 * @param $text String
601 * @return mixed An integer if $text is a valid value otherwise false
603 function getNsIndex( $text ) {
604 $lctext = $this->lc( $text );
605 $ns = MWNamespace
::getCanonicalIndex( $lctext );
606 if ( $ns !== null ) {
609 $ids = $this->getNamespaceIds();
610 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
614 * short names for language variants used for language conversion links.
616 * @param $code String
617 * @param $usemsg bool Use the "variantname-xyz" message if it exists
620 function getVariantname( $code, $usemsg = true ) {
621 $msg = "variantname-$code";
622 if ( $usemsg && wfMessage( $msg )->exists() ) {
623 return $this->getMessageFromDB( $msg );
625 $name = self
::fetchLanguageName( $code );
627 return $name; # if it's defined as a language name, show that
629 # otherwise, output the language code
635 * @param $name string
638 function specialPage( $name ) {
639 $aliases = $this->getSpecialPageAliases();
640 if ( isset( $aliases[$name][0] ) ) {
641 $name = $aliases[$name][0];
643 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
649 function getQuickbarSettings() {
651 $this->getMessage( 'qbsettings-none' ),
652 $this->getMessage( 'qbsettings-fixedleft' ),
653 $this->getMessage( 'qbsettings-fixedright' ),
654 $this->getMessage( 'qbsettings-floatingleft' ),
655 $this->getMessage( 'qbsettings-floatingright' ),
656 $this->getMessage( 'qbsettings-directionality' )
663 function getDatePreferences() {
664 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
670 function getDateFormats() {
671 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
675 * @return array|string
677 function getDefaultDateFormat() {
678 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
679 if ( $df === 'dmy or mdy' ) {
680 global $wgAmericanDates;
681 return $wgAmericanDates ?
'mdy' : 'dmy';
690 function getDatePreferenceMigrationMap() {
691 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
698 function getImageFile( $image ) {
699 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
705 function getExtraUserToggles() {
706 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
713 function getUserToggle( $tog ) {
714 return $this->getMessageFromDB( "tog-$tog" );
718 * Get native language names, indexed by code.
719 * Only those defined in MediaWiki, no other data like CLDR.
720 * If $customisedOnly is true, only returns codes with a messages file
722 * @param $customisedOnly bool
725 * @deprecated in 1.20, use fetchLanguageNames()
727 public static function getLanguageNames( $customisedOnly = false ) {
728 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
732 * Get translated language names. This is done on best effort and
733 * by default this is exactly the same as Language::getLanguageNames.
734 * The CLDR extension provides translated names.
735 * @param $code String Language code.
736 * @return Array language code => language name
738 * @deprecated in 1.20, use fetchLanguageNames()
740 public static function getTranslatedLanguageNames( $code ) {
741 return self
::fetchLanguageNames( $code, 'all' );
745 * Get an array of language names, indexed by code.
746 * @param $inLanguage null|string: Code of language in which to return the names
747 * Use null for autonyms (native names)
748 * @param $include string:
749 * 'all' all available languages
750 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
751 * 'mwfile' only if the language is in 'mw' *and* has a message file
752 * @return array: language code => language name
755 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
756 global $wgExtraLanguageNames;
757 static $coreLanguageNames;
759 if ( $coreLanguageNames === null ) {
760 include( MWInit
::compiledPath( 'languages/Names.php' ) );
766 # TODO: also include when $inLanguage is null, when this code is more efficient
767 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
770 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
771 foreach ( $mwNames as $mwCode => $mwName ) {
772 # - Prefer own MediaWiki native name when not using the hook
773 # - For other names just add if not added through the hook
774 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
775 $names[$mwCode] = $mwName;
779 if ( $include === 'all' ) {
784 $coreCodes = array_keys( $mwNames );
785 foreach ( $coreCodes as $coreCode ) {
786 $returnMw[$coreCode] = $names[$coreCode];
789 if ( $include === 'mwfile' ) {
790 $namesMwFile = array();
791 # We do this using a foreach over the codes instead of a directory
792 # loop so that messages files in extensions will work correctly.
793 foreach ( $returnMw as $code => $value ) {
794 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
795 $namesMwFile[$code] = $names[$code];
800 # 'mw' option; default if it's not one of the other two options (all/mwfile)
805 * @param $code string: The code of the language for which to get the name
806 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
807 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
808 * @return string: Language name or empty
811 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
812 $array = self
::fetchLanguageNames( $inLanguage, $include );
813 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
817 * Get a message from the MediaWiki namespace.
819 * @param $msg String: message name
822 function getMessageFromDB( $msg ) {
823 return wfMessage( $msg )->inLanguage( $this )->text();
827 * Get the native language name of $code.
828 * Only if defined in MediaWiki, no other data like CLDR.
829 * @param $code string
831 * @deprecated in 1.20, use fetchLanguageName()
833 function getLanguageName( $code ) {
834 return self
::fetchLanguageName( $code );
841 function getMonthName( $key ) {
842 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
848 function getMonthNamesArray() {
849 $monthNames = array( '' );
850 for ( $i = 1; $i < 13; $i++
) {
851 $monthNames[] = $this->getMonthName( $i );
860 function getMonthNameGen( $key ) {
861 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
868 function getMonthAbbreviation( $key ) {
869 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
875 function getMonthAbbreviationsArray() {
876 $monthNames = array( '' );
877 for ( $i = 1; $i < 13; $i++
) {
878 $monthNames[] = $this->getMonthAbbreviation( $i );
887 function getWeekdayName( $key ) {
888 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
895 function getWeekdayAbbreviation( $key ) {
896 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
903 function getIranianCalendarMonthName( $key ) {
904 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
911 function getHebrewCalendarMonthName( $key ) {
912 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
919 function getHebrewCalendarMonthNameGen( $key ) {
920 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
927 function getHijriCalendarMonthName( $key ) {
928 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
932 * This is a workalike of PHP's date() function, but with better
933 * internationalisation, a reduced set of format characters, and a better
936 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
937 * PHP manual for definitions. There are a number of extensions, which
940 * xn Do not translate digits of the next numeric format character
941 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
942 * xr Use roman numerals for the next numeric format character
943 * xh Use hebrew numerals for the next numeric format character
945 * xg Genitive month name
947 * xij j (day number) in Iranian calendar
948 * xiF F (month name) in Iranian calendar
949 * xin n (month number) in Iranian calendar
950 * xiy y (two digit year) in Iranian calendar
951 * xiY Y (full year) in Iranian calendar
953 * xjj j (day number) in Hebrew calendar
954 * xjF F (month name) in Hebrew calendar
955 * xjt t (days in month) in Hebrew calendar
956 * xjx xg (genitive month name) in Hebrew calendar
957 * xjn n (month number) in Hebrew calendar
958 * xjY Y (full year) in Hebrew calendar
960 * xmj j (day number) in Hijri calendar
961 * xmF F (month name) in Hijri calendar
962 * xmn n (month number) in Hijri calendar
963 * xmY Y (full year) in Hijri calendar
965 * xkY Y (full year) in Thai solar calendar. Months and days are
966 * identical to the Gregorian calendar
967 * xoY Y (full year) in Minguo calendar or Juche year.
968 * Months and days are identical to the
970 * xtY Y (full year) in Japanese nengo. Months and days are
971 * identical to the Gregorian calendar
973 * Characters enclosed in double quotes will be considered literal (with
974 * the quotes themselves removed). Unmatched quotes will be considered
975 * literal quotes. Example:
977 * "The month is" F => The month is January
980 * Backslash escaping is also supported.
982 * Input timestamp is assumed to be pre-normalized to the desired local
985 * @param $format String
986 * @param $ts String: 14-character timestamp
989 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
993 function sprintfDate( $format, $ts ) {
1006 for ( $p = 0; $p < strlen( $format ); $p++
) {
1008 $code = $format[$p];
1009 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1010 $code .= $format[++
$p];
1013 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1014 $code .= $format[++
$p];
1025 $rawToggle = !$rawToggle;
1034 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1037 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1038 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1041 $num = substr( $ts, 6, 2 );
1044 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1045 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1048 $num = intval( substr( $ts, 6, 2 ) );
1052 $iranian = self
::tsToIranian( $ts );
1058 $hijri = self
::tsToHijri( $ts );
1064 $hebrew = self
::tsToHebrew( $ts );
1070 $unix = wfTimestamp( TS_UNIX
, $ts );
1072 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1076 $unix = wfTimestamp( TS_UNIX
, $ts );
1078 $w = gmdate( 'w', $unix );
1083 $unix = wfTimestamp( TS_UNIX
, $ts );
1085 $num = gmdate( 'w', $unix );
1089 $unix = wfTimestamp( TS_UNIX
, $ts );
1091 $num = gmdate( 'z', $unix );
1095 $unix = wfTimestamp( TS_UNIX
, $ts );
1097 $num = gmdate( 'W', $unix );
1100 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1104 $iranian = self
::tsToIranian( $ts );
1106 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1110 $hijri = self
::tsToHijri( $ts );
1112 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1116 $hebrew = self
::tsToHebrew( $ts );
1118 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1121 $num = substr( $ts, 4, 2 );
1124 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1127 $num = intval( substr( $ts, 4, 2 ) );
1131 $iranian = self
::tsToIranian( $ts );
1137 $hijri = self
::tsToHijri ( $ts );
1143 $hebrew = self
::tsToHebrew( $ts );
1149 $unix = wfTimestamp( TS_UNIX
, $ts );
1151 $num = gmdate( 't', $unix );
1155 $hebrew = self
::tsToHebrew( $ts );
1161 $unix = wfTimestamp( TS_UNIX
, $ts );
1163 $num = gmdate( 'L', $unix );
1167 $unix = wfTimestamp( TS_UNIX
, $ts );
1169 $num = gmdate( 'o', $unix );
1172 $num = substr( $ts, 0, 4 );
1176 $iranian = self
::tsToIranian( $ts );
1182 $hijri = self
::tsToHijri( $ts );
1188 $hebrew = self
::tsToHebrew( $ts );
1194 $thai = self
::tsToYear( $ts, 'thai' );
1200 $minguo = self
::tsToYear( $ts, 'minguo' );
1206 $tenno = self
::tsToYear( $ts, 'tenno' );
1211 $num = substr( $ts, 2, 2 );
1215 $iranian = self
::tsToIranian( $ts );
1217 $num = substr( $iranian[0], -2 );
1220 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1223 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1226 $h = substr( $ts, 8, 2 );
1227 $num = $h %
12 ?
$h %
12 : 12;
1230 $num = intval( substr( $ts, 8, 2 ) );
1233 $h = substr( $ts, 8, 2 );
1234 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1237 $num = substr( $ts, 8, 2 );
1240 $num = substr( $ts, 10, 2 );
1243 $num = substr( $ts, 12, 2 );
1247 $unix = wfTimestamp( TS_UNIX
, $ts );
1249 $s .= gmdate( 'c', $unix );
1253 $unix = wfTimestamp( TS_UNIX
, $ts );
1255 $s .= gmdate( 'r', $unix );
1259 $unix = wfTimestamp( TS_UNIX
, $ts );
1264 # Backslash escaping
1265 if ( $p < strlen( $format ) - 1 ) {
1266 $s .= $format[++
$p];
1273 if ( $p < strlen( $format ) - 1 ) {
1274 $endQuote = strpos( $format, '"', $p +
1 );
1275 if ( $endQuote === false ) {
1276 # No terminating quote, assume literal "
1279 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1283 # Quote at end of string, assume literal "
1290 if ( $num !== false ) {
1291 if ( $rawToggle ||
$raw ) {
1294 } elseif ( $roman ) {
1295 $s .= Language
::romanNumeral( $num );
1297 } elseif ( $hebrewNum ) {
1298 $s .= self
::hebrewNumeral( $num );
1301 $s .= $this->formatNum( $num, true );
1308 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1309 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1312 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1313 * Gregorian dates to Iranian dates. Originally written in C, it
1314 * is released under the terms of GNU Lesser General Public
1315 * License. Conversion to PHP was performed by Niklas Laxström.
1317 * Link: http://www.farsiweb.info/jalali/jalali.c
1323 private static function tsToIranian( $ts ) {
1324 $gy = substr( $ts, 0, 4 ) -1600;
1325 $gm = substr( $ts, 4, 2 ) -1;
1326 $gd = substr( $ts, 6, 2 ) -1;
1328 # Days passed from the beginning (including leap years)
1330 +
floor( ( $gy +
3 ) / 4 )
1331 - floor( ( $gy +
99 ) / 100 )
1332 +
floor( ( $gy +
399 ) / 400 );
1334 // Add days of the past months of this year
1335 for ( $i = 0; $i < $gm; $i++
) {
1336 $gDayNo +
= self
::$GREG_DAYS[$i];
1340 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1344 // Days passed in current month
1345 $gDayNo +
= (int)$gd;
1347 $jDayNo = $gDayNo - 79;
1349 $jNp = floor( $jDayNo / 12053 );
1352 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1355 if ( $jDayNo >= 366 ) {
1356 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1357 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1360 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1361 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1367 return array( $jy, $jm, $jd );
1371 * Converting Gregorian dates to Hijri dates.
1373 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1375 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1381 private static function tsToHijri( $ts ) {
1382 $year = substr( $ts, 0, 4 );
1383 $month = substr( $ts, 4, 2 );
1384 $day = substr( $ts, 6, 2 );
1392 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1393 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1396 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1397 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1398 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1401 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1402 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1405 $zl = $zjd -1948440 +
10632;
1406 $zn = (int)( ( $zl - 1 ) / 10631 );
1407 $zl = $zl - 10631 * $zn +
354;
1408 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1409 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1410 $zm = (int)( ( 24 * $zl ) / 709 );
1411 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1412 $zy = 30 * $zn +
$zj - 30;
1414 return array( $zy, $zm, $zd );
1418 * Converting Gregorian dates to Hebrew dates.
1420 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1421 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1422 * to translate the relevant functions into PHP and release them under
1425 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1426 * and Adar II is 14. In a non-leap year, Adar is 6.
1432 private static function tsToHebrew( $ts ) {
1434 $year = substr( $ts, 0, 4 );
1435 $month = substr( $ts, 4, 2 );
1436 $day = substr( $ts, 6, 2 );
1438 # Calculate Hebrew year
1439 $hebrewYear = $year +
3760;
1441 # Month number when September = 1, August = 12
1443 if ( $month > 12 ) {
1450 # Calculate day of year from 1 September
1452 for ( $i = 1; $i < $month; $i++
) {
1456 # Check if the year is leap
1457 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1460 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1467 # Calculate the start of the Hebrew year
1468 $start = self
::hebrewYearStart( $hebrewYear );
1470 # Calculate next year's start
1471 if ( $dayOfYear <= $start ) {
1472 # Day is before the start of the year - it is the previous year
1474 $nextStart = $start;
1478 # Add days since previous year's 1 September
1480 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1484 # Start of the new (previous) year
1485 $start = self
::hebrewYearStart( $hebrewYear );
1488 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1491 # Calculate Hebrew day of year
1492 $hebrewDayOfYear = $dayOfYear - $start;
1494 # Difference between year's days
1495 $diff = $nextStart - $start;
1496 # Add 12 (or 13 for leap years) days to ignore the difference between
1497 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1498 # difference is only about the year type
1499 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1505 # Check the year pattern, and is leap year
1506 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1507 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1508 # and non-leap years
1509 $yearPattern = $diff %
30;
1510 # Check if leap year
1511 $isLeap = $diff >= 30;
1513 # Calculate day in the month from number of day in the Hebrew year
1514 # Don't check Adar - if the day is not in Adar, we will stop before;
1515 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1516 $hebrewDay = $hebrewDayOfYear;
1519 while ( $hebrewMonth <= 12 ) {
1520 # Calculate days in this month
1521 if ( $isLeap && $hebrewMonth == 6 ) {
1522 # Adar in a leap year
1524 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1526 if ( $hebrewDay <= $days ) {
1530 # Subtract the days of Adar I
1531 $hebrewDay -= $days;
1534 if ( $hebrewDay <= $days ) {
1540 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1541 # Cheshvan in a complete year (otherwise as the rule below)
1543 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1544 # Kislev in an incomplete year (otherwise as the rule below)
1547 # Odd months have 30 days, even have 29
1548 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1550 if ( $hebrewDay <= $days ) {
1551 # In the current month
1554 # Subtract the days of the current month
1555 $hebrewDay -= $days;
1556 # Try in the next month
1561 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1565 * This calculates the Hebrew year start, as days since 1 September.
1566 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1567 * Used for Hebrew date.
1573 private static function hebrewYearStart( $year ) {
1574 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1575 $b = intval( ( $year - 1 ) %
4 );
1576 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1580 $Mar = intval( $m );
1586 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1587 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1589 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1591 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1595 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1600 * Algorithm to convert Gregorian dates to Thai solar dates,
1601 * Minguo dates or Minguo dates.
1603 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1604 * http://en.wikipedia.org/wiki/Minguo_calendar
1605 * http://en.wikipedia.org/wiki/Japanese_era_name
1607 * @param $ts String: 14-character timestamp
1608 * @param $cName String: calender name
1609 * @return Array: converted year, month, day
1611 private static function tsToYear( $ts, $cName ) {
1612 $gy = substr( $ts, 0, 4 );
1613 $gm = substr( $ts, 4, 2 );
1614 $gd = substr( $ts, 6, 2 );
1616 if ( !strcmp( $cName, 'thai' ) ) {
1618 # Add 543 years to the Gregorian calendar
1619 # Months and days are identical
1620 $gy_offset = $gy +
543;
1621 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1623 # Deduct 1911 years from the Gregorian calendar
1624 # Months and days are identical
1625 $gy_offset = $gy - 1911;
1626 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1627 # Nengō dates up to Meiji period
1628 # Deduct years from the Gregorian calendar
1629 # depending on the nengo periods
1630 # Months and days are identical
1631 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1633 $gy_gannen = $gy - 1868 +
1;
1634 $gy_offset = $gy_gannen;
1635 if ( $gy_gannen == 1 ) {
1638 $gy_offset = '明治' . $gy_offset;
1640 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1641 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1642 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1643 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1644 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1648 $gy_gannen = $gy - 1912 +
1;
1649 $gy_offset = $gy_gannen;
1650 if ( $gy_gannen == 1 ) {
1653 $gy_offset = '大正' . $gy_offset;
1655 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1656 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1657 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1661 $gy_gannen = $gy - 1926 +
1;
1662 $gy_offset = $gy_gannen;
1663 if ( $gy_gannen == 1 ) {
1666 $gy_offset = '昭和' . $gy_offset;
1669 $gy_gannen = $gy - 1989 +
1;
1670 $gy_offset = $gy_gannen;
1671 if ( $gy_gannen == 1 ) {
1674 $gy_offset = '平成' . $gy_offset;
1680 return array( $gy_offset, $gm, $gd );
1684 * Roman number formatting up to 10000
1690 static function romanNumeral( $num ) {
1691 static $table = array(
1692 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1693 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1694 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1695 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1698 $num = intval( $num );
1699 if ( $num > 10000 ||
$num <= 0 ) {
1704 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1705 if ( $num >= $pow10 ) {
1706 $s .= $table[$i][(int)floor( $num / $pow10 )];
1708 $num = $num %
$pow10;
1714 * Hebrew Gematria number formatting up to 9999
1720 static function hebrewNumeral( $num ) {
1721 static $table = array(
1722 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1723 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1724 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1725 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1728 $num = intval( $num );
1729 if ( $num > 9999 ||
$num <= 0 ) {
1734 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1735 if ( $num >= $pow10 ) {
1736 if ( $num == 15 ||
$num == 16 ) {
1737 $s .= $table[0][9] . $table[0][$num - 9];
1740 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1741 if ( $pow10 == 1000 ) {
1746 $num = $num %
$pow10;
1748 if ( strlen( $s ) == 2 ) {
1751 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1752 $str .= substr( $s, strlen( $s ) - 2, 2 );
1754 $start = substr( $str, 0, strlen( $str ) - 2 );
1755 $end = substr( $str, strlen( $str ) - 2 );
1758 $str = $start . 'ך';
1761 $str = $start . 'ם';
1764 $str = $start . 'ן';
1767 $str = $start . 'ף';
1770 $str = $start . 'ץ';
1777 * Used by date() and time() to adjust the time output.
1779 * @param $ts Int the time in date('YmdHis') format
1780 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1781 * get user timecorrection setting)
1784 function userAdjust( $ts, $tz = false ) {
1785 global $wgUser, $wgLocalTZoffset;
1787 if ( $tz === false ) {
1788 $tz = $wgUser->getOption( 'timecorrection' );
1791 $data = explode( '|', $tz, 3 );
1793 if ( $data[0] == 'ZoneInfo' ) {
1794 wfSuppressWarnings();
1795 $userTZ = timezone_open( $data[2] );
1796 wfRestoreWarnings();
1797 if ( $userTZ !== false ) {
1798 $date = date_create( $ts, timezone_open( 'UTC' ) );
1799 date_timezone_set( $date, $userTZ );
1800 $date = date_format( $date, 'YmdHis' );
1803 # Unrecognized timezone, default to 'Offset' with the stored offset.
1804 $data[0] = 'Offset';
1808 if ( $data[0] == 'System' ||
$tz == '' ) {
1809 # Global offset in minutes.
1810 if ( isset( $wgLocalTZoffset ) ) {
1811 $minDiff = $wgLocalTZoffset;
1813 } elseif ( $data[0] == 'Offset' ) {
1814 $minDiff = intval( $data[1] );
1816 $data = explode( ':', $tz );
1817 if ( count( $data ) == 2 ) {
1818 $data[0] = intval( $data[0] );
1819 $data[1] = intval( $data[1] );
1820 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1821 if ( $data[0] < 0 ) {
1822 $minDiff = -$minDiff;
1825 $minDiff = intval( $data[0] ) * 60;
1829 # No difference ? Return time unchanged
1830 if ( 0 == $minDiff ) {
1834 wfSuppressWarnings(); // E_STRICT system time bitching
1835 # Generate an adjusted date; take advantage of the fact that mktime
1836 # will normalize out-of-range values so we don't have to split $minDiff
1837 # into hours and minutes.
1839 (int)substr( $ts, 8, 2 ) ), # Hours
1840 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1841 (int)substr( $ts, 12, 2 ), # Seconds
1842 (int)substr( $ts, 4, 2 ), # Month
1843 (int)substr( $ts, 6, 2 ), # Day
1844 (int)substr( $ts, 0, 4 ) ); # Year
1846 $date = date( 'YmdHis', $t );
1847 wfRestoreWarnings();
1853 * This is meant to be used by time(), date(), and timeanddate() to get
1854 * the date preference they're supposed to use, it should be used in
1858 * function timeanddate([...], $format = true) {
1859 * $datePreference = $this->dateFormat($format);
1864 * @param $usePrefs Mixed: if true, the user's preference is used
1865 * if false, the site/language default is used
1866 * if int/string, assumed to be a format.
1869 function dateFormat( $usePrefs = true ) {
1872 if ( is_bool( $usePrefs ) ) {
1874 $datePreference = $wgUser->getDatePreference();
1876 $datePreference = (string)User
::getDefaultOption( 'date' );
1879 $datePreference = (string)$usePrefs;
1883 if ( $datePreference == '' ) {
1887 return $datePreference;
1891 * Get a format string for a given type and preference
1892 * @param $type string May be date, time or both
1893 * @param $pref string The format name as it appears in Messages*.php
1897 function getDateFormatString( $type, $pref ) {
1898 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1899 if ( $pref == 'default' ) {
1900 $pref = $this->getDefaultDateFormat();
1901 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1903 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1904 if ( is_null( $df ) ) {
1905 $pref = $this->getDefaultDateFormat();
1906 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1909 $this->dateFormatStrings
[$type][$pref] = $df;
1911 return $this->dateFormatStrings
[$type][$pref];
1915 * @param $ts Mixed: the time format which needs to be turned into a
1916 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1917 * @param $adj Bool: whether to adjust the time output according to the
1918 * user configured offset ($timecorrection)
1919 * @param $format Mixed: true to use user's date format preference
1920 * @param $timecorrection String|bool the time offset as returned by
1921 * validateTimeZone() in Special:Preferences
1924 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1925 $ts = wfTimestamp( TS_MW
, $ts );
1927 $ts = $this->userAdjust( $ts, $timecorrection );
1929 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1930 return $this->sprintfDate( $df, $ts );
1934 * @param $ts Mixed: the time format which needs to be turned into a
1935 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1936 * @param $adj Bool: whether to adjust the time output according to the
1937 * user configured offset ($timecorrection)
1938 * @param $format Mixed: true to use user's date format preference
1939 * @param $timecorrection String|bool the time offset as returned by
1940 * validateTimeZone() in Special:Preferences
1943 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1944 $ts = wfTimestamp( TS_MW
, $ts );
1946 $ts = $this->userAdjust( $ts, $timecorrection );
1948 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1949 return $this->sprintfDate( $df, $ts );
1953 * @param $ts Mixed: the time format which needs to be turned into a
1954 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1955 * @param $adj Bool: whether to adjust the time output according to the
1956 * user configured offset ($timecorrection)
1957 * @param $format Mixed: what format to return, if it's false output the
1958 * default one (default true)
1959 * @param $timecorrection String|bool the time offset as returned by
1960 * validateTimeZone() in Special:Preferences
1963 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1964 $ts = wfTimestamp( TS_MW
, $ts );
1966 $ts = $this->userAdjust( $ts, $timecorrection );
1968 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1969 return $this->sprintfDate( $df, $ts );
1973 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1977 * @param integer $seconds The amount of seconds.
1978 * @param array $chosenIntervals The intervals to enable.
1982 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1983 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1985 $segments = array();
1987 foreach ( $intervals as $intervalName => $intervalValue ) {
1988 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1989 $segments[] = $message->inLanguage( $this )->escaped();
1992 return $this->listToText( $segments );
1996 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1997 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2001 * @param integer $seconds The amount of seconds.
2002 * @param array $chosenIntervals The intervals to enable.
2006 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2007 if ( empty( $chosenIntervals ) ) {
2008 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2011 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2012 $sortedNames = array_keys( $intervals );
2013 $smallestInterval = array_pop( $sortedNames );
2015 $segments = array();
2017 foreach ( $intervals as $name => $length ) {
2018 $value = floor( $seconds / $length );
2020 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2021 $seconds -= $value * $length;
2022 $segments[$name] = $value;
2030 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2032 * @param $type String: can be 'date', 'time' or 'both'
2033 * @param $ts Mixed: the time format which needs to be turned into a
2034 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2035 * @param $user User object used to get preferences for timezone and format
2036 * @param $options Array, can contain the following keys:
2037 * - 'timecorrection': time correction, can have the following values:
2038 * - true: use user's preference
2039 * - false: don't use time correction
2040 * - integer: value of time correction in minutes
2041 * - 'format': format to use, can have the following values:
2042 * - true: use user's preference
2043 * - false: use default preference
2044 * - string: format to use
2048 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2049 $ts = wfTimestamp( TS_MW
, $ts );
2050 $options +
= array( 'timecorrection' => true, 'format' => true );
2051 if ( $options['timecorrection'] !== false ) {
2052 if ( $options['timecorrection'] === true ) {
2053 $offset = $user->getOption( 'timecorrection' );
2055 $offset = $options['timecorrection'];
2057 $ts = $this->userAdjust( $ts, $offset );
2059 if ( $options['format'] === true ) {
2060 $format = $user->getDatePreference();
2062 $format = $options['format'];
2064 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2065 return $this->sprintfDate( $df, $ts );
2069 * Get the formatted date for the given timestamp and formatted for
2072 * @param $ts Mixed: the time format which needs to be turned into a
2073 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2074 * @param $user User object used to get preferences for timezone and format
2075 * @param $options Array, can contain the following keys:
2076 * - 'timecorrection': time correction, can have the following values:
2077 * - true: use user's preference
2078 * - false: don't use time correction
2079 * - integer: value of time correction in minutes
2080 * - 'format': format to use, can have the following values:
2081 * - true: use user's preference
2082 * - false: use default preference
2083 * - string: format to use
2087 public function userDate( $ts, User
$user, array $options = array() ) {
2088 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2092 * Get the formatted time for the given timestamp and formatted for
2095 * @param $ts Mixed: the time format which needs to be turned into a
2096 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2097 * @param $user User object used to get preferences for timezone and format
2098 * @param $options Array, can contain the following keys:
2099 * - 'timecorrection': time correction, can have the following values:
2100 * - true: use user's preference
2101 * - false: don't use time correction
2102 * - integer: value of time correction in minutes
2103 * - 'format': format to use, can have the following values:
2104 * - true: use user's preference
2105 * - false: use default preference
2106 * - string: format to use
2110 public function userTime( $ts, User
$user, array $options = array() ) {
2111 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2115 * Get the formatted date and time for the given timestamp and formatted for
2118 * @param $ts Mixed: the time format which needs to be turned into a
2119 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2120 * @param $user User object used to get preferences for timezone and format
2121 * @param $options Array, can contain the following keys:
2122 * - 'timecorrection': time correction, can have the following values:
2123 * - true: use user's preference
2124 * - false: don't use time correction
2125 * - integer: value of time correction in minutes
2126 * - 'format': format to use, can have the following values:
2127 * - true: use user's preference
2128 * - false: use default preference
2129 * - string: format to use
2133 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2134 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2138 * @param $key string
2139 * @return array|null
2141 function getMessage( $key ) {
2142 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2148 function getAllMessages() {
2149 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2158 function iconv( $in, $out, $string ) {
2159 # This is a wrapper for iconv in all languages except esperanto,
2160 # which does some nasty x-conversions beforehand
2162 # Even with //IGNORE iconv can whine about illegal characters in
2163 # *input* string. We just ignore those too.
2164 # REF: http://bugs.php.net/bug.php?id=37166
2165 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2166 wfSuppressWarnings();
2167 $text = iconv( $in, $out . '//IGNORE', $string );
2168 wfRestoreWarnings();
2172 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2175 * @param $matches array
2176 * @return mixed|string
2178 function ucwordbreaksCallbackAscii( $matches ) {
2179 return $this->ucfirst( $matches[1] );
2183 * @param $matches array
2186 function ucwordbreaksCallbackMB( $matches ) {
2187 return mb_strtoupper( $matches[0] );
2191 * @param $matches array
2194 function ucCallback( $matches ) {
2195 list( $wikiUpperChars ) = self
::getCaseMaps();
2196 return strtr( $matches[1], $wikiUpperChars );
2200 * @param $matches array
2203 function lcCallback( $matches ) {
2204 list( , $wikiLowerChars ) = self
::getCaseMaps();
2205 return strtr( $matches[1], $wikiLowerChars );
2209 * @param $matches array
2212 function ucwordsCallbackMB( $matches ) {
2213 return mb_strtoupper( $matches[0] );
2217 * @param $matches array
2220 function ucwordsCallbackWiki( $matches ) {
2221 list( $wikiUpperChars ) = self
::getCaseMaps();
2222 return strtr( $matches[0], $wikiUpperChars );
2226 * Make a string's first character uppercase
2228 * @param $str string
2232 function ucfirst( $str ) {
2234 if ( $o < 96 ) { // if already uppercase...
2236 } elseif ( $o < 128 ) {
2237 return ucfirst( $str ); // use PHP's ucfirst()
2239 // fall back to more complex logic in case of multibyte strings
2240 return $this->uc( $str, true );
2245 * Convert a string to uppercase
2247 * @param $str string
2248 * @param $first bool
2252 function uc( $str, $first = false ) {
2253 if ( function_exists( 'mb_strtoupper' ) ) {
2255 if ( $this->isMultibyte( $str ) ) {
2256 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2258 return ucfirst( $str );
2261 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2264 if ( $this->isMultibyte( $str ) ) {
2265 $x = $first ?
'^' : '';
2266 return preg_replace_callback(
2267 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2268 array( $this, 'ucCallback' ),
2272 return $first ?
ucfirst( $str ) : strtoupper( $str );
2278 * @param $str string
2279 * @return mixed|string
2281 function lcfirst( $str ) {
2284 return strval( $str );
2285 } elseif ( $o >= 128 ) {
2286 return $this->lc( $str, true );
2287 } elseif ( $o > 96 ) {
2290 $str[0] = strtolower( $str[0] );
2296 * @param $str string
2297 * @param $first bool
2298 * @return mixed|string
2300 function lc( $str, $first = false ) {
2301 if ( function_exists( 'mb_strtolower' ) ) {
2303 if ( $this->isMultibyte( $str ) ) {
2304 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2306 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2309 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2312 if ( $this->isMultibyte( $str ) ) {
2313 $x = $first ?
'^' : '';
2314 return preg_replace_callback(
2315 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2316 array( $this, 'lcCallback' ),
2320 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2326 * @param $str string
2329 function isMultibyte( $str ) {
2330 return (bool)preg_match( '/[\x80-\xff]/', $str );
2334 * @param $str string
2335 * @return mixed|string
2337 function ucwords( $str ) {
2338 if ( $this->isMultibyte( $str ) ) {
2339 $str = $this->lc( $str );
2341 // regexp to find first letter in each word (i.e. after each space)
2342 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2344 // function to use to capitalize a single char
2345 if ( function_exists( 'mb_strtoupper' ) ) {
2346 return preg_replace_callback(
2348 array( $this, 'ucwordsCallbackMB' ),
2352 return preg_replace_callback(
2354 array( $this, 'ucwordsCallbackWiki' ),
2359 return ucwords( strtolower( $str ) );
2364 * capitalize words at word breaks
2366 * @param $str string
2369 function ucwordbreaks( $str ) {
2370 if ( $this->isMultibyte( $str ) ) {
2371 $str = $this->lc( $str );
2373 // since \b doesn't work for UTF-8, we explicitely define word break chars
2374 $breaks = "[ \-\(\)\}\{\.,\?!]";
2376 // find first letter after word break
2377 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2379 if ( function_exists( 'mb_strtoupper' ) ) {
2380 return preg_replace_callback(
2382 array( $this, 'ucwordbreaksCallbackMB' ),
2386 return preg_replace_callback(
2388 array( $this, 'ucwordsCallbackWiki' ),
2393 return preg_replace_callback(
2394 '/\b([\w\x80-\xff]+)\b/',
2395 array( $this, 'ucwordbreaksCallbackAscii' ),
2402 * Return a case-folded representation of $s
2404 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2405 * and $s2 are the same except for the case of their characters. It is not
2406 * necessary for the value returned to make sense when displayed.
2408 * Do *not* perform any other normalisation in this function. If a caller
2409 * uses this function when it should be using a more general normalisation
2410 * function, then fix the caller.
2416 function caseFold( $s ) {
2417 return $this->uc( $s );
2424 function checkTitleEncoding( $s ) {
2425 if ( is_array( $s ) ) {
2426 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2428 # Check for non-UTF-8 URLs
2429 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2434 if ( function_exists( 'mb_check_encoding' ) ) {
2435 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2437 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2438 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2444 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2450 function fallback8bitEncoding() {
2451 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2455 * Most writing systems use whitespace to break up words.
2456 * Some languages such as Chinese don't conventionally do this,
2457 * which requires special handling when breaking up words for
2462 function hasWordBreaks() {
2467 * Some languages such as Chinese require word segmentation,
2468 * Specify such segmentation when overridden in derived class.
2470 * @param $string String
2473 function segmentByWord( $string ) {
2478 * Some languages have special punctuation need to be normalized.
2479 * Make such changes here.
2481 * @param $string String
2484 function normalizeForSearch( $string ) {
2485 return self
::convertDoubleWidth( $string );
2489 * convert double-width roman characters to single-width.
2490 * range: ff00-ff5f ~= 0020-007f
2492 * @param $string string
2496 protected static function convertDoubleWidth( $string ) {
2497 static $full = null;
2498 static $half = null;
2500 if ( $full === null ) {
2501 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2502 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2503 $full = str_split( $fullWidth, 3 );
2504 $half = str_split( $halfWidth );
2507 $string = str_replace( $full, $half, $string );
2512 * @param $string string
2513 * @param $pattern string
2516 protected static function insertSpace( $string, $pattern ) {
2517 $string = preg_replace( $pattern, " $1 ", $string );
2518 $string = preg_replace( '/ +/', ' ', $string );
2523 * @param $termsArray array
2526 function convertForSearchResult( $termsArray ) {
2527 # some languages, e.g. Chinese, need to do a conversion
2528 # in order for search results to be displayed correctly
2533 * Get the first character of a string.
2538 function firstChar( $s ) {
2541 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2542 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2547 if ( isset( $matches[1] ) ) {
2548 if ( strlen( $matches[1] ) != 3 ) {
2552 // Break down Hangul syllables to grab the first jamo
2553 $code = utf8ToCodepoint( $matches[1] );
2554 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2556 } elseif ( $code < 0xb098 ) {
2557 return "\xe3\x84\xb1";
2558 } elseif ( $code < 0xb2e4 ) {
2559 return "\xe3\x84\xb4";
2560 } elseif ( $code < 0xb77c ) {
2561 return "\xe3\x84\xb7";
2562 } elseif ( $code < 0xb9c8 ) {
2563 return "\xe3\x84\xb9";
2564 } elseif ( $code < 0xbc14 ) {
2565 return "\xe3\x85\x81";
2566 } elseif ( $code < 0xc0ac ) {
2567 return "\xe3\x85\x82";
2568 } elseif ( $code < 0xc544 ) {
2569 return "\xe3\x85\x85";
2570 } elseif ( $code < 0xc790 ) {
2571 return "\xe3\x85\x87";
2572 } elseif ( $code < 0xcc28 ) {
2573 return "\xe3\x85\x88";
2574 } elseif ( $code < 0xce74 ) {
2575 return "\xe3\x85\x8a";
2576 } elseif ( $code < 0xd0c0 ) {
2577 return "\xe3\x85\x8b";
2578 } elseif ( $code < 0xd30c ) {
2579 return "\xe3\x85\x8c";
2580 } elseif ( $code < 0xd558 ) {
2581 return "\xe3\x85\x8d";
2583 return "\xe3\x85\x8e";
2590 function initEncoding() {
2591 # Some languages may have an alternate char encoding option
2592 # (Esperanto X-coding, Japanese furigana conversion, etc)
2593 # If this language is used as the primary content language,
2594 # an override to the defaults can be set here on startup.
2601 function recodeForEdit( $s ) {
2602 # For some languages we'll want to explicitly specify
2603 # which characters make it into the edit box raw
2604 # or are converted in some way or another.
2605 global $wgEditEncoding;
2606 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2609 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2617 function recodeInput( $s ) {
2618 # Take the previous into account.
2619 global $wgEditEncoding;
2620 if ( $wgEditEncoding != '' ) {
2621 $enc = $wgEditEncoding;
2625 if ( $enc == 'UTF-8' ) {
2628 return $this->iconv( $enc, 'UTF-8', $s );
2633 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2634 * also cleans up certain backwards-compatible sequences, converting them
2635 * to the modern Unicode equivalent.
2637 * This is language-specific for performance reasons only.
2643 function normalize( $s ) {
2644 global $wgAllUnicodeFixes;
2645 $s = UtfNormal
::cleanUp( $s );
2646 if ( $wgAllUnicodeFixes ) {
2647 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2648 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2655 * Transform a string using serialized data stored in the given file (which
2656 * must be in the serialized subdirectory of $IP). The file contains pairs
2657 * mapping source characters to destination characters.
2659 * The data is cached in process memory. This will go faster if you have the
2660 * FastStringSearch extension.
2662 * @param $file string
2663 * @param $string string
2665 * @throws MWException
2668 function transformUsingPairFile( $file, $string ) {
2669 if ( !isset( $this->transformData
[$file] ) ) {
2670 $data = wfGetPrecompiledData( $file );
2671 if ( $data === false ) {
2672 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2674 $this->transformData
[$file] = new ReplacementArray( $data );
2676 return $this->transformData
[$file]->replace( $string );
2680 * For right-to-left language support
2685 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2689 * Return the correct HTML 'dir' attribute value for this language.
2693 return $this->isRTL() ?
'rtl' : 'ltr';
2697 * Return 'left' or 'right' as appropriate alignment for line-start
2698 * for this language's text direction.
2700 * Should be equivalent to CSS3 'start' text-align value....
2704 function alignStart() {
2705 return $this->isRTL() ?
'right' : 'left';
2709 * Return 'right' or 'left' as appropriate alignment for line-end
2710 * for this language's text direction.
2712 * Should be equivalent to CSS3 'end' text-align value....
2716 function alignEnd() {
2717 return $this->isRTL() ?
'left' : 'right';
2721 * A hidden direction mark (LRM or RLM), depending on the language direction.
2722 * Unlike getDirMark(), this function returns the character as an HTML entity.
2723 * This function should be used when the output is guaranteed to be HTML,
2724 * because it makes the output HTML source code more readable. When
2725 * the output is plain text or can be escaped, getDirMark() should be used.
2727 * @param $opposite Boolean Get the direction mark opposite to your language
2731 function getDirMarkEntity( $opposite = false ) {
2732 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2733 return $this->isRTL() ?
'‏' : '‎';
2737 * A hidden direction mark (LRM or RLM), depending on the language direction.
2738 * This function produces them as invisible Unicode characters and
2739 * the output may be hard to read and debug, so it should only be used
2740 * when the output is plain text or can be escaped. When the output is
2741 * HTML, use getDirMarkEntity() instead.
2743 * @param $opposite Boolean Get the direction mark opposite to your language
2746 function getDirMark( $opposite = false ) {
2747 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2748 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2749 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2750 return $this->isRTL() ?
$rlm : $lrm;
2756 function capitalizeAllNouns() {
2757 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2761 * An arrow, depending on the language direction.
2763 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2766 function getArrow( $direction = 'forwards' ) {
2767 switch ( $direction ) {
2769 return $this->isRTL() ?
'←' : '→';
2771 return $this->isRTL() ?
'→' : '←';
2784 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2788 function linkPrefixExtension() {
2789 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2795 function getMagicWords() {
2796 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2799 protected function doMagicHook() {
2800 if ( $this->mMagicHookDone
) {
2803 $this->mMagicHookDone
= true;
2804 wfProfileIn( 'LanguageGetMagic' );
2805 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2806 wfProfileOut( 'LanguageGetMagic' );
2810 * Fill a MagicWord object with data from here
2814 function getMagic( $mw ) {
2815 $this->doMagicHook();
2817 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2818 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2820 $magicWords = $this->getMagicWords();
2821 if ( isset( $magicWords[$mw->mId
] ) ) {
2822 $rawEntry = $magicWords[$mw->mId
];
2828 if ( !is_array( $rawEntry ) ) {
2829 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2831 $mw->mCaseSensitive
= $rawEntry[0];
2832 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2837 * Add magic words to the extension array
2839 * @param $newWords array
2841 function addMagicWordsByLang( $newWords ) {
2842 $fallbackChain = $this->getFallbackLanguages();
2843 $fallbackChain = array_reverse( $fallbackChain );
2844 foreach ( $fallbackChain as $code ) {
2845 if ( isset( $newWords[$code] ) ) {
2846 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2852 * Get special page names, as an associative array
2853 * case folded alias => real name
2855 function getSpecialPageAliases() {
2856 // Cache aliases because it may be slow to load them
2857 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2859 $this->mExtendedSpecialPageAliases
=
2860 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2861 wfRunHooks( 'LanguageGetSpecialPageAliases',
2862 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2865 return $this->mExtendedSpecialPageAliases
;
2869 * Italic is unsuitable for some languages
2871 * @param $text String: the text to be emphasized.
2874 function emphasize( $text ) {
2875 return "<em>$text</em>";
2879 * Normally we output all numbers in plain en_US style, that is
2880 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2881 * point twohundredthirtyfive. However this is not suitable for all
2882 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2883 * Icelandic just want to use commas instead of dots, and dots instead
2884 * of commas like "293.291,235".
2886 * An example of this function being called:
2888 * wfMessage( 'message' )->numParams( $num )->text()
2891 * See LanguageGu.php for the Gujarati implementation and
2892 * $separatorTransformTable on MessageIs.php for
2893 * the , => . and . => , implementation.
2895 * @todo check if it's viable to use localeconv() for the decimal
2897 * @param $number Mixed: the string to be formatted, should be an integer
2898 * or a floating point number.
2899 * @param $nocommafy Bool: set to true for special numbers like dates
2902 public function formatNum( $number, $nocommafy = false ) {
2903 global $wgTranslateNumerals;
2904 if ( !$nocommafy ) {
2905 $number = $this->commafy( $number );
2906 $s = $this->separatorTransformTable();
2908 $number = strtr( $number, $s );
2912 if ( $wgTranslateNumerals ) {
2913 $s = $this->digitTransformTable();
2915 $number = strtr( $number, $s );
2923 * @param $number string
2926 function parseFormattedNumber( $number ) {
2927 $s = $this->digitTransformTable();
2929 $number = strtr( $number, array_flip( $s ) );
2932 $s = $this->separatorTransformTable();
2934 $number = strtr( $number, array_flip( $s ) );
2937 $number = strtr( $number, array( ',' => '' ) );
2942 * Adds commas to a given number
2947 function commafy( $_ ) {
2948 $digitGroupingPattern = $this->digitGroupingPattern();
2949 if ( $_ === null ) {
2953 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2954 // default grouping is at thousands, use the same for ###,###,### pattern too.
2955 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2957 // Ref: http://cldr.unicode.org/translation/number-patterns
2959 if ( intval( $_ ) < 0 ) {
2960 // For negative numbers apply the algorithm like positive number and add sign.
2962 $_ = substr( $_, 1 );
2964 $numberpart = array();
2965 $decimalpart = array();
2966 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2967 preg_match( "/\d+/", $_, $numberpart );
2968 preg_match( "/\.\d*/", $_, $decimalpart );
2969 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2970 if ( $groupedNumber === $_ ) {
2971 // the string does not have any number part. Eg: .12345
2972 return $sign . $groupedNumber;
2974 $start = $end = strlen( $numberpart[0] );
2975 while ( $start > 0 ) {
2976 $match = $matches[0][$numMatches -1] ;
2977 $matchLen = strlen( $match );
2978 $start = $end - $matchLen;
2982 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2984 if ( $numMatches > 1 ) {
2985 // use the last pattern for the rest of the number
2989 $groupedNumber = "," . $groupedNumber;
2992 return $sign . $groupedNumber;
2998 function digitGroupingPattern() {
2999 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3005 function digitTransformTable() {
3006 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3012 function separatorTransformTable() {
3013 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3017 * Take a list of strings and build a locale-friendly comma-separated
3018 * list, using the local comma-separator message.
3019 * The last two strings are chained with an "and".
3020 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3025 function listToText( array $l ) {
3027 $m = count( $l ) - 1;
3031 } elseif ( $m === 1 ) {
3032 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3034 for ( $i = $m; $i >= 0; $i-- ) {
3037 } elseif ( $i == $m - 1 ) {
3038 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3040 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3048 * Take a list of strings and build a locale-friendly comma-separated
3049 * list, using the local comma-separator message.
3050 * @param $list array of strings to put in a comma list
3053 function commaList( array $list ) {
3055 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3061 * Take a list of strings and build a locale-friendly semicolon-separated
3062 * list, using the local semicolon-separator message.
3063 * @param $list array of strings to put in a semicolon list
3066 function semicolonList( array $list ) {
3068 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3074 * Same as commaList, but separate it with the pipe instead.
3075 * @param $list array of strings to put in a pipe list
3078 function pipeList( array $list ) {
3080 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3086 * Truncate a string to a specified length in bytes, appending an optional
3087 * string (e.g. for ellipses)
3089 * The database offers limited byte lengths for some columns in the database;
3090 * multi-byte character sets mean we need to ensure that only whole characters
3091 * are included, otherwise broken characters can be passed to the user
3093 * If $length is negative, the string will be truncated from the beginning
3095 * @param $string String to truncate
3096 * @param $length Int: maximum length (including ellipses)
3097 * @param $ellipsis String to append to the truncated text
3098 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3099 * $adjustLength was introduced in 1.18, before that behaved as if false.
3102 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3103 # Use the localized ellipsis character
3104 if ( $ellipsis == '...' ) {
3105 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3107 # Check if there is no need to truncate
3108 if ( $length == 0 ) {
3109 return $ellipsis; // convention
3110 } elseif ( strlen( $string ) <= abs( $length ) ) {
3111 return $string; // no need to truncate
3113 $stringOriginal = $string;
3114 # If ellipsis length is >= $length then we can't apply $adjustLength
3115 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3116 $string = $ellipsis; // this can be slightly unexpected
3117 # Otherwise, truncate and add ellipsis...
3119 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3120 if ( $length > 0 ) {
3121 $length -= $eLength;
3122 $string = substr( $string, 0, $length ); // xyz...
3123 $string = $this->removeBadCharLast( $string );
3124 $string = $string . $ellipsis;
3126 $length +
= $eLength;
3127 $string = substr( $string, $length ); // ...xyz
3128 $string = $this->removeBadCharFirst( $string );
3129 $string = $ellipsis . $string;
3132 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3133 # This check is *not* redundant if $adjustLength, due to the single case where
3134 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3135 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3138 return $stringOriginal;
3143 * Remove bytes that represent an incomplete Unicode character
3144 * at the end of string (e.g. bytes of the char are missing)
3146 * @param $string String
3149 protected function removeBadCharLast( $string ) {
3150 if ( $string != '' ) {
3151 $char = ord( $string[strlen( $string ) - 1] );
3153 if ( $char >= 0xc0 ) {
3154 # We got the first byte only of a multibyte char; remove it.
3155 $string = substr( $string, 0, -1 );
3156 } elseif ( $char >= 0x80 &&
3157 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3158 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3160 # We chopped in the middle of a character; remove it
3168 * Remove bytes that represent an incomplete Unicode character
3169 * at the start of string (e.g. bytes of the char are missing)
3171 * @param $string String
3174 protected function removeBadCharFirst( $string ) {
3175 if ( $string != '' ) {
3176 $char = ord( $string[0] );
3177 if ( $char >= 0x80 && $char < 0xc0 ) {
3178 # We chopped in the middle of a character; remove the whole thing
3179 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3186 * Truncate a string of valid HTML to a specified length in bytes,
3187 * appending an optional string (e.g. for ellipses), and return valid HTML
3189 * This is only intended for styled/linked text, such as HTML with
3190 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3191 * Also, this will not detect things like "display:none" CSS.
3193 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3195 * @param string $text HTML string to truncate
3196 * @param int $length (zero/positive) Maximum length (including ellipses)
3197 * @param string $ellipsis String to append to the truncated text
3200 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3201 # Use the localized ellipsis character
3202 if ( $ellipsis == '...' ) {
3203 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3205 # Check if there is clearly no need to truncate
3206 if ( $length <= 0 ) {
3207 return $ellipsis; // no text shown, nothing to format (convention)
3208 } elseif ( strlen( $text ) <= $length ) {
3209 return $text; // string short enough even *with* HTML (short-circuit)
3212 $dispLen = 0; // innerHTML legth so far
3213 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3214 $tagType = 0; // 0-open, 1-close
3215 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3216 $entityState = 0; // 0-not entity, 1-entity
3217 $tag = $ret = ''; // accumulated tag name, accumulated result string
3218 $openTags = array(); // open tag stack
3219 $maybeState = null; // possible truncation state
3221 $textLen = strlen( $text );
3222 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3223 for ( $pos = 0; true; ++
$pos ) {
3224 # Consider truncation once the display length has reached the maximim.
3225 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3226 # Check that we're not in the middle of a bracket/entity...
3227 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3228 if ( !$testingEllipsis ) {
3229 $testingEllipsis = true;
3230 # Save where we are; we will truncate here unless there turn out to
3231 # be so few remaining characters that truncation is not necessary.
3232 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3233 $maybeState = array( $ret, $openTags ); // save state
3235 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3236 # String in fact does need truncation, the truncation point was OK.
3237 list( $ret, $openTags ) = $maybeState; // reload state
3238 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3239 $ret .= $ellipsis; // add ellipsis
3243 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3245 # Read the next char...
3247 $lastCh = $pos ?
$text[$pos - 1] : '';
3248 $ret .= $ch; // add to result string
3250 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3251 $entityState = 0; // for bad HTML
3252 $bracketState = 1; // tag started (checking for backslash)
3253 } elseif ( $ch == '>' ) {
3254 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3255 $entityState = 0; // for bad HTML
3256 $bracketState = 0; // out of brackets
3257 } elseif ( $bracketState == 1 ) {
3259 $tagType = 1; // close tag (e.g. "</span>")
3261 $tagType = 0; // open tag (e.g. "<span>")
3264 $bracketState = 2; // building tag name
3265 } elseif ( $bracketState == 2 ) {
3269 // Name found (e.g. "<a href=..."), add on tag attributes...
3270 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3272 } elseif ( $bracketState == 0 ) {
3273 if ( $entityState ) {
3276 $dispLen++
; // entity is one displayed char
3279 if ( $neLength == 0 && !$maybeState ) {
3280 // Save state without $ch. We want to *hit* the first
3281 // display char (to get tags) but not *use* it if truncating.
3282 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3285 $entityState = 1; // entity found, (e.g. " ")
3287 $dispLen++
; // this char is displayed
3288 // Add the next $max display text chars after this in one swoop...
3289 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3290 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3291 $dispLen +
= $skipped;
3297 // Close the last tag if left unclosed by bad HTML
3298 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3299 while ( count( $openTags ) > 0 ) {
3300 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3306 * truncateHtml() helper function
3307 * like strcspn() but adds the skipped chars to $ret
3316 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3317 if ( $len === null ) {
3318 $len = -1; // -1 means "no limit" for strcspn
3319 } elseif ( $len < 0 ) {
3323 if ( $start < strlen( $text ) ) {
3324 $skipCount = strcspn( $text, $search, $start, $len );
3325 $ret .= substr( $text, $start, $skipCount );
3331 * truncateHtml() helper function
3332 * (a) push or pop $tag from $openTags as needed
3333 * (b) clear $tag value
3334 * @param &$tag string Current HTML tag name we are looking at
3335 * @param $tagType int (0-open tag, 1-close tag)
3336 * @param $lastCh string Character before the '>' that ended this tag
3337 * @param &$openTags array Open tag stack (not accounting for $tag)
3339 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3340 $tag = ltrim( $tag );
3342 if ( $tagType == 0 && $lastCh != '/' ) {
3343 $openTags[] = $tag; // tag opened (didn't close itself)
3344 } elseif ( $tagType == 1 ) {
3345 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3346 array_pop( $openTags ); // tag closed
3354 * Grammatical transformations, needed for inflected languages
3355 * Invoked by putting {{grammar:case|word}} in a message
3357 * @param $word string
3358 * @param $case string
3361 function convertGrammar( $word, $case ) {
3362 global $wgGrammarForms;
3363 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3364 return $wgGrammarForms[$this->getCode()][$case][$word];
3369 * Get the grammar forms for the content language
3370 * @return array of grammar forms
3373 function getGrammarForms() {
3374 global $wgGrammarForms;
3375 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3376 return $wgGrammarForms[$this->getCode()];
3381 * Provides an alternative text depending on specified gender.
3382 * Usage {{gender:username|masculine|feminine|neutral}}.
3383 * username is optional, in which case the gender of current user is used,
3384 * but only in (some) interface messages; otherwise default gender is used.
3386 * If no forms are given, an empty string is returned. If only one form is
3387 * given, it will be returned unconditionally. These details are implied by
3388 * the caller and cannot be overridden in subclasses.
3390 * If more than one form is given, the default is to use the neutral one
3391 * if it is specified, and to use the masculine one otherwise. These
3392 * details can be overridden in subclasses.
3394 * @param $gender string
3395 * @param $forms array
3399 function gender( $gender, $forms ) {
3400 if ( !count( $forms ) ) {
3403 $forms = $this->preConvertPlural( $forms, 2 );
3404 if ( $gender === 'male' ) {
3407 if ( $gender === 'female' ) {
3410 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3414 * Plural form transformations, needed for some languages.
3415 * For example, there are 3 form of plural in Russian and Polish,
3416 * depending on "count mod 10". See [[w:Plural]]
3417 * For English it is pretty simple.
3419 * Invoked by putting {{plural:count|wordform1|wordform2}}
3420 * or {{plural:count|wordform1|wordform2|wordform3}}
3422 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3424 * @param $count Integer: non-localized number
3425 * @param $forms Array: different plural forms
3426 * @return string Correct form of plural for $count in this language
3428 function convertPlural( $count, $forms ) {
3429 if ( !count( $forms ) ) {
3433 // Handle explicit 0= and 1= forms
3434 foreach ( $forms as $index => $form ) {
3435 if ( isset( $form[1] ) && $form[1] === '=' ) {
3436 if ( $form[0] === (string) $count ) {
3437 return substr( $form, 2 );
3439 unset( $forms[$index] );
3442 $forms = array_values( $forms );
3444 $pluralForm = $this->getPluralForm( $count );
3445 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3446 return $forms[$pluralForm];
3450 * Checks that convertPlural was given an array and pads it to requested
3451 * amount of forms by copying the last one.
3453 * @param $count Integer: How many forms should there be at least
3454 * @param $forms Array of forms given to convertPlural
3455 * @return array Padded array of forms or an exception if not an array
3457 protected function preConvertPlural( /* Array */ $forms, $count ) {
3458 while ( count( $forms ) < $count ) {
3459 $forms[] = $forms[count( $forms ) - 1];
3465 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3466 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3467 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3468 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3471 * @param $str String: the validated block duration in English
3472 * @return string Somehow translated block duration
3473 * @see LanguageFi.php for example implementation
3475 function translateBlockExpiry( $str ) {
3476 $duration = SpecialBlock
::getSuggestedDurations( $this );
3477 foreach ( $duration as $show => $value ) {
3478 if ( strcmp( $str, $value ) == 0 ) {
3479 return htmlspecialchars( trim( $show ) );
3483 // Since usually only infinite or indefinite is only on list, so try
3484 // equivalents if still here.
3485 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3486 if ( in_array( $str, $indefs ) ) {
3487 foreach ( $indefs as $val ) {
3488 $show = array_search( $val, $duration, true );
3489 if ( $show !== false ) {
3490 return htmlspecialchars( trim( $show ) );
3495 // If all else fails, return a standard duration or timestamp description.
3496 $time = strtotime( $str, 0 );
3497 if ( $time === false ) { // Unknown format. Return it as-is in case.
3499 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3500 // $time is relative to 0 so it's a duration length.
3501 return $this->formatDuration( $time );
3502 } else { // It's an absolute timestamp.
3503 if ( $time === 0 ) {
3504 // wfTimestamp() handles 0 as current time instead of epoch.
3505 return $this->timeanddate( '19700101000000' );
3507 return $this->timeanddate( $time );
3513 * languages like Chinese need to be segmented in order for the diff
3516 * @param $text String
3519 public function segmentForDiff( $text ) {
3524 * and unsegment to show the result
3526 * @param $text String
3529 public function unsegmentForDiff( $text ) {
3534 * Return the LanguageConverter used in the Language
3537 * @return LanguageConverter
3539 public function getConverter() {
3540 return $this->mConverter
;
3544 * convert text to all supported variants
3546 * @param $text string
3549 public function autoConvertToAllVariants( $text ) {
3550 return $this->mConverter
->autoConvertToAllVariants( $text );
3554 * convert text to different variants of a language.
3556 * @param $text string
3559 public function convert( $text ) {
3560 return $this->mConverter
->convert( $text );
3564 * Convert a Title object to a string in the preferred variant
3566 * @param $title Title
3569 public function convertTitle( $title ) {
3570 return $this->mConverter
->convertTitle( $title );
3574 * Convert a namespace index to a string in the preferred variant
3579 public function convertNamespace( $ns ) {
3580 return $this->mConverter
->convertNamespace( $ns );
3584 * Check if this is a language with variants
3588 public function hasVariants() {
3589 return sizeof( $this->getVariants() ) > 1;
3593 * Check if the language has the specific variant
3596 * @param $variant string
3599 public function hasVariant( $variant ) {
3600 return (bool)$this->mConverter
->validateVariant( $variant );
3604 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3606 * @param $text string
3609 public function armourMath( $text ) {
3610 return $this->mConverter
->armourMath( $text );
3614 * Perform output conversion on a string, and encode for safe HTML output.
3615 * @param $text String text to be converted
3616 * @param $isTitle Bool whether this conversion is for the article title
3618 * @todo this should get integrated somewhere sane
3620 public function convertHtml( $text, $isTitle = false ) {
3621 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3625 * @param $key string
3628 public function convertCategoryKey( $key ) {
3629 return $this->mConverter
->convertCategoryKey( $key );
3633 * Get the list of variants supported by this language
3634 * see sample implementation in LanguageZh.php
3636 * @return array an array of language codes
3638 public function getVariants() {
3639 return $this->mConverter
->getVariants();
3645 public function getPreferredVariant() {
3646 return $this->mConverter
->getPreferredVariant();
3652 public function getDefaultVariant() {
3653 return $this->mConverter
->getDefaultVariant();
3659 public function getURLVariant() {
3660 return $this->mConverter
->getURLVariant();
3664 * If a language supports multiple variants, it is
3665 * possible that non-existing link in one variant
3666 * actually exists in another variant. this function
3667 * tries to find it. See e.g. LanguageZh.php
3669 * @param $link String: the name of the link
3670 * @param $nt Mixed: the title object of the link
3671 * @param $ignoreOtherCond Boolean: to disable other conditions when
3672 * we need to transclude a template or update a category's link
3673 * @return null the input parameters may be modified upon return
3675 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3676 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3680 * If a language supports multiple variants, converts text
3681 * into an array of all possible variants of the text:
3682 * 'variant' => text in that variant
3684 * @deprecated since 1.17 Use autoConvertToAllVariants()
3686 * @param $text string
3690 public function convertLinkToAllVariants( $text ) {
3691 return $this->mConverter
->convertLinkToAllVariants( $text );
3695 * returns language specific options used by User::getPageRenderHash()
3696 * for example, the preferred language variant
3700 function getExtraHashOptions() {
3701 return $this->mConverter
->getExtraHashOptions();
3705 * For languages that support multiple variants, the title of an
3706 * article may be displayed differently in different variants. this
3707 * function returns the apporiate title defined in the body of the article.
3711 public function getParsedTitle() {
3712 return $this->mConverter
->getParsedTitle();
3716 * Prepare external link text for conversion. When the text is
3717 * a URL, it shouldn't be converted, and it'll be wrapped in
3718 * the "raw" tag (-{R| }-) to prevent conversion.
3720 * This function is called "markNoConversion" for historical
3723 * @param $text String: text to be used for external link
3724 * @param $noParse bool: wrap it without confirming it's a real URL first
3725 * @return string the tagged text
3727 public function markNoConversion( $text, $noParse = false ) {
3728 // Excluding protocal-relative URLs may avoid many false positives.
3729 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3730 return $this->mConverter
->markNoConversion( $text );
3737 * A regular expression to match legal word-trailing characters
3738 * which should be merged onto a link of the form [[foo]]bar.
3742 public function linkTrail() {
3743 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3749 function getLangObj() {
3754 * Get the RFC 3066 code for this language object
3756 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3757 * htmlspecialchars() or similar
3761 public function getCode() {
3762 return $this->mCode
;
3766 * Get the code in Bcp47 format which we can use
3767 * inside of html lang="" tags.
3769 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3770 * htmlspecialchars() or similar.
3775 public function getHtmlCode() {
3776 if ( is_null( $this->mHtmlCode
) ) {
3777 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3779 return $this->mHtmlCode
;
3783 * @param $code string
3785 public function setCode( $code ) {
3786 $this->mCode
= $code;
3787 // Ensure we don't leave an incorrect html code lying around
3788 $this->mHtmlCode
= null;
3792 * Get the name of a file for a certain language code
3793 * @param $prefix string Prepend this to the filename
3794 * @param $code string Language code
3795 * @param $suffix string Append this to the filename
3796 * @throws MWException
3797 * @return string $prefix . $mangledCode . $suffix
3799 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3800 // Protect against path traversal
3801 if ( !Language
::isValidCode( $code )
3802 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3804 throw new MWException( "Invalid language code \"$code\"" );
3807 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3811 * Get the language code from a file name. Inverse of getFileName()
3812 * @param $filename string $prefix . $languageCode . $suffix
3813 * @param $prefix string Prefix before the language code
3814 * @param $suffix string Suffix after the language code
3815 * @return string Language code, or false if $prefix or $suffix isn't found
3817 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3819 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3820 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3821 if ( !count( $m ) ) {
3824 return str_replace( '_', '-', strtolower( $m[1] ) );
3828 * @param $code string
3831 public static function getMessagesFileName( $code ) {
3833 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3834 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3839 * @param $code string
3842 public static function getClassFileName( $code ) {
3844 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3848 * Get the first fallback for a given language.
3850 * @param $code string
3852 * @return bool|string
3854 public static function getFallbackFor( $code ) {
3855 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3858 $fallbacks = self
::getFallbacksFor( $code );
3859 $first = array_shift( $fallbacks );
3865 * Get the ordered list of fallback languages.
3868 * @param $code string Language code
3871 public static function getFallbacksFor( $code ) {
3872 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3875 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3876 $v = array_map( 'trim', explode( ',', $v ) );
3877 if ( $v[count( $v ) - 1] !== 'en' ) {
3885 * Get all messages for a given language
3886 * WARNING: this may take a long time. If you just need all message *keys*
3887 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3889 * @param $code string
3893 public static function getMessagesFor( $code ) {
3894 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3898 * Get a message for a given language
3900 * @param $key string
3901 * @param $code string
3905 public static function getMessageFor( $key, $code ) {
3906 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3910 * Get all message keys for a given language. This is a faster alternative to
3911 * array_keys( Language::getMessagesFor( $code ) )
3914 * @param $code string Language code
3915 * @return array of message keys (strings)
3917 public static function getMessageKeysFor( $code ) {
3918 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3925 function fixVariableInNamespace( $talk ) {
3926 if ( strpos( $talk, '$1' ) === false ) {
3930 global $wgMetaNamespace;
3931 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3933 # Allow grammar transformations
3934 # Allowing full message-style parsing would make simple requests
3935 # such as action=raw much more expensive than they need to be.
3936 # This will hopefully cover most cases.
3937 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3938 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3939 return str_replace( ' ', '_', $talk );
3946 function replaceGrammarInNamespace( $m ) {
3947 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3951 * @throws MWException
3954 static function getCaseMaps() {
3955 static $wikiUpperChars, $wikiLowerChars;
3956 if ( isset( $wikiUpperChars ) ) {
3957 return array( $wikiUpperChars, $wikiLowerChars );
3960 wfProfileIn( __METHOD__
);
3961 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3962 if ( $arr === false ) {
3963 throw new MWException(
3964 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3966 $wikiUpperChars = $arr['wikiUpperChars'];
3967 $wikiLowerChars = $arr['wikiLowerChars'];
3968 wfProfileOut( __METHOD__
);
3969 return array( $wikiUpperChars, $wikiLowerChars );
3973 * Decode an expiry (block, protection, etc) which has come from the DB
3975 * @todo FIXME: why are we returnings DBMS-dependent strings???
3977 * @param $expiry String: Database expiry String
3978 * @param $format Bool|Int true to process using language functions, or TS_ constant
3979 * to return the expiry in a given timestamp
3983 public function formatExpiry( $expiry, $format = true ) {
3984 static $infinity, $infinityMsg;
3985 if ( $infinity === null ) {
3986 $infinityMsg = wfMessage( 'infiniteblock' );
3987 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3990 if ( $expiry == '' ||
$expiry == $infinity ) {
3991 return $format === true
3995 return $format === true
3996 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3997 : wfTimestamp( $format, $expiry );
4003 * @param $seconds int|float
4004 * @param $format Array Optional
4005 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4006 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4007 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4008 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4011 function formatTimePeriod( $seconds, $format = array() ) {
4012 if ( !is_array( $format ) ) {
4013 $format = array( 'avoid' => $format ); // For backwards compatibility
4015 if ( !isset( $format['avoid'] ) ) {
4016 $format['avoid'] = false;
4018 if ( !isset( $format['noabbrevs' ] ) ) {
4019 $format['noabbrevs'] = false;
4021 $secondsMsg = wfMessage(
4022 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4023 $minutesMsg = wfMessage(
4024 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4025 $hoursMsg = wfMessage(
4026 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4027 $daysMsg = wfMessage(
4028 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4030 if ( round( $seconds * 10 ) < 100 ) {
4031 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4032 $s = $secondsMsg->params( $s )->text();
4033 } elseif ( round( $seconds ) < 60 ) {
4034 $s = $this->formatNum( round( $seconds ) );
4035 $s = $secondsMsg->params( $s )->text();
4036 } elseif ( round( $seconds ) < 3600 ) {
4037 $minutes = floor( $seconds / 60 );
4038 $secondsPart = round( fmod( $seconds, 60 ) );
4039 if ( $secondsPart == 60 ) {
4043 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4045 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4046 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4047 $hours = floor( $seconds / 3600 );
4048 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4049 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4050 if ( $secondsPart == 60 ) {
4054 if ( $minutes == 60 ) {
4058 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4060 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4061 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4062 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4065 $days = floor( $seconds / 86400 );
4066 if ( $format['avoid'] === 'avoidminutes' ) {
4067 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4068 if ( $hours == 24 ) {
4072 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4074 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4075 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4076 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4077 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4078 if ( $minutes == 60 ) {
4082 if ( $hours == 24 ) {
4086 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4088 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4090 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4092 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4094 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4101 * Format a bitrate for output, using an appropriate
4102 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4104 * This use base 1000. For base 1024 use formatSize(), for another base
4105 * see formatComputingNumbers()
4110 function formatBitrate( $bps ) {
4111 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4115 * @param $size int Size of the unit
4116 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4117 * @param $messageKey string Message key to be uesd
4120 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4122 return str_replace( '$1', $this->formatNum( $size ),
4123 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4126 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4129 $maxIndex = count( $sizes ) - 1;
4130 while ( $size >= $boundary && $index < $maxIndex ) {
4135 // For small sizes no decimal places necessary
4138 // For MB and bigger two decimal places are smarter
4141 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4143 $size = round( $size, $round );
4144 $text = $this->getMessageFromDB( $msg );
4145 return str_replace( '$1', $this->formatNum( $size ), $text );
4149 * Format a size in bytes for output, using an appropriate
4150 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4152 * This method use base 1024. For base 1000 use formatBitrate(), for
4153 * another base see formatComputingNumbers()
4155 * @param $size int Size to format
4156 * @return string Plain text (not HTML)
4158 function formatSize( $size ) {
4159 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4163 * Make a list item, used by various special pages
4165 * @param $page String Page link
4166 * @param $details String Text between brackets
4167 * @param $oppositedm Boolean Add the direction mark opposite to your
4168 * language, to display text properly
4171 function specialList( $page, $details, $oppositedm = true ) {
4172 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4173 $this->getDirMark();
4174 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4175 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4176 return $page . $details;
4180 * Generate (prev x| next x) (20|50|100...) type links for paging
4182 * @param $title Title object to link
4183 * @param $offset Integer offset parameter
4184 * @param $limit Integer limit parameter
4185 * @param $query array|String optional URL query parameter string
4186 * @param $atend Bool optional param for specified if this is the last page
4189 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4190 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4192 # Make 'previous' link
4193 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4194 if ( $offset > 0 ) {
4195 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4196 $query, $prev, 'prevn-title', 'mw-prevlink' );
4198 $plink = htmlspecialchars( $prev );
4202 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4204 $nlink = htmlspecialchars( $next );
4206 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4207 $query, $next, 'prevn-title', 'mw-nextlink' );
4210 # Make links to set number of items per page
4211 $numLinks = array();
4212 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4213 $numLinks[] = $this->numLink( $title, $offset, $num,
4214 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4217 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4218 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4222 * Helper function for viewPrevNext() that generates links
4224 * @param $title Title object to link
4225 * @param $offset Integer offset parameter
4226 * @param $limit Integer limit parameter
4227 * @param $query Array extra query parameters
4228 * @param $link String text to use for the link; will be escaped
4229 * @param $tooltipMsg String name of the message to use as tooltip
4230 * @param $class String value of the "class" attribute of the link
4231 * @return String HTML fragment
4233 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4234 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4235 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4236 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4237 'title' => $tooltip, 'class' => $class ), $link );
4241 * Get the conversion rule title, if any.
4245 public function getConvRuleTitle() {
4246 return $this->mConverter
->getConvRuleTitle();
4250 * Get the compiled plural rules for the language
4252 * @return array Associative array with plural form, and plural rule as key-value pairs
4254 public function getCompiledPluralRules() {
4255 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4256 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4257 if ( !$pluralRules ) {
4258 foreach ( $fallbacks as $fallbackCode ) {
4259 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4260 if ( $pluralRules ) {
4265 return $pluralRules;
4269 * Get the plural rules for the language
4271 * @return array Associative array with plural form, and plural rule as key-value pairs
4273 public function getPluralRules() {
4274 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4275 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4276 if ( !$pluralRules ) {
4277 foreach ( $fallbacks as $fallbackCode ) {
4278 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4279 if ( $pluralRules ) {
4284 return $pluralRules;
4288 * Find the plural form matching to the given number
4289 * It return the form index.
4290 * @return int The index of the plural form
4292 private function getPluralForm( $number ) {
4293 $pluralRules = $this->getCompiledPluralRules();
4294 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );