Follow-up changes to r84610:
[mediawiki.git] / languages / Language.php
blob1acc15012c4f8753fa72f021f7ebc85cb99d1f36
1 <?php
2 /**
3 * Internationalisation code
5 * @file
6 * @ingroup Language
7 */
9 /**
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
22 global $wgInputEncoding, $wgOutputEncoding;
24 /**
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
34 /**
35 * a fake language converter
37 * @ingroup Language
39 class FakeConverter {
40 var $mLang;
41 function __construct( $langobj ) { $this->mLang = $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang->getCode() ); }
46 function getPreferredVariant() { return $this->mLang->getCode(); }
47 function getDefaultVariant() { return $this->mLang->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
59 /**
60 * Internationalisation code
61 * @ingroup Language
63 class Language {
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
71 /**
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
81 'friday', 'saturday'
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
91 'december'
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
96 'december-gen'
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
135 * @param $code String
136 * @return Language
138 static function factory( $code ) {
139 if ( !isset( self::$mLangObjCache[$code] ) ) {
140 if ( count( self::$mLangObjCache ) > 10 ) {
141 // Don't keep a billion objects around, that's stupid.
142 self::$mLangObjCache = array();
144 self::$mLangObjCache[$code] = self::newFromCode( $code );
146 return self::$mLangObjCache[$code];
150 * Create a language object for a given language code
151 * @param $code String
152 * @return Language
154 protected static function newFromCode( $code ) {
155 global $IP;
156 static $recursionLevel = 0;
158 // Protect against path traversal below
159 if ( !Language::isValidCode( $code )
160 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
162 throw new MWException( "Invalid language code \"$code\"" );
165 if ( !Language::isValidBuiltInCode( $code ) ) {
166 // It's not possible to customise this code with class files, so
167 // just return a Language object. This is to support uselang= hacks.
168 $lang = new Language;
169 $lang->setCode( $code );
170 return $lang;
173 if ( $code == 'en' ) {
174 $class = 'Language';
175 } else {
176 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
177 // Preload base classes to work around APC/PHP5 bug
178 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
179 include_once( "$IP/languages/classes/$class.deps.php" );
181 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
182 include_once( "$IP/languages/classes/$class.php" );
186 if ( $recursionLevel > 5 ) {
187 throw new MWException( "Language fallback loop detected when creating class $class\n" );
190 if ( !class_exists( $class ) ) {
191 $fallback = Language::getFallbackFor( $code );
192 ++$recursionLevel;
193 $lang = Language::newFromCode( $fallback );
194 --$recursionLevel;
195 $lang->setCode( $code );
196 } else {
197 $lang = new $class;
199 return $lang;
203 * Returns true if a language code string is of a valid form, whether or
204 * not it exists. This includes codes which are used solely for
205 * customisation via the MediaWiki namespace.
207 public static function isValidCode( $code ) {
208 return
209 strcspn( $code, ":/\\\000" ) === strlen( $code )
210 && !preg_match( Title::getTitleInvalidRegex(), $code );
214 * Returns true if a language code is of a valid form for the purposes of
215 * internal customisation of MediaWiki, via Messages*.php.
217 public static function isValidBuiltInCode( $code ) {
218 return preg_match( '/^[a-z0-9-]*$/i', $code );
222 * Get the LocalisationCache instance
224 * @return LocalisationCache
226 public static function getLocalisationCache() {
227 if ( is_null( self::$dataCache ) ) {
228 global $wgLocalisationCacheConf;
229 $class = $wgLocalisationCacheConf['class'];
230 self::$dataCache = new $class( $wgLocalisationCacheConf );
232 return self::$dataCache;
235 function __construct() {
236 $this->mConverter = new FakeConverter( $this );
237 // Set the code to the name of the descendant
238 if ( get_class( $this ) == 'Language' ) {
239 $this->mCode = 'en';
240 } else {
241 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
243 self::getLocalisationCache();
247 * Reduce memory usage
249 function __destruct() {
250 foreach ( $this as $name => $value ) {
251 unset( $this->$name );
256 * Hook which will be called if this is the content language.
257 * Descendants can use this to register hook functions or modify globals
259 function initContLang() { }
262 * @deprecated Use User::getDefaultOptions()
263 * @return array
265 function getDefaultUserOptions() {
266 wfDeprecated( __METHOD__ );
267 return User::getDefaultOptions();
270 function getFallbackLanguageCode() {
271 if ( $this->mCode === 'en' ) {
272 return false;
273 } else {
274 return self::$dataCache->getItem( $this->mCode, 'fallback' );
279 * Exports $wgBookstoreListEn
280 * @return array
282 function getBookstoreList() {
283 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
287 * @return array
289 function getNamespaces() {
290 if ( is_null( $this->namespaceNames ) ) {
291 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
293 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
294 $validNamespaces = MWNamespace::getCanonicalNamespaces();
296 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
298 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
299 if ( $wgMetaNamespaceTalk ) {
300 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
301 } else {
302 $talk = $this->namespaceNames[NS_PROJECT_TALK];
303 $this->namespaceNames[NS_PROJECT_TALK] =
304 $this->fixVariableInNamespace( $talk );
307 # Sometimes a language will be localised but not actually exist on this wiki.
308 foreach( $this->namespaceNames as $key => $text ) {
309 if ( !isset( $validNamespaces[$key] ) ) {
310 unset( $this->namespaceNames[$key] );
314 # The above mixing may leave namespaces out of canonical order.
315 # Re-order by namespace ID number...
316 ksort( $this->namespaceNames );
318 return $this->namespaceNames;
322 * A convenience function that returns the same thing as
323 * getNamespaces() except with the array values changed to ' '
324 * where it found '_', useful for producing output to be displayed
325 * e.g. in <select> forms.
327 * @return array
329 function getFormattedNamespaces() {
330 $ns = $this->getNamespaces();
331 foreach ( $ns as $k => $v ) {
332 $ns[$k] = strtr( $v, '_', ' ' );
334 return $ns;
338 * Get a namespace value by key
339 * <code>
340 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
341 * echo $mw_ns; // prints 'MediaWiki'
342 * </code>
344 * @param $index Int: the array key of the namespace to return
345 * @return mixed, string if the namespace value exists, otherwise false
347 function getNsText( $index ) {
348 $ns = $this->getNamespaces();
349 return isset( $ns[$index] ) ? $ns[$index] : false;
353 * A convenience function that returns the same thing as
354 * getNsText() except with '_' changed to ' ', useful for
355 * producing output.
357 * @return array
359 function getFormattedNsText( $index ) {
360 $ns = $this->getNsText( $index );
361 return strtr( $ns, '_', ' ' );
365 * Returns gender-dependent namespace alias if available.
366 * @param $index Int: namespace index
367 * @param $gender String: gender key (male, female... )
368 * @return String
369 * @since 1.18
371 function getGenderNsText( $index, $gender ) {
372 $ns = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
373 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
377 * Whether this language makes distinguishes genders for example in
378 * namespaces.
379 * @return bool
380 * @since 1.18
382 function needsGenderDistinction() {
383 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
384 return count( $aliases ) > 0;
388 * Get a namespace key by value, case insensitive.
389 * Only matches namespace names for the current language, not the
390 * canonical ones defined in Namespace.php.
392 * @param $text String
393 * @return mixed An integer if $text is a valid value otherwise false
395 function getLocalNsIndex( $text ) {
396 $lctext = $this->lc( $text );
397 $ids = $this->getNamespaceIds();
398 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
401 function getNamespaceAliases() {
402 if ( is_null( $this->namespaceAliases ) ) {
403 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
404 if ( !$aliases ) {
405 $aliases = array();
406 } else {
407 foreach ( $aliases as $name => $index ) {
408 if ( $index === NS_PROJECT_TALK ) {
409 unset( $aliases[$name] );
410 $name = $this->fixVariableInNamespace( $name );
411 $aliases[$name] = $index;
416 $genders = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
417 foreach ( $genders as $index => $forms ) {
418 foreach ( $forms as $alias ) {
419 $aliases[$alias] = $index;
423 $this->namespaceAliases = $aliases;
425 return $this->namespaceAliases;
428 function getNamespaceIds() {
429 if ( is_null( $this->mNamespaceIds ) ) {
430 global $wgNamespaceAliases;
431 # Put namespace names and aliases into a hashtable.
432 # If this is too slow, then we should arrange it so that it is done
433 # before caching. The catch is that at pre-cache time, the above
434 # class-specific fixup hasn't been done.
435 $this->mNamespaceIds = array();
436 foreach ( $this->getNamespaces() as $index => $name ) {
437 $this->mNamespaceIds[$this->lc( $name )] = $index;
439 foreach ( $this->getNamespaceAliases() as $name => $index ) {
440 $this->mNamespaceIds[$this->lc( $name )] = $index;
442 if ( $wgNamespaceAliases ) {
443 foreach ( $wgNamespaceAliases as $name => $index ) {
444 $this->mNamespaceIds[$this->lc( $name )] = $index;
448 return $this->mNamespaceIds;
453 * Get a namespace key by value, case insensitive. Canonical namespace
454 * names override custom ones defined for the current language.
456 * @param $text String
457 * @return mixed An integer if $text is a valid value otherwise false
459 function getNsIndex( $text ) {
460 $lctext = $this->lc( $text );
461 if ( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) {
462 return $ns;
464 $ids = $this->getNamespaceIds();
465 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
469 * short names for language variants used for language conversion links.
471 * @param $code String
472 * @return string
474 function getVariantname( $code ) {
475 return $this->getMessageFromDB( "variantname-$code" );
478 function specialPage( $name ) {
479 $aliases = $this->getSpecialPageAliases();
480 if ( isset( $aliases[$name][0] ) ) {
481 $name = $aliases[$name][0];
483 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
486 function getQuickbarSettings() {
487 return array(
488 $this->getMessage( 'qbsettings-none' ),
489 $this->getMessage( 'qbsettings-fixedleft' ),
490 $this->getMessage( 'qbsettings-fixedright' ),
491 $this->getMessage( 'qbsettings-floatingleft' ),
492 $this->getMessage( 'qbsettings-floatingright' )
496 function getMathNames() {
497 return self::$dataCache->getItem( $this->mCode, 'mathNames' );
500 function getDatePreferences() {
501 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
504 function getDateFormats() {
505 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
508 function getDefaultDateFormat() {
509 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
510 if ( $df === 'dmy or mdy' ) {
511 global $wgAmericanDates;
512 return $wgAmericanDates ? 'mdy' : 'dmy';
513 } else {
514 return $df;
518 function getDatePreferenceMigrationMap() {
519 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
522 function getImageFile( $image ) {
523 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
526 function getDefaultUserOptionOverrides() {
527 return self::$dataCache->getItem( $this->mCode, 'defaultUserOptionOverrides' );
530 function getExtraUserToggles() {
531 return self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
534 function getUserToggle( $tog ) {
535 return $this->getMessageFromDB( "tog-$tog" );
539 * Get language names, indexed by code.
540 * If $customisedOnly is true, only returns codes with a messages file
542 public static function getLanguageNames( $customisedOnly = false ) {
543 global $wgLanguageNames, $wgExtraLanguageNames;
544 $allNames = $wgExtraLanguageNames + $wgLanguageNames;
545 if ( !$customisedOnly ) {
546 return $allNames;
549 global $IP;
550 $names = array();
551 $dir = opendir( "$IP/languages/messages" );
552 while ( false !== ( $file = readdir( $dir ) ) ) {
553 $code = self::getCodeFromFileName( $file, 'Messages' );
554 if ( $code && isset( $allNames[$code] ) ) {
555 $names[$code] = $allNames[$code];
558 closedir( $dir );
559 return $names;
563 * Get translated language names. This is done on best effort and
564 * by default this is exactly the same as Language::getLanguageNames.
565 * The CLDR extension provides translated names.
566 * @param $code String Language code.
567 * @return Array language code => language name
568 * @since 1.18.0
570 public static function getTranslatedLanguageNames( $code ) {
571 $names = array();
572 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
574 foreach ( self::getLanguageNames() as $code => $name ) {
575 if ( !isset( $names[$code] ) ) $names[$code] = $name;
578 return $names;
582 * Get a message from the MediaWiki namespace.
584 * @param $msg String: message name
585 * @return string
587 function getMessageFromDB( $msg ) {
588 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
591 function getLanguageName( $code ) {
592 $names = self::getLanguageNames();
593 if ( !array_key_exists( $code, $names ) ) {
594 return '';
596 return $names[$code];
599 function getMonthName( $key ) {
600 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
603 function getMonthNameGen( $key ) {
604 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
607 function getMonthAbbreviation( $key ) {
608 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
611 function getWeekdayName( $key ) {
612 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
615 function getWeekdayAbbreviation( $key ) {
616 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
619 function getIranianCalendarMonthName( $key ) {
620 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
623 function getHebrewCalendarMonthName( $key ) {
624 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
627 function getHebrewCalendarMonthNameGen( $key ) {
628 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
631 function getHijriCalendarMonthName( $key ) {
632 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
636 * Used by date() and time() to adjust the time output.
638 * @param $ts Int the time in date('YmdHis') format
639 * @param $tz Mixed: adjust the time by this amount (default false, mean we
640 * get user timecorrection setting)
641 * @return int
643 function userAdjust( $ts, $tz = false ) {
644 global $wgUser, $wgLocalTZoffset;
646 if ( $tz === false ) {
647 $tz = $wgUser->getOption( 'timecorrection' );
650 $data = explode( '|', $tz, 3 );
652 if ( $data[0] == 'ZoneInfo' ) {
653 if ( function_exists( 'timezone_open' ) && @timezone_open( $data[2] ) !== false ) {
654 $date = date_create( $ts, timezone_open( 'UTC' ) );
655 date_timezone_set( $date, timezone_open( $data[2] ) );
656 $date = date_format( $date, 'YmdHis' );
657 return $date;
659 # Unrecognized timezone, default to 'Offset' with the stored offset.
660 $data[0] = 'Offset';
663 $minDiff = 0;
664 if ( $data[0] == 'System' || $tz == '' ) {
665 #  Global offset in minutes.
666 if ( isset( $wgLocalTZoffset ) ) {
667 $minDiff = $wgLocalTZoffset;
669 } else if ( $data[0] == 'Offset' ) {
670 $minDiff = intval( $data[1] );
671 } else {
672 $data = explode( ':', $tz );
673 if ( count( $data ) == 2 ) {
674 $data[0] = intval( $data[0] );
675 $data[1] = intval( $data[1] );
676 $minDiff = abs( $data[0] ) * 60 + $data[1];
677 if ( $data[0] < 0 ) {
678 $minDiff = -$minDiff;
680 } else {
681 $minDiff = intval( $data[0] ) * 60;
685 # No difference ? Return time unchanged
686 if ( 0 == $minDiff ) {
687 return $ts;
690 wfSuppressWarnings(); // E_STRICT system time bitching
691 # Generate an adjusted date; take advantage of the fact that mktime
692 # will normalize out-of-range values so we don't have to split $minDiff
693 # into hours and minutes.
694 $t = mktime( (
695 (int)substr( $ts, 8, 2 ) ), # Hours
696 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
697 (int)substr( $ts, 12, 2 ), # Seconds
698 (int)substr( $ts, 4, 2 ), # Month
699 (int)substr( $ts, 6, 2 ), # Day
700 (int)substr( $ts, 0, 4 ) ); # Year
702 $date = date( 'YmdHis', $t );
703 wfRestoreWarnings();
705 return $date;
709 * This is a workalike of PHP's date() function, but with better
710 * internationalisation, a reduced set of format characters, and a better
711 * escaping format.
713 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
714 * PHP manual for definitions. There are a number of extensions, which
715 * start with "x":
717 * xn Do not translate digits of the next numeric format character
718 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
719 * xr Use roman numerals for the next numeric format character
720 * xh Use hebrew numerals for the next numeric format character
721 * xx Literal x
722 * xg Genitive month name
724 * xij j (day number) in Iranian calendar
725 * xiF F (month name) in Iranian calendar
726 * xin n (month number) in Iranian calendar
727 * xiY Y (full year) in Iranian calendar
729 * xjj j (day number) in Hebrew calendar
730 * xjF F (month name) in Hebrew calendar
731 * xjt t (days in month) in Hebrew calendar
732 * xjx xg (genitive month name) in Hebrew calendar
733 * xjn n (month number) in Hebrew calendar
734 * xjY Y (full year) in Hebrew calendar
736 * xmj j (day number) in Hijri calendar
737 * xmF F (month name) in Hijri calendar
738 * xmn n (month number) in Hijri calendar
739 * xmY Y (full year) in Hijri calendar
741 * xkY Y (full year) in Thai solar calendar. Months and days are
742 * identical to the Gregorian calendar
743 * xoY Y (full year) in Minguo calendar or Juche year.
744 * Months and days are identical to the
745 * Gregorian calendar
746 * xtY Y (full year) in Japanese nengo. Months and days are
747 * identical to the Gregorian calendar
749 * Characters enclosed in double quotes will be considered literal (with
750 * the quotes themselves removed). Unmatched quotes will be considered
751 * literal quotes. Example:
753 * "The month is" F => The month is January
754 * i's" => 20'11"
756 * Backslash escaping is also supported.
758 * Input timestamp is assumed to be pre-normalized to the desired local
759 * time zone, if any.
761 * @param $format String
762 * @param $ts String: 14-character timestamp
763 * YYYYMMDDHHMMSS
764 * 01234567890123
765 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
767 function sprintfDate( $format, $ts ) {
768 $s = '';
769 $raw = false;
770 $roman = false;
771 $hebrewNum = false;
772 $unix = false;
773 $rawToggle = false;
774 $iranian = false;
775 $hebrew = false;
776 $hijri = false;
777 $thai = false;
778 $minguo = false;
779 $tenno = false;
780 for ( $p = 0; $p < strlen( $format ); $p++ ) {
781 $num = false;
782 $code = $format[$p];
783 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
784 $code .= $format[++$p];
787 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
788 $code .= $format[++$p];
791 switch ( $code ) {
792 case 'xx':
793 $s .= 'x';
794 break;
795 case 'xn':
796 $raw = true;
797 break;
798 case 'xN':
799 $rawToggle = !$rawToggle;
800 break;
801 case 'xr':
802 $roman = true;
803 break;
804 case 'xh':
805 $hebrewNum = true;
806 break;
807 case 'xg':
808 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
809 break;
810 case 'xjx':
811 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
812 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
813 break;
814 case 'd':
815 $num = substr( $ts, 6, 2 );
816 break;
817 case 'D':
818 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
819 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
820 break;
821 case 'j':
822 $num = intval( substr( $ts, 6, 2 ) );
823 break;
824 case 'xij':
825 if ( !$iranian ) {
826 $iranian = self::tsToIranian( $ts );
828 $num = $iranian[2];
829 break;
830 case 'xmj':
831 if ( !$hijri ) {
832 $hijri = self::tsToHijri( $ts );
834 $num = $hijri[2];
835 break;
836 case 'xjj':
837 if ( !$hebrew ) {
838 $hebrew = self::tsToHebrew( $ts );
840 $num = $hebrew[2];
841 break;
842 case 'l':
843 if ( !$unix ) {
844 $unix = wfTimestamp( TS_UNIX, $ts );
846 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
847 break;
848 case 'N':
849 if ( !$unix ) {
850 $unix = wfTimestamp( TS_UNIX, $ts );
852 $w = gmdate( 'w', $unix );
853 $num = $w ? $w : 7;
854 break;
855 case 'w':
856 if ( !$unix ) {
857 $unix = wfTimestamp( TS_UNIX, $ts );
859 $num = gmdate( 'w', $unix );
860 break;
861 case 'z':
862 if ( !$unix ) {
863 $unix = wfTimestamp( TS_UNIX, $ts );
865 $num = gmdate( 'z', $unix );
866 break;
867 case 'W':
868 if ( !$unix ) {
869 $unix = wfTimestamp( TS_UNIX, $ts );
871 $num = gmdate( 'W', $unix );
872 break;
873 case 'F':
874 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
875 break;
876 case 'xiF':
877 if ( !$iranian ) {
878 $iranian = self::tsToIranian( $ts );
880 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
881 break;
882 case 'xmF':
883 if ( !$hijri ) {
884 $hijri = self::tsToHijri( $ts );
886 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
887 break;
888 case 'xjF':
889 if ( !$hebrew ) {
890 $hebrew = self::tsToHebrew( $ts );
892 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
893 break;
894 case 'm':
895 $num = substr( $ts, 4, 2 );
896 break;
897 case 'M':
898 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
899 break;
900 case 'n':
901 $num = intval( substr( $ts, 4, 2 ) );
902 break;
903 case 'xin':
904 if ( !$iranian ) {
905 $iranian = self::tsToIranian( $ts );
907 $num = $iranian[1];
908 break;
909 case 'xmn':
910 if ( !$hijri ) {
911 $hijri = self::tsToHijri ( $ts );
913 $num = $hijri[1];
914 break;
915 case 'xjn':
916 if ( !$hebrew ) {
917 $hebrew = self::tsToHebrew( $ts );
919 $num = $hebrew[1];
920 break;
921 case 't':
922 if ( !$unix ) {
923 $unix = wfTimestamp( TS_UNIX, $ts );
925 $num = gmdate( 't', $unix );
926 break;
927 case 'xjt':
928 if ( !$hebrew ) {
929 $hebrew = self::tsToHebrew( $ts );
931 $num = $hebrew[3];
932 break;
933 case 'L':
934 if ( !$unix ) {
935 $unix = wfTimestamp( TS_UNIX, $ts );
937 $num = gmdate( 'L', $unix );
938 break;
939 case 'o':
940 if ( !$unix ) {
941 $unix = wfTimestamp( TS_UNIX, $ts );
943 $num = date( 'o', $unix );
944 break;
945 case 'Y':
946 $num = substr( $ts, 0, 4 );
947 break;
948 case 'xiY':
949 if ( !$iranian ) {
950 $iranian = self::tsToIranian( $ts );
952 $num = $iranian[0];
953 break;
954 case 'xmY':
955 if ( !$hijri ) {
956 $hijri = self::tsToHijri( $ts );
958 $num = $hijri[0];
959 break;
960 case 'xjY':
961 if ( !$hebrew ) {
962 $hebrew = self::tsToHebrew( $ts );
964 $num = $hebrew[0];
965 break;
966 case 'xkY':
967 if ( !$thai ) {
968 $thai = self::tsToYear( $ts, 'thai' );
970 $num = $thai[0];
971 break;
972 case 'xoY':
973 if ( !$minguo ) {
974 $minguo = self::tsToYear( $ts, 'minguo' );
976 $num = $minguo[0];
977 break;
978 case 'xtY':
979 if ( !$tenno ) {
980 $tenno = self::tsToYear( $ts, 'tenno' );
982 $num = $tenno[0];
983 break;
984 case 'y':
985 $num = substr( $ts, 2, 2 );
986 break;
987 case 'a':
988 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
989 break;
990 case 'A':
991 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
992 break;
993 case 'g':
994 $h = substr( $ts, 8, 2 );
995 $num = $h % 12 ? $h % 12 : 12;
996 break;
997 case 'G':
998 $num = intval( substr( $ts, 8, 2 ) );
999 break;
1000 case 'h':
1001 $h = substr( $ts, 8, 2 );
1002 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1003 break;
1004 case 'H':
1005 $num = substr( $ts, 8, 2 );
1006 break;
1007 case 'i':
1008 $num = substr( $ts, 10, 2 );
1009 break;
1010 case 's':
1011 $num = substr( $ts, 12, 2 );
1012 break;
1013 case 'c':
1014 if ( !$unix ) {
1015 $unix = wfTimestamp( TS_UNIX, $ts );
1017 $s .= gmdate( 'c', $unix );
1018 break;
1019 case 'r':
1020 if ( !$unix ) {
1021 $unix = wfTimestamp( TS_UNIX, $ts );
1023 $s .= gmdate( 'r', $unix );
1024 break;
1025 case 'U':
1026 if ( !$unix ) {
1027 $unix = wfTimestamp( TS_UNIX, $ts );
1029 $num = $unix;
1030 break;
1031 case '\\':
1032 # Backslash escaping
1033 if ( $p < strlen( $format ) - 1 ) {
1034 $s .= $format[++$p];
1035 } else {
1036 $s .= '\\';
1038 break;
1039 case '"':
1040 # Quoted literal
1041 if ( $p < strlen( $format ) - 1 ) {
1042 $endQuote = strpos( $format, '"', $p + 1 );
1043 if ( $endQuote === false ) {
1044 # No terminating quote, assume literal "
1045 $s .= '"';
1046 } else {
1047 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1048 $p = $endQuote;
1050 } else {
1051 # Quote at end of string, assume literal "
1052 $s .= '"';
1054 break;
1055 default:
1056 $s .= $format[$p];
1058 if ( $num !== false ) {
1059 if ( $rawToggle || $raw ) {
1060 $s .= $num;
1061 $raw = false;
1062 } elseif ( $roman ) {
1063 $s .= self::romanNumeral( $num );
1064 $roman = false;
1065 } elseif ( $hebrewNum ) {
1066 $s .= self::hebrewNumeral( $num );
1067 $hebrewNum = false;
1068 } else {
1069 $s .= $this->formatNum( $num, true );
1073 return $s;
1076 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1077 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1079 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1080 * Gregorian dates to Iranian dates. Originally written in C, it
1081 * is released under the terms of GNU Lesser General Public
1082 * License. Conversion to PHP was performed by Niklas Laxström.
1084 * Link: http://www.farsiweb.info/jalali/jalali.c
1086 private static function tsToIranian( $ts ) {
1087 $gy = substr( $ts, 0, 4 ) -1600;
1088 $gm = substr( $ts, 4, 2 ) -1;
1089 $gd = (int)substr( $ts, 6, 2 ) -1;
1091 # Days passed from the beginning (including leap years)
1092 $gDayNo = 365 * $gy
1093 + floor( ( $gy + 3 ) / 4 )
1094 - floor( ( $gy + 99 ) / 100 )
1095 + floor( ( $gy + 399 ) / 400 );
1098 // Add days of the past months of this year
1099 for ( $i = 0; $i < $gm; $i++ ) {
1100 $gDayNo += self::$GREG_DAYS[$i];
1103 // Leap years
1104 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1105 $gDayNo++;
1108 // Days passed in current month
1109 $gDayNo += $gd;
1111 $jDayNo = $gDayNo - 79;
1113 $jNp = floor( $jDayNo / 12053 );
1114 $jDayNo %= 12053;
1116 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1117 $jDayNo %= 1461;
1119 if ( $jDayNo >= 366 ) {
1120 $jy += floor( ( $jDayNo - 1 ) / 365 );
1121 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1124 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1125 $jDayNo -= self::$IRANIAN_DAYS[$i];
1128 $jm = $i + 1;
1129 $jd = $jDayNo + 1;
1131 return array( $jy, $jm, $jd );
1135 * Converting Gregorian dates to Hijri dates.
1137 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1139 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1141 private static function tsToHijri( $ts ) {
1142 $year = substr( $ts, 0, 4 );
1143 $month = substr( $ts, 4, 2 );
1144 $day = substr( $ts, 6, 2 );
1146 $zyr = $year;
1147 $zd = $day;
1148 $zm = $month;
1149 $zy = $zyr;
1151 if (
1152 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1153 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1156 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1157 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1158 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1159 $zd - 32075;
1160 } else {
1161 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1162 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1165 $zl = $zjd -1948440 + 10632;
1166 $zn = (int)( ( $zl - 1 ) / 10631 );
1167 $zl = $zl - 10631 * $zn + 354;
1168 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1169 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1170 $zm = (int)( ( 24 * $zl ) / 709 );
1171 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1172 $zy = 30 * $zn + $zj - 30;
1174 return array( $zy, $zm, $zd );
1178 * Converting Gregorian dates to Hebrew dates.
1180 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1181 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1182 * to translate the relevant functions into PHP and release them under
1183 * GNU GPL.
1185 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1186 * and Adar II is 14. In a non-leap year, Adar is 6.
1188 private static function tsToHebrew( $ts ) {
1189 # Parse date
1190 $year = substr( $ts, 0, 4 );
1191 $month = substr( $ts, 4, 2 );
1192 $day = substr( $ts, 6, 2 );
1194 # Calculate Hebrew year
1195 $hebrewYear = $year + 3760;
1197 # Month number when September = 1, August = 12
1198 $month += 4;
1199 if ( $month > 12 ) {
1200 # Next year
1201 $month -= 12;
1202 $year++;
1203 $hebrewYear++;
1206 # Calculate day of year from 1 September
1207 $dayOfYear = $day;
1208 for ( $i = 1; $i < $month; $i++ ) {
1209 if ( $i == 6 ) {
1210 # February
1211 $dayOfYear += 28;
1212 # Check if the year is leap
1213 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1214 $dayOfYear++;
1216 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1217 $dayOfYear += 30;
1218 } else {
1219 $dayOfYear += 31;
1223 # Calculate the start of the Hebrew year
1224 $start = self::hebrewYearStart( $hebrewYear );
1226 # Calculate next year's start
1227 if ( $dayOfYear <= $start ) {
1228 # Day is before the start of the year - it is the previous year
1229 # Next year's start
1230 $nextStart = $start;
1231 # Previous year
1232 $year--;
1233 $hebrewYear--;
1234 # Add days since previous year's 1 September
1235 $dayOfYear += 365;
1236 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1237 # Leap year
1238 $dayOfYear++;
1240 # Start of the new (previous) year
1241 $start = self::hebrewYearStart( $hebrewYear );
1242 } else {
1243 # Next year's start
1244 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1247 # Calculate Hebrew day of year
1248 $hebrewDayOfYear = $dayOfYear - $start;
1250 # Difference between year's days
1251 $diff = $nextStart - $start;
1252 # Add 12 (or 13 for leap years) days to ignore the difference between
1253 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1254 # difference is only about the year type
1255 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1256 $diff += 13;
1257 } else {
1258 $diff += 12;
1261 # Check the year pattern, and is leap year
1262 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1263 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1264 # and non-leap years
1265 $yearPattern = $diff % 30;
1266 # Check if leap year
1267 $isLeap = $diff >= 30;
1269 # Calculate day in the month from number of day in the Hebrew year
1270 # Don't check Adar - if the day is not in Adar, we will stop before;
1271 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1272 $hebrewDay = $hebrewDayOfYear;
1273 $hebrewMonth = 1;
1274 $days = 0;
1275 while ( $hebrewMonth <= 12 ) {
1276 # Calculate days in this month
1277 if ( $isLeap && $hebrewMonth == 6 ) {
1278 # Adar in a leap year
1279 if ( $isLeap ) {
1280 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1281 $days = 30;
1282 if ( $hebrewDay <= $days ) {
1283 # Day in Adar I
1284 $hebrewMonth = 13;
1285 } else {
1286 # Subtract the days of Adar I
1287 $hebrewDay -= $days;
1288 # Try Adar II
1289 $days = 29;
1290 if ( $hebrewDay <= $days ) {
1291 # Day in Adar II
1292 $hebrewMonth = 14;
1296 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1297 # Cheshvan in a complete year (otherwise as the rule below)
1298 $days = 30;
1299 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1300 # Kislev in an incomplete year (otherwise as the rule below)
1301 $days = 29;
1302 } else {
1303 # Odd months have 30 days, even have 29
1304 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1306 if ( $hebrewDay <= $days ) {
1307 # In the current month
1308 break;
1309 } else {
1310 # Subtract the days of the current month
1311 $hebrewDay -= $days;
1312 # Try in the next month
1313 $hebrewMonth++;
1317 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1321 * This calculates the Hebrew year start, as days since 1 September.
1322 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1323 * Used for Hebrew date.
1325 private static function hebrewYearStart( $year ) {
1326 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1327 $b = intval( ( $year - 1 ) % 4 );
1328 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1329 if ( $m < 0 ) {
1330 $m--;
1332 $Mar = intval( $m );
1333 if ( $m < 0 ) {
1334 $m++;
1336 $m -= $Mar;
1338 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1339 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1340 $Mar++;
1341 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1342 $Mar += 2;
1343 } else if ( $c == 2 || $c == 4 || $c == 6 ) {
1344 $Mar++;
1347 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1348 return $Mar;
1352 * Algorithm to convert Gregorian dates to Thai solar dates,
1353 * Minguo dates or Minguo dates.
1355 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1356 * http://en.wikipedia.org/wiki/Minguo_calendar
1357 * http://en.wikipedia.org/wiki/Japanese_era_name
1359 * @param $ts String: 14-character timestamp
1360 * @param $cName String: calender name
1361 * @return Array: converted year, month, day
1363 private static function tsToYear( $ts, $cName ) {
1364 $gy = substr( $ts, 0, 4 );
1365 $gm = substr( $ts, 4, 2 );
1366 $gd = substr( $ts, 6, 2 );
1368 if ( !strcmp( $cName, 'thai' ) ) {
1369 # Thai solar dates
1370 # Add 543 years to the Gregorian calendar
1371 # Months and days are identical
1372 $gy_offset = $gy + 543;
1373 } else if ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1374 # Minguo dates
1375 # Deduct 1911 years from the Gregorian calendar
1376 # Months and days are identical
1377 $gy_offset = $gy - 1911;
1378 } else if ( !strcmp( $cName, 'tenno' ) ) {
1379 # Nengō dates up to Meiji period
1380 # Deduct years from the Gregorian calendar
1381 # depending on the nengo periods
1382 # Months and days are identical
1383 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1384 # Meiji period
1385 $gy_gannen = $gy - 1868 + 1;
1386 $gy_offset = $gy_gannen;
1387 if ( $gy_gannen == 1 ) {
1388 $gy_offset = '元';
1390 $gy_offset = '明治' . $gy_offset;
1391 } else if (
1392 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1393 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1394 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1395 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1396 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1399 # Taishō period
1400 $gy_gannen = $gy - 1912 + 1;
1401 $gy_offset = $gy_gannen;
1402 if ( $gy_gannen == 1 ) {
1403 $gy_offset = '元';
1405 $gy_offset = '大正' . $gy_offset;
1406 } else if (
1407 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1408 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1409 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1412 # Shōwa period
1413 $gy_gannen = $gy - 1926 + 1;
1414 $gy_offset = $gy_gannen;
1415 if ( $gy_gannen == 1 ) {
1416 $gy_offset = '元';
1418 $gy_offset = '昭和' . $gy_offset;
1419 } else {
1420 # Heisei period
1421 $gy_gannen = $gy - 1989 + 1;
1422 $gy_offset = $gy_gannen;
1423 if ( $gy_gannen == 1 ) {
1424 $gy_offset = '元';
1426 $gy_offset = '平成' . $gy_offset;
1428 } else {
1429 $gy_offset = $gy;
1432 return array( $gy_offset, $gm, $gd );
1436 * Roman number formatting up to 3000
1438 static function romanNumeral( $num ) {
1439 static $table = array(
1440 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1441 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1442 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1443 array( '', 'M', 'MM', 'MMM' )
1446 $num = intval( $num );
1447 if ( $num > 3000 || $num <= 0 ) {
1448 return $num;
1451 $s = '';
1452 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1453 if ( $num >= $pow10 ) {
1454 $s .= $table[$i][floor( $num / $pow10 )];
1456 $num = $num % $pow10;
1458 return $s;
1462 * Hebrew Gematria number formatting up to 9999
1464 static function hebrewNumeral( $num ) {
1465 static $table = array(
1466 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1467 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1468 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1469 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1472 $num = intval( $num );
1473 if ( $num > 9999 || $num <= 0 ) {
1474 return $num;
1477 $s = '';
1478 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1479 if ( $num >= $pow10 ) {
1480 if ( $num == 15 || $num == 16 ) {
1481 $s .= $table[0][9] . $table[0][$num - 9];
1482 $num = 0;
1483 } else {
1484 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1485 if ( $pow10 == 1000 ) {
1486 $s .= "'";
1490 $num = $num % $pow10;
1492 if ( strlen( $s ) == 2 ) {
1493 $str = $s . "'";
1494 } else {
1495 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1496 $str .= substr( $s, strlen( $s ) - 2, 2 );
1498 $start = substr( $str, 0, strlen( $str ) - 2 );
1499 $end = substr( $str, strlen( $str ) - 2 );
1500 switch( $end ) {
1501 case 'כ':
1502 $str = $start . 'ך';
1503 break;
1504 case 'מ':
1505 $str = $start . 'ם';
1506 break;
1507 case 'נ':
1508 $str = $start . 'ן';
1509 break;
1510 case 'פ':
1511 $str = $start . 'ף';
1512 break;
1513 case 'צ':
1514 $str = $start . 'ץ';
1515 break;
1517 return $str;
1521 * This is meant to be used by time(), date(), and timeanddate() to get
1522 * the date preference they're supposed to use, it should be used in
1523 * all children.
1525 *<code>
1526 * function timeanddate([...], $format = true) {
1527 * $datePreference = $this->dateFormat($format);
1528 * [...]
1530 *</code>
1532 * @param $usePrefs Mixed: if true, the user's preference is used
1533 * if false, the site/language default is used
1534 * if int/string, assumed to be a format.
1535 * @return string
1537 function dateFormat( $usePrefs = true ) {
1538 global $wgUser;
1540 if ( is_bool( $usePrefs ) ) {
1541 if ( $usePrefs ) {
1542 $datePreference = $wgUser->getDatePreference();
1543 } else {
1544 $datePreference = (string)User::getDefaultOption( 'date' );
1546 } else {
1547 $datePreference = (string)$usePrefs;
1550 // return int
1551 if ( $datePreference == '' ) {
1552 return 'default';
1555 return $datePreference;
1559 * Get a format string for a given type and preference
1560 * @param $type May be date, time or both
1561 * @param $pref The format name as it appears in Messages*.php
1563 function getDateFormatString( $type, $pref ) {
1564 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1565 if ( $pref == 'default' ) {
1566 $pref = $this->getDefaultDateFormat();
1567 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1568 } else {
1569 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1570 if ( is_null( $df ) ) {
1571 $pref = $this->getDefaultDateFormat();
1572 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1575 $this->dateFormatStrings[$type][$pref] = $df;
1577 return $this->dateFormatStrings[$type][$pref];
1581 * @param $ts Mixed: the time format which needs to be turned into a
1582 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1583 * @param $adj Bool: whether to adjust the time output according to the
1584 * user configured offset ($timecorrection)
1585 * @param $format Mixed: true to use user's date format preference
1586 * @param $timecorrection String: the time offset as returned by
1587 * validateTimeZone() in Special:Preferences
1588 * @return string
1590 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1591 $ts = wfTimestamp( TS_MW, $ts );
1592 if ( $adj ) {
1593 $ts = $this->userAdjust( $ts, $timecorrection );
1595 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1596 return $this->sprintfDate( $df, $ts );
1600 * @param $ts Mixed: the time format which needs to be turned into a
1601 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1602 * @param $adj Bool: whether to adjust the time output according to the
1603 * user configured offset ($timecorrection)
1604 * @param $format Mixed: true to use user's date format preference
1605 * @param $timecorrection String: the time offset as returned by
1606 * validateTimeZone() in Special:Preferences
1607 * @return string
1609 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1610 $ts = wfTimestamp( TS_MW, $ts );
1611 if ( $adj ) {
1612 $ts = $this->userAdjust( $ts, $timecorrection );
1614 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1615 return $this->sprintfDate( $df, $ts );
1619 * @param $ts Mixed: the time format which needs to be turned into a
1620 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1621 * @param $adj Bool: whether to adjust the time output according to the
1622 * user configured offset ($timecorrection)
1623 * @param $format Mixed: what format to return, if it's false output the
1624 * default one (default true)
1625 * @param $timecorrection String: the time offset as returned by
1626 * validateTimeZone() in Special:Preferences
1627 * @return string
1629 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1630 $ts = wfTimestamp( TS_MW, $ts );
1631 if ( $adj ) {
1632 $ts = $this->userAdjust( $ts, $timecorrection );
1634 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1635 return $this->sprintfDate( $df, $ts );
1638 function getMessage( $key ) {
1639 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
1642 function getAllMessages() {
1643 return self::$dataCache->getItem( $this->mCode, 'messages' );
1646 function iconv( $in, $out, $string ) {
1647 # This is a wrapper for iconv in all languages except esperanto,
1648 # which does some nasty x-conversions beforehand
1650 # Even with //IGNORE iconv can whine about illegal characters in
1651 # *input* string. We just ignore those too.
1652 # REF: http://bugs.php.net/bug.php?id=37166
1653 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1654 wfSuppressWarnings();
1655 $text = iconv( $in, $out . '//IGNORE', $string );
1656 wfRestoreWarnings();
1657 return $text;
1660 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1661 function ucwordbreaksCallbackAscii( $matches ) {
1662 return $this->ucfirst( $matches[1] );
1665 function ucwordbreaksCallbackMB( $matches ) {
1666 return mb_strtoupper( $matches[0] );
1669 function ucCallback( $matches ) {
1670 list( $wikiUpperChars ) = self::getCaseMaps();
1671 return strtr( $matches[1], $wikiUpperChars );
1674 function lcCallback( $matches ) {
1675 list( , $wikiLowerChars ) = self::getCaseMaps();
1676 return strtr( $matches[1], $wikiLowerChars );
1679 function ucwordsCallbackMB( $matches ) {
1680 return mb_strtoupper( $matches[0] );
1683 function ucwordsCallbackWiki( $matches ) {
1684 list( $wikiUpperChars ) = self::getCaseMaps();
1685 return strtr( $matches[0], $wikiUpperChars );
1689 * Make a string's first character uppercase
1691 function ucfirst( $str ) {
1692 $o = ord( $str );
1693 if ( $o < 96 ) { // if already uppercase...
1694 return $str;
1695 } elseif ( $o < 128 ) {
1696 return ucfirst( $str ); // use PHP's ucfirst()
1697 } else {
1698 // fall back to more complex logic in case of multibyte strings
1699 return $this->uc( $str, true );
1704 * Convert a string to uppercase
1706 function uc( $str, $first = false ) {
1707 if ( function_exists( 'mb_strtoupper' ) ) {
1708 if ( $first ) {
1709 if ( $this->isMultibyte( $str ) ) {
1710 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1711 } else {
1712 return ucfirst( $str );
1714 } else {
1715 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1717 } else {
1718 if ( $this->isMultibyte( $str ) ) {
1719 $x = $first ? '^' : '';
1720 return preg_replace_callback(
1721 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1722 array( $this, 'ucCallback' ),
1723 $str
1725 } else {
1726 return $first ? ucfirst( $str ) : strtoupper( $str );
1731 function lcfirst( $str ) {
1732 $o = ord( $str );
1733 if ( !$o ) {
1734 return strval( $str );
1735 } elseif ( $o >= 128 ) {
1736 return $this->lc( $str, true );
1737 } elseif ( $o > 96 ) {
1738 return $str;
1739 } else {
1740 $str[0] = strtolower( $str[0] );
1741 return $str;
1745 function lc( $str, $first = false ) {
1746 if ( function_exists( 'mb_strtolower' ) ) {
1747 if ( $first ) {
1748 if ( $this->isMultibyte( $str ) ) {
1749 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1750 } else {
1751 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1753 } else {
1754 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1756 } else {
1757 if ( $this->isMultibyte( $str ) ) {
1758 $x = $first ? '^' : '';
1759 return preg_replace_callback(
1760 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1761 array( $this, 'lcCallback' ),
1762 $str
1764 } else {
1765 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1770 function isMultibyte( $str ) {
1771 return (bool)preg_match( '/[\x80-\xff]/', $str );
1774 function ucwords( $str ) {
1775 if ( $this->isMultibyte( $str ) ) {
1776 $str = $this->lc( $str );
1778 // regexp to find first letter in each word (i.e. after each space)
1779 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1781 // function to use to capitalize a single char
1782 if ( function_exists( 'mb_strtoupper' ) ) {
1783 return preg_replace_callback(
1784 $replaceRegexp,
1785 array( $this, 'ucwordsCallbackMB' ),
1786 $str
1788 } else {
1789 return preg_replace_callback(
1790 $replaceRegexp,
1791 array( $this, 'ucwordsCallbackWiki' ),
1792 $str
1795 } else {
1796 return ucwords( strtolower( $str ) );
1800 # capitalize words at word breaks
1801 function ucwordbreaks( $str ) {
1802 if ( $this->isMultibyte( $str ) ) {
1803 $str = $this->lc( $str );
1805 // since \b doesn't work for UTF-8, we explicitely define word break chars
1806 $breaks = "[ \-\(\)\}\{\.,\?!]";
1808 // find first letter after word break
1809 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1811 if ( function_exists( 'mb_strtoupper' ) ) {
1812 return preg_replace_callback(
1813 $replaceRegexp,
1814 array( $this, 'ucwordbreaksCallbackMB' ),
1815 $str
1817 } else {
1818 return preg_replace_callback(
1819 $replaceRegexp,
1820 array( $this, 'ucwordsCallbackWiki' ),
1821 $str
1824 } else {
1825 return preg_replace_callback(
1826 '/\b([\w\x80-\xff]+)\b/',
1827 array( $this, 'ucwordbreaksCallbackAscii' ),
1828 $str
1834 * Return a case-folded representation of $s
1836 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1837 * and $s2 are the same except for the case of their characters. It is not
1838 * necessary for the value returned to make sense when displayed.
1840 * Do *not* perform any other normalisation in this function. If a caller
1841 * uses this function when it should be using a more general normalisation
1842 * function, then fix the caller.
1844 function caseFold( $s ) {
1845 return $this->uc( $s );
1848 function checkTitleEncoding( $s ) {
1849 if ( is_array( $s ) ) {
1850 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1852 # Check for non-UTF-8 URLs
1853 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1854 if ( !$ishigh ) {
1855 return $s;
1858 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1859 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1860 if ( $isutf8 ) {
1861 return $s;
1864 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1867 function fallback8bitEncoding() {
1868 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
1872 * Most writing systems use whitespace to break up words.
1873 * Some languages such as Chinese don't conventionally do this,
1874 * which requires special handling when breaking up words for
1875 * searching etc.
1877 function hasWordBreaks() {
1878 return true;
1882 * Some languages such as Chinese require word segmentation,
1883 * Specify such segmentation when overridden in derived class.
1885 * @param $string String
1886 * @return String
1888 function segmentByWord( $string ) {
1889 return $string;
1893 * Some languages have special punctuation need to be normalized.
1894 * Make such changes here.
1896 * @param $string String
1897 * @return String
1899 function normalizeForSearch( $string ) {
1900 return self::convertDoubleWidth( $string );
1904 * convert double-width roman characters to single-width.
1905 * range: ff00-ff5f ~= 0020-007f
1907 protected static function convertDoubleWidth( $string ) {
1908 static $full = null;
1909 static $half = null;
1911 if ( $full === null ) {
1912 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1913 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1914 $full = str_split( $fullWidth, 3 );
1915 $half = str_split( $halfWidth );
1918 $string = str_replace( $full, $half, $string );
1919 return $string;
1922 protected static function insertSpace( $string, $pattern ) {
1923 $string = preg_replace( $pattern, " $1 ", $string );
1924 $string = preg_replace( '/ +/', ' ', $string );
1925 return $string;
1928 function convertForSearchResult( $termsArray ) {
1929 # some languages, e.g. Chinese, need to do a conversion
1930 # in order for search results to be displayed correctly
1931 return $termsArray;
1935 * Get the first character of a string.
1937 * @param $s string
1938 * @return string
1940 function firstChar( $s ) {
1941 $matches = array();
1942 preg_match(
1943 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1944 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1946 $matches
1949 if ( isset( $matches[1] ) ) {
1950 if ( strlen( $matches[1] ) != 3 ) {
1951 return $matches[1];
1954 // Break down Hangul syllables to grab the first jamo
1955 $code = utf8ToCodepoint( $matches[1] );
1956 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
1957 return $matches[1];
1958 } elseif ( $code < 0xb098 ) {
1959 return "\xe3\x84\xb1";
1960 } elseif ( $code < 0xb2e4 ) {
1961 return "\xe3\x84\xb4";
1962 } elseif ( $code < 0xb77c ) {
1963 return "\xe3\x84\xb7";
1964 } elseif ( $code < 0xb9c8 ) {
1965 return "\xe3\x84\xb9";
1966 } elseif ( $code < 0xbc14 ) {
1967 return "\xe3\x85\x81";
1968 } elseif ( $code < 0xc0ac ) {
1969 return "\xe3\x85\x82";
1970 } elseif ( $code < 0xc544 ) {
1971 return "\xe3\x85\x85";
1972 } elseif ( $code < 0xc790 ) {
1973 return "\xe3\x85\x87";
1974 } elseif ( $code < 0xcc28 ) {
1975 return "\xe3\x85\x88";
1976 } elseif ( $code < 0xce74 ) {
1977 return "\xe3\x85\x8a";
1978 } elseif ( $code < 0xd0c0 ) {
1979 return "\xe3\x85\x8b";
1980 } elseif ( $code < 0xd30c ) {
1981 return "\xe3\x85\x8c";
1982 } elseif ( $code < 0xd558 ) {
1983 return "\xe3\x85\x8d";
1984 } else {
1985 return "\xe3\x85\x8e";
1987 } else {
1988 return '';
1992 function initEncoding() {
1993 # Some languages may have an alternate char encoding option
1994 # (Esperanto X-coding, Japanese furigana conversion, etc)
1995 # If this language is used as the primary content language,
1996 # an override to the defaults can be set here on startup.
1999 function recodeForEdit( $s ) {
2000 # For some languages we'll want to explicitly specify
2001 # which characters make it into the edit box raw
2002 # or are converted in some way or another.
2003 # Note that if wgOutputEncoding is different from
2004 # wgInputEncoding, this text will be further converted
2005 # to wgOutputEncoding.
2006 global $wgEditEncoding;
2007 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2008 return $s;
2009 } else {
2010 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2014 function recodeInput( $s ) {
2015 # Take the previous into account.
2016 global $wgEditEncoding;
2017 if ( $wgEditEncoding != '' ) {
2018 $enc = $wgEditEncoding;
2019 } else {
2020 $enc = 'UTF-8';
2022 if ( $enc == 'UTF-8' ) {
2023 return $s;
2024 } else {
2025 return $this->iconv( $enc, 'UTF-8', $s );
2030 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2031 * also cleans up certain backwards-compatible sequences, converting them
2032 * to the modern Unicode equivalent.
2034 * This is language-specific for performance reasons only.
2036 function normalize( $s ) {
2037 global $wgAllUnicodeFixes;
2038 $s = UtfNormal::cleanUp( $s );
2039 if ( $wgAllUnicodeFixes ) {
2040 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2041 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2044 return $s;
2048 * Transform a string using serialized data stored in the given file (which
2049 * must be in the serialized subdirectory of $IP). The file contains pairs
2050 * mapping source characters to destination characters.
2052 * The data is cached in process memory. This will go faster if you have the
2053 * FastStringSearch extension.
2055 function transformUsingPairFile( $file, $string ) {
2056 if ( !isset( $this->transformData[$file] ) ) {
2057 $data = wfGetPrecompiledData( $file );
2058 if ( $data === false ) {
2059 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2061 $this->transformData[$file] = new ReplacementArray( $data );
2063 return $this->transformData[$file]->replace( $string );
2067 * For right-to-left language support
2069 * @return bool
2071 function isRTL() {
2072 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2076 * Return the correct HTML 'dir' attribute value for this language.
2077 * @return String
2079 function getDir() {
2080 return $this->isRTL() ? 'rtl' : 'ltr';
2084 * Return 'left' or 'right' as appropriate alignment for line-start
2085 * for this language's text direction.
2087 * Should be equivalent to CSS3 'start' text-align value....
2089 * @return String
2091 function alignStart() {
2092 return $this->isRTL() ? 'right' : 'left';
2096 * Return 'right' or 'left' as appropriate alignment for line-end
2097 * for this language's text direction.
2099 * Should be equivalent to CSS3 'end' text-align value....
2101 * @return String
2103 function alignEnd() {
2104 return $this->isRTL() ? 'left' : 'right';
2108 * A hidden direction mark (LRM or RLM), depending on the language direction
2110 * @return string
2112 function getDirMark() {
2113 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
2116 function capitalizeAllNouns() {
2117 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2121 * An arrow, depending on the language direction
2123 * @return string
2125 function getArrow() {
2126 return $this->isRTL() ? '←' : '→';
2130 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2132 * @return bool
2134 function linkPrefixExtension() {
2135 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2138 function getMagicWords() {
2139 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2142 protected function doMagicHook() {
2143 if ( $this->mMagicHookDone ) {
2144 return;
2146 $this->mMagicHookDone = true;
2147 wfProfileIn( 'LanguageGetMagic' );
2148 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2149 wfProfileOut( 'LanguageGetMagic' );
2152 # Fill a MagicWord object with data from here
2153 function getMagic( $mw ) {
2154 $this->doMagicHook();
2156 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2157 $rawEntry = $this->mMagicExtensions[$mw->mId];
2158 } else {
2159 $magicWords = $this->getMagicWords();
2160 if ( isset( $magicWords[$mw->mId] ) ) {
2161 $rawEntry = $magicWords[$mw->mId];
2162 } else {
2163 $rawEntry = false;
2167 if ( !is_array( $rawEntry ) ) {
2168 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2169 } else {
2170 $mw->mCaseSensitive = $rawEntry[0];
2171 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2176 * Add magic words to the extension array
2178 function addMagicWordsByLang( $newWords ) {
2179 $code = $this->getCode();
2180 $fallbackChain = array();
2181 while ( $code && !in_array( $code, $fallbackChain ) ) {
2182 $fallbackChain[] = $code;
2183 $code = self::getFallbackFor( $code );
2185 if ( !in_array( 'en', $fallbackChain ) ) {
2186 $fallbackChain[] = 'en';
2188 $fallbackChain = array_reverse( $fallbackChain );
2189 foreach ( $fallbackChain as $code ) {
2190 if ( isset( $newWords[$code] ) ) {
2191 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2197 * Get special page names, as an associative array
2198 * case folded alias => real name
2200 function getSpecialPageAliases() {
2201 // Cache aliases because it may be slow to load them
2202 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2203 // Initialise array
2204 $this->mExtendedSpecialPageAliases =
2205 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2206 wfRunHooks( 'LanguageGetSpecialPageAliases',
2207 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2210 return $this->mExtendedSpecialPageAliases;
2214 * Italic is unsuitable for some languages
2216 * @param $text String: the text to be emphasized.
2217 * @return string
2219 function emphasize( $text ) {
2220 return "<em>$text</em>";
2224 * Normally we output all numbers in plain en_US style, that is
2225 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2226 * point twohundredthirtyfive. However this is not sutable for all
2227 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2228 * Icelandic just want to use commas instead of dots, and dots instead
2229 * of commas like "293.291,235".
2231 * An example of this function being called:
2232 * <code>
2233 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2234 * </code>
2236 * See LanguageGu.php for the Gujarati implementation and
2237 * $separatorTransformTable on MessageIs.php for
2238 * the , => . and . => , implementation.
2240 * @todo check if it's viable to use localeconv() for the decimal
2241 * separator thing.
2242 * @param $number Mixed: the string to be formatted, should be an integer
2243 * or a floating point number.
2244 * @param $nocommafy Bool: set to true for special numbers like dates
2245 * @return string
2247 function formatNum( $number, $nocommafy = false ) {
2248 global $wgTranslateNumerals;
2249 if ( !$nocommafy ) {
2250 $number = $this->commafy( $number );
2251 $s = $this->separatorTransformTable();
2252 if ( $s ) {
2253 $number = strtr( $number, $s );
2257 if ( $wgTranslateNumerals ) {
2258 $s = $this->digitTransformTable();
2259 if ( $s ) {
2260 $number = strtr( $number, $s );
2264 return $number;
2267 function parseFormattedNumber( $number ) {
2268 $s = $this->digitTransformTable();
2269 if ( $s ) {
2270 $number = strtr( $number, array_flip( $s ) );
2273 $s = $this->separatorTransformTable();
2274 if ( $s ) {
2275 $number = strtr( $number, array_flip( $s ) );
2278 $number = strtr( $number, array( ',' => '' ) );
2279 return $number;
2283 * Adds commas to a given number
2285 * @param $_ mixed
2286 * @return string
2288 function commafy( $_ ) {
2289 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2292 function digitTransformTable() {
2293 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2296 function separatorTransformTable() {
2297 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2301 * Take a list of strings and build a locale-friendly comma-separated
2302 * list, using the local comma-separator message.
2303 * The last two strings are chained with an "and".
2305 * @param $l Array
2306 * @return string
2308 function listToText( $l ) {
2309 $s = '';
2310 $m = count( $l ) - 1;
2311 if ( $m == 1 ) {
2312 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2313 } else {
2314 for ( $i = $m; $i >= 0; $i-- ) {
2315 if ( $i == $m ) {
2316 $s = $l[$i];
2317 } else if ( $i == $m - 1 ) {
2318 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2319 } else {
2320 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2323 return $s;
2328 * Take a list of strings and build a locale-friendly comma-separated
2329 * list, using the local comma-separator message.
2330 * @param $list array of strings to put in a comma list
2331 * @return string
2333 function commaList( $list ) {
2334 return implode(
2335 $list,
2336 wfMsgExt(
2337 'comma-separator',
2338 array( 'parsemag', 'escapenoentities', 'language' => $this )
2344 * Take a list of strings and build a locale-friendly semicolon-separated
2345 * list, using the local semicolon-separator message.
2346 * @param $list array of strings to put in a semicolon list
2347 * @return string
2349 function semicolonList( $list ) {
2350 return implode(
2351 $list,
2352 wfMsgExt(
2353 'semicolon-separator',
2354 array( 'parsemag', 'escapenoentities', 'language' => $this )
2360 * Same as commaList, but separate it with the pipe instead.
2361 * @param $list array of strings to put in a pipe list
2362 * @return string
2364 function pipeList( $list ) {
2365 return implode(
2366 $list,
2367 wfMsgExt(
2368 'pipe-separator',
2369 array( 'escapenoentities', 'language' => $this )
2375 * Truncate a string to a specified length in bytes, appending an optional
2376 * string (e.g. for ellipses)
2378 * The database offers limited byte lengths for some columns in the database;
2379 * multi-byte character sets mean we need to ensure that only whole characters
2380 * are included, otherwise broken characters can be passed to the user
2382 * If $length is negative, the string will be truncated from the beginning
2384 * @param $string String to truncate
2385 * @param $length Int: maximum length (including ellipses)
2386 * @param $ellipsis String to append to the truncated text
2387 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2388 * $adjustLength was introduced in 1.18, before that behaved as if false.
2389 * @return string
2391 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2392 # Use the localized ellipsis character
2393 if ( $ellipsis == '...' ) {
2394 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2396 # Check if there is no need to truncate
2397 if ( $length == 0 ) {
2398 return $ellipsis; // convention
2399 } elseif ( strlen( $string ) <= abs( $length ) ) {
2400 return $string; // no need to truncate
2402 $stringOriginal = $string;
2403 # If ellipsis length is >= $length then we can't apply $adjustLength
2404 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2405 $string = $ellipsis; // this can be slightly unexpected
2406 # Otherwise, truncate and add ellipsis...
2407 } else {
2408 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
2409 if ( $length > 0 ) {
2410 $length -= $eLength;
2411 $string = substr( $string, 0, $length ); // xyz...
2412 $string = $this->removeBadCharLast( $string );
2413 $string = $string . $ellipsis;
2414 } else {
2415 $length += $eLength;
2416 $string = substr( $string, $length ); // ...xyz
2417 $string = $this->removeBadCharFirst( $string );
2418 $string = $ellipsis . $string;
2421 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2422 # This check is *not* redundant if $adjustLength, due to the single case where
2423 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2424 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2425 return $string;
2426 } else {
2427 return $stringOriginal;
2432 * Remove bytes that represent an incomplete Unicode character
2433 * at the end of string (e.g. bytes of the char are missing)
2435 * @param $string String
2436 * @return string
2438 protected function removeBadCharLast( $string ) {
2439 if ( $string != '' ) {
2440 $char = ord( $string[strlen( $string ) - 1] );
2441 $m = array();
2442 if ( $char >= 0xc0 ) {
2443 # We got the first byte only of a multibyte char; remove it.
2444 $string = substr( $string, 0, -1 );
2445 } elseif ( $char >= 0x80 &&
2446 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2447 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2449 # We chopped in the middle of a character; remove it
2450 $string = $m[1];
2453 return $string;
2457 * Remove bytes that represent an incomplete Unicode character
2458 * at the start of string (e.g. bytes of the char are missing)
2460 * @param $string String
2461 * @return string
2463 protected function removeBadCharFirst( $string ) {
2464 if ( $string != '' ) {
2465 $char = ord( $string[0] );
2466 if ( $char >= 0x80 && $char < 0xc0 ) {
2467 # We chopped in the middle of a character; remove the whole thing
2468 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2471 return $string;
2475 * Truncate a string of valid HTML to a specified length in bytes,
2476 * appending an optional string (e.g. for ellipses), and return valid HTML
2478 * This is only intended for styled/linked text, such as HTML with
2479 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2480 * Also, this will not detect things like "display:none" CSS.
2482 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2484 * @param string $text HTML string to truncate
2485 * @param int $length (zero/positive) Maximum length (including ellipses)
2486 * @param string $ellipsis String to append to the truncated text
2487 * @returns string
2489 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2490 # Use the localized ellipsis character
2491 if ( $ellipsis == '...' ) {
2492 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2494 # Check if there is clearly no need to truncate
2495 if ( $length <= 0 ) {
2496 return $ellipsis; // no text shown, nothing to format (convention)
2497 } elseif ( strlen( $text ) <= $length ) {
2498 return $text; // string short enough even *with* HTML (short-circuit)
2501 $displayLen = 0; // innerHTML legth so far
2502 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2503 $tagType = 0; // 0-open, 1-close
2504 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2505 $entityState = 0; // 0-not entity, 1-entity
2506 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2507 $openTags = array(); // open tag stack
2508 $pOpenTags = array();
2510 $textLen = strlen( $text );
2511 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2512 for ( $pos = 0; true; ++$pos ) {
2513 # Consider truncation once the display length has reached the maximim.
2514 # Check that we're not in the middle of a bracket/entity...
2515 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2516 if ( !$testingEllipsis ) {
2517 $testingEllipsis = true;
2518 # Save where we are; we will truncate here unless there turn out to
2519 # be so few remaining characters that truncation is not necessary.
2520 $pOpenTags = $openTags; // save state
2521 $pRet = $ret; // save state
2522 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2523 # String in fact does need truncation, the truncation point was OK.
2524 $openTags = $pOpenTags; // reload state
2525 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2526 $ret .= $ellipsis; // add ellipsis
2527 break;
2530 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2532 # Read the next char...
2533 $ch = $text[$pos];
2534 $lastCh = $pos ? $text[$pos - 1] : '';
2535 $ret .= $ch; // add to result string
2536 if ( $ch == '<' ) {
2537 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2538 $entityState = 0; // for bad HTML
2539 $bracketState = 1; // tag started (checking for backslash)
2540 } elseif ( $ch == '>' ) {
2541 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2542 $entityState = 0; // for bad HTML
2543 $bracketState = 0; // out of brackets
2544 } elseif ( $bracketState == 1 ) {
2545 if ( $ch == '/' ) {
2546 $tagType = 1; // close tag (e.g. "</span>")
2547 } else {
2548 $tagType = 0; // open tag (e.g. "<span>")
2549 $tag .= $ch;
2551 $bracketState = 2; // building tag name
2552 } elseif ( $bracketState == 2 ) {
2553 if ( $ch != ' ' ) {
2554 $tag .= $ch;
2555 } else {
2556 // Name found (e.g. "<a href=..."), add on tag attributes...
2557 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2559 } elseif ( $bracketState == 0 ) {
2560 if ( $entityState ) {
2561 if ( $ch == ';' ) {
2562 $entityState = 0;
2563 $displayLen++; // entity is one displayed char
2565 } else {
2566 if ( $ch == '&' ) {
2567 $entityState = 1; // entity found, (e.g. "&#160;")
2568 } else {
2569 $displayLen++; // this char is displayed
2570 // Add the next $max display text chars after this in one swoop...
2571 $max = ( $testingEllipsis ? $length : $neLength ) - $displayLen;
2572 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
2573 $displayLen += $skipped;
2574 $pos += $skipped;
2579 if ( $displayLen == 0 ) {
2580 return ''; // no text shown, nothing to format
2582 // Close the last tag if left unclosed by bad HTML
2583 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2584 while ( count( $openTags ) > 0 ) {
2585 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2587 return $ret;
2590 // truncateHtml() helper function
2591 // like strcspn() but adds the skipped chars to $ret
2592 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2593 if ( $len === null ) {
2594 $len = -1; // -1 means "no limit" for strcspn
2595 } elseif ( $len < 0 ) {
2596 $len = 0; // sanity
2598 $skipCount = 0;
2599 if ( $start < strlen( $text ) ) {
2600 $skipCount = strcspn( $text, $search, $start, $len );
2601 $ret .= substr( $text, $start, $skipCount );
2603 return $skipCount;
2607 * truncateHtml() helper function
2608 * (a) push or pop $tag from $openTags as needed
2609 * (b) clear $tag value
2610 * @param String &$tag Current HTML tag name we are looking at
2611 * @param int $tagType (0-open tag, 1-close tag)
2612 * @param char $lastCh Character before the '>' that ended this tag
2613 * @param array &$openTags Open tag stack (not accounting for $tag)
2615 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2616 $tag = ltrim( $tag );
2617 if ( $tag != '' ) {
2618 if ( $tagType == 0 && $lastCh != '/' ) {
2619 $openTags[] = $tag; // tag opened (didn't close itself)
2620 } else if ( $tagType == 1 ) {
2621 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2622 array_pop( $openTags ); // tag closed
2625 $tag = '';
2630 * Grammatical transformations, needed for inflected languages
2631 * Invoked by putting {{grammar:case|word}} in a message
2633 * @param $word string
2634 * @param $case string
2635 * @return string
2637 function convertGrammar( $word, $case ) {
2638 global $wgGrammarForms;
2639 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2640 return $wgGrammarForms[$this->getCode()][$case][$word];
2642 return $word;
2646 * Provides an alternative text depending on specified gender.
2647 * Usage {{gender:username|masculine|feminine|neutral}}.
2648 * username is optional, in which case the gender of current user is used,
2649 * but only in (some) interface messages; otherwise default gender is used.
2650 * If second or third parameter are not specified, masculine is used.
2651 * These details may be overriden per language.
2653 function gender( $gender, $forms ) {
2654 if ( !count( $forms ) ) {
2655 return '';
2657 $forms = $this->preConvertPlural( $forms, 2 );
2658 if ( $gender === 'male' ) {
2659 return $forms[0];
2661 if ( $gender === 'female' ) {
2662 return $forms[1];
2664 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2668 * Plural form transformations, needed for some languages.
2669 * For example, there are 3 form of plural in Russian and Polish,
2670 * depending on "count mod 10". See [[w:Plural]]
2671 * For English it is pretty simple.
2673 * Invoked by putting {{plural:count|wordform1|wordform2}}
2674 * or {{plural:count|wordform1|wordform2|wordform3}}
2676 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2678 * @param $count Integer: non-localized number
2679 * @param $forms Array: different plural forms
2680 * @return string Correct form of plural for $count in this language
2682 function convertPlural( $count, $forms ) {
2683 if ( !count( $forms ) ) {
2684 return '';
2686 $forms = $this->preConvertPlural( $forms, 2 );
2688 return ( $count == 1 ) ? $forms[0] : $forms[1];
2692 * Checks that convertPlural was given an array and pads it to requested
2693 * amound of forms by copying the last one.
2695 * @param $count Integer: How many forms should there be at least
2696 * @param $forms Array of forms given to convertPlural
2697 * @return array Padded array of forms or an exception if not an array
2699 protected function preConvertPlural( /* Array */ $forms, $count ) {
2700 while ( count( $forms ) < $count ) {
2701 $forms[] = $forms[count( $forms ) - 1];
2703 return $forms;
2707 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2708 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2709 * (which is an absolute timestamp).
2710 * @param $str String: the validated block duration in English
2711 * @return Somehow translated block duration
2712 * @see LanguageFi.php for example implementation
2714 function translateBlockExpiry( $str ) {
2715 foreach( SpecialBlock::getSuggestedDurations( $this ) as $show => $value ){
2716 if ( strcmp( $str, $value ) == 0 ) {
2717 return htmlspecialchars( trim( $show ) );
2720 return $str;
2724 * languages like Chinese need to be segmented in order for the diff
2725 * to be of any use
2727 * @param $text String
2728 * @return String
2730 function segmentForDiff( $text ) {
2731 return $text;
2735 * and unsegment to show the result
2737 * @param $text String
2738 * @return String
2740 function unsegmentForDiff( $text ) {
2741 return $text;
2744 # convert text to all supported variants
2745 function autoConvertToAllVariants( $text ) {
2746 return $this->mConverter->autoConvertToAllVariants( $text );
2749 # convert text to different variants of a language.
2750 function convert( $text ) {
2751 return $this->mConverter->convert( $text );
2754 # Convert a Title object to a string in the preferred variant
2755 function convertTitle( $title ) {
2756 return $this->mConverter->convertTitle( $title );
2759 # Check if this is a language with variants
2760 function hasVariants() {
2761 return sizeof( $this->getVariants() ) > 1;
2764 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2765 function armourMath( $text ) {
2766 return $this->mConverter->armourMath( $text );
2770 * Perform output conversion on a string, and encode for safe HTML output.
2771 * @param $text String text to be converted
2772 * @param $isTitle Bool whether this conversion is for the article title
2773 * @return string
2774 * @todo this should get integrated somewhere sane
2776 function convertHtml( $text, $isTitle = false ) {
2777 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2780 function convertCategoryKey( $key ) {
2781 return $this->mConverter->convertCategoryKey( $key );
2785 * Get the list of variants supported by this language
2786 * see sample implementation in LanguageZh.php
2788 * @return array an array of language codes
2790 function getVariants() {
2791 return $this->mConverter->getVariants();
2794 function getPreferredVariant() {
2795 return $this->mConverter->getPreferredVariant();
2798 function getDefaultVariant() {
2799 return $this->mConverter->getDefaultVariant();
2802 function getURLVariant() {
2803 return $this->mConverter->getURLVariant();
2807 * If a language supports multiple variants, it is
2808 * possible that non-existing link in one variant
2809 * actually exists in another variant. this function
2810 * tries to find it. See e.g. LanguageZh.php
2812 * @param $link String: the name of the link
2813 * @param $nt Mixed: the title object of the link
2814 * @param $ignoreOtherCond Boolean: to disable other conditions when
2815 * we need to transclude a template or update a category's link
2816 * @return null the input parameters may be modified upon return
2818 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2819 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
2823 * If a language supports multiple variants, converts text
2824 * into an array of all possible variants of the text:
2825 * 'variant' => text in that variant
2827 * @deprecated Use autoConvertToAllVariants()
2829 function convertLinkToAllVariants( $text ) {
2830 return $this->mConverter->convertLinkToAllVariants( $text );
2834 * returns language specific options used by User::getPageRenderHash()
2835 * for example, the preferred language variant
2837 * @return string
2839 function getExtraHashOptions() {
2840 return $this->mConverter->getExtraHashOptions();
2844 * For languages that support multiple variants, the title of an
2845 * article may be displayed differently in different variants. this
2846 * function returns the apporiate title defined in the body of the article.
2848 * @return string
2850 function getParsedTitle() {
2851 return $this->mConverter->getParsedTitle();
2855 * Enclose a string with the "no conversion" tag. This is used by
2856 * various functions in the Parser
2858 * @param $text String: text to be tagged for no conversion
2859 * @param $noParse
2860 * @return string the tagged text
2862 function markNoConversion( $text, $noParse = false ) {
2863 return $this->mConverter->markNoConversion( $text, $noParse );
2867 * A regular expression to match legal word-trailing characters
2868 * which should be merged onto a link of the form [[foo]]bar.
2870 * @return string
2872 function linkTrail() {
2873 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
2876 function getLangObj() {
2877 return $this;
2881 * Get the RFC 3066 code for this language object
2883 function getCode() {
2884 return $this->mCode;
2887 function setCode( $code ) {
2888 $this->mCode = $code;
2892 * Get the name of a file for a certain language code
2893 * @param $prefix string Prepend this to the filename
2894 * @param $code string Language code
2895 * @param $suffix string Append this to the filename
2896 * @return string $prefix . $mangledCode . $suffix
2898 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2899 // Protect against path traversal
2900 if ( !Language::isValidCode( $code )
2901 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
2903 throw new MWException( "Invalid language code \"$code\"" );
2906 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2910 * Get the language code from a file name. Inverse of getFileName()
2911 * @param $filename string $prefix . $languageCode . $suffix
2912 * @param $prefix string Prefix before the language code
2913 * @param $suffix string Suffix after the language code
2914 * @return Language code, or false if $prefix or $suffix isn't found
2916 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2917 $m = null;
2918 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2919 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2920 if ( !count( $m ) ) {
2921 return false;
2923 return str_replace( '_', '-', strtolower( $m[1] ) );
2926 static function getMessagesFileName( $code ) {
2927 global $IP;
2928 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2931 static function getClassFileName( $code ) {
2932 global $IP;
2933 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2937 * Get the fallback for a given language
2939 static function getFallbackFor( $code ) {
2940 if ( $code === 'en' ) {
2941 // Shortcut
2942 return false;
2943 } else {
2944 return self::getLocalisationCache()->getItem( $code, 'fallback' );
2949 * Get all messages for a given language
2950 * WARNING: this may take a long time
2952 static function getMessagesFor( $code ) {
2953 return self::getLocalisationCache()->getItem( $code, 'messages' );
2957 * Get a message for a given language
2959 static function getMessageFor( $key, $code ) {
2960 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2963 function fixVariableInNamespace( $talk ) {
2964 if ( strpos( $talk, '$1' ) === false ) {
2965 return $talk;
2968 global $wgMetaNamespace;
2969 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2971 # Allow grammar transformations
2972 # Allowing full message-style parsing would make simple requests
2973 # such as action=raw much more expensive than they need to be.
2974 # This will hopefully cover most cases.
2975 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2976 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2977 return str_replace( ' ', '_', $talk );
2980 function replaceGrammarInNamespace( $m ) {
2981 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2984 static function getCaseMaps() {
2985 static $wikiUpperChars, $wikiLowerChars;
2986 if ( isset( $wikiUpperChars ) ) {
2987 return array( $wikiUpperChars, $wikiLowerChars );
2990 wfProfileIn( __METHOD__ );
2991 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2992 if ( $arr === false ) {
2993 throw new MWException(
2994 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2996 $wikiUpperChars = $arr['wikiUpperChars'];
2997 $wikiLowerChars = $arr['wikiLowerChars'];
2998 wfProfileOut( __METHOD__ );
2999 return array( $wikiUpperChars, $wikiLowerChars );
3003 * Decode an expiry (block, protection, etc) which has come from the DB
3005 * @param $expiry String: Database expiry String
3006 * @param $format Bool|Int true to process using language functions, or TS_ constant
3007 * to return the expiry in a given timestamp
3008 * @return String
3010 public function formatExpiry( $expiry, $format = true ) {
3011 static $infinity, $infinityMsg;
3012 if( $infinity === null ){
3013 $infinityMsg = wfMessage( 'infiniteblock' );
3014 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3017 if ( $expiry == '' || $expiry == $infinity ) {
3018 return $format === true
3019 ? $infinityMsg
3020 : $infinity;
3021 } else {
3022 return $format === true
3023 ? $this->timeanddate( $expiry )
3024 : wfTimestamp( $format, $expiry );
3029 * @todo Document
3030 * @param $seconds String
3031 * @return string
3033 function formatTimePeriod( $seconds ) {
3034 if ( round( $seconds * 10 ) < 100 ) {
3035 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3036 } elseif ( round( $seconds ) < 60 ) {
3037 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3038 } elseif ( round( $seconds ) < 3600 ) {
3039 $minutes = floor( $seconds / 60 );
3040 $secondsPart = round( fmod( $seconds, 60 ) );
3041 if ( $secondsPart == 60 ) {
3042 $secondsPart = 0;
3043 $minutes++;
3045 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3046 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3047 } else {
3048 $hours = floor( $seconds / 3600 );
3049 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3050 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3051 if ( $secondsPart == 60 ) {
3052 $secondsPart = 0;
3053 $minutes++;
3055 if ( $minutes == 60 ) {
3056 $minutes = 0;
3057 $hours++;
3059 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3060 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3061 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3065 function formatBitrate( $bps ) {
3066 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3067 if ( $bps <= 0 ) {
3068 return $this->formatNum( $bps ) . $units[0];
3070 $unitIndex = floor( log10( $bps ) / 3 );
3071 $mantissa = $bps / pow( 1000, $unitIndex );
3072 if ( $mantissa < 10 ) {
3073 $mantissa = round( $mantissa, 1 );
3074 } else {
3075 $mantissa = round( $mantissa );
3077 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3081 * Format a size in bytes for output, using an appropriate
3082 * unit (B, KB, MB or GB) according to the magnitude in question
3084 * @param $size Size to format
3085 * @return string Plain text (not HTML)
3087 function formatSize( $size ) {
3088 // For small sizes no decimal places necessary
3089 $round = 0;
3090 if ( $size > 1024 ) {
3091 $size = $size / 1024;
3092 if ( $size > 1024 ) {
3093 $size = $size / 1024;
3094 // For MB and bigger two decimal places are smarter
3095 $round = 2;
3096 if ( $size > 1024 ) {
3097 $size = $size / 1024;
3098 $msg = 'size-gigabytes';
3099 } else {
3100 $msg = 'size-megabytes';
3102 } else {
3103 $msg = 'size-kilobytes';
3105 } else {
3106 $msg = 'size-bytes';
3108 $size = round( $size, $round );
3109 $text = $this->getMessageFromDB( $msg );
3110 return str_replace( '$1', $this->formatNum( $size ), $text );
3114 * Get the conversion rule title, if any.
3116 function getConvRuleTitle() {
3117 return $this->mConverter->getConvRuleTitle();