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 ) {
152 static $recursionLevel = 0;
154 // Protect against path traversal below
155 if ( !Language
::isValidCode( $code )
156 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
158 throw new MWException( "Invalid language code \"$code\"" );
161 if ( !Language
::isValidBuiltInCode( $code ) ) {
162 // It's not possible to customise this code with class files, so
163 // just return a Language object. This is to support uselang= hacks.
164 $lang = new Language
;
165 $lang->setCode( $code );
169 if ( $code == 'en' ) {
172 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
173 if ( !defined( 'MW_COMPILED' ) ) {
174 // Preload base classes to work around APC/PHP5 bug
175 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
176 include_once( "$IP/languages/classes/$class.deps.php" );
178 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
179 include_once( "$IP/languages/classes/$class.php" );
184 if ( $recursionLevel > 5 ) {
185 throw new MWException( "Language fallback loop detected when creating class $class\n" );
188 if ( !MWInit
::classExists( $class ) ) {
189 $fallback = Language
::getFallbackFor( $code );
191 $lang = Language
::newFromCode( $fallback );
193 $lang->setCode( $code );
201 * Returns true if a language code string is of a valid form, whether or
202 * not it exists. This includes codes which are used solely for
203 * customisation via the MediaWiki namespace.
205 * @param $code string
209 public static function isValidCode( $code ) {
211 strcspn( $code, ":/\\\000" ) === strlen( $code )
212 && !preg_match( Title
::getTitleInvalidRegex(), $code );
216 * Returns true if a language code is of a valid form for the purposes of
217 * internal customisation of MediaWiki, via Messages*.php.
219 * @param $code string
223 public static function isValidBuiltInCode( $code ) {
224 return preg_match( '/^[a-z0-9-]*$/i', $code );
228 * Get the LocalisationCache instance
230 * @return LocalisationCache
232 public static function getLocalisationCache() {
233 if ( is_null( self
::$dataCache ) ) {
234 global $wgLocalisationCacheConf;
235 $class = $wgLocalisationCacheConf['class'];
236 self
::$dataCache = new $class( $wgLocalisationCacheConf );
238 return self
::$dataCache;
241 function __construct() {
242 $this->mConverter
= new FakeConverter( $this );
243 // Set the code to the name of the descendant
244 if ( get_class( $this ) == 'Language' ) {
247 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
249 self
::getLocalisationCache();
253 * Reduce memory usage
255 function __destruct() {
256 foreach ( $this as $name => $value ) {
257 unset( $this->$name );
262 * Hook which will be called if this is the content language.
263 * Descendants can use this to register hook functions or modify globals
265 function initContLang() { }
270 function getFallbackLanguageCode() {
271 if ( $this->mCode
=== 'en' ) {
274 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
279 * Exports $wgBookstoreListEn
282 function getBookstoreList() {
283 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
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;
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.
329 function getFormattedNamespaces() {
330 $ns = $this->getNamespaces();
331 foreach ( $ns as $k => $v ) {
332 $ns[$k] = strtr( $v, '_', ' ' );
338 * Get a namespace value by key
340 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
341 * echo $mw_ns; // prints 'MediaWiki'
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
357 * @param $index string
361 function getFormattedNsText( $index ) {
362 $ns = $this->getNsText( $index );
363 return strtr( $ns, '_', ' ' );
367 * Returns gender-dependent namespace alias if available.
368 * @param $index Int: namespace index
369 * @param $gender String: gender key (male, female... )
373 function getGenderNsText( $index, $gender ) {
374 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
375 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
379 * Whether this language makes distinguishes genders for example in
384 function needsGenderDistinction() {
385 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
386 return count( $aliases ) > 0;
390 * Get a namespace key by value, case insensitive.
391 * Only matches namespace names for the current language, not the
392 * canonical ones defined in Namespace.php.
394 * @param $text String
395 * @return mixed An integer if $text is a valid value otherwise false
397 function getLocalNsIndex( $text ) {
398 $lctext = $this->lc( $text );
399 $ids = $this->getNamespaceIds();
400 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
406 function getNamespaceAliases() {
407 if ( is_null( $this->namespaceAliases
) ) {
408 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
412 foreach ( $aliases as $name => $index ) {
413 if ( $index === NS_PROJECT_TALK
) {
414 unset( $aliases[$name] );
415 $name = $this->fixVariableInNamespace( $name );
416 $aliases[$name] = $index;
421 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
422 foreach ( $genders as $index => $forms ) {
423 foreach ( $forms as $alias ) {
424 $aliases[$alias] = $index;
428 $this->namespaceAliases
= $aliases;
430 return $this->namespaceAliases
;
436 function getNamespaceIds() {
437 if ( is_null( $this->mNamespaceIds
) ) {
438 global $wgNamespaceAliases;
439 # Put namespace names and aliases into a hashtable.
440 # If this is too slow, then we should arrange it so that it is done
441 # before caching. The catch is that at pre-cache time, the above
442 # class-specific fixup hasn't been done.
443 $this->mNamespaceIds
= array();
444 foreach ( $this->getNamespaces() as $index => $name ) {
445 $this->mNamespaceIds
[$this->lc( $name )] = $index;
447 foreach ( $this->getNamespaceAliases() as $name => $index ) {
448 $this->mNamespaceIds
[$this->lc( $name )] = $index;
450 if ( $wgNamespaceAliases ) {
451 foreach ( $wgNamespaceAliases as $name => $index ) {
452 $this->mNamespaceIds
[$this->lc( $name )] = $index;
456 return $this->mNamespaceIds
;
461 * Get a namespace key by value, case insensitive. Canonical namespace
462 * names override custom ones defined for the current language.
464 * @param $text String
465 * @return mixed An integer if $text is a valid value otherwise false
467 function getNsIndex( $text ) {
468 $lctext = $this->lc( $text );
469 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
472 $ids = $this->getNamespaceIds();
473 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
477 * short names for language variants used for language conversion links.
479 * @param $code String
482 function getVariantname( $code ) {
483 return $this->getMessageFromDB( "variantname-$code" );
487 * @param $name string
490 function specialPage( $name ) {
491 $aliases = $this->getSpecialPageAliases();
492 if ( isset( $aliases[$name][0] ) ) {
493 $name = $aliases[$name][0];
495 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
501 function getQuickbarSettings() {
503 $this->getMessage( 'qbsettings-none' ),
504 $this->getMessage( 'qbsettings-fixedleft' ),
505 $this->getMessage( 'qbsettings-fixedright' ),
506 $this->getMessage( 'qbsettings-floatingleft' ),
507 $this->getMessage( 'qbsettings-floatingright' )
514 function getDatePreferences() {
515 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
521 function getDateFormats() {
522 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
526 * @return array|string
528 function getDefaultDateFormat() {
529 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
530 if ( $df === 'dmy or mdy' ) {
531 global $wgAmericanDates;
532 return $wgAmericanDates ?
'mdy' : 'dmy';
541 function getDatePreferenceMigrationMap() {
542 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
549 function getImageFile( $image ) {
550 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
556 function getDefaultUserOptionOverrides() {
557 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
563 function getExtraUserToggles() {
564 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
571 function getUserToggle( $tog ) {
572 return $this->getMessageFromDB( "tog-$tog" );
576 * Get language names, indexed by code.
577 * If $customisedOnly is true, only returns codes with a messages file
579 * @param $customisedOnly bool
583 public static function getLanguageNames( $customisedOnly = false ) {
584 global $wgExtraLanguageNames;
585 static $coreLanguageNames;
587 if ( $coreLanguageNames === null ) {
588 include( MWInit
::compiledPath( 'languages/Names.php' ) );
591 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
592 if ( !$customisedOnly ) {
598 $dir = opendir( "$IP/languages/messages" );
599 while ( false !== ( $file = readdir( $dir ) ) ) {
600 $code = self
::getCodeFromFileName( $file, 'Messages' );
601 if ( $code && isset( $allNames[$code] ) ) {
602 $names[$code] = $allNames[$code];
610 * Get translated language names. This is done on best effort and
611 * by default this is exactly the same as Language::getLanguageNames.
612 * The CLDR extension provides translated names.
613 * @param $code String Language code.
614 * @return Array language code => language name
617 public static function getTranslatedLanguageNames( $code ) {
619 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
621 foreach ( self
::getLanguageNames() as $code => $name ) {
622 if ( !isset( $names[$code] ) ) $names[$code] = $name;
629 * Get a message from the MediaWiki namespace.
631 * @param $msg String: message name
634 function getMessageFromDB( $msg ) {
635 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
639 * @param $code string
642 function getLanguageName( $code ) {
643 $names = self
::getLanguageNames();
644 if ( !array_key_exists( $code, $names ) ) {
647 return $names[$code];
654 function getMonthName( $key ) {
655 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
661 function getMonthNamesArray() {
662 $monthNames = array( '' );
663 for ( $i=1; $i < 13; $i++
) {
664 $monthNames[] = $this->getMonthName( $i );
673 function getMonthNameGen( $key ) {
674 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
681 function getMonthAbbreviation( $key ) {
682 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
688 function getMonthAbbreviationsArray() {
689 $monthNames = array( '' );
690 for ( $i=1; $i < 13; $i++
) {
691 $monthNames[] = $this->getMonthAbbreviation( $i );
700 function getWeekdayName( $key ) {
701 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
708 function getWeekdayAbbreviation( $key ) {
709 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
716 function getIranianCalendarMonthName( $key ) {
717 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
724 function getHebrewCalendarMonthName( $key ) {
725 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
732 function getHebrewCalendarMonthNameGen( $key ) {
733 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
740 function getHijriCalendarMonthName( $key ) {
741 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
745 * Used by date() and time() to adjust the time output.
747 * @param $ts Int the time in date('YmdHis') format
748 * @param $tz Mixed: adjust the time by this amount (default false, mean we
749 * get user timecorrection setting)
752 function userAdjust( $ts, $tz = false ) {
753 global $wgUser, $wgLocalTZoffset;
755 if ( $tz === false ) {
756 $tz = $wgUser->getOption( 'timecorrection' );
759 $data = explode( '|', $tz, 3 );
761 if ( $data[0] == 'ZoneInfo' ) {
762 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
763 $date = date_create( $ts, timezone_open( 'UTC' ) );
764 date_timezone_set( $date, timezone_open( $data[2] ) );
765 $date = date_format( $date, 'YmdHis' );
768 # Unrecognized timezone, default to 'Offset' with the stored offset.
773 if ( $data[0] == 'System' ||
$tz == '' ) {
774 # Global offset in minutes.
775 if ( isset( $wgLocalTZoffset ) ) {
776 $minDiff = $wgLocalTZoffset;
778 } else if ( $data[0] == 'Offset' ) {
779 $minDiff = intval( $data[1] );
781 $data = explode( ':', $tz );
782 if ( count( $data ) == 2 ) {
783 $data[0] = intval( $data[0] );
784 $data[1] = intval( $data[1] );
785 $minDiff = abs( $data[0] ) * 60 +
$data[1];
786 if ( $data[0] < 0 ) {
787 $minDiff = -$minDiff;
790 $minDiff = intval( $data[0] ) * 60;
794 # No difference ? Return time unchanged
795 if ( 0 == $minDiff ) {
799 wfSuppressWarnings(); // E_STRICT system time bitching
800 # Generate an adjusted date; take advantage of the fact that mktime
801 # will normalize out-of-range values so we don't have to split $minDiff
802 # into hours and minutes.
804 (int)substr( $ts, 8, 2 ) ), # Hours
805 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
806 (int)substr( $ts, 12, 2 ), # Seconds
807 (int)substr( $ts, 4, 2 ), # Month
808 (int)substr( $ts, 6, 2 ), # Day
809 (int)substr( $ts, 0, 4 ) ); # Year
811 $date = date( 'YmdHis', $t );
818 * This is a workalike of PHP's date() function, but with better
819 * internationalisation, a reduced set of format characters, and a better
822 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
823 * PHP manual for definitions. There are a number of extensions, which
826 * xn Do not translate digits of the next numeric format character
827 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
828 * xr Use roman numerals for the next numeric format character
829 * xh Use hebrew numerals for the next numeric format character
831 * xg Genitive month name
833 * xij j (day number) in Iranian calendar
834 * xiF F (month name) in Iranian calendar
835 * xin n (month number) in Iranian calendar
836 * xiY Y (full year) in Iranian calendar
838 * xjj j (day number) in Hebrew calendar
839 * xjF F (month name) in Hebrew calendar
840 * xjt t (days in month) in Hebrew calendar
841 * xjx xg (genitive month name) in Hebrew calendar
842 * xjn n (month number) in Hebrew calendar
843 * xjY Y (full year) in Hebrew calendar
845 * xmj j (day number) in Hijri calendar
846 * xmF F (month name) in Hijri calendar
847 * xmn n (month number) in Hijri calendar
848 * xmY Y (full year) in Hijri calendar
850 * xkY Y (full year) in Thai solar calendar. Months and days are
851 * identical to the Gregorian calendar
852 * xoY Y (full year) in Minguo calendar or Juche year.
853 * Months and days are identical to the
855 * xtY Y (full year) in Japanese nengo. Months and days are
856 * identical to the Gregorian calendar
858 * Characters enclosed in double quotes will be considered literal (with
859 * the quotes themselves removed). Unmatched quotes will be considered
860 * literal quotes. Example:
862 * "The month is" F => The month is January
865 * Backslash escaping is also supported.
867 * Input timestamp is assumed to be pre-normalized to the desired local
870 * @param $format String
871 * @param $ts String: 14-character timestamp
874 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
878 function sprintfDate( $format, $ts ) {
891 for ( $p = 0; $p < strlen( $format ); $p++
) {
894 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
895 $code .= $format[++
$p];
898 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
899 $code .= $format[++
$p];
910 $rawToggle = !$rawToggle;
919 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
922 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
923 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
926 $num = substr( $ts, 6, 2 );
929 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
930 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
933 $num = intval( substr( $ts, 6, 2 ) );
937 $iranian = self
::tsToIranian( $ts );
943 $hijri = self
::tsToHijri( $ts );
949 $hebrew = self
::tsToHebrew( $ts );
955 $unix = wfTimestamp( TS_UNIX
, $ts );
957 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
961 $unix = wfTimestamp( TS_UNIX
, $ts );
963 $w = gmdate( 'w', $unix );
968 $unix = wfTimestamp( TS_UNIX
, $ts );
970 $num = gmdate( 'w', $unix );
974 $unix = wfTimestamp( TS_UNIX
, $ts );
976 $num = gmdate( 'z', $unix );
980 $unix = wfTimestamp( TS_UNIX
, $ts );
982 $num = gmdate( 'W', $unix );
985 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
989 $iranian = self
::tsToIranian( $ts );
991 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
995 $hijri = self
::tsToHijri( $ts );
997 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1001 $hebrew = self
::tsToHebrew( $ts );
1003 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1006 $num = substr( $ts, 4, 2 );
1009 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1012 $num = intval( substr( $ts, 4, 2 ) );
1016 $iranian = self
::tsToIranian( $ts );
1022 $hijri = self
::tsToHijri ( $ts );
1028 $hebrew = self
::tsToHebrew( $ts );
1034 $unix = wfTimestamp( TS_UNIX
, $ts );
1036 $num = gmdate( 't', $unix );
1040 $hebrew = self
::tsToHebrew( $ts );
1046 $unix = wfTimestamp( TS_UNIX
, $ts );
1048 $num = gmdate( 'L', $unix );
1052 $unix = wfTimestamp( TS_UNIX
, $ts );
1054 $num = date( 'o', $unix );
1057 $num = substr( $ts, 0, 4 );
1061 $iranian = self
::tsToIranian( $ts );
1067 $hijri = self
::tsToHijri( $ts );
1073 $hebrew = self
::tsToHebrew( $ts );
1079 $thai = self
::tsToYear( $ts, 'thai' );
1085 $minguo = self
::tsToYear( $ts, 'minguo' );
1091 $tenno = self
::tsToYear( $ts, 'tenno' );
1096 $num = substr( $ts, 2, 2 );
1099 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1102 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1105 $h = substr( $ts, 8, 2 );
1106 $num = $h %
12 ?
$h %
12 : 12;
1109 $num = intval( substr( $ts, 8, 2 ) );
1112 $h = substr( $ts, 8, 2 );
1113 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1116 $num = substr( $ts, 8, 2 );
1119 $num = substr( $ts, 10, 2 );
1122 $num = substr( $ts, 12, 2 );
1126 $unix = wfTimestamp( TS_UNIX
, $ts );
1128 $s .= gmdate( 'c', $unix );
1132 $unix = wfTimestamp( TS_UNIX
, $ts );
1134 $s .= gmdate( 'r', $unix );
1138 $unix = wfTimestamp( TS_UNIX
, $ts );
1143 # Backslash escaping
1144 if ( $p < strlen( $format ) - 1 ) {
1145 $s .= $format[++
$p];
1152 if ( $p < strlen( $format ) - 1 ) {
1153 $endQuote = strpos( $format, '"', $p +
1 );
1154 if ( $endQuote === false ) {
1155 # No terminating quote, assume literal "
1158 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1162 # Quote at end of string, assume literal "
1169 if ( $num !== false ) {
1170 if ( $rawToggle ||
$raw ) {
1173 } elseif ( $roman ) {
1174 $s .= self
::romanNumeral( $num );
1176 } elseif ( $hebrewNum ) {
1177 $s .= self
::hebrewNumeral( $num );
1180 $s .= $this->formatNum( $num, true );
1187 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1188 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1191 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1192 * Gregorian dates to Iranian dates. Originally written in C, it
1193 * is released under the terms of GNU Lesser General Public
1194 * License. Conversion to PHP was performed by Niklas Laxström.
1196 * Link: http://www.farsiweb.info/jalali/jalali.c
1202 private static function tsToIranian( $ts ) {
1203 $gy = substr( $ts, 0, 4 ) -1600;
1204 $gm = substr( $ts, 4, 2 ) -1;
1205 $gd = (int)substr( $ts, 6, 2 ) -1;
1207 # Days passed from the beginning (including leap years)
1209 +
floor( ( $gy +
3 ) / 4 )
1210 - floor( ( $gy +
99 ) / 100 )
1211 +
floor( ( $gy +
399 ) / 400 );
1214 // Add days of the past months of this year
1215 for ( $i = 0; $i < $gm; $i++
) {
1216 $gDayNo +
= self
::$GREG_DAYS[$i];
1220 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1224 // Days passed in current month
1227 $jDayNo = $gDayNo - 79;
1229 $jNp = floor( $jDayNo / 12053 );
1232 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1235 if ( $jDayNo >= 366 ) {
1236 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1237 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1240 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1241 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1247 return array( $jy, $jm, $jd );
1251 * Converting Gregorian dates to Hijri dates.
1253 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1255 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1261 private static function tsToHijri( $ts ) {
1262 $year = substr( $ts, 0, 4 );
1263 $month = substr( $ts, 4, 2 );
1264 $day = substr( $ts, 6, 2 );
1272 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1273 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1276 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1277 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1278 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1281 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1282 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1285 $zl = $zjd -1948440 +
10632;
1286 $zn = (int)( ( $zl - 1 ) / 10631 );
1287 $zl = $zl - 10631 * $zn +
354;
1288 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1289 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1290 $zm = (int)( ( 24 * $zl ) / 709 );
1291 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1292 $zy = 30 * $zn +
$zj - 30;
1294 return array( $zy, $zm, $zd );
1298 * Converting Gregorian dates to Hebrew dates.
1300 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1301 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1302 * to translate the relevant functions into PHP and release them under
1305 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1306 * and Adar II is 14. In a non-leap year, Adar is 6.
1312 private static function tsToHebrew( $ts ) {
1314 $year = substr( $ts, 0, 4 );
1315 $month = substr( $ts, 4, 2 );
1316 $day = substr( $ts, 6, 2 );
1318 # Calculate Hebrew year
1319 $hebrewYear = $year +
3760;
1321 # Month number when September = 1, August = 12
1323 if ( $month > 12 ) {
1330 # Calculate day of year from 1 September
1332 for ( $i = 1; $i < $month; $i++
) {
1336 # Check if the year is leap
1337 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1340 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1347 # Calculate the start of the Hebrew year
1348 $start = self
::hebrewYearStart( $hebrewYear );
1350 # Calculate next year's start
1351 if ( $dayOfYear <= $start ) {
1352 # Day is before the start of the year - it is the previous year
1354 $nextStart = $start;
1358 # Add days since previous year's 1 September
1360 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1364 # Start of the new (previous) year
1365 $start = self
::hebrewYearStart( $hebrewYear );
1368 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1371 # Calculate Hebrew day of year
1372 $hebrewDayOfYear = $dayOfYear - $start;
1374 # Difference between year's days
1375 $diff = $nextStart - $start;
1376 # Add 12 (or 13 for leap years) days to ignore the difference between
1377 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1378 # difference is only about the year type
1379 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1385 # Check the year pattern, and is leap year
1386 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1387 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1388 # and non-leap years
1389 $yearPattern = $diff %
30;
1390 # Check if leap year
1391 $isLeap = $diff >= 30;
1393 # Calculate day in the month from number of day in the Hebrew year
1394 # Don't check Adar - if the day is not in Adar, we will stop before;
1395 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1396 $hebrewDay = $hebrewDayOfYear;
1399 while ( $hebrewMonth <= 12 ) {
1400 # Calculate days in this month
1401 if ( $isLeap && $hebrewMonth == 6 ) {
1402 # Adar in a leap year
1404 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1406 if ( $hebrewDay <= $days ) {
1410 # Subtract the days of Adar I
1411 $hebrewDay -= $days;
1414 if ( $hebrewDay <= $days ) {
1420 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1421 # Cheshvan in a complete year (otherwise as the rule below)
1423 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1424 # Kislev in an incomplete year (otherwise as the rule below)
1427 # Odd months have 30 days, even have 29
1428 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1430 if ( $hebrewDay <= $days ) {
1431 # In the current month
1434 # Subtract the days of the current month
1435 $hebrewDay -= $days;
1436 # Try in the next month
1441 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1445 * This calculates the Hebrew year start, as days since 1 September.
1446 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1447 * Used for Hebrew date.
1453 private static function hebrewYearStart( $year ) {
1454 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1455 $b = intval( ( $year - 1 ) %
4 );
1456 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1460 $Mar = intval( $m );
1466 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1467 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1469 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1471 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1475 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1480 * Algorithm to convert Gregorian dates to Thai solar dates,
1481 * Minguo dates or Minguo dates.
1483 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1484 * http://en.wikipedia.org/wiki/Minguo_calendar
1485 * http://en.wikipedia.org/wiki/Japanese_era_name
1487 * @param $ts String: 14-character timestamp
1488 * @param $cName String: calender name
1489 * @return Array: converted year, month, day
1491 private static function tsToYear( $ts, $cName ) {
1492 $gy = substr( $ts, 0, 4 );
1493 $gm = substr( $ts, 4, 2 );
1494 $gd = substr( $ts, 6, 2 );
1496 if ( !strcmp( $cName, 'thai' ) ) {
1498 # Add 543 years to the Gregorian calendar
1499 # Months and days are identical
1500 $gy_offset = $gy +
543;
1501 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1503 # Deduct 1911 years from the Gregorian calendar
1504 # Months and days are identical
1505 $gy_offset = $gy - 1911;
1506 } else if ( !strcmp( $cName, 'tenno' ) ) {
1507 # Nengō dates up to Meiji period
1508 # Deduct years from the Gregorian calendar
1509 # depending on the nengo periods
1510 # Months and days are identical
1511 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1513 $gy_gannen = $gy - 1868 +
1;
1514 $gy_offset = $gy_gannen;
1515 if ( $gy_gannen == 1 ) {
1518 $gy_offset = '明治' . $gy_offset;
1520 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1521 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1522 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1523 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1524 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1528 $gy_gannen = $gy - 1912 +
1;
1529 $gy_offset = $gy_gannen;
1530 if ( $gy_gannen == 1 ) {
1533 $gy_offset = '大正' . $gy_offset;
1535 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1536 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1537 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1541 $gy_gannen = $gy - 1926 +
1;
1542 $gy_offset = $gy_gannen;
1543 if ( $gy_gannen == 1 ) {
1546 $gy_offset = '昭和' . $gy_offset;
1549 $gy_gannen = $gy - 1989 +
1;
1550 $gy_offset = $gy_gannen;
1551 if ( $gy_gannen == 1 ) {
1554 $gy_offset = '平成' . $gy_offset;
1560 return array( $gy_offset, $gm, $gd );
1564 * Roman number formatting up to 3000
1570 static function romanNumeral( $num ) {
1571 static $table = array(
1572 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1573 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1574 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1575 array( '', 'M', 'MM', 'MMM' )
1578 $num = intval( $num );
1579 if ( $num > 3000 ||
$num <= 0 ) {
1584 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1585 if ( $num >= $pow10 ) {
1586 $s .= $table[$i][floor( $num / $pow10 )];
1588 $num = $num %
$pow10;
1594 * Hebrew Gematria number formatting up to 9999
1600 static function hebrewNumeral( $num ) {
1601 static $table = array(
1602 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1603 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1604 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1605 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1608 $num = intval( $num );
1609 if ( $num > 9999 ||
$num <= 0 ) {
1614 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1615 if ( $num >= $pow10 ) {
1616 if ( $num == 15 ||
$num == 16 ) {
1617 $s .= $table[0][9] . $table[0][$num - 9];
1620 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1621 if ( $pow10 == 1000 ) {
1626 $num = $num %
$pow10;
1628 if ( strlen( $s ) == 2 ) {
1631 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1632 $str .= substr( $s, strlen( $s ) - 2, 2 );
1634 $start = substr( $str, 0, strlen( $str ) - 2 );
1635 $end = substr( $str, strlen( $str ) - 2 );
1638 $str = $start . 'ך';
1641 $str = $start . 'ם';
1644 $str = $start . 'ן';
1647 $str = $start . 'ף';
1650 $str = $start . 'ץ';
1657 * This is meant to be used by time(), date(), and timeanddate() to get
1658 * the date preference they're supposed to use, it should be used in
1662 * function timeanddate([...], $format = true) {
1663 * $datePreference = $this->dateFormat($format);
1668 * @param $usePrefs Mixed: if true, the user's preference is used
1669 * if false, the site/language default is used
1670 * if int/string, assumed to be a format.
1673 function dateFormat( $usePrefs = true ) {
1676 if ( is_bool( $usePrefs ) ) {
1678 $datePreference = $wgUser->getDatePreference();
1680 $datePreference = (string)User
::getDefaultOption( 'date' );
1683 $datePreference = (string)$usePrefs;
1687 if ( $datePreference == '' ) {
1691 return $datePreference;
1695 * Get a format string for a given type and preference
1696 * @param $type string May be date, time or both
1697 * @param $pref string The format name as it appears in Messages*.php
1701 function getDateFormatString( $type, $pref ) {
1702 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1703 if ( $pref == 'default' ) {
1704 $pref = $this->getDefaultDateFormat();
1705 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1707 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1708 if ( is_null( $df ) ) {
1709 $pref = $this->getDefaultDateFormat();
1710 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1713 $this->dateFormatStrings
[$type][$pref] = $df;
1715 return $this->dateFormatStrings
[$type][$pref];
1719 * @param $ts Mixed: the time format which needs to be turned into a
1720 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1721 * @param $adj Bool: whether to adjust the time output according to the
1722 * user configured offset ($timecorrection)
1723 * @param $format Mixed: true to use user's date format preference
1724 * @param $timecorrection String|bool the time offset as returned by
1725 * validateTimeZone() in Special:Preferences
1728 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1729 $ts = wfTimestamp( TS_MW
, $ts );
1731 $ts = $this->userAdjust( $ts, $timecorrection );
1733 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1734 return $this->sprintfDate( $df, $ts );
1738 * @param $ts Mixed: the time format which needs to be turned into a
1739 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1740 * @param $adj Bool: whether to adjust the time output according to the
1741 * user configured offset ($timecorrection)
1742 * @param $format Mixed: true to use user's date format preference
1743 * @param $timecorrection String|bool the time offset as returned by
1744 * validateTimeZone() in Special:Preferences
1747 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1748 $ts = wfTimestamp( TS_MW
, $ts );
1750 $ts = $this->userAdjust( $ts, $timecorrection );
1752 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1753 return $this->sprintfDate( $df, $ts );
1757 * @param $ts Mixed: the time format which needs to be turned into a
1758 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1759 * @param $adj Bool: whether to adjust the time output according to the
1760 * user configured offset ($timecorrection)
1761 * @param $format Mixed: what format to return, if it's false output the
1762 * default one (default true)
1763 * @param $timecorrection String|bool the time offset as returned by
1764 * validateTimeZone() in Special:Preferences
1767 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1768 $ts = wfTimestamp( TS_MW
, $ts );
1770 $ts = $this->userAdjust( $ts, $timecorrection );
1772 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1773 return $this->sprintfDate( $df, $ts );
1777 * @param $key string
1778 * @return array|null
1780 function getMessage( $key ) {
1781 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1787 function getAllMessages() {
1788 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1797 function iconv( $in, $out, $string ) {
1798 # This is a wrapper for iconv in all languages except esperanto,
1799 # which does some nasty x-conversions beforehand
1801 # Even with //IGNORE iconv can whine about illegal characters in
1802 # *input* string. We just ignore those too.
1803 # REF: http://bugs.php.net/bug.php?id=37166
1804 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1805 wfSuppressWarnings();
1806 $text = iconv( $in, $out . '//IGNORE', $string );
1807 wfRestoreWarnings();
1811 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1814 * @param $matches array
1815 * @return mixed|string
1817 function ucwordbreaksCallbackAscii( $matches ) {
1818 return $this->ucfirst( $matches[1] );
1822 * @param $matches array
1825 function ucwordbreaksCallbackMB( $matches ) {
1826 return mb_strtoupper( $matches[0] );
1830 * @param $matches array
1833 function ucCallback( $matches ) {
1834 list( $wikiUpperChars ) = self
::getCaseMaps();
1835 return strtr( $matches[1], $wikiUpperChars );
1839 * @param $matches array
1842 function lcCallback( $matches ) {
1843 list( , $wikiLowerChars ) = self
::getCaseMaps();
1844 return strtr( $matches[1], $wikiLowerChars );
1848 * @param $matches array
1851 function ucwordsCallbackMB( $matches ) {
1852 return mb_strtoupper( $matches[0] );
1856 * @param $matches array
1859 function ucwordsCallbackWiki( $matches ) {
1860 list( $wikiUpperChars ) = self
::getCaseMaps();
1861 return strtr( $matches[0], $wikiUpperChars );
1865 * Make a string's first character uppercase
1867 * @param $str string
1871 function ucfirst( $str ) {
1873 if ( $o < 96 ) { // if already uppercase...
1875 } elseif ( $o < 128 ) {
1876 return ucfirst( $str ); // use PHP's ucfirst()
1878 // fall back to more complex logic in case of multibyte strings
1879 return $this->uc( $str, true );
1884 * Convert a string to uppercase
1886 * @param $str string
1887 * @param $first bool
1891 function uc( $str, $first = false ) {
1892 if ( function_exists( 'mb_strtoupper' ) ) {
1894 if ( $this->isMultibyte( $str ) ) {
1895 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1897 return ucfirst( $str );
1900 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1903 if ( $this->isMultibyte( $str ) ) {
1904 $x = $first ?
'^' : '';
1905 return preg_replace_callback(
1906 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1907 array( $this, 'ucCallback' ),
1911 return $first ?
ucfirst( $str ) : strtoupper( $str );
1917 * @param $str string
1918 * @return mixed|string
1920 function lcfirst( $str ) {
1923 return strval( $str );
1924 } elseif ( $o >= 128 ) {
1925 return $this->lc( $str, true );
1926 } elseif ( $o > 96 ) {
1929 $str[0] = strtolower( $str[0] );
1935 * @param $str string
1936 * @param $first bool
1937 * @return mixed|string
1939 function lc( $str, $first = false ) {
1940 if ( function_exists( 'mb_strtolower' ) ) {
1942 if ( $this->isMultibyte( $str ) ) {
1943 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1945 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1948 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1951 if ( $this->isMultibyte( $str ) ) {
1952 $x = $first ?
'^' : '';
1953 return preg_replace_callback(
1954 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1955 array( $this, 'lcCallback' ),
1959 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1965 * @param $str string
1968 function isMultibyte( $str ) {
1969 return (bool)preg_match( '/[\x80-\xff]/', $str );
1973 * @param $str string
1974 * @return mixed|string
1976 function ucwords( $str ) {
1977 if ( $this->isMultibyte( $str ) ) {
1978 $str = $this->lc( $str );
1980 // regexp to find first letter in each word (i.e. after each space)
1981 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1983 // function to use to capitalize a single char
1984 if ( function_exists( 'mb_strtoupper' ) ) {
1985 return preg_replace_callback(
1987 array( $this, 'ucwordsCallbackMB' ),
1991 return preg_replace_callback(
1993 array( $this, 'ucwordsCallbackWiki' ),
1998 return ucwords( strtolower( $str ) );
2003 * capitalize words at word breaks
2005 * @param $str string
2008 function ucwordbreaks( $str ) {
2009 if ( $this->isMultibyte( $str ) ) {
2010 $str = $this->lc( $str );
2012 // since \b doesn't work for UTF-8, we explicitely define word break chars
2013 $breaks = "[ \-\(\)\}\{\.,\?!]";
2015 // find first letter after word break
2016 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2018 if ( function_exists( 'mb_strtoupper' ) ) {
2019 return preg_replace_callback(
2021 array( $this, 'ucwordbreaksCallbackMB' ),
2025 return preg_replace_callback(
2027 array( $this, 'ucwordsCallbackWiki' ),
2032 return preg_replace_callback(
2033 '/\b([\w\x80-\xff]+)\b/',
2034 array( $this, 'ucwordbreaksCallbackAscii' ),
2041 * Return a case-folded representation of $s
2043 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2044 * and $s2 are the same except for the case of their characters. It is not
2045 * necessary for the value returned to make sense when displayed.
2047 * Do *not* perform any other normalisation in this function. If a caller
2048 * uses this function when it should be using a more general normalisation
2049 * function, then fix the caller.
2055 function caseFold( $s ) {
2056 return $this->uc( $s );
2063 function checkTitleEncoding( $s ) {
2064 if ( is_array( $s ) ) {
2065 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2067 # Check for non-UTF-8 URLs
2068 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2073 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2074 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2079 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2085 function fallback8bitEncoding() {
2086 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2090 * Most writing systems use whitespace to break up words.
2091 * Some languages such as Chinese don't conventionally do this,
2092 * which requires special handling when breaking up words for
2097 function hasWordBreaks() {
2102 * Some languages such as Chinese require word segmentation,
2103 * Specify such segmentation when overridden in derived class.
2105 * @param $string String
2108 function segmentByWord( $string ) {
2113 * Some languages have special punctuation need to be normalized.
2114 * Make such changes here.
2116 * @param $string String
2119 function normalizeForSearch( $string ) {
2120 return self
::convertDoubleWidth( $string );
2124 * convert double-width roman characters to single-width.
2125 * range: ff00-ff5f ~= 0020-007f
2127 * @param $string string
2131 protected static function convertDoubleWidth( $string ) {
2132 static $full = null;
2133 static $half = null;
2135 if ( $full === null ) {
2136 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2137 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2138 $full = str_split( $fullWidth, 3 );
2139 $half = str_split( $halfWidth );
2142 $string = str_replace( $full, $half, $string );
2147 * @param $string string
2148 * @param $pattern string
2151 protected static function insertSpace( $string, $pattern ) {
2152 $string = preg_replace( $pattern, " $1 ", $string );
2153 $string = preg_replace( '/ +/', ' ', $string );
2158 * @param $termsArray array
2161 function convertForSearchResult( $termsArray ) {
2162 # some languages, e.g. Chinese, need to do a conversion
2163 # in order for search results to be displayed correctly
2168 * Get the first character of a string.
2173 function firstChar( $s ) {
2176 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2177 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2182 if ( isset( $matches[1] ) ) {
2183 if ( strlen( $matches[1] ) != 3 ) {
2187 // Break down Hangul syllables to grab the first jamo
2188 $code = utf8ToCodepoint( $matches[1] );
2189 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2191 } elseif ( $code < 0xb098 ) {
2192 return "\xe3\x84\xb1";
2193 } elseif ( $code < 0xb2e4 ) {
2194 return "\xe3\x84\xb4";
2195 } elseif ( $code < 0xb77c ) {
2196 return "\xe3\x84\xb7";
2197 } elseif ( $code < 0xb9c8 ) {
2198 return "\xe3\x84\xb9";
2199 } elseif ( $code < 0xbc14 ) {
2200 return "\xe3\x85\x81";
2201 } elseif ( $code < 0xc0ac ) {
2202 return "\xe3\x85\x82";
2203 } elseif ( $code < 0xc544 ) {
2204 return "\xe3\x85\x85";
2205 } elseif ( $code < 0xc790 ) {
2206 return "\xe3\x85\x87";
2207 } elseif ( $code < 0xcc28 ) {
2208 return "\xe3\x85\x88";
2209 } elseif ( $code < 0xce74 ) {
2210 return "\xe3\x85\x8a";
2211 } elseif ( $code < 0xd0c0 ) {
2212 return "\xe3\x85\x8b";
2213 } elseif ( $code < 0xd30c ) {
2214 return "\xe3\x85\x8c";
2215 } elseif ( $code < 0xd558 ) {
2216 return "\xe3\x85\x8d";
2218 return "\xe3\x85\x8e";
2225 function initEncoding() {
2226 # Some languages may have an alternate char encoding option
2227 # (Esperanto X-coding, Japanese furigana conversion, etc)
2228 # If this language is used as the primary content language,
2229 # an override to the defaults can be set here on startup.
2236 function recodeForEdit( $s ) {
2237 # For some languages we'll want to explicitly specify
2238 # which characters make it into the edit box raw
2239 # or are converted in some way or another.
2240 global $wgEditEncoding;
2241 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2244 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2252 function recodeInput( $s ) {
2253 # Take the previous into account.
2254 global $wgEditEncoding;
2255 if ( $wgEditEncoding != '' ) {
2256 $enc = $wgEditEncoding;
2260 if ( $enc == 'UTF-8' ) {
2263 return $this->iconv( $enc, 'UTF-8', $s );
2268 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2269 * also cleans up certain backwards-compatible sequences, converting them
2270 * to the modern Unicode equivalent.
2272 * This is language-specific for performance reasons only.
2278 function normalize( $s ) {
2279 global $wgAllUnicodeFixes;
2280 $s = UtfNormal
::cleanUp( $s );
2281 if ( $wgAllUnicodeFixes ) {
2282 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2283 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2290 * Transform a string using serialized data stored in the given file (which
2291 * must be in the serialized subdirectory of $IP). The file contains pairs
2292 * mapping source characters to destination characters.
2294 * The data is cached in process memory. This will go faster if you have the
2295 * FastStringSearch extension.
2297 * @param $file string
2298 * @param $string string
2302 function transformUsingPairFile( $file, $string ) {
2303 if ( !isset( $this->transformData
[$file] ) ) {
2304 $data = wfGetPrecompiledData( $file );
2305 if ( $data === false ) {
2306 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2308 $this->transformData
[$file] = new ReplacementArray( $data );
2310 return $this->transformData
[$file]->replace( $string );
2314 * For right-to-left language support
2319 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2323 * Return the correct HTML 'dir' attribute value for this language.
2327 return $this->isRTL() ?
'rtl' : 'ltr';
2331 * Return 'left' or 'right' as appropriate alignment for line-start
2332 * for this language's text direction.
2334 * Should be equivalent to CSS3 'start' text-align value....
2338 function alignStart() {
2339 return $this->isRTL() ?
'right' : 'left';
2343 * Return 'right' or 'left' as appropriate alignment for line-end
2344 * for this language's text direction.
2346 * Should be equivalent to CSS3 'end' text-align value....
2350 function alignEnd() {
2351 return $this->isRTL() ?
'left' : 'right';
2355 * A hidden direction mark (LRM or RLM), depending on the language direction
2359 function getDirMark() {
2360 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2366 function capitalizeAllNouns() {
2367 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2371 * An arrow, depending on the language direction
2375 function getArrow() {
2376 return $this->isRTL() ?
'←' : '→';
2380 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2384 function linkPrefixExtension() {
2385 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2391 function getMagicWords() {
2392 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2395 protected function doMagicHook() {
2396 if ( $this->mMagicHookDone
) {
2399 $this->mMagicHookDone
= true;
2400 wfProfileIn( 'LanguageGetMagic' );
2401 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2402 wfProfileOut( 'LanguageGetMagic' );
2406 * Fill a MagicWord object with data from here
2410 function getMagic( $mw ) {
2411 $this->doMagicHook();
2413 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2414 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2416 $magicWords = $this->getMagicWords();
2417 if ( isset( $magicWords[$mw->mId
] ) ) {
2418 $rawEntry = $magicWords[$mw->mId
];
2424 if ( !is_array( $rawEntry ) ) {
2425 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2427 $mw->mCaseSensitive
= $rawEntry[0];
2428 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2433 * Add magic words to the extension array
2435 * @param $newWords array
2437 function addMagicWordsByLang( $newWords ) {
2438 $code = $this->getCode();
2439 $fallbackChain = array();
2440 while ( $code && !in_array( $code, $fallbackChain ) ) {
2441 $fallbackChain[] = $code;
2442 $code = self
::getFallbackFor( $code );
2444 if ( !in_array( 'en', $fallbackChain ) ) {
2445 $fallbackChain[] = 'en';
2447 $fallbackChain = array_reverse( $fallbackChain );
2448 foreach ( $fallbackChain as $code ) {
2449 if ( isset( $newWords[$code] ) ) {
2450 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2456 * Get special page names, as an associative array
2457 * case folded alias => real name
2459 function getSpecialPageAliases() {
2460 // Cache aliases because it may be slow to load them
2461 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2463 $this->mExtendedSpecialPageAliases
=
2464 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2465 wfRunHooks( 'LanguageGetSpecialPageAliases',
2466 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2469 return $this->mExtendedSpecialPageAliases
;
2473 * Italic is unsuitable for some languages
2475 * @param $text String: the text to be emphasized.
2478 function emphasize( $text ) {
2479 return "<em>$text</em>";
2483 * Normally we output all numbers in plain en_US style, that is
2484 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2485 * point twohundredthirtyfive. However this is not sutable for all
2486 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2487 * Icelandic just want to use commas instead of dots, and dots instead
2488 * of commas like "293.291,235".
2490 * An example of this function being called:
2492 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2495 * See LanguageGu.php for the Gujarati implementation and
2496 * $separatorTransformTable on MessageIs.php for
2497 * the , => . and . => , implementation.
2499 * @todo check if it's viable to use localeconv() for the decimal
2501 * @param $number Mixed: the string to be formatted, should be an integer
2502 * or a floating point number.
2503 * @param $nocommafy Bool: set to true for special numbers like dates
2506 function formatNum( $number, $nocommafy = false ) {
2507 global $wgTranslateNumerals;
2508 if ( !$nocommafy ) {
2509 $number = $this->commafy( $number );
2510 $s = $this->separatorTransformTable();
2512 $number = strtr( $number, $s );
2516 if ( $wgTranslateNumerals ) {
2517 $s = $this->digitTransformTable();
2519 $number = strtr( $number, $s );
2527 * @param $number string
2530 function parseFormattedNumber( $number ) {
2531 $s = $this->digitTransformTable();
2533 $number = strtr( $number, array_flip( $s ) );
2536 $s = $this->separatorTransformTable();
2538 $number = strtr( $number, array_flip( $s ) );
2541 $number = strtr( $number, array( ',' => '' ) );
2546 * Adds commas to a given number
2551 function commafy( $_ ) {
2552 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2558 function digitTransformTable() {
2559 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2565 function separatorTransformTable() {
2566 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2570 * Take a list of strings and build a locale-friendly comma-separated
2571 * list, using the local comma-separator message.
2572 * The last two strings are chained with an "and".
2577 function listToText( $l ) {
2579 $m = count( $l ) - 1;
2581 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2583 for ( $i = $m; $i >= 0; $i-- ) {
2586 } else if ( $i == $m - 1 ) {
2587 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2589 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2597 * Take a list of strings and build a locale-friendly comma-separated
2598 * list, using the local comma-separator message.
2599 * @param $list array of strings to put in a comma list
2602 function commaList( $list ) {
2607 array( 'parsemag', 'escapenoentities', 'language' => $this )
2613 * Take a list of strings and build a locale-friendly semicolon-separated
2614 * list, using the local semicolon-separator message.
2615 * @param $list array of strings to put in a semicolon list
2618 function semicolonList( $list ) {
2622 'semicolon-separator',
2623 array( 'parsemag', 'escapenoentities', 'language' => $this )
2629 * Same as commaList, but separate it with the pipe instead.
2630 * @param $list array of strings to put in a pipe list
2633 function pipeList( $list ) {
2638 array( 'escapenoentities', 'language' => $this )
2644 * Truncate a string to a specified length in bytes, appending an optional
2645 * string (e.g. for ellipses)
2647 * The database offers limited byte lengths for some columns in the database;
2648 * multi-byte character sets mean we need to ensure that only whole characters
2649 * are included, otherwise broken characters can be passed to the user
2651 * If $length is negative, the string will be truncated from the beginning
2653 * @param $string String to truncate
2654 * @param $length Int: maximum length (including ellipses)
2655 * @param $ellipsis String to append to the truncated text
2656 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2657 * $adjustLength was introduced in 1.18, before that behaved as if false.
2660 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2661 # Use the localized ellipsis character
2662 if ( $ellipsis == '...' ) {
2663 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2665 # Check if there is no need to truncate
2666 if ( $length == 0 ) {
2667 return $ellipsis; // convention
2668 } elseif ( strlen( $string ) <= abs( $length ) ) {
2669 return $string; // no need to truncate
2671 $stringOriginal = $string;
2672 # If ellipsis length is >= $length then we can't apply $adjustLength
2673 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2674 $string = $ellipsis; // this can be slightly unexpected
2675 # Otherwise, truncate and add ellipsis...
2677 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2678 if ( $length > 0 ) {
2679 $length -= $eLength;
2680 $string = substr( $string, 0, $length ); // xyz...
2681 $string = $this->removeBadCharLast( $string );
2682 $string = $string . $ellipsis;
2684 $length +
= $eLength;
2685 $string = substr( $string, $length ); // ...xyz
2686 $string = $this->removeBadCharFirst( $string );
2687 $string = $ellipsis . $string;
2690 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2691 # This check is *not* redundant if $adjustLength, due to the single case where
2692 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2693 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2696 return $stringOriginal;
2701 * Remove bytes that represent an incomplete Unicode character
2702 * at the end of string (e.g. bytes of the char are missing)
2704 * @param $string String
2707 protected function removeBadCharLast( $string ) {
2708 if ( $string != '' ) {
2709 $char = ord( $string[strlen( $string ) - 1] );
2711 if ( $char >= 0xc0 ) {
2712 # We got the first byte only of a multibyte char; remove it.
2713 $string = substr( $string, 0, -1 );
2714 } elseif ( $char >= 0x80 &&
2715 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2716 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2718 # We chopped in the middle of a character; remove it
2726 * Remove bytes that represent an incomplete Unicode character
2727 * at the start of string (e.g. bytes of the char are missing)
2729 * @param $string String
2732 protected function removeBadCharFirst( $string ) {
2733 if ( $string != '' ) {
2734 $char = ord( $string[0] );
2735 if ( $char >= 0x80 && $char < 0xc0 ) {
2736 # We chopped in the middle of a character; remove the whole thing
2737 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2744 * Truncate a string of valid HTML to a specified length in bytes,
2745 * appending an optional string (e.g. for ellipses), and return valid HTML
2747 * This is only intended for styled/linked text, such as HTML with
2748 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2749 * Also, this will not detect things like "display:none" CSS.
2751 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2753 * @param string $text HTML string to truncate
2754 * @param int $length (zero/positive) Maximum length (including ellipses)
2755 * @param string $ellipsis String to append to the truncated text
2758 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2759 # Use the localized ellipsis character
2760 if ( $ellipsis == '...' ) {
2761 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2763 # Check if there is clearly no need to truncate
2764 if ( $length <= 0 ) {
2765 return $ellipsis; // no text shown, nothing to format (convention)
2766 } elseif ( strlen( $text ) <= $length ) {
2767 return $text; // string short enough even *with* HTML (short-circuit)
2770 $displayLen = 0; // innerHTML legth so far
2771 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2772 $tagType = 0; // 0-open, 1-close
2773 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2774 $entityState = 0; // 0-not entity, 1-entity
2775 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2776 $openTags = array(); // open tag stack
2777 $pOpenTags = array();
2779 $textLen = strlen( $text );
2780 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2781 for ( $pos = 0; true; ++
$pos ) {
2782 # Consider truncation once the display length has reached the maximim.
2783 # Check that we're not in the middle of a bracket/entity...
2784 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2785 if ( !$testingEllipsis ) {
2786 $testingEllipsis = true;
2787 # Save where we are; we will truncate here unless there turn out to
2788 # be so few remaining characters that truncation is not necessary.
2789 $pOpenTags = $openTags; // save state
2790 $pRet = $ret; // save state
2791 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2792 # String in fact does need truncation, the truncation point was OK.
2793 $openTags = $pOpenTags; // reload state
2794 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2795 $ret .= $ellipsis; // add ellipsis
2799 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2801 # Read the next char...
2803 $lastCh = $pos ?
$text[$pos - 1] : '';
2804 $ret .= $ch; // add to result string
2806 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2807 $entityState = 0; // for bad HTML
2808 $bracketState = 1; // tag started (checking for backslash)
2809 } elseif ( $ch == '>' ) {
2810 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2811 $entityState = 0; // for bad HTML
2812 $bracketState = 0; // out of brackets
2813 } elseif ( $bracketState == 1 ) {
2815 $tagType = 1; // close tag (e.g. "</span>")
2817 $tagType = 0; // open tag (e.g. "<span>")
2820 $bracketState = 2; // building tag name
2821 } elseif ( $bracketState == 2 ) {
2825 // Name found (e.g. "<a href=..."), add on tag attributes...
2826 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2828 } elseif ( $bracketState == 0 ) {
2829 if ( $entityState ) {
2832 $displayLen++
; // entity is one displayed char
2836 $entityState = 1; // entity found, (e.g. " ")
2838 $displayLen++
; // this char is displayed
2839 // Add the next $max display text chars after this in one swoop...
2840 $max = ( $testingEllipsis ?
$length : $neLength ) - $displayLen;
2841 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2842 $displayLen +
= $skipped;
2848 if ( $displayLen == 0 ) {
2849 return ''; // no text shown, nothing to format
2851 // Close the last tag if left unclosed by bad HTML
2852 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2853 while ( count( $openTags ) > 0 ) {
2854 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2860 * truncateHtml() helper function
2861 * like strcspn() but adds the skipped chars to $ret
2870 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2871 if ( $len === null ) {
2872 $len = -1; // -1 means "no limit" for strcspn
2873 } elseif ( $len < 0 ) {
2877 if ( $start < strlen( $text ) ) {
2878 $skipCount = strcspn( $text, $search, $start, $len );
2879 $ret .= substr( $text, $start, $skipCount );
2885 * truncateHtml() helper function
2886 * (a) push or pop $tag from $openTags as needed
2887 * (b) clear $tag value
2888 * @param String &$tag Current HTML tag name we are looking at
2889 * @param int $tagType (0-open tag, 1-close tag)
2890 * @param char $lastCh Character before the '>' that ended this tag
2891 * @param array &$openTags Open tag stack (not accounting for $tag)
2893 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2894 $tag = ltrim( $tag );
2896 if ( $tagType == 0 && $lastCh != '/' ) {
2897 $openTags[] = $tag; // tag opened (didn't close itself)
2898 } else if ( $tagType == 1 ) {
2899 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2900 array_pop( $openTags ); // tag closed
2908 * Grammatical transformations, needed for inflected languages
2909 * Invoked by putting {{grammar:case|word}} in a message
2911 * @param $word string
2912 * @param $case string
2915 function convertGrammar( $word, $case ) {
2916 global $wgGrammarForms;
2917 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2918 return $wgGrammarForms[$this->getCode()][$case][$word];
2924 * Provides an alternative text depending on specified gender.
2925 * Usage {{gender:username|masculine|feminine|neutral}}.
2926 * username is optional, in which case the gender of current user is used,
2927 * but only in (some) interface messages; otherwise default gender is used.
2928 * If second or third parameter are not specified, masculine is used.
2929 * These details may be overriden per language.
2931 * @param $gender string
2932 * @param $forms array
2936 function gender( $gender, $forms ) {
2937 if ( !count( $forms ) ) {
2940 $forms = $this->preConvertPlural( $forms, 2 );
2941 if ( $gender === 'male' ) {
2944 if ( $gender === 'female' ) {
2947 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2951 * Plural form transformations, needed for some languages.
2952 * For example, there are 3 form of plural in Russian and Polish,
2953 * depending on "count mod 10". See [[w:Plural]]
2954 * For English it is pretty simple.
2956 * Invoked by putting {{plural:count|wordform1|wordform2}}
2957 * or {{plural:count|wordform1|wordform2|wordform3}}
2959 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2961 * @param $count Integer: non-localized number
2962 * @param $forms Array: different plural forms
2963 * @return string Correct form of plural for $count in this language
2965 function convertPlural( $count, $forms ) {
2966 if ( !count( $forms ) ) {
2969 $forms = $this->preConvertPlural( $forms, 2 );
2971 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2975 * Checks that convertPlural was given an array and pads it to requested
2976 * amount of forms by copying the last one.
2978 * @param $count Integer: How many forms should there be at least
2979 * @param $forms Array of forms given to convertPlural
2980 * @return array Padded array of forms or an exception if not an array
2982 protected function preConvertPlural( /* Array */ $forms, $count ) {
2983 while ( count( $forms ) < $count ) {
2984 $forms[] = $forms[count( $forms ) - 1];
2990 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2991 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2992 * (which is an absolute timestamp).
2993 * @param $str String: the validated block duration in English
2994 * @return Somehow translated block duration
2995 * @see LanguageFi.php for example implementation
2997 function translateBlockExpiry( $str ) {
2998 $duration = SpecialBlock
::getSuggestedDurations( $this );
2999 foreach( $duration as $show => $value ){
3000 if ( strcmp( $str, $value ) == 0 ) {
3001 return htmlspecialchars( trim( $show ) );
3005 // Since usually only infinite or indefinite is only on list, so try
3006 // equivalents if still here.
3007 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3008 if ( in_array( $str, $indefs ) ) {
3009 foreach( $indefs as $val ) {
3010 $show = array_search( $val, $duration, true );
3011 if ( $show !== false ) {
3012 return htmlspecialchars( trim( $show ) );
3016 // If all else fails, return the original string.
3021 * languages like Chinese need to be segmented in order for the diff
3024 * @param $text String
3027 function segmentForDiff( $text ) {
3032 * and unsegment to show the result
3034 * @param $text String
3037 function unsegmentForDiff( $text ) {
3042 * convert text to all supported variants
3044 * @param $text string
3047 function autoConvertToAllVariants( $text ) {
3048 return $this->mConverter
->autoConvertToAllVariants( $text );
3052 * convert text to different variants of a language.
3054 * @param $text string
3057 function convert( $text ) {
3058 return $this->mConverter
->convert( $text );
3063 * Convert a Title object to a string in the preferred variant
3065 * @param $title Title
3068 function convertTitle( $title ) {
3069 return $this->mConverter
->convertTitle( $title );
3073 * Check if this is a language with variants
3077 function hasVariants() {
3078 return sizeof( $this->getVariants() ) > 1;
3082 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3084 * @param $text string
3087 function armourMath( $text ) {
3088 return $this->mConverter
->armourMath( $text );
3092 * Perform output conversion on a string, and encode for safe HTML output.
3093 * @param $text String text to be converted
3094 * @param $isTitle Bool whether this conversion is for the article title
3096 * @todo this should get integrated somewhere sane
3098 function convertHtml( $text, $isTitle = false ) {
3099 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3103 * @param $key string
3106 function convertCategoryKey( $key ) {
3107 return $this->mConverter
->convertCategoryKey( $key );
3111 * Get the list of variants supported by this language
3112 * see sample implementation in LanguageZh.php
3114 * @return array an array of language codes
3116 function getVariants() {
3117 return $this->mConverter
->getVariants();
3123 function getPreferredVariant() {
3124 return $this->mConverter
->getPreferredVariant();
3130 function getDefaultVariant() {
3131 return $this->mConverter
->getDefaultVariant();
3137 function getURLVariant() {
3138 return $this->mConverter
->getURLVariant();
3142 * If a language supports multiple variants, it is
3143 * possible that non-existing link in one variant
3144 * actually exists in another variant. this function
3145 * tries to find it. See e.g. LanguageZh.php
3147 * @param $link String: the name of the link
3148 * @param $nt Mixed: the title object of the link
3149 * @param $ignoreOtherCond Boolean: to disable other conditions when
3150 * we need to transclude a template or update a category's link
3151 * @return null the input parameters may be modified upon return
3153 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3154 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3158 * If a language supports multiple variants, converts text
3159 * into an array of all possible variants of the text:
3160 * 'variant' => text in that variant
3162 * @deprecated since 1.17 Use autoConvertToAllVariants()
3164 * @param $text string
3168 function convertLinkToAllVariants( $text ) {
3169 return $this->mConverter
->convertLinkToAllVariants( $text );
3173 * returns language specific options used by User::getPageRenderHash()
3174 * for example, the preferred language variant
3178 function getExtraHashOptions() {
3179 return $this->mConverter
->getExtraHashOptions();
3183 * For languages that support multiple variants, the title of an
3184 * article may be displayed differently in different variants. this
3185 * function returns the apporiate title defined in the body of the article.
3189 function getParsedTitle() {
3190 return $this->mConverter
->getParsedTitle();
3194 * Enclose a string with the "no conversion" tag. This is used by
3195 * various functions in the Parser
3197 * @param $text String: text to be tagged for no conversion
3198 * @param $noParse bool
3199 * @return string the tagged text
3201 function markNoConversion( $text, $noParse = false ) {
3202 return $this->mConverter
->markNoConversion( $text, $noParse );
3206 * A regular expression to match legal word-trailing characters
3207 * which should be merged onto a link of the form [[foo]]bar.
3211 function linkTrail() {
3212 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3218 function getLangObj() {
3223 * Get the RFC 3066 code for this language object
3227 function getCode() {
3228 return $this->mCode
;
3232 * @param $code string
3234 function setCode( $code ) {
3235 $this->mCode
= $code;
3239 * Get the name of a file for a certain language code
3240 * @param $prefix string Prepend this to the filename
3241 * @param $code string Language code
3242 * @param $suffix string Append this to the filename
3243 * @return string $prefix . $mangledCode . $suffix
3245 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3246 // Protect against path traversal
3247 if ( !Language
::isValidCode( $code )
3248 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3250 throw new MWException( "Invalid language code \"$code\"" );
3253 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3257 * Get the language code from a file name. Inverse of getFileName()
3258 * @param $filename string $prefix . $languageCode . $suffix
3259 * @param $prefix string Prefix before the language code
3260 * @param $suffix string Suffix after the language code
3261 * @return string Language code, or false if $prefix or $suffix isn't found
3263 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3265 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3266 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3267 if ( !count( $m ) ) {
3270 return str_replace( '_', '-', strtolower( $m[1] ) );
3274 * @param $code string
3277 static function getMessagesFileName( $code ) {
3279 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3283 * @param $code string
3286 static function getClassFileName( $code ) {
3288 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3292 * Get the fallback for a given language
3294 * @param $code string
3296 * @return false|string
3298 static function getFallbackFor( $code ) {
3299 if ( $code === 'en' ) {
3303 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
3308 * Get all messages for a given language
3309 * WARNING: this may take a long time
3311 * @param $code string
3315 static function getMessagesFor( $code ) {
3316 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3320 * Get a message for a given language
3322 * @param $key string
3323 * @param $code string
3327 static function getMessageFor( $key, $code ) {
3328 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3335 function fixVariableInNamespace( $talk ) {
3336 if ( strpos( $talk, '$1' ) === false ) {
3340 global $wgMetaNamespace;
3341 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3343 # Allow grammar transformations
3344 # Allowing full message-style parsing would make simple requests
3345 # such as action=raw much more expensive than they need to be.
3346 # This will hopefully cover most cases.
3347 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3348 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3349 return str_replace( ' ', '_', $talk );
3356 function replaceGrammarInNamespace( $m ) {
3357 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3361 * @throws MWException
3364 static function getCaseMaps() {
3365 static $wikiUpperChars, $wikiLowerChars;
3366 if ( isset( $wikiUpperChars ) ) {
3367 return array( $wikiUpperChars, $wikiLowerChars );
3370 wfProfileIn( __METHOD__
);
3371 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3372 if ( $arr === false ) {
3373 throw new MWException(
3374 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3376 $wikiUpperChars = $arr['wikiUpperChars'];
3377 $wikiLowerChars = $arr['wikiLowerChars'];
3378 wfProfileOut( __METHOD__
);
3379 return array( $wikiUpperChars, $wikiLowerChars );
3383 * Decode an expiry (block, protection, etc) which has come from the DB
3385 * @param $expiry String: Database expiry String
3386 * @param $format Bool|Int true to process using language functions, or TS_ constant
3387 * to return the expiry in a given timestamp
3390 public function formatExpiry( $expiry, $format = true ) {
3391 static $infinity, $infinityMsg;
3392 if( $infinity === null ){
3393 $infinityMsg = wfMessage( 'infiniteblock' );
3394 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3397 if ( $expiry == '' ||
$expiry == $infinity ) {
3398 return $format === true
3402 return $format === true
3403 ?
$this->timeanddate( $expiry )
3404 : wfTimestamp( $format, $expiry );
3410 * @param $seconds String
3413 function formatTimePeriod( $seconds ) {
3414 if ( round( $seconds * 10 ) < 100 ) {
3415 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3416 } elseif ( round( $seconds ) < 60 ) {
3417 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3418 } elseif ( round( $seconds ) < 3600 ) {
3419 $minutes = floor( $seconds / 60 );
3420 $secondsPart = round( fmod( $seconds, 60 ) );
3421 if ( $secondsPart == 60 ) {
3425 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3426 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3428 $hours = floor( $seconds / 3600 );
3429 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3430 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3431 if ( $secondsPart == 60 ) {
3435 if ( $minutes == 60 ) {
3439 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3440 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3441 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3449 function formatBitrate( $bps ) {
3450 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3452 return $this->formatNum( $bps ) . $units[0];
3454 $unitIndex = floor( log10( $bps ) / 3 );
3455 $mantissa = $bps / pow( 1000, $unitIndex );
3456 if ( $mantissa < 10 ) {
3457 $mantissa = round( $mantissa, 1 );
3459 $mantissa = round( $mantissa );
3461 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3465 * Format a size in bytes for output, using an appropriate
3466 * unit (B, KB, MB or GB) according to the magnitude in question
3468 * @param $size Size to format
3469 * @return string Plain text (not HTML)
3471 function formatSize( $size ) {
3472 // For small sizes no decimal places necessary
3474 if ( $size > 1024 ) {
3475 $size = $size / 1024;
3476 if ( $size > 1024 ) {
3477 $size = $size / 1024;
3478 // For MB and bigger two decimal places are smarter
3480 if ( $size > 1024 ) {
3481 $size = $size / 1024;
3482 $msg = 'size-gigabytes';
3484 $msg = 'size-megabytes';
3487 $msg = 'size-kilobytes';
3490 $msg = 'size-bytes';
3492 $size = round( $size, $round );
3493 $text = $this->getMessageFromDB( $msg );
3494 return str_replace( '$1', $this->formatNum( $size ), $text );
3498 * Get the conversion rule title, if any.
3502 function getConvRuleTitle() {
3503 return $this->mConverter
->getConvRuleTitle();