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 if ( StringUtils
::isUtf8( $s ) ) {
2432 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2438 function fallback8bitEncoding() {
2439 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2443 * Most writing systems use whitespace to break up words.
2444 * Some languages such as Chinese don't conventionally do this,
2445 * which requires special handling when breaking up words for
2450 function hasWordBreaks() {
2455 * Some languages such as Chinese require word segmentation,
2456 * Specify such segmentation when overridden in derived class.
2458 * @param $string String
2461 function segmentByWord( $string ) {
2466 * Some languages have special punctuation need to be normalized.
2467 * Make such changes here.
2469 * @param $string String
2472 function normalizeForSearch( $string ) {
2473 return self
::convertDoubleWidth( $string );
2477 * convert double-width roman characters to single-width.
2478 * range: ff00-ff5f ~= 0020-007f
2480 * @param $string string
2484 protected static function convertDoubleWidth( $string ) {
2485 static $full = null;
2486 static $half = null;
2488 if ( $full === null ) {
2489 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2490 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2491 $full = str_split( $fullWidth, 3 );
2492 $half = str_split( $halfWidth );
2495 $string = str_replace( $full, $half, $string );
2500 * @param $string string
2501 * @param $pattern string
2504 protected static function insertSpace( $string, $pattern ) {
2505 $string = preg_replace( $pattern, " $1 ", $string );
2506 $string = preg_replace( '/ +/', ' ', $string );
2511 * @param $termsArray array
2514 function convertForSearchResult( $termsArray ) {
2515 # some languages, e.g. Chinese, need to do a conversion
2516 # in order for search results to be displayed correctly
2521 * Get the first character of a string.
2526 function firstChar( $s ) {
2529 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2530 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2535 if ( isset( $matches[1] ) ) {
2536 if ( strlen( $matches[1] ) != 3 ) {
2540 // Break down Hangul syllables to grab the first jamo
2541 $code = utf8ToCodepoint( $matches[1] );
2542 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2544 } elseif ( $code < 0xb098 ) {
2545 return "\xe3\x84\xb1";
2546 } elseif ( $code < 0xb2e4 ) {
2547 return "\xe3\x84\xb4";
2548 } elseif ( $code < 0xb77c ) {
2549 return "\xe3\x84\xb7";
2550 } elseif ( $code < 0xb9c8 ) {
2551 return "\xe3\x84\xb9";
2552 } elseif ( $code < 0xbc14 ) {
2553 return "\xe3\x85\x81";
2554 } elseif ( $code < 0xc0ac ) {
2555 return "\xe3\x85\x82";
2556 } elseif ( $code < 0xc544 ) {
2557 return "\xe3\x85\x85";
2558 } elseif ( $code < 0xc790 ) {
2559 return "\xe3\x85\x87";
2560 } elseif ( $code < 0xcc28 ) {
2561 return "\xe3\x85\x88";
2562 } elseif ( $code < 0xce74 ) {
2563 return "\xe3\x85\x8a";
2564 } elseif ( $code < 0xd0c0 ) {
2565 return "\xe3\x85\x8b";
2566 } elseif ( $code < 0xd30c ) {
2567 return "\xe3\x85\x8c";
2568 } elseif ( $code < 0xd558 ) {
2569 return "\xe3\x85\x8d";
2571 return "\xe3\x85\x8e";
2578 function initEncoding() {
2579 # Some languages may have an alternate char encoding option
2580 # (Esperanto X-coding, Japanese furigana conversion, etc)
2581 # If this language is used as the primary content language,
2582 # an override to the defaults can be set here on startup.
2589 function recodeForEdit( $s ) {
2590 # For some languages we'll want to explicitly specify
2591 # which characters make it into the edit box raw
2592 # or are converted in some way or another.
2593 global $wgEditEncoding;
2594 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2597 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2605 function recodeInput( $s ) {
2606 # Take the previous into account.
2607 global $wgEditEncoding;
2608 if ( $wgEditEncoding != '' ) {
2609 $enc = $wgEditEncoding;
2613 if ( $enc == 'UTF-8' ) {
2616 return $this->iconv( $enc, 'UTF-8', $s );
2621 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2622 * also cleans up certain backwards-compatible sequences, converting them
2623 * to the modern Unicode equivalent.
2625 * This is language-specific for performance reasons only.
2631 function normalize( $s ) {
2632 global $wgAllUnicodeFixes;
2633 $s = UtfNormal
::cleanUp( $s );
2634 if ( $wgAllUnicodeFixes ) {
2635 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2636 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2643 * Transform a string using serialized data stored in the given file (which
2644 * must be in the serialized subdirectory of $IP). The file contains pairs
2645 * mapping source characters to destination characters.
2647 * The data is cached in process memory. This will go faster if you have the
2648 * FastStringSearch extension.
2650 * @param $file string
2651 * @param $string string
2653 * @throws MWException
2656 function transformUsingPairFile( $file, $string ) {
2657 if ( !isset( $this->transformData
[$file] ) ) {
2658 $data = wfGetPrecompiledData( $file );
2659 if ( $data === false ) {
2660 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2662 $this->transformData
[$file] = new ReplacementArray( $data );
2664 return $this->transformData
[$file]->replace( $string );
2668 * For right-to-left language support
2673 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2677 * Return the correct HTML 'dir' attribute value for this language.
2681 return $this->isRTL() ?
'rtl' : 'ltr';
2685 * Return 'left' or 'right' as appropriate alignment for line-start
2686 * for this language's text direction.
2688 * Should be equivalent to CSS3 'start' text-align value....
2692 function alignStart() {
2693 return $this->isRTL() ?
'right' : 'left';
2697 * Return 'right' or 'left' as appropriate alignment for line-end
2698 * for this language's text direction.
2700 * Should be equivalent to CSS3 'end' text-align value....
2704 function alignEnd() {
2705 return $this->isRTL() ?
'left' : 'right';
2709 * A hidden direction mark (LRM or RLM), depending on the language direction.
2710 * Unlike getDirMark(), this function returns the character as an HTML entity.
2711 * This function should be used when the output is guaranteed to be HTML,
2712 * because it makes the output HTML source code more readable. When
2713 * the output is plain text or can be escaped, getDirMark() should be used.
2715 * @param $opposite Boolean Get the direction mark opposite to your language
2719 function getDirMarkEntity( $opposite = false ) {
2720 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2721 return $this->isRTL() ?
'‏' : '‎';
2725 * A hidden direction mark (LRM or RLM), depending on the language direction.
2726 * This function produces them as invisible Unicode characters and
2727 * the output may be hard to read and debug, so it should only be used
2728 * when the output is plain text or can be escaped. When the output is
2729 * HTML, use getDirMarkEntity() instead.
2731 * @param $opposite Boolean Get the direction mark opposite to your language
2734 function getDirMark( $opposite = false ) {
2735 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2736 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2737 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2738 return $this->isRTL() ?
$rlm : $lrm;
2744 function capitalizeAllNouns() {
2745 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2749 * An arrow, depending on the language direction.
2751 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2754 function getArrow( $direction = 'forwards' ) {
2755 switch ( $direction ) {
2757 return $this->isRTL() ?
'←' : '→';
2759 return $this->isRTL() ?
'→' : '←';
2772 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2776 function linkPrefixExtension() {
2777 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2783 function getMagicWords() {
2784 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2787 protected function doMagicHook() {
2788 if ( $this->mMagicHookDone
) {
2791 $this->mMagicHookDone
= true;
2792 wfProfileIn( 'LanguageGetMagic' );
2793 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2794 wfProfileOut( 'LanguageGetMagic' );
2798 * Fill a MagicWord object with data from here
2802 function getMagic( $mw ) {
2803 $this->doMagicHook();
2805 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2806 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2808 $magicWords = $this->getMagicWords();
2809 if ( isset( $magicWords[$mw->mId
] ) ) {
2810 $rawEntry = $magicWords[$mw->mId
];
2816 if ( !is_array( $rawEntry ) ) {
2817 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2819 $mw->mCaseSensitive
= $rawEntry[0];
2820 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2825 * Add magic words to the extension array
2827 * @param $newWords array
2829 function addMagicWordsByLang( $newWords ) {
2830 $fallbackChain = $this->getFallbackLanguages();
2831 $fallbackChain = array_reverse( $fallbackChain );
2832 foreach ( $fallbackChain as $code ) {
2833 if ( isset( $newWords[$code] ) ) {
2834 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2840 * Get special page names, as an associative array
2841 * case folded alias => real name
2843 function getSpecialPageAliases() {
2844 // Cache aliases because it may be slow to load them
2845 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2847 $this->mExtendedSpecialPageAliases
=
2848 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2849 wfRunHooks( 'LanguageGetSpecialPageAliases',
2850 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2853 return $this->mExtendedSpecialPageAliases
;
2857 * Italic is unsuitable for some languages
2859 * @param $text String: the text to be emphasized.
2862 function emphasize( $text ) {
2863 return "<em>$text</em>";
2867 * Normally we output all numbers in plain en_US style, that is
2868 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2869 * point twohundredthirtyfive. However this is not suitable for all
2870 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2871 * Icelandic just want to use commas instead of dots, and dots instead
2872 * of commas like "293.291,235".
2874 * An example of this function being called:
2876 * wfMessage( 'message' )->numParams( $num )->text()
2879 * See LanguageGu.php for the Gujarati implementation and
2880 * $separatorTransformTable on MessageIs.php for
2881 * the , => . and . => , implementation.
2883 * @todo check if it's viable to use localeconv() for the decimal
2885 * @param $number Mixed: the string to be formatted, should be an integer
2886 * or a floating point number.
2887 * @param $nocommafy Bool: set to true for special numbers like dates
2890 public function formatNum( $number, $nocommafy = false ) {
2891 global $wgTranslateNumerals;
2892 if ( !$nocommafy ) {
2893 $number = $this->commafy( $number );
2894 $s = $this->separatorTransformTable();
2896 $number = strtr( $number, $s );
2900 if ( $wgTranslateNumerals ) {
2901 $s = $this->digitTransformTable();
2903 $number = strtr( $number, $s );
2911 * @param $number string
2914 function parseFormattedNumber( $number ) {
2915 $s = $this->digitTransformTable();
2917 $number = strtr( $number, array_flip( $s ) );
2920 $s = $this->separatorTransformTable();
2922 $number = strtr( $number, array_flip( $s ) );
2925 $number = strtr( $number, array( ',' => '' ) );
2930 * Adds commas to a given number
2935 function commafy( $_ ) {
2936 $digitGroupingPattern = $this->digitGroupingPattern();
2937 if ( $_ === null ) {
2941 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2942 // default grouping is at thousands, use the same for ###,###,### pattern too.
2943 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2945 // Ref: http://cldr.unicode.org/translation/number-patterns
2947 if ( intval( $_ ) < 0 ) {
2948 // For negative numbers apply the algorithm like positive number and add sign.
2950 $_ = substr( $_, 1 );
2952 $numberpart = array();
2953 $decimalpart = array();
2954 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2955 preg_match( "/\d+/", $_, $numberpart );
2956 preg_match( "/\.\d*/", $_, $decimalpart );
2957 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2958 if ( $groupedNumber === $_ ) {
2959 // the string does not have any number part. Eg: .12345
2960 return $sign . $groupedNumber;
2962 $start = $end = strlen( $numberpart[0] );
2963 while ( $start > 0 ) {
2964 $match = $matches[0][$numMatches -1] ;
2965 $matchLen = strlen( $match );
2966 $start = $end - $matchLen;
2970 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2972 if ( $numMatches > 1 ) {
2973 // use the last pattern for the rest of the number
2977 $groupedNumber = "," . $groupedNumber;
2980 return $sign . $groupedNumber;
2986 function digitGroupingPattern() {
2987 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2993 function digitTransformTable() {
2994 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3000 function separatorTransformTable() {
3001 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3005 * Take a list of strings and build a locale-friendly comma-separated
3006 * list, using the local comma-separator message.
3007 * The last two strings are chained with an "and".
3008 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3013 function listToText( array $l ) {
3015 $m = count( $l ) - 1;
3019 } elseif ( $m === 1 ) {
3020 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3022 for ( $i = $m; $i >= 0; $i-- ) {
3025 } elseif ( $i == $m - 1 ) {
3026 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3028 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3036 * Take a list of strings and build a locale-friendly comma-separated
3037 * list, using the local comma-separator message.
3038 * @param $list array of strings to put in a comma list
3041 function commaList( array $list ) {
3043 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3049 * Take a list of strings and build a locale-friendly semicolon-separated
3050 * list, using the local semicolon-separator message.
3051 * @param $list array of strings to put in a semicolon list
3054 function semicolonList( array $list ) {
3056 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3062 * Same as commaList, but separate it with the pipe instead.
3063 * @param $list array of strings to put in a pipe list
3066 function pipeList( array $list ) {
3068 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3074 * Truncate a string to a specified length in bytes, appending an optional
3075 * string (e.g. for ellipses)
3077 * The database offers limited byte lengths for some columns in the database;
3078 * multi-byte character sets mean we need to ensure that only whole characters
3079 * are included, otherwise broken characters can be passed to the user
3081 * If $length is negative, the string will be truncated from the beginning
3083 * @param $string String to truncate
3084 * @param $length Int: maximum length (including ellipses)
3085 * @param $ellipsis String to append to the truncated text
3086 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3087 * $adjustLength was introduced in 1.18, before that behaved as if false.
3090 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3091 # Use the localized ellipsis character
3092 if ( $ellipsis == '...' ) {
3093 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3095 # Check if there is no need to truncate
3096 if ( $length == 0 ) {
3097 return $ellipsis; // convention
3098 } elseif ( strlen( $string ) <= abs( $length ) ) {
3099 return $string; // no need to truncate
3101 $stringOriginal = $string;
3102 # If ellipsis length is >= $length then we can't apply $adjustLength
3103 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3104 $string = $ellipsis; // this can be slightly unexpected
3105 # Otherwise, truncate and add ellipsis...
3107 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3108 if ( $length > 0 ) {
3109 $length -= $eLength;
3110 $string = substr( $string, 0, $length ); // xyz...
3111 $string = $this->removeBadCharLast( $string );
3112 $string = $string . $ellipsis;
3114 $length +
= $eLength;
3115 $string = substr( $string, $length ); // ...xyz
3116 $string = $this->removeBadCharFirst( $string );
3117 $string = $ellipsis . $string;
3120 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3121 # This check is *not* redundant if $adjustLength, due to the single case where
3122 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3123 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3126 return $stringOriginal;
3131 * Remove bytes that represent an incomplete Unicode character
3132 * at the end of string (e.g. bytes of the char are missing)
3134 * @param $string String
3137 protected function removeBadCharLast( $string ) {
3138 if ( $string != '' ) {
3139 $char = ord( $string[strlen( $string ) - 1] );
3141 if ( $char >= 0xc0 ) {
3142 # We got the first byte only of a multibyte char; remove it.
3143 $string = substr( $string, 0, -1 );
3144 } elseif ( $char >= 0x80 &&
3145 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3146 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3148 # We chopped in the middle of a character; remove it
3156 * Remove bytes that represent an incomplete Unicode character
3157 * at the start of string (e.g. bytes of the char are missing)
3159 * @param $string String
3162 protected function removeBadCharFirst( $string ) {
3163 if ( $string != '' ) {
3164 $char = ord( $string[0] );
3165 if ( $char >= 0x80 && $char < 0xc0 ) {
3166 # We chopped in the middle of a character; remove the whole thing
3167 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3174 * Truncate a string of valid HTML to a specified length in bytes,
3175 * appending an optional string (e.g. for ellipses), and return valid HTML
3177 * This is only intended for styled/linked text, such as HTML with
3178 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3179 * Also, this will not detect things like "display:none" CSS.
3181 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3183 * @param string $text HTML string to truncate
3184 * @param int $length (zero/positive) Maximum length (including ellipses)
3185 * @param string $ellipsis String to append to the truncated text
3188 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3189 # Use the localized ellipsis character
3190 if ( $ellipsis == '...' ) {
3191 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3193 # Check if there is clearly no need to truncate
3194 if ( $length <= 0 ) {
3195 return $ellipsis; // no text shown, nothing to format (convention)
3196 } elseif ( strlen( $text ) <= $length ) {
3197 return $text; // string short enough even *with* HTML (short-circuit)
3200 $dispLen = 0; // innerHTML legth so far
3201 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3202 $tagType = 0; // 0-open, 1-close
3203 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3204 $entityState = 0; // 0-not entity, 1-entity
3205 $tag = $ret = ''; // accumulated tag name, accumulated result string
3206 $openTags = array(); // open tag stack
3207 $maybeState = null; // possible truncation state
3209 $textLen = strlen( $text );
3210 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3211 for ( $pos = 0; true; ++
$pos ) {
3212 # Consider truncation once the display length has reached the maximim.
3213 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3214 # Check that we're not in the middle of a bracket/entity...
3215 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3216 if ( !$testingEllipsis ) {
3217 $testingEllipsis = true;
3218 # Save where we are; we will truncate here unless there turn out to
3219 # be so few remaining characters that truncation is not necessary.
3220 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3221 $maybeState = array( $ret, $openTags ); // save state
3223 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3224 # String in fact does need truncation, the truncation point was OK.
3225 list( $ret, $openTags ) = $maybeState; // reload state
3226 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3227 $ret .= $ellipsis; // add ellipsis
3231 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3233 # Read the next char...
3235 $lastCh = $pos ?
$text[$pos - 1] : '';
3236 $ret .= $ch; // add to result string
3238 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3239 $entityState = 0; // for bad HTML
3240 $bracketState = 1; // tag started (checking for backslash)
3241 } elseif ( $ch == '>' ) {
3242 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3243 $entityState = 0; // for bad HTML
3244 $bracketState = 0; // out of brackets
3245 } elseif ( $bracketState == 1 ) {
3247 $tagType = 1; // close tag (e.g. "</span>")
3249 $tagType = 0; // open tag (e.g. "<span>")
3252 $bracketState = 2; // building tag name
3253 } elseif ( $bracketState == 2 ) {
3257 // Name found (e.g. "<a href=..."), add on tag attributes...
3258 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3260 } elseif ( $bracketState == 0 ) {
3261 if ( $entityState ) {
3264 $dispLen++
; // entity is one displayed char
3267 if ( $neLength == 0 && !$maybeState ) {
3268 // Save state without $ch. We want to *hit* the first
3269 // display char (to get tags) but not *use* it if truncating.
3270 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3273 $entityState = 1; // entity found, (e.g. " ")
3275 $dispLen++
; // this char is displayed
3276 // Add the next $max display text chars after this in one swoop...
3277 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3278 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3279 $dispLen +
= $skipped;
3285 // Close the last tag if left unclosed by bad HTML
3286 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3287 while ( count( $openTags ) > 0 ) {
3288 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3294 * truncateHtml() helper function
3295 * like strcspn() but adds the skipped chars to $ret
3304 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3305 if ( $len === null ) {
3306 $len = -1; // -1 means "no limit" for strcspn
3307 } elseif ( $len < 0 ) {
3311 if ( $start < strlen( $text ) ) {
3312 $skipCount = strcspn( $text, $search, $start, $len );
3313 $ret .= substr( $text, $start, $skipCount );
3319 * truncateHtml() helper function
3320 * (a) push or pop $tag from $openTags as needed
3321 * (b) clear $tag value
3322 * @param &$tag string Current HTML tag name we are looking at
3323 * @param $tagType int (0-open tag, 1-close tag)
3324 * @param $lastCh string Character before the '>' that ended this tag
3325 * @param &$openTags array Open tag stack (not accounting for $tag)
3327 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3328 $tag = ltrim( $tag );
3330 if ( $tagType == 0 && $lastCh != '/' ) {
3331 $openTags[] = $tag; // tag opened (didn't close itself)
3332 } elseif ( $tagType == 1 ) {
3333 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3334 array_pop( $openTags ); // tag closed
3342 * Grammatical transformations, needed for inflected languages
3343 * Invoked by putting {{grammar:case|word}} in a message
3345 * @param $word string
3346 * @param $case string
3349 function convertGrammar( $word, $case ) {
3350 global $wgGrammarForms;
3351 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3352 return $wgGrammarForms[$this->getCode()][$case][$word];
3357 * Get the grammar forms for the content language
3358 * @return array of grammar forms
3361 function getGrammarForms() {
3362 global $wgGrammarForms;
3363 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3364 return $wgGrammarForms[$this->getCode()];
3369 * Provides an alternative text depending on specified gender.
3370 * Usage {{gender:username|masculine|feminine|neutral}}.
3371 * username is optional, in which case the gender of current user is used,
3372 * but only in (some) interface messages; otherwise default gender is used.
3374 * If no forms are given, an empty string is returned. If only one form is
3375 * given, it will be returned unconditionally. These details are implied by
3376 * the caller and cannot be overridden in subclasses.
3378 * If more than one form is given, the default is to use the neutral one
3379 * if it is specified, and to use the masculine one otherwise. These
3380 * details can be overridden in subclasses.
3382 * @param $gender string
3383 * @param $forms array
3387 function gender( $gender, $forms ) {
3388 if ( !count( $forms ) ) {
3391 $forms = $this->preConvertPlural( $forms, 2 );
3392 if ( $gender === 'male' ) {
3395 if ( $gender === 'female' ) {
3398 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3402 * Plural form transformations, needed for some languages.
3403 * For example, there are 3 form of plural in Russian and Polish,
3404 * depending on "count mod 10". See [[w:Plural]]
3405 * For English it is pretty simple.
3407 * Invoked by putting {{plural:count|wordform1|wordform2}}
3408 * or {{plural:count|wordform1|wordform2|wordform3}}
3410 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3412 * @param $count Integer: non-localized number
3413 * @param $forms Array: different plural forms
3414 * @return string Correct form of plural for $count in this language
3416 function convertPlural( $count, $forms ) {
3417 if ( !count( $forms ) ) {
3421 // Handle explicit 0= and 1= forms
3422 foreach ( $forms as $index => $form ) {
3423 if ( isset( $form[1] ) && $form[1] === '=' ) {
3424 if ( $form[0] === (string) $count ) {
3425 return substr( $form, 2 );
3427 unset( $forms[$index] );
3430 $forms = array_values( $forms );
3432 $pluralForm = $this->getPluralForm( $count );
3433 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3434 return $forms[$pluralForm];
3438 * Checks that convertPlural was given an array and pads it to requested
3439 * amount of forms by copying the last one.
3441 * @param $count Integer: How many forms should there be at least
3442 * @param $forms Array of forms given to convertPlural
3443 * @return array Padded array of forms or an exception if not an array
3445 protected function preConvertPlural( /* Array */ $forms, $count ) {
3446 while ( count( $forms ) < $count ) {
3447 $forms[] = $forms[count( $forms ) - 1];
3453 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3454 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3455 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3456 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3459 * @param $str String: the validated block duration in English
3460 * @return string Somehow translated block duration
3461 * @see LanguageFi.php for example implementation
3463 function translateBlockExpiry( $str ) {
3464 $duration = SpecialBlock
::getSuggestedDurations( $this );
3465 foreach ( $duration as $show => $value ) {
3466 if ( strcmp( $str, $value ) == 0 ) {
3467 return htmlspecialchars( trim( $show ) );
3471 // Since usually only infinite or indefinite is only on list, so try
3472 // equivalents if still here.
3473 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3474 if ( in_array( $str, $indefs ) ) {
3475 foreach ( $indefs as $val ) {
3476 $show = array_search( $val, $duration, true );
3477 if ( $show !== false ) {
3478 return htmlspecialchars( trim( $show ) );
3483 // If all else fails, return a standard duration or timestamp description.
3484 $time = strtotime( $str, 0 );
3485 if ( $time === false ) { // Unknown format. Return it as-is in case.
3487 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3488 // $time is relative to 0 so it's a duration length.
3489 return $this->formatDuration( $time );
3490 } else { // It's an absolute timestamp.
3491 if ( $time === 0 ) {
3492 // wfTimestamp() handles 0 as current time instead of epoch.
3493 return $this->timeanddate( '19700101000000' );
3495 return $this->timeanddate( $time );
3501 * languages like Chinese need to be segmented in order for the diff
3504 * @param $text String
3507 public function segmentForDiff( $text ) {
3512 * and unsegment to show the result
3514 * @param $text String
3517 public function unsegmentForDiff( $text ) {
3522 * Return the LanguageConverter used in the Language
3525 * @return LanguageConverter
3527 public function getConverter() {
3528 return $this->mConverter
;
3532 * convert text to all supported variants
3534 * @param $text string
3537 public function autoConvertToAllVariants( $text ) {
3538 return $this->mConverter
->autoConvertToAllVariants( $text );
3542 * convert text to different variants of a language.
3544 * @param $text string
3547 public function convert( $text ) {
3548 return $this->mConverter
->convert( $text );
3552 * Convert a Title object to a string in the preferred variant
3554 * @param $title Title
3557 public function convertTitle( $title ) {
3558 return $this->mConverter
->convertTitle( $title );
3562 * Convert a namespace index to a string in the preferred variant
3567 public function convertNamespace( $ns ) {
3568 return $this->mConverter
->convertNamespace( $ns );
3572 * Check if this is a language with variants
3576 public function hasVariants() {
3577 return sizeof( $this->getVariants() ) > 1;
3581 * Check if the language has the specific variant
3584 * @param $variant string
3587 public function hasVariant( $variant ) {
3588 return (bool)$this->mConverter
->validateVariant( $variant );
3592 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3594 * @param $text string
3597 public function armourMath( $text ) {
3598 return $this->mConverter
->armourMath( $text );
3602 * Perform output conversion on a string, and encode for safe HTML output.
3603 * @param $text String text to be converted
3604 * @param $isTitle Bool whether this conversion is for the article title
3606 * @todo this should get integrated somewhere sane
3608 public function convertHtml( $text, $isTitle = false ) {
3609 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3613 * @param $key string
3616 public function convertCategoryKey( $key ) {
3617 return $this->mConverter
->convertCategoryKey( $key );
3621 * Get the list of variants supported by this language
3622 * see sample implementation in LanguageZh.php
3624 * @return array an array of language codes
3626 public function getVariants() {
3627 return $this->mConverter
->getVariants();
3633 public function getPreferredVariant() {
3634 return $this->mConverter
->getPreferredVariant();
3640 public function getDefaultVariant() {
3641 return $this->mConverter
->getDefaultVariant();
3647 public function getURLVariant() {
3648 return $this->mConverter
->getURLVariant();
3652 * If a language supports multiple variants, it is
3653 * possible that non-existing link in one variant
3654 * actually exists in another variant. this function
3655 * tries to find it. See e.g. LanguageZh.php
3657 * @param $link String: the name of the link
3658 * @param $nt Mixed: the title object of the link
3659 * @param $ignoreOtherCond Boolean: to disable other conditions when
3660 * we need to transclude a template or update a category's link
3661 * @return null the input parameters may be modified upon return
3663 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3664 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3668 * If a language supports multiple variants, converts text
3669 * into an array of all possible variants of the text:
3670 * 'variant' => text in that variant
3672 * @deprecated since 1.17 Use autoConvertToAllVariants()
3674 * @param $text string
3678 public function convertLinkToAllVariants( $text ) {
3679 return $this->mConverter
->convertLinkToAllVariants( $text );
3683 * returns language specific options used by User::getPageRenderHash()
3684 * for example, the preferred language variant
3688 function getExtraHashOptions() {
3689 return $this->mConverter
->getExtraHashOptions();
3693 * For languages that support multiple variants, the title of an
3694 * article may be displayed differently in different variants. this
3695 * function returns the apporiate title defined in the body of the article.
3699 public function getParsedTitle() {
3700 return $this->mConverter
->getParsedTitle();
3704 * Prepare external link text for conversion. When the text is
3705 * a URL, it shouldn't be converted, and it'll be wrapped in
3706 * the "raw" tag (-{R| }-) to prevent conversion.
3708 * This function is called "markNoConversion" for historical
3711 * @param $text String: text to be used for external link
3712 * @param $noParse bool: wrap it without confirming it's a real URL first
3713 * @return string the tagged text
3715 public function markNoConversion( $text, $noParse = false ) {
3716 // Excluding protocal-relative URLs may avoid many false positives.
3717 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3718 return $this->mConverter
->markNoConversion( $text );
3725 * A regular expression to match legal word-trailing characters
3726 * which should be merged onto a link of the form [[foo]]bar.
3730 public function linkTrail() {
3731 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3737 function getLangObj() {
3742 * Get the RFC 3066 code for this language object
3744 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3745 * htmlspecialchars() or similar
3749 public function getCode() {
3750 return $this->mCode
;
3754 * Get the code in Bcp47 format which we can use
3755 * inside of html lang="" tags.
3757 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3758 * htmlspecialchars() or similar.
3763 public function getHtmlCode() {
3764 if ( is_null( $this->mHtmlCode
) ) {
3765 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3767 return $this->mHtmlCode
;
3771 * @param $code string
3773 public function setCode( $code ) {
3774 $this->mCode
= $code;
3775 // Ensure we don't leave an incorrect html code lying around
3776 $this->mHtmlCode
= null;
3780 * Get the name of a file for a certain language code
3781 * @param $prefix string Prepend this to the filename
3782 * @param $code string Language code
3783 * @param $suffix string Append this to the filename
3784 * @throws MWException
3785 * @return string $prefix . $mangledCode . $suffix
3787 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3788 // Protect against path traversal
3789 if ( !Language
::isValidCode( $code )
3790 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3792 throw new MWException( "Invalid language code \"$code\"" );
3795 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3799 * Get the language code from a file name. Inverse of getFileName()
3800 * @param $filename string $prefix . $languageCode . $suffix
3801 * @param $prefix string Prefix before the language code
3802 * @param $suffix string Suffix after the language code
3803 * @return string Language code, or false if $prefix or $suffix isn't found
3805 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3807 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3808 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3809 if ( !count( $m ) ) {
3812 return str_replace( '_', '-', strtolower( $m[1] ) );
3816 * @param $code string
3819 public static function getMessagesFileName( $code ) {
3821 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3822 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3827 * @param $code string
3830 public static function getClassFileName( $code ) {
3832 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3836 * Get the first fallback for a given language.
3838 * @param $code string
3840 * @return bool|string
3842 public static function getFallbackFor( $code ) {
3843 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3846 $fallbacks = self
::getFallbacksFor( $code );
3847 $first = array_shift( $fallbacks );
3853 * Get the ordered list of fallback languages.
3856 * @param $code string Language code
3859 public static function getFallbacksFor( $code ) {
3860 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3863 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3864 $v = array_map( 'trim', explode( ',', $v ) );
3865 if ( $v[count( $v ) - 1] !== 'en' ) {
3873 * Get all messages for a given language
3874 * WARNING: this may take a long time. If you just need all message *keys*
3875 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3877 * @param $code string
3881 public static function getMessagesFor( $code ) {
3882 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3886 * Get a message for a given language
3888 * @param $key string
3889 * @param $code string
3893 public static function getMessageFor( $key, $code ) {
3894 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3898 * Get all message keys for a given language. This is a faster alternative to
3899 * array_keys( Language::getMessagesFor( $code ) )
3902 * @param $code string Language code
3903 * @return array of message keys (strings)
3905 public static function getMessageKeysFor( $code ) {
3906 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3913 function fixVariableInNamespace( $talk ) {
3914 if ( strpos( $talk, '$1' ) === false ) {
3918 global $wgMetaNamespace;
3919 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3921 # Allow grammar transformations
3922 # Allowing full message-style parsing would make simple requests
3923 # such as action=raw much more expensive than they need to be.
3924 # This will hopefully cover most cases.
3925 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3926 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3927 return str_replace( ' ', '_', $talk );
3934 function replaceGrammarInNamespace( $m ) {
3935 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3939 * @throws MWException
3942 static function getCaseMaps() {
3943 static $wikiUpperChars, $wikiLowerChars;
3944 if ( isset( $wikiUpperChars ) ) {
3945 return array( $wikiUpperChars, $wikiLowerChars );
3948 wfProfileIn( __METHOD__
);
3949 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3950 if ( $arr === false ) {
3951 throw new MWException(
3952 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3954 $wikiUpperChars = $arr['wikiUpperChars'];
3955 $wikiLowerChars = $arr['wikiLowerChars'];
3956 wfProfileOut( __METHOD__
);
3957 return array( $wikiUpperChars, $wikiLowerChars );
3961 * Decode an expiry (block, protection, etc) which has come from the DB
3963 * @todo FIXME: why are we returnings DBMS-dependent strings???
3965 * @param $expiry String: Database expiry String
3966 * @param $format Bool|Int true to process using language functions, or TS_ constant
3967 * to return the expiry in a given timestamp
3971 public function formatExpiry( $expiry, $format = true ) {
3972 static $infinity, $infinityMsg;
3973 if ( $infinity === null ) {
3974 $infinityMsg = wfMessage( 'infiniteblock' );
3975 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3978 if ( $expiry == '' ||
$expiry == $infinity ) {
3979 return $format === true
3983 return $format === true
3984 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3985 : wfTimestamp( $format, $expiry );
3991 * @param $seconds int|float
3992 * @param $format Array Optional
3993 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3994 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3995 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3996 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3999 function formatTimePeriod( $seconds, $format = array() ) {
4000 if ( !is_array( $format ) ) {
4001 $format = array( 'avoid' => $format ); // For backwards compatibility
4003 if ( !isset( $format['avoid'] ) ) {
4004 $format['avoid'] = false;
4006 if ( !isset( $format['noabbrevs' ] ) ) {
4007 $format['noabbrevs'] = false;
4009 $secondsMsg = wfMessage(
4010 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4011 $minutesMsg = wfMessage(
4012 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4013 $hoursMsg = wfMessage(
4014 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4015 $daysMsg = wfMessage(
4016 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4018 if ( round( $seconds * 10 ) < 100 ) {
4019 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4020 $s = $secondsMsg->params( $s )->text();
4021 } elseif ( round( $seconds ) < 60 ) {
4022 $s = $this->formatNum( round( $seconds ) );
4023 $s = $secondsMsg->params( $s )->text();
4024 } elseif ( round( $seconds ) < 3600 ) {
4025 $minutes = floor( $seconds / 60 );
4026 $secondsPart = round( fmod( $seconds, 60 ) );
4027 if ( $secondsPart == 60 ) {
4031 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4033 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4034 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4035 $hours = floor( $seconds / 3600 );
4036 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4037 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4038 if ( $secondsPart == 60 ) {
4042 if ( $minutes == 60 ) {
4046 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4048 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4049 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4050 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4053 $days = floor( $seconds / 86400 );
4054 if ( $format['avoid'] === 'avoidminutes' ) {
4055 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4056 if ( $hours == 24 ) {
4060 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4062 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4063 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4064 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4065 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4066 if ( $minutes == 60 ) {
4070 if ( $hours == 24 ) {
4074 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4076 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4078 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4080 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4082 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4089 * Format a bitrate for output, using an appropriate
4090 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4092 * This use base 1000. For base 1024 use formatSize(), for another base
4093 * see formatComputingNumbers()
4098 function formatBitrate( $bps ) {
4099 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4103 * @param $size int Size of the unit
4104 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4105 * @param $messageKey string Message key to be uesd
4108 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4110 return str_replace( '$1', $this->formatNum( $size ),
4111 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4114 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4117 $maxIndex = count( $sizes ) - 1;
4118 while ( $size >= $boundary && $index < $maxIndex ) {
4123 // For small sizes no decimal places necessary
4126 // For MB and bigger two decimal places are smarter
4129 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4131 $size = round( $size, $round );
4132 $text = $this->getMessageFromDB( $msg );
4133 return str_replace( '$1', $this->formatNum( $size ), $text );
4137 * Format a size in bytes for output, using an appropriate
4138 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4140 * This method use base 1024. For base 1000 use formatBitrate(), for
4141 * another base see formatComputingNumbers()
4143 * @param $size int Size to format
4144 * @return string Plain text (not HTML)
4146 function formatSize( $size ) {
4147 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4151 * Make a list item, used by various special pages
4153 * @param $page String Page link
4154 * @param $details String Text between brackets
4155 * @param $oppositedm Boolean Add the direction mark opposite to your
4156 * language, to display text properly
4159 function specialList( $page, $details, $oppositedm = true ) {
4160 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4161 $this->getDirMark();
4162 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4163 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4164 return $page . $details;
4168 * Generate (prev x| next x) (20|50|100...) type links for paging
4170 * @param $title Title object to link
4171 * @param $offset Integer offset parameter
4172 * @param $limit Integer limit parameter
4173 * @param $query array|String optional URL query parameter string
4174 * @param $atend Bool optional param for specified if this is the last page
4177 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4178 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4180 # Make 'previous' link
4181 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4182 if ( $offset > 0 ) {
4183 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4184 $query, $prev, 'prevn-title', 'mw-prevlink' );
4186 $plink = htmlspecialchars( $prev );
4190 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4192 $nlink = htmlspecialchars( $next );
4194 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4195 $query, $next, 'prevn-title', 'mw-nextlink' );
4198 # Make links to set number of items per page
4199 $numLinks = array();
4200 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4201 $numLinks[] = $this->numLink( $title, $offset, $num,
4202 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4205 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4206 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4210 * Helper function for viewPrevNext() that generates links
4212 * @param $title Title object to link
4213 * @param $offset Integer offset parameter
4214 * @param $limit Integer limit parameter
4215 * @param $query Array extra query parameters
4216 * @param $link String text to use for the link; will be escaped
4217 * @param $tooltipMsg String name of the message to use as tooltip
4218 * @param $class String value of the "class" attribute of the link
4219 * @return String HTML fragment
4221 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4222 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4223 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4224 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4225 'title' => $tooltip, 'class' => $class ), $link );
4229 * Get the conversion rule title, if any.
4233 public function getConvRuleTitle() {
4234 return $this->mConverter
->getConvRuleTitle();
4238 * Get the compiled plural rules for the language
4240 * @return array Associative array with plural form, and plural rule as key-value pairs
4242 public function getCompiledPluralRules() {
4243 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4244 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4245 if ( !$pluralRules ) {
4246 foreach ( $fallbacks as $fallbackCode ) {
4247 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4248 if ( $pluralRules ) {
4253 return $pluralRules;
4257 * Get the plural rules for the language
4259 * @return array Associative array with plural form, and plural rule as key-value pairs
4261 public function getPluralRules() {
4262 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4263 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4264 if ( !$pluralRules ) {
4265 foreach ( $fallbacks as $fallbackCode ) {
4266 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4267 if ( $pluralRules ) {
4272 return $pluralRules;
4276 * Find the plural form matching to the given number
4277 * It return the form index.
4278 * @return int The index of the plural form
4280 private function getPluralForm( $number ) {
4281 $pluralRules = $this->getCompiledPluralRules();
4282 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );