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( dirname( __FILE__
) . '/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 getVariants() { return array( $this->mLang
->getCode() ); }
58 function getPreferredVariant() { return $this->mLang
->getCode(); }
59 function getDefaultVariant() { return $this->mLang
->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
72 * Internationalisation code
78 * @var LanguageConverter
82 var $mVariants, $mCode, $mLoaded = false;
83 var $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 var $dateFormatStrings = array();
87 var $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
92 * ReplacementArray object caches
94 var $transformData = array();
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
161 static public $durationIntervals = array(
162 'millennia' => 31557600000,
163 'centuries' => 3155760000,
164 'decades' => 315576000,
165 'years' => 31557600, // 86400 * 365.25
174 * Get a cached language object for a given language code
175 * @param $code String
178 static function factory( $code ) {
179 if ( !isset( self
::$mLangObjCache[$code] ) ) {
180 if ( count( self
::$mLangObjCache ) > 10 ) {
181 // Don't keep a billion objects around, that's stupid.
182 self
::$mLangObjCache = array();
184 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
186 return self
::$mLangObjCache[$code];
190 * Create a language object for a given language code
191 * @param $code String
192 * @throws MWException
195 protected static function newFromCode( $code ) {
196 // Protect against path traversal below
197 if ( !Language
::isValidCode( $code )
198 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
200 throw new MWException( "Invalid language code \"$code\"" );
203 if ( !Language
::isValidBuiltInCode( $code ) ) {
204 // It's not possible to customise this code with class files, so
205 // just return a Language object. This is to support uselang= hacks.
206 $lang = new Language
;
207 $lang->setCode( $code );
211 // Check if there is a language class for the code
212 $class = self
::classFromCode( $code );
213 self
::preloadLanguageClass( $class );
214 if ( MWInit
::classExists( $class ) ) {
219 // Keep trying the fallback list until we find an existing class
220 $fallbacks = Language
::getFallbacksFor( $code );
221 foreach ( $fallbacks as $fallbackCode ) {
222 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
223 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
226 $class = self
::classFromCode( $fallbackCode );
227 self
::preloadLanguageClass( $class );
228 if ( MWInit
::classExists( $class ) ) {
229 $lang = Language
::newFromCode( $fallbackCode );
230 $lang->setCode( $code );
235 throw new MWException( "Invalid fallback sequence for language '$code'" );
239 * Returns true if a language code string is of a valid form, whether or
240 * not it exists. This includes codes which are used solely for
241 * customisation via the MediaWiki namespace.
243 * @param $code string
247 public static function isValidCode( $code ) {
249 strcspn( $code, ":/\\\000" ) === strlen( $code )
250 && !preg_match( Title
::getTitleInvalidRegex(), $code );
254 * Returns true if a language code is of a valid form for the purposes of
255 * internal customisation of MediaWiki, via Messages*.php.
257 * @param $code string
262 public static function isValidBuiltInCode( $code ) {
264 if( !is_string($code) ) {
265 $type = gettype( $code );
266 if( $type === 'object' ) {
267 $addmsg = " of class " . get_class( $code );
271 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
274 return preg_match( '/^[a-z0-9-]+$/i', $code );
279 * @return String Name of the language class
281 public static function classFromCode( $code ) {
282 if ( $code == 'en' ) {
285 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
290 * Includes language class files
292 * @param $class string Name of the language class
294 public static function preloadLanguageClass( $class ) {
297 if ( $class === 'Language' ) {
301 if ( !defined( 'MW_COMPILED' ) ) {
302 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
303 include_once( "$IP/languages/classes/$class.php" );
309 * Get the LocalisationCache instance
311 * @return LocalisationCache
313 public static function getLocalisationCache() {
314 if ( is_null( self
::$dataCache ) ) {
315 global $wgLocalisationCacheConf;
316 $class = $wgLocalisationCacheConf['class'];
317 self
::$dataCache = new $class( $wgLocalisationCacheConf );
319 return self
::$dataCache;
322 function __construct() {
323 $this->mConverter
= new FakeConverter( $this );
324 // Set the code to the name of the descendant
325 if ( get_class( $this ) == 'Language' ) {
328 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
330 self
::getLocalisationCache();
334 * Reduce memory usage
336 function __destruct() {
337 foreach ( $this as $name => $value ) {
338 unset( $this->$name );
343 * Hook which will be called if this is the content language.
344 * Descendants can use this to register hook functions or modify globals
346 function initContLang() { }
349 * Same as getFallbacksFor for current language.
351 * @deprecated in 1.19
353 function getFallbackLanguageCode() {
354 wfDeprecated( __METHOD__
);
355 return self
::getFallbackFor( $this->mCode
);
362 function getFallbackLanguages() {
363 return self
::getFallbacksFor( $this->mCode
);
367 * Exports $wgBookstoreListEn
370 function getBookstoreList() {
371 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
377 public function getNamespaces() {
378 if ( is_null( $this->namespaceNames
) ) {
379 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
381 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
382 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
384 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
386 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
387 if ( $wgMetaNamespaceTalk ) {
388 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
390 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
391 $this->namespaceNames
[NS_PROJECT_TALK
] =
392 $this->fixVariableInNamespace( $talk );
395 # Sometimes a language will be localised but not actually exist on this wiki.
396 foreach ( $this->namespaceNames
as $key => $text ) {
397 if ( !isset( $validNamespaces[$key] ) ) {
398 unset( $this->namespaceNames
[$key] );
402 # The above mixing may leave namespaces out of canonical order.
403 # Re-order by namespace ID number...
404 ksort( $this->namespaceNames
);
406 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
408 return $this->namespaceNames
;
412 * Arbitrarily set all of the namespace names at once. Mainly used for testing
413 * @param $namespaces Array of namespaces (id => name)
415 public function setNamespaces( array $namespaces ) {
416 $this->namespaceNames
= $namespaces;
420 * A convenience function that returns the same thing as
421 * getNamespaces() except with the array values changed to ' '
422 * where it found '_', useful for producing output to be displayed
423 * e.g. in <select> forms.
427 function getFormattedNamespaces() {
428 $ns = $this->getNamespaces();
429 foreach ( $ns as $k => $v ) {
430 $ns[$k] = strtr( $v, '_', ' ' );
436 * Get a namespace value by key
438 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
439 * echo $mw_ns; // prints 'MediaWiki'
442 * @param $index Int: the array key of the namespace to return
443 * @return mixed, string if the namespace value exists, otherwise false
445 function getNsText( $index ) {
446 $ns = $this->getNamespaces();
447 return isset( $ns[$index] ) ?
$ns[$index] : false;
451 * A convenience function that returns the same thing as
452 * getNsText() except with '_' changed to ' ', useful for
455 * @param $index string
459 function getFormattedNsText( $index ) {
460 $ns = $this->getNsText( $index );
461 return strtr( $ns, '_', ' ' );
465 * Returns gender-dependent namespace alias if available.
466 * @param $index Int: namespace index
467 * @param $gender String: gender key (male, female... )
471 function getGenderNsText( $index, $gender ) {
472 global $wgExtraGenderNamespaces;
474 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
475 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
479 * Whether this language makes distinguishes genders for example in
484 function needsGenderDistinction() {
485 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
486 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
487 // $wgExtraGenderNamespaces overrides everything
489 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
490 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
491 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
494 // Check what is in i18n files
495 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
496 return count( $aliases ) > 0;
501 * Get a namespace key by value, case insensitive.
502 * Only matches namespace names for the current language, not the
503 * canonical ones defined in Namespace.php.
505 * @param $text String
506 * @return mixed An integer if $text is a valid value otherwise false
508 function getLocalNsIndex( $text ) {
509 $lctext = $this->lc( $text );
510 $ids = $this->getNamespaceIds();
511 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
517 function getNamespaceAliases() {
518 if ( is_null( $this->namespaceAliases
) ) {
519 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
523 foreach ( $aliases as $name => $index ) {
524 if ( $index === NS_PROJECT_TALK
) {
525 unset( $aliases[$name] );
526 $name = $this->fixVariableInNamespace( $name );
527 $aliases[$name] = $index;
532 global $wgExtraGenderNamespaces;
533 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
534 foreach ( $genders as $index => $forms ) {
535 foreach ( $forms as $alias ) {
536 $aliases[$alias] = $index;
540 $this->namespaceAliases
= $aliases;
542 return $this->namespaceAliases
;
548 function getNamespaceIds() {
549 if ( is_null( $this->mNamespaceIds
) ) {
550 global $wgNamespaceAliases;
551 # Put namespace names and aliases into a hashtable.
552 # If this is too slow, then we should arrange it so that it is done
553 # before caching. The catch is that at pre-cache time, the above
554 # class-specific fixup hasn't been done.
555 $this->mNamespaceIds
= array();
556 foreach ( $this->getNamespaces() as $index => $name ) {
557 $this->mNamespaceIds
[$this->lc( $name )] = $index;
559 foreach ( $this->getNamespaceAliases() as $name => $index ) {
560 $this->mNamespaceIds
[$this->lc( $name )] = $index;
562 if ( $wgNamespaceAliases ) {
563 foreach ( $wgNamespaceAliases as $name => $index ) {
564 $this->mNamespaceIds
[$this->lc( $name )] = $index;
568 return $this->mNamespaceIds
;
572 * Get a namespace key by value, case insensitive. Canonical namespace
573 * names override custom ones defined for the current language.
575 * @param $text String
576 * @return mixed An integer if $text is a valid value otherwise false
578 function getNsIndex( $text ) {
579 $lctext = $this->lc( $text );
580 $ns = MWNamespace
::getCanonicalIndex( $lctext );
581 if ( $ns !== null ) {
584 $ids = $this->getNamespaceIds();
585 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
589 * short names for language variants used for language conversion links.
591 * @param $code String
592 * @param $usemsg bool Use the "variantname-xyz" message if it exists
595 function getVariantname( $code, $usemsg = true ) {
596 $msg = "variantname-$code";
597 if ( $usemsg && wfMessage( $msg )->exists() ) {
598 return $this->getMessageFromDB( $msg );
600 $name = self
::fetchLanguageName( $code );
602 return $name; # if it's defined as a language name, show that
604 # otherwise, output the language code
610 * @param $name string
613 function specialPage( $name ) {
614 $aliases = $this->getSpecialPageAliases();
615 if ( isset( $aliases[$name][0] ) ) {
616 $name = $aliases[$name][0];
618 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
624 function getQuickbarSettings() {
626 $this->getMessage( 'qbsettings-none' ),
627 $this->getMessage( 'qbsettings-fixedleft' ),
628 $this->getMessage( 'qbsettings-fixedright' ),
629 $this->getMessage( 'qbsettings-floatingleft' ),
630 $this->getMessage( 'qbsettings-floatingright' ),
631 $this->getMessage( 'qbsettings-directionality' )
638 function getDatePreferences() {
639 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
645 function getDateFormats() {
646 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
650 * @return array|string
652 function getDefaultDateFormat() {
653 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
654 if ( $df === 'dmy or mdy' ) {
655 global $wgAmericanDates;
656 return $wgAmericanDates ?
'mdy' : 'dmy';
665 function getDatePreferenceMigrationMap() {
666 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
673 function getImageFile( $image ) {
674 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
680 function getExtraUserToggles() {
681 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
688 function getUserToggle( $tog ) {
689 return $this->getMessageFromDB( "tog-$tog" );
693 * Get native language names, indexed by code.
694 * Only those defined in MediaWiki, no other data like CLDR.
695 * If $customisedOnly is true, only returns codes with a messages file
697 * @param $customisedOnly bool
700 * @deprecated in 1.20, use fetchLanguageNames()
702 public static function getLanguageNames( $customisedOnly = false ) {
703 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
707 * Get translated language names. This is done on best effort and
708 * by default this is exactly the same as Language::getLanguageNames.
709 * The CLDR extension provides translated names.
710 * @param $code String Language code.
711 * @return Array language code => language name
713 * @deprecated in 1.20, use fetchLanguageNames()
715 public static function getTranslatedLanguageNames( $code ) {
716 return self
::fetchLanguageNames( $code, 'all' );
720 * Get an array of language names, indexed by code.
721 * @param $inLanguage null|string: Code of language in which to return the names
722 * Use null for autonyms (native names)
723 * @param $include string:
724 * 'all' all available languages
725 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
726 * 'mwfile' only if the language is in 'mw' *and* has a message file
727 * @return array: language code => language name
730 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
731 global $wgExtraLanguageNames;
732 static $coreLanguageNames;
734 if ( $coreLanguageNames === null ) {
735 include( MWInit
::compiledPath( 'languages/Names.php' ) );
741 # TODO: also include when $inLanguage is null, when this code is more efficient
742 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
745 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
746 foreach ( $mwNames as $mwCode => $mwName ) {
747 # - Prefer own MediaWiki native name when not using the hook
748 # - For other names just add if not added through the hook
749 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
750 $names[$mwCode] = $mwName;
754 if ( $include === 'all' ) {
759 $coreCodes = array_keys( $mwNames );
760 foreach( $coreCodes as $coreCode ) {
761 $returnMw[$coreCode] = $names[$coreCode];
764 if( $include === 'mwfile' ) {
765 $namesMwFile = array();
766 # We do this using a foreach over the codes instead of a directory
767 # loop so that messages files in extensions will work correctly.
768 foreach ( $returnMw as $code => $value ) {
769 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
770 $namesMwFile[$code] = $names[$code];
775 # 'mw' option; default if it's not one of the other two options (all/mwfile)
780 * @param $code string: The code of the language for which to get the name
781 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
782 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
783 * @return string: Language name or empty
786 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
787 $array = self
::fetchLanguageNames( $inLanguage, $include );
788 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
792 * Get a message from the MediaWiki namespace.
794 * @param $msg String: message name
797 function getMessageFromDB( $msg ) {
798 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
802 * Get the native language name of $code.
803 * Only if defined in MediaWiki, no other data like CLDR.
804 * @param $code string
806 * @deprecated in 1.20, use fetchLanguageName()
808 function getLanguageName( $code ) {
809 return self
::fetchLanguageName( $code );
816 function getMonthName( $key ) {
817 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
823 function getMonthNamesArray() {
824 $monthNames = array( '' );
825 for ( $i = 1; $i < 13; $i++
) {
826 $monthNames[] = $this->getMonthName( $i );
835 function getMonthNameGen( $key ) {
836 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
843 function getMonthAbbreviation( $key ) {
844 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
850 function getMonthAbbreviationsArray() {
851 $monthNames = array( '' );
852 for ( $i = 1; $i < 13; $i++
) {
853 $monthNames[] = $this->getMonthAbbreviation( $i );
862 function getWeekdayName( $key ) {
863 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
870 function getWeekdayAbbreviation( $key ) {
871 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
878 function getIranianCalendarMonthName( $key ) {
879 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
886 function getHebrewCalendarMonthName( $key ) {
887 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
894 function getHebrewCalendarMonthNameGen( $key ) {
895 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
902 function getHijriCalendarMonthName( $key ) {
903 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
907 * This is a workalike of PHP's date() function, but with better
908 * internationalisation, a reduced set of format characters, and a better
911 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
912 * PHP manual for definitions. There are a number of extensions, which
915 * xn Do not translate digits of the next numeric format character
916 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
917 * xr Use roman numerals for the next numeric format character
918 * xh Use hebrew numerals for the next numeric format character
920 * xg Genitive month name
922 * xij j (day number) in Iranian calendar
923 * xiF F (month name) in Iranian calendar
924 * xin n (month number) in Iranian calendar
925 * xiy y (two digit year) in Iranian calendar
926 * xiY Y (full year) in Iranian calendar
928 * xjj j (day number) in Hebrew calendar
929 * xjF F (month name) in Hebrew calendar
930 * xjt t (days in month) in Hebrew calendar
931 * xjx xg (genitive month name) in Hebrew calendar
932 * xjn n (month number) in Hebrew calendar
933 * xjY Y (full year) in Hebrew calendar
935 * xmj j (day number) in Hijri calendar
936 * xmF F (month name) in Hijri calendar
937 * xmn n (month number) in Hijri calendar
938 * xmY Y (full year) in Hijri calendar
940 * xkY Y (full year) in Thai solar calendar. Months and days are
941 * identical to the Gregorian calendar
942 * xoY Y (full year) in Minguo calendar or Juche year.
943 * Months and days are identical to the
945 * xtY Y (full year) in Japanese nengo. Months and days are
946 * identical to the Gregorian calendar
948 * Characters enclosed in double quotes will be considered literal (with
949 * the quotes themselves removed). Unmatched quotes will be considered
950 * literal quotes. Example:
952 * "The month is" F => The month is January
955 * Backslash escaping is also supported.
957 * Input timestamp is assumed to be pre-normalized to the desired local
960 * @param $format String
961 * @param $ts String: 14-character timestamp
964 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
968 function sprintfDate( $format, $ts ) {
981 for ( $p = 0; $p < strlen( $format ); $p++
) {
984 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
985 $code .= $format[++
$p];
988 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
989 $code .= $format[++
$p];
1000 $rawToggle = !$rawToggle;
1009 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1012 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1013 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1016 $num = substr( $ts, 6, 2 );
1019 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1020 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1023 $num = intval( substr( $ts, 6, 2 ) );
1027 $iranian = self
::tsToIranian( $ts );
1033 $hijri = self
::tsToHijri( $ts );
1039 $hebrew = self
::tsToHebrew( $ts );
1045 $unix = wfTimestamp( TS_UNIX
, $ts );
1047 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1051 $unix = wfTimestamp( TS_UNIX
, $ts );
1053 $w = gmdate( 'w', $unix );
1058 $unix = wfTimestamp( TS_UNIX
, $ts );
1060 $num = gmdate( 'w', $unix );
1064 $unix = wfTimestamp( TS_UNIX
, $ts );
1066 $num = gmdate( 'z', $unix );
1070 $unix = wfTimestamp( TS_UNIX
, $ts );
1072 $num = gmdate( 'W', $unix );
1075 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1079 $iranian = self
::tsToIranian( $ts );
1081 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1085 $hijri = self
::tsToHijri( $ts );
1087 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1091 $hebrew = self
::tsToHebrew( $ts );
1093 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1096 $num = substr( $ts, 4, 2 );
1099 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1102 $num = intval( substr( $ts, 4, 2 ) );
1106 $iranian = self
::tsToIranian( $ts );
1112 $hijri = self
::tsToHijri ( $ts );
1118 $hebrew = self
::tsToHebrew( $ts );
1124 $unix = wfTimestamp( TS_UNIX
, $ts );
1126 $num = gmdate( 't', $unix );
1130 $hebrew = self
::tsToHebrew( $ts );
1136 $unix = wfTimestamp( TS_UNIX
, $ts );
1138 $num = gmdate( 'L', $unix );
1142 $unix = wfTimestamp( TS_UNIX
, $ts );
1144 $num = gmdate( 'o', $unix );
1147 $num = substr( $ts, 0, 4 );
1151 $iranian = self
::tsToIranian( $ts );
1157 $hijri = self
::tsToHijri( $ts );
1163 $hebrew = self
::tsToHebrew( $ts );
1169 $thai = self
::tsToYear( $ts, 'thai' );
1175 $minguo = self
::tsToYear( $ts, 'minguo' );
1181 $tenno = self
::tsToYear( $ts, 'tenno' );
1186 $num = substr( $ts, 2, 2 );
1190 $iranian = self
::tsToIranian( $ts );
1192 $num = substr( $iranian[0], -2 );
1195 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1198 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1201 $h = substr( $ts, 8, 2 );
1202 $num = $h %
12 ?
$h %
12 : 12;
1205 $num = intval( substr( $ts, 8, 2 ) );
1208 $h = substr( $ts, 8, 2 );
1209 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1212 $num = substr( $ts, 8, 2 );
1215 $num = substr( $ts, 10, 2 );
1218 $num = substr( $ts, 12, 2 );
1222 $unix = wfTimestamp( TS_UNIX
, $ts );
1224 $s .= gmdate( 'c', $unix );
1228 $unix = wfTimestamp( TS_UNIX
, $ts );
1230 $s .= gmdate( 'r', $unix );
1234 $unix = wfTimestamp( TS_UNIX
, $ts );
1239 # Backslash escaping
1240 if ( $p < strlen( $format ) - 1 ) {
1241 $s .= $format[++
$p];
1248 if ( $p < strlen( $format ) - 1 ) {
1249 $endQuote = strpos( $format, '"', $p +
1 );
1250 if ( $endQuote === false ) {
1251 # No terminating quote, assume literal "
1254 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1258 # Quote at end of string, assume literal "
1265 if ( $num !== false ) {
1266 if ( $rawToggle ||
$raw ) {
1269 } elseif ( $roman ) {
1270 $s .= self
::romanNumeral( $num );
1272 } elseif ( $hebrewNum ) {
1273 $s .= self
::hebrewNumeral( $num );
1276 $s .= $this->formatNum( $num, true );
1283 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1284 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1287 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1288 * Gregorian dates to Iranian dates. Originally written in C, it
1289 * is released under the terms of GNU Lesser General Public
1290 * License. Conversion to PHP was performed by Niklas Laxström.
1292 * Link: http://www.farsiweb.info/jalali/jalali.c
1298 private static function tsToIranian( $ts ) {
1299 $gy = substr( $ts, 0, 4 ) -1600;
1300 $gm = substr( $ts, 4, 2 ) -1;
1301 $gd = substr( $ts, 6, 2 ) -1;
1303 # Days passed from the beginning (including leap years)
1305 +
floor( ( $gy +
3 ) / 4 )
1306 - floor( ( $gy +
99 ) / 100 )
1307 +
floor( ( $gy +
399 ) / 400 );
1309 // Add days of the past months of this year
1310 for ( $i = 0; $i < $gm; $i++
) {
1311 $gDayNo +
= self
::$GREG_DAYS[$i];
1315 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1319 // Days passed in current month
1320 $gDayNo +
= (int)$gd;
1322 $jDayNo = $gDayNo - 79;
1324 $jNp = floor( $jDayNo / 12053 );
1327 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1330 if ( $jDayNo >= 366 ) {
1331 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1332 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1335 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1336 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1342 return array( $jy, $jm, $jd );
1346 * Converting Gregorian dates to Hijri dates.
1348 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1350 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1356 private static function tsToHijri( $ts ) {
1357 $year = substr( $ts, 0, 4 );
1358 $month = substr( $ts, 4, 2 );
1359 $day = substr( $ts, 6, 2 );
1367 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1368 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1371 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1372 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1373 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1376 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1377 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1380 $zl = $zjd -1948440 +
10632;
1381 $zn = (int)( ( $zl - 1 ) / 10631 );
1382 $zl = $zl - 10631 * $zn +
354;
1383 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1384 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1385 $zm = (int)( ( 24 * $zl ) / 709 );
1386 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1387 $zy = 30 * $zn +
$zj - 30;
1389 return array( $zy, $zm, $zd );
1393 * Converting Gregorian dates to Hebrew dates.
1395 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1396 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1397 * to translate the relevant functions into PHP and release them under
1400 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1401 * and Adar II is 14. In a non-leap year, Adar is 6.
1407 private static function tsToHebrew( $ts ) {
1409 $year = substr( $ts, 0, 4 );
1410 $month = substr( $ts, 4, 2 );
1411 $day = substr( $ts, 6, 2 );
1413 # Calculate Hebrew year
1414 $hebrewYear = $year +
3760;
1416 # Month number when September = 1, August = 12
1418 if ( $month > 12 ) {
1425 # Calculate day of year from 1 September
1427 for ( $i = 1; $i < $month; $i++
) {
1431 # Check if the year is leap
1432 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1435 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1442 # Calculate the start of the Hebrew year
1443 $start = self
::hebrewYearStart( $hebrewYear );
1445 # Calculate next year's start
1446 if ( $dayOfYear <= $start ) {
1447 # Day is before the start of the year - it is the previous year
1449 $nextStart = $start;
1453 # Add days since previous year's 1 September
1455 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1459 # Start of the new (previous) year
1460 $start = self
::hebrewYearStart( $hebrewYear );
1463 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1466 # Calculate Hebrew day of year
1467 $hebrewDayOfYear = $dayOfYear - $start;
1469 # Difference between year's days
1470 $diff = $nextStart - $start;
1471 # Add 12 (or 13 for leap years) days to ignore the difference between
1472 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1473 # difference is only about the year type
1474 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1480 # Check the year pattern, and is leap year
1481 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1482 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1483 # and non-leap years
1484 $yearPattern = $diff %
30;
1485 # Check if leap year
1486 $isLeap = $diff >= 30;
1488 # Calculate day in the month from number of day in the Hebrew year
1489 # Don't check Adar - if the day is not in Adar, we will stop before;
1490 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1491 $hebrewDay = $hebrewDayOfYear;
1494 while ( $hebrewMonth <= 12 ) {
1495 # Calculate days in this month
1496 if ( $isLeap && $hebrewMonth == 6 ) {
1497 # Adar in a leap year
1499 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1501 if ( $hebrewDay <= $days ) {
1505 # Subtract the days of Adar I
1506 $hebrewDay -= $days;
1509 if ( $hebrewDay <= $days ) {
1515 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1516 # Cheshvan in a complete year (otherwise as the rule below)
1518 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1519 # Kislev in an incomplete year (otherwise as the rule below)
1522 # Odd months have 30 days, even have 29
1523 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1525 if ( $hebrewDay <= $days ) {
1526 # In the current month
1529 # Subtract the days of the current month
1530 $hebrewDay -= $days;
1531 # Try in the next month
1536 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1540 * This calculates the Hebrew year start, as days since 1 September.
1541 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1542 * Used for Hebrew date.
1548 private static function hebrewYearStart( $year ) {
1549 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1550 $b = intval( ( $year - 1 ) %
4 );
1551 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1555 $Mar = intval( $m );
1561 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1562 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1564 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1566 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1570 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1575 * Algorithm to convert Gregorian dates to Thai solar dates,
1576 * Minguo dates or Minguo dates.
1578 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1579 * http://en.wikipedia.org/wiki/Minguo_calendar
1580 * http://en.wikipedia.org/wiki/Japanese_era_name
1582 * @param $ts String: 14-character timestamp
1583 * @param $cName String: calender name
1584 * @return Array: converted year, month, day
1586 private static function tsToYear( $ts, $cName ) {
1587 $gy = substr( $ts, 0, 4 );
1588 $gm = substr( $ts, 4, 2 );
1589 $gd = substr( $ts, 6, 2 );
1591 if ( !strcmp( $cName, 'thai' ) ) {
1593 # Add 543 years to the Gregorian calendar
1594 # Months and days are identical
1595 $gy_offset = $gy +
543;
1596 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1598 # Deduct 1911 years from the Gregorian calendar
1599 # Months and days are identical
1600 $gy_offset = $gy - 1911;
1601 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1602 # Nengō dates up to Meiji period
1603 # Deduct years from the Gregorian calendar
1604 # depending on the nengo periods
1605 # Months and days are identical
1606 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1608 $gy_gannen = $gy - 1868 +
1;
1609 $gy_offset = $gy_gannen;
1610 if ( $gy_gannen == 1 ) {
1613 $gy_offset = '明治' . $gy_offset;
1615 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1616 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1617 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1618 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1619 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1623 $gy_gannen = $gy - 1912 +
1;
1624 $gy_offset = $gy_gannen;
1625 if ( $gy_gannen == 1 ) {
1628 $gy_offset = '大正' . $gy_offset;
1630 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1631 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1632 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1636 $gy_gannen = $gy - 1926 +
1;
1637 $gy_offset = $gy_gannen;
1638 if ( $gy_gannen == 1 ) {
1641 $gy_offset = '昭和' . $gy_offset;
1644 $gy_gannen = $gy - 1989 +
1;
1645 $gy_offset = $gy_gannen;
1646 if ( $gy_gannen == 1 ) {
1649 $gy_offset = '平成' . $gy_offset;
1655 return array( $gy_offset, $gm, $gd );
1659 * Roman number formatting up to 3000
1665 static function romanNumeral( $num ) {
1666 static $table = array(
1667 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1668 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1669 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1670 array( '', 'M', 'MM', 'MMM' )
1673 $num = intval( $num );
1674 if ( $num > 3000 ||
$num <= 0 ) {
1679 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1680 if ( $num >= $pow10 ) {
1681 $s .= $table[$i][(int)floor( $num / $pow10 )];
1683 $num = $num %
$pow10;
1689 * Hebrew Gematria number formatting up to 9999
1695 static function hebrewNumeral( $num ) {
1696 static $table = array(
1697 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1698 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1699 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1700 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1703 $num = intval( $num );
1704 if ( $num > 9999 ||
$num <= 0 ) {
1709 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1710 if ( $num >= $pow10 ) {
1711 if ( $num == 15 ||
$num == 16 ) {
1712 $s .= $table[0][9] . $table[0][$num - 9];
1715 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1716 if ( $pow10 == 1000 ) {
1721 $num = $num %
$pow10;
1723 if ( strlen( $s ) == 2 ) {
1726 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1727 $str .= substr( $s, strlen( $s ) - 2, 2 );
1729 $start = substr( $str, 0, strlen( $str ) - 2 );
1730 $end = substr( $str, strlen( $str ) - 2 );
1733 $str = $start . 'ך';
1736 $str = $start . 'ם';
1739 $str = $start . 'ן';
1742 $str = $start . 'ף';
1745 $str = $start . 'ץ';
1752 * Used by date() and time() to adjust the time output.
1754 * @param $ts Int the time in date('YmdHis') format
1755 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1756 * get user timecorrection setting)
1759 function userAdjust( $ts, $tz = false ) {
1760 global $wgUser, $wgLocalTZoffset;
1762 if ( $tz === false ) {
1763 $tz = $wgUser->getOption( 'timecorrection' );
1766 $data = explode( '|', $tz, 3 );
1768 if ( $data[0] == 'ZoneInfo' ) {
1769 wfSuppressWarnings();
1770 $userTZ = timezone_open( $data[2] );
1771 wfRestoreWarnings();
1772 if ( $userTZ !== false ) {
1773 $date = date_create( $ts, timezone_open( 'UTC' ) );
1774 date_timezone_set( $date, $userTZ );
1775 $date = date_format( $date, 'YmdHis' );
1778 # Unrecognized timezone, default to 'Offset' with the stored offset.
1779 $data[0] = 'Offset';
1783 if ( $data[0] == 'System' ||
$tz == '' ) {
1784 # Global offset in minutes.
1785 if ( isset( $wgLocalTZoffset ) ) {
1786 $minDiff = $wgLocalTZoffset;
1788 } elseif ( $data[0] == 'Offset' ) {
1789 $minDiff = intval( $data[1] );
1791 $data = explode( ':', $tz );
1792 if ( count( $data ) == 2 ) {
1793 $data[0] = intval( $data[0] );
1794 $data[1] = intval( $data[1] );
1795 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1796 if ( $data[0] < 0 ) {
1797 $minDiff = -$minDiff;
1800 $minDiff = intval( $data[0] ) * 60;
1804 # No difference ? Return time unchanged
1805 if ( 0 == $minDiff ) {
1809 wfSuppressWarnings(); // E_STRICT system time bitching
1810 # Generate an adjusted date; take advantage of the fact that mktime
1811 # will normalize out-of-range values so we don't have to split $minDiff
1812 # into hours and minutes.
1814 (int)substr( $ts, 8, 2 ) ), # Hours
1815 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1816 (int)substr( $ts, 12, 2 ), # Seconds
1817 (int)substr( $ts, 4, 2 ), # Month
1818 (int)substr( $ts, 6, 2 ), # Day
1819 (int)substr( $ts, 0, 4 ) ); # Year
1821 $date = date( 'YmdHis', $t );
1822 wfRestoreWarnings();
1828 * This is meant to be used by time(), date(), and timeanddate() to get
1829 * the date preference they're supposed to use, it should be used in
1833 * function timeanddate([...], $format = true) {
1834 * $datePreference = $this->dateFormat($format);
1839 * @param $usePrefs Mixed: if true, the user's preference is used
1840 * if false, the site/language default is used
1841 * if int/string, assumed to be a format.
1844 function dateFormat( $usePrefs = true ) {
1847 if ( is_bool( $usePrefs ) ) {
1849 $datePreference = $wgUser->getDatePreference();
1851 $datePreference = (string)User
::getDefaultOption( 'date' );
1854 $datePreference = (string)$usePrefs;
1858 if ( $datePreference == '' ) {
1862 return $datePreference;
1866 * Get a format string for a given type and preference
1867 * @param $type string May be date, time or both
1868 * @param $pref string The format name as it appears in Messages*.php
1872 function getDateFormatString( $type, $pref ) {
1873 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1874 if ( $pref == 'default' ) {
1875 $pref = $this->getDefaultDateFormat();
1876 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1878 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1879 if ( is_null( $df ) ) {
1880 $pref = $this->getDefaultDateFormat();
1881 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1884 $this->dateFormatStrings
[$type][$pref] = $df;
1886 return $this->dateFormatStrings
[$type][$pref];
1890 * @param $ts Mixed: the time format which needs to be turned into a
1891 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1892 * @param $adj Bool: whether to adjust the time output according to the
1893 * user configured offset ($timecorrection)
1894 * @param $format Mixed: true to use user's date format preference
1895 * @param $timecorrection String|bool the time offset as returned by
1896 * validateTimeZone() in Special:Preferences
1899 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1900 $ts = wfTimestamp( TS_MW
, $ts );
1902 $ts = $this->userAdjust( $ts, $timecorrection );
1904 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1905 return $this->sprintfDate( $df, $ts );
1909 * @param $ts Mixed: the time format which needs to be turned into a
1910 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1911 * @param $adj Bool: whether to adjust the time output according to the
1912 * user configured offset ($timecorrection)
1913 * @param $format Mixed: true to use user's date format preference
1914 * @param $timecorrection String|bool the time offset as returned by
1915 * validateTimeZone() in Special:Preferences
1918 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1919 $ts = wfTimestamp( TS_MW
, $ts );
1921 $ts = $this->userAdjust( $ts, $timecorrection );
1923 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1924 return $this->sprintfDate( $df, $ts );
1928 * @param $ts Mixed: the time format which needs to be turned into a
1929 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1930 * @param $adj Bool: whether to adjust the time output according to the
1931 * user configured offset ($timecorrection)
1932 * @param $format Mixed: what format to return, if it's false output the
1933 * default one (default true)
1934 * @param $timecorrection String|bool the time offset as returned by
1935 * validateTimeZone() in Special:Preferences
1938 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1939 $ts = wfTimestamp( TS_MW
, $ts );
1941 $ts = $this->userAdjust( $ts, $timecorrection );
1943 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1944 return $this->sprintfDate( $df, $ts );
1948 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1952 * @param integer $seconds The amount of seconds.
1953 * @param array $chosenIntervals The intervals to enable.
1957 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1958 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1960 $segments = array();
1962 foreach ( $intervals as $intervalName => $intervalValue ) {
1963 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1964 $segments[] = $message->inLanguage( $this )->escaped();
1967 return $this->listToText( $segments );
1971 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1972 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1976 * @param integer $seconds The amount of seconds.
1977 * @param array $chosenIntervals The intervals to enable.
1981 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1982 if ( empty( $chosenIntervals ) ) {
1983 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1986 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
1987 $sortedNames = array_keys( $intervals );
1988 $smallestInterval = array_pop( $sortedNames );
1990 $segments = array();
1992 foreach ( $intervals as $name => $length ) {
1993 $value = floor( $seconds / $length );
1995 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
1996 $seconds -= $value * $length;
1997 $segments[$name] = $value;
2005 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2007 * @param $type String: can be 'date', 'time' or 'both'
2008 * @param $ts Mixed: the time format which needs to be turned into a
2009 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2010 * @param $user User object used to get preferences for timezone and format
2011 * @param $options Array, can contain the following keys:
2012 * - 'timecorrection': time correction, can have the following values:
2013 * - true: use user's preference
2014 * - false: don't use time correction
2015 * - integer: value of time correction in minutes
2016 * - 'format': format to use, can have the following values:
2017 * - true: use user's preference
2018 * - false: use default preference
2019 * - string: format to use
2023 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2024 $ts = wfTimestamp( TS_MW
, $ts );
2025 $options +
= array( 'timecorrection' => true, 'format' => true );
2026 if ( $options['timecorrection'] !== false ) {
2027 if ( $options['timecorrection'] === true ) {
2028 $offset = $user->getOption( 'timecorrection' );
2030 $offset = $options['timecorrection'];
2032 $ts = $this->userAdjust( $ts, $offset );
2034 if ( $options['format'] === true ) {
2035 $format = $user->getDatePreference();
2037 $format = $options['format'];
2039 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2040 return $this->sprintfDate( $df, $ts );
2044 * Get the formatted date for the given timestamp and formatted for
2047 * @param $ts Mixed: the time format which needs to be turned into a
2048 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2049 * @param $user User object used to get preferences for timezone and format
2050 * @param $options Array, can contain the following keys:
2051 * - 'timecorrection': time correction, can have the following values:
2052 * - true: use user's preference
2053 * - false: don't use time correction
2054 * - integer: value of time correction in minutes
2055 * - 'format': format to use, can have the following values:
2056 * - true: use user's preference
2057 * - false: use default preference
2058 * - string: format to use
2062 public function userDate( $ts, User
$user, array $options = array() ) {
2063 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2067 * Get the formatted time for the given timestamp and formatted for
2070 * @param $ts Mixed: the time format which needs to be turned into a
2071 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2072 * @param $user User object used to get preferences for timezone and format
2073 * @param $options Array, can contain the following keys:
2074 * - 'timecorrection': time correction, can have the following values:
2075 * - true: use user's preference
2076 * - false: don't use time correction
2077 * - integer: value of time correction in minutes
2078 * - 'format': format to use, can have the following values:
2079 * - true: use user's preference
2080 * - false: use default preference
2081 * - string: format to use
2085 public function userTime( $ts, User
$user, array $options = array() ) {
2086 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2090 * Get the formatted date and time for the given timestamp and formatted for
2093 * @param $ts Mixed: the time format which needs to be turned into a
2094 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2095 * @param $user User object used to get preferences for timezone and format
2096 * @param $options Array, can contain the following keys:
2097 * - 'timecorrection': time correction, can have the following values:
2098 * - true: use user's preference
2099 * - false: don't use time correction
2100 * - integer: value of time correction in minutes
2101 * - 'format': format to use, can have the following values:
2102 * - true: use user's preference
2103 * - false: use default preference
2104 * - string: format to use
2108 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2109 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2113 * @param $key string
2114 * @return array|null
2116 function getMessage( $key ) {
2117 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2123 function getAllMessages() {
2124 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2133 function iconv( $in, $out, $string ) {
2134 # This is a wrapper for iconv in all languages except esperanto,
2135 # which does some nasty x-conversions beforehand
2137 # Even with //IGNORE iconv can whine about illegal characters in
2138 # *input* string. We just ignore those too.
2139 # REF: http://bugs.php.net/bug.php?id=37166
2140 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2141 wfSuppressWarnings();
2142 $text = iconv( $in, $out . '//IGNORE', $string );
2143 wfRestoreWarnings();
2147 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2150 * @param $matches array
2151 * @return mixed|string
2153 function ucwordbreaksCallbackAscii( $matches ) {
2154 return $this->ucfirst( $matches[1] );
2158 * @param $matches array
2161 function ucwordbreaksCallbackMB( $matches ) {
2162 return mb_strtoupper( $matches[0] );
2166 * @param $matches array
2169 function ucCallback( $matches ) {
2170 list( $wikiUpperChars ) = self
::getCaseMaps();
2171 return strtr( $matches[1], $wikiUpperChars );
2175 * @param $matches array
2178 function lcCallback( $matches ) {
2179 list( , $wikiLowerChars ) = self
::getCaseMaps();
2180 return strtr( $matches[1], $wikiLowerChars );
2184 * @param $matches array
2187 function ucwordsCallbackMB( $matches ) {
2188 return mb_strtoupper( $matches[0] );
2192 * @param $matches array
2195 function ucwordsCallbackWiki( $matches ) {
2196 list( $wikiUpperChars ) = self
::getCaseMaps();
2197 return strtr( $matches[0], $wikiUpperChars );
2201 * Make a string's first character uppercase
2203 * @param $str string
2207 function ucfirst( $str ) {
2209 if ( $o < 96 ) { // if already uppercase...
2211 } elseif ( $o < 128 ) {
2212 return ucfirst( $str ); // use PHP's ucfirst()
2214 // fall back to more complex logic in case of multibyte strings
2215 return $this->uc( $str, true );
2220 * Convert a string to uppercase
2222 * @param $str string
2223 * @param $first bool
2227 function uc( $str, $first = false ) {
2228 if ( function_exists( 'mb_strtoupper' ) ) {
2230 if ( $this->isMultibyte( $str ) ) {
2231 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2233 return ucfirst( $str );
2236 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2239 if ( $this->isMultibyte( $str ) ) {
2240 $x = $first ?
'^' : '';
2241 return preg_replace_callback(
2242 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2243 array( $this, 'ucCallback' ),
2247 return $first ?
ucfirst( $str ) : strtoupper( $str );
2253 * @param $str string
2254 * @return mixed|string
2256 function lcfirst( $str ) {
2259 return strval( $str );
2260 } elseif ( $o >= 128 ) {
2261 return $this->lc( $str, true );
2262 } elseif ( $o > 96 ) {
2265 $str[0] = strtolower( $str[0] );
2271 * @param $str string
2272 * @param $first bool
2273 * @return mixed|string
2275 function lc( $str, $first = false ) {
2276 if ( function_exists( 'mb_strtolower' ) ) {
2278 if ( $this->isMultibyte( $str ) ) {
2279 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2281 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2284 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2287 if ( $this->isMultibyte( $str ) ) {
2288 $x = $first ?
'^' : '';
2289 return preg_replace_callback(
2290 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2291 array( $this, 'lcCallback' ),
2295 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2301 * @param $str string
2304 function isMultibyte( $str ) {
2305 return (bool)preg_match( '/[\x80-\xff]/', $str );
2309 * @param $str string
2310 * @return mixed|string
2312 function ucwords( $str ) {
2313 if ( $this->isMultibyte( $str ) ) {
2314 $str = $this->lc( $str );
2316 // regexp to find first letter in each word (i.e. after each space)
2317 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2319 // function to use to capitalize a single char
2320 if ( function_exists( 'mb_strtoupper' ) ) {
2321 return preg_replace_callback(
2323 array( $this, 'ucwordsCallbackMB' ),
2327 return preg_replace_callback(
2329 array( $this, 'ucwordsCallbackWiki' ),
2334 return ucwords( strtolower( $str ) );
2339 * capitalize words at word breaks
2341 * @param $str string
2344 function ucwordbreaks( $str ) {
2345 if ( $this->isMultibyte( $str ) ) {
2346 $str = $this->lc( $str );
2348 // since \b doesn't work for UTF-8, we explicitely define word break chars
2349 $breaks = "[ \-\(\)\}\{\.,\?!]";
2351 // find first letter after word break
2352 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2354 if ( function_exists( 'mb_strtoupper' ) ) {
2355 return preg_replace_callback(
2357 array( $this, 'ucwordbreaksCallbackMB' ),
2361 return preg_replace_callback(
2363 array( $this, 'ucwordsCallbackWiki' ),
2368 return preg_replace_callback(
2369 '/\b([\w\x80-\xff]+)\b/',
2370 array( $this, 'ucwordbreaksCallbackAscii' ),
2377 * Return a case-folded representation of $s
2379 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2380 * and $s2 are the same except for the case of their characters. It is not
2381 * necessary for the value returned to make sense when displayed.
2383 * Do *not* perform any other normalisation in this function. If a caller
2384 * uses this function when it should be using a more general normalisation
2385 * function, then fix the caller.
2391 function caseFold( $s ) {
2392 return $this->uc( $s );
2399 function checkTitleEncoding( $s ) {
2400 if ( is_array( $s ) ) {
2401 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2403 # Check for non-UTF-8 URLs
2404 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2409 if ( function_exists( 'mb_check_encoding' ) ) {
2410 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2412 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2413 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2419 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2425 function fallback8bitEncoding() {
2426 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2430 * Most writing systems use whitespace to break up words.
2431 * Some languages such as Chinese don't conventionally do this,
2432 * which requires special handling when breaking up words for
2437 function hasWordBreaks() {
2442 * Some languages such as Chinese require word segmentation,
2443 * Specify such segmentation when overridden in derived class.
2445 * @param $string String
2448 function segmentByWord( $string ) {
2453 * Some languages have special punctuation need to be normalized.
2454 * Make such changes here.
2456 * @param $string String
2459 function normalizeForSearch( $string ) {
2460 return self
::convertDoubleWidth( $string );
2464 * convert double-width roman characters to single-width.
2465 * range: ff00-ff5f ~= 0020-007f
2467 * @param $string string
2471 protected static function convertDoubleWidth( $string ) {
2472 static $full = null;
2473 static $half = null;
2475 if ( $full === null ) {
2476 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2477 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2478 $full = str_split( $fullWidth, 3 );
2479 $half = str_split( $halfWidth );
2482 $string = str_replace( $full, $half, $string );
2487 * @param $string string
2488 * @param $pattern string
2491 protected static function insertSpace( $string, $pattern ) {
2492 $string = preg_replace( $pattern, " $1 ", $string );
2493 $string = preg_replace( '/ +/', ' ', $string );
2498 * @param $termsArray array
2501 function convertForSearchResult( $termsArray ) {
2502 # some languages, e.g. Chinese, need to do a conversion
2503 # in order for search results to be displayed correctly
2508 * Get the first character of a string.
2513 function firstChar( $s ) {
2516 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2517 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2522 if ( isset( $matches[1] ) ) {
2523 if ( strlen( $matches[1] ) != 3 ) {
2527 // Break down Hangul syllables to grab the first jamo
2528 $code = utf8ToCodepoint( $matches[1] );
2529 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2531 } elseif ( $code < 0xb098 ) {
2532 return "\xe3\x84\xb1";
2533 } elseif ( $code < 0xb2e4 ) {
2534 return "\xe3\x84\xb4";
2535 } elseif ( $code < 0xb77c ) {
2536 return "\xe3\x84\xb7";
2537 } elseif ( $code < 0xb9c8 ) {
2538 return "\xe3\x84\xb9";
2539 } elseif ( $code < 0xbc14 ) {
2540 return "\xe3\x85\x81";
2541 } elseif ( $code < 0xc0ac ) {
2542 return "\xe3\x85\x82";
2543 } elseif ( $code < 0xc544 ) {
2544 return "\xe3\x85\x85";
2545 } elseif ( $code < 0xc790 ) {
2546 return "\xe3\x85\x87";
2547 } elseif ( $code < 0xcc28 ) {
2548 return "\xe3\x85\x88";
2549 } elseif ( $code < 0xce74 ) {
2550 return "\xe3\x85\x8a";
2551 } elseif ( $code < 0xd0c0 ) {
2552 return "\xe3\x85\x8b";
2553 } elseif ( $code < 0xd30c ) {
2554 return "\xe3\x85\x8c";
2555 } elseif ( $code < 0xd558 ) {
2556 return "\xe3\x85\x8d";
2558 return "\xe3\x85\x8e";
2565 function initEncoding() {
2566 # Some languages may have an alternate char encoding option
2567 # (Esperanto X-coding, Japanese furigana conversion, etc)
2568 # If this language is used as the primary content language,
2569 # an override to the defaults can be set here on startup.
2576 function recodeForEdit( $s ) {
2577 # For some languages we'll want to explicitly specify
2578 # which characters make it into the edit box raw
2579 # or are converted in some way or another.
2580 global $wgEditEncoding;
2581 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2584 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2592 function recodeInput( $s ) {
2593 # Take the previous into account.
2594 global $wgEditEncoding;
2595 if ( $wgEditEncoding != '' ) {
2596 $enc = $wgEditEncoding;
2600 if ( $enc == 'UTF-8' ) {
2603 return $this->iconv( $enc, 'UTF-8', $s );
2608 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2609 * also cleans up certain backwards-compatible sequences, converting them
2610 * to the modern Unicode equivalent.
2612 * This is language-specific for performance reasons only.
2618 function normalize( $s ) {
2619 global $wgAllUnicodeFixes;
2620 $s = UtfNormal
::cleanUp( $s );
2621 if ( $wgAllUnicodeFixes ) {
2622 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2623 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2630 * Transform a string using serialized data stored in the given file (which
2631 * must be in the serialized subdirectory of $IP). The file contains pairs
2632 * mapping source characters to destination characters.
2634 * The data is cached in process memory. This will go faster if you have the
2635 * FastStringSearch extension.
2637 * @param $file string
2638 * @param $string string
2640 * @throws MWException
2643 function transformUsingPairFile( $file, $string ) {
2644 if ( !isset( $this->transformData
[$file] ) ) {
2645 $data = wfGetPrecompiledData( $file );
2646 if ( $data === false ) {
2647 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2649 $this->transformData
[$file] = new ReplacementArray( $data );
2651 return $this->transformData
[$file]->replace( $string );
2655 * For right-to-left language support
2660 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2664 * Return the correct HTML 'dir' attribute value for this language.
2668 return $this->isRTL() ?
'rtl' : 'ltr';
2672 * Return 'left' or 'right' as appropriate alignment for line-start
2673 * for this language's text direction.
2675 * Should be equivalent to CSS3 'start' text-align value....
2679 function alignStart() {
2680 return $this->isRTL() ?
'right' : 'left';
2684 * Return 'right' or 'left' as appropriate alignment for line-end
2685 * for this language's text direction.
2687 * Should be equivalent to CSS3 'end' text-align value....
2691 function alignEnd() {
2692 return $this->isRTL() ?
'left' : 'right';
2696 * A hidden direction mark (LRM or RLM), depending on the language direction.
2697 * Unlike getDirMark(), this function returns the character as an HTML entity.
2698 * This function should be used when the output is guaranteed to be HTML,
2699 * because it makes the output HTML source code more readable. When
2700 * the output is plain text or can be escaped, getDirMark() should be used.
2702 * @param $opposite Boolean Get the direction mark opposite to your language
2705 function getDirMarkEntity( $opposite = false ) {
2706 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2707 return $this->isRTL() ?
'‏' : '‎';
2711 * A hidden direction mark (LRM or RLM), depending on the language direction.
2712 * This function produces them as invisible Unicode characters and
2713 * the output may be hard to read and debug, so it should only be used
2714 * when the output is plain text or can be escaped. When the output is
2715 * HTML, use getDirMarkEntity() instead.
2717 * @param $opposite Boolean Get the direction mark opposite to your language
2720 function getDirMark( $opposite = false ) {
2721 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2722 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2723 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2724 return $this->isRTL() ?
$rlm : $lrm;
2730 function capitalizeAllNouns() {
2731 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2735 * An arrow, depending on the language direction.
2737 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2740 function getArrow( $direction = 'forwards' ) {
2741 switch ( $direction ) {
2743 return $this->isRTL() ?
'←' : '→';
2745 return $this->isRTL() ?
'→' : '←';
2758 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2762 function linkPrefixExtension() {
2763 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2769 function getMagicWords() {
2770 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2773 protected function doMagicHook() {
2774 if ( $this->mMagicHookDone
) {
2777 $this->mMagicHookDone
= true;
2778 wfProfileIn( 'LanguageGetMagic' );
2779 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2780 wfProfileOut( 'LanguageGetMagic' );
2784 * Fill a MagicWord object with data from here
2788 function getMagic( $mw ) {
2789 $this->doMagicHook();
2791 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2792 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2794 $magicWords = $this->getMagicWords();
2795 if ( isset( $magicWords[$mw->mId
] ) ) {
2796 $rawEntry = $magicWords[$mw->mId
];
2802 if ( !is_array( $rawEntry ) ) {
2803 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2805 $mw->mCaseSensitive
= $rawEntry[0];
2806 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2811 * Add magic words to the extension array
2813 * @param $newWords array
2815 function addMagicWordsByLang( $newWords ) {
2816 $fallbackChain = $this->getFallbackLanguages();
2817 $fallbackChain = array_reverse( $fallbackChain );
2818 foreach ( $fallbackChain as $code ) {
2819 if ( isset( $newWords[$code] ) ) {
2820 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2826 * Get special page names, as an associative array
2827 * case folded alias => real name
2829 function getSpecialPageAliases() {
2830 // Cache aliases because it may be slow to load them
2831 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2833 $this->mExtendedSpecialPageAliases
=
2834 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2835 wfRunHooks( 'LanguageGetSpecialPageAliases',
2836 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2839 return $this->mExtendedSpecialPageAliases
;
2843 * Italic is unsuitable for some languages
2845 * @param $text String: the text to be emphasized.
2848 function emphasize( $text ) {
2849 return "<em>$text</em>";
2853 * Normally we output all numbers in plain en_US style, that is
2854 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2855 * point twohundredthirtyfive. However this is not suitable for all
2856 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2857 * Icelandic just want to use commas instead of dots, and dots instead
2858 * of commas like "293.291,235".
2860 * An example of this function being called:
2862 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2865 * See LanguageGu.php for the Gujarati implementation and
2866 * $separatorTransformTable on MessageIs.php for
2867 * the , => . and . => , implementation.
2869 * @todo check if it's viable to use localeconv() for the decimal
2871 * @param $number Mixed: the string to be formatted, should be an integer
2872 * or a floating point number.
2873 * @param $nocommafy Bool: set to true for special numbers like dates
2876 public function formatNum( $number, $nocommafy = false ) {
2877 global $wgTranslateNumerals;
2878 if ( !$nocommafy ) {
2879 $number = $this->commafy( $number );
2880 $s = $this->separatorTransformTable();
2882 $number = strtr( $number, $s );
2886 if ( $wgTranslateNumerals ) {
2887 $s = $this->digitTransformTable();
2889 $number = strtr( $number, $s );
2897 * @param $number string
2900 function parseFormattedNumber( $number ) {
2901 $s = $this->digitTransformTable();
2903 $number = strtr( $number, array_flip( $s ) );
2906 $s = $this->separatorTransformTable();
2908 $number = strtr( $number, array_flip( $s ) );
2911 $number = strtr( $number, array( ',' => '' ) );
2916 * Adds commas to a given number
2921 function commafy( $_ ) {
2922 $digitGroupingPattern = $this->digitGroupingPattern();
2923 if ( $_ === null ) {
2927 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
2928 // default grouping is at thousands, use the same for ###,###,### pattern too.
2929 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2931 // Ref: http://cldr.unicode.org/translation/number-patterns
2933 if ( intval( $_ ) < 0 ) {
2934 // For negative numbers apply the algorithm like positive number and add sign.
2936 $_ = substr( $_, 1 );
2938 $numberpart = array();
2939 $decimalpart = array();
2940 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2941 preg_match( "/\d+/", $_, $numberpart );
2942 preg_match( "/\.\d*/", $_, $decimalpart );
2943 $groupedNumber = ( count( $decimalpart ) > 0 ) ?
$decimalpart[0]:"";
2944 if ( $groupedNumber === $_ ) {
2945 // the string does not have any number part. Eg: .12345
2946 return $sign . $groupedNumber;
2948 $start = $end = strlen( $numberpart[0] );
2949 while ( $start > 0 ) {
2950 $match = $matches[0][$numMatches -1] ;
2951 $matchLen = strlen( $match );
2952 $start = $end - $matchLen;
2956 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2958 if ( $numMatches > 1 ) {
2959 // use the last pattern for the rest of the number
2963 $groupedNumber = "," . $groupedNumber;
2966 return $sign . $groupedNumber;
2972 function digitGroupingPattern() {
2973 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
2979 function digitTransformTable() {
2980 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2986 function separatorTransformTable() {
2987 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2991 * Take a list of strings and build a locale-friendly comma-separated
2992 * list, using the local comma-separator message.
2993 * The last two strings are chained with an "and".
2998 function listToText( array $l ) {
3000 $m = count( $l ) - 1;
3002 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3004 for ( $i = $m; $i >= 0; $i-- ) {
3007 } elseif ( $i == $m - 1 ) {
3008 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3010 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3018 * Take a list of strings and build a locale-friendly comma-separated
3019 * list, using the local comma-separator message.
3020 * @param $list array of strings to put in a comma list
3023 function commaList( array $list ) {
3027 array( 'parsemag', 'escapenoentities', 'language' => $this )
3034 * Take a list of strings and build a locale-friendly semicolon-separated
3035 * list, using the local semicolon-separator message.
3036 * @param $list array of strings to put in a semicolon list
3039 function semicolonList( array $list ) {
3042 'semicolon-separator',
3043 array( 'parsemag', 'escapenoentities', 'language' => $this )
3050 * Same as commaList, but separate it with the pipe instead.
3051 * @param $list array of strings to put in a pipe list
3054 function pipeList( array $list ) {
3058 array( 'escapenoentities', 'language' => $this )
3065 * Truncate a string to a specified length in bytes, appending an optional
3066 * string (e.g. for ellipses)
3068 * The database offers limited byte lengths for some columns in the database;
3069 * multi-byte character sets mean we need to ensure that only whole characters
3070 * are included, otherwise broken characters can be passed to the user
3072 * If $length is negative, the string will be truncated from the beginning
3074 * @param $string String to truncate
3075 * @param $length Int: maximum length (including ellipses)
3076 * @param $ellipsis String to append to the truncated text
3077 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3078 * $adjustLength was introduced in 1.18, before that behaved as if false.
3081 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3082 # Use the localized ellipsis character
3083 if ( $ellipsis == '...' ) {
3084 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3086 # Check if there is no need to truncate
3087 if ( $length == 0 ) {
3088 return $ellipsis; // convention
3089 } elseif ( strlen( $string ) <= abs( $length ) ) {
3090 return $string; // no need to truncate
3092 $stringOriginal = $string;
3093 # If ellipsis length is >= $length then we can't apply $adjustLength
3094 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3095 $string = $ellipsis; // this can be slightly unexpected
3096 # Otherwise, truncate and add ellipsis...
3098 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3099 if ( $length > 0 ) {
3100 $length -= $eLength;
3101 $string = substr( $string, 0, $length ); // xyz...
3102 $string = $this->removeBadCharLast( $string );
3103 $string = $string . $ellipsis;
3105 $length +
= $eLength;
3106 $string = substr( $string, $length ); // ...xyz
3107 $string = $this->removeBadCharFirst( $string );
3108 $string = $ellipsis . $string;
3111 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3112 # This check is *not* redundant if $adjustLength, due to the single case where
3113 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3114 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3117 return $stringOriginal;
3122 * Remove bytes that represent an incomplete Unicode character
3123 * at the end of string (e.g. bytes of the char are missing)
3125 * @param $string String
3128 protected function removeBadCharLast( $string ) {
3129 if ( $string != '' ) {
3130 $char = ord( $string[strlen( $string ) - 1] );
3132 if ( $char >= 0xc0 ) {
3133 # We got the first byte only of a multibyte char; remove it.
3134 $string = substr( $string, 0, -1 );
3135 } elseif ( $char >= 0x80 &&
3136 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3137 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3139 # We chopped in the middle of a character; remove it
3147 * Remove bytes that represent an incomplete Unicode character
3148 * at the start of string (e.g. bytes of the char are missing)
3150 * @param $string String
3153 protected function removeBadCharFirst( $string ) {
3154 if ( $string != '' ) {
3155 $char = ord( $string[0] );
3156 if ( $char >= 0x80 && $char < 0xc0 ) {
3157 # We chopped in the middle of a character; remove the whole thing
3158 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3165 * Truncate a string of valid HTML to a specified length in bytes,
3166 * appending an optional string (e.g. for ellipses), and return valid HTML
3168 * This is only intended for styled/linked text, such as HTML with
3169 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3170 * Also, this will not detect things like "display:none" CSS.
3172 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3174 * @param string $text HTML string to truncate
3175 * @param int $length (zero/positive) Maximum length (including ellipses)
3176 * @param string $ellipsis String to append to the truncated text
3179 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3180 # Use the localized ellipsis character
3181 if ( $ellipsis == '...' ) {
3182 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3184 # Check if there is clearly no need to truncate
3185 if ( $length <= 0 ) {
3186 return $ellipsis; // no text shown, nothing to format (convention)
3187 } elseif ( strlen( $text ) <= $length ) {
3188 return $text; // string short enough even *with* HTML (short-circuit)
3191 $dispLen = 0; // innerHTML legth so far
3192 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3193 $tagType = 0; // 0-open, 1-close
3194 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3195 $entityState = 0; // 0-not entity, 1-entity
3196 $tag = $ret = ''; // accumulated tag name, accumulated result string
3197 $openTags = array(); // open tag stack
3198 $maybeState = null; // possible truncation state
3200 $textLen = strlen( $text );
3201 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3202 for ( $pos = 0; true; ++
$pos ) {
3203 # Consider truncation once the display length has reached the maximim.
3204 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3205 # Check that we're not in the middle of a bracket/entity...
3206 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3207 if ( !$testingEllipsis ) {
3208 $testingEllipsis = true;
3209 # Save where we are; we will truncate here unless there turn out to
3210 # be so few remaining characters that truncation is not necessary.
3211 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3212 $maybeState = array( $ret, $openTags ); // save state
3214 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3215 # String in fact does need truncation, the truncation point was OK.
3216 list( $ret, $openTags ) = $maybeState; // reload state
3217 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3218 $ret .= $ellipsis; // add ellipsis
3222 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3224 # Read the next char...
3226 $lastCh = $pos ?
$text[$pos - 1] : '';
3227 $ret .= $ch; // add to result string
3229 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3230 $entityState = 0; // for bad HTML
3231 $bracketState = 1; // tag started (checking for backslash)
3232 } elseif ( $ch == '>' ) {
3233 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3234 $entityState = 0; // for bad HTML
3235 $bracketState = 0; // out of brackets
3236 } elseif ( $bracketState == 1 ) {
3238 $tagType = 1; // close tag (e.g. "</span>")
3240 $tagType = 0; // open tag (e.g. "<span>")
3243 $bracketState = 2; // building tag name
3244 } elseif ( $bracketState == 2 ) {
3248 // Name found (e.g. "<a href=..."), add on tag attributes...
3249 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3251 } elseif ( $bracketState == 0 ) {
3252 if ( $entityState ) {
3255 $dispLen++
; // entity is one displayed char
3258 if ( $neLength == 0 && !$maybeState ) {
3259 // Save state without $ch. We want to *hit* the first
3260 // display char (to get tags) but not *use* it if truncating.
3261 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3264 $entityState = 1; // entity found, (e.g. " ")
3266 $dispLen++
; // this char is displayed
3267 // Add the next $max display text chars after this in one swoop...
3268 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3269 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3270 $dispLen +
= $skipped;
3276 // Close the last tag if left unclosed by bad HTML
3277 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3278 while ( count( $openTags ) > 0 ) {
3279 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3285 * truncateHtml() helper function
3286 * like strcspn() but adds the skipped chars to $ret
3295 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3296 if ( $len === null ) {
3297 $len = -1; // -1 means "no limit" for strcspn
3298 } elseif ( $len < 0 ) {
3302 if ( $start < strlen( $text ) ) {
3303 $skipCount = strcspn( $text, $search, $start, $len );
3304 $ret .= substr( $text, $start, $skipCount );
3310 * truncateHtml() helper function
3311 * (a) push or pop $tag from $openTags as needed
3312 * (b) clear $tag value
3313 * @param &$tag string Current HTML tag name we are looking at
3314 * @param $tagType int (0-open tag, 1-close tag)
3315 * @param $lastCh string Character before the '>' that ended this tag
3316 * @param &$openTags array Open tag stack (not accounting for $tag)
3318 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3319 $tag = ltrim( $tag );
3321 if ( $tagType == 0 && $lastCh != '/' ) {
3322 $openTags[] = $tag; // tag opened (didn't close itself)
3323 } elseif ( $tagType == 1 ) {
3324 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3325 array_pop( $openTags ); // tag closed
3333 * Grammatical transformations, needed for inflected languages
3334 * Invoked by putting {{grammar:case|word}} in a message
3336 * @param $word string
3337 * @param $case string
3340 function convertGrammar( $word, $case ) {
3341 global $wgGrammarForms;
3342 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3343 return $wgGrammarForms[$this->getCode()][$case][$word];
3348 * Get the grammar forms for the content language
3349 * @return array of grammar forms
3352 function getGrammarForms() {
3353 global $wgGrammarForms;
3354 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3355 return $wgGrammarForms[$this->getCode()];
3360 * Provides an alternative text depending on specified gender.
3361 * Usage {{gender:username|masculine|feminine|neutral}}.
3362 * username is optional, in which case the gender of current user is used,
3363 * but only in (some) interface messages; otherwise default gender is used.
3365 * If no forms are given, an empty string is returned. If only one form is
3366 * given, it will be returned unconditionally. These details are implied by
3367 * the caller and cannot be overridden in subclasses.
3369 * If more than one form is given, the default is to use the neutral one
3370 * if it is specified, and to use the masculine one otherwise. These
3371 * details can be overridden in subclasses.
3373 * @param $gender string
3374 * @param $forms array
3378 function gender( $gender, $forms ) {
3379 if ( !count( $forms ) ) {
3382 $forms = $this->preConvertPlural( $forms, 2 );
3383 if ( $gender === 'male' ) {
3386 if ( $gender === 'female' ) {
3389 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3393 * Plural form transformations, needed for some languages.
3394 * For example, there are 3 form of plural in Russian and Polish,
3395 * depending on "count mod 10". See [[w:Plural]]
3396 * For English it is pretty simple.
3398 * Invoked by putting {{plural:count|wordform1|wordform2}}
3399 * or {{plural:count|wordform1|wordform2|wordform3}}
3401 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3403 * @param $count Integer: non-localized number
3404 * @param $forms Array: different plural forms
3405 * @return string Correct form of plural for $count in this language
3407 function convertPlural( $count, $forms ) {
3408 if ( !count( $forms ) ) {
3411 $forms = $this->preConvertPlural( $forms, 2 );
3413 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3417 * Checks that convertPlural was given an array and pads it to requested
3418 * amount of forms by copying the last one.
3420 * @param $count Integer: How many forms should there be at least
3421 * @param $forms Array of forms given to convertPlural
3422 * @return array Padded array of forms or an exception if not an array
3424 protected function preConvertPlural( /* Array */ $forms, $count ) {
3425 while ( count( $forms ) < $count ) {
3426 $forms[] = $forms[count( $forms ) - 1];
3432 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3433 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3434 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3435 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3438 * @param $str String: the validated block duration in English
3439 * @return string Somehow translated block duration
3440 * @see LanguageFi.php for example implementation
3442 function translateBlockExpiry( $str ) {
3443 $duration = SpecialBlock
::getSuggestedDurations( $this );
3444 foreach ( $duration as $show => $value ) {
3445 if ( strcmp( $str, $value ) == 0 ) {
3446 return htmlspecialchars( trim( $show ) );
3450 // Since usually only infinite or indefinite is only on list, so try
3451 // equivalents if still here.
3452 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3453 if ( in_array( $str, $indefs ) ) {
3454 foreach ( $indefs as $val ) {
3455 $show = array_search( $val, $duration, true );
3456 if ( $show !== false ) {
3457 return htmlspecialchars( trim( $show ) );
3461 // If all else fails, return the original string.
3466 * languages like Chinese need to be segmented in order for the diff
3469 * @param $text String
3472 public function segmentForDiff( $text ) {
3477 * and unsegment to show the result
3479 * @param $text String
3482 public function unsegmentForDiff( $text ) {
3487 * Return the LanguageConverter used in the Language
3490 * @return LanguageConverter
3492 public function getConverter() {
3493 return $this->mConverter
;
3497 * convert text to all supported variants
3499 * @param $text string
3502 public function autoConvertToAllVariants( $text ) {
3503 return $this->mConverter
->autoConvertToAllVariants( $text );
3507 * convert text to different variants of a language.
3509 * @param $text string
3512 public function convert( $text ) {
3513 return $this->mConverter
->convert( $text );
3517 * Convert a Title object to a string in the preferred variant
3519 * @param $title Title
3522 public function convertTitle( $title ) {
3523 return $this->mConverter
->convertTitle( $title );
3527 * Check if this is a language with variants
3531 public function hasVariants() {
3532 return sizeof( $this->getVariants() ) > 1;
3536 * Check if the language has the specific variant
3539 * @param $variant string
3542 public function hasVariant( $variant ) {
3543 return (bool)$this->mConverter
->validateVariant( $variant );
3547 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3549 * @param $text string
3552 public function armourMath( $text ) {
3553 return $this->mConverter
->armourMath( $text );
3557 * Perform output conversion on a string, and encode for safe HTML output.
3558 * @param $text String text to be converted
3559 * @param $isTitle Bool whether this conversion is for the article title
3561 * @todo this should get integrated somewhere sane
3563 public function convertHtml( $text, $isTitle = false ) {
3564 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3568 * @param $key string
3571 public function convertCategoryKey( $key ) {
3572 return $this->mConverter
->convertCategoryKey( $key );
3576 * Get the list of variants supported by this language
3577 * see sample implementation in LanguageZh.php
3579 * @return array an array of language codes
3581 public function getVariants() {
3582 return $this->mConverter
->getVariants();
3588 public function getPreferredVariant() {
3589 return $this->mConverter
->getPreferredVariant();
3595 public function getDefaultVariant() {
3596 return $this->mConverter
->getDefaultVariant();
3602 public function getURLVariant() {
3603 return $this->mConverter
->getURLVariant();
3607 * If a language supports multiple variants, it is
3608 * possible that non-existing link in one variant
3609 * actually exists in another variant. this function
3610 * tries to find it. See e.g. LanguageZh.php
3612 * @param $link String: the name of the link
3613 * @param $nt Mixed: the title object of the link
3614 * @param $ignoreOtherCond Boolean: to disable other conditions when
3615 * we need to transclude a template or update a category's link
3616 * @return null the input parameters may be modified upon return
3618 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3619 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3623 * If a language supports multiple variants, converts text
3624 * into an array of all possible variants of the text:
3625 * 'variant' => text in that variant
3627 * @deprecated since 1.17 Use autoConvertToAllVariants()
3629 * @param $text string
3633 public function convertLinkToAllVariants( $text ) {
3634 return $this->mConverter
->convertLinkToAllVariants( $text );
3638 * returns language specific options used by User::getPageRenderHash()
3639 * for example, the preferred language variant
3643 function getExtraHashOptions() {
3644 return $this->mConverter
->getExtraHashOptions();
3648 * For languages that support multiple variants, the title of an
3649 * article may be displayed differently in different variants. this
3650 * function returns the apporiate title defined in the body of the article.
3654 public function getParsedTitle() {
3655 return $this->mConverter
->getParsedTitle();
3659 * Enclose a string with the "no conversion" tag. This is used by
3660 * various functions in the Parser
3662 * @param $text String: text to be tagged for no conversion
3663 * @param $noParse bool
3664 * @return string the tagged text
3666 public function markNoConversion( $text, $noParse = false ) {
3667 return $this->mConverter
->markNoConversion( $text, $noParse );
3671 * A regular expression to match legal word-trailing characters
3672 * which should be merged onto a link of the form [[foo]]bar.
3676 public function linkTrail() {
3677 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3683 function getLangObj() {
3688 * Get the RFC 3066 code for this language object
3690 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3691 * htmlspecialchars() or similar
3695 public function getCode() {
3696 return $this->mCode
;
3700 * Get the code in Bcp47 format which we can use
3701 * inside of html lang="" tags.
3703 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3704 * htmlspecialchars() or similar.
3709 public function getHtmlCode() {
3710 if ( is_null( $this->mHtmlCode
) ) {
3711 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3713 return $this->mHtmlCode
;
3717 * @param $code string
3719 public function setCode( $code ) {
3720 $this->mCode
= $code;
3721 // Ensure we don't leave an incorrect html code lying around
3722 $this->mHtmlCode
= null;
3726 * Get the name of a file for a certain language code
3727 * @param $prefix string Prepend this to the filename
3728 * @param $code string Language code
3729 * @param $suffix string Append this to the filename
3730 * @throws MWException
3731 * @return string $prefix . $mangledCode . $suffix
3733 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3734 // Protect against path traversal
3735 if ( !Language
::isValidCode( $code )
3736 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3738 throw new MWException( "Invalid language code \"$code\"" );
3741 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3745 * Get the language code from a file name. Inverse of getFileName()
3746 * @param $filename string $prefix . $languageCode . $suffix
3747 * @param $prefix string Prefix before the language code
3748 * @param $suffix string Suffix after the language code
3749 * @return string Language code, or false if $prefix or $suffix isn't found
3751 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3753 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3754 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3755 if ( !count( $m ) ) {
3758 return str_replace( '_', '-', strtolower( $m[1] ) );
3762 * @param $code string
3765 public static function getMessagesFileName( $code ) {
3767 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3768 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3773 * @param $code string
3776 public static function getClassFileName( $code ) {
3778 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3782 * Get the first fallback for a given language.
3784 * @param $code string
3786 * @return bool|string
3788 public static function getFallbackFor( $code ) {
3789 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3792 $fallbacks = self
::getFallbacksFor( $code );
3793 $first = array_shift( $fallbacks );
3799 * Get the ordered list of fallback languages.
3802 * @param $code string Language code
3805 public static function getFallbacksFor( $code ) {
3806 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3809 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3810 $v = array_map( 'trim', explode( ',', $v ) );
3811 if ( $v[count( $v ) - 1] !== 'en' ) {
3819 * Get all messages for a given language
3820 * WARNING: this may take a long time. If you just need all message *keys*
3821 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3823 * @param $code string
3827 public static function getMessagesFor( $code ) {
3828 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3832 * Get a message for a given language
3834 * @param $key string
3835 * @param $code string
3839 public static function getMessageFor( $key, $code ) {
3840 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3844 * Get all message keys for a given language. This is a faster alternative to
3845 * array_keys( Language::getMessagesFor( $code ) )
3848 * @param $code string Language code
3849 * @return array of message keys (strings)
3851 public static function getMessageKeysFor( $code ) {
3852 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
3859 function fixVariableInNamespace( $talk ) {
3860 if ( strpos( $talk, '$1' ) === false ) {
3864 global $wgMetaNamespace;
3865 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3867 # Allow grammar transformations
3868 # Allowing full message-style parsing would make simple requests
3869 # such as action=raw much more expensive than they need to be.
3870 # This will hopefully cover most cases.
3871 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3872 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3873 return str_replace( ' ', '_', $talk );
3880 function replaceGrammarInNamespace( $m ) {
3881 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3885 * @throws MWException
3888 static function getCaseMaps() {
3889 static $wikiUpperChars, $wikiLowerChars;
3890 if ( isset( $wikiUpperChars ) ) {
3891 return array( $wikiUpperChars, $wikiLowerChars );
3894 wfProfileIn( __METHOD__
);
3895 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3896 if ( $arr === false ) {
3897 throw new MWException(
3898 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3900 $wikiUpperChars = $arr['wikiUpperChars'];
3901 $wikiLowerChars = $arr['wikiLowerChars'];
3902 wfProfileOut( __METHOD__
);
3903 return array( $wikiUpperChars, $wikiLowerChars );
3907 * Decode an expiry (block, protection, etc) which has come from the DB
3909 * @FIXME: why are we returnings DBMS-dependent strings???
3911 * @param $expiry String: Database expiry String
3912 * @param $format Bool|Int true to process using language functions, or TS_ constant
3913 * to return the expiry in a given timestamp
3916 public function formatExpiry( $expiry, $format = true ) {
3917 static $infinity, $infinityMsg;
3918 if ( $infinity === null ) {
3919 $infinityMsg = wfMessage( 'infiniteblock' );
3920 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3923 if ( $expiry == '' ||
$expiry == $infinity ) {
3924 return $format === true
3928 return $format === true
3929 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
3930 : wfTimestamp( $format, $expiry );
3936 * @param $seconds int|float
3937 * @param $format Array Optional
3938 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3939 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3940 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3941 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3944 function formatTimePeriod( $seconds, $format = array() ) {
3945 if ( !is_array( $format ) ) {
3946 $format = array( 'avoid' => $format ); // For backwards compatibility
3948 if ( !isset( $format['avoid'] ) ) {
3949 $format['avoid'] = false;
3951 if ( !isset( $format['noabbrevs' ] ) ) {
3952 $format['noabbrevs'] = false;
3954 $secondsMsg = wfMessage(
3955 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3956 $minutesMsg = wfMessage(
3957 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3958 $hoursMsg = wfMessage(
3959 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
3960 $daysMsg = wfMessage(
3961 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
3963 if ( round( $seconds * 10 ) < 100 ) {
3964 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3965 $s = $secondsMsg->params( $s )->text();
3966 } elseif ( round( $seconds ) < 60 ) {
3967 $s = $this->formatNum( round( $seconds ) );
3968 $s = $secondsMsg->params( $s )->text();
3969 } elseif ( round( $seconds ) < 3600 ) {
3970 $minutes = floor( $seconds / 60 );
3971 $secondsPart = round( fmod( $seconds, 60 ) );
3972 if ( $secondsPart == 60 ) {
3976 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3978 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3979 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3980 $hours = floor( $seconds / 3600 );
3981 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3982 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3983 if ( $secondsPart == 60 ) {
3987 if ( $minutes == 60 ) {
3991 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3993 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3994 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3995 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3998 $days = floor( $seconds / 86400 );
3999 if ( $format['avoid'] === 'avoidminutes' ) {
4000 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4001 if ( $hours == 24 ) {
4005 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4007 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4008 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4009 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4010 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4011 if ( $minutes == 60 ) {
4015 if ( $hours == 24 ) {
4019 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4021 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4023 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4025 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4027 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4034 * Format a bitrate for output, using an appropriate
4035 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4037 * This use base 1000. For base 1024 use formatSize(), for another base
4038 * see formatComputingNumbers()
4043 function formatBitrate( $bps ) {
4044 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4048 * @param $size int Size of the unit
4049 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4050 * @param $messageKey string Message key to be uesd
4053 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4055 return str_replace( '$1', $this->formatNum( $size ),
4056 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4059 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4062 $maxIndex = count( $sizes ) - 1;
4063 while ( $size >= $boundary && $index < $maxIndex ) {
4068 // For small sizes no decimal places necessary
4071 // For MB and bigger two decimal places are smarter
4074 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4076 $size = round( $size, $round );
4077 $text = $this->getMessageFromDB( $msg );
4078 return str_replace( '$1', $this->formatNum( $size ), $text );
4082 * Format a size in bytes for output, using an appropriate
4083 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4085 * This method use base 1024. For base 1000 use formatBitrate(), for
4086 * another base see formatComputingNumbers()
4088 * @param $size int Size to format
4089 * @return string Plain text (not HTML)
4091 function formatSize( $size ) {
4092 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4096 * Make a list item, used by various special pages
4098 * @param $page String Page link
4099 * @param $details String Text between brackets
4100 * @param $oppositedm Boolean Add the direction mark opposite to your
4101 * language, to display text properly
4104 function specialList( $page, $details, $oppositedm = true ) {
4105 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4106 $this->getDirMark();
4107 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4108 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4109 return $page . $details;
4113 * Generate (prev x| next x) (20|50|100...) type links for paging
4115 * @param $title Title object to link
4116 * @param $offset Integer offset parameter
4117 * @param $limit Integer limit parameter
4118 * @param $query String optional URL query parameter string
4119 * @param $atend Bool optional param for specified if this is the last page
4122 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4123 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4125 # Make 'previous' link
4126 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4127 if ( $offset > 0 ) {
4128 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4129 $query, $prev, 'prevn-title', 'mw-prevlink' );
4131 $plink = htmlspecialchars( $prev );
4135 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4137 $nlink = htmlspecialchars( $next );
4139 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4140 $query, $next, 'prevn-title', 'mw-nextlink' );
4143 # Make links to set number of items per page
4144 $numLinks = array();
4145 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4146 $numLinks[] = $this->numLink( $title, $offset, $num,
4147 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4150 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4151 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4155 * Helper function for viewPrevNext() that generates links
4157 * @param $title Title object to link
4158 * @param $offset Integer offset parameter
4159 * @param $limit Integer limit parameter
4160 * @param $query Array extra query parameters
4161 * @param $link String text to use for the link; will be escaped
4162 * @param $tooltipMsg String name of the message to use as tooltip
4163 * @param $class String value of the "class" attribute of the link
4164 * @return String HTML fragment
4166 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4167 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4168 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4169 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4170 'title' => $tooltip, 'class' => $class ), $link );
4174 * Get the conversion rule title, if any.
4178 public function getConvRuleTitle() {
4179 return $this->mConverter
->getConvRuleTitle();