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 wfSuppressWarnings();
763 $userTZ = timezone_open( $data[2] );
765 if ( $userTZ !== false ) {
766 $date = date_create( $ts, timezone_open( 'UTC' ) );
767 date_timezone_set( $date, $userTZ );
768 $date = date_format( $date, 'YmdHis' );
771 # Unrecognized timezone, default to 'Offset' with the stored offset.
776 if ( $data[0] == 'System' ||
$tz == '' ) {
777 # Global offset in minutes.
778 if ( isset( $wgLocalTZoffset ) ) {
779 $minDiff = $wgLocalTZoffset;
781 } elseif ( $data[0] == 'Offset' ) {
782 $minDiff = intval( $data[1] );
784 $data = explode( ':', $tz );
785 if ( count( $data ) == 2 ) {
786 $data[0] = intval( $data[0] );
787 $data[1] = intval( $data[1] );
788 $minDiff = abs( $data[0] ) * 60 +
$data[1];
789 if ( $data[0] < 0 ) {
790 $minDiff = -$minDiff;
793 $minDiff = intval( $data[0] ) * 60;
797 # No difference ? Return time unchanged
798 if ( 0 == $minDiff ) {
802 wfSuppressWarnings(); // E_STRICT system time bitching
803 # Generate an adjusted date; take advantage of the fact that mktime
804 # will normalize out-of-range values so we don't have to split $minDiff
805 # into hours and minutes.
807 (int)substr( $ts, 8, 2 ) ), # Hours
808 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
809 (int)substr( $ts, 12, 2 ), # Seconds
810 (int)substr( $ts, 4, 2 ), # Month
811 (int)substr( $ts, 6, 2 ), # Day
812 (int)substr( $ts, 0, 4 ) ); # Year
814 $date = date( 'YmdHis', $t );
821 * This is a workalike of PHP's date() function, but with better
822 * internationalisation, a reduced set of format characters, and a better
825 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
826 * PHP manual for definitions. There are a number of extensions, which
829 * xn Do not translate digits of the next numeric format character
830 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
831 * xr Use roman numerals for the next numeric format character
832 * xh Use hebrew numerals for the next numeric format character
834 * xg Genitive month name
836 * xij j (day number) in Iranian calendar
837 * xiF F (month name) in Iranian calendar
838 * xin n (month number) in Iranian calendar
839 * xiY Y (full year) in Iranian calendar
841 * xjj j (day number) in Hebrew calendar
842 * xjF F (month name) in Hebrew calendar
843 * xjt t (days in month) in Hebrew calendar
844 * xjx xg (genitive month name) in Hebrew calendar
845 * xjn n (month number) in Hebrew calendar
846 * xjY Y (full year) in Hebrew calendar
848 * xmj j (day number) in Hijri calendar
849 * xmF F (month name) in Hijri calendar
850 * xmn n (month number) in Hijri calendar
851 * xmY Y (full year) in Hijri calendar
853 * xkY Y (full year) in Thai solar calendar. Months and days are
854 * identical to the Gregorian calendar
855 * xoY Y (full year) in Minguo calendar or Juche year.
856 * Months and days are identical to the
858 * xtY Y (full year) in Japanese nengo. Months and days are
859 * identical to the Gregorian calendar
861 * Characters enclosed in double quotes will be considered literal (with
862 * the quotes themselves removed). Unmatched quotes will be considered
863 * literal quotes. Example:
865 * "The month is" F => The month is January
868 * Backslash escaping is also supported.
870 * Input timestamp is assumed to be pre-normalized to the desired local
873 * @param $format String
874 * @param $ts String: 14-character timestamp
877 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
881 function sprintfDate( $format, $ts ) {
894 for ( $p = 0; $p < strlen( $format ); $p++
) {
897 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
898 $code .= $format[++
$p];
901 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
902 $code .= $format[++
$p];
913 $rawToggle = !$rawToggle;
922 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
925 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
926 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
929 $num = substr( $ts, 6, 2 );
932 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
933 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
936 $num = intval( substr( $ts, 6, 2 ) );
940 $iranian = self
::tsToIranian( $ts );
946 $hijri = self
::tsToHijri( $ts );
952 $hebrew = self
::tsToHebrew( $ts );
958 $unix = wfTimestamp( TS_UNIX
, $ts );
960 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
964 $unix = wfTimestamp( TS_UNIX
, $ts );
966 $w = gmdate( 'w', $unix );
971 $unix = wfTimestamp( TS_UNIX
, $ts );
973 $num = gmdate( 'w', $unix );
977 $unix = wfTimestamp( TS_UNIX
, $ts );
979 $num = gmdate( 'z', $unix );
983 $unix = wfTimestamp( TS_UNIX
, $ts );
985 $num = gmdate( 'W', $unix );
988 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
992 $iranian = self
::tsToIranian( $ts );
994 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
998 $hijri = self
::tsToHijri( $ts );
1000 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1004 $hebrew = self
::tsToHebrew( $ts );
1006 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1009 $num = substr( $ts, 4, 2 );
1012 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1015 $num = intval( substr( $ts, 4, 2 ) );
1019 $iranian = self
::tsToIranian( $ts );
1025 $hijri = self
::tsToHijri ( $ts );
1031 $hebrew = self
::tsToHebrew( $ts );
1037 $unix = wfTimestamp( TS_UNIX
, $ts );
1039 $num = gmdate( 't', $unix );
1043 $hebrew = self
::tsToHebrew( $ts );
1049 $unix = wfTimestamp( TS_UNIX
, $ts );
1051 $num = gmdate( 'L', $unix );
1055 $unix = wfTimestamp( TS_UNIX
, $ts );
1057 $num = date( 'o', $unix );
1060 $num = substr( $ts, 0, 4 );
1064 $iranian = self
::tsToIranian( $ts );
1070 $hijri = self
::tsToHijri( $ts );
1076 $hebrew = self
::tsToHebrew( $ts );
1082 $thai = self
::tsToYear( $ts, 'thai' );
1088 $minguo = self
::tsToYear( $ts, 'minguo' );
1094 $tenno = self
::tsToYear( $ts, 'tenno' );
1099 $num = substr( $ts, 2, 2 );
1102 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1105 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1108 $h = substr( $ts, 8, 2 );
1109 $num = $h %
12 ?
$h %
12 : 12;
1112 $num = intval( substr( $ts, 8, 2 ) );
1115 $h = substr( $ts, 8, 2 );
1116 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1119 $num = substr( $ts, 8, 2 );
1122 $num = substr( $ts, 10, 2 );
1125 $num = substr( $ts, 12, 2 );
1129 $unix = wfTimestamp( TS_UNIX
, $ts );
1131 $s .= gmdate( 'c', $unix );
1135 $unix = wfTimestamp( TS_UNIX
, $ts );
1137 $s .= gmdate( 'r', $unix );
1141 $unix = wfTimestamp( TS_UNIX
, $ts );
1146 # Backslash escaping
1147 if ( $p < strlen( $format ) - 1 ) {
1148 $s .= $format[++
$p];
1155 if ( $p < strlen( $format ) - 1 ) {
1156 $endQuote = strpos( $format, '"', $p +
1 );
1157 if ( $endQuote === false ) {
1158 # No terminating quote, assume literal "
1161 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1165 # Quote at end of string, assume literal "
1172 if ( $num !== false ) {
1173 if ( $rawToggle ||
$raw ) {
1176 } elseif ( $roman ) {
1177 $s .= self
::romanNumeral( $num );
1179 } elseif ( $hebrewNum ) {
1180 $s .= self
::hebrewNumeral( $num );
1183 $s .= $this->formatNum( $num, true );
1190 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1191 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1194 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1195 * Gregorian dates to Iranian dates. Originally written in C, it
1196 * is released under the terms of GNU Lesser General Public
1197 * License. Conversion to PHP was performed by Niklas Laxström.
1199 * Link: http://www.farsiweb.info/jalali/jalali.c
1205 private static function tsToIranian( $ts ) {
1206 $gy = substr( $ts, 0, 4 ) -1600;
1207 $gm = substr( $ts, 4, 2 ) -1;
1208 $gd = substr( $ts, 6, 2 ) -1;
1210 # Days passed from the beginning (including leap years)
1212 +
floor( ( $gy +
3 ) / 4 )
1213 - floor( ( $gy +
99 ) / 100 )
1214 +
floor( ( $gy +
399 ) / 400 );
1217 // Add days of the past months of this year
1218 for ( $i = 0; $i < $gm; $i++
) {
1219 $gDayNo +
= self
::$GREG_DAYS[$i];
1223 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1227 // Days passed in current month
1230 $jDayNo = $gDayNo - 79;
1232 $jNp = floor( $jDayNo / 12053 );
1235 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1238 if ( $jDayNo >= 366 ) {
1239 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1240 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1243 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1244 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1250 return array( $jy, $jm, $jd );
1254 * Converting Gregorian dates to Hijri dates.
1256 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1258 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1264 private static function tsToHijri( $ts ) {
1265 $year = substr( $ts, 0, 4 );
1266 $month = substr( $ts, 4, 2 );
1267 $day = substr( $ts, 6, 2 );
1275 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1276 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1279 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1280 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1281 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1284 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1285 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1288 $zl = $zjd -1948440 +
10632;
1289 $zn = (int)( ( $zl - 1 ) / 10631 );
1290 $zl = $zl - 10631 * $zn +
354;
1291 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1292 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1293 $zm = (int)( ( 24 * $zl ) / 709 );
1294 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1295 $zy = 30 * $zn +
$zj - 30;
1297 return array( $zy, $zm, $zd );
1301 * Converting Gregorian dates to Hebrew dates.
1303 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1304 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1305 * to translate the relevant functions into PHP and release them under
1308 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1309 * and Adar II is 14. In a non-leap year, Adar is 6.
1315 private static function tsToHebrew( $ts ) {
1317 $year = substr( $ts, 0, 4 );
1318 $month = substr( $ts, 4, 2 );
1319 $day = substr( $ts, 6, 2 );
1321 # Calculate Hebrew year
1322 $hebrewYear = $year +
3760;
1324 # Month number when September = 1, August = 12
1326 if ( $month > 12 ) {
1333 # Calculate day of year from 1 September
1335 for ( $i = 1; $i < $month; $i++
) {
1339 # Check if the year is leap
1340 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1343 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1350 # Calculate the start of the Hebrew year
1351 $start = self
::hebrewYearStart( $hebrewYear );
1353 # Calculate next year's start
1354 if ( $dayOfYear <= $start ) {
1355 # Day is before the start of the year - it is the previous year
1357 $nextStart = $start;
1361 # Add days since previous year's 1 September
1363 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1367 # Start of the new (previous) year
1368 $start = self
::hebrewYearStart( $hebrewYear );
1371 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1374 # Calculate Hebrew day of year
1375 $hebrewDayOfYear = $dayOfYear - $start;
1377 # Difference between year's days
1378 $diff = $nextStart - $start;
1379 # Add 12 (or 13 for leap years) days to ignore the difference between
1380 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1381 # difference is only about the year type
1382 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1388 # Check the year pattern, and is leap year
1389 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1390 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1391 # and non-leap years
1392 $yearPattern = $diff %
30;
1393 # Check if leap year
1394 $isLeap = $diff >= 30;
1396 # Calculate day in the month from number of day in the Hebrew year
1397 # Don't check Adar - if the day is not in Adar, we will stop before;
1398 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1399 $hebrewDay = $hebrewDayOfYear;
1402 while ( $hebrewMonth <= 12 ) {
1403 # Calculate days in this month
1404 if ( $isLeap && $hebrewMonth == 6 ) {
1405 # Adar in a leap year
1407 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1409 if ( $hebrewDay <= $days ) {
1413 # Subtract the days of Adar I
1414 $hebrewDay -= $days;
1417 if ( $hebrewDay <= $days ) {
1423 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1424 # Cheshvan in a complete year (otherwise as the rule below)
1426 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1427 # Kislev in an incomplete year (otherwise as the rule below)
1430 # Odd months have 30 days, even have 29
1431 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1433 if ( $hebrewDay <= $days ) {
1434 # In the current month
1437 # Subtract the days of the current month
1438 $hebrewDay -= $days;
1439 # Try in the next month
1444 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1448 * This calculates the Hebrew year start, as days since 1 September.
1449 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1450 * Used for Hebrew date.
1456 private static function hebrewYearStart( $year ) {
1457 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1458 $b = intval( ( $year - 1 ) %
4 );
1459 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1463 $Mar = intval( $m );
1469 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1470 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1472 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1474 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1478 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1483 * Algorithm to convert Gregorian dates to Thai solar dates,
1484 * Minguo dates or Minguo dates.
1486 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1487 * http://en.wikipedia.org/wiki/Minguo_calendar
1488 * http://en.wikipedia.org/wiki/Japanese_era_name
1490 * @param $ts String: 14-character timestamp
1491 * @param $cName String: calender name
1492 * @return Array: converted year, month, day
1494 private static function tsToYear( $ts, $cName ) {
1495 $gy = substr( $ts, 0, 4 );
1496 $gm = substr( $ts, 4, 2 );
1497 $gd = substr( $ts, 6, 2 );
1499 if ( !strcmp( $cName, 'thai' ) ) {
1501 # Add 543 years to the Gregorian calendar
1502 # Months and days are identical
1503 $gy_offset = $gy +
543;
1504 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1506 # Deduct 1911 years from the Gregorian calendar
1507 # Months and days are identical
1508 $gy_offset = $gy - 1911;
1509 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1510 # Nengō dates up to Meiji period
1511 # Deduct years from the Gregorian calendar
1512 # depending on the nengo periods
1513 # Months and days are identical
1514 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1516 $gy_gannen = $gy - 1868 +
1;
1517 $gy_offset = $gy_gannen;
1518 if ( $gy_gannen == 1 ) {
1521 $gy_offset = '明治' . $gy_offset;
1523 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1524 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1525 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1526 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1527 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1531 $gy_gannen = $gy - 1912 +
1;
1532 $gy_offset = $gy_gannen;
1533 if ( $gy_gannen == 1 ) {
1536 $gy_offset = '大正' . $gy_offset;
1538 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1539 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1540 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1544 $gy_gannen = $gy - 1926 +
1;
1545 $gy_offset = $gy_gannen;
1546 if ( $gy_gannen == 1 ) {
1549 $gy_offset = '昭和' . $gy_offset;
1552 $gy_gannen = $gy - 1989 +
1;
1553 $gy_offset = $gy_gannen;
1554 if ( $gy_gannen == 1 ) {
1557 $gy_offset = '平成' . $gy_offset;
1563 return array( $gy_offset, $gm, $gd );
1567 * Roman number formatting up to 3000
1573 static function romanNumeral( $num ) {
1574 static $table = array(
1575 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1576 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1577 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1578 array( '', 'M', 'MM', 'MMM' )
1581 $num = intval( $num );
1582 if ( $num > 3000 ||
$num <= 0 ) {
1587 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1588 if ( $num >= $pow10 ) {
1589 $s .= $table[$i][floor( $num / $pow10 )];
1591 $num = $num %
$pow10;
1597 * Hebrew Gematria number formatting up to 9999
1603 static function hebrewNumeral( $num ) {
1604 static $table = array(
1605 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1606 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1607 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1608 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1611 $num = intval( $num );
1612 if ( $num > 9999 ||
$num <= 0 ) {
1617 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1618 if ( $num >= $pow10 ) {
1619 if ( $num == 15 ||
$num == 16 ) {
1620 $s .= $table[0][9] . $table[0][$num - 9];
1623 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1624 if ( $pow10 == 1000 ) {
1629 $num = $num %
$pow10;
1631 if ( strlen( $s ) == 2 ) {
1634 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1635 $str .= substr( $s, strlen( $s ) - 2, 2 );
1637 $start = substr( $str, 0, strlen( $str ) - 2 );
1638 $end = substr( $str, strlen( $str ) - 2 );
1641 $str = $start . 'ך';
1644 $str = $start . 'ם';
1647 $str = $start . 'ן';
1650 $str = $start . 'ף';
1653 $str = $start . 'ץ';
1660 * This is meant to be used by time(), date(), and timeanddate() to get
1661 * the date preference they're supposed to use, it should be used in
1665 * function timeanddate([...], $format = true) {
1666 * $datePreference = $this->dateFormat($format);
1671 * @param $usePrefs Mixed: if true, the user's preference is used
1672 * if false, the site/language default is used
1673 * if int/string, assumed to be a format.
1676 function dateFormat( $usePrefs = true ) {
1679 if ( is_bool( $usePrefs ) ) {
1681 $datePreference = $wgUser->getDatePreference();
1683 $datePreference = (string)User
::getDefaultOption( 'date' );
1686 $datePreference = (string)$usePrefs;
1690 if ( $datePreference == '' ) {
1694 return $datePreference;
1698 * Get a format string for a given type and preference
1699 * @param $type string May be date, time or both
1700 * @param $pref string The format name as it appears in Messages*.php
1704 function getDateFormatString( $type, $pref ) {
1705 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1706 if ( $pref == 'default' ) {
1707 $pref = $this->getDefaultDateFormat();
1708 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1710 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1711 if ( is_null( $df ) ) {
1712 $pref = $this->getDefaultDateFormat();
1713 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1716 $this->dateFormatStrings
[$type][$pref] = $df;
1718 return $this->dateFormatStrings
[$type][$pref];
1722 * @param $ts Mixed: the time format which needs to be turned into a
1723 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1724 * @param $adj Bool: whether to adjust the time output according to the
1725 * user configured offset ($timecorrection)
1726 * @param $format Mixed: true to use user's date format preference
1727 * @param $timecorrection String|bool the time offset as returned by
1728 * validateTimeZone() in Special:Preferences
1731 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1732 $ts = wfTimestamp( TS_MW
, $ts );
1734 $ts = $this->userAdjust( $ts, $timecorrection );
1736 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1737 return $this->sprintfDate( $df, $ts );
1741 * @param $ts Mixed: the time format which needs to be turned into a
1742 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1743 * @param $adj Bool: whether to adjust the time output according to the
1744 * user configured offset ($timecorrection)
1745 * @param $format Mixed: true to use user's date format preference
1746 * @param $timecorrection String|bool the time offset as returned by
1747 * validateTimeZone() in Special:Preferences
1750 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1751 $ts = wfTimestamp( TS_MW
, $ts );
1753 $ts = $this->userAdjust( $ts, $timecorrection );
1755 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1756 return $this->sprintfDate( $df, $ts );
1760 * @param $ts Mixed: the time format which needs to be turned into a
1761 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1762 * @param $adj Bool: whether to adjust the time output according to the
1763 * user configured offset ($timecorrection)
1764 * @param $format Mixed: what format to return, if it's false output the
1765 * default one (default true)
1766 * @param $timecorrection String|bool the time offset as returned by
1767 * validateTimeZone() in Special:Preferences
1770 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1771 $ts = wfTimestamp( TS_MW
, $ts );
1773 $ts = $this->userAdjust( $ts, $timecorrection );
1775 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1776 return $this->sprintfDate( $df, $ts );
1780 * @param $key string
1781 * @return array|null
1783 function getMessage( $key ) {
1784 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1790 function getAllMessages() {
1791 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1800 function iconv( $in, $out, $string ) {
1801 # This is a wrapper for iconv in all languages except esperanto,
1802 # which does some nasty x-conversions beforehand
1804 # Even with //IGNORE iconv can whine about illegal characters in
1805 # *input* string. We just ignore those too.
1806 # REF: http://bugs.php.net/bug.php?id=37166
1807 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1808 wfSuppressWarnings();
1809 $text = iconv( $in, $out . '//IGNORE', $string );
1810 wfRestoreWarnings();
1814 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1817 * @param $matches array
1818 * @return mixed|string
1820 function ucwordbreaksCallbackAscii( $matches ) {
1821 return $this->ucfirst( $matches[1] );
1825 * @param $matches array
1828 function ucwordbreaksCallbackMB( $matches ) {
1829 return mb_strtoupper( $matches[0] );
1833 * @param $matches array
1836 function ucCallback( $matches ) {
1837 list( $wikiUpperChars ) = self
::getCaseMaps();
1838 return strtr( $matches[1], $wikiUpperChars );
1842 * @param $matches array
1845 function lcCallback( $matches ) {
1846 list( , $wikiLowerChars ) = self
::getCaseMaps();
1847 return strtr( $matches[1], $wikiLowerChars );
1851 * @param $matches array
1854 function ucwordsCallbackMB( $matches ) {
1855 return mb_strtoupper( $matches[0] );
1859 * @param $matches array
1862 function ucwordsCallbackWiki( $matches ) {
1863 list( $wikiUpperChars ) = self
::getCaseMaps();
1864 return strtr( $matches[0], $wikiUpperChars );
1868 * Make a string's first character uppercase
1870 * @param $str string
1874 function ucfirst( $str ) {
1876 if ( $o < 96 ) { // if already uppercase...
1878 } elseif ( $o < 128 ) {
1879 return ucfirst( $str ); // use PHP's ucfirst()
1881 // fall back to more complex logic in case of multibyte strings
1882 return $this->uc( $str, true );
1887 * Convert a string to uppercase
1889 * @param $str string
1890 * @param $first bool
1894 function uc( $str, $first = false ) {
1895 if ( function_exists( 'mb_strtoupper' ) ) {
1897 if ( $this->isMultibyte( $str ) ) {
1898 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1900 return ucfirst( $str );
1903 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1906 if ( $this->isMultibyte( $str ) ) {
1907 $x = $first ?
'^' : '';
1908 return preg_replace_callback(
1909 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1910 array( $this, 'ucCallback' ),
1914 return $first ?
ucfirst( $str ) : strtoupper( $str );
1920 * @param $str string
1921 * @return mixed|string
1923 function lcfirst( $str ) {
1926 return strval( $str );
1927 } elseif ( $o >= 128 ) {
1928 return $this->lc( $str, true );
1929 } elseif ( $o > 96 ) {
1932 $str[0] = strtolower( $str[0] );
1938 * @param $str string
1939 * @param $first bool
1940 * @return mixed|string
1942 function lc( $str, $first = false ) {
1943 if ( function_exists( 'mb_strtolower' ) ) {
1945 if ( $this->isMultibyte( $str ) ) {
1946 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1948 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1951 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1954 if ( $this->isMultibyte( $str ) ) {
1955 $x = $first ?
'^' : '';
1956 return preg_replace_callback(
1957 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1958 array( $this, 'lcCallback' ),
1962 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1968 * @param $str string
1971 function isMultibyte( $str ) {
1972 return (bool)preg_match( '/[\x80-\xff]/', $str );
1976 * @param $str string
1977 * @return mixed|string
1979 function ucwords( $str ) {
1980 if ( $this->isMultibyte( $str ) ) {
1981 $str = $this->lc( $str );
1983 // regexp to find first letter in each word (i.e. after each space)
1984 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1986 // function to use to capitalize a single char
1987 if ( function_exists( 'mb_strtoupper' ) ) {
1988 return preg_replace_callback(
1990 array( $this, 'ucwordsCallbackMB' ),
1994 return preg_replace_callback(
1996 array( $this, 'ucwordsCallbackWiki' ),
2001 return ucwords( strtolower( $str ) );
2006 * capitalize words at word breaks
2008 * @param $str string
2011 function ucwordbreaks( $str ) {
2012 if ( $this->isMultibyte( $str ) ) {
2013 $str = $this->lc( $str );
2015 // since \b doesn't work for UTF-8, we explicitely define word break chars
2016 $breaks = "[ \-\(\)\}\{\.,\?!]";
2018 // find first letter after word break
2019 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2021 if ( function_exists( 'mb_strtoupper' ) ) {
2022 return preg_replace_callback(
2024 array( $this, 'ucwordbreaksCallbackMB' ),
2028 return preg_replace_callback(
2030 array( $this, 'ucwordsCallbackWiki' ),
2035 return preg_replace_callback(
2036 '/\b([\w\x80-\xff]+)\b/',
2037 array( $this, 'ucwordbreaksCallbackAscii' ),
2044 * Return a case-folded representation of $s
2046 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2047 * and $s2 are the same except for the case of their characters. It is not
2048 * necessary for the value returned to make sense when displayed.
2050 * Do *not* perform any other normalisation in this function. If a caller
2051 * uses this function when it should be using a more general normalisation
2052 * function, then fix the caller.
2058 function caseFold( $s ) {
2059 return $this->uc( $s );
2066 function checkTitleEncoding( $s ) {
2067 if ( is_array( $s ) ) {
2068 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2070 # Check for non-UTF-8 URLs
2071 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2076 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2077 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2082 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2088 function fallback8bitEncoding() {
2089 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2093 * Most writing systems use whitespace to break up words.
2094 * Some languages such as Chinese don't conventionally do this,
2095 * which requires special handling when breaking up words for
2100 function hasWordBreaks() {
2105 * Some languages such as Chinese require word segmentation,
2106 * Specify such segmentation when overridden in derived class.
2108 * @param $string String
2111 function segmentByWord( $string ) {
2116 * Some languages have special punctuation need to be normalized.
2117 * Make such changes here.
2119 * @param $string String
2122 function normalizeForSearch( $string ) {
2123 return self
::convertDoubleWidth( $string );
2127 * convert double-width roman characters to single-width.
2128 * range: ff00-ff5f ~= 0020-007f
2130 * @param $string string
2134 protected static function convertDoubleWidth( $string ) {
2135 static $full = null;
2136 static $half = null;
2138 if ( $full === null ) {
2139 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2140 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2141 $full = str_split( $fullWidth, 3 );
2142 $half = str_split( $halfWidth );
2145 $string = str_replace( $full, $half, $string );
2150 * @param $string string
2151 * @param $pattern string
2154 protected static function insertSpace( $string, $pattern ) {
2155 $string = preg_replace( $pattern, " $1 ", $string );
2156 $string = preg_replace( '/ +/', ' ', $string );
2161 * @param $termsArray array
2164 function convertForSearchResult( $termsArray ) {
2165 # some languages, e.g. Chinese, need to do a conversion
2166 # in order for search results to be displayed correctly
2171 * Get the first character of a string.
2176 function firstChar( $s ) {
2179 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2180 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2185 if ( isset( $matches[1] ) ) {
2186 if ( strlen( $matches[1] ) != 3 ) {
2190 // Break down Hangul syllables to grab the first jamo
2191 $code = utf8ToCodepoint( $matches[1] );
2192 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2194 } elseif ( $code < 0xb098 ) {
2195 return "\xe3\x84\xb1";
2196 } elseif ( $code < 0xb2e4 ) {
2197 return "\xe3\x84\xb4";
2198 } elseif ( $code < 0xb77c ) {
2199 return "\xe3\x84\xb7";
2200 } elseif ( $code < 0xb9c8 ) {
2201 return "\xe3\x84\xb9";
2202 } elseif ( $code < 0xbc14 ) {
2203 return "\xe3\x85\x81";
2204 } elseif ( $code < 0xc0ac ) {
2205 return "\xe3\x85\x82";
2206 } elseif ( $code < 0xc544 ) {
2207 return "\xe3\x85\x85";
2208 } elseif ( $code < 0xc790 ) {
2209 return "\xe3\x85\x87";
2210 } elseif ( $code < 0xcc28 ) {
2211 return "\xe3\x85\x88";
2212 } elseif ( $code < 0xce74 ) {
2213 return "\xe3\x85\x8a";
2214 } elseif ( $code < 0xd0c0 ) {
2215 return "\xe3\x85\x8b";
2216 } elseif ( $code < 0xd30c ) {
2217 return "\xe3\x85\x8c";
2218 } elseif ( $code < 0xd558 ) {
2219 return "\xe3\x85\x8d";
2221 return "\xe3\x85\x8e";
2228 function initEncoding() {
2229 # Some languages may have an alternate char encoding option
2230 # (Esperanto X-coding, Japanese furigana conversion, etc)
2231 # If this language is used as the primary content language,
2232 # an override to the defaults can be set here on startup.
2239 function recodeForEdit( $s ) {
2240 # For some languages we'll want to explicitly specify
2241 # which characters make it into the edit box raw
2242 # or are converted in some way or another.
2243 global $wgEditEncoding;
2244 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2247 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2255 function recodeInput( $s ) {
2256 # Take the previous into account.
2257 global $wgEditEncoding;
2258 if ( $wgEditEncoding != '' ) {
2259 $enc = $wgEditEncoding;
2263 if ( $enc == 'UTF-8' ) {
2266 return $this->iconv( $enc, 'UTF-8', $s );
2271 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2272 * also cleans up certain backwards-compatible sequences, converting them
2273 * to the modern Unicode equivalent.
2275 * This is language-specific for performance reasons only.
2281 function normalize( $s ) {
2282 global $wgAllUnicodeFixes;
2283 $s = UtfNormal
::cleanUp( $s );
2284 if ( $wgAllUnicodeFixes ) {
2285 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2286 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2293 * Transform a string using serialized data stored in the given file (which
2294 * must be in the serialized subdirectory of $IP). The file contains pairs
2295 * mapping source characters to destination characters.
2297 * The data is cached in process memory. This will go faster if you have the
2298 * FastStringSearch extension.
2300 * @param $file string
2301 * @param $string string
2305 function transformUsingPairFile( $file, $string ) {
2306 if ( !isset( $this->transformData
[$file] ) ) {
2307 $data = wfGetPrecompiledData( $file );
2308 if ( $data === false ) {
2309 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2311 $this->transformData
[$file] = new ReplacementArray( $data );
2313 return $this->transformData
[$file]->replace( $string );
2317 * For right-to-left language support
2322 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2326 * Return the correct HTML 'dir' attribute value for this language.
2330 return $this->isRTL() ?
'rtl' : 'ltr';
2334 * Return 'left' or 'right' as appropriate alignment for line-start
2335 * for this language's text direction.
2337 * Should be equivalent to CSS3 'start' text-align value....
2341 function alignStart() {
2342 return $this->isRTL() ?
'right' : 'left';
2346 * Return 'right' or 'left' as appropriate alignment for line-end
2347 * for this language's text direction.
2349 * Should be equivalent to CSS3 'end' text-align value....
2353 function alignEnd() {
2354 return $this->isRTL() ?
'left' : 'right';
2358 * A hidden direction mark (LRM or RLM), depending on the language direction
2362 function getDirMark() {
2363 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2369 function capitalizeAllNouns() {
2370 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2374 * An arrow, depending on the language direction
2378 function getArrow() {
2379 return $this->isRTL() ?
'←' : '→';
2383 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2387 function linkPrefixExtension() {
2388 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2394 function getMagicWords() {
2395 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2398 protected function doMagicHook() {
2399 if ( $this->mMagicHookDone
) {
2402 $this->mMagicHookDone
= true;
2403 wfProfileIn( 'LanguageGetMagic' );
2404 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2405 wfProfileOut( 'LanguageGetMagic' );
2409 * Fill a MagicWord object with data from here
2413 function getMagic( $mw ) {
2414 $this->doMagicHook();
2416 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2417 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2419 $magicWords = $this->getMagicWords();
2420 if ( isset( $magicWords[$mw->mId
] ) ) {
2421 $rawEntry = $magicWords[$mw->mId
];
2427 if ( !is_array( $rawEntry ) ) {
2428 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2430 $mw->mCaseSensitive
= $rawEntry[0];
2431 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2436 * Add magic words to the extension array
2438 * @param $newWords array
2440 function addMagicWordsByLang( $newWords ) {
2441 $code = $this->getCode();
2442 $fallbackChain = array();
2443 while ( $code && !in_array( $code, $fallbackChain ) ) {
2444 $fallbackChain[] = $code;
2445 $code = self
::getFallbackFor( $code );
2447 if ( !in_array( 'en', $fallbackChain ) ) {
2448 $fallbackChain[] = 'en';
2450 $fallbackChain = array_reverse( $fallbackChain );
2451 foreach ( $fallbackChain as $code ) {
2452 if ( isset( $newWords[$code] ) ) {
2453 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2459 * Get special page names, as an associative array
2460 * case folded alias => real name
2462 function getSpecialPageAliases() {
2463 // Cache aliases because it may be slow to load them
2464 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2466 $this->mExtendedSpecialPageAliases
=
2467 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2468 wfRunHooks( 'LanguageGetSpecialPageAliases',
2469 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2472 return $this->mExtendedSpecialPageAliases
;
2476 * Italic is unsuitable for some languages
2478 * @param $text String: the text to be emphasized.
2481 function emphasize( $text ) {
2482 return "<em>$text</em>";
2486 * Normally we output all numbers in plain en_US style, that is
2487 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2488 * point twohundredthirtyfive. However this is not sutable for all
2489 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2490 * Icelandic just want to use commas instead of dots, and dots instead
2491 * of commas like "293.291,235".
2493 * An example of this function being called:
2495 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2498 * See LanguageGu.php for the Gujarati implementation and
2499 * $separatorTransformTable on MessageIs.php for
2500 * the , => . and . => , implementation.
2502 * @todo check if it's viable to use localeconv() for the decimal
2504 * @param $number Mixed: the string to be formatted, should be an integer
2505 * or a floating point number.
2506 * @param $nocommafy Bool: set to true for special numbers like dates
2509 function formatNum( $number, $nocommafy = false ) {
2510 global $wgTranslateNumerals;
2511 if ( !$nocommafy ) {
2512 $number = $this->commafy( $number );
2513 $s = $this->separatorTransformTable();
2515 $number = strtr( $number, $s );
2519 if ( $wgTranslateNumerals ) {
2520 $s = $this->digitTransformTable();
2522 $number = strtr( $number, $s );
2530 * @param $number string
2533 function parseFormattedNumber( $number ) {
2534 $s = $this->digitTransformTable();
2536 $number = strtr( $number, array_flip( $s ) );
2539 $s = $this->separatorTransformTable();
2541 $number = strtr( $number, array_flip( $s ) );
2544 $number = strtr( $number, array( ',' => '' ) );
2549 * Adds commas to a given number
2554 function commafy( $_ ) {
2555 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2561 function digitTransformTable() {
2562 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2568 function separatorTransformTable() {
2569 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2573 * Take a list of strings and build a locale-friendly comma-separated
2574 * list, using the local comma-separator message.
2575 * The last two strings are chained with an "and".
2580 function listToText( $l ) {
2582 $m = count( $l ) - 1;
2584 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2586 for ( $i = $m; $i >= 0; $i-- ) {
2589 } elseif ( $i == $m - 1 ) {
2590 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2592 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2600 * Take a list of strings and build a locale-friendly comma-separated
2601 * list, using the local comma-separator message.
2602 * @param $list array of strings to put in a comma list
2605 function commaList( $list ) {
2610 array( 'parsemag', 'escapenoentities', 'language' => $this )
2616 * Take a list of strings and build a locale-friendly semicolon-separated
2617 * list, using the local semicolon-separator message.
2618 * @param $list array of strings to put in a semicolon list
2621 function semicolonList( $list ) {
2625 'semicolon-separator',
2626 array( 'parsemag', 'escapenoentities', 'language' => $this )
2632 * Same as commaList, but separate it with the pipe instead.
2633 * @param $list array of strings to put in a pipe list
2636 function pipeList( $list ) {
2641 array( 'escapenoentities', 'language' => $this )
2647 * Truncate a string to a specified length in bytes, appending an optional
2648 * string (e.g. for ellipses)
2650 * The database offers limited byte lengths for some columns in the database;
2651 * multi-byte character sets mean we need to ensure that only whole characters
2652 * are included, otherwise broken characters can be passed to the user
2654 * If $length is negative, the string will be truncated from the beginning
2656 * @param $string String to truncate
2657 * @param $length Int: maximum length (including ellipses)
2658 * @param $ellipsis String to append to the truncated text
2659 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2660 * $adjustLength was introduced in 1.18, before that behaved as if false.
2663 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2664 # Use the localized ellipsis character
2665 if ( $ellipsis == '...' ) {
2666 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2668 # Check if there is no need to truncate
2669 if ( $length == 0 ) {
2670 return $ellipsis; // convention
2671 } elseif ( strlen( $string ) <= abs( $length ) ) {
2672 return $string; // no need to truncate
2674 $stringOriginal = $string;
2675 # If ellipsis length is >= $length then we can't apply $adjustLength
2676 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2677 $string = $ellipsis; // this can be slightly unexpected
2678 # Otherwise, truncate and add ellipsis...
2680 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2681 if ( $length > 0 ) {
2682 $length -= $eLength;
2683 $string = substr( $string, 0, $length ); // xyz...
2684 $string = $this->removeBadCharLast( $string );
2685 $string = $string . $ellipsis;
2687 $length +
= $eLength;
2688 $string = substr( $string, $length ); // ...xyz
2689 $string = $this->removeBadCharFirst( $string );
2690 $string = $ellipsis . $string;
2693 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2694 # This check is *not* redundant if $adjustLength, due to the single case where
2695 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2696 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2699 return $stringOriginal;
2704 * Remove bytes that represent an incomplete Unicode character
2705 * at the end of string (e.g. bytes of the char are missing)
2707 * @param $string String
2710 protected function removeBadCharLast( $string ) {
2711 if ( $string != '' ) {
2712 $char = ord( $string[strlen( $string ) - 1] );
2714 if ( $char >= 0xc0 ) {
2715 # We got the first byte only of a multibyte char; remove it.
2716 $string = substr( $string, 0, -1 );
2717 } elseif ( $char >= 0x80 &&
2718 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2719 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2721 # We chopped in the middle of a character; remove it
2729 * Remove bytes that represent an incomplete Unicode character
2730 * at the start of string (e.g. bytes of the char are missing)
2732 * @param $string String
2735 protected function removeBadCharFirst( $string ) {
2736 if ( $string != '' ) {
2737 $char = ord( $string[0] );
2738 if ( $char >= 0x80 && $char < 0xc0 ) {
2739 # We chopped in the middle of a character; remove the whole thing
2740 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2747 * Truncate a string of valid HTML to a specified length in bytes,
2748 * appending an optional string (e.g. for ellipses), and return valid HTML
2750 * This is only intended for styled/linked text, such as HTML with
2751 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2752 * Also, this will not detect things like "display:none" CSS.
2754 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2756 * @param string $text HTML string to truncate
2757 * @param int $length (zero/positive) Maximum length (including ellipses)
2758 * @param string $ellipsis String to append to the truncated text
2761 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2762 # Use the localized ellipsis character
2763 if ( $ellipsis == '...' ) {
2764 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2766 # Check if there is clearly no need to truncate
2767 if ( $length <= 0 ) {
2768 return $ellipsis; // no text shown, nothing to format (convention)
2769 } elseif ( strlen( $text ) <= $length ) {
2770 return $text; // string short enough even *with* HTML (short-circuit)
2773 $dispLen = 0; // innerHTML legth so far
2774 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2775 $tagType = 0; // 0-open, 1-close
2776 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2777 $entityState = 0; // 0-not entity, 1-entity
2778 $tag = $ret = ''; // accumulated tag name, accumulated result string
2779 $openTags = array(); // open tag stack
2780 $maybeState = null; // possible truncation state
2782 $textLen = strlen( $text );
2783 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2784 for ( $pos = 0; true; ++
$pos ) {
2785 # Consider truncation once the display length has reached the maximim.
2786 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2787 # Check that we're not in the middle of a bracket/entity...
2788 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2789 if ( !$testingEllipsis ) {
2790 $testingEllipsis = true;
2791 # Save where we are; we will truncate here unless there turn out to
2792 # be so few remaining characters that truncation is not necessary.
2793 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2794 $maybeState = array( $ret, $openTags ); // save state
2796 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2797 # String in fact does need truncation, the truncation point was OK.
2798 list( $ret, $openTags ) = $maybeState; // reload state
2799 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2800 $ret .= $ellipsis; // add ellipsis
2804 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2806 # Read the next char...
2808 $lastCh = $pos ?
$text[$pos - 1] : '';
2809 $ret .= $ch; // add to result string
2811 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2812 $entityState = 0; // for bad HTML
2813 $bracketState = 1; // tag started (checking for backslash)
2814 } elseif ( $ch == '>' ) {
2815 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2816 $entityState = 0; // for bad HTML
2817 $bracketState = 0; // out of brackets
2818 } elseif ( $bracketState == 1 ) {
2820 $tagType = 1; // close tag (e.g. "</span>")
2822 $tagType = 0; // open tag (e.g. "<span>")
2825 $bracketState = 2; // building tag name
2826 } elseif ( $bracketState == 2 ) {
2830 // Name found (e.g. "<a href=..."), add on tag attributes...
2831 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2833 } elseif ( $bracketState == 0 ) {
2834 if ( $entityState ) {
2837 $dispLen++
; // entity is one displayed char
2840 if ( $neLength == 0 && !$maybeState ) {
2841 // Save state without $ch. We want to *hit* the first
2842 // display char (to get tags) but not *use* it if truncating.
2843 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2846 $entityState = 1; // entity found, (e.g. " ")
2848 $dispLen++
; // this char is displayed
2849 // Add the next $max display text chars after this in one swoop...
2850 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2851 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2852 $dispLen +
= $skipped;
2858 // Close the last tag if left unclosed by bad HTML
2859 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2860 while ( count( $openTags ) > 0 ) {
2861 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2867 * truncateHtml() helper function
2868 * like strcspn() but adds the skipped chars to $ret
2877 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2878 if ( $len === null ) {
2879 $len = -1; // -1 means "no limit" for strcspn
2880 } elseif ( $len < 0 ) {
2884 if ( $start < strlen( $text ) ) {
2885 $skipCount = strcspn( $text, $search, $start, $len );
2886 $ret .= substr( $text, $start, $skipCount );
2892 * truncateHtml() helper function
2893 * (a) push or pop $tag from $openTags as needed
2894 * (b) clear $tag value
2895 * @param String &$tag Current HTML tag name we are looking at
2896 * @param int $tagType (0-open tag, 1-close tag)
2897 * @param char $lastCh Character before the '>' that ended this tag
2898 * @param array &$openTags Open tag stack (not accounting for $tag)
2900 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2901 $tag = ltrim( $tag );
2903 if ( $tagType == 0 && $lastCh != '/' ) {
2904 $openTags[] = $tag; // tag opened (didn't close itself)
2905 } elseif ( $tagType == 1 ) {
2906 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2907 array_pop( $openTags ); // tag closed
2915 * Grammatical transformations, needed for inflected languages
2916 * Invoked by putting {{grammar:case|word}} in a message
2918 * @param $word string
2919 * @param $case string
2922 function convertGrammar( $word, $case ) {
2923 global $wgGrammarForms;
2924 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2925 return $wgGrammarForms[$this->getCode()][$case][$word];
2931 * Provides an alternative text depending on specified gender.
2932 * Usage {{gender:username|masculine|feminine|neutral}}.
2933 * username is optional, in which case the gender of current user is used,
2934 * but only in (some) interface messages; otherwise default gender is used.
2935 * If second or third parameter are not specified, masculine is used.
2936 * These details may be overriden per language.
2938 * @param $gender string
2939 * @param $forms array
2943 function gender( $gender, $forms ) {
2944 if ( !count( $forms ) ) {
2947 $forms = $this->preConvertPlural( $forms, 2 );
2948 if ( $gender === 'male' ) {
2951 if ( $gender === 'female' ) {
2954 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2958 * Plural form transformations, needed for some languages.
2959 * For example, there are 3 form of plural in Russian and Polish,
2960 * depending on "count mod 10". See [[w:Plural]]
2961 * For English it is pretty simple.
2963 * Invoked by putting {{plural:count|wordform1|wordform2}}
2964 * or {{plural:count|wordform1|wordform2|wordform3}}
2966 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2968 * @param $count Integer: non-localized number
2969 * @param $forms Array: different plural forms
2970 * @return string Correct form of plural for $count in this language
2972 function convertPlural( $count, $forms ) {
2973 if ( !count( $forms ) ) {
2976 $forms = $this->preConvertPlural( $forms, 2 );
2978 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2982 * Checks that convertPlural was given an array and pads it to requested
2983 * amount of forms by copying the last one.
2985 * @param $count Integer: How many forms should there be at least
2986 * @param $forms Array of forms given to convertPlural
2987 * @return array Padded array of forms or an exception if not an array
2989 protected function preConvertPlural( /* Array */ $forms, $count ) {
2990 while ( count( $forms ) < $count ) {
2991 $forms[] = $forms[count( $forms ) - 1];
2997 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2998 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2999 * (which is an absolute timestamp).
3000 * @param $str String: the validated block duration in English
3001 * @return Somehow translated block duration
3002 * @see LanguageFi.php for example implementation
3004 function translateBlockExpiry( $str ) {
3005 $duration = SpecialBlock
::getSuggestedDurations( $this );
3006 foreach( $duration as $show => $value ){
3007 if ( strcmp( $str, $value ) == 0 ) {
3008 return htmlspecialchars( trim( $show ) );
3012 // Since usually only infinite or indefinite is only on list, so try
3013 // equivalents if still here.
3014 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3015 if ( in_array( $str, $indefs ) ) {
3016 foreach( $indefs as $val ) {
3017 $show = array_search( $val, $duration, true );
3018 if ( $show !== false ) {
3019 return htmlspecialchars( trim( $show ) );
3023 // If all else fails, return the original string.
3028 * languages like Chinese need to be segmented in order for the diff
3031 * @param $text String
3034 function segmentForDiff( $text ) {
3039 * and unsegment to show the result
3041 * @param $text String
3044 function unsegmentForDiff( $text ) {
3049 * convert text to all supported variants
3051 * @param $text string
3054 function autoConvertToAllVariants( $text ) {
3055 return $this->mConverter
->autoConvertToAllVariants( $text );
3059 * convert text to different variants of a language.
3061 * @param $text string
3064 function convert( $text ) {
3065 return $this->mConverter
->convert( $text );
3070 * Convert a Title object to a string in the preferred variant
3072 * @param $title Title
3075 function convertTitle( $title ) {
3076 return $this->mConverter
->convertTitle( $title );
3080 * Check if this is a language with variants
3084 function hasVariants() {
3085 return sizeof( $this->getVariants() ) > 1;
3089 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3091 * @param $text string
3094 function armourMath( $text ) {
3095 return $this->mConverter
->armourMath( $text );
3099 * Perform output conversion on a string, and encode for safe HTML output.
3100 * @param $text String text to be converted
3101 * @param $isTitle Bool whether this conversion is for the article title
3103 * @todo this should get integrated somewhere sane
3105 function convertHtml( $text, $isTitle = false ) {
3106 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3110 * @param $key string
3113 function convertCategoryKey( $key ) {
3114 return $this->mConverter
->convertCategoryKey( $key );
3118 * Get the list of variants supported by this language
3119 * see sample implementation in LanguageZh.php
3121 * @return array an array of language codes
3123 function getVariants() {
3124 return $this->mConverter
->getVariants();
3130 function getPreferredVariant() {
3131 return $this->mConverter
->getPreferredVariant();
3137 function getDefaultVariant() {
3138 return $this->mConverter
->getDefaultVariant();
3144 function getURLVariant() {
3145 return $this->mConverter
->getURLVariant();
3149 * If a language supports multiple variants, it is
3150 * possible that non-existing link in one variant
3151 * actually exists in another variant. this function
3152 * tries to find it. See e.g. LanguageZh.php
3154 * @param $link String: the name of the link
3155 * @param $nt Mixed: the title object of the link
3156 * @param $ignoreOtherCond Boolean: to disable other conditions when
3157 * we need to transclude a template or update a category's link
3158 * @return null the input parameters may be modified upon return
3160 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3161 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3165 * If a language supports multiple variants, converts text
3166 * into an array of all possible variants of the text:
3167 * 'variant' => text in that variant
3169 * @deprecated since 1.17 Use autoConvertToAllVariants()
3171 * @param $text string
3175 function convertLinkToAllVariants( $text ) {
3176 return $this->mConverter
->convertLinkToAllVariants( $text );
3180 * returns language specific options used by User::getPageRenderHash()
3181 * for example, the preferred language variant
3185 function getExtraHashOptions() {
3186 return $this->mConverter
->getExtraHashOptions();
3190 * For languages that support multiple variants, the title of an
3191 * article may be displayed differently in different variants. this
3192 * function returns the apporiate title defined in the body of the article.
3196 function getParsedTitle() {
3197 return $this->mConverter
->getParsedTitle();
3201 * Enclose a string with the "no conversion" tag. This is used by
3202 * various functions in the Parser
3204 * @param $text String: text to be tagged for no conversion
3205 * @param $noParse bool
3206 * @return string the tagged text
3208 function markNoConversion( $text, $noParse = false ) {
3209 return $this->mConverter
->markNoConversion( $text, $noParse );
3213 * A regular expression to match legal word-trailing characters
3214 * which should be merged onto a link of the form [[foo]]bar.
3218 function linkTrail() {
3219 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3225 function getLangObj() {
3230 * Get the RFC 3066 code for this language object
3234 function getCode() {
3235 return $this->mCode
;
3239 * @param $code string
3241 function setCode( $code ) {
3242 $this->mCode
= $code;
3246 * Get the name of a file for a certain language code
3247 * @param $prefix string Prepend this to the filename
3248 * @param $code string Language code
3249 * @param $suffix string Append this to the filename
3250 * @return string $prefix . $mangledCode . $suffix
3252 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3253 // Protect against path traversal
3254 if ( !Language
::isValidCode( $code )
3255 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3257 throw new MWException( "Invalid language code \"$code\"" );
3260 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3264 * Get the language code from a file name. Inverse of getFileName()
3265 * @param $filename string $prefix . $languageCode . $suffix
3266 * @param $prefix string Prefix before the language code
3267 * @param $suffix string Suffix after the language code
3268 * @return string Language code, or false if $prefix or $suffix isn't found
3270 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3272 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3273 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3274 if ( !count( $m ) ) {
3277 return str_replace( '_', '-', strtolower( $m[1] ) );
3281 * @param $code string
3284 static function getMessagesFileName( $code ) {
3286 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3290 * @param $code string
3293 static function getClassFileName( $code ) {
3295 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3299 * Get the fallback for a given language
3301 * @param $code string
3303 * @return false|string
3305 static function getFallbackFor( $code ) {
3306 if ( $code === 'en' ) {
3310 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
3315 * Get all messages for a given language
3316 * WARNING: this may take a long time
3318 * @param $code string
3322 static function getMessagesFor( $code ) {
3323 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3327 * Get a message for a given language
3329 * @param $key string
3330 * @param $code string
3334 static function getMessageFor( $key, $code ) {
3335 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3342 function fixVariableInNamespace( $talk ) {
3343 if ( strpos( $talk, '$1' ) === false ) {
3347 global $wgMetaNamespace;
3348 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3350 # Allow grammar transformations
3351 # Allowing full message-style parsing would make simple requests
3352 # such as action=raw much more expensive than they need to be.
3353 # This will hopefully cover most cases.
3354 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3355 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3356 return str_replace( ' ', '_', $talk );
3363 function replaceGrammarInNamespace( $m ) {
3364 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3368 * @throws MWException
3371 static function getCaseMaps() {
3372 static $wikiUpperChars, $wikiLowerChars;
3373 if ( isset( $wikiUpperChars ) ) {
3374 return array( $wikiUpperChars, $wikiLowerChars );
3377 wfProfileIn( __METHOD__
);
3378 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3379 if ( $arr === false ) {
3380 throw new MWException(
3381 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3383 $wikiUpperChars = $arr['wikiUpperChars'];
3384 $wikiLowerChars = $arr['wikiLowerChars'];
3385 wfProfileOut( __METHOD__
);
3386 return array( $wikiUpperChars, $wikiLowerChars );
3390 * Decode an expiry (block, protection, etc) which has come from the DB
3392 * @param $expiry String: Database expiry String
3393 * @param $format Bool|Int true to process using language functions, or TS_ constant
3394 * to return the expiry in a given timestamp
3397 public function formatExpiry( $expiry, $format = true ) {
3398 static $infinity, $infinityMsg;
3399 if( $infinity === null ){
3400 $infinityMsg = wfMessage( 'infiniteblock' );
3401 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3404 if ( $expiry == '' ||
$expiry == $infinity ) {
3405 return $format === true
3409 return $format === true
3410 ?
$this->timeanddate( $expiry )
3411 : wfTimestamp( $format, $expiry );
3417 * @param $seconds int|float
3418 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3419 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3420 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3423 function formatTimePeriod( $seconds, $format = false ) {
3424 if ( round( $seconds * 10 ) < 100 ) {
3425 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3426 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3427 } elseif ( round( $seconds ) < 60 ) {
3428 $s = $this->formatNum( round( $seconds ) );
3429 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3430 } elseif ( round( $seconds ) < 3600 ) {
3431 $minutes = floor( $seconds / 60 );
3432 $secondsPart = round( fmod( $seconds, 60 ) );
3433 if ( $secondsPart == 60 ) {
3437 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3439 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3440 } elseif ( round( $seconds ) <= 2*86400 ) {
3441 $hours = floor( $seconds / 3600 );
3442 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3443 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3444 if ( $secondsPart == 60 ) {
3448 if ( $minutes == 60 ) {
3452 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3454 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3455 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3456 $s .= ' ' . $this->formatNum( $secondsPart ) .
3457 $this->getMessageFromDB( 'seconds-abbrev' );
3460 $days = floor( $seconds / 86400 );
3461 if ( $format === 'avoidminutes' ) {
3462 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3463 if ( $hours == 24 ) {
3467 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3469 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3470 } elseif ( $format === 'avoidseconds' ) {
3471 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3472 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3473 if ( $minutes == 60 ) {
3477 if ( $hours == 24 ) {
3481 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3483 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3485 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3487 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3489 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3499 function formatBitrate( $bps ) {
3500 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3502 return $this->formatNum( $bps ) . $units[0];
3504 $unitIndex = floor( log10( $bps ) / 3 );
3505 $mantissa = $bps / pow( 1000, $unitIndex );
3506 if ( $mantissa < 10 ) {
3507 $mantissa = round( $mantissa, 1 );
3509 $mantissa = round( $mantissa );
3511 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3515 * Format a size in bytes for output, using an appropriate
3516 * unit (B, KB, MB or GB) according to the magnitude in question
3518 * @param $size Size to format
3519 * @return string Plain text (not HTML)
3521 function formatSize( $size ) {
3522 // For small sizes no decimal places necessary
3524 if ( $size > 1024 ) {
3525 $size = $size / 1024;
3526 if ( $size > 1024 ) {
3527 $size = $size / 1024;
3528 // For MB and bigger two decimal places are smarter
3530 if ( $size > 1024 ) {
3531 $size = $size / 1024;
3532 $msg = 'size-gigabytes';
3534 $msg = 'size-megabytes';
3537 $msg = 'size-kilobytes';
3540 $msg = 'size-bytes';
3542 $size = round( $size, $round );
3543 $text = $this->getMessageFromDB( $msg );
3544 return str_replace( '$1', $this->formatNum( $size ), $text );
3548 * Get the conversion rule title, if any.
3552 function getConvRuleTitle() {
3553 return $this->mConverter
->getConvRuleTitle();