3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
33 function __construct( $langobj ) { $this->mLang
= $langobj; }
34 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
35 function convert( $t ) { return $t; }
36 function convertTitle( $t ) { return $t->getPrefixedText(); }
37 function getVariants() { return array( $this->mLang
->getCode() ); }
38 function getPreferredVariant() { return $this->mLang
->getCode(); }
39 function getDefaultVariant() { return $this->mLang
->getCode(); }
40 function getURLVariant() { return ''; }
41 function getConvRuleTitle() { return false; }
42 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
43 function getExtraHashOptions() { return ''; }
44 function getParsedTitle() { return ''; }
45 function markNoConversion( $text, $noParse = false ) { return $text; }
46 function convertCategoryKey( $key ) { return $key; }
47 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
48 function armourMath( $text ) { return $text; }
52 * Internationalisation code
56 var $mConverter, $mVariants, $mCode, $mLoaded = false;
57 var $mMagicExtensions = array(), $mMagicHookDone = false;
59 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
60 var $dateFormatStrings = array();
61 var $mExtendedSpecialPageAliases;
64 * ReplacementArray object caches
66 var $transformData = array();
69 * @var LocalisationCache
71 static public $dataCache;
73 static public $mLangObjCache = array();
75 static public $mWeekdayMsgs = array(
76 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
80 static public $mWeekdayAbbrevMsgs = array(
81 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
84 static public $mMonthMsgs = array(
85 'january', 'february', 'march', 'april', 'may_long', 'june',
86 'july', 'august', 'september', 'october', 'november',
89 static public $mMonthGenMsgs = array(
90 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
91 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
94 static public $mMonthAbbrevMsgs = array(
95 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
96 'sep', 'oct', 'nov', 'dec'
99 static public $mIranianCalendarMonthMsgs = array(
100 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
101 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
102 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
103 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
106 static public $mHebrewCalendarMonthMsgs = array(
107 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
108 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
109 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
110 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
111 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
114 static public $mHebrewCalendarMonthGenMsgs = array(
115 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
116 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
117 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
118 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
119 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
122 static public $mHijriCalendarMonthMsgs = array(
123 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
124 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
125 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
126 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
130 * Get a cached language object for a given language code
131 * @param $code String
134 static function factory( $code ) {
135 if ( !isset( self
::$mLangObjCache[$code] ) ) {
136 if ( count( self
::$mLangObjCache ) > 10 ) {
137 // Don't keep a billion objects around, that's stupid.
138 self
::$mLangObjCache = array();
140 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
142 return self
::$mLangObjCache[$code];
146 * Create a language object for a given language code
147 * @param $code String
150 protected static function newFromCode( $code ) {
151 // Protect against path traversal below
152 if ( !Language
::isValidCode( $code )
153 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
155 throw new MWException( "Invalid language code \"$code\"" );
158 if ( !Language
::isValidBuiltInCode( $code ) ) {
159 // It's not possible to customise this code with class files, so
160 // just return a Language object. This is to support uselang= hacks.
161 $lang = new Language
;
162 $lang->setCode( $code );
166 // Check if there is a language class for the code
167 $class = self
::classFromCode( $code );
168 self
::preloadLanguageClass( $class );
169 if ( MWInit
::classExists( $class ) ) {
174 // Keep trying the fallback list until we find an existing class
175 $fallbacks = Language
::getFallbacksFor( $code );
176 foreach ( $fallbacks as $fallbackCode ) {
177 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
178 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
181 $class = self
::classFromCode( $fallbackCode );
182 self
::preloadLanguageClass( $class );
183 if ( MWInit
::classExists( $class ) ) {
184 $lang = Language
::newFromCode( $fallbackCode );
185 $lang->setCode( $code );
190 throw new MWException( "Invalid fallback sequence for language '$code'" );
194 * Returns true if a language code string is of a valid form, whether or
195 * not it exists. This includes codes which are used solely for
196 * customisation via the MediaWiki namespace.
198 * @param $code string
202 public static function isValidCode( $code ) {
204 strcspn( $code, ":/\\\000" ) === strlen( $code )
205 && !preg_match( Title
::getTitleInvalidRegex(), $code );
209 * Returns true if a language code is of a valid form for the purposes of
210 * internal customisation of MediaWiki, via Messages*.php.
212 * @param $code string
217 public static function isValidBuiltInCode( $code ) {
218 return preg_match( '/^[a-z0-9-]+$/i', $code );
221 public static function classFromCode( $code ) {
222 if ( $code == 'en' ) {
225 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
229 public static function preloadLanguageClass( $class ) {
232 if ( $class === 'Language' ) {
236 if ( !defined( 'MW_COMPILED' ) ) {
237 // Preload base classes to work around APC/PHP5 bug
238 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
239 include_once( "$IP/languages/classes/$class.deps.php" );
241 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
242 include_once( "$IP/languages/classes/$class.php" );
248 * Get the LocalisationCache instance
250 * @return LocalisationCache
252 public static function getLocalisationCache() {
253 if ( is_null( self
::$dataCache ) ) {
254 global $wgLocalisationCacheConf;
255 $class = $wgLocalisationCacheConf['class'];
256 self
::$dataCache = new $class( $wgLocalisationCacheConf );
258 return self
::$dataCache;
261 function __construct() {
262 $this->mConverter
= new FakeConverter( $this );
263 // Set the code to the name of the descendant
264 if ( get_class( $this ) == 'Language' ) {
267 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
269 self
::getLocalisationCache();
273 * Reduce memory usage
275 function __destruct() {
276 foreach ( $this as $name => $value ) {
277 unset( $this->$name );
282 * Hook which will be called if this is the content language.
283 * Descendants can use this to register hook functions or modify globals
285 function initContLang() { }
288 * Same as getFallbacksFor for current language.
290 * @deprecated in 1.19
292 function getFallbackLanguageCode() {
293 wfDeprecated( __METHOD__
);
294 return self
::getFallbackFor( $this->mCode
);
301 function getFallbackLanguages() {
302 return self
::getFallbacksFor( $this->mCode
);
306 * Exports $wgBookstoreListEn
309 function getBookstoreList() {
310 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
316 function getNamespaces() {
317 if ( is_null( $this->namespaceNames
) ) {
318 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
320 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
321 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
323 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
325 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
326 if ( $wgMetaNamespaceTalk ) {
327 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
329 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
330 $this->namespaceNames
[NS_PROJECT_TALK
] =
331 $this->fixVariableInNamespace( $talk );
334 # Sometimes a language will be localised but not actually exist on this wiki.
335 foreach( $this->namespaceNames
as $key => $text ) {
336 if ( !isset( $validNamespaces[$key] ) ) {
337 unset( $this->namespaceNames
[$key] );
341 # The above mixing may leave namespaces out of canonical order.
342 # Re-order by namespace ID number...
343 ksort( $this->namespaceNames
);
345 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
347 return $this->namespaceNames
;
351 * A convenience function that returns the same thing as
352 * getNamespaces() except with the array values changed to ' '
353 * where it found '_', useful for producing output to be displayed
354 * e.g. in <select> forms.
358 function getFormattedNamespaces() {
359 $ns = $this->getNamespaces();
360 foreach ( $ns as $k => $v ) {
361 $ns[$k] = strtr( $v, '_', ' ' );
367 * Get a namespace value by key
369 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
370 * echo $mw_ns; // prints 'MediaWiki'
373 * @param $index Int: the array key of the namespace to return
374 * @return mixed, string if the namespace value exists, otherwise false
376 function getNsText( $index ) {
377 $ns = $this->getNamespaces();
378 return isset( $ns[$index] ) ?
$ns[$index] : false;
382 * A convenience function that returns the same thing as
383 * getNsText() except with '_' changed to ' ', useful for
386 * @param $index string
390 function getFormattedNsText( $index ) {
391 $ns = $this->getNsText( $index );
392 return strtr( $ns, '_', ' ' );
396 * Returns gender-dependent namespace alias if available.
397 * @param $index Int: namespace index
398 * @param $gender String: gender key (male, female... )
402 function getGenderNsText( $index, $gender ) {
403 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
404 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
408 * Whether this language makes distinguishes genders for example in
413 function needsGenderDistinction() {
414 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
415 return count( $aliases ) > 0;
419 * Get a namespace key by value, case insensitive.
420 * Only matches namespace names for the current language, not the
421 * canonical ones defined in Namespace.php.
423 * @param $text String
424 * @return mixed An integer if $text is a valid value otherwise false
426 function getLocalNsIndex( $text ) {
427 $lctext = $this->lc( $text );
428 $ids = $this->getNamespaceIds();
429 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
435 function getNamespaceAliases() {
436 if ( is_null( $this->namespaceAliases
) ) {
437 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
441 foreach ( $aliases as $name => $index ) {
442 if ( $index === NS_PROJECT_TALK
) {
443 unset( $aliases[$name] );
444 $name = $this->fixVariableInNamespace( $name );
445 $aliases[$name] = $index;
450 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
451 foreach ( $genders as $index => $forms ) {
452 foreach ( $forms as $alias ) {
453 $aliases[$alias] = $index;
457 $this->namespaceAliases
= $aliases;
459 return $this->namespaceAliases
;
465 function getNamespaceIds() {
466 if ( is_null( $this->mNamespaceIds
) ) {
467 global $wgNamespaceAliases;
468 # Put namespace names and aliases into a hashtable.
469 # If this is too slow, then we should arrange it so that it is done
470 # before caching. The catch is that at pre-cache time, the above
471 # class-specific fixup hasn't been done.
472 $this->mNamespaceIds
= array();
473 foreach ( $this->getNamespaces() as $index => $name ) {
474 $this->mNamespaceIds
[$this->lc( $name )] = $index;
476 foreach ( $this->getNamespaceAliases() as $name => $index ) {
477 $this->mNamespaceIds
[$this->lc( $name )] = $index;
479 if ( $wgNamespaceAliases ) {
480 foreach ( $wgNamespaceAliases as $name => $index ) {
481 $this->mNamespaceIds
[$this->lc( $name )] = $index;
485 return $this->mNamespaceIds
;
490 * Get a namespace key by value, case insensitive. Canonical namespace
491 * names override custom ones defined for the current language.
493 * @param $text String
494 * @return mixed An integer if $text is a valid value otherwise false
496 function getNsIndex( $text ) {
497 $lctext = $this->lc( $text );
498 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
501 $ids = $this->getNamespaceIds();
502 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
506 * short names for language variants used for language conversion links.
508 * @param $code String
511 function getVariantname( $code ) {
512 return $this->getMessageFromDB( "variantname-$code" );
516 * @param $name string
519 function specialPage( $name ) {
520 $aliases = $this->getSpecialPageAliases();
521 if ( isset( $aliases[$name][0] ) ) {
522 $name = $aliases[$name][0];
524 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
530 function getQuickbarSettings() {
532 $this->getMessage( 'qbsettings-none' ),
533 $this->getMessage( 'qbsettings-fixedleft' ),
534 $this->getMessage( 'qbsettings-fixedright' ),
535 $this->getMessage( 'qbsettings-floatingleft' ),
536 $this->getMessage( 'qbsettings-floatingright' ),
537 $this->getMessage( 'qbsettings-directionality' )
544 function getDatePreferences() {
545 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
551 function getDateFormats() {
552 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
556 * @return array|string
558 function getDefaultDateFormat() {
559 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
560 if ( $df === 'dmy or mdy' ) {
561 global $wgAmericanDates;
562 return $wgAmericanDates ?
'mdy' : 'dmy';
571 function getDatePreferenceMigrationMap() {
572 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
579 function getImageFile( $image ) {
580 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
586 function getExtraUserToggles() {
587 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
594 function getUserToggle( $tog ) {
595 return $this->getMessageFromDB( "tog-$tog" );
599 * Get language names, indexed by code.
600 * If $customisedOnly is true, only returns codes with a messages file
602 * @param $customisedOnly bool
606 public static function getLanguageNames( $customisedOnly = false ) {
607 global $wgExtraLanguageNames;
608 static $coreLanguageNames;
610 if ( $coreLanguageNames === null ) {
611 include( MWInit
::compiledPath( 'languages/Names.php' ) );
614 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
615 if ( !$customisedOnly ) {
621 $dir = opendir( "$IP/languages/messages" );
622 while ( false !== ( $file = readdir( $dir ) ) ) {
623 $code = self
::getCodeFromFileName( $file, 'Messages' );
624 if ( $code && isset( $allNames[$code] ) ) {
625 $names[$code] = $allNames[$code];
633 * Get translated language names. This is done on best effort and
634 * by default this is exactly the same as Language::getLanguageNames.
635 * The CLDR extension provides translated names.
636 * @param $code String Language code.
637 * @return Array language code => language name
640 public static function getTranslatedLanguageNames( $code ) {
642 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
644 foreach ( self
::getLanguageNames() as $code => $name ) {
645 if ( !isset( $names[$code] ) ) $names[$code] = $name;
652 * Get a message from the MediaWiki namespace.
654 * @param $msg String: message name
657 function getMessageFromDB( $msg ) {
658 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
662 * @param $code string
665 function getLanguageName( $code ) {
666 $names = self
::getLanguageNames();
667 if ( !array_key_exists( $code, $names ) ) {
670 return $names[$code];
677 function getMonthName( $key ) {
678 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
684 function getMonthNamesArray() {
685 $monthNames = array( '' );
686 for ( $i=1; $i < 13; $i++
) {
687 $monthNames[] = $this->getMonthName( $i );
696 function getMonthNameGen( $key ) {
697 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
704 function getMonthAbbreviation( $key ) {
705 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
711 function getMonthAbbreviationsArray() {
712 $monthNames = array( '' );
713 for ( $i=1; $i < 13; $i++
) {
714 $monthNames[] = $this->getMonthAbbreviation( $i );
723 function getWeekdayName( $key ) {
724 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
731 function getWeekdayAbbreviation( $key ) {
732 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
739 function getIranianCalendarMonthName( $key ) {
740 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
747 function getHebrewCalendarMonthName( $key ) {
748 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
755 function getHebrewCalendarMonthNameGen( $key ) {
756 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
763 function getHijriCalendarMonthName( $key ) {
764 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
768 * Used by date() and time() to adjust the time output.
770 * @param $ts Int the time in date('YmdHis') format
771 * @param $tz Mixed: adjust the time by this amount (default false, mean we
772 * get user timecorrection setting)
775 function userAdjust( $ts, $tz = false ) {
776 global $wgUser, $wgLocalTZoffset;
778 if ( $tz === false ) {
779 $tz = $wgUser->getOption( 'timecorrection' );
782 $data = explode( '|', $tz, 3 );
784 if ( $data[0] == 'ZoneInfo' ) {
785 wfSuppressWarnings();
786 $userTZ = timezone_open( $data[2] );
788 if ( $userTZ !== false ) {
789 $date = date_create( $ts, timezone_open( 'UTC' ) );
790 date_timezone_set( $date, $userTZ );
791 $date = date_format( $date, 'YmdHis' );
794 # Unrecognized timezone, default to 'Offset' with the stored offset.
799 if ( $data[0] == 'System' ||
$tz == '' ) {
800 # Global offset in minutes.
801 if ( isset( $wgLocalTZoffset ) ) {
802 $minDiff = $wgLocalTZoffset;
804 } elseif ( $data[0] == 'Offset' ) {
805 $minDiff = intval( $data[1] );
807 $data = explode( ':', $tz );
808 if ( count( $data ) == 2 ) {
809 $data[0] = intval( $data[0] );
810 $data[1] = intval( $data[1] );
811 $minDiff = abs( $data[0] ) * 60 +
$data[1];
812 if ( $data[0] < 0 ) {
813 $minDiff = -$minDiff;
816 $minDiff = intval( $data[0] ) * 60;
820 # No difference ? Return time unchanged
821 if ( 0 == $minDiff ) {
825 wfSuppressWarnings(); // E_STRICT system time bitching
826 # Generate an adjusted date; take advantage of the fact that mktime
827 # will normalize out-of-range values so we don't have to split $minDiff
828 # into hours and minutes.
830 (int)substr( $ts, 8, 2 ) ), # Hours
831 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
832 (int)substr( $ts, 12, 2 ), # Seconds
833 (int)substr( $ts, 4, 2 ), # Month
834 (int)substr( $ts, 6, 2 ), # Day
835 (int)substr( $ts, 0, 4 ) ); # Year
837 $date = date( 'YmdHis', $t );
844 * This is a workalike of PHP's date() function, but with better
845 * internationalisation, a reduced set of format characters, and a better
848 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
849 * PHP manual for definitions. There are a number of extensions, which
852 * xn Do not translate digits of the next numeric format character
853 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
854 * xr Use roman numerals for the next numeric format character
855 * xh Use hebrew numerals for the next numeric format character
857 * xg Genitive month name
859 * xij j (day number) in Iranian calendar
860 * xiF F (month name) in Iranian calendar
861 * xin n (month number) in Iranian calendar
862 * xiY Y (full year) in Iranian calendar
864 * xjj j (day number) in Hebrew calendar
865 * xjF F (month name) in Hebrew calendar
866 * xjt t (days in month) in Hebrew calendar
867 * xjx xg (genitive month name) in Hebrew calendar
868 * xjn n (month number) in Hebrew calendar
869 * xjY Y (full year) in Hebrew calendar
871 * xmj j (day number) in Hijri calendar
872 * xmF F (month name) in Hijri calendar
873 * xmn n (month number) in Hijri calendar
874 * xmY Y (full year) in Hijri calendar
876 * xkY Y (full year) in Thai solar calendar. Months and days are
877 * identical to the Gregorian calendar
878 * xoY Y (full year) in Minguo calendar or Juche year.
879 * Months and days are identical to the
881 * xtY Y (full year) in Japanese nengo. Months and days are
882 * identical to the Gregorian calendar
884 * Characters enclosed in double quotes will be considered literal (with
885 * the quotes themselves removed). Unmatched quotes will be considered
886 * literal quotes. Example:
888 * "The month is" F => The month is January
891 * Backslash escaping is also supported.
893 * Input timestamp is assumed to be pre-normalized to the desired local
896 * @param $format String
897 * @param $ts String: 14-character timestamp
900 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
904 function sprintfDate( $format, $ts ) {
917 for ( $p = 0; $p < strlen( $format ); $p++
) {
920 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
921 $code .= $format[++
$p];
924 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
925 $code .= $format[++
$p];
936 $rawToggle = !$rawToggle;
945 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
948 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
949 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
952 $num = substr( $ts, 6, 2 );
955 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
956 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
959 $num = intval( substr( $ts, 6, 2 ) );
963 $iranian = self
::tsToIranian( $ts );
969 $hijri = self
::tsToHijri( $ts );
975 $hebrew = self
::tsToHebrew( $ts );
981 $unix = wfTimestamp( TS_UNIX
, $ts );
983 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
987 $unix = wfTimestamp( TS_UNIX
, $ts );
989 $w = gmdate( 'w', $unix );
994 $unix = wfTimestamp( TS_UNIX
, $ts );
996 $num = gmdate( 'w', $unix );
1000 $unix = wfTimestamp( TS_UNIX
, $ts );
1002 $num = gmdate( 'z', $unix );
1006 $unix = wfTimestamp( TS_UNIX
, $ts );
1008 $num = gmdate( 'W', $unix );
1011 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1015 $iranian = self
::tsToIranian( $ts );
1017 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1021 $hijri = self
::tsToHijri( $ts );
1023 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1027 $hebrew = self
::tsToHebrew( $ts );
1029 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1032 $num = substr( $ts, 4, 2 );
1035 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1038 $num = intval( substr( $ts, 4, 2 ) );
1042 $iranian = self
::tsToIranian( $ts );
1048 $hijri = self
::tsToHijri ( $ts );
1054 $hebrew = self
::tsToHebrew( $ts );
1060 $unix = wfTimestamp( TS_UNIX
, $ts );
1062 $num = gmdate( 't', $unix );
1066 $hebrew = self
::tsToHebrew( $ts );
1072 $unix = wfTimestamp( TS_UNIX
, $ts );
1074 $num = gmdate( 'L', $unix );
1078 $unix = wfTimestamp( TS_UNIX
, $ts );
1080 $num = date( 'o', $unix );
1083 $num = substr( $ts, 0, 4 );
1087 $iranian = self
::tsToIranian( $ts );
1093 $hijri = self
::tsToHijri( $ts );
1099 $hebrew = self
::tsToHebrew( $ts );
1105 $thai = self
::tsToYear( $ts, 'thai' );
1111 $minguo = self
::tsToYear( $ts, 'minguo' );
1117 $tenno = self
::tsToYear( $ts, 'tenno' );
1122 $num = substr( $ts, 2, 2 );
1125 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1128 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1131 $h = substr( $ts, 8, 2 );
1132 $num = $h %
12 ?
$h %
12 : 12;
1135 $num = intval( substr( $ts, 8, 2 ) );
1138 $h = substr( $ts, 8, 2 );
1139 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1142 $num = substr( $ts, 8, 2 );
1145 $num = substr( $ts, 10, 2 );
1148 $num = substr( $ts, 12, 2 );
1152 $unix = wfTimestamp( TS_UNIX
, $ts );
1154 $s .= gmdate( 'c', $unix );
1158 $unix = wfTimestamp( TS_UNIX
, $ts );
1160 $s .= gmdate( 'r', $unix );
1164 $unix = wfTimestamp( TS_UNIX
, $ts );
1169 # Backslash escaping
1170 if ( $p < strlen( $format ) - 1 ) {
1171 $s .= $format[++
$p];
1178 if ( $p < strlen( $format ) - 1 ) {
1179 $endQuote = strpos( $format, '"', $p +
1 );
1180 if ( $endQuote === false ) {
1181 # No terminating quote, assume literal "
1184 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1188 # Quote at end of string, assume literal "
1195 if ( $num !== false ) {
1196 if ( $rawToggle ||
$raw ) {
1199 } elseif ( $roman ) {
1200 $s .= self
::romanNumeral( $num );
1202 } elseif ( $hebrewNum ) {
1203 $s .= self
::hebrewNumeral( $num );
1206 $s .= $this->formatNum( $num, true );
1213 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1214 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1217 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1218 * Gregorian dates to Iranian dates. Originally written in C, it
1219 * is released under the terms of GNU Lesser General Public
1220 * License. Conversion to PHP was performed by Niklas Laxström.
1222 * Link: http://www.farsiweb.info/jalali/jalali.c
1228 private static function tsToIranian( $ts ) {
1229 $gy = substr( $ts, 0, 4 ) -1600;
1230 $gm = substr( $ts, 4, 2 ) -1;
1231 $gd = substr( $ts, 6, 2 ) -1;
1233 # Days passed from the beginning (including leap years)
1235 +
floor( ( $gy +
3 ) / 4 )
1236 - floor( ( $gy +
99 ) / 100 )
1237 +
floor( ( $gy +
399 ) / 400 );
1240 // Add days of the past months of this year
1241 for ( $i = 0; $i < $gm; $i++
) {
1242 $gDayNo +
= self
::$GREG_DAYS[$i];
1246 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1250 // Days passed in current month
1253 $jDayNo = $gDayNo - 79;
1255 $jNp = floor( $jDayNo / 12053 );
1258 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1261 if ( $jDayNo >= 366 ) {
1262 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1263 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1266 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1267 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1273 return array( $jy, $jm, $jd );
1277 * Converting Gregorian dates to Hijri dates.
1279 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1281 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1287 private static function tsToHijri( $ts ) {
1288 $year = substr( $ts, 0, 4 );
1289 $month = substr( $ts, 4, 2 );
1290 $day = substr( $ts, 6, 2 );
1298 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1299 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1302 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1303 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1304 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1307 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1308 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1311 $zl = $zjd -1948440 +
10632;
1312 $zn = (int)( ( $zl - 1 ) / 10631 );
1313 $zl = $zl - 10631 * $zn +
354;
1314 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1315 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1316 $zm = (int)( ( 24 * $zl ) / 709 );
1317 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1318 $zy = 30 * $zn +
$zj - 30;
1320 return array( $zy, $zm, $zd );
1324 * Converting Gregorian dates to Hebrew dates.
1326 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1327 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1328 * to translate the relevant functions into PHP and release them under
1331 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1332 * and Adar II is 14. In a non-leap year, Adar is 6.
1338 private static function tsToHebrew( $ts ) {
1340 $year = substr( $ts, 0, 4 );
1341 $month = substr( $ts, 4, 2 );
1342 $day = substr( $ts, 6, 2 );
1344 # Calculate Hebrew year
1345 $hebrewYear = $year +
3760;
1347 # Month number when September = 1, August = 12
1349 if ( $month > 12 ) {
1356 # Calculate day of year from 1 September
1358 for ( $i = 1; $i < $month; $i++
) {
1362 # Check if the year is leap
1363 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1366 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1373 # Calculate the start of the Hebrew year
1374 $start = self
::hebrewYearStart( $hebrewYear );
1376 # Calculate next year's start
1377 if ( $dayOfYear <= $start ) {
1378 # Day is before the start of the year - it is the previous year
1380 $nextStart = $start;
1384 # Add days since previous year's 1 September
1386 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1390 # Start of the new (previous) year
1391 $start = self
::hebrewYearStart( $hebrewYear );
1394 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1397 # Calculate Hebrew day of year
1398 $hebrewDayOfYear = $dayOfYear - $start;
1400 # Difference between year's days
1401 $diff = $nextStart - $start;
1402 # Add 12 (or 13 for leap years) days to ignore the difference between
1403 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1404 # difference is only about the year type
1405 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1411 # Check the year pattern, and is leap year
1412 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1413 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1414 # and non-leap years
1415 $yearPattern = $diff %
30;
1416 # Check if leap year
1417 $isLeap = $diff >= 30;
1419 # Calculate day in the month from number of day in the Hebrew year
1420 # Don't check Adar - if the day is not in Adar, we will stop before;
1421 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1422 $hebrewDay = $hebrewDayOfYear;
1425 while ( $hebrewMonth <= 12 ) {
1426 # Calculate days in this month
1427 if ( $isLeap && $hebrewMonth == 6 ) {
1428 # Adar in a leap year
1430 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1432 if ( $hebrewDay <= $days ) {
1436 # Subtract the days of Adar I
1437 $hebrewDay -= $days;
1440 if ( $hebrewDay <= $days ) {
1446 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1447 # Cheshvan in a complete year (otherwise as the rule below)
1449 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1450 # Kislev in an incomplete year (otherwise as the rule below)
1453 # Odd months have 30 days, even have 29
1454 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1456 if ( $hebrewDay <= $days ) {
1457 # In the current month
1460 # Subtract the days of the current month
1461 $hebrewDay -= $days;
1462 # Try in the next month
1467 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1471 * This calculates the Hebrew year start, as days since 1 September.
1472 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1473 * Used for Hebrew date.
1479 private static function hebrewYearStart( $year ) {
1480 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1481 $b = intval( ( $year - 1 ) %
4 );
1482 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1486 $Mar = intval( $m );
1492 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1493 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1495 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1497 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1501 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1506 * Algorithm to convert Gregorian dates to Thai solar dates,
1507 * Minguo dates or Minguo dates.
1509 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1510 * http://en.wikipedia.org/wiki/Minguo_calendar
1511 * http://en.wikipedia.org/wiki/Japanese_era_name
1513 * @param $ts String: 14-character timestamp
1514 * @param $cName String: calender name
1515 * @return Array: converted year, month, day
1517 private static function tsToYear( $ts, $cName ) {
1518 $gy = substr( $ts, 0, 4 );
1519 $gm = substr( $ts, 4, 2 );
1520 $gd = substr( $ts, 6, 2 );
1522 if ( !strcmp( $cName, 'thai' ) ) {
1524 # Add 543 years to the Gregorian calendar
1525 # Months and days are identical
1526 $gy_offset = $gy +
543;
1527 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1529 # Deduct 1911 years from the Gregorian calendar
1530 # Months and days are identical
1531 $gy_offset = $gy - 1911;
1532 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1533 # Nengō dates up to Meiji period
1534 # Deduct years from the Gregorian calendar
1535 # depending on the nengo periods
1536 # Months and days are identical
1537 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1539 $gy_gannen = $gy - 1868 +
1;
1540 $gy_offset = $gy_gannen;
1541 if ( $gy_gannen == 1 ) {
1544 $gy_offset = '明治' . $gy_offset;
1546 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1547 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1548 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1549 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1550 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1554 $gy_gannen = $gy - 1912 +
1;
1555 $gy_offset = $gy_gannen;
1556 if ( $gy_gannen == 1 ) {
1559 $gy_offset = '大正' . $gy_offset;
1561 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1562 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1563 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1567 $gy_gannen = $gy - 1926 +
1;
1568 $gy_offset = $gy_gannen;
1569 if ( $gy_gannen == 1 ) {
1572 $gy_offset = '昭和' . $gy_offset;
1575 $gy_gannen = $gy - 1989 +
1;
1576 $gy_offset = $gy_gannen;
1577 if ( $gy_gannen == 1 ) {
1580 $gy_offset = '平成' . $gy_offset;
1586 return array( $gy_offset, $gm, $gd );
1590 * Roman number formatting up to 3000
1596 static function romanNumeral( $num ) {
1597 static $table = array(
1598 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1599 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1600 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1601 array( '', 'M', 'MM', 'MMM' )
1604 $num = intval( $num );
1605 if ( $num > 3000 ||
$num <= 0 ) {
1610 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1611 if ( $num >= $pow10 ) {
1612 $s .= $table[$i][floor( $num / $pow10 )];
1614 $num = $num %
$pow10;
1620 * Hebrew Gematria number formatting up to 9999
1626 static function hebrewNumeral( $num ) {
1627 static $table = array(
1628 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1629 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1630 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1631 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1634 $num = intval( $num );
1635 if ( $num > 9999 ||
$num <= 0 ) {
1640 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1641 if ( $num >= $pow10 ) {
1642 if ( $num == 15 ||
$num == 16 ) {
1643 $s .= $table[0][9] . $table[0][$num - 9];
1646 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1647 if ( $pow10 == 1000 ) {
1652 $num = $num %
$pow10;
1654 if ( strlen( $s ) == 2 ) {
1657 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1658 $str .= substr( $s, strlen( $s ) - 2, 2 );
1660 $start = substr( $str, 0, strlen( $str ) - 2 );
1661 $end = substr( $str, strlen( $str ) - 2 );
1664 $str = $start . 'ך';
1667 $str = $start . 'ם';
1670 $str = $start . 'ן';
1673 $str = $start . 'ף';
1676 $str = $start . 'ץ';
1683 * This is meant to be used by time(), date(), and timeanddate() to get
1684 * the date preference they're supposed to use, it should be used in
1688 * function timeanddate([...], $format = true) {
1689 * $datePreference = $this->dateFormat($format);
1694 * @param $usePrefs Mixed: if true, the user's preference is used
1695 * if false, the site/language default is used
1696 * if int/string, assumed to be a format.
1699 function dateFormat( $usePrefs = true ) {
1702 if ( is_bool( $usePrefs ) ) {
1704 $datePreference = $wgUser->getDatePreference();
1706 $datePreference = (string)User
::getDefaultOption( 'date' );
1709 $datePreference = (string)$usePrefs;
1713 if ( $datePreference == '' ) {
1717 return $datePreference;
1721 * Get a format string for a given type and preference
1722 * @param $type string May be date, time or both
1723 * @param $pref string The format name as it appears in Messages*.php
1727 function getDateFormatString( $type, $pref ) {
1728 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1729 if ( $pref == 'default' ) {
1730 $pref = $this->getDefaultDateFormat();
1731 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1733 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1734 if ( is_null( $df ) ) {
1735 $pref = $this->getDefaultDateFormat();
1736 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1739 $this->dateFormatStrings
[$type][$pref] = $df;
1741 return $this->dateFormatStrings
[$type][$pref];
1745 * @param $ts Mixed: the time format which needs to be turned into a
1746 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1747 * @param $adj Bool: whether to adjust the time output according to the
1748 * user configured offset ($timecorrection)
1749 * @param $format Mixed: true to use user's date format preference
1750 * @param $timecorrection String|bool the time offset as returned by
1751 * validateTimeZone() in Special:Preferences
1754 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1755 $ts = wfTimestamp( TS_MW
, $ts );
1757 $ts = $this->userAdjust( $ts, $timecorrection );
1759 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1760 return $this->sprintfDate( $df, $ts );
1764 * @param $ts Mixed: the time format which needs to be turned into a
1765 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1766 * @param $adj Bool: whether to adjust the time output according to the
1767 * user configured offset ($timecorrection)
1768 * @param $format Mixed: true to use user's date format preference
1769 * @param $timecorrection String|bool the time offset as returned by
1770 * validateTimeZone() in Special:Preferences
1773 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1774 $ts = wfTimestamp( TS_MW
, $ts );
1776 $ts = $this->userAdjust( $ts, $timecorrection );
1778 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1779 return $this->sprintfDate( $df, $ts );
1783 * @param $ts Mixed: the time format which needs to be turned into a
1784 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1785 * @param $adj Bool: whether to adjust the time output according to the
1786 * user configured offset ($timecorrection)
1787 * @param $format Mixed: what format to return, if it's false output the
1788 * default one (default true)
1789 * @param $timecorrection String|bool the time offset as returned by
1790 * validateTimeZone() in Special:Preferences
1793 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1794 $ts = wfTimestamp( TS_MW
, $ts );
1796 $ts = $this->userAdjust( $ts, $timecorrection );
1798 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1799 return $this->sprintfDate( $df, $ts );
1803 * @param $key string
1804 * @return array|null
1806 function getMessage( $key ) {
1807 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1813 function getAllMessages() {
1814 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1823 function iconv( $in, $out, $string ) {
1824 # This is a wrapper for iconv in all languages except esperanto,
1825 # which does some nasty x-conversions beforehand
1827 # Even with //IGNORE iconv can whine about illegal characters in
1828 # *input* string. We just ignore those too.
1829 # REF: http://bugs.php.net/bug.php?id=37166
1830 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1831 wfSuppressWarnings();
1832 $text = iconv( $in, $out . '//IGNORE', $string );
1833 wfRestoreWarnings();
1837 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1840 * @param $matches array
1841 * @return mixed|string
1843 function ucwordbreaksCallbackAscii( $matches ) {
1844 return $this->ucfirst( $matches[1] );
1848 * @param $matches array
1851 function ucwordbreaksCallbackMB( $matches ) {
1852 return mb_strtoupper( $matches[0] );
1856 * @param $matches array
1859 function ucCallback( $matches ) {
1860 list( $wikiUpperChars ) = self
::getCaseMaps();
1861 return strtr( $matches[1], $wikiUpperChars );
1865 * @param $matches array
1868 function lcCallback( $matches ) {
1869 list( , $wikiLowerChars ) = self
::getCaseMaps();
1870 return strtr( $matches[1], $wikiLowerChars );
1874 * @param $matches array
1877 function ucwordsCallbackMB( $matches ) {
1878 return mb_strtoupper( $matches[0] );
1882 * @param $matches array
1885 function ucwordsCallbackWiki( $matches ) {
1886 list( $wikiUpperChars ) = self
::getCaseMaps();
1887 return strtr( $matches[0], $wikiUpperChars );
1891 * Make a string's first character uppercase
1893 * @param $str string
1897 function ucfirst( $str ) {
1899 if ( $o < 96 ) { // if already uppercase...
1901 } elseif ( $o < 128 ) {
1902 return ucfirst( $str ); // use PHP's ucfirst()
1904 // fall back to more complex logic in case of multibyte strings
1905 return $this->uc( $str, true );
1910 * Convert a string to uppercase
1912 * @param $str string
1913 * @param $first bool
1917 function uc( $str, $first = false ) {
1918 if ( function_exists( 'mb_strtoupper' ) ) {
1920 if ( $this->isMultibyte( $str ) ) {
1921 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1923 return ucfirst( $str );
1926 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1929 if ( $this->isMultibyte( $str ) ) {
1930 $x = $first ?
'^' : '';
1931 return preg_replace_callback(
1932 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1933 array( $this, 'ucCallback' ),
1937 return $first ?
ucfirst( $str ) : strtoupper( $str );
1943 * @param $str string
1944 * @return mixed|string
1946 function lcfirst( $str ) {
1949 return strval( $str );
1950 } elseif ( $o >= 128 ) {
1951 return $this->lc( $str, true );
1952 } elseif ( $o > 96 ) {
1955 $str[0] = strtolower( $str[0] );
1961 * @param $str string
1962 * @param $first bool
1963 * @return mixed|string
1965 function lc( $str, $first = false ) {
1966 if ( function_exists( 'mb_strtolower' ) ) {
1968 if ( $this->isMultibyte( $str ) ) {
1969 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1971 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1974 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1977 if ( $this->isMultibyte( $str ) ) {
1978 $x = $first ?
'^' : '';
1979 return preg_replace_callback(
1980 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1981 array( $this, 'lcCallback' ),
1985 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1991 * @param $str string
1994 function isMultibyte( $str ) {
1995 return (bool)preg_match( '/[\x80-\xff]/', $str );
1999 * @param $str string
2000 * @return mixed|string
2002 function ucwords( $str ) {
2003 if ( $this->isMultibyte( $str ) ) {
2004 $str = $this->lc( $str );
2006 // regexp to find first letter in each word (i.e. after each space)
2007 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2009 // function to use to capitalize a single char
2010 if ( function_exists( 'mb_strtoupper' ) ) {
2011 return preg_replace_callback(
2013 array( $this, 'ucwordsCallbackMB' ),
2017 return preg_replace_callback(
2019 array( $this, 'ucwordsCallbackWiki' ),
2024 return ucwords( strtolower( $str ) );
2029 * capitalize words at word breaks
2031 * @param $str string
2034 function ucwordbreaks( $str ) {
2035 if ( $this->isMultibyte( $str ) ) {
2036 $str = $this->lc( $str );
2038 // since \b doesn't work for UTF-8, we explicitely define word break chars
2039 $breaks = "[ \-\(\)\}\{\.,\?!]";
2041 // find first letter after word break
2042 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2044 if ( function_exists( 'mb_strtoupper' ) ) {
2045 return preg_replace_callback(
2047 array( $this, 'ucwordbreaksCallbackMB' ),
2051 return preg_replace_callback(
2053 array( $this, 'ucwordsCallbackWiki' ),
2058 return preg_replace_callback(
2059 '/\b([\w\x80-\xff]+)\b/',
2060 array( $this, 'ucwordbreaksCallbackAscii' ),
2067 * Return a case-folded representation of $s
2069 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2070 * and $s2 are the same except for the case of their characters. It is not
2071 * necessary for the value returned to make sense when displayed.
2073 * Do *not* perform any other normalisation in this function. If a caller
2074 * uses this function when it should be using a more general normalisation
2075 * function, then fix the caller.
2081 function caseFold( $s ) {
2082 return $this->uc( $s );
2089 function checkTitleEncoding( $s ) {
2090 if ( is_array( $s ) ) {
2091 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2093 # Check for non-UTF-8 URLs
2094 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2099 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2100 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2105 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2111 function fallback8bitEncoding() {
2112 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2116 * Most writing systems use whitespace to break up words.
2117 * Some languages such as Chinese don't conventionally do this,
2118 * which requires special handling when breaking up words for
2123 function hasWordBreaks() {
2128 * Some languages such as Chinese require word segmentation,
2129 * Specify such segmentation when overridden in derived class.
2131 * @param $string String
2134 function segmentByWord( $string ) {
2139 * Some languages have special punctuation need to be normalized.
2140 * Make such changes here.
2142 * @param $string String
2145 function normalizeForSearch( $string ) {
2146 return self
::convertDoubleWidth( $string );
2150 * convert double-width roman characters to single-width.
2151 * range: ff00-ff5f ~= 0020-007f
2153 * @param $string string
2157 protected static function convertDoubleWidth( $string ) {
2158 static $full = null;
2159 static $half = null;
2161 if ( $full === null ) {
2162 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2163 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2164 $full = str_split( $fullWidth, 3 );
2165 $half = str_split( $halfWidth );
2168 $string = str_replace( $full, $half, $string );
2173 * @param $string string
2174 * @param $pattern string
2177 protected static function insertSpace( $string, $pattern ) {
2178 $string = preg_replace( $pattern, " $1 ", $string );
2179 $string = preg_replace( '/ +/', ' ', $string );
2184 * @param $termsArray array
2187 function convertForSearchResult( $termsArray ) {
2188 # some languages, e.g. Chinese, need to do a conversion
2189 # in order for search results to be displayed correctly
2194 * Get the first character of a string.
2199 function firstChar( $s ) {
2202 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2203 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2208 if ( isset( $matches[1] ) ) {
2209 if ( strlen( $matches[1] ) != 3 ) {
2213 // Break down Hangul syllables to grab the first jamo
2214 $code = utf8ToCodepoint( $matches[1] );
2215 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2217 } elseif ( $code < 0xb098 ) {
2218 return "\xe3\x84\xb1";
2219 } elseif ( $code < 0xb2e4 ) {
2220 return "\xe3\x84\xb4";
2221 } elseif ( $code < 0xb77c ) {
2222 return "\xe3\x84\xb7";
2223 } elseif ( $code < 0xb9c8 ) {
2224 return "\xe3\x84\xb9";
2225 } elseif ( $code < 0xbc14 ) {
2226 return "\xe3\x85\x81";
2227 } elseif ( $code < 0xc0ac ) {
2228 return "\xe3\x85\x82";
2229 } elseif ( $code < 0xc544 ) {
2230 return "\xe3\x85\x85";
2231 } elseif ( $code < 0xc790 ) {
2232 return "\xe3\x85\x87";
2233 } elseif ( $code < 0xcc28 ) {
2234 return "\xe3\x85\x88";
2235 } elseif ( $code < 0xce74 ) {
2236 return "\xe3\x85\x8a";
2237 } elseif ( $code < 0xd0c0 ) {
2238 return "\xe3\x85\x8b";
2239 } elseif ( $code < 0xd30c ) {
2240 return "\xe3\x85\x8c";
2241 } elseif ( $code < 0xd558 ) {
2242 return "\xe3\x85\x8d";
2244 return "\xe3\x85\x8e";
2251 function initEncoding() {
2252 # Some languages may have an alternate char encoding option
2253 # (Esperanto X-coding, Japanese furigana conversion, etc)
2254 # If this language is used as the primary content language,
2255 # an override to the defaults can be set here on startup.
2262 function recodeForEdit( $s ) {
2263 # For some languages we'll want to explicitly specify
2264 # which characters make it into the edit box raw
2265 # or are converted in some way or another.
2266 global $wgEditEncoding;
2267 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2270 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2278 function recodeInput( $s ) {
2279 # Take the previous into account.
2280 global $wgEditEncoding;
2281 if ( $wgEditEncoding != '' ) {
2282 $enc = $wgEditEncoding;
2286 if ( $enc == 'UTF-8' ) {
2289 return $this->iconv( $enc, 'UTF-8', $s );
2294 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2295 * also cleans up certain backwards-compatible sequences, converting them
2296 * to the modern Unicode equivalent.
2298 * This is language-specific for performance reasons only.
2304 function normalize( $s ) {
2305 global $wgAllUnicodeFixes;
2306 $s = UtfNormal
::cleanUp( $s );
2307 if ( $wgAllUnicodeFixes ) {
2308 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2309 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2316 * Transform a string using serialized data stored in the given file (which
2317 * must be in the serialized subdirectory of $IP). The file contains pairs
2318 * mapping source characters to destination characters.
2320 * The data is cached in process memory. This will go faster if you have the
2321 * FastStringSearch extension.
2323 * @param $file string
2324 * @param $string string
2328 function transformUsingPairFile( $file, $string ) {
2329 if ( !isset( $this->transformData
[$file] ) ) {
2330 $data = wfGetPrecompiledData( $file );
2331 if ( $data === false ) {
2332 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2334 $this->transformData
[$file] = new ReplacementArray( $data );
2336 return $this->transformData
[$file]->replace( $string );
2340 * For right-to-left language support
2345 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2349 * Return the correct HTML 'dir' attribute value for this language.
2353 return $this->isRTL() ?
'rtl' : 'ltr';
2357 * Return 'left' or 'right' as appropriate alignment for line-start
2358 * for this language's text direction.
2360 * Should be equivalent to CSS3 'start' text-align value....
2364 function alignStart() {
2365 return $this->isRTL() ?
'right' : 'left';
2369 * Return 'right' or 'left' as appropriate alignment for line-end
2370 * for this language's text direction.
2372 * Should be equivalent to CSS3 'end' text-align value....
2376 function alignEnd() {
2377 return $this->isRTL() ?
'left' : 'right';
2381 * A hidden direction mark (LRM or RLM), depending on the language direction
2383 * @param $opposite Boolean Get the direction mark opposite to your language
2386 function getDirMark( $opposite = false ) {
2387 $rtl = "\xE2\x80\x8F";
2388 $ltr = "\xE2\x80\x8E";
2389 if( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2390 return $this->isRTL() ?
$rtl : $ltr;
2396 function capitalizeAllNouns() {
2397 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2401 * An arrow, depending on the language direction
2405 function getArrow() {
2406 return $this->isRTL() ?
'←' : '→';
2410 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2414 function linkPrefixExtension() {
2415 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2421 function getMagicWords() {
2422 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2425 protected function doMagicHook() {
2426 if ( $this->mMagicHookDone
) {
2429 $this->mMagicHookDone
= true;
2430 wfProfileIn( 'LanguageGetMagic' );
2431 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2432 wfProfileOut( 'LanguageGetMagic' );
2436 * Fill a MagicWord object with data from here
2440 function getMagic( $mw ) {
2441 $this->doMagicHook();
2443 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2444 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2446 $magicWords = $this->getMagicWords();
2447 if ( isset( $magicWords[$mw->mId
] ) ) {
2448 $rawEntry = $magicWords[$mw->mId
];
2454 if ( !is_array( $rawEntry ) ) {
2455 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2457 $mw->mCaseSensitive
= $rawEntry[0];
2458 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2463 * Add magic words to the extension array
2465 * @param $newWords array
2467 function addMagicWordsByLang( $newWords ) {
2468 $fallbackChain = $this->getFallbackLanguages();
2469 $fallbackChain = array_reverse( $fallbackChain );
2470 foreach ( $fallbackChain as $code ) {
2471 if ( isset( $newWords[$code] ) ) {
2472 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2478 * Get special page names, as an associative array
2479 * case folded alias => real name
2481 function getSpecialPageAliases() {
2482 // Cache aliases because it may be slow to load them
2483 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2485 $this->mExtendedSpecialPageAliases
=
2486 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2487 wfRunHooks( 'LanguageGetSpecialPageAliases',
2488 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2491 return $this->mExtendedSpecialPageAliases
;
2495 * Italic is unsuitable for some languages
2497 * @param $text String: the text to be emphasized.
2500 function emphasize( $text ) {
2501 return "<em>$text</em>";
2505 * Normally we output all numbers in plain en_US style, that is
2506 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2507 * point twohundredthirtyfive. However this is not sutable for all
2508 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2509 * Icelandic just want to use commas instead of dots, and dots instead
2510 * of commas like "293.291,235".
2512 * An example of this function being called:
2514 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2517 * See LanguageGu.php for the Gujarati implementation and
2518 * $separatorTransformTable on MessageIs.php for
2519 * the , => . and . => , implementation.
2521 * @todo check if it's viable to use localeconv() for the decimal
2523 * @param $number Mixed: the string to be formatted, should be an integer
2524 * or a floating point number.
2525 * @param $nocommafy Bool: set to true for special numbers like dates
2528 function formatNum( $number, $nocommafy = false ) {
2529 global $wgTranslateNumerals;
2530 if ( !$nocommafy ) {
2531 $number = $this->commafy( $number );
2532 $s = $this->separatorTransformTable();
2534 $number = strtr( $number, $s );
2538 if ( $wgTranslateNumerals ) {
2539 $s = $this->digitTransformTable();
2541 $number = strtr( $number, $s );
2549 * @param $number string
2552 function parseFormattedNumber( $number ) {
2553 $s = $this->digitTransformTable();
2555 $number = strtr( $number, array_flip( $s ) );
2558 $s = $this->separatorTransformTable();
2560 $number = strtr( $number, array_flip( $s ) );
2563 $number = strtr( $number, array( ',' => '' ) );
2568 * Adds commas to a given number
2573 function commafy( $_ ) {
2574 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2580 function digitTransformTable() {
2581 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2587 function separatorTransformTable() {
2588 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2592 * Take a list of strings and build a locale-friendly comma-separated
2593 * list, using the local comma-separator message.
2594 * The last two strings are chained with an "and".
2599 function listToText( $l ) {
2601 $m = count( $l ) - 1;
2603 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2605 for ( $i = $m; $i >= 0; $i-- ) {
2608 } elseif ( $i == $m - 1 ) {
2609 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2611 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2619 * Take a list of strings and build a locale-friendly comma-separated
2620 * list, using the local comma-separator message.
2621 * @param $list array of strings to put in a comma list
2624 function commaList( $list ) {
2629 array( 'parsemag', 'escapenoentities', 'language' => $this )
2635 * Take a list of strings and build a locale-friendly semicolon-separated
2636 * list, using the local semicolon-separator message.
2637 * @param $list array of strings to put in a semicolon list
2640 function semicolonList( $list ) {
2644 'semicolon-separator',
2645 array( 'parsemag', 'escapenoentities', 'language' => $this )
2651 * Same as commaList, but separate it with the pipe instead.
2652 * @param $list array of strings to put in a pipe list
2655 function pipeList( $list ) {
2660 array( 'escapenoentities', 'language' => $this )
2666 * Truncate a string to a specified length in bytes, appending an optional
2667 * string (e.g. for ellipses)
2669 * The database offers limited byte lengths for some columns in the database;
2670 * multi-byte character sets mean we need to ensure that only whole characters
2671 * are included, otherwise broken characters can be passed to the user
2673 * If $length is negative, the string will be truncated from the beginning
2675 * @param $string String to truncate
2676 * @param $length Int: maximum length (including ellipses)
2677 * @param $ellipsis String to append to the truncated text
2678 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2679 * $adjustLength was introduced in 1.18, before that behaved as if false.
2682 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2683 # Use the localized ellipsis character
2684 if ( $ellipsis == '...' ) {
2685 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2687 # Check if there is no need to truncate
2688 if ( $length == 0 ) {
2689 return $ellipsis; // convention
2690 } elseif ( strlen( $string ) <= abs( $length ) ) {
2691 return $string; // no need to truncate
2693 $stringOriginal = $string;
2694 # If ellipsis length is >= $length then we can't apply $adjustLength
2695 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2696 $string = $ellipsis; // this can be slightly unexpected
2697 # Otherwise, truncate and add ellipsis...
2699 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2700 if ( $length > 0 ) {
2701 $length -= $eLength;
2702 $string = substr( $string, 0, $length ); // xyz...
2703 $string = $this->removeBadCharLast( $string );
2704 $string = $string . $ellipsis;
2706 $length +
= $eLength;
2707 $string = substr( $string, $length ); // ...xyz
2708 $string = $this->removeBadCharFirst( $string );
2709 $string = $ellipsis . $string;
2712 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2713 # This check is *not* redundant if $adjustLength, due to the single case where
2714 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2715 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2718 return $stringOriginal;
2723 * Remove bytes that represent an incomplete Unicode character
2724 * at the end of string (e.g. bytes of the char are missing)
2726 * @param $string String
2729 protected function removeBadCharLast( $string ) {
2730 if ( $string != '' ) {
2731 $char = ord( $string[strlen( $string ) - 1] );
2733 if ( $char >= 0xc0 ) {
2734 # We got the first byte only of a multibyte char; remove it.
2735 $string = substr( $string, 0, -1 );
2736 } elseif ( $char >= 0x80 &&
2737 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2738 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2740 # We chopped in the middle of a character; remove it
2748 * Remove bytes that represent an incomplete Unicode character
2749 * at the start of string (e.g. bytes of the char are missing)
2751 * @param $string String
2754 protected function removeBadCharFirst( $string ) {
2755 if ( $string != '' ) {
2756 $char = ord( $string[0] );
2757 if ( $char >= 0x80 && $char < 0xc0 ) {
2758 # We chopped in the middle of a character; remove the whole thing
2759 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2766 * Truncate a string of valid HTML to a specified length in bytes,
2767 * appending an optional string (e.g. for ellipses), and return valid HTML
2769 * This is only intended for styled/linked text, such as HTML with
2770 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2771 * Also, this will not detect things like "display:none" CSS.
2773 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2775 * @param string $text HTML string to truncate
2776 * @param int $length (zero/positive) Maximum length (including ellipses)
2777 * @param string $ellipsis String to append to the truncated text
2780 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2781 # Use the localized ellipsis character
2782 if ( $ellipsis == '...' ) {
2783 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2785 # Check if there is clearly no need to truncate
2786 if ( $length <= 0 ) {
2787 return $ellipsis; // no text shown, nothing to format (convention)
2788 } elseif ( strlen( $text ) <= $length ) {
2789 return $text; // string short enough even *with* HTML (short-circuit)
2792 $dispLen = 0; // innerHTML legth so far
2793 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2794 $tagType = 0; // 0-open, 1-close
2795 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2796 $entityState = 0; // 0-not entity, 1-entity
2797 $tag = $ret = ''; // accumulated tag name, accumulated result string
2798 $openTags = array(); // open tag stack
2799 $maybeState = null; // possible truncation state
2801 $textLen = strlen( $text );
2802 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2803 for ( $pos = 0; true; ++
$pos ) {
2804 # Consider truncation once the display length has reached the maximim.
2805 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2806 # Check that we're not in the middle of a bracket/entity...
2807 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2808 if ( !$testingEllipsis ) {
2809 $testingEllipsis = true;
2810 # Save where we are; we will truncate here unless there turn out to
2811 # be so few remaining characters that truncation is not necessary.
2812 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2813 $maybeState = array( $ret, $openTags ); // save state
2815 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2816 # String in fact does need truncation, the truncation point was OK.
2817 list( $ret, $openTags ) = $maybeState; // reload state
2818 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2819 $ret .= $ellipsis; // add ellipsis
2823 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2825 # Read the next char...
2827 $lastCh = $pos ?
$text[$pos - 1] : '';
2828 $ret .= $ch; // add to result string
2830 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2831 $entityState = 0; // for bad HTML
2832 $bracketState = 1; // tag started (checking for backslash)
2833 } elseif ( $ch == '>' ) {
2834 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2835 $entityState = 0; // for bad HTML
2836 $bracketState = 0; // out of brackets
2837 } elseif ( $bracketState == 1 ) {
2839 $tagType = 1; // close tag (e.g. "</span>")
2841 $tagType = 0; // open tag (e.g. "<span>")
2844 $bracketState = 2; // building tag name
2845 } elseif ( $bracketState == 2 ) {
2849 // Name found (e.g. "<a href=..."), add on tag attributes...
2850 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2852 } elseif ( $bracketState == 0 ) {
2853 if ( $entityState ) {
2856 $dispLen++
; // entity is one displayed char
2859 if ( $neLength == 0 && !$maybeState ) {
2860 // Save state without $ch. We want to *hit* the first
2861 // display char (to get tags) but not *use* it if truncating.
2862 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2865 $entityState = 1; // entity found, (e.g. " ")
2867 $dispLen++
; // this char is displayed
2868 // Add the next $max display text chars after this in one swoop...
2869 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2870 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2871 $dispLen +
= $skipped;
2877 // Close the last tag if left unclosed by bad HTML
2878 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2879 while ( count( $openTags ) > 0 ) {
2880 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2886 * truncateHtml() helper function
2887 * like strcspn() but adds the skipped chars to $ret
2896 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2897 if ( $len === null ) {
2898 $len = -1; // -1 means "no limit" for strcspn
2899 } elseif ( $len < 0 ) {
2903 if ( $start < strlen( $text ) ) {
2904 $skipCount = strcspn( $text, $search, $start, $len );
2905 $ret .= substr( $text, $start, $skipCount );
2911 * truncateHtml() helper function
2912 * (a) push or pop $tag from $openTags as needed
2913 * (b) clear $tag value
2914 * @param String &$tag Current HTML tag name we are looking at
2915 * @param int $tagType (0-open tag, 1-close tag)
2916 * @param char $lastCh Character before the '>' that ended this tag
2917 * @param array &$openTags Open tag stack (not accounting for $tag)
2919 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2920 $tag = ltrim( $tag );
2922 if ( $tagType == 0 && $lastCh != '/' ) {
2923 $openTags[] = $tag; // tag opened (didn't close itself)
2924 } elseif ( $tagType == 1 ) {
2925 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2926 array_pop( $openTags ); // tag closed
2934 * Grammatical transformations, needed for inflected languages
2935 * Invoked by putting {{grammar:case|word}} in a message
2937 * @param $word string
2938 * @param $case string
2941 function convertGrammar( $word, $case ) {
2942 global $wgGrammarForms;
2943 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2944 return $wgGrammarForms[$this->getCode()][$case][$word];
2950 * Provides an alternative text depending on specified gender.
2951 * Usage {{gender:username|masculine|feminine|neutral}}.
2952 * username is optional, in which case the gender of current user is used,
2953 * but only in (some) interface messages; otherwise default gender is used.
2954 * If second or third parameter are not specified, masculine is used.
2955 * These details may be overriden per language.
2957 * @param $gender string
2958 * @param $forms array
2962 function gender( $gender, $forms ) {
2963 if ( !count( $forms ) ) {
2966 $forms = $this->preConvertPlural( $forms, 2 );
2967 if ( $gender === 'male' ) {
2970 if ( $gender === 'female' ) {
2973 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2977 * Plural form transformations, needed for some languages.
2978 * For example, there are 3 form of plural in Russian and Polish,
2979 * depending on "count mod 10". See [[w:Plural]]
2980 * For English it is pretty simple.
2982 * Invoked by putting {{plural:count|wordform1|wordform2}}
2983 * or {{plural:count|wordform1|wordform2|wordform3}}
2985 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2987 * @param $count Integer: non-localized number
2988 * @param $forms Array: different plural forms
2989 * @return string Correct form of plural for $count in this language
2991 function convertPlural( $count, $forms ) {
2992 if ( !count( $forms ) ) {
2995 $forms = $this->preConvertPlural( $forms, 2 );
2997 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3001 * Checks that convertPlural was given an array and pads it to requested
3002 * amount of forms by copying the last one.
3004 * @param $count Integer: How many forms should there be at least
3005 * @param $forms Array of forms given to convertPlural
3006 * @return array Padded array of forms or an exception if not an array
3008 protected function preConvertPlural( /* Array */ $forms, $count ) {
3009 while ( count( $forms ) < $count ) {
3010 $forms[] = $forms[count( $forms ) - 1];
3016 * This translates the duration ("1 week", "4 days", etc)
3017 * as well as the expiry time (which is an absolute timestamp).
3018 * @param $str String: the validated block duration in English
3019 * @return Somehow translated block duration
3020 * @see LanguageFi.php for example implementation
3022 function translateBlockExpiry( $str ) {
3023 $duration = SpecialBlock
::getSuggestedDurations( $this );
3024 foreach( $duration as $show => $value ){
3025 if ( strcmp( $str, $value ) == 0 ) {
3026 return htmlspecialchars( trim( $show ) );
3030 // Since usually only infinite or indefinite is only on list, so try
3031 // equivalents if still here.
3032 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3033 if ( in_array( $str, $indefs ) ) {
3034 foreach( $indefs as $val ) {
3035 $show = array_search( $val, $duration, true );
3036 if ( $show !== false ) {
3037 return htmlspecialchars( trim( $show ) );
3041 // If no duration is given, but a timestamp, display that
3042 return ( strtotime( $str ) ?
$this->timeanddate( strtotime( $str ) ) : $str );
3046 * languages like Chinese need to be segmented in order for the diff
3049 * @param $text String
3052 function segmentForDiff( $text ) {
3057 * and unsegment to show the result
3059 * @param $text String
3062 function unsegmentForDiff( $text ) {
3067 * convert text to all supported variants
3069 * @param $text string
3072 function autoConvertToAllVariants( $text ) {
3073 return $this->mConverter
->autoConvertToAllVariants( $text );
3077 * convert text to different variants of a language.
3079 * @param $text string
3082 function convert( $text ) {
3083 return $this->mConverter
->convert( $text );
3088 * Convert a Title object to a string in the preferred variant
3090 * @param $title Title
3093 function convertTitle( $title ) {
3094 return $this->mConverter
->convertTitle( $title );
3098 * Check if this is a language with variants
3102 function hasVariants() {
3103 return sizeof( $this->getVariants() ) > 1;
3107 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3109 * @param $text string
3112 function armourMath( $text ) {
3113 return $this->mConverter
->armourMath( $text );
3117 * Perform output conversion on a string, and encode for safe HTML output.
3118 * @param $text String text to be converted
3119 * @param $isTitle Bool whether this conversion is for the article title
3121 * @todo this should get integrated somewhere sane
3123 function convertHtml( $text, $isTitle = false ) {
3124 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3128 * @param $key string
3131 function convertCategoryKey( $key ) {
3132 return $this->mConverter
->convertCategoryKey( $key );
3136 * Get the list of variants supported by this language
3137 * see sample implementation in LanguageZh.php
3139 * @return array an array of language codes
3141 function getVariants() {
3142 return $this->mConverter
->getVariants();
3148 function getPreferredVariant() {
3149 return $this->mConverter
->getPreferredVariant();
3155 function getDefaultVariant() {
3156 return $this->mConverter
->getDefaultVariant();
3162 function getURLVariant() {
3163 return $this->mConverter
->getURLVariant();
3167 * If a language supports multiple variants, it is
3168 * possible that non-existing link in one variant
3169 * actually exists in another variant. this function
3170 * tries to find it. See e.g. LanguageZh.php
3172 * @param $link String: the name of the link
3173 * @param $nt Mixed: the title object of the link
3174 * @param $ignoreOtherCond Boolean: to disable other conditions when
3175 * we need to transclude a template or update a category's link
3176 * @return null the input parameters may be modified upon return
3178 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3179 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3183 * If a language supports multiple variants, converts text
3184 * into an array of all possible variants of the text:
3185 * 'variant' => text in that variant
3187 * @deprecated since 1.17 Use autoConvertToAllVariants()
3189 * @param $text string
3193 function convertLinkToAllVariants( $text ) {
3194 return $this->mConverter
->convertLinkToAllVariants( $text );
3198 * returns language specific options used by User::getPageRenderHash()
3199 * for example, the preferred language variant
3203 function getExtraHashOptions() {
3204 return $this->mConverter
->getExtraHashOptions();
3208 * For languages that support multiple variants, the title of an
3209 * article may be displayed differently in different variants. this
3210 * function returns the apporiate title defined in the body of the article.
3214 function getParsedTitle() {
3215 return $this->mConverter
->getParsedTitle();
3219 * Enclose a string with the "no conversion" tag. This is used by
3220 * various functions in the Parser
3222 * @param $text String: text to be tagged for no conversion
3223 * @param $noParse bool
3224 * @return string the tagged text
3226 function markNoConversion( $text, $noParse = false ) {
3227 return $this->mConverter
->markNoConversion( $text, $noParse );
3231 * A regular expression to match legal word-trailing characters
3232 * which should be merged onto a link of the form [[foo]]bar.
3236 function linkTrail() {
3237 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3243 function getLangObj() {
3248 * Get the RFC 3066 code for this language object
3252 function getCode() {
3253 return $this->mCode
;
3257 * @param $code string
3259 function setCode( $code ) {
3260 $this->mCode
= $code;
3264 * Get the name of a file for a certain language code
3265 * @param $prefix string Prepend this to the filename
3266 * @param $code string Language code
3267 * @param $suffix string Append this to the filename
3268 * @return string $prefix . $mangledCode . $suffix
3270 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3271 // Protect against path traversal
3272 if ( !Language
::isValidCode( $code )
3273 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3275 throw new MWException( "Invalid language code \"$code\"" );
3278 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3282 * Get the language code from a file name. Inverse of getFileName()
3283 * @param $filename string $prefix . $languageCode . $suffix
3284 * @param $prefix string Prefix before the language code
3285 * @param $suffix string Suffix after the language code
3286 * @return string Language code, or false if $prefix or $suffix isn't found
3288 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3290 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3291 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3292 if ( !count( $m ) ) {
3295 return str_replace( '_', '-', strtolower( $m[1] ) );
3299 * @param $code string
3302 static function getMessagesFileName( $code ) {
3304 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3308 * @param $code string
3311 static function getClassFileName( $code ) {
3313 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3317 * Get the first fallback for a given language.
3319 * @param $code string
3321 * @return false|string
3323 static function getFallbackFor( $code ) {
3324 if ( $code === 'en' ) {
3327 $fallbacks = self
::getFallbacksFor( $code );
3328 $first = array_shift( $fallbacks );
3334 * Get the ordered list of fallback languages.
3337 * @param $code string Language code
3340 static function getFallbacksFor( $code ) {
3341 if ( $code === 'en' ) {
3344 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3345 $v = array_map( 'trim', explode( ',', $v ) );
3346 if ( $v[count( $v ) - 1] !== 'en' ) {
3354 * Get all messages for a given language
3355 * WARNING: this may take a long time
3357 * @param $code string
3361 static function getMessagesFor( $code ) {
3362 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3366 * Get a message for a given language
3368 * @param $key string
3369 * @param $code string
3373 static function getMessageFor( $key, $code ) {
3374 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3381 function fixVariableInNamespace( $talk ) {
3382 if ( strpos( $talk, '$1' ) === false ) {
3386 global $wgMetaNamespace;
3387 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3389 # Allow grammar transformations
3390 # Allowing full message-style parsing would make simple requests
3391 # such as action=raw much more expensive than they need to be.
3392 # This will hopefully cover most cases.
3393 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3394 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3395 return str_replace( ' ', '_', $talk );
3402 function replaceGrammarInNamespace( $m ) {
3403 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3407 * @throws MWException
3410 static function getCaseMaps() {
3411 static $wikiUpperChars, $wikiLowerChars;
3412 if ( isset( $wikiUpperChars ) ) {
3413 return array( $wikiUpperChars, $wikiLowerChars );
3416 wfProfileIn( __METHOD__
);
3417 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3418 if ( $arr === false ) {
3419 throw new MWException(
3420 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3422 $wikiUpperChars = $arr['wikiUpperChars'];
3423 $wikiLowerChars = $arr['wikiLowerChars'];
3424 wfProfileOut( __METHOD__
);
3425 return array( $wikiUpperChars, $wikiLowerChars );
3429 * Decode an expiry (block, protection, etc) which has come from the DB
3431 * @param $expiry String: Database expiry String
3432 * @param $format Bool|Int true to process using language functions, or TS_ constant
3433 * to return the expiry in a given timestamp
3436 public function formatExpiry( $expiry, $format = true ) {
3437 static $infinity, $infinityMsg;
3438 if( $infinity === null ){
3439 $infinityMsg = wfMessage( 'infiniteblock' );
3440 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3443 if ( $expiry == '' ||
$expiry == $infinity ) {
3444 return $format === true
3448 return $format === true
3449 ?
$this->timeanddate( $expiry )
3450 : wfTimestamp( $format, $expiry );
3456 * @param $seconds int|float
3457 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3458 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3459 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3462 function formatTimePeriod( $seconds, $format = false ) {
3463 if ( round( $seconds * 10 ) < 100 ) {
3464 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3465 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3466 } elseif ( round( $seconds ) < 60 ) {
3467 $s = $this->formatNum( round( $seconds ) );
3468 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3469 } elseif ( round( $seconds ) < 3600 ) {
3470 $minutes = floor( $seconds / 60 );
3471 $secondsPart = round( fmod( $seconds, 60 ) );
3472 if ( $secondsPart == 60 ) {
3476 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3478 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3479 } elseif ( round( $seconds ) <= 2*86400 ) {
3480 $hours = floor( $seconds / 3600 );
3481 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3482 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3483 if ( $secondsPart == 60 ) {
3487 if ( $minutes == 60 ) {
3491 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3493 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3494 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3495 $s .= ' ' . $this->formatNum( $secondsPart ) .
3496 $this->getMessageFromDB( 'seconds-abbrev' );
3499 $days = floor( $seconds / 86400 );
3500 if ( $format === 'avoidminutes' ) {
3501 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3502 if ( $hours == 24 ) {
3506 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3508 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3509 } elseif ( $format === 'avoidseconds' ) {
3510 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3511 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3512 if ( $minutes == 60 ) {
3516 if ( $hours == 24 ) {
3520 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3522 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3524 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3526 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3528 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3538 function formatBitrate( $bps ) {
3539 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3541 return $this->formatNum( $bps ) . $units[0];
3543 $unitIndex = floor( log10( $bps ) / 3 );
3544 $mantissa = $bps / pow( 1000, $unitIndex );
3545 if ( $mantissa < 10 ) {
3546 $mantissa = round( $mantissa, 1 );
3548 $mantissa = round( $mantissa );
3550 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3554 * Format a size in bytes for output, using an appropriate
3555 * unit (B, KB, MB or GB) according to the magnitude in question
3557 * @param $size int Size to format
3558 * @return string Plain text (not HTML)
3560 function formatSize( $size ) {
3561 // For small sizes no decimal places necessary
3563 if ( $size > 1024 ) {
3564 $size = $size / 1024;
3565 if ( $size > 1024 ) {
3566 $size = $size / 1024;
3567 // For MB and bigger two decimal places are smarter
3569 if ( $size > 1024 ) {
3570 $size = $size / 1024;
3571 $msg = 'size-gigabytes';
3573 $msg = 'size-megabytes';
3576 $msg = 'size-kilobytes';
3579 $msg = 'size-bytes';
3581 $size = round( $size, $round );
3582 $text = $this->getMessageFromDB( $msg );
3583 return str_replace( '$1', $this->formatNum( $size ), $text );
3587 * Get the conversion rule title, if any.
3591 function getConvRuleTitle() {
3592 return $this->mConverter
->getConvRuleTitle();