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
224 public static function isValidBuiltInCode( $code ) {
225 return preg_match( '/^[a-z0-9-]*$/i', $code );
229 * Get the LocalisationCache instance
231 * @return LocalisationCache
233 public static function getLocalisationCache() {
234 if ( is_null( self
::$dataCache ) ) {
235 global $wgLocalisationCacheConf;
236 $class = $wgLocalisationCacheConf['class'];
237 self
::$dataCache = new $class( $wgLocalisationCacheConf );
239 return self
::$dataCache;
242 function __construct() {
243 $this->mConverter
= new FakeConverter( $this );
244 // Set the code to the name of the descendant
245 if ( get_class( $this ) == 'Language' ) {
248 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
250 self
::getLocalisationCache();
254 * Reduce memory usage
256 function __destruct() {
257 foreach ( $this as $name => $value ) {
258 unset( $this->$name );
263 * Hook which will be called if this is the content language.
264 * Descendants can use this to register hook functions or modify globals
266 function initContLang() { }
271 function getFallbackLanguageCode() {
272 if ( $this->mCode
=== 'en' ) {
275 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
280 * Exports $wgBookstoreListEn
283 function getBookstoreList() {
284 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
290 function getNamespaces() {
291 if ( is_null( $this->namespaceNames
) ) {
292 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
294 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
295 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
297 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
299 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
300 if ( $wgMetaNamespaceTalk ) {
301 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
303 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
304 $this->namespaceNames
[NS_PROJECT_TALK
] =
305 $this->fixVariableInNamespace( $talk );
308 # Sometimes a language will be localised but not actually exist on this wiki.
309 foreach( $this->namespaceNames
as $key => $text ) {
310 if ( !isset( $validNamespaces[$key] ) ) {
311 unset( $this->namespaceNames
[$key] );
315 # The above mixing may leave namespaces out of canonical order.
316 # Re-order by namespace ID number...
317 ksort( $this->namespaceNames
);
319 return $this->namespaceNames
;
323 * A convenience function that returns the same thing as
324 * getNamespaces() except with the array values changed to ' '
325 * where it found '_', useful for producing output to be displayed
326 * e.g. in <select> forms.
330 function getFormattedNamespaces() {
331 $ns = $this->getNamespaces();
332 foreach ( $ns as $k => $v ) {
333 $ns[$k] = strtr( $v, '_', ' ' );
339 * Get a namespace value by key
341 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
342 * echo $mw_ns; // prints 'MediaWiki'
345 * @param $index Int: the array key of the namespace to return
346 * @return mixed, string if the namespace value exists, otherwise false
348 function getNsText( $index ) {
349 $ns = $this->getNamespaces();
350 return isset( $ns[$index] ) ?
$ns[$index] : false;
354 * A convenience function that returns the same thing as
355 * getNsText() except with '_' changed to ' ', useful for
358 * @param $index string
362 function getFormattedNsText( $index ) {
363 $ns = $this->getNsText( $index );
364 return strtr( $ns, '_', ' ' );
368 * Returns gender-dependent namespace alias if available.
369 * @param $index Int: namespace index
370 * @param $gender String: gender key (male, female... )
374 function getGenderNsText( $index, $gender ) {
375 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
376 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
380 * Whether this language makes distinguishes genders for example in
385 function needsGenderDistinction() {
386 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
387 return count( $aliases ) > 0;
391 * Get a namespace key by value, case insensitive.
392 * Only matches namespace names for the current language, not the
393 * canonical ones defined in Namespace.php.
395 * @param $text String
396 * @return mixed An integer if $text is a valid value otherwise false
398 function getLocalNsIndex( $text ) {
399 $lctext = $this->lc( $text );
400 $ids = $this->getNamespaceIds();
401 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
407 function getNamespaceAliases() {
408 if ( is_null( $this->namespaceAliases
) ) {
409 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
413 foreach ( $aliases as $name => $index ) {
414 if ( $index === NS_PROJECT_TALK
) {
415 unset( $aliases[$name] );
416 $name = $this->fixVariableInNamespace( $name );
417 $aliases[$name] = $index;
422 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
423 foreach ( $genders as $index => $forms ) {
424 foreach ( $forms as $alias ) {
425 $aliases[$alias] = $index;
429 $this->namespaceAliases
= $aliases;
431 return $this->namespaceAliases
;
437 function getNamespaceIds() {
438 if ( is_null( $this->mNamespaceIds
) ) {
439 global $wgNamespaceAliases;
440 # Put namespace names and aliases into a hashtable.
441 # If this is too slow, then we should arrange it so that it is done
442 # before caching. The catch is that at pre-cache time, the above
443 # class-specific fixup hasn't been done.
444 $this->mNamespaceIds
= array();
445 foreach ( $this->getNamespaces() as $index => $name ) {
446 $this->mNamespaceIds
[$this->lc( $name )] = $index;
448 foreach ( $this->getNamespaceAliases() as $name => $index ) {
449 $this->mNamespaceIds
[$this->lc( $name )] = $index;
451 if ( $wgNamespaceAliases ) {
452 foreach ( $wgNamespaceAliases as $name => $index ) {
453 $this->mNamespaceIds
[$this->lc( $name )] = $index;
457 return $this->mNamespaceIds
;
462 * Get a namespace key by value, case insensitive. Canonical namespace
463 * names override custom ones defined for the current language.
465 * @param $text String
466 * @return mixed An integer if $text is a valid value otherwise false
468 function getNsIndex( $text ) {
469 $lctext = $this->lc( $text );
470 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
473 $ids = $this->getNamespaceIds();
474 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
478 * short names for language variants used for language conversion links.
480 * @param $code String
483 function getVariantname( $code ) {
484 return $this->getMessageFromDB( "variantname-$code" );
488 * @param $name string
491 function specialPage( $name ) {
492 $aliases = $this->getSpecialPageAliases();
493 if ( isset( $aliases[$name][0] ) ) {
494 $name = $aliases[$name][0];
496 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
502 function getQuickbarSettings() {
504 $this->getMessage( 'qbsettings-none' ),
505 $this->getMessage( 'qbsettings-fixedleft' ),
506 $this->getMessage( 'qbsettings-fixedright' ),
507 $this->getMessage( 'qbsettings-floatingleft' ),
508 $this->getMessage( 'qbsettings-floatingright' ),
509 $this->getMessage( 'qbsettings-directionality' )
516 function getDatePreferences() {
517 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
523 function getDateFormats() {
524 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
528 * @return array|string
530 function getDefaultDateFormat() {
531 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
532 if ( $df === 'dmy or mdy' ) {
533 global $wgAmericanDates;
534 return $wgAmericanDates ?
'mdy' : 'dmy';
543 function getDatePreferenceMigrationMap() {
544 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
551 function getImageFile( $image ) {
552 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
558 function getExtraUserToggles() {
559 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
566 function getUserToggle( $tog ) {
567 return $this->getMessageFromDB( "tog-$tog" );
571 * Get language names, indexed by code.
572 * If $customisedOnly is true, only returns codes with a messages file
574 * @param $customisedOnly bool
578 public static function getLanguageNames( $customisedOnly = false ) {
579 global $wgExtraLanguageNames;
580 static $coreLanguageNames;
582 if ( $coreLanguageNames === null ) {
583 include( MWInit
::compiledPath( 'languages/Names.php' ) );
586 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
587 if ( !$customisedOnly ) {
593 $dir = opendir( "$IP/languages/messages" );
594 while ( false !== ( $file = readdir( $dir ) ) ) {
595 $code = self
::getCodeFromFileName( $file, 'Messages' );
596 if ( $code && isset( $allNames[$code] ) ) {
597 $names[$code] = $allNames[$code];
605 * Get translated language names. This is done on best effort and
606 * by default this is exactly the same as Language::getLanguageNames.
607 * The CLDR extension provides translated names.
608 * @param $code String Language code.
609 * @return Array language code => language name
612 public static function getTranslatedLanguageNames( $code ) {
614 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
616 foreach ( self
::getLanguageNames() as $code => $name ) {
617 if ( !isset( $names[$code] ) ) $names[$code] = $name;
624 * Get a message from the MediaWiki namespace.
626 * @param $msg String: message name
629 function getMessageFromDB( $msg ) {
630 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
634 * @param $code string
637 function getLanguageName( $code ) {
638 $names = self
::getLanguageNames();
639 if ( !array_key_exists( $code, $names ) ) {
642 return $names[$code];
649 function getMonthName( $key ) {
650 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
656 function getMonthNamesArray() {
657 $monthNames = array( '' );
658 for ( $i=1; $i < 13; $i++
) {
659 $monthNames[] = $this->getMonthName( $i );
668 function getMonthNameGen( $key ) {
669 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
676 function getMonthAbbreviation( $key ) {
677 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
683 function getMonthAbbreviationsArray() {
684 $monthNames = array( '' );
685 for ( $i=1; $i < 13; $i++
) {
686 $monthNames[] = $this->getMonthAbbreviation( $i );
695 function getWeekdayName( $key ) {
696 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
703 function getWeekdayAbbreviation( $key ) {
704 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
711 function getIranianCalendarMonthName( $key ) {
712 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
719 function getHebrewCalendarMonthName( $key ) {
720 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
727 function getHebrewCalendarMonthNameGen( $key ) {
728 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
735 function getHijriCalendarMonthName( $key ) {
736 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
740 * Used by date() and time() to adjust the time output.
742 * @param $ts Int the time in date('YmdHis') format
743 * @param $tz Mixed: adjust the time by this amount (default false, mean we
744 * get user timecorrection setting)
747 function userAdjust( $ts, $tz = false ) {
748 global $wgUser, $wgLocalTZoffset;
750 if ( $tz === false ) {
751 $tz = $wgUser->getOption( 'timecorrection' );
754 $data = explode( '|', $tz, 3 );
756 if ( $data[0] == 'ZoneInfo' ) {
757 wfSuppressWarnings();
758 $userTZ = timezone_open( $data[2] );
760 if ( $userTZ !== false ) {
761 $date = date_create( $ts, timezone_open( 'UTC' ) );
762 date_timezone_set( $date, $userTZ );
763 $date = date_format( $date, 'YmdHis' );
766 # Unrecognized timezone, default to 'Offset' with the stored offset.
771 if ( $data[0] == 'System' ||
$tz == '' ) {
772 # Global offset in minutes.
773 if ( isset( $wgLocalTZoffset ) ) {
774 $minDiff = $wgLocalTZoffset;
776 } elseif ( $data[0] == 'Offset' ) {
777 $minDiff = intval( $data[1] );
779 $data = explode( ':', $tz );
780 if ( count( $data ) == 2 ) {
781 $data[0] = intval( $data[0] );
782 $data[1] = intval( $data[1] );
783 $minDiff = abs( $data[0] ) * 60 +
$data[1];
784 if ( $data[0] < 0 ) {
785 $minDiff = -$minDiff;
788 $minDiff = intval( $data[0] ) * 60;
792 # No difference ? Return time unchanged
793 if ( 0 == $minDiff ) {
797 wfSuppressWarnings(); // E_STRICT system time bitching
798 # Generate an adjusted date; take advantage of the fact that mktime
799 # will normalize out-of-range values so we don't have to split $minDiff
800 # into hours and minutes.
802 (int)substr( $ts, 8, 2 ) ), # Hours
803 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
804 (int)substr( $ts, 12, 2 ), # Seconds
805 (int)substr( $ts, 4, 2 ), # Month
806 (int)substr( $ts, 6, 2 ), # Day
807 (int)substr( $ts, 0, 4 ) ); # Year
809 $date = date( 'YmdHis', $t );
816 * This is a workalike of PHP's date() function, but with better
817 * internationalisation, a reduced set of format characters, and a better
820 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
821 * PHP manual for definitions. There are a number of extensions, which
824 * xn Do not translate digits of the next numeric format character
825 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
826 * xr Use roman numerals for the next numeric format character
827 * xh Use hebrew numerals for the next numeric format character
829 * xg Genitive month name
831 * xij j (day number) in Iranian calendar
832 * xiF F (month name) in Iranian calendar
833 * xin n (month number) in Iranian calendar
834 * xiY Y (full year) in Iranian calendar
836 * xjj j (day number) in Hebrew calendar
837 * xjF F (month name) in Hebrew calendar
838 * xjt t (days in month) in Hebrew calendar
839 * xjx xg (genitive month name) in Hebrew calendar
840 * xjn n (month number) in Hebrew calendar
841 * xjY Y (full year) in Hebrew calendar
843 * xmj j (day number) in Hijri calendar
844 * xmF F (month name) in Hijri calendar
845 * xmn n (month number) in Hijri calendar
846 * xmY Y (full year) in Hijri calendar
848 * xkY Y (full year) in Thai solar calendar. Months and days are
849 * identical to the Gregorian calendar
850 * xoY Y (full year) in Minguo calendar or Juche year.
851 * Months and days are identical to the
853 * xtY Y (full year) in Japanese nengo. Months and days are
854 * identical to the Gregorian calendar
856 * Characters enclosed in double quotes will be considered literal (with
857 * the quotes themselves removed). Unmatched quotes will be considered
858 * literal quotes. Example:
860 * "The month is" F => The month is January
863 * Backslash escaping is also supported.
865 * Input timestamp is assumed to be pre-normalized to the desired local
868 * @param $format String
869 * @param $ts String: 14-character timestamp
872 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
876 function sprintfDate( $format, $ts ) {
889 for ( $p = 0; $p < strlen( $format ); $p++
) {
892 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
893 $code .= $format[++
$p];
896 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
897 $code .= $format[++
$p];
908 $rawToggle = !$rawToggle;
917 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
920 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
921 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
924 $num = substr( $ts, 6, 2 );
927 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
928 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
931 $num = intval( substr( $ts, 6, 2 ) );
935 $iranian = self
::tsToIranian( $ts );
941 $hijri = self
::tsToHijri( $ts );
947 $hebrew = self
::tsToHebrew( $ts );
953 $unix = wfTimestamp( TS_UNIX
, $ts );
955 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
959 $unix = wfTimestamp( TS_UNIX
, $ts );
961 $w = gmdate( 'w', $unix );
966 $unix = wfTimestamp( TS_UNIX
, $ts );
968 $num = gmdate( 'w', $unix );
972 $unix = wfTimestamp( TS_UNIX
, $ts );
974 $num = gmdate( 'z', $unix );
978 $unix = wfTimestamp( TS_UNIX
, $ts );
980 $num = gmdate( 'W', $unix );
983 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
987 $iranian = self
::tsToIranian( $ts );
989 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
993 $hijri = self
::tsToHijri( $ts );
995 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
999 $hebrew = self
::tsToHebrew( $ts );
1001 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1004 $num = substr( $ts, 4, 2 );
1007 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1010 $num = intval( substr( $ts, 4, 2 ) );
1014 $iranian = self
::tsToIranian( $ts );
1020 $hijri = self
::tsToHijri ( $ts );
1026 $hebrew = self
::tsToHebrew( $ts );
1032 $unix = wfTimestamp( TS_UNIX
, $ts );
1034 $num = gmdate( 't', $unix );
1038 $hebrew = self
::tsToHebrew( $ts );
1044 $unix = wfTimestamp( TS_UNIX
, $ts );
1046 $num = gmdate( 'L', $unix );
1050 $unix = wfTimestamp( TS_UNIX
, $ts );
1052 $num = date( 'o', $unix );
1055 $num = substr( $ts, 0, 4 );
1059 $iranian = self
::tsToIranian( $ts );
1065 $hijri = self
::tsToHijri( $ts );
1071 $hebrew = self
::tsToHebrew( $ts );
1077 $thai = self
::tsToYear( $ts, 'thai' );
1083 $minguo = self
::tsToYear( $ts, 'minguo' );
1089 $tenno = self
::tsToYear( $ts, 'tenno' );
1094 $num = substr( $ts, 2, 2 );
1097 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1100 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1103 $h = substr( $ts, 8, 2 );
1104 $num = $h %
12 ?
$h %
12 : 12;
1107 $num = intval( substr( $ts, 8, 2 ) );
1110 $h = substr( $ts, 8, 2 );
1111 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1114 $num = substr( $ts, 8, 2 );
1117 $num = substr( $ts, 10, 2 );
1120 $num = substr( $ts, 12, 2 );
1124 $unix = wfTimestamp( TS_UNIX
, $ts );
1126 $s .= gmdate( 'c', $unix );
1130 $unix = wfTimestamp( TS_UNIX
, $ts );
1132 $s .= gmdate( 'r', $unix );
1136 $unix = wfTimestamp( TS_UNIX
, $ts );
1141 # Backslash escaping
1142 if ( $p < strlen( $format ) - 1 ) {
1143 $s .= $format[++
$p];
1150 if ( $p < strlen( $format ) - 1 ) {
1151 $endQuote = strpos( $format, '"', $p +
1 );
1152 if ( $endQuote === false ) {
1153 # No terminating quote, assume literal "
1156 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1160 # Quote at end of string, assume literal "
1167 if ( $num !== false ) {
1168 if ( $rawToggle ||
$raw ) {
1171 } elseif ( $roman ) {
1172 $s .= self
::romanNumeral( $num );
1174 } elseif ( $hebrewNum ) {
1175 $s .= self
::hebrewNumeral( $num );
1178 $s .= $this->formatNum( $num, true );
1185 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1186 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1189 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1190 * Gregorian dates to Iranian dates. Originally written in C, it
1191 * is released under the terms of GNU Lesser General Public
1192 * License. Conversion to PHP was performed by Niklas Laxström.
1194 * Link: http://www.farsiweb.info/jalali/jalali.c
1200 private static function tsToIranian( $ts ) {
1201 $gy = substr( $ts, 0, 4 ) -1600;
1202 $gm = substr( $ts, 4, 2 ) -1;
1203 $gd = substr( $ts, 6, 2 ) -1;
1205 # Days passed from the beginning (including leap years)
1207 +
floor( ( $gy +
3 ) / 4 )
1208 - floor( ( $gy +
99 ) / 100 )
1209 +
floor( ( $gy +
399 ) / 400 );
1212 // Add days of the past months of this year
1213 for ( $i = 0; $i < $gm; $i++
) {
1214 $gDayNo +
= self
::$GREG_DAYS[$i];
1218 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1222 // Days passed in current month
1225 $jDayNo = $gDayNo - 79;
1227 $jNp = floor( $jDayNo / 12053 );
1230 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1233 if ( $jDayNo >= 366 ) {
1234 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1235 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1238 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1239 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1245 return array( $jy, $jm, $jd );
1249 * Converting Gregorian dates to Hijri dates.
1251 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1253 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1259 private static function tsToHijri( $ts ) {
1260 $year = substr( $ts, 0, 4 );
1261 $month = substr( $ts, 4, 2 );
1262 $day = substr( $ts, 6, 2 );
1270 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1271 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1274 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1275 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1276 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1279 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1280 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1283 $zl = $zjd -1948440 +
10632;
1284 $zn = (int)( ( $zl - 1 ) / 10631 );
1285 $zl = $zl - 10631 * $zn +
354;
1286 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1287 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1288 $zm = (int)( ( 24 * $zl ) / 709 );
1289 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1290 $zy = 30 * $zn +
$zj - 30;
1292 return array( $zy, $zm, $zd );
1296 * Converting Gregorian dates to Hebrew dates.
1298 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1299 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1300 * to translate the relevant functions into PHP and release them under
1303 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1304 * and Adar II is 14. In a non-leap year, Adar is 6.
1310 private static function tsToHebrew( $ts ) {
1312 $year = substr( $ts, 0, 4 );
1313 $month = substr( $ts, 4, 2 );
1314 $day = substr( $ts, 6, 2 );
1316 # Calculate Hebrew year
1317 $hebrewYear = $year +
3760;
1319 # Month number when September = 1, August = 12
1321 if ( $month > 12 ) {
1328 # Calculate day of year from 1 September
1330 for ( $i = 1; $i < $month; $i++
) {
1334 # Check if the year is leap
1335 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1338 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1345 # Calculate the start of the Hebrew year
1346 $start = self
::hebrewYearStart( $hebrewYear );
1348 # Calculate next year's start
1349 if ( $dayOfYear <= $start ) {
1350 # Day is before the start of the year - it is the previous year
1352 $nextStart = $start;
1356 # Add days since previous year's 1 September
1358 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1362 # Start of the new (previous) year
1363 $start = self
::hebrewYearStart( $hebrewYear );
1366 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1369 # Calculate Hebrew day of year
1370 $hebrewDayOfYear = $dayOfYear - $start;
1372 # Difference between year's days
1373 $diff = $nextStart - $start;
1374 # Add 12 (or 13 for leap years) days to ignore the difference between
1375 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1376 # difference is only about the year type
1377 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1383 # Check the year pattern, and is leap year
1384 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1385 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1386 # and non-leap years
1387 $yearPattern = $diff %
30;
1388 # Check if leap year
1389 $isLeap = $diff >= 30;
1391 # Calculate day in the month from number of day in the Hebrew year
1392 # Don't check Adar - if the day is not in Adar, we will stop before;
1393 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1394 $hebrewDay = $hebrewDayOfYear;
1397 while ( $hebrewMonth <= 12 ) {
1398 # Calculate days in this month
1399 if ( $isLeap && $hebrewMonth == 6 ) {
1400 # Adar in a leap year
1402 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1404 if ( $hebrewDay <= $days ) {
1408 # Subtract the days of Adar I
1409 $hebrewDay -= $days;
1412 if ( $hebrewDay <= $days ) {
1418 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1419 # Cheshvan in a complete year (otherwise as the rule below)
1421 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1422 # Kislev in an incomplete year (otherwise as the rule below)
1425 # Odd months have 30 days, even have 29
1426 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1428 if ( $hebrewDay <= $days ) {
1429 # In the current month
1432 # Subtract the days of the current month
1433 $hebrewDay -= $days;
1434 # Try in the next month
1439 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1443 * This calculates the Hebrew year start, as days since 1 September.
1444 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1445 * Used for Hebrew date.
1451 private static function hebrewYearStart( $year ) {
1452 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1453 $b = intval( ( $year - 1 ) %
4 );
1454 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1458 $Mar = intval( $m );
1464 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1465 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1467 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1469 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1473 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1478 * Algorithm to convert Gregorian dates to Thai solar dates,
1479 * Minguo dates or Minguo dates.
1481 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1482 * http://en.wikipedia.org/wiki/Minguo_calendar
1483 * http://en.wikipedia.org/wiki/Japanese_era_name
1485 * @param $ts String: 14-character timestamp
1486 * @param $cName String: calender name
1487 * @return Array: converted year, month, day
1489 private static function tsToYear( $ts, $cName ) {
1490 $gy = substr( $ts, 0, 4 );
1491 $gm = substr( $ts, 4, 2 );
1492 $gd = substr( $ts, 6, 2 );
1494 if ( !strcmp( $cName, 'thai' ) ) {
1496 # Add 543 years to the Gregorian calendar
1497 # Months and days are identical
1498 $gy_offset = $gy +
543;
1499 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1501 # Deduct 1911 years from the Gregorian calendar
1502 # Months and days are identical
1503 $gy_offset = $gy - 1911;
1504 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1505 # Nengō dates up to Meiji period
1506 # Deduct years from the Gregorian calendar
1507 # depending on the nengo periods
1508 # Months and days are identical
1509 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1511 $gy_gannen = $gy - 1868 +
1;
1512 $gy_offset = $gy_gannen;
1513 if ( $gy_gannen == 1 ) {
1516 $gy_offset = '明治' . $gy_offset;
1518 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1519 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1520 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1521 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1522 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1526 $gy_gannen = $gy - 1912 +
1;
1527 $gy_offset = $gy_gannen;
1528 if ( $gy_gannen == 1 ) {
1531 $gy_offset = '大正' . $gy_offset;
1533 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1534 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1535 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1539 $gy_gannen = $gy - 1926 +
1;
1540 $gy_offset = $gy_gannen;
1541 if ( $gy_gannen == 1 ) {
1544 $gy_offset = '昭和' . $gy_offset;
1547 $gy_gannen = $gy - 1989 +
1;
1548 $gy_offset = $gy_gannen;
1549 if ( $gy_gannen == 1 ) {
1552 $gy_offset = '平成' . $gy_offset;
1558 return array( $gy_offset, $gm, $gd );
1562 * Roman number formatting up to 3000
1568 static function romanNumeral( $num ) {
1569 static $table = array(
1570 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1571 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1572 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1573 array( '', 'M', 'MM', 'MMM' )
1576 $num = intval( $num );
1577 if ( $num > 3000 ||
$num <= 0 ) {
1582 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1583 if ( $num >= $pow10 ) {
1584 $s .= $table[$i][floor( $num / $pow10 )];
1586 $num = $num %
$pow10;
1592 * Hebrew Gematria number formatting up to 9999
1598 static function hebrewNumeral( $num ) {
1599 static $table = array(
1600 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1601 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1602 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1603 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1606 $num = intval( $num );
1607 if ( $num > 9999 ||
$num <= 0 ) {
1612 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1613 if ( $num >= $pow10 ) {
1614 if ( $num == 15 ||
$num == 16 ) {
1615 $s .= $table[0][9] . $table[0][$num - 9];
1618 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1619 if ( $pow10 == 1000 ) {
1624 $num = $num %
$pow10;
1626 if ( strlen( $s ) == 2 ) {
1629 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1630 $str .= substr( $s, strlen( $s ) - 2, 2 );
1632 $start = substr( $str, 0, strlen( $str ) - 2 );
1633 $end = substr( $str, strlen( $str ) - 2 );
1636 $str = $start . 'ך';
1639 $str = $start . 'ם';
1642 $str = $start . 'ן';
1645 $str = $start . 'ף';
1648 $str = $start . 'ץ';
1655 * This is meant to be used by time(), date(), and timeanddate() to get
1656 * the date preference they're supposed to use, it should be used in
1660 * function timeanddate([...], $format = true) {
1661 * $datePreference = $this->dateFormat($format);
1666 * @param $usePrefs Mixed: if true, the user's preference is used
1667 * if false, the site/language default is used
1668 * if int/string, assumed to be a format.
1671 function dateFormat( $usePrefs = true ) {
1674 if ( is_bool( $usePrefs ) ) {
1676 $datePreference = $wgUser->getDatePreference();
1678 $datePreference = (string)User
::getDefaultOption( 'date' );
1681 $datePreference = (string)$usePrefs;
1685 if ( $datePreference == '' ) {
1689 return $datePreference;
1693 * Get a format string for a given type and preference
1694 * @param $type string May be date, time or both
1695 * @param $pref string The format name as it appears in Messages*.php
1699 function getDateFormatString( $type, $pref ) {
1700 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1701 if ( $pref == 'default' ) {
1702 $pref = $this->getDefaultDateFormat();
1703 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1705 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1706 if ( is_null( $df ) ) {
1707 $pref = $this->getDefaultDateFormat();
1708 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1711 $this->dateFormatStrings
[$type][$pref] = $df;
1713 return $this->dateFormatStrings
[$type][$pref];
1717 * @param $ts Mixed: the time format which needs to be turned into a
1718 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1719 * @param $adj Bool: whether to adjust the time output according to the
1720 * user configured offset ($timecorrection)
1721 * @param $format Mixed: true to use user's date format preference
1722 * @param $timecorrection String|bool the time offset as returned by
1723 * validateTimeZone() in Special:Preferences
1726 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1727 $ts = wfTimestamp( TS_MW
, $ts );
1729 $ts = $this->userAdjust( $ts, $timecorrection );
1731 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1732 return $this->sprintfDate( $df, $ts );
1736 * @param $ts Mixed: the time format which needs to be turned into a
1737 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1738 * @param $adj Bool: whether to adjust the time output according to the
1739 * user configured offset ($timecorrection)
1740 * @param $format Mixed: true to use user's date format preference
1741 * @param $timecorrection String|bool the time offset as returned by
1742 * validateTimeZone() in Special:Preferences
1745 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1746 $ts = wfTimestamp( TS_MW
, $ts );
1748 $ts = $this->userAdjust( $ts, $timecorrection );
1750 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1751 return $this->sprintfDate( $df, $ts );
1755 * @param $ts Mixed: the time format which needs to be turned into a
1756 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1757 * @param $adj Bool: whether to adjust the time output according to the
1758 * user configured offset ($timecorrection)
1759 * @param $format Mixed: what format to return, if it's false output the
1760 * default one (default true)
1761 * @param $timecorrection String|bool the time offset as returned by
1762 * validateTimeZone() in Special:Preferences
1765 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1766 $ts = wfTimestamp( TS_MW
, $ts );
1768 $ts = $this->userAdjust( $ts, $timecorrection );
1770 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1771 return $this->sprintfDate( $df, $ts );
1775 * @param $key string
1776 * @return array|null
1778 function getMessage( $key ) {
1779 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1785 function getAllMessages() {
1786 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1795 function iconv( $in, $out, $string ) {
1796 # This is a wrapper for iconv in all languages except esperanto,
1797 # which does some nasty x-conversions beforehand
1799 # Even with //IGNORE iconv can whine about illegal characters in
1800 # *input* string. We just ignore those too.
1801 # REF: http://bugs.php.net/bug.php?id=37166
1802 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1803 wfSuppressWarnings();
1804 $text = iconv( $in, $out . '//IGNORE', $string );
1805 wfRestoreWarnings();
1809 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1812 * @param $matches array
1813 * @return mixed|string
1815 function ucwordbreaksCallbackAscii( $matches ) {
1816 return $this->ucfirst( $matches[1] );
1820 * @param $matches array
1823 function ucwordbreaksCallbackMB( $matches ) {
1824 return mb_strtoupper( $matches[0] );
1828 * @param $matches array
1831 function ucCallback( $matches ) {
1832 list( $wikiUpperChars ) = self
::getCaseMaps();
1833 return strtr( $matches[1], $wikiUpperChars );
1837 * @param $matches array
1840 function lcCallback( $matches ) {
1841 list( , $wikiLowerChars ) = self
::getCaseMaps();
1842 return strtr( $matches[1], $wikiLowerChars );
1846 * @param $matches array
1849 function ucwordsCallbackMB( $matches ) {
1850 return mb_strtoupper( $matches[0] );
1854 * @param $matches array
1857 function ucwordsCallbackWiki( $matches ) {
1858 list( $wikiUpperChars ) = self
::getCaseMaps();
1859 return strtr( $matches[0], $wikiUpperChars );
1863 * Make a string's first character uppercase
1865 * @param $str string
1869 function ucfirst( $str ) {
1871 if ( $o < 96 ) { // if already uppercase...
1873 } elseif ( $o < 128 ) {
1874 return ucfirst( $str ); // use PHP's ucfirst()
1876 // fall back to more complex logic in case of multibyte strings
1877 return $this->uc( $str, true );
1882 * Convert a string to uppercase
1884 * @param $str string
1885 * @param $first bool
1889 function uc( $str, $first = false ) {
1890 if ( function_exists( 'mb_strtoupper' ) ) {
1892 if ( $this->isMultibyte( $str ) ) {
1893 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1895 return ucfirst( $str );
1898 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1901 if ( $this->isMultibyte( $str ) ) {
1902 $x = $first ?
'^' : '';
1903 return preg_replace_callback(
1904 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1905 array( $this, 'ucCallback' ),
1909 return $first ?
ucfirst( $str ) : strtoupper( $str );
1915 * @param $str string
1916 * @return mixed|string
1918 function lcfirst( $str ) {
1921 return strval( $str );
1922 } elseif ( $o >= 128 ) {
1923 return $this->lc( $str, true );
1924 } elseif ( $o > 96 ) {
1927 $str[0] = strtolower( $str[0] );
1933 * @param $str string
1934 * @param $first bool
1935 * @return mixed|string
1937 function lc( $str, $first = false ) {
1938 if ( function_exists( 'mb_strtolower' ) ) {
1940 if ( $this->isMultibyte( $str ) ) {
1941 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1943 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1946 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1949 if ( $this->isMultibyte( $str ) ) {
1950 $x = $first ?
'^' : '';
1951 return preg_replace_callback(
1952 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1953 array( $this, 'lcCallback' ),
1957 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1963 * @param $str string
1966 function isMultibyte( $str ) {
1967 return (bool)preg_match( '/[\x80-\xff]/', $str );
1971 * @param $str string
1972 * @return mixed|string
1974 function ucwords( $str ) {
1975 if ( $this->isMultibyte( $str ) ) {
1976 $str = $this->lc( $str );
1978 // regexp to find first letter in each word (i.e. after each space)
1979 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1981 // function to use to capitalize a single char
1982 if ( function_exists( 'mb_strtoupper' ) ) {
1983 return preg_replace_callback(
1985 array( $this, 'ucwordsCallbackMB' ),
1989 return preg_replace_callback(
1991 array( $this, 'ucwordsCallbackWiki' ),
1996 return ucwords( strtolower( $str ) );
2001 * capitalize words at word breaks
2003 * @param $str string
2006 function ucwordbreaks( $str ) {
2007 if ( $this->isMultibyte( $str ) ) {
2008 $str = $this->lc( $str );
2010 // since \b doesn't work for UTF-8, we explicitely define word break chars
2011 $breaks = "[ \-\(\)\}\{\.,\?!]";
2013 // find first letter after word break
2014 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2016 if ( function_exists( 'mb_strtoupper' ) ) {
2017 return preg_replace_callback(
2019 array( $this, 'ucwordbreaksCallbackMB' ),
2023 return preg_replace_callback(
2025 array( $this, 'ucwordsCallbackWiki' ),
2030 return preg_replace_callback(
2031 '/\b([\w\x80-\xff]+)\b/',
2032 array( $this, 'ucwordbreaksCallbackAscii' ),
2039 * Return a case-folded representation of $s
2041 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2042 * and $s2 are the same except for the case of their characters. It is not
2043 * necessary for the value returned to make sense when displayed.
2045 * Do *not* perform any other normalisation in this function. If a caller
2046 * uses this function when it should be using a more general normalisation
2047 * function, then fix the caller.
2053 function caseFold( $s ) {
2054 return $this->uc( $s );
2061 function checkTitleEncoding( $s ) {
2062 if ( is_array( $s ) ) {
2063 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2065 # Check for non-UTF-8 URLs
2066 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2071 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2072 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2077 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2083 function fallback8bitEncoding() {
2084 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2088 * Most writing systems use whitespace to break up words.
2089 * Some languages such as Chinese don't conventionally do this,
2090 * which requires special handling when breaking up words for
2095 function hasWordBreaks() {
2100 * Some languages such as Chinese require word segmentation,
2101 * Specify such segmentation when overridden in derived class.
2103 * @param $string String
2106 function segmentByWord( $string ) {
2111 * Some languages have special punctuation need to be normalized.
2112 * Make such changes here.
2114 * @param $string String
2117 function normalizeForSearch( $string ) {
2118 return self
::convertDoubleWidth( $string );
2122 * convert double-width roman characters to single-width.
2123 * range: ff00-ff5f ~= 0020-007f
2125 * @param $string string
2129 protected static function convertDoubleWidth( $string ) {
2130 static $full = null;
2131 static $half = null;
2133 if ( $full === null ) {
2134 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2135 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2136 $full = str_split( $fullWidth, 3 );
2137 $half = str_split( $halfWidth );
2140 $string = str_replace( $full, $half, $string );
2145 * @param $string string
2146 * @param $pattern string
2149 protected static function insertSpace( $string, $pattern ) {
2150 $string = preg_replace( $pattern, " $1 ", $string );
2151 $string = preg_replace( '/ +/', ' ', $string );
2156 * @param $termsArray array
2159 function convertForSearchResult( $termsArray ) {
2160 # some languages, e.g. Chinese, need to do a conversion
2161 # in order for search results to be displayed correctly
2166 * Get the first character of a string.
2171 function firstChar( $s ) {
2174 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2175 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2180 if ( isset( $matches[1] ) ) {
2181 if ( strlen( $matches[1] ) != 3 ) {
2185 // Break down Hangul syllables to grab the first jamo
2186 $code = utf8ToCodepoint( $matches[1] );
2187 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2189 } elseif ( $code < 0xb098 ) {
2190 return "\xe3\x84\xb1";
2191 } elseif ( $code < 0xb2e4 ) {
2192 return "\xe3\x84\xb4";
2193 } elseif ( $code < 0xb77c ) {
2194 return "\xe3\x84\xb7";
2195 } elseif ( $code < 0xb9c8 ) {
2196 return "\xe3\x84\xb9";
2197 } elseif ( $code < 0xbc14 ) {
2198 return "\xe3\x85\x81";
2199 } elseif ( $code < 0xc0ac ) {
2200 return "\xe3\x85\x82";
2201 } elseif ( $code < 0xc544 ) {
2202 return "\xe3\x85\x85";
2203 } elseif ( $code < 0xc790 ) {
2204 return "\xe3\x85\x87";
2205 } elseif ( $code < 0xcc28 ) {
2206 return "\xe3\x85\x88";
2207 } elseif ( $code < 0xce74 ) {
2208 return "\xe3\x85\x8a";
2209 } elseif ( $code < 0xd0c0 ) {
2210 return "\xe3\x85\x8b";
2211 } elseif ( $code < 0xd30c ) {
2212 return "\xe3\x85\x8c";
2213 } elseif ( $code < 0xd558 ) {
2214 return "\xe3\x85\x8d";
2216 return "\xe3\x85\x8e";
2223 function initEncoding() {
2224 # Some languages may have an alternate char encoding option
2225 # (Esperanto X-coding, Japanese furigana conversion, etc)
2226 # If this language is used as the primary content language,
2227 # an override to the defaults can be set here on startup.
2234 function recodeForEdit( $s ) {
2235 # For some languages we'll want to explicitly specify
2236 # which characters make it into the edit box raw
2237 # or are converted in some way or another.
2238 global $wgEditEncoding;
2239 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2242 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2250 function recodeInput( $s ) {
2251 # Take the previous into account.
2252 global $wgEditEncoding;
2253 if ( $wgEditEncoding != '' ) {
2254 $enc = $wgEditEncoding;
2258 if ( $enc == 'UTF-8' ) {
2261 return $this->iconv( $enc, 'UTF-8', $s );
2266 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2267 * also cleans up certain backwards-compatible sequences, converting them
2268 * to the modern Unicode equivalent.
2270 * This is language-specific for performance reasons only.
2276 function normalize( $s ) {
2277 global $wgAllUnicodeFixes;
2278 $s = UtfNormal
::cleanUp( $s );
2279 if ( $wgAllUnicodeFixes ) {
2280 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2281 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2288 * Transform a string using serialized data stored in the given file (which
2289 * must be in the serialized subdirectory of $IP). The file contains pairs
2290 * mapping source characters to destination characters.
2292 * The data is cached in process memory. This will go faster if you have the
2293 * FastStringSearch extension.
2295 * @param $file string
2296 * @param $string string
2300 function transformUsingPairFile( $file, $string ) {
2301 if ( !isset( $this->transformData
[$file] ) ) {
2302 $data = wfGetPrecompiledData( $file );
2303 if ( $data === false ) {
2304 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2306 $this->transformData
[$file] = new ReplacementArray( $data );
2308 return $this->transformData
[$file]->replace( $string );
2312 * For right-to-left language support
2317 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2321 * Return the correct HTML 'dir' attribute value for this language.
2325 return $this->isRTL() ?
'rtl' : 'ltr';
2329 * Return 'left' or 'right' as appropriate alignment for line-start
2330 * for this language's text direction.
2332 * Should be equivalent to CSS3 'start' text-align value....
2336 function alignStart() {
2337 return $this->isRTL() ?
'right' : 'left';
2341 * Return 'right' or 'left' as appropriate alignment for line-end
2342 * for this language's text direction.
2344 * Should be equivalent to CSS3 'end' text-align value....
2348 function alignEnd() {
2349 return $this->isRTL() ?
'left' : 'right';
2353 * A hidden direction mark (LRM or RLM), depending on the language direction
2355 * @param $opposite Boolean Get the direction mark opposite to your language
2358 function getDirMark( $opposite = false ) {
2359 $rtl = "\xE2\x80\x8F";
2360 $ltr = "\xE2\x80\x8E";
2361 if( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2362 return $this->isRTL() ?
$rtl : $ltr;
2368 function capitalizeAllNouns() {
2369 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2373 * An arrow, depending on the language direction
2377 function getArrow() {
2378 return $this->isRTL() ?
'←' : '→';
2382 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2386 function linkPrefixExtension() {
2387 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2393 function getMagicWords() {
2394 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2397 protected function doMagicHook() {
2398 if ( $this->mMagicHookDone
) {
2401 $this->mMagicHookDone
= true;
2402 wfProfileIn( 'LanguageGetMagic' );
2403 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2404 wfProfileOut( 'LanguageGetMagic' );
2408 * Fill a MagicWord object with data from here
2412 function getMagic( $mw ) {
2413 $this->doMagicHook();
2415 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2416 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2418 $magicWords = $this->getMagicWords();
2419 if ( isset( $magicWords[$mw->mId
] ) ) {
2420 $rawEntry = $magicWords[$mw->mId
];
2426 if ( !is_array( $rawEntry ) ) {
2427 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2429 $mw->mCaseSensitive
= $rawEntry[0];
2430 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2435 * Add magic words to the extension array
2437 * @param $newWords array
2439 function addMagicWordsByLang( $newWords ) {
2440 $code = $this->getCode();
2441 $fallbackChain = array();
2442 while ( $code && !in_array( $code, $fallbackChain ) ) {
2443 $fallbackChain[] = $code;
2444 $code = self
::getFallbackFor( $code );
2446 if ( !in_array( 'en', $fallbackChain ) ) {
2447 $fallbackChain[] = 'en';
2449 $fallbackChain = array_reverse( $fallbackChain );
2450 foreach ( $fallbackChain as $code ) {
2451 if ( isset( $newWords[$code] ) ) {
2452 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2458 * Get special page names, as an associative array
2459 * case folded alias => real name
2461 function getSpecialPageAliases() {
2462 // Cache aliases because it may be slow to load them
2463 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2465 $this->mExtendedSpecialPageAliases
=
2466 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2467 wfRunHooks( 'LanguageGetSpecialPageAliases',
2468 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2471 return $this->mExtendedSpecialPageAliases
;
2475 * Italic is unsuitable for some languages
2477 * @param $text String: the text to be emphasized.
2480 function emphasize( $text ) {
2481 return "<em>$text</em>";
2485 * Normally we output all numbers in plain en_US style, that is
2486 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2487 * point twohundredthirtyfive. However this is not sutable for all
2488 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2489 * Icelandic just want to use commas instead of dots, and dots instead
2490 * of commas like "293.291,235".
2492 * An example of this function being called:
2494 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2497 * See LanguageGu.php for the Gujarati implementation and
2498 * $separatorTransformTable on MessageIs.php for
2499 * the , => . and . => , implementation.
2501 * @todo check if it's viable to use localeconv() for the decimal
2503 * @param $number Mixed: the string to be formatted, should be an integer
2504 * or a floating point number.
2505 * @param $nocommafy Bool: set to true for special numbers like dates
2508 function formatNum( $number, $nocommafy = false ) {
2509 global $wgTranslateNumerals;
2510 if ( !$nocommafy ) {
2511 $number = $this->commafy( $number );
2512 $s = $this->separatorTransformTable();
2514 $number = strtr( $number, $s );
2518 if ( $wgTranslateNumerals ) {
2519 $s = $this->digitTransformTable();
2521 $number = strtr( $number, $s );
2529 * @param $number string
2532 function parseFormattedNumber( $number ) {
2533 $s = $this->digitTransformTable();
2535 $number = strtr( $number, array_flip( $s ) );
2538 $s = $this->separatorTransformTable();
2540 $number = strtr( $number, array_flip( $s ) );
2543 $number = strtr( $number, array( ',' => '' ) );
2548 * Adds commas to a given number
2553 function commafy( $_ ) {
2554 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2560 function digitTransformTable() {
2561 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2567 function separatorTransformTable() {
2568 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2572 * Take a list of strings and build a locale-friendly comma-separated
2573 * list, using the local comma-separator message.
2574 * The last two strings are chained with an "and".
2579 function listToText( $l ) {
2581 $m = count( $l ) - 1;
2583 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2585 for ( $i = $m; $i >= 0; $i-- ) {
2588 } elseif ( $i == $m - 1 ) {
2589 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2591 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2599 * Take a list of strings and build a locale-friendly comma-separated
2600 * list, using the local comma-separator message.
2601 * @param $list array of strings to put in a comma list
2604 function commaList( $list ) {
2609 array( 'parsemag', 'escapenoentities', 'language' => $this )
2615 * Take a list of strings and build a locale-friendly semicolon-separated
2616 * list, using the local semicolon-separator message.
2617 * @param $list array of strings to put in a semicolon list
2620 function semicolonList( $list ) {
2624 'semicolon-separator',
2625 array( 'parsemag', 'escapenoentities', 'language' => $this )
2631 * Same as commaList, but separate it with the pipe instead.
2632 * @param $list array of strings to put in a pipe list
2635 function pipeList( $list ) {
2640 array( 'escapenoentities', 'language' => $this )
2646 * Truncate a string to a specified length in bytes, appending an optional
2647 * string (e.g. for ellipses)
2649 * The database offers limited byte lengths for some columns in the database;
2650 * multi-byte character sets mean we need to ensure that only whole characters
2651 * are included, otherwise broken characters can be passed to the user
2653 * If $length is negative, the string will be truncated from the beginning
2655 * @param $string String to truncate
2656 * @param $length Int: maximum length (including ellipses)
2657 * @param $ellipsis String to append to the truncated text
2658 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2659 * $adjustLength was introduced in 1.18, before that behaved as if false.
2662 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2663 # Use the localized ellipsis character
2664 if ( $ellipsis == '...' ) {
2665 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2667 # Check if there is no need to truncate
2668 if ( $length == 0 ) {
2669 return $ellipsis; // convention
2670 } elseif ( strlen( $string ) <= abs( $length ) ) {
2671 return $string; // no need to truncate
2673 $stringOriginal = $string;
2674 # If ellipsis length is >= $length then we can't apply $adjustLength
2675 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2676 $string = $ellipsis; // this can be slightly unexpected
2677 # Otherwise, truncate and add ellipsis...
2679 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2680 if ( $length > 0 ) {
2681 $length -= $eLength;
2682 $string = substr( $string, 0, $length ); // xyz...
2683 $string = $this->removeBadCharLast( $string );
2684 $string = $string . $ellipsis;
2686 $length +
= $eLength;
2687 $string = substr( $string, $length ); // ...xyz
2688 $string = $this->removeBadCharFirst( $string );
2689 $string = $ellipsis . $string;
2692 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2693 # This check is *not* redundant if $adjustLength, due to the single case where
2694 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2695 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2698 return $stringOriginal;
2703 * Remove bytes that represent an incomplete Unicode character
2704 * at the end of string (e.g. bytes of the char are missing)
2706 * @param $string String
2709 protected function removeBadCharLast( $string ) {
2710 if ( $string != '' ) {
2711 $char = ord( $string[strlen( $string ) - 1] );
2713 if ( $char >= 0xc0 ) {
2714 # We got the first byte only of a multibyte char; remove it.
2715 $string = substr( $string, 0, -1 );
2716 } elseif ( $char >= 0x80 &&
2717 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2718 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2720 # We chopped in the middle of a character; remove it
2728 * Remove bytes that represent an incomplete Unicode character
2729 * at the start of string (e.g. bytes of the char are missing)
2731 * @param $string String
2734 protected function removeBadCharFirst( $string ) {
2735 if ( $string != '' ) {
2736 $char = ord( $string[0] );
2737 if ( $char >= 0x80 && $char < 0xc0 ) {
2738 # We chopped in the middle of a character; remove the whole thing
2739 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2746 * Truncate a string of valid HTML to a specified length in bytes,
2747 * appending an optional string (e.g. for ellipses), and return valid HTML
2749 * This is only intended for styled/linked text, such as HTML with
2750 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2751 * Also, this will not detect things like "display:none" CSS.
2753 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2755 * @param string $text HTML string to truncate
2756 * @param int $length (zero/positive) Maximum length (including ellipses)
2757 * @param string $ellipsis String to append to the truncated text
2760 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2761 # Use the localized ellipsis character
2762 if ( $ellipsis == '...' ) {
2763 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2765 # Check if there is clearly no need to truncate
2766 if ( $length <= 0 ) {
2767 return $ellipsis; // no text shown, nothing to format (convention)
2768 } elseif ( strlen( $text ) <= $length ) {
2769 return $text; // string short enough even *with* HTML (short-circuit)
2772 $dispLen = 0; // innerHTML legth so far
2773 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2774 $tagType = 0; // 0-open, 1-close
2775 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2776 $entityState = 0; // 0-not entity, 1-entity
2777 $tag = $ret = ''; // accumulated tag name, accumulated result string
2778 $openTags = array(); // open tag stack
2779 $maybeState = null; // possible truncation state
2781 $textLen = strlen( $text );
2782 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2783 for ( $pos = 0; true; ++
$pos ) {
2784 # Consider truncation once the display length has reached the maximim.
2785 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2786 # Check that we're not in the middle of a bracket/entity...
2787 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2788 if ( !$testingEllipsis ) {
2789 $testingEllipsis = true;
2790 # Save where we are; we will truncate here unless there turn out to
2791 # be so few remaining characters that truncation is not necessary.
2792 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2793 $maybeState = array( $ret, $openTags ); // save state
2795 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2796 # String in fact does need truncation, the truncation point was OK.
2797 list( $ret, $openTags ) = $maybeState; // reload state
2798 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2799 $ret .= $ellipsis; // add ellipsis
2803 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2805 # Read the next char...
2807 $lastCh = $pos ?
$text[$pos - 1] : '';
2808 $ret .= $ch; // add to result string
2810 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2811 $entityState = 0; // for bad HTML
2812 $bracketState = 1; // tag started (checking for backslash)
2813 } elseif ( $ch == '>' ) {
2814 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2815 $entityState = 0; // for bad HTML
2816 $bracketState = 0; // out of brackets
2817 } elseif ( $bracketState == 1 ) {
2819 $tagType = 1; // close tag (e.g. "</span>")
2821 $tagType = 0; // open tag (e.g. "<span>")
2824 $bracketState = 2; // building tag name
2825 } elseif ( $bracketState == 2 ) {
2829 // Name found (e.g. "<a href=..."), add on tag attributes...
2830 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2832 } elseif ( $bracketState == 0 ) {
2833 if ( $entityState ) {
2836 $dispLen++
; // entity is one displayed char
2839 if ( $neLength == 0 && !$maybeState ) {
2840 // Save state without $ch. We want to *hit* the first
2841 // display char (to get tags) but not *use* it if truncating.
2842 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2845 $entityState = 1; // entity found, (e.g. " ")
2847 $dispLen++
; // this char is displayed
2848 // Add the next $max display text chars after this in one swoop...
2849 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2850 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2851 $dispLen +
= $skipped;
2857 // Close the last tag if left unclosed by bad HTML
2858 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2859 while ( count( $openTags ) > 0 ) {
2860 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2866 * truncateHtml() helper function
2867 * like strcspn() but adds the skipped chars to $ret
2876 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2877 if ( $len === null ) {
2878 $len = -1; // -1 means "no limit" for strcspn
2879 } elseif ( $len < 0 ) {
2883 if ( $start < strlen( $text ) ) {
2884 $skipCount = strcspn( $text, $search, $start, $len );
2885 $ret .= substr( $text, $start, $skipCount );
2891 * truncateHtml() helper function
2892 * (a) push or pop $tag from $openTags as needed
2893 * (b) clear $tag value
2894 * @param String &$tag Current HTML tag name we are looking at
2895 * @param int $tagType (0-open tag, 1-close tag)
2896 * @param char $lastCh Character before the '>' that ended this tag
2897 * @param array &$openTags Open tag stack (not accounting for $tag)
2899 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2900 $tag = ltrim( $tag );
2902 if ( $tagType == 0 && $lastCh != '/' ) {
2903 $openTags[] = $tag; // tag opened (didn't close itself)
2904 } elseif ( $tagType == 1 ) {
2905 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2906 array_pop( $openTags ); // tag closed
2914 * Grammatical transformations, needed for inflected languages
2915 * Invoked by putting {{grammar:case|word}} in a message
2917 * @param $word string
2918 * @param $case string
2921 function convertGrammar( $word, $case ) {
2922 global $wgGrammarForms;
2923 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2924 return $wgGrammarForms[$this->getCode()][$case][$word];
2930 * Provides an alternative text depending on specified gender.
2931 * Usage {{gender:username|masculine|feminine|neutral}}.
2932 * username is optional, in which case the gender of current user is used,
2933 * but only in (some) interface messages; otherwise default gender is used.
2934 * If second or third parameter are not specified, masculine is used.
2935 * These details may be overriden per language.
2937 * @param $gender string
2938 * @param $forms array
2942 function gender( $gender, $forms ) {
2943 if ( !count( $forms ) ) {
2946 $forms = $this->preConvertPlural( $forms, 2 );
2947 if ( $gender === 'male' ) {
2950 if ( $gender === 'female' ) {
2953 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2957 * Plural form transformations, needed for some languages.
2958 * For example, there are 3 form of plural in Russian and Polish,
2959 * depending on "count mod 10". See [[w:Plural]]
2960 * For English it is pretty simple.
2962 * Invoked by putting {{plural:count|wordform1|wordform2}}
2963 * or {{plural:count|wordform1|wordform2|wordform3}}
2965 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2967 * @param $count Integer: non-localized number
2968 * @param $forms Array: different plural forms
2969 * @return string Correct form of plural for $count in this language
2971 function convertPlural( $count, $forms ) {
2972 if ( !count( $forms ) ) {
2975 $forms = $this->preConvertPlural( $forms, 2 );
2977 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2981 * Checks that convertPlural was given an array and pads it to requested
2982 * amount of forms by copying the last one.
2984 * @param $count Integer: How many forms should there be at least
2985 * @param $forms Array of forms given to convertPlural
2986 * @return array Padded array of forms or an exception if not an array
2988 protected function preConvertPlural( /* Array */ $forms, $count ) {
2989 while ( count( $forms ) < $count ) {
2990 $forms[] = $forms[count( $forms ) - 1];
2996 * This translates the duration ("1 week", "4 days", etc)
2997 * as well as the expiry time (which is an absolute timestamp).
2998 * @param $str String: the validated block duration in English
2999 * @return Somehow translated block duration
3000 * @see LanguageFi.php for example implementation
3002 function translateBlockExpiry( $str ) {
3003 $duration = SpecialBlock
::getSuggestedDurations( $this );
3004 foreach( $duration as $show => $value ){
3005 if ( strcmp( $str, $value ) == 0 ) {
3006 return htmlspecialchars( trim( $show ) );
3010 // Since usually only infinite or indefinite is only on list, so try
3011 // equivalents if still here.
3012 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3013 if ( in_array( $str, $indefs ) ) {
3014 foreach( $indefs as $val ) {
3015 $show = array_search( $val, $duration, true );
3016 if ( $show !== false ) {
3017 return htmlspecialchars( trim( $show ) );
3021 // If no duration is given, but a timestamp, display that
3022 return ( strtotime( $str ) ?
$this->timeanddate( strtotime( $str ) ) : $str );
3026 * languages like Chinese need to be segmented in order for the diff
3029 * @param $text String
3032 function segmentForDiff( $text ) {
3037 * and unsegment to show the result
3039 * @param $text String
3042 function unsegmentForDiff( $text ) {
3047 * convert text to all supported variants
3049 * @param $text string
3052 function autoConvertToAllVariants( $text ) {
3053 return $this->mConverter
->autoConvertToAllVariants( $text );
3057 * convert text to different variants of a language.
3059 * @param $text string
3062 function convert( $text ) {
3063 return $this->mConverter
->convert( $text );
3068 * Convert a Title object to a string in the preferred variant
3070 * @param $title Title
3073 function convertTitle( $title ) {
3074 return $this->mConverter
->convertTitle( $title );
3078 * Check if this is a language with variants
3082 function hasVariants() {
3083 return sizeof( $this->getVariants() ) > 1;
3087 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3089 * @param $text string
3092 function armourMath( $text ) {
3093 return $this->mConverter
->armourMath( $text );
3097 * Perform output conversion on a string, and encode for safe HTML output.
3098 * @param $text String text to be converted
3099 * @param $isTitle Bool whether this conversion is for the article title
3101 * @todo this should get integrated somewhere sane
3103 function convertHtml( $text, $isTitle = false ) {
3104 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3108 * @param $key string
3111 function convertCategoryKey( $key ) {
3112 return $this->mConverter
->convertCategoryKey( $key );
3116 * Get the list of variants supported by this language
3117 * see sample implementation in LanguageZh.php
3119 * @return array an array of language codes
3121 function getVariants() {
3122 return $this->mConverter
->getVariants();
3128 function getPreferredVariant() {
3129 return $this->mConverter
->getPreferredVariant();
3135 function getDefaultVariant() {
3136 return $this->mConverter
->getDefaultVariant();
3142 function getURLVariant() {
3143 return $this->mConverter
->getURLVariant();
3147 * If a language supports multiple variants, it is
3148 * possible that non-existing link in one variant
3149 * actually exists in another variant. this function
3150 * tries to find it. See e.g. LanguageZh.php
3152 * @param $link String: the name of the link
3153 * @param $nt Mixed: the title object of the link
3154 * @param $ignoreOtherCond Boolean: to disable other conditions when
3155 * we need to transclude a template or update a category's link
3156 * @return null the input parameters may be modified upon return
3158 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3159 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3163 * If a language supports multiple variants, converts text
3164 * into an array of all possible variants of the text:
3165 * 'variant' => text in that variant
3167 * @deprecated since 1.17 Use autoConvertToAllVariants()
3169 * @param $text string
3173 function convertLinkToAllVariants( $text ) {
3174 return $this->mConverter
->convertLinkToAllVariants( $text );
3178 * returns language specific options used by User::getPageRenderHash()
3179 * for example, the preferred language variant
3183 function getExtraHashOptions() {
3184 return $this->mConverter
->getExtraHashOptions();
3188 * For languages that support multiple variants, the title of an
3189 * article may be displayed differently in different variants. this
3190 * function returns the apporiate title defined in the body of the article.
3194 function getParsedTitle() {
3195 return $this->mConverter
->getParsedTitle();
3199 * Enclose a string with the "no conversion" tag. This is used by
3200 * various functions in the Parser
3202 * @param $text String: text to be tagged for no conversion
3203 * @param $noParse bool
3204 * @return string the tagged text
3206 function markNoConversion( $text, $noParse = false ) {
3207 return $this->mConverter
->markNoConversion( $text, $noParse );
3211 * A regular expression to match legal word-trailing characters
3212 * which should be merged onto a link of the form [[foo]]bar.
3216 function linkTrail() {
3217 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3223 function getLangObj() {
3228 * Get the RFC 3066 code for this language object
3232 function getCode() {
3233 return $this->mCode
;
3237 * @param $code string
3239 function setCode( $code ) {
3240 $this->mCode
= $code;
3244 * Get the name of a file for a certain language code
3245 * @param $prefix string Prepend this to the filename
3246 * @param $code string Language code
3247 * @param $suffix string Append this to the filename
3248 * @return string $prefix . $mangledCode . $suffix
3250 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3251 // Protect against path traversal
3252 if ( !Language
::isValidCode( $code )
3253 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3255 throw new MWException( "Invalid language code \"$code\"" );
3258 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3262 * Get the language code from a file name. Inverse of getFileName()
3263 * @param $filename string $prefix . $languageCode . $suffix
3264 * @param $prefix string Prefix before the language code
3265 * @param $suffix string Suffix after the language code
3266 * @return string Language code, or false if $prefix or $suffix isn't found
3268 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3270 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3271 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3272 if ( !count( $m ) ) {
3275 return str_replace( '_', '-', strtolower( $m[1] ) );
3279 * @param $code string
3282 static function getMessagesFileName( $code ) {
3284 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3288 * @param $code string
3291 static function getClassFileName( $code ) {
3293 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3297 * Get the fallback for a given language
3299 * @param $code string
3301 * @return false|string
3303 static function getFallbackFor( $code ) {
3304 if ( $code === 'en' ) {
3308 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
3313 * Get all messages for a given language
3314 * WARNING: this may take a long time
3316 * @param $code string
3320 static function getMessagesFor( $code ) {
3321 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3325 * Get a message for a given language
3327 * @param $key string
3328 * @param $code string
3332 static function getMessageFor( $key, $code ) {
3333 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3340 function fixVariableInNamespace( $talk ) {
3341 if ( strpos( $talk, '$1' ) === false ) {
3345 global $wgMetaNamespace;
3346 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3348 # Allow grammar transformations
3349 # Allowing full message-style parsing would make simple requests
3350 # such as action=raw much more expensive than they need to be.
3351 # This will hopefully cover most cases.
3352 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3353 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3354 return str_replace( ' ', '_', $talk );
3361 function replaceGrammarInNamespace( $m ) {
3362 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3366 * @throws MWException
3369 static function getCaseMaps() {
3370 static $wikiUpperChars, $wikiLowerChars;
3371 if ( isset( $wikiUpperChars ) ) {
3372 return array( $wikiUpperChars, $wikiLowerChars );
3375 wfProfileIn( __METHOD__
);
3376 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3377 if ( $arr === false ) {
3378 throw new MWException(
3379 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3381 $wikiUpperChars = $arr['wikiUpperChars'];
3382 $wikiLowerChars = $arr['wikiLowerChars'];
3383 wfProfileOut( __METHOD__
);
3384 return array( $wikiUpperChars, $wikiLowerChars );
3388 * Decode an expiry (block, protection, etc) which has come from the DB
3390 * @param $expiry String: Database expiry String
3391 * @param $format Bool|Int true to process using language functions, or TS_ constant
3392 * to return the expiry in a given timestamp
3395 public function formatExpiry( $expiry, $format = true ) {
3396 static $infinity, $infinityMsg;
3397 if( $infinity === null ){
3398 $infinityMsg = wfMessage( 'infiniteblock' );
3399 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3402 if ( $expiry == '' ||
$expiry == $infinity ) {
3403 return $format === true
3407 return $format === true
3408 ?
$this->timeanddate( $expiry )
3409 : wfTimestamp( $format, $expiry );
3415 * @param $seconds int|float
3416 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3417 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3418 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3421 function formatTimePeriod( $seconds, $format = false ) {
3422 if ( round( $seconds * 10 ) < 100 ) {
3423 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3424 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3425 } elseif ( round( $seconds ) < 60 ) {
3426 $s = $this->formatNum( round( $seconds ) );
3427 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3428 } elseif ( round( $seconds ) < 3600 ) {
3429 $minutes = floor( $seconds / 60 );
3430 $secondsPart = round( fmod( $seconds, 60 ) );
3431 if ( $secondsPart == 60 ) {
3435 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3437 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3438 } elseif ( round( $seconds ) <= 2*86400 ) {
3439 $hours = floor( $seconds / 3600 );
3440 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3441 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3442 if ( $secondsPart == 60 ) {
3446 if ( $minutes == 60 ) {
3450 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3452 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3453 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3454 $s .= ' ' . $this->formatNum( $secondsPart ) .
3455 $this->getMessageFromDB( 'seconds-abbrev' );
3458 $days = floor( $seconds / 86400 );
3459 if ( $format === 'avoidminutes' ) {
3460 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3461 if ( $hours == 24 ) {
3465 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3467 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3468 } elseif ( $format === 'avoidseconds' ) {
3469 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3470 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3471 if ( $minutes == 60 ) {
3475 if ( $hours == 24 ) {
3479 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3481 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3483 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3485 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3487 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3497 function formatBitrate( $bps ) {
3498 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3500 return $this->formatNum( $bps ) . $units[0];
3502 $unitIndex = floor( log10( $bps ) / 3 );
3503 $mantissa = $bps / pow( 1000, $unitIndex );
3504 if ( $mantissa < 10 ) {
3505 $mantissa = round( $mantissa, 1 );
3507 $mantissa = round( $mantissa );
3509 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3513 * Format a size in bytes for output, using an appropriate
3514 * unit (B, KB, MB or GB) according to the magnitude in question
3516 * @param $size int Size to format
3517 * @return string Plain text (not HTML)
3519 function formatSize( $size ) {
3520 // For small sizes no decimal places necessary
3522 if ( $size > 1024 ) {
3523 $size = $size / 1024;
3524 if ( $size > 1024 ) {
3525 $size = $size / 1024;
3526 // For MB and bigger two decimal places are smarter
3528 if ( $size > 1024 ) {
3529 $size = $size / 1024;
3530 $msg = 'size-gigabytes';
3532 $msg = 'size-megabytes';
3535 $msg = 'size-kilobytes';
3538 $msg = 'size-bytes';
3540 $size = round( $size, $round );
3541 $text = $this->getMessageFromDB( $msg );
3542 return str_replace( '$1', $this->formatNum( $size ), $text );
3546 * Get the conversion rule title, if any.
3550 function getConvRuleTitle() {
3551 return $this->mConverter
->getConvRuleTitle();