3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
34 global $wgLanguageNames;
35 require_once( __DIR__
. '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
42 * a fake language converter
52 function __construct( $langobj ) { $this->mLang
= $langobj; }
53 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
54 function convert( $t ) { return $t; }
55 function convertTo( $text, $variant ) { return $text; }
56 function convertTitle( $t ) { return $t->getPrefixedText(); }
57 function convertNamespace( $ns ) { return $this->mLang
->getFormattedNsText( $ns ); }
58 function getVariants() { return array( $this->mLang
->getCode() ); }
59 function getPreferredVariant() { return $this->mLang
->getCode(); }
60 function getDefaultVariant() { return $this->mLang
->getCode(); }
61 function getURLVariant() { return ''; }
62 function getConvRuleTitle() { return false; }
63 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
64 function getExtraHashOptions() { return ''; }
65 function getParsedTitle() { return ''; }
66 function markNoConversion( $text, $noParse = false ) { return $text; }
67 function convertCategoryKey( $key ) { return $key; }
68 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
69 function armourMath( $text ) { return $text; }
73 * Internationalisation code
79 * @var LanguageConverter
83 public $mVariants, $mCode, $mLoaded = false;
84 public $mMagicExtensions = array(), $mMagicHookDone = false;
85 private $mHtmlCode = null;
87 public $dateFormatStrings = array();
88 public $mExtendedSpecialPageAliases;
90 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
93 * ReplacementArray object caches
95 public $transformData = array();
98 * @var LocalisationCache
100 static public $dataCache;
102 static public $mLangObjCache = array();
104 static public $mWeekdayMsgs = array(
105 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
109 static public $mWeekdayAbbrevMsgs = array(
110 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
113 static public $mMonthMsgs = array(
114 'january', 'february', 'march', 'april', 'may_long', 'june',
115 'july', 'august', 'september', 'october', 'november',
118 static public $mMonthGenMsgs = array(
119 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
120 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
123 static public $mMonthAbbrevMsgs = array(
124 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
125 'sep', 'oct', 'nov', 'dec'
128 static public $mIranianCalendarMonthMsgs = array(
129 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
130 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
131 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
132 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
135 static public $mHebrewCalendarMonthMsgs = array(
136 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
137 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
138 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
139 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
140 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
143 static public $mHebrewCalendarMonthGenMsgs = array(
144 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
145 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
146 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
147 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
148 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
151 static public $mHijriCalendarMonthMsgs = array(
152 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
153 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
154 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
155 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
162 static public $durationIntervals = array(
163 'millennia' => 31556952000,
164 'centuries' => 3155695200,
165 'decades' => 315569520,
166 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
175 * Get a cached or new language object for a given language code
176 * @param $code String
179 static function factory( $code ) {
180 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
182 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
183 $code = $wgDummyLanguageCodes[$code];
186 // get the language object to process
187 $langObj = isset( self
::$mLangObjCache[$code] )
188 ? self
::$mLangObjCache[$code]
189 : self
::newFromCode( $code );
191 // merge the language object in to get it up front in the cache
192 self
::$mLangObjCache = array_merge( array( $code => $langObj ), self
::$mLangObjCache );
193 // get rid of the oldest ones in case we have an overflow
194 self
::$mLangObjCache = array_slice( self
::$mLangObjCache, 0, $wgLangObjCacheSize, true );
200 * Create a language object for a given language code
201 * @param $code String
202 * @throws MWException
205 protected static function newFromCode( $code ) {
206 // Protect against path traversal below
207 if ( !Language
::isValidCode( $code )
208 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
210 throw new MWException( "Invalid language code \"$code\"" );
213 if ( !Language
::isValidBuiltInCode( $code ) ) {
214 // It's not possible to customise this code with class files, so
215 // just return a Language object. This is to support uselang= hacks.
216 $lang = new Language
;
217 $lang->setCode( $code );
221 // Check if there is a language class for the code
222 $class = self
::classFromCode( $code );
223 self
::preloadLanguageClass( $class );
224 if ( MWInit
::classExists( $class ) ) {
229 // Keep trying the fallback list until we find an existing class
230 $fallbacks = Language
::getFallbacksFor( $code );
231 foreach ( $fallbacks as $fallbackCode ) {
232 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
233 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
236 $class = self
::classFromCode( $fallbackCode );
237 self
::preloadLanguageClass( $class );
238 if ( MWInit
::classExists( $class ) ) {
239 $lang = Language
::newFromCode( $fallbackCode );
240 $lang->setCode( $code );
245 throw new MWException( "Invalid fallback sequence for language '$code'" );
249 * Checks whether any localisation is available for that language tag
250 * in MediaWiki (MessagesXx.php exists).
252 * @param string $code Language tag (in lower case)
253 * @return bool Whether language is supported
256 public static function isSupportedLanguage( $code ) {
257 return $code === strtolower( $code ) && is_readable( self
::getMessagesFileName( $code ) );
261 * Returns true if a language code string is a well-formed language tag
262 * according to RFC 5646.
263 * This function only checks well-formedness; it doesn't check that
264 * language, script or variant codes actually exist in the repositories.
266 * Based on regexes by Mark Davis of the Unicode Consortium:
267 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
269 * @param $code string
270 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
275 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
278 $alphanum = '[a-z0-9]';
279 $x = 'x' ; # private use singleton
280 $singleton = '[a-wy-z]'; # other singleton
281 $s = $lenient ?
'[-_]' : '-';
283 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
284 $script = "$alpha{4}"; # ISO 15924
285 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
286 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
287 $extension = "$singleton(?:$s$alphanum{2,8})+";
288 $privateUse = "$x(?:$s$alphanum{1,8})+";
290 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
291 # Since these are limited, this is safe even later changes to the registry --
292 # the only oddity is that it might change the type of the tag, and thus
293 # the results from the capturing groups.
294 # http://www.iana.org/assignments/language-subtag-registry
296 $grandfathered = "en{$s}GB{$s}oed"
297 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
298 . "|no{$s}(?:bok|nyn)"
299 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
300 . "|zh{$s}min{$s}nan";
302 $variantList = "$variant(?:$s$variant)*";
303 $extensionList = "$extension(?:$s$extension)*";
305 $langtag = "(?:($language)"
308 . "(?:$s$variantList)?"
309 . "(?:$s$extensionList)?"
310 . "(?:$s$privateUse)?)";
312 # The final breakdown, with capturing groups for each of these components
313 # The variants, extensions, grandfathered, and private-use may have interior '-'
315 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
317 return (bool)preg_match( "/$root/", strtolower( $code ) );
321 * Returns true if a language code string is of a valid form, whether or
322 * not it exists. This includes codes which are used solely for
323 * customisation via the MediaWiki namespace.
325 * @param $code string
329 public static function isValidCode( $code ) {
331 // People think language codes are html safe, so enforce it.
332 // Ideally we should only allow a-zA-Z0-9-
333 // but, .+ and other chars are often used for {{int:}} hacks
334 // see bugs 37564, 37587, 36938
335 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
336 && !preg_match( Title
::getTitleInvalidRegex(), $code );
340 * Returns true if a language code is of a valid form for the purposes of
341 * internal customisation of MediaWiki, via Messages*.php.
343 * @param $code string
345 * @throws MWException
349 public static function isValidBuiltInCode( $code ) {
351 if ( !is_string( $code ) ) {
352 $type = gettype( $code );
353 if ( $type === 'object' ) {
354 $addmsg = " of class " . get_class( $code );
358 throw new MWException( __METHOD__
. " must be passed a string, $type given$addmsg" );
361 return (bool)preg_match( '/^[a-z0-9-]+$/i', $code );
365 * Returns true if a language code is an IETF tag known to MediaWiki.
367 * @param $code string
372 public static function isKnownLanguageTag( $tag ) {
373 static $coreLanguageNames;
375 if ( $coreLanguageNames === null ) {
376 include( MWInit
::compiledPath( 'languages/Names.php' ) );
379 if ( isset( $coreLanguageNames[$tag] )
380 || self
::fetchLanguageName( $tag, $tag ) !== ''
390 * @return String Name of the language class
392 public static function classFromCode( $code ) {
393 if ( $code == 'en' ) {
396 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
401 * Includes language class files
403 * @param $class string Name of the language class
405 public static function preloadLanguageClass( $class ) {
408 if ( $class === 'Language' ) {
412 if ( !defined( 'MW_COMPILED' ) ) {
413 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
414 include_once( "$IP/languages/classes/$class.php" );
420 * Get the LocalisationCache instance
422 * @return LocalisationCache
424 public static function getLocalisationCache() {
425 if ( is_null( self
::$dataCache ) ) {
426 global $wgLocalisationCacheConf;
427 $class = $wgLocalisationCacheConf['class'];
428 self
::$dataCache = new $class( $wgLocalisationCacheConf );
430 return self
::$dataCache;
433 function __construct() {
434 $this->mConverter
= new FakeConverter( $this );
435 // Set the code to the name of the descendant
436 if ( get_class( $this ) == 'Language' ) {
439 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
441 self
::getLocalisationCache();
445 * Reduce memory usage
447 function __destruct() {
448 foreach ( $this as $name => $value ) {
449 unset( $this->$name );
454 * Hook which will be called if this is the content language.
455 * Descendants can use this to register hook functions or modify globals
457 function initContLang() { }
460 * Same as getFallbacksFor for current language.
462 * @deprecated in 1.19
464 function getFallbackLanguageCode() {
465 wfDeprecated( __METHOD__
, '1.19' );
466 return self
::getFallbackFor( $this->mCode
);
473 function getFallbackLanguages() {
474 return self
::getFallbacksFor( $this->mCode
);
478 * Exports $wgBookstoreListEn
481 function getBookstoreList() {
482 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
488 public function getNamespaces() {
489 if ( is_null( $this->namespaceNames
) ) {
490 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
492 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
493 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
495 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
497 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
498 if ( $wgMetaNamespaceTalk ) {
499 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
501 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
502 $this->namespaceNames
[NS_PROJECT_TALK
] =
503 $this->fixVariableInNamespace( $talk );
506 # Sometimes a language will be localised but not actually exist on this wiki.
507 foreach ( $this->namespaceNames
as $key => $text ) {
508 if ( !isset( $validNamespaces[$key] ) ) {
509 unset( $this->namespaceNames
[$key] );
513 # The above mixing may leave namespaces out of canonical order.
514 # Re-order by namespace ID number...
515 ksort( $this->namespaceNames
);
517 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
519 return $this->namespaceNames
;
523 * Arbitrarily set all of the namespace names at once. Mainly used for testing
524 * @param $namespaces Array of namespaces (id => name)
526 public function setNamespaces( array $namespaces ) {
527 $this->namespaceNames
= $namespaces;
528 $this->mNamespaceIds
= null;
532 * Resets all of the namespace caches. Mainly used for testing
534 public function resetNamespaces( ) {
535 $this->namespaceNames
= null;
536 $this->mNamespaceIds
= null;
537 $this->namespaceAliases
= null;
541 * A convenience function that returns the same thing as
542 * getNamespaces() except with the array values changed to ' '
543 * where it found '_', useful for producing output to be displayed
544 * e.g. in <select> forms.
548 function getFormattedNamespaces() {
549 $ns = $this->getNamespaces();
550 foreach ( $ns as $k => $v ) {
551 $ns[$k] = strtr( $v, '_', ' ' );
557 * Get a namespace value by key
559 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
560 * echo $mw_ns; // prints 'MediaWiki'
563 * @param $index Int: the array key of the namespace to return
564 * @return mixed, string if the namespace value exists, otherwise false
566 function getNsText( $index ) {
567 $ns = $this->getNamespaces();
568 return isset( $ns[$index] ) ?
$ns[$index] : false;
572 * A convenience function that returns the same thing as
573 * getNsText() except with '_' changed to ' ', useful for
577 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
578 * echo $mw_ns; // prints 'MediaWiki talk'
581 * @param int $index The array key of the namespace to return
582 * @return string Namespace name without underscores (empty string if namespace does not exist)
584 function getFormattedNsText( $index ) {
585 $ns = $this->getNsText( $index );
586 return strtr( $ns, '_', ' ' );
590 * Returns gender-dependent namespace alias if available.
591 * @param $index Int: namespace index
592 * @param $gender String: gender key (male, female... )
596 function getGenderNsText( $index, $gender ) {
597 global $wgExtraGenderNamespaces;
599 $ns = $wgExtraGenderNamespaces + self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
600 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
604 * Whether this language makes distinguishes genders for example in
609 function needsGenderDistinction() {
610 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
611 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
612 // $wgExtraGenderNamespaces overrides everything
614 } elseif ( isset( $wgExtraNamespaces[NS_USER
] ) && isset( $wgExtraNamespaces[NS_USER_TALK
] ) ) {
615 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
616 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
619 // Check what is in i18n files
620 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
621 return count( $aliases ) > 0;
626 * Get a namespace key by value, case insensitive.
627 * Only matches namespace names for the current language, not the
628 * canonical ones defined in Namespace.php.
630 * @param $text String
631 * @return mixed An integer if $text is a valid value otherwise false
633 function getLocalNsIndex( $text ) {
634 $lctext = $this->lc( $text );
635 $ids = $this->getNamespaceIds();
636 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
642 function getNamespaceAliases() {
643 if ( is_null( $this->namespaceAliases
) ) {
644 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
648 foreach ( $aliases as $name => $index ) {
649 if ( $index === NS_PROJECT_TALK
) {
650 unset( $aliases[$name] );
651 $name = $this->fixVariableInNamespace( $name );
652 $aliases[$name] = $index;
657 global $wgExtraGenderNamespaces;
658 $genders = $wgExtraGenderNamespaces +
(array)self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
659 foreach ( $genders as $index => $forms ) {
660 foreach ( $forms as $alias ) {
661 $aliases[$alias] = $index;
665 $this->namespaceAliases
= $aliases;
667 return $this->namespaceAliases
;
673 function getNamespaceIds() {
674 if ( is_null( $this->mNamespaceIds
) ) {
675 global $wgNamespaceAliases;
676 # Put namespace names and aliases into a hashtable.
677 # If this is too slow, then we should arrange it so that it is done
678 # before caching. The catch is that at pre-cache time, the above
679 # class-specific fixup hasn't been done.
680 $this->mNamespaceIds
= array();
681 foreach ( $this->getNamespaces() as $index => $name ) {
682 $this->mNamespaceIds
[$this->lc( $name )] = $index;
684 foreach ( $this->getNamespaceAliases() as $name => $index ) {
685 $this->mNamespaceIds
[$this->lc( $name )] = $index;
687 if ( $wgNamespaceAliases ) {
688 foreach ( $wgNamespaceAliases as $name => $index ) {
689 $this->mNamespaceIds
[$this->lc( $name )] = $index;
693 return $this->mNamespaceIds
;
697 * Get a namespace key by value, case insensitive. Canonical namespace
698 * names override custom ones defined for the current language.
700 * @param $text String
701 * @return mixed An integer if $text is a valid value otherwise false
703 function getNsIndex( $text ) {
704 $lctext = $this->lc( $text );
705 $ns = MWNamespace
::getCanonicalIndex( $lctext );
706 if ( $ns !== null ) {
709 $ids = $this->getNamespaceIds();
710 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
714 * short names for language variants used for language conversion links.
716 * @param $code String
717 * @param $usemsg bool Use the "variantname-xyz" message if it exists
720 function getVariantname( $code, $usemsg = true ) {
721 $msg = "variantname-$code";
722 if ( $usemsg && wfMessage( $msg )->exists() ) {
723 return $this->getMessageFromDB( $msg );
725 $name = self
::fetchLanguageName( $code );
727 return $name; # if it's defined as a language name, show that
729 # otherwise, output the language code
735 * @param $name string
738 function specialPage( $name ) {
739 $aliases = $this->getSpecialPageAliases();
740 if ( isset( $aliases[$name][0] ) ) {
741 $name = $aliases[$name][0];
743 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
749 function getQuickbarSettings() {
751 $this->getMessage( 'qbsettings-none' ),
752 $this->getMessage( 'qbsettings-fixedleft' ),
753 $this->getMessage( 'qbsettings-fixedright' ),
754 $this->getMessage( 'qbsettings-floatingleft' ),
755 $this->getMessage( 'qbsettings-floatingright' ),
756 $this->getMessage( 'qbsettings-directionality' )
763 function getDatePreferences() {
764 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
770 function getDateFormats() {
771 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
775 * @return array|string
777 function getDefaultDateFormat() {
778 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
779 if ( $df === 'dmy or mdy' ) {
780 global $wgAmericanDates;
781 return $wgAmericanDates ?
'mdy' : 'dmy';
790 function getDatePreferenceMigrationMap() {
791 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
798 function getImageFile( $image ) {
799 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
805 function getExtraUserToggles() {
806 return (array)self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
813 function getUserToggle( $tog ) {
814 return $this->getMessageFromDB( "tog-$tog" );
818 * Get native language names, indexed by code.
819 * Only those defined in MediaWiki, no other data like CLDR.
820 * If $customisedOnly is true, only returns codes with a messages file
822 * @param $customisedOnly bool
825 * @deprecated in 1.20, use fetchLanguageNames()
827 public static function getLanguageNames( $customisedOnly = false ) {
828 return self
::fetchLanguageNames( null, $customisedOnly ?
'mwfile' : 'mw' );
832 * Get translated language names. This is done on best effort and
833 * by default this is exactly the same as Language::getLanguageNames.
834 * The CLDR extension provides translated names.
835 * @param $code String Language code.
836 * @return Array language code => language name
838 * @deprecated in 1.20, use fetchLanguageNames()
840 public static function getTranslatedLanguageNames( $code ) {
841 return self
::fetchLanguageNames( $code, 'all' );
845 * Get an array of language names, indexed by code.
846 * @param $inLanguage null|string: Code of language in which to return the names
847 * Use null for autonyms (native names)
848 * @param $include string:
849 * 'all' all available languages
850 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
851 * 'mwfile' only if the language is in 'mw' *and* has a message file
852 * @return array: language code => language name
855 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
856 global $wgExtraLanguageNames;
857 static $coreLanguageNames;
859 if ( $coreLanguageNames === null ) {
860 include( MWInit
::compiledPath( 'languages/Names.php' ) );
866 # TODO: also include when $inLanguage is null, when this code is more efficient
867 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
870 $mwNames = $wgExtraLanguageNames +
$coreLanguageNames;
871 foreach ( $mwNames as $mwCode => $mwName ) {
872 # - Prefer own MediaWiki native name when not using the hook
873 # - For other names just add if not added through the hook
874 if ( $mwCode === $inLanguage ||
!isset( $names[$mwCode] ) ) {
875 $names[$mwCode] = $mwName;
879 if ( $include === 'all' ) {
884 $coreCodes = array_keys( $mwNames );
885 foreach ( $coreCodes as $coreCode ) {
886 $returnMw[$coreCode] = $names[$coreCode];
889 if ( $include === 'mwfile' ) {
890 $namesMwFile = array();
891 # We do this using a foreach over the codes instead of a directory
892 # loop so that messages files in extensions will work correctly.
893 foreach ( $returnMw as $code => $value ) {
894 if ( is_readable( self
::getMessagesFileName( $code ) ) ) {
895 $namesMwFile[$code] = $names[$code];
900 # 'mw' option; default if it's not one of the other two options (all/mwfile)
905 * @param $code string: The code of the language for which to get the name
906 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
907 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
908 * @return string: Language name or empty
911 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
912 $array = self
::fetchLanguageNames( $inLanguage, $include );
913 return !array_key_exists( $code, $array ) ?
'' : $array[$code];
917 * Get a message from the MediaWiki namespace.
919 * @param $msg String: message name
922 function getMessageFromDB( $msg ) {
923 return wfMessage( $msg )->inLanguage( $this )->text();
927 * Get the native language name of $code.
928 * Only if defined in MediaWiki, no other data like CLDR.
929 * @param $code string
931 * @deprecated in 1.20, use fetchLanguageName()
933 function getLanguageName( $code ) {
934 return self
::fetchLanguageName( $code );
941 function getMonthName( $key ) {
942 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
948 function getMonthNamesArray() {
949 $monthNames = array( '' );
950 for ( $i = 1; $i < 13; $i++
) {
951 $monthNames[] = $this->getMonthName( $i );
960 function getMonthNameGen( $key ) {
961 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
968 function getMonthAbbreviation( $key ) {
969 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
975 function getMonthAbbreviationsArray() {
976 $monthNames = array( '' );
977 for ( $i = 1; $i < 13; $i++
) {
978 $monthNames[] = $this->getMonthAbbreviation( $i );
987 function getWeekdayName( $key ) {
988 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
995 function getWeekdayAbbreviation( $key ) {
996 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
1000 * @param $key string
1003 function getIranianCalendarMonthName( $key ) {
1004 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
1008 * @param $key string
1011 function getHebrewCalendarMonthName( $key ) {
1012 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
1016 * @param $key string
1019 function getHebrewCalendarMonthNameGen( $key ) {
1020 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1024 * @param $key string
1027 function getHijriCalendarMonthName( $key ) {
1028 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
1032 * This is a workalike of PHP's date() function, but with better
1033 * internationalisation, a reduced set of format characters, and a better
1036 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
1037 * PHP manual for definitions. There are a number of extensions, which
1040 * xn Do not translate digits of the next numeric format character
1041 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1042 * xr Use roman numerals for the next numeric format character
1043 * xh Use hebrew numerals for the next numeric format character
1045 * xg Genitive month name
1047 * xij j (day number) in Iranian calendar
1048 * xiF F (month name) in Iranian calendar
1049 * xin n (month number) in Iranian calendar
1050 * xiy y (two digit year) in Iranian calendar
1051 * xiY Y (full year) in Iranian calendar
1053 * xjj j (day number) in Hebrew calendar
1054 * xjF F (month name) in Hebrew calendar
1055 * xjt t (days in month) in Hebrew calendar
1056 * xjx xg (genitive month name) in Hebrew calendar
1057 * xjn n (month number) in Hebrew calendar
1058 * xjY Y (full year) in Hebrew calendar
1060 * xmj j (day number) in Hijri calendar
1061 * xmF F (month name) in Hijri calendar
1062 * xmn n (month number) in Hijri calendar
1063 * xmY Y (full year) in Hijri calendar
1065 * xkY Y (full year) in Thai solar calendar. Months and days are
1066 * identical to the Gregorian calendar
1067 * xoY Y (full year) in Minguo calendar or Juche year.
1068 * Months and days are identical to the
1069 * Gregorian calendar
1070 * xtY Y (full year) in Japanese nengo. Months and days are
1071 * identical to the Gregorian calendar
1073 * Characters enclosed in double quotes will be considered literal (with
1074 * the quotes themselves removed). Unmatched quotes will be considered
1075 * literal quotes. Example:
1077 * "The month is" F => The month is January
1080 * Backslash escaping is also supported.
1082 * Input timestamp is assumed to be pre-normalized to the desired local
1083 * time zone, if any.
1085 * @param $format String
1086 * @param $ts String: 14-character timestamp
1089 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1093 function sprintfDate( $format, $ts ) {
1106 for ( $p = 0; $p < strlen( $format ); $p++
) {
1108 $code = $format[$p];
1109 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1110 $code .= $format[++
$p];
1113 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1114 $code .= $format[++
$p];
1125 $rawToggle = !$rawToggle;
1134 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1137 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
1138 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1141 $num = substr( $ts, 6, 2 );
1144 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
1145 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
1148 $num = intval( substr( $ts, 6, 2 ) );
1152 $iranian = self
::tsToIranian( $ts );
1158 $hijri = self
::tsToHijri( $ts );
1164 $hebrew = self
::tsToHebrew( $ts );
1170 $unix = wfTimestamp( TS_UNIX
, $ts );
1172 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
1176 $unix = wfTimestamp( TS_UNIX
, $ts );
1178 $w = gmdate( 'w', $unix );
1183 $unix = wfTimestamp( TS_UNIX
, $ts );
1185 $num = gmdate( 'w', $unix );
1189 $unix = wfTimestamp( TS_UNIX
, $ts );
1191 $num = gmdate( 'z', $unix );
1195 $unix = wfTimestamp( TS_UNIX
, $ts );
1197 $num = gmdate( 'W', $unix );
1200 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1204 $iranian = self
::tsToIranian( $ts );
1206 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1210 $hijri = self
::tsToHijri( $ts );
1212 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1216 $hebrew = self
::tsToHebrew( $ts );
1218 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1221 $num = substr( $ts, 4, 2 );
1224 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1227 $num = intval( substr( $ts, 4, 2 ) );
1231 $iranian = self
::tsToIranian( $ts );
1237 $hijri = self
::tsToHijri ( $ts );
1243 $hebrew = self
::tsToHebrew( $ts );
1249 $unix = wfTimestamp( TS_UNIX
, $ts );
1251 $num = gmdate( 't', $unix );
1255 $hebrew = self
::tsToHebrew( $ts );
1261 $unix = wfTimestamp( TS_UNIX
, $ts );
1263 $num = gmdate( 'L', $unix );
1267 $unix = wfTimestamp( TS_UNIX
, $ts );
1269 $num = gmdate( 'o', $unix );
1272 $num = substr( $ts, 0, 4 );
1276 $iranian = self
::tsToIranian( $ts );
1282 $hijri = self
::tsToHijri( $ts );
1288 $hebrew = self
::tsToHebrew( $ts );
1294 $thai = self
::tsToYear( $ts, 'thai' );
1300 $minguo = self
::tsToYear( $ts, 'minguo' );
1306 $tenno = self
::tsToYear( $ts, 'tenno' );
1311 $num = substr( $ts, 2, 2 );
1315 $iranian = self
::tsToIranian( $ts );
1317 $num = substr( $iranian[0], -2 );
1320 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1323 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1326 $h = substr( $ts, 8, 2 );
1327 $num = $h %
12 ?
$h %
12 : 12;
1330 $num = intval( substr( $ts, 8, 2 ) );
1333 $h = substr( $ts, 8, 2 );
1334 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1337 $num = substr( $ts, 8, 2 );
1340 $num = substr( $ts, 10, 2 );
1343 $num = substr( $ts, 12, 2 );
1347 $unix = wfTimestamp( TS_UNIX
, $ts );
1349 $s .= gmdate( 'c', $unix );
1353 $unix = wfTimestamp( TS_UNIX
, $ts );
1355 $s .= gmdate( 'r', $unix );
1359 $unix = wfTimestamp( TS_UNIX
, $ts );
1364 # Backslash escaping
1365 if ( $p < strlen( $format ) - 1 ) {
1366 $s .= $format[++
$p];
1373 if ( $p < strlen( $format ) - 1 ) {
1374 $endQuote = strpos( $format, '"', $p +
1 );
1375 if ( $endQuote === false ) {
1376 # No terminating quote, assume literal "
1379 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1383 # Quote at end of string, assume literal "
1390 if ( $num !== false ) {
1391 if ( $rawToggle ||
$raw ) {
1394 } elseif ( $roman ) {
1395 $s .= Language
::romanNumeral( $num );
1397 } elseif ( $hebrewNum ) {
1398 $s .= self
::hebrewNumeral( $num );
1401 $s .= $this->formatNum( $num, true );
1408 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1409 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1412 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1413 * Gregorian dates to Iranian dates. Originally written in C, it
1414 * is released under the terms of GNU Lesser General Public
1415 * License. Conversion to PHP was performed by Niklas Laxström.
1417 * Link: http://www.farsiweb.info/jalali/jalali.c
1423 private static function tsToIranian( $ts ) {
1424 $gy = substr( $ts, 0, 4 ) -1600;
1425 $gm = substr( $ts, 4, 2 ) -1;
1426 $gd = substr( $ts, 6, 2 ) -1;
1428 # Days passed from the beginning (including leap years)
1430 +
floor( ( $gy +
3 ) / 4 )
1431 - floor( ( $gy +
99 ) / 100 )
1432 +
floor( ( $gy +
399 ) / 400 );
1434 // Add days of the past months of this year
1435 for ( $i = 0; $i < $gm; $i++
) {
1436 $gDayNo +
= self
::$GREG_DAYS[$i];
1440 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1444 // Days passed in current month
1445 $gDayNo +
= (int)$gd;
1447 $jDayNo = $gDayNo - 79;
1449 $jNp = floor( $jDayNo / 12053 );
1452 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1455 if ( $jDayNo >= 366 ) {
1456 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1457 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1460 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1461 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1467 return array( $jy, $jm, $jd );
1471 * Converting Gregorian dates to Hijri dates.
1473 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1475 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1481 private static function tsToHijri( $ts ) {
1482 $year = substr( $ts, 0, 4 );
1483 $month = substr( $ts, 4, 2 );
1484 $day = substr( $ts, 6, 2 );
1492 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1493 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1496 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1497 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1498 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1501 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1502 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1505 $zl = $zjd -1948440 +
10632;
1506 $zn = (int)( ( $zl - 1 ) / 10631 );
1507 $zl = $zl - 10631 * $zn +
354;
1508 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1509 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1510 $zm = (int)( ( 24 * $zl ) / 709 );
1511 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1512 $zy = 30 * $zn +
$zj - 30;
1514 return array( $zy, $zm, $zd );
1518 * Converting Gregorian dates to Hebrew dates.
1520 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1521 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1522 * to translate the relevant functions into PHP and release them under
1525 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1526 * and Adar II is 14. In a non-leap year, Adar is 6.
1532 private static function tsToHebrew( $ts ) {
1534 $year = substr( $ts, 0, 4 );
1535 $month = substr( $ts, 4, 2 );
1536 $day = substr( $ts, 6, 2 );
1538 # Calculate Hebrew year
1539 $hebrewYear = $year +
3760;
1541 # Month number when September = 1, August = 12
1543 if ( $month > 12 ) {
1550 # Calculate day of year from 1 September
1552 for ( $i = 1; $i < $month; $i++
) {
1556 # Check if the year is leap
1557 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1560 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1567 # Calculate the start of the Hebrew year
1568 $start = self
::hebrewYearStart( $hebrewYear );
1570 # Calculate next year's start
1571 if ( $dayOfYear <= $start ) {
1572 # Day is before the start of the year - it is the previous year
1574 $nextStart = $start;
1578 # Add days since previous year's 1 September
1580 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1584 # Start of the new (previous) year
1585 $start = self
::hebrewYearStart( $hebrewYear );
1588 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1591 # Calculate Hebrew day of year
1592 $hebrewDayOfYear = $dayOfYear - $start;
1594 # Difference between year's days
1595 $diff = $nextStart - $start;
1596 # Add 12 (or 13 for leap years) days to ignore the difference between
1597 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1598 # difference is only about the year type
1599 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1605 # Check the year pattern, and is leap year
1606 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1607 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1608 # and non-leap years
1609 $yearPattern = $diff %
30;
1610 # Check if leap year
1611 $isLeap = $diff >= 30;
1613 # Calculate day in the month from number of day in the Hebrew year
1614 # Don't check Adar - if the day is not in Adar, we will stop before;
1615 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1616 $hebrewDay = $hebrewDayOfYear;
1619 while ( $hebrewMonth <= 12 ) {
1620 # Calculate days in this month
1621 if ( $isLeap && $hebrewMonth == 6 ) {
1622 # Adar in a leap year
1624 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1626 if ( $hebrewDay <= $days ) {
1630 # Subtract the days of Adar I
1631 $hebrewDay -= $days;
1634 if ( $hebrewDay <= $days ) {
1640 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1641 # Cheshvan in a complete year (otherwise as the rule below)
1643 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1644 # Kislev in an incomplete year (otherwise as the rule below)
1647 # Odd months have 30 days, even have 29
1648 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1650 if ( $hebrewDay <= $days ) {
1651 # In the current month
1654 # Subtract the days of the current month
1655 $hebrewDay -= $days;
1656 # Try in the next month
1661 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1665 * This calculates the Hebrew year start, as days since 1 September.
1666 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1667 * Used for Hebrew date.
1673 private static function hebrewYearStart( $year ) {
1674 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1675 $b = intval( ( $year - 1 ) %
4 );
1676 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1680 $Mar = intval( $m );
1686 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1687 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1689 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1691 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1695 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1700 * Algorithm to convert Gregorian dates to Thai solar dates,
1701 * Minguo dates or Minguo dates.
1703 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1704 * http://en.wikipedia.org/wiki/Minguo_calendar
1705 * http://en.wikipedia.org/wiki/Japanese_era_name
1707 * @param $ts String: 14-character timestamp
1708 * @param $cName String: calender name
1709 * @return Array: converted year, month, day
1711 private static function tsToYear( $ts, $cName ) {
1712 $gy = substr( $ts, 0, 4 );
1713 $gm = substr( $ts, 4, 2 );
1714 $gd = substr( $ts, 6, 2 );
1716 if ( !strcmp( $cName, 'thai' ) ) {
1718 # Add 543 years to the Gregorian calendar
1719 # Months and days are identical
1720 $gy_offset = $gy +
543;
1721 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1723 # Deduct 1911 years from the Gregorian calendar
1724 # Months and days are identical
1725 $gy_offset = $gy - 1911;
1726 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1727 # Nengō dates up to Meiji period
1728 # Deduct years from the Gregorian calendar
1729 # depending on the nengo periods
1730 # Months and days are identical
1731 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1733 $gy_gannen = $gy - 1868 +
1;
1734 $gy_offset = $gy_gannen;
1735 if ( $gy_gannen == 1 ) {
1738 $gy_offset = '明治' . $gy_offset;
1740 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1741 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1742 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1743 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1744 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1748 $gy_gannen = $gy - 1912 +
1;
1749 $gy_offset = $gy_gannen;
1750 if ( $gy_gannen == 1 ) {
1753 $gy_offset = '大正' . $gy_offset;
1755 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1756 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1757 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1761 $gy_gannen = $gy - 1926 +
1;
1762 $gy_offset = $gy_gannen;
1763 if ( $gy_gannen == 1 ) {
1766 $gy_offset = '昭和' . $gy_offset;
1769 $gy_gannen = $gy - 1989 +
1;
1770 $gy_offset = $gy_gannen;
1771 if ( $gy_gannen == 1 ) {
1774 $gy_offset = '平成' . $gy_offset;
1780 return array( $gy_offset, $gm, $gd );
1784 * Roman number formatting up to 10000
1790 static function romanNumeral( $num ) {
1791 static $table = array(
1792 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1793 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1794 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1795 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1798 $num = intval( $num );
1799 if ( $num > 10000 ||
$num <= 0 ) {
1804 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1805 if ( $num >= $pow10 ) {
1806 $s .= $table[$i][(int)floor( $num / $pow10 )];
1808 $num = $num %
$pow10;
1814 * Hebrew Gematria number formatting up to 9999
1820 static function hebrewNumeral( $num ) {
1821 static $table = array(
1822 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1823 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1824 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1825 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1828 $num = intval( $num );
1829 if ( $num > 9999 ||
$num <= 0 ) {
1834 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1835 if ( $num >= $pow10 ) {
1836 if ( $num == 15 ||
$num == 16 ) {
1837 $s .= $table[0][9] . $table[0][$num - 9];
1840 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1841 if ( $pow10 == 1000 ) {
1846 $num = $num %
$pow10;
1848 if ( strlen( $s ) == 2 ) {
1851 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1852 $str .= substr( $s, strlen( $s ) - 2, 2 );
1854 $start = substr( $str, 0, strlen( $str ) - 2 );
1855 $end = substr( $str, strlen( $str ) - 2 );
1858 $str = $start . 'ך';
1861 $str = $start . 'ם';
1864 $str = $start . 'ן';
1867 $str = $start . 'ף';
1870 $str = $start . 'ץ';
1877 * Used by date() and time() to adjust the time output.
1879 * @param $ts Int the time in date('YmdHis') format
1880 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1881 * get user timecorrection setting)
1884 function userAdjust( $ts, $tz = false ) {
1885 global $wgUser, $wgLocalTZoffset;
1887 if ( $tz === false ) {
1888 $tz = $wgUser->getOption( 'timecorrection' );
1891 $data = explode( '|', $tz, 3 );
1893 if ( $data[0] == 'ZoneInfo' ) {
1894 wfSuppressWarnings();
1895 $userTZ = timezone_open( $data[2] );
1896 wfRestoreWarnings();
1897 if ( $userTZ !== false ) {
1898 $date = date_create( $ts, timezone_open( 'UTC' ) );
1899 date_timezone_set( $date, $userTZ );
1900 $date = date_format( $date, 'YmdHis' );
1903 # Unrecognized timezone, default to 'Offset' with the stored offset.
1904 $data[0] = 'Offset';
1908 if ( $data[0] == 'System' ||
$tz == '' ) {
1909 # Global offset in minutes.
1910 if ( isset( $wgLocalTZoffset ) ) {
1911 $minDiff = $wgLocalTZoffset;
1913 } elseif ( $data[0] == 'Offset' ) {
1914 $minDiff = intval( $data[1] );
1916 $data = explode( ':', $tz );
1917 if ( count( $data ) == 2 ) {
1918 $data[0] = intval( $data[0] );
1919 $data[1] = intval( $data[1] );
1920 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1921 if ( $data[0] < 0 ) {
1922 $minDiff = -$minDiff;
1925 $minDiff = intval( $data[0] ) * 60;
1929 # No difference ? Return time unchanged
1930 if ( 0 == $minDiff ) {
1934 wfSuppressWarnings(); // E_STRICT system time bitching
1935 # Generate an adjusted date; take advantage of the fact that mktime
1936 # will normalize out-of-range values so we don't have to split $minDiff
1937 # into hours and minutes.
1939 (int)substr( $ts, 8, 2 ) ), # Hours
1940 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
1941 (int)substr( $ts, 12, 2 ), # Seconds
1942 (int)substr( $ts, 4, 2 ), # Month
1943 (int)substr( $ts, 6, 2 ), # Day
1944 (int)substr( $ts, 0, 4 ) ); # Year
1946 $date = date( 'YmdHis', $t );
1947 wfRestoreWarnings();
1953 * This is meant to be used by time(), date(), and timeanddate() to get
1954 * the date preference they're supposed to use, it should be used in
1958 * function timeanddate([...], $format = true) {
1959 * $datePreference = $this->dateFormat($format);
1964 * @param $usePrefs Mixed: if true, the user's preference is used
1965 * if false, the site/language default is used
1966 * if int/string, assumed to be a format.
1969 function dateFormat( $usePrefs = true ) {
1972 if ( is_bool( $usePrefs ) ) {
1974 $datePreference = $wgUser->getDatePreference();
1976 $datePreference = (string)User
::getDefaultOption( 'date' );
1979 $datePreference = (string)$usePrefs;
1983 if ( $datePreference == '' ) {
1987 return $datePreference;
1991 * Get a format string for a given type and preference
1992 * @param $type string May be date, time or both
1993 * @param $pref string The format name as it appears in Messages*.php
1997 function getDateFormatString( $type, $pref ) {
1998 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1999 if ( $pref == 'default' ) {
2000 $pref = $this->getDefaultDateFormat();
2001 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2003 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2004 if ( is_null( $df ) ) {
2005 $pref = $this->getDefaultDateFormat();
2006 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
2009 $this->dateFormatStrings
[$type][$pref] = $df;
2011 return $this->dateFormatStrings
[$type][$pref];
2015 * @param $ts Mixed: the time format which needs to be turned into a
2016 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2017 * @param $adj Bool: whether to adjust the time output according to the
2018 * user configured offset ($timecorrection)
2019 * @param $format Mixed: true to use user's date format preference
2020 * @param $timecorrection String|bool the time offset as returned by
2021 * validateTimeZone() in Special:Preferences
2024 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2025 $ts = wfTimestamp( TS_MW
, $ts );
2027 $ts = $this->userAdjust( $ts, $timecorrection );
2029 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2030 return $this->sprintfDate( $df, $ts );
2034 * @param $ts Mixed: the time format which needs to be turned into a
2035 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2036 * @param $adj Bool: whether to adjust the time output according to the
2037 * user configured offset ($timecorrection)
2038 * @param $format Mixed: true to use user's date format preference
2039 * @param $timecorrection String|bool the time offset as returned by
2040 * validateTimeZone() in Special:Preferences
2043 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2044 $ts = wfTimestamp( TS_MW
, $ts );
2046 $ts = $this->userAdjust( $ts, $timecorrection );
2048 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2049 return $this->sprintfDate( $df, $ts );
2053 * @param $ts Mixed: the time format which needs to be turned into a
2054 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2055 * @param $adj Bool: whether to adjust the time output according to the
2056 * user configured offset ($timecorrection)
2057 * @param $format Mixed: what format to return, if it's false output the
2058 * default one (default true)
2059 * @param $timecorrection String|bool the time offset as returned by
2060 * validateTimeZone() in Special:Preferences
2063 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2064 $ts = wfTimestamp( TS_MW
, $ts );
2066 $ts = $this->userAdjust( $ts, $timecorrection );
2068 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2069 return $this->sprintfDate( $df, $ts );
2073 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2077 * @param integer $seconds The amount of seconds.
2078 * @param array $chosenIntervals The intervals to enable.
2082 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2083 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2085 $segments = array();
2087 foreach ( $intervals as $intervalName => $intervalValue ) {
2088 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2089 $segments[] = $message->inLanguage( $this )->escaped();
2092 return $this->listToText( $segments );
2096 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2097 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2101 * @param integer $seconds The amount of seconds.
2102 * @param array $chosenIntervals The intervals to enable.
2106 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2107 if ( empty( $chosenIntervals ) ) {
2108 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2111 $intervals = array_intersect_key( self
::$durationIntervals, array_flip( $chosenIntervals ) );
2112 $sortedNames = array_keys( $intervals );
2113 $smallestInterval = array_pop( $sortedNames );
2115 $segments = array();
2117 foreach ( $intervals as $name => $length ) {
2118 $value = floor( $seconds / $length );
2120 if ( $value > 0 ||
( $name == $smallestInterval && empty( $segments ) ) ) {
2121 $seconds -= $value * $length;
2122 $segments[$name] = $value;
2130 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2132 * @param $type String: can be 'date', 'time' or 'both'
2133 * @param $ts Mixed: the time format which needs to be turned into a
2134 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2135 * @param $user User object used to get preferences for timezone and format
2136 * @param $options Array, can contain the following keys:
2137 * - 'timecorrection': time correction, can have the following values:
2138 * - true: use user's preference
2139 * - false: don't use time correction
2140 * - integer: value of time correction in minutes
2141 * - 'format': format to use, can have the following values:
2142 * - true: use user's preference
2143 * - false: use default preference
2144 * - string: format to use
2148 private function internalUserTimeAndDate( $type, $ts, User
$user, array $options ) {
2149 $ts = wfTimestamp( TS_MW
, $ts );
2150 $options +
= array( 'timecorrection' => true, 'format' => true );
2151 if ( $options['timecorrection'] !== false ) {
2152 if ( $options['timecorrection'] === true ) {
2153 $offset = $user->getOption( 'timecorrection' );
2155 $offset = $options['timecorrection'];
2157 $ts = $this->userAdjust( $ts, $offset );
2159 if ( $options['format'] === true ) {
2160 $format = $user->getDatePreference();
2162 $format = $options['format'];
2164 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2165 return $this->sprintfDate( $df, $ts );
2169 * Get the formatted date for the given timestamp and formatted for
2172 * @param $ts Mixed: the time format which needs to be turned into a
2173 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2174 * @param $user User object used to get preferences for timezone and format
2175 * @param $options Array, can contain the following keys:
2176 * - 'timecorrection': time correction, can have the following values:
2177 * - true: use user's preference
2178 * - false: don't use time correction
2179 * - integer: value of time correction in minutes
2180 * - 'format': format to use, can have the following values:
2181 * - true: use user's preference
2182 * - false: use default preference
2183 * - string: format to use
2187 public function userDate( $ts, User
$user, array $options = array() ) {
2188 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2192 * Get the formatted time for the given timestamp and formatted for
2195 * @param $ts Mixed: the time format which needs to be turned into a
2196 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2197 * @param $user User object used to get preferences for timezone and format
2198 * @param $options Array, can contain the following keys:
2199 * - 'timecorrection': time correction, can have the following values:
2200 * - true: use user's preference
2201 * - false: don't use time correction
2202 * - integer: value of time correction in minutes
2203 * - 'format': format to use, can have the following values:
2204 * - true: use user's preference
2205 * - false: use default preference
2206 * - string: format to use
2210 public function userTime( $ts, User
$user, array $options = array() ) {
2211 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2215 * Get the formatted date and time for the given timestamp and formatted for
2218 * @param $ts Mixed: the time format which needs to be turned into a
2219 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2220 * @param $user User object used to get preferences for timezone and format
2221 * @param $options Array, can contain the following keys:
2222 * - 'timecorrection': time correction, can have the following values:
2223 * - true: use user's preference
2224 * - false: don't use time correction
2225 * - integer: value of time correction in minutes
2226 * - 'format': format to use, can have the following values:
2227 * - true: use user's preference
2228 * - false: use default preference
2229 * - string: format to use
2233 public function userTimeAndDate( $ts, User
$user, array $options = array() ) {
2234 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2238 * @param $key string
2239 * @return array|null
2241 function getMessage( $key ) {
2242 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
2248 function getAllMessages() {
2249 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
2258 function iconv( $in, $out, $string ) {
2259 # This is a wrapper for iconv in all languages except esperanto,
2260 # which does some nasty x-conversions beforehand
2262 # Even with //IGNORE iconv can whine about illegal characters in
2263 # *input* string. We just ignore those too.
2264 # REF: http://bugs.php.net/bug.php?id=37166
2265 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2266 wfSuppressWarnings();
2267 $text = iconv( $in, $out . '//IGNORE', $string );
2268 wfRestoreWarnings();
2272 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2275 * @param $matches array
2276 * @return mixed|string
2278 function ucwordbreaksCallbackAscii( $matches ) {
2279 return $this->ucfirst( $matches[1] );
2283 * @param $matches array
2286 function ucwordbreaksCallbackMB( $matches ) {
2287 return mb_strtoupper( $matches[0] );
2291 * @param $matches array
2294 function ucCallback( $matches ) {
2295 list( $wikiUpperChars ) = self
::getCaseMaps();
2296 return strtr( $matches[1], $wikiUpperChars );
2300 * @param $matches array
2303 function lcCallback( $matches ) {
2304 list( , $wikiLowerChars ) = self
::getCaseMaps();
2305 return strtr( $matches[1], $wikiLowerChars );
2309 * @param $matches array
2312 function ucwordsCallbackMB( $matches ) {
2313 return mb_strtoupper( $matches[0] );
2317 * @param $matches array
2320 function ucwordsCallbackWiki( $matches ) {
2321 list( $wikiUpperChars ) = self
::getCaseMaps();
2322 return strtr( $matches[0], $wikiUpperChars );
2326 * Make a string's first character uppercase
2328 * @param $str string
2332 function ucfirst( $str ) {
2334 if ( $o < 96 ) { // if already uppercase...
2336 } elseif ( $o < 128 ) {
2337 return ucfirst( $str ); // use PHP's ucfirst()
2339 // fall back to more complex logic in case of multibyte strings
2340 return $this->uc( $str, true );
2345 * Convert a string to uppercase
2347 * @param $str string
2348 * @param $first bool
2352 function uc( $str, $first = false ) {
2353 if ( function_exists( 'mb_strtoupper' ) ) {
2355 if ( $this->isMultibyte( $str ) ) {
2356 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2358 return ucfirst( $str );
2361 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
2364 if ( $this->isMultibyte( $str ) ) {
2365 $x = $first ?
'^' : '';
2366 return preg_replace_callback(
2367 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2368 array( $this, 'ucCallback' ),
2372 return $first ?
ucfirst( $str ) : strtoupper( $str );
2378 * @param $str string
2379 * @return mixed|string
2381 function lcfirst( $str ) {
2384 return strval( $str );
2385 } elseif ( $o >= 128 ) {
2386 return $this->lc( $str, true );
2387 } elseif ( $o > 96 ) {
2390 $str[0] = strtolower( $str[0] );
2396 * @param $str string
2397 * @param $first bool
2398 * @return mixed|string
2400 function lc( $str, $first = false ) {
2401 if ( function_exists( 'mb_strtolower' ) ) {
2403 if ( $this->isMultibyte( $str ) ) {
2404 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2406 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2409 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
2412 if ( $this->isMultibyte( $str ) ) {
2413 $x = $first ?
'^' : '';
2414 return preg_replace_callback(
2415 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2416 array( $this, 'lcCallback' ),
2420 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2426 * @param $str string
2429 function isMultibyte( $str ) {
2430 return (bool)preg_match( '/[\x80-\xff]/', $str );
2434 * @param $str string
2435 * @return mixed|string
2437 function ucwords( $str ) {
2438 if ( $this->isMultibyte( $str ) ) {
2439 $str = $this->lc( $str );
2441 // regexp to find first letter in each word (i.e. after each space)
2442 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2444 // function to use to capitalize a single char
2445 if ( function_exists( 'mb_strtoupper' ) ) {
2446 return preg_replace_callback(
2448 array( $this, 'ucwordsCallbackMB' ),
2452 return preg_replace_callback(
2454 array( $this, 'ucwordsCallbackWiki' ),
2459 return ucwords( strtolower( $str ) );
2464 * capitalize words at word breaks
2466 * @param $str string
2469 function ucwordbreaks( $str ) {
2470 if ( $this->isMultibyte( $str ) ) {
2471 $str = $this->lc( $str );
2473 // since \b doesn't work for UTF-8, we explicitely define word break chars
2474 $breaks = "[ \-\(\)\}\{\.,\?!]";
2476 // find first letter after word break
2477 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2479 if ( function_exists( 'mb_strtoupper' ) ) {
2480 return preg_replace_callback(
2482 array( $this, 'ucwordbreaksCallbackMB' ),
2486 return preg_replace_callback(
2488 array( $this, 'ucwordsCallbackWiki' ),
2493 return preg_replace_callback(
2494 '/\b([\w\x80-\xff]+)\b/',
2495 array( $this, 'ucwordbreaksCallbackAscii' ),
2502 * Return a case-folded representation of $s
2504 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2505 * and $s2 are the same except for the case of their characters. It is not
2506 * necessary for the value returned to make sense when displayed.
2508 * Do *not* perform any other normalisation in this function. If a caller
2509 * uses this function when it should be using a more general normalisation
2510 * function, then fix the caller.
2516 function caseFold( $s ) {
2517 return $this->uc( $s );
2524 function checkTitleEncoding( $s ) {
2525 if ( is_array( $s ) ) {
2526 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2528 if ( StringUtils
::isUtf8( $s ) ) {
2532 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2538 function fallback8bitEncoding() {
2539 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2543 * Most writing systems use whitespace to break up words.
2544 * Some languages such as Chinese don't conventionally do this,
2545 * which requires special handling when breaking up words for
2550 function hasWordBreaks() {
2555 * Some languages such as Chinese require word segmentation,
2556 * Specify such segmentation when overridden in derived class.
2558 * @param $string String
2561 function segmentByWord( $string ) {
2566 * Some languages have special punctuation need to be normalized.
2567 * Make such changes here.
2569 * @param $string String
2572 function normalizeForSearch( $string ) {
2573 return self
::convertDoubleWidth( $string );
2577 * convert double-width roman characters to single-width.
2578 * range: ff00-ff5f ~= 0020-007f
2580 * @param $string string
2584 protected static function convertDoubleWidth( $string ) {
2585 static $full = null;
2586 static $half = null;
2588 if ( $full === null ) {
2589 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2590 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2591 $full = str_split( $fullWidth, 3 );
2592 $half = str_split( $halfWidth );
2595 $string = str_replace( $full, $half, $string );
2600 * @param $string string
2601 * @param $pattern string
2604 protected static function insertSpace( $string, $pattern ) {
2605 $string = preg_replace( $pattern, " $1 ", $string );
2606 $string = preg_replace( '/ +/', ' ', $string );
2611 * @param $termsArray array
2614 function convertForSearchResult( $termsArray ) {
2615 # some languages, e.g. Chinese, need to do a conversion
2616 # in order for search results to be displayed correctly
2621 * Get the first character of a string.
2626 function firstChar( $s ) {
2629 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2630 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2635 if ( isset( $matches[1] ) ) {
2636 if ( strlen( $matches[1] ) != 3 ) {
2640 // Break down Hangul syllables to grab the first jamo
2641 $code = utf8ToCodepoint( $matches[1] );
2642 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2644 } elseif ( $code < 0xb098 ) {
2645 return "\xe3\x84\xb1";
2646 } elseif ( $code < 0xb2e4 ) {
2647 return "\xe3\x84\xb4";
2648 } elseif ( $code < 0xb77c ) {
2649 return "\xe3\x84\xb7";
2650 } elseif ( $code < 0xb9c8 ) {
2651 return "\xe3\x84\xb9";
2652 } elseif ( $code < 0xbc14 ) {
2653 return "\xe3\x85\x81";
2654 } elseif ( $code < 0xc0ac ) {
2655 return "\xe3\x85\x82";
2656 } elseif ( $code < 0xc544 ) {
2657 return "\xe3\x85\x85";
2658 } elseif ( $code < 0xc790 ) {
2659 return "\xe3\x85\x87";
2660 } elseif ( $code < 0xcc28 ) {
2661 return "\xe3\x85\x88";
2662 } elseif ( $code < 0xce74 ) {
2663 return "\xe3\x85\x8a";
2664 } elseif ( $code < 0xd0c0 ) {
2665 return "\xe3\x85\x8b";
2666 } elseif ( $code < 0xd30c ) {
2667 return "\xe3\x85\x8c";
2668 } elseif ( $code < 0xd558 ) {
2669 return "\xe3\x85\x8d";
2671 return "\xe3\x85\x8e";
2678 function initEncoding() {
2679 # Some languages may have an alternate char encoding option
2680 # (Esperanto X-coding, Japanese furigana conversion, etc)
2681 # If this language is used as the primary content language,
2682 # an override to the defaults can be set here on startup.
2689 function recodeForEdit( $s ) {
2690 # For some languages we'll want to explicitly specify
2691 # which characters make it into the edit box raw
2692 # or are converted in some way or another.
2693 global $wgEditEncoding;
2694 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2697 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2705 function recodeInput( $s ) {
2706 # Take the previous into account.
2707 global $wgEditEncoding;
2708 if ( $wgEditEncoding != '' ) {
2709 $enc = $wgEditEncoding;
2713 if ( $enc == 'UTF-8' ) {
2716 return $this->iconv( $enc, 'UTF-8', $s );
2721 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2722 * also cleans up certain backwards-compatible sequences, converting them
2723 * to the modern Unicode equivalent.
2725 * This is language-specific for performance reasons only.
2731 function normalize( $s ) {
2732 global $wgAllUnicodeFixes;
2733 $s = UtfNormal
::cleanUp( $s );
2734 if ( $wgAllUnicodeFixes ) {
2735 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2736 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2743 * Transform a string using serialized data stored in the given file (which
2744 * must be in the serialized subdirectory of $IP). The file contains pairs
2745 * mapping source characters to destination characters.
2747 * The data is cached in process memory. This will go faster if you have the
2748 * FastStringSearch extension.
2750 * @param $file string
2751 * @param $string string
2753 * @throws MWException
2756 function transformUsingPairFile( $file, $string ) {
2757 if ( !isset( $this->transformData
[$file] ) ) {
2758 $data = wfGetPrecompiledData( $file );
2759 if ( $data === false ) {
2760 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2762 $this->transformData
[$file] = new ReplacementArray( $data );
2764 return $this->transformData
[$file]->replace( $string );
2768 * For right-to-left language support
2773 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2777 * Return the correct HTML 'dir' attribute value for this language.
2781 return $this->isRTL() ?
'rtl' : 'ltr';
2785 * Return 'left' or 'right' as appropriate alignment for line-start
2786 * for this language's text direction.
2788 * Should be equivalent to CSS3 'start' text-align value....
2792 function alignStart() {
2793 return $this->isRTL() ?
'right' : 'left';
2797 * Return 'right' or 'left' as appropriate alignment for line-end
2798 * for this language's text direction.
2800 * Should be equivalent to CSS3 'end' text-align value....
2804 function alignEnd() {
2805 return $this->isRTL() ?
'left' : 'right';
2809 * A hidden direction mark (LRM or RLM), depending on the language direction.
2810 * Unlike getDirMark(), this function returns the character as an HTML entity.
2811 * This function should be used when the output is guaranteed to be HTML,
2812 * because it makes the output HTML source code more readable. When
2813 * the output is plain text or can be escaped, getDirMark() should be used.
2815 * @param $opposite Boolean Get the direction mark opposite to your language
2819 function getDirMarkEntity( $opposite = false ) {
2820 if ( $opposite ) { return $this->isRTL() ?
'‎' : '‏'; }
2821 return $this->isRTL() ?
'‏' : '‎';
2825 * A hidden direction mark (LRM or RLM), depending on the language direction.
2826 * This function produces them as invisible Unicode characters and
2827 * the output may be hard to read and debug, so it should only be used
2828 * when the output is plain text or can be escaped. When the output is
2829 * HTML, use getDirMarkEntity() instead.
2831 * @param $opposite Boolean Get the direction mark opposite to your language
2834 function getDirMark( $opposite = false ) {
2835 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2836 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2837 if ( $opposite ) { return $this->isRTL() ?
$lrm : $rlm; }
2838 return $this->isRTL() ?
$rlm : $lrm;
2844 function capitalizeAllNouns() {
2845 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2849 * An arrow, depending on the language direction.
2851 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2854 function getArrow( $direction = 'forwards' ) {
2855 switch ( $direction ) {
2857 return $this->isRTL() ?
'←' : '→';
2859 return $this->isRTL() ?
'→' : '←';
2872 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2876 function linkPrefixExtension() {
2877 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2883 function getMagicWords() {
2884 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2887 protected function doMagicHook() {
2888 if ( $this->mMagicHookDone
) {
2891 $this->mMagicHookDone
= true;
2892 wfProfileIn( 'LanguageGetMagic' );
2893 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2894 wfProfileOut( 'LanguageGetMagic' );
2898 * Fill a MagicWord object with data from here
2902 function getMagic( $mw ) {
2903 $this->doMagicHook();
2905 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2906 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2908 $magicWords = $this->getMagicWords();
2909 if ( isset( $magicWords[$mw->mId
] ) ) {
2910 $rawEntry = $magicWords[$mw->mId
];
2916 if ( !is_array( $rawEntry ) ) {
2917 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2919 $mw->mCaseSensitive
= $rawEntry[0];
2920 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2925 * Add magic words to the extension array
2927 * @param $newWords array
2929 function addMagicWordsByLang( $newWords ) {
2930 $fallbackChain = $this->getFallbackLanguages();
2931 $fallbackChain = array_reverse( $fallbackChain );
2932 foreach ( $fallbackChain as $code ) {
2933 if ( isset( $newWords[$code] ) ) {
2934 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2940 * Get special page names, as an associative array
2941 * case folded alias => real name
2943 function getSpecialPageAliases() {
2944 // Cache aliases because it may be slow to load them
2945 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2947 $this->mExtendedSpecialPageAliases
=
2948 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2949 wfRunHooks( 'LanguageGetSpecialPageAliases',
2950 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2953 return $this->mExtendedSpecialPageAliases
;
2957 * Italic is unsuitable for some languages
2959 * @param $text String: the text to be emphasized.
2962 function emphasize( $text ) {
2963 return "<em>$text</em>";
2967 * Normally we output all numbers in plain en_US style, that is
2968 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2969 * point twohundredthirtyfive. However this is not suitable for all
2970 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2971 * Icelandic just want to use commas instead of dots, and dots instead
2972 * of commas like "293.291,235".
2974 * An example of this function being called:
2976 * wfMessage( 'message' )->numParams( $num )->text()
2979 * See LanguageGu.php for the Gujarati implementation and
2980 * $separatorTransformTable on MessageIs.php for
2981 * the , => . and . => , implementation.
2983 * @todo check if it's viable to use localeconv() for the decimal
2985 * @param $number Mixed: the string to be formatted, should be an integer
2986 * or a floating point number.
2987 * @param $nocommafy Bool: set to true for special numbers like dates
2990 public function formatNum( $number, $nocommafy = false ) {
2991 global $wgTranslateNumerals;
2992 if ( !$nocommafy ) {
2993 $number = $this->commafy( $number );
2994 $s = $this->separatorTransformTable();
2996 $number = strtr( $number, $s );
3000 if ( $wgTranslateNumerals ) {
3001 $s = $this->digitTransformTable();
3003 $number = strtr( $number, $s );
3011 * Front-end for non-commafied formatNum
3013 * @param mixed $number the string to be formatted, should be an integer
3014 * or a floating point number.
3018 public function formatNumNoSeparators( $number ) {
3019 return $this->formatNum( $number, true );
3023 * @param $number string
3026 function parseFormattedNumber( $number ) {
3027 $s = $this->digitTransformTable();
3029 $number = strtr( $number, array_flip( $s ) );
3032 $s = $this->separatorTransformTable();
3034 $number = strtr( $number, array_flip( $s ) );
3037 $number = strtr( $number, array( ',' => '' ) );
3042 * Adds commas to a given number
3044 * @param $number mixed
3047 function commafy( $number ) {
3048 $digitGroupingPattern = $this->digitGroupingPattern();
3049 if ( $number === null ) {
3053 if ( !$digitGroupingPattern ||
$digitGroupingPattern === "###,###,###" ) {
3054 // default grouping is at thousands, use the same for ###,###,### pattern too.
3055 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3057 // Ref: http://cldr.unicode.org/translation/number-patterns
3059 if ( intval( $number ) < 0 ) {
3060 // For negative numbers apply the algorithm like positive number and add sign.
3062 $number = substr( $number, 1 );
3064 $integerPart = array();
3065 $decimalPart = array();
3066 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3067 preg_match( "/\d+/", $number, $integerPart );
3068 preg_match( "/\.\d*/", $number, $decimalPart );
3069 $groupedNumber = ( count( $decimalPart ) > 0 ) ?
$decimalPart[0]:"";
3070 if ( $groupedNumber === $number ) {
3071 // the string does not have any number part. Eg: .12345
3072 return $sign . $groupedNumber;
3074 $start = $end = strlen( $integerPart[0] );
3075 while ( $start > 0 ) {
3076 $match = $matches[0][$numMatches -1] ;
3077 $matchLen = strlen( $match );
3078 $start = $end - $matchLen;
3082 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber ;
3084 if ( $numMatches > 1 ) {
3085 // use the last pattern for the rest of the number
3089 $groupedNumber = "," . $groupedNumber;
3092 return $sign . $groupedNumber;
3099 function digitGroupingPattern() {
3100 return self
::$dataCache->getItem( $this->mCode
, 'digitGroupingPattern' );
3106 function digitTransformTable() {
3107 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
3113 function separatorTransformTable() {
3114 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
3118 * Take a list of strings and build a locale-friendly comma-separated
3119 * list, using the local comma-separator message.
3120 * The last two strings are chained with an "and".
3121 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3126 function listToText( array $l ) {
3127 $m = count( $l ) - 1;
3132 $and = $this->getMessageFromDB( 'and' );
3133 $space = $this->getMessageFromDB( 'word-separator' );
3135 $comma = $this->getMessageFromDB( 'comma-separator' );
3139 for ( $i = $m - 1; $i >= 0; $i-- ) {
3140 if ( $i == $m - 1 ) {
3141 $s = $l[$i] . $and . $space . $s;
3143 $s = $l[$i] . $comma . $s;
3150 * Take a list of strings and build a locale-friendly comma-separated
3151 * list, using the local comma-separator message.
3152 * @param $list array of strings to put in a comma list
3155 function commaList( array $list ) {
3157 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3163 * Take a list of strings and build a locale-friendly semicolon-separated
3164 * list, using the local semicolon-separator message.
3165 * @param $list array of strings to put in a semicolon list
3168 function semicolonList( array $list ) {
3170 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3176 * Same as commaList, but separate it with the pipe instead.
3177 * @param $list array of strings to put in a pipe list
3180 function pipeList( array $list ) {
3182 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3188 * Truncate a string to a specified length in bytes, appending an optional
3189 * string (e.g. for ellipses)
3191 * The database offers limited byte lengths for some columns in the database;
3192 * multi-byte character sets mean we need to ensure that only whole characters
3193 * are included, otherwise broken characters can be passed to the user
3195 * If $length is negative, the string will be truncated from the beginning
3197 * @param $string String to truncate
3198 * @param $length Int: maximum length (including ellipses)
3199 * @param $ellipsis String to append to the truncated text
3200 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3201 * $adjustLength was introduced in 1.18, before that behaved as if false.
3204 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3205 # Use the localized ellipsis character
3206 if ( $ellipsis == '...' ) {
3207 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3209 # Check if there is no need to truncate
3210 if ( $length == 0 ) {
3211 return $ellipsis; // convention
3212 } elseif ( strlen( $string ) <= abs( $length ) ) {
3213 return $string; // no need to truncate
3215 $stringOriginal = $string;
3216 # If ellipsis length is >= $length then we can't apply $adjustLength
3217 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3218 $string = $ellipsis; // this can be slightly unexpected
3219 # Otherwise, truncate and add ellipsis...
3221 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
3222 if ( $length > 0 ) {
3223 $length -= $eLength;
3224 $string = substr( $string, 0, $length ); // xyz...
3225 $string = $this->removeBadCharLast( $string );
3226 $string = $string . $ellipsis;
3228 $length +
= $eLength;
3229 $string = substr( $string, $length ); // ...xyz
3230 $string = $this->removeBadCharFirst( $string );
3231 $string = $ellipsis . $string;
3234 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3235 # This check is *not* redundant if $adjustLength, due to the single case where
3236 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3237 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3240 return $stringOriginal;
3245 * Remove bytes that represent an incomplete Unicode character
3246 * at the end of string (e.g. bytes of the char are missing)
3248 * @param $string String
3251 protected function removeBadCharLast( $string ) {
3252 if ( $string != '' ) {
3253 $char = ord( $string[strlen( $string ) - 1] );
3255 if ( $char >= 0xc0 ) {
3256 # We got the first byte only of a multibyte char; remove it.
3257 $string = substr( $string, 0, -1 );
3258 } elseif ( $char >= 0x80 &&
3259 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3260 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3262 # We chopped in the middle of a character; remove it
3270 * Remove bytes that represent an incomplete Unicode character
3271 * at the start of string (e.g. bytes of the char are missing)
3273 * @param $string String
3276 protected function removeBadCharFirst( $string ) {
3277 if ( $string != '' ) {
3278 $char = ord( $string[0] );
3279 if ( $char >= 0x80 && $char < 0xc0 ) {
3280 # We chopped in the middle of a character; remove the whole thing
3281 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3288 * Truncate a string of valid HTML to a specified length in bytes,
3289 * appending an optional string (e.g. for ellipses), and return valid HTML
3291 * This is only intended for styled/linked text, such as HTML with
3292 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3293 * Also, this will not detect things like "display:none" CSS.
3295 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3297 * @param string $text HTML string to truncate
3298 * @param int $length (zero/positive) Maximum length (including ellipses)
3299 * @param string $ellipsis String to append to the truncated text
3302 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3303 # Use the localized ellipsis character
3304 if ( $ellipsis == '...' ) {
3305 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3307 # Check if there is clearly no need to truncate
3308 if ( $length <= 0 ) {
3309 return $ellipsis; // no text shown, nothing to format (convention)
3310 } elseif ( strlen( $text ) <= $length ) {
3311 return $text; // string short enough even *with* HTML (short-circuit)
3314 $dispLen = 0; // innerHTML legth so far
3315 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3316 $tagType = 0; // 0-open, 1-close
3317 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3318 $entityState = 0; // 0-not entity, 1-entity
3319 $tag = $ret = ''; // accumulated tag name, accumulated result string
3320 $openTags = array(); // open tag stack
3321 $maybeState = null; // possible truncation state
3323 $textLen = strlen( $text );
3324 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3325 for ( $pos = 0; true; ++
$pos ) {
3326 # Consider truncation once the display length has reached the maximim.
3327 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3328 # Check that we're not in the middle of a bracket/entity...
3329 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3330 if ( !$testingEllipsis ) {
3331 $testingEllipsis = true;
3332 # Save where we are; we will truncate here unless there turn out to
3333 # be so few remaining characters that truncation is not necessary.
3334 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3335 $maybeState = array( $ret, $openTags ); // save state
3337 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3338 # String in fact does need truncation, the truncation point was OK.
3339 list( $ret, $openTags ) = $maybeState; // reload state
3340 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3341 $ret .= $ellipsis; // add ellipsis
3345 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3347 # Read the next char...
3349 $lastCh = $pos ?
$text[$pos - 1] : '';
3350 $ret .= $ch; // add to result string
3352 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3353 $entityState = 0; // for bad HTML
3354 $bracketState = 1; // tag started (checking for backslash)
3355 } elseif ( $ch == '>' ) {
3356 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3357 $entityState = 0; // for bad HTML
3358 $bracketState = 0; // out of brackets
3359 } elseif ( $bracketState == 1 ) {
3361 $tagType = 1; // close tag (e.g. "</span>")
3363 $tagType = 0; // open tag (e.g. "<span>")
3366 $bracketState = 2; // building tag name
3367 } elseif ( $bracketState == 2 ) {
3371 // Name found (e.g. "<a href=..."), add on tag attributes...
3372 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
3374 } elseif ( $bracketState == 0 ) {
3375 if ( $entityState ) {
3378 $dispLen++
; // entity is one displayed char
3381 if ( $neLength == 0 && !$maybeState ) {
3382 // Save state without $ch. We want to *hit* the first
3383 // display char (to get tags) but not *use* it if truncating.
3384 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3387 $entityState = 1; // entity found, (e.g. " ")
3389 $dispLen++
; // this char is displayed
3390 // Add the next $max display text chars after this in one swoop...
3391 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
3392 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
3393 $dispLen +
= $skipped;
3399 // Close the last tag if left unclosed by bad HTML
3400 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3401 while ( count( $openTags ) > 0 ) {
3402 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3408 * truncateHtml() helper function
3409 * like strcspn() but adds the skipped chars to $ret
3418 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3419 if ( $len === null ) {
3420 $len = -1; // -1 means "no limit" for strcspn
3421 } elseif ( $len < 0 ) {
3425 if ( $start < strlen( $text ) ) {
3426 $skipCount = strcspn( $text, $search, $start, $len );
3427 $ret .= substr( $text, $start, $skipCount );
3433 * truncateHtml() helper function
3434 * (a) push or pop $tag from $openTags as needed
3435 * (b) clear $tag value
3436 * @param &$tag string Current HTML tag name we are looking at
3437 * @param $tagType int (0-open tag, 1-close tag)
3438 * @param $lastCh string Character before the '>' that ended this tag
3439 * @param &$openTags array Open tag stack (not accounting for $tag)
3441 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3442 $tag = ltrim( $tag );
3444 if ( $tagType == 0 && $lastCh != '/' ) {
3445 $openTags[] = $tag; // tag opened (didn't close itself)
3446 } elseif ( $tagType == 1 ) {
3447 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3448 array_pop( $openTags ); // tag closed
3456 * Grammatical transformations, needed for inflected languages
3457 * Invoked by putting {{grammar:case|word}} in a message
3459 * @param $word string
3460 * @param $case string
3463 function convertGrammar( $word, $case ) {
3464 global $wgGrammarForms;
3465 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3466 return $wgGrammarForms[$this->getCode()][$case][$word];
3471 * Get the grammar forms for the content language
3472 * @return array of grammar forms
3475 function getGrammarForms() {
3476 global $wgGrammarForms;
3477 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3478 return $wgGrammarForms[$this->getCode()];
3483 * Provides an alternative text depending on specified gender.
3484 * Usage {{gender:username|masculine|feminine|neutral}}.
3485 * username is optional, in which case the gender of current user is used,
3486 * but only in (some) interface messages; otherwise default gender is used.
3488 * If no forms are given, an empty string is returned. If only one form is
3489 * given, it will be returned unconditionally. These details are implied by
3490 * the caller and cannot be overridden in subclasses.
3492 * If more than one form is given, the default is to use the neutral one
3493 * if it is specified, and to use the masculine one otherwise. These
3494 * details can be overridden in subclasses.
3496 * @param $gender string
3497 * @param $forms array
3501 function gender( $gender, $forms ) {
3502 if ( !count( $forms ) ) {
3505 $forms = $this->preConvertPlural( $forms, 2 );
3506 if ( $gender === 'male' ) {
3509 if ( $gender === 'female' ) {
3512 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
3516 * Plural form transformations, needed for some languages.
3517 * For example, there are 3 form of plural in Russian and Polish,
3518 * depending on "count mod 10". See [[w:Plural]]
3519 * For English it is pretty simple.
3521 * Invoked by putting {{plural:count|wordform1|wordform2}}
3522 * or {{plural:count|wordform1|wordform2|wordform3}}
3524 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3526 * @param $count Integer: non-localized number
3527 * @param $forms Array: different plural forms
3528 * @return string Correct form of plural for $count in this language
3530 function convertPlural( $count, $forms ) {
3531 if ( !count( $forms ) ) {
3535 // Handle explicit n=pluralform cases
3536 foreach ( $forms as $index => $form ) {
3537 if ( preg_match( '/\d+=/i', $form ) ) {
3538 $pos = strpos( $form, '=' );
3539 if ( substr( $form, 0, $pos ) === (string) $count ) {
3540 return substr( $form, $pos +
1 );
3542 unset( $forms[$index] );
3545 $forms = array_values( $forms );
3547 $pluralForm = $this->getPluralForm( $count );
3548 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3549 return $forms[$pluralForm];
3553 * Checks that convertPlural was given an array and pads it to requested
3554 * amount of forms by copying the last one.
3556 * @param $count Integer: How many forms should there be at least
3557 * @param $forms Array of forms given to convertPlural
3558 * @return array Padded array of forms or an exception if not an array
3560 protected function preConvertPlural( /* Array */ $forms, $count ) {
3561 while ( count( $forms ) < $count ) {
3562 $forms[] = $forms[count( $forms ) - 1];
3568 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3569 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3570 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3571 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3574 * @param $str String: the validated block duration in English
3575 * @return string Somehow translated block duration
3576 * @see LanguageFi.php for example implementation
3578 function translateBlockExpiry( $str ) {
3579 $duration = SpecialBlock
::getSuggestedDurations( $this );
3580 foreach ( $duration as $show => $value ) {
3581 if ( strcmp( $str, $value ) == 0 ) {
3582 return htmlspecialchars( trim( $show ) );
3586 // Since usually only infinite or indefinite is only on list, so try
3587 // equivalents if still here.
3588 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3589 if ( in_array( $str, $indefs ) ) {
3590 foreach ( $indefs as $val ) {
3591 $show = array_search( $val, $duration, true );
3592 if ( $show !== false ) {
3593 return htmlspecialchars( trim( $show ) );
3598 // If all else fails, return a standard duration or timestamp description.
3599 $time = strtotime( $str, 0 );
3600 if ( $time === false ) { // Unknown format. Return it as-is in case.
3602 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3603 // $time is relative to 0 so it's a duration length.
3604 return $this->formatDuration( $time );
3605 } else { // It's an absolute timestamp.
3606 if ( $time === 0 ) {
3607 // wfTimestamp() handles 0 as current time instead of epoch.
3608 return $this->timeanddate( '19700101000000' );
3610 return $this->timeanddate( $time );
3616 * languages like Chinese need to be segmented in order for the diff
3619 * @param $text String
3622 public function segmentForDiff( $text ) {
3627 * and unsegment to show the result
3629 * @param $text String
3632 public function unsegmentForDiff( $text ) {
3637 * Return the LanguageConverter used in the Language
3640 * @return LanguageConverter
3642 public function getConverter() {
3643 return $this->mConverter
;
3647 * convert text to all supported variants
3649 * @param $text string
3652 public function autoConvertToAllVariants( $text ) {
3653 return $this->mConverter
->autoConvertToAllVariants( $text );
3657 * convert text to different variants of a language.
3659 * @param $text string
3662 public function convert( $text ) {
3663 return $this->mConverter
->convert( $text );
3667 * Convert a Title object to a string in the preferred variant
3669 * @param $title Title
3672 public function convertTitle( $title ) {
3673 return $this->mConverter
->convertTitle( $title );
3677 * Convert a namespace index to a string in the preferred variant
3682 public function convertNamespace( $ns ) {
3683 return $this->mConverter
->convertNamespace( $ns );
3687 * Check if this is a language with variants
3691 public function hasVariants() {
3692 return count( $this->getVariants() ) > 1;
3696 * Check if the language has the specific variant
3699 * @param $variant string
3702 public function hasVariant( $variant ) {
3703 return (bool)$this->mConverter
->validateVariant( $variant );
3707 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3709 * @param $text string
3712 public function armourMath( $text ) {
3713 return $this->mConverter
->armourMath( $text );
3717 * Perform output conversion on a string, and encode for safe HTML output.
3718 * @param $text String text to be converted
3719 * @param $isTitle Bool whether this conversion is for the article title
3721 * @todo this should get integrated somewhere sane
3723 public function convertHtml( $text, $isTitle = false ) {
3724 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3728 * @param $key string
3731 public function convertCategoryKey( $key ) {
3732 return $this->mConverter
->convertCategoryKey( $key );
3736 * Get the list of variants supported by this language
3737 * see sample implementation in LanguageZh.php
3739 * @return array an array of language codes
3741 public function getVariants() {
3742 return $this->mConverter
->getVariants();
3748 public function getPreferredVariant() {
3749 return $this->mConverter
->getPreferredVariant();
3755 public function getDefaultVariant() {
3756 return $this->mConverter
->getDefaultVariant();
3762 public function getURLVariant() {
3763 return $this->mConverter
->getURLVariant();
3767 * If a language supports multiple variants, it is
3768 * possible that non-existing link in one variant
3769 * actually exists in another variant. this function
3770 * tries to find it. See e.g. LanguageZh.php
3772 * @param $link String: the name of the link
3773 * @param $nt Mixed: the title object of the link
3774 * @param $ignoreOtherCond Boolean: to disable other conditions when
3775 * we need to transclude a template or update a category's link
3776 * @return null the input parameters may be modified upon return
3778 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3779 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3783 * If a language supports multiple variants, converts text
3784 * into an array of all possible variants of the text:
3785 * 'variant' => text in that variant
3787 * @deprecated since 1.17 Use autoConvertToAllVariants()
3789 * @param $text string
3793 public function convertLinkToAllVariants( $text ) {
3794 return $this->mConverter
->convertLinkToAllVariants( $text );
3798 * returns language specific options used by User::getPageRenderHash()
3799 * for example, the preferred language variant
3803 function getExtraHashOptions() {
3804 return $this->mConverter
->getExtraHashOptions();
3808 * For languages that support multiple variants, the title of an
3809 * article may be displayed differently in different variants. this
3810 * function returns the apporiate title defined in the body of the article.
3814 public function getParsedTitle() {
3815 return $this->mConverter
->getParsedTitle();
3819 * Prepare external link text for conversion. When the text is
3820 * a URL, it shouldn't be converted, and it'll be wrapped in
3821 * the "raw" tag (-{R| }-) to prevent conversion.
3823 * This function is called "markNoConversion" for historical
3826 * @param $text String: text to be used for external link
3827 * @param $noParse bool: wrap it without confirming it's a real URL first
3828 * @return string the tagged text
3830 public function markNoConversion( $text, $noParse = false ) {
3831 // Excluding protocal-relative URLs may avoid many false positives.
3832 if ( $noParse ||
preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3833 return $this->mConverter
->markNoConversion( $text );
3840 * A regular expression to match legal word-trailing characters
3841 * which should be merged onto a link of the form [[foo]]bar.
3845 public function linkTrail() {
3846 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3852 function getLangObj() {
3857 * Get the RFC 3066 code for this language object
3859 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3860 * htmlspecialchars() or similar
3864 public function getCode() {
3865 return $this->mCode
;
3869 * Get the code in Bcp47 format which we can use
3870 * inside of html lang="" tags.
3872 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3873 * htmlspecialchars() or similar.
3878 public function getHtmlCode() {
3879 if ( is_null( $this->mHtmlCode
) ) {
3880 $this->mHtmlCode
= wfBCP47( $this->getCode() );
3882 return $this->mHtmlCode
;
3886 * @param $code string
3888 public function setCode( $code ) {
3889 $this->mCode
= $code;
3890 // Ensure we don't leave an incorrect html code lying around
3891 $this->mHtmlCode
= null;
3895 * Get the name of a file for a certain language code
3896 * @param $prefix string Prepend this to the filename
3897 * @param $code string Language code
3898 * @param $suffix string Append this to the filename
3899 * @throws MWException
3900 * @return string $prefix . $mangledCode . $suffix
3902 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3903 // Protect against path traversal
3904 if ( !Language
::isValidCode( $code )
3905 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3907 throw new MWException( "Invalid language code \"$code\"" );
3910 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3914 * Get the language code from a file name. Inverse of getFileName()
3915 * @param $filename string $prefix . $languageCode . $suffix
3916 * @param $prefix string Prefix before the language code
3917 * @param $suffix string Suffix after the language code
3918 * @return string Language code, or false if $prefix or $suffix isn't found
3920 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3922 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3923 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3924 if ( !count( $m ) ) {
3927 return str_replace( '_', '-', strtolower( $m[1] ) );
3931 * @param $code string
3934 public static function getMessagesFileName( $code ) {
3936 $file = self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3937 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3942 * @param $code string
3945 public static function getClassFileName( $code ) {
3947 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3951 * Get the first fallback for a given language.
3953 * @param $code string
3955 * @return bool|string
3957 public static function getFallbackFor( $code ) {
3958 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3961 $fallbacks = self
::getFallbacksFor( $code );
3962 $first = array_shift( $fallbacks );
3968 * Get the ordered list of fallback languages.
3971 * @param $code string Language code
3974 public static function getFallbacksFor( $code ) {
3975 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3978 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3979 $v = array_map( 'trim', explode( ',', $v ) );
3980 if ( $v[count( $v ) - 1] !== 'en' ) {
3988 * Get the ordered list of fallback languages, ending with the fallback
3989 * language chain for the site language.
3992 * @param $code string Language code
3995 public static function getFallbacksIncludingSiteLanguage( $code ) {
3996 global $wgLanguageCode;
3998 // Usually, we will only store a tiny number of fallback chains, so we
3999 // keep them in static memory.
4000 static $fallbackLanguageCache = array();
4001 $cacheKey = "{$code}-{$wgLanguageCode}";
4003 if ( !array_key_exists( $cacheKey, $fallbackLanguageCache ) ) {
4004 $fallbacks = self
::getFallbacksFor( $code );
4006 // Take the final 'en' off of the array before splicing
4007 if ( end( $fallbacks ) === 'en' ) {
4008 array_pop( $fallbacks );
4010 // Append the site's fallback chain
4011 $siteFallbacks = self
::getFallbacksFor( $wgLanguageCode );
4013 // Eliminate any languages already included in the chain
4014 $siteFallbacks = array_intersect( array_diff( $siteFallbacks, $fallbacks ), $siteFallbacks );
4015 if ( $siteFallbacks ) {
4016 $fallbacks = array_merge( $fallbacks, $siteFallbacks );
4018 if ( end( $fallbacks ) !== 'en' ) {
4019 $fallbacks[] = 'en';
4021 $fallbackLanguageCache[$cacheKey] = $fallbacks;
4023 return $fallbackLanguageCache[$cacheKey];
4027 * Get all messages for a given language
4028 * WARNING: this may take a long time. If you just need all message *keys*
4029 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4031 * @param $code string
4035 public static function getMessagesFor( $code ) {
4036 return self
::getLocalisationCache()->getItem( $code, 'messages' );
4040 * Get a message for a given language
4042 * @param $key string
4043 * @param $code string
4047 public static function getMessageFor( $key, $code ) {
4048 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4052 * Get all message keys for a given language. This is a faster alternative to
4053 * array_keys( Language::getMessagesFor( $code ) )
4056 * @param $code string Language code
4057 * @return array of message keys (strings)
4059 public static function getMessageKeysFor( $code ) {
4060 return self
::getLocalisationCache()->getSubItemList( $code, 'messages' );
4067 function fixVariableInNamespace( $talk ) {
4068 if ( strpos( $talk, '$1' ) === false ) {
4072 global $wgMetaNamespace;
4073 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4075 # Allow grammar transformations
4076 # Allowing full message-style parsing would make simple requests
4077 # such as action=raw much more expensive than they need to be.
4078 # This will hopefully cover most cases.
4079 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4080 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4081 return str_replace( ' ', '_', $talk );
4088 function replaceGrammarInNamespace( $m ) {
4089 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4093 * @throws MWException
4096 static function getCaseMaps() {
4097 static $wikiUpperChars, $wikiLowerChars;
4098 if ( isset( $wikiUpperChars ) ) {
4099 return array( $wikiUpperChars, $wikiLowerChars );
4102 wfProfileIn( __METHOD__
);
4103 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4104 if ( $arr === false ) {
4105 throw new MWException(
4106 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4108 $wikiUpperChars = $arr['wikiUpperChars'];
4109 $wikiLowerChars = $arr['wikiLowerChars'];
4110 wfProfileOut( __METHOD__
);
4111 return array( $wikiUpperChars, $wikiLowerChars );
4115 * Decode an expiry (block, protection, etc) which has come from the DB
4117 * @todo FIXME: why are we returnings DBMS-dependent strings???
4119 * @param $expiry String: Database expiry String
4120 * @param $format Bool|Int true to process using language functions, or TS_ constant
4121 * to return the expiry in a given timestamp
4125 public function formatExpiry( $expiry, $format = true ) {
4126 static $infinity, $infinityMsg;
4127 if ( $infinity === null ) {
4128 $infinityMsg = wfMessage( 'infiniteblock' );
4129 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
4132 if ( $expiry == '' ||
$expiry == $infinity ) {
4133 return $format === true
4137 return $format === true
4138 ?
$this->timeanddate( $expiry, /* User preference timezone */ true )
4139 : wfTimestamp( $format, $expiry );
4145 * @param $seconds int|float
4146 * @param $format Array Optional
4147 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4148 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4149 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4150 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4153 function formatTimePeriod( $seconds, $format = array() ) {
4154 if ( !is_array( $format ) ) {
4155 $format = array( 'avoid' => $format ); // For backwards compatibility
4157 if ( !isset( $format['avoid'] ) ) {
4158 $format['avoid'] = false;
4160 if ( !isset( $format['noabbrevs' ] ) ) {
4161 $format['noabbrevs'] = false;
4163 $secondsMsg = wfMessage(
4164 $format['noabbrevs'] ?
'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4165 $minutesMsg = wfMessage(
4166 $format['noabbrevs'] ?
'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4167 $hoursMsg = wfMessage(
4168 $format['noabbrevs'] ?
'hours' : 'hours-abbrev' )->inLanguage( $this );
4169 $daysMsg = wfMessage(
4170 $format['noabbrevs'] ?
'days' : 'days-abbrev' )->inLanguage( $this );
4172 if ( round( $seconds * 10 ) < 100 ) {
4173 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4174 $s = $secondsMsg->params( $s )->text();
4175 } elseif ( round( $seconds ) < 60 ) {
4176 $s = $this->formatNum( round( $seconds ) );
4177 $s = $secondsMsg->params( $s )->text();
4178 } elseif ( round( $seconds ) < 3600 ) {
4179 $minutes = floor( $seconds / 60 );
4180 $secondsPart = round( fmod( $seconds, 60 ) );
4181 if ( $secondsPart == 60 ) {
4185 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4187 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4188 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4189 $hours = floor( $seconds / 3600 );
4190 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4191 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4192 if ( $secondsPart == 60 ) {
4196 if ( $minutes == 60 ) {
4200 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4202 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4203 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4204 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4207 $days = floor( $seconds / 86400 );
4208 if ( $format['avoid'] === 'avoidminutes' ) {
4209 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4210 if ( $hours == 24 ) {
4214 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4216 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4217 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4218 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4219 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4220 if ( $minutes == 60 ) {
4224 if ( $hours == 24 ) {
4228 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4230 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4232 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4234 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4236 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4243 * Format a bitrate for output, using an appropriate
4244 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4246 * This use base 1000. For base 1024 use formatSize(), for another base
4247 * see formatComputingNumbers()
4252 function formatBitrate( $bps ) {
4253 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4257 * @param $size int Size of the unit
4258 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4259 * @param $messageKey string Message key to be uesd
4262 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4264 return str_replace( '$1', $this->formatNum( $size ),
4265 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4268 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4271 $maxIndex = count( $sizes ) - 1;
4272 while ( $size >= $boundary && $index < $maxIndex ) {
4277 // For small sizes no decimal places necessary
4280 // For MB and bigger two decimal places are smarter
4283 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4285 $size = round( $size, $round );
4286 $text = $this->getMessageFromDB( $msg );
4287 return str_replace( '$1', $this->formatNum( $size ), $text );
4291 * Format a size in bytes for output, using an appropriate
4292 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4294 * This method use base 1024. For base 1000 use formatBitrate(), for
4295 * another base see formatComputingNumbers()
4297 * @param $size int Size to format
4298 * @return string Plain text (not HTML)
4300 function formatSize( $size ) {
4301 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4305 * Make a list item, used by various special pages
4307 * @param $page String Page link
4308 * @param $details String Text between brackets
4309 * @param $oppositedm Boolean Add the direction mark opposite to your
4310 * language, to display text properly
4313 function specialList( $page, $details, $oppositedm = true ) {
4314 $dirmark = ( $oppositedm ?
$this->getDirMark( true ) : '' ) .
4315 $this->getDirMark();
4316 $details = $details ?
$dirmark . $this->getMessageFromDB( 'word-separator' ) .
4317 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4318 return $page . $details;
4322 * Generate (prev x| next x) (20|50|100...) type links for paging
4324 * @param $title Title object to link
4325 * @param $offset Integer offset parameter
4326 * @param $limit Integer limit parameter
4327 * @param $query array|String optional URL query parameter string
4328 * @param $atend Bool optional param for specified if this is the last page
4331 public function viewPrevNext( Title
$title, $offset, $limit, array $query = array(), $atend = false ) {
4332 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4334 # Make 'previous' link
4335 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4336 if ( $offset > 0 ) {
4337 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4338 $query, $prev, 'prevn-title', 'mw-prevlink' );
4340 $plink = htmlspecialchars( $prev );
4344 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4346 $nlink = htmlspecialchars( $next );
4348 $nlink = $this->numLink( $title, $offset +
$limit, $limit,
4349 $query, $next, 'prevn-title', 'mw-nextlink' );
4352 # Make links to set number of items per page
4353 $numLinks = array();
4354 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4355 $numLinks[] = $this->numLink( $title, $offset, $num,
4356 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4359 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4360 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4364 * Helper function for viewPrevNext() that generates links
4366 * @param $title Title object to link
4367 * @param $offset Integer offset parameter
4368 * @param $limit Integer limit parameter
4369 * @param $query Array extra query parameters
4370 * @param $link String text to use for the link; will be escaped
4371 * @param $tooltipMsg String name of the message to use as tooltip
4372 * @param $class String value of the "class" attribute of the link
4373 * @return String HTML fragment
4375 private function numLink( Title
$title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4376 $query = array( 'limit' => $limit, 'offset' => $offset ) +
$query;
4377 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4378 return Html
::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4379 'title' => $tooltip, 'class' => $class ), $link );
4383 * Get the conversion rule title, if any.
4387 public function getConvRuleTitle() {
4388 return $this->mConverter
->getConvRuleTitle();
4392 * Get the compiled plural rules for the language
4394 * @return array Associative array with plural form, and plural rule as key-value pairs
4396 public function getCompiledPluralRules() {
4397 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'compiledPluralRules' );
4398 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4399 if ( !$pluralRules ) {
4400 foreach ( $fallbacks as $fallbackCode ) {
4401 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4402 if ( $pluralRules ) {
4407 return $pluralRules;
4411 * Get the plural rules for the language
4413 * @return array Associative array with plural form, and plural rule as key-value pairs
4415 public function getPluralRules() {
4416 $pluralRules = self
::$dataCache->getItem( strtolower( $this->mCode
), 'pluralRules' );
4417 $fallbacks = Language
::getFallbacksFor( $this->mCode
);
4418 if ( !$pluralRules ) {
4419 foreach ( $fallbacks as $fallbackCode ) {
4420 $pluralRules = self
::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4421 if ( $pluralRules ) {
4426 return $pluralRules;
4430 * Find the plural form matching to the given number
4431 * It return the form index.
4432 * @return int The index of the plural form
4434 private function getPluralForm( $number ) {
4435 $pluralRules = $this->getCompiledPluralRules();
4436 $form = CLDRPluralRuleEvaluator
::evaluateCompiled( $number, $pluralRules );