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 global $wgInputEncoding, $wgOutputEncoding;
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
35 * a fake language converter
41 function __construct( $langobj ) { $this->mLang
= $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang
->getCode() ); }
46 function getPreferredVariant() { return $this->mLang
->getCode(); }
47 function getDefaultVariant() { return $this->mLang
->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
60 * Internationalisation code
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
136 static function factory( $code ) {
137 if ( !isset( self
::$mLangObjCache[$code] ) ) {
138 if ( count( self
::$mLangObjCache ) > 10 ) {
139 // Don't keep a billion objects around, that's stupid.
140 self
::$mLangObjCache = array();
142 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
144 return self
::$mLangObjCache[$code];
148 * Create a language object for a given language code
150 protected static function newFromCode( $code ) {
152 static $recursionLevel = 0;
153 if ( $code == 'en' ) {
156 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
157 // Preload base classes to work around APC/PHP5 bug
158 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
159 include_once( "$IP/languages/classes/$class.deps.php" );
161 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
162 include_once( "$IP/languages/classes/$class.php" );
166 if ( $recursionLevel > 5 ) {
167 throw new MWException( "Language fallback loop detected when creating class $class\n" );
170 if ( !class_exists( $class ) ) {
171 $fallback = Language
::getFallbackFor( $code );
173 $lang = Language
::newFromCode( $fallback );
175 $lang->setCode( $code );
183 * Get the LocalisationCache instance
185 public static function getLocalisationCache() {
186 if ( is_null( self
::$dataCache ) ) {
187 global $wgLocalisationCacheConf;
188 $class = $wgLocalisationCacheConf['class'];
189 self
::$dataCache = new $class( $wgLocalisationCacheConf );
191 return self
::$dataCache;
194 function __construct() {
195 $this->mConverter
= new FakeConverter( $this );
196 // Set the code to the name of the descendant
197 if ( get_class( $this ) == 'Language' ) {
200 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
202 self
::getLocalisationCache();
206 * Reduce memory usage
208 function __destruct() {
209 foreach ( $this as $name => $value ) {
210 unset( $this->$name );
215 * Hook which will be called if this is the content language.
216 * Descendants can use this to register hook functions or modify globals
218 function initContLang() { }
221 * @deprecated Use User::getDefaultOptions()
224 function getDefaultUserOptions() {
225 wfDeprecated( __METHOD__
);
226 return User
::getDefaultOptions();
229 function getFallbackLanguageCode() {
230 if ( $this->mCode
=== 'en' ) {
233 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
238 * Exports $wgBookstoreListEn
241 function getBookstoreList() {
242 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
248 function getNamespaces() {
249 if ( is_null( $this->namespaceNames
) ) {
250 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
252 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
253 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
255 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
257 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
258 if ( $wgMetaNamespaceTalk ) {
259 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
261 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
262 $this->namespaceNames
[NS_PROJECT_TALK
] =
263 $this->fixVariableInNamespace( $talk );
266 # Sometimes a language will be localised but not actually exist on this wiki.
267 foreach( $this->namespaceNames
as $key => $text ) {
268 if ( !isset( $validNamespaces[$key] ) ) {
269 unset( $this->namespaceNames
[$key] );
273 # The above mixing may leave namespaces out of canonical order.
274 # Re-order by namespace ID number...
275 ksort( $this->namespaceNames
);
277 return $this->namespaceNames
;
281 * A convenience function that returns the same thing as
282 * getNamespaces() except with the array values changed to ' '
283 * where it found '_', useful for producing output to be displayed
284 * e.g. in <select> forms.
288 function getFormattedNamespaces() {
289 $ns = $this->getNamespaces();
290 foreach ( $ns as $k => $v ) {
291 $ns[$k] = strtr( $v, '_', ' ' );
297 * Get a namespace value by key
299 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
300 * echo $mw_ns; // prints 'MediaWiki'
303 * @param $index Int: the array key of the namespace to return
304 * @return mixed, string if the namespace value exists, otherwise false
306 function getNsText( $index ) {
307 $ns = $this->getNamespaces();
308 return isset( $ns[$index] ) ?
$ns[$index] : false;
312 * A convenience function that returns the same thing as
313 * getNsText() except with '_' changed to ' ', useful for
318 function getFormattedNsText( $index ) {
319 $ns = $this->getNsText( $index );
320 return strtr( $ns, '_', ' ' );
324 * Get a namespace key by value, case insensitive.
325 * Only matches namespace names for the current language, not the
326 * canonical ones defined in Namespace.php.
328 * @param $text String
329 * @return mixed An integer if $text is a valid value otherwise false
331 function getLocalNsIndex( $text ) {
332 $lctext = $this->lc( $text );
333 $ids = $this->getNamespaceIds();
334 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
337 function getNamespaceAliases() {
338 if ( is_null( $this->namespaceAliases
) ) {
339 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
343 foreach ( $aliases as $name => $index ) {
344 if ( $index === NS_PROJECT_TALK
) {
345 unset( $aliases[$name] );
346 $name = $this->fixVariableInNamespace( $name );
347 $aliases[$name] = $index;
351 $this->namespaceAliases
= $aliases;
353 return $this->namespaceAliases
;
356 function getNamespaceIds() {
357 if ( is_null( $this->mNamespaceIds
) ) {
358 global $wgNamespaceAliases;
359 # Put namespace names and aliases into a hashtable.
360 # If this is too slow, then we should arrange it so that it is done
361 # before caching. The catch is that at pre-cache time, the above
362 # class-specific fixup hasn't been done.
363 $this->mNamespaceIds
= array();
364 foreach ( $this->getNamespaces() as $index => $name ) {
365 $this->mNamespaceIds
[$this->lc( $name )] = $index;
367 foreach ( $this->getNamespaceAliases() as $name => $index ) {
368 $this->mNamespaceIds
[$this->lc( $name )] = $index;
370 if ( $wgNamespaceAliases ) {
371 foreach ( $wgNamespaceAliases as $name => $index ) {
372 $this->mNamespaceIds
[$this->lc( $name )] = $index;
376 return $this->mNamespaceIds
;
381 * Get a namespace key by value, case insensitive. Canonical namespace
382 * names override custom ones defined for the current language.
384 * @param $text String
385 * @return mixed An integer if $text is a valid value otherwise false
387 function getNsIndex( $text ) {
388 $lctext = $this->lc( $text );
389 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
392 $ids = $this->getNamespaceIds();
393 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
397 * short names for language variants used for language conversion links.
399 * @param $code String
402 function getVariantname( $code ) {
403 return $this->getMessageFromDB( "variantname-$code" );
406 function specialPage( $name ) {
407 $aliases = $this->getSpecialPageAliases();
408 if ( isset( $aliases[$name][0] ) ) {
409 $name = $aliases[$name][0];
411 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
414 function getQuickbarSettings() {
416 $this->getMessage( 'qbsettings-none' ),
417 $this->getMessage( 'qbsettings-fixedleft' ),
418 $this->getMessage( 'qbsettings-fixedright' ),
419 $this->getMessage( 'qbsettings-floatingleft' ),
420 $this->getMessage( 'qbsettings-floatingright' )
424 function getMathNames() {
425 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
428 function getDatePreferences() {
429 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
432 function getDateFormats() {
433 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
436 function getDefaultDateFormat() {
437 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
438 if ( $df === 'dmy or mdy' ) {
439 global $wgAmericanDates;
440 return $wgAmericanDates ?
'mdy' : 'dmy';
446 function getDatePreferenceMigrationMap() {
447 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
450 function getImageFile( $image ) {
451 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
454 function getDefaultUserOptionOverrides() {
455 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
458 function getExtraUserToggles() {
459 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
462 function getUserToggle( $tog ) {
463 return $this->getMessageFromDB( "tog-$tog" );
467 * Get language names, indexed by code.
468 * If $customisedOnly is true, only returns codes with a messages file
470 public static function getLanguageNames( $customisedOnly = false ) {
471 global $wgLanguageNames, $wgExtraLanguageNames;
472 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
473 if ( !$customisedOnly ) {
479 $dir = opendir( "$IP/languages/messages" );
480 while ( false !== ( $file = readdir( $dir ) ) ) {
481 $code = self
::getCodeFromFileName( $file, 'Messages' );
482 if ( $code && isset( $allNames[$code] ) ) {
483 $names[$code] = $allNames[$code];
491 * Get translated language names. This is done on best effort and
492 * by default this is exactly the same as Language::getLanguageNames.
493 * The CLDR extension provides translated names.
494 * @param $code String Language code.
495 * @return Array language code => language name
498 public static function getTranslatedLanguageNames( $code ) {
500 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
502 foreach ( self
::getLanguageNames() as $code => $name ) {
503 if ( !isset( $names[$code] ) ) $names[$code] = $name;
510 * Get a message from the MediaWiki namespace.
512 * @param $msg String: message name
515 function getMessageFromDB( $msg ) {
516 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
519 function getLanguageName( $code ) {
520 $names = self
::getLanguageNames();
521 if ( !array_key_exists( $code, $names ) ) {
524 return $names[$code];
527 function getMonthName( $key ) {
528 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
531 function getMonthNameGen( $key ) {
532 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
535 function getMonthAbbreviation( $key ) {
536 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
539 function getWeekdayName( $key ) {
540 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
543 function getWeekdayAbbreviation( $key ) {
544 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
547 function getIranianCalendarMonthName( $key ) {
548 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
551 function getHebrewCalendarMonthName( $key ) {
552 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
555 function getHebrewCalendarMonthNameGen( $key ) {
556 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
559 function getHijriCalendarMonthName( $key ) {
560 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
564 * Used by date() and time() to adjust the time output.
566 * @param $ts Int the time in date('YmdHis') format
567 * @param $tz Mixed: adjust the time by this amount (default false, mean we
568 * get user timecorrection setting)
571 function userAdjust( $ts, $tz = false ) {
572 global $wgUser, $wgLocalTZoffset;
574 if ( $tz === false ) {
575 $tz = $wgUser->getOption( 'timecorrection' );
578 $data = explode( '|', $tz, 3 );
580 if ( $data[0] == 'ZoneInfo' ) {
581 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
582 $date = date_create( $ts, timezone_open( 'UTC' ) );
583 date_timezone_set( $date, timezone_open( $data[2] ) );
584 $date = date_format( $date, 'YmdHis' );
587 # Unrecognized timezone, default to 'Offset' with the stored offset.
592 if ( $data[0] == 'System' ||
$tz == '' ) {
593 # Global offset in minutes.
594 if ( isset( $wgLocalTZoffset ) ) {
595 $minDiff = $wgLocalTZoffset;
597 } else if ( $data[0] == 'Offset' ) {
598 $minDiff = intval( $data[1] );
600 $data = explode( ':', $tz );
601 if ( count( $data ) == 2 ) {
602 $data[0] = intval( $data[0] );
603 $data[1] = intval( $data[1] );
604 $minDiff = abs( $data[0] ) * 60 +
$data[1];
605 if ( $data[0] < 0 ) {
606 $minDiff = -$minDiff;
609 $minDiff = intval( $data[0] ) * 60;
613 # No difference ? Return time unchanged
614 if ( 0 == $minDiff ) {
618 wfSuppressWarnings(); // E_STRICT system time bitching
619 # Generate an adjusted date; take advantage of the fact that mktime
620 # will normalize out-of-range values so we don't have to split $minDiff
621 # into hours and minutes.
623 (int)substr( $ts, 8, 2 ) ), # Hours
624 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
625 (int)substr( $ts, 12, 2 ), # Seconds
626 (int)substr( $ts, 4, 2 ), # Month
627 (int)substr( $ts, 6, 2 ), # Day
628 (int)substr( $ts, 0, 4 ) ); # Year
630 $date = date( 'YmdHis', $t );
637 * This is a workalike of PHP's date() function, but with better
638 * internationalisation, a reduced set of format characters, and a better
641 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
642 * PHP manual for definitions. There are a number of extensions, which
645 * xn Do not translate digits of the next numeric format character
646 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
647 * xr Use roman numerals for the next numeric format character
648 * xh Use hebrew numerals for the next numeric format character
650 * xg Genitive month name
652 * xij j (day number) in Iranian calendar
653 * xiF F (month name) in Iranian calendar
654 * xin n (month number) in Iranian calendar
655 * xiY Y (full year) in Iranian calendar
657 * xjj j (day number) in Hebrew calendar
658 * xjF F (month name) in Hebrew calendar
659 * xjt t (days in month) in Hebrew calendar
660 * xjx xg (genitive month name) in Hebrew calendar
661 * xjn n (month number) in Hebrew calendar
662 * xjY Y (full year) in Hebrew calendar
664 * xmj j (day number) in Hijri calendar
665 * xmF F (month name) in Hijri calendar
666 * xmn n (month number) in Hijri calendar
667 * xmY Y (full year) in Hijri calendar
669 * xkY Y (full year) in Thai solar calendar. Months and days are
670 * identical to the Gregorian calendar
671 * xoY Y (full year) in Minguo calendar or Juche year.
672 * Months and days are identical to the
674 * xtY Y (full year) in Japanese nengo. Months and days are
675 * identical to the Gregorian calendar
677 * Characters enclosed in double quotes will be considered literal (with
678 * the quotes themselves removed). Unmatched quotes will be considered
679 * literal quotes. Example:
681 * "The month is" F => The month is January
684 * Backslash escaping is also supported.
686 * Input timestamp is assumed to be pre-normalized to the desired local
689 * @param $format String
690 * @param $ts String: 14-character timestamp
693 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
695 function sprintfDate( $format, $ts ) {
708 for ( $p = 0; $p < strlen( $format ); $p++
) {
711 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
712 $code .= $format[++
$p];
715 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
716 $code .= $format[++
$p];
727 $rawToggle = !$rawToggle;
736 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
739 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
740 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
743 $num = substr( $ts, 6, 2 );
746 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
747 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
750 $num = intval( substr( $ts, 6, 2 ) );
754 $iranian = self
::tsToIranian( $ts );
760 $hijri = self
::tsToHijri( $ts );
766 $hebrew = self
::tsToHebrew( $ts );
772 $unix = wfTimestamp( TS_UNIX
, $ts );
774 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
778 $unix = wfTimestamp( TS_UNIX
, $ts );
780 $w = gmdate( 'w', $unix );
785 $unix = wfTimestamp( TS_UNIX
, $ts );
787 $num = gmdate( 'w', $unix );
791 $unix = wfTimestamp( TS_UNIX
, $ts );
793 $num = gmdate( 'z', $unix );
797 $unix = wfTimestamp( TS_UNIX
, $ts );
799 $num = gmdate( 'W', $unix );
802 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
806 $iranian = self
::tsToIranian( $ts );
808 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
812 $hijri = self
::tsToHijri( $ts );
814 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
818 $hebrew = self
::tsToHebrew( $ts );
820 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
823 $num = substr( $ts, 4, 2 );
826 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
829 $num = intval( substr( $ts, 4, 2 ) );
833 $iranian = self
::tsToIranian( $ts );
839 $hijri = self
::tsToHijri ( $ts );
845 $hebrew = self
::tsToHebrew( $ts );
851 $unix = wfTimestamp( TS_UNIX
, $ts );
853 $num = gmdate( 't', $unix );
857 $hebrew = self
::tsToHebrew( $ts );
863 $unix = wfTimestamp( TS_UNIX
, $ts );
865 $num = gmdate( 'L', $unix );
869 $unix = wfTimestamp( TS_UNIX
, $ts );
871 $num = date( 'o', $unix );
874 $num = substr( $ts, 0, 4 );
878 $iranian = self
::tsToIranian( $ts );
884 $hijri = self
::tsToHijri( $ts );
890 $hebrew = self
::tsToHebrew( $ts );
896 $thai = self
::tsToYear( $ts, 'thai' );
902 $minguo = self
::tsToYear( $ts, 'minguo' );
908 $tenno = self
::tsToYear( $ts, 'tenno' );
913 $num = substr( $ts, 2, 2 );
916 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
919 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
922 $h = substr( $ts, 8, 2 );
923 $num = $h %
12 ?
$h %
12 : 12;
926 $num = intval( substr( $ts, 8, 2 ) );
929 $h = substr( $ts, 8, 2 );
930 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
933 $num = substr( $ts, 8, 2 );
936 $num = substr( $ts, 10, 2 );
939 $num = substr( $ts, 12, 2 );
943 $unix = wfTimestamp( TS_UNIX
, $ts );
945 $s .= gmdate( 'c', $unix );
949 $unix = wfTimestamp( TS_UNIX
, $ts );
951 $s .= gmdate( 'r', $unix );
955 $unix = wfTimestamp( TS_UNIX
, $ts );
961 if ( $p < strlen( $format ) - 1 ) {
969 if ( $p < strlen( $format ) - 1 ) {
970 $endQuote = strpos( $format, '"', $p +
1 );
971 if ( $endQuote === false ) {
972 # No terminating quote, assume literal "
975 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
979 # Quote at end of string, assume literal "
986 if ( $num !== false ) {
987 if ( $rawToggle ||
$raw ) {
990 } elseif ( $roman ) {
991 $s .= self
::romanNumeral( $num );
993 } elseif ( $hebrewNum ) {
994 $s .= self
::hebrewNumeral( $num );
997 $s .= $this->formatNum( $num, true );
1004 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1005 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1007 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1008 * Gregorian dates to Iranian dates. Originally written in C, it
1009 * is released under the terms of GNU Lesser General Public
1010 * License. Conversion to PHP was performed by Niklas Laxström.
1012 * Link: http://www.farsiweb.info/jalali/jalali.c
1014 private static function tsToIranian( $ts ) {
1015 $gy = substr( $ts, 0, 4 ) -1600;
1016 $gm = substr( $ts, 4, 2 ) -1;
1017 $gd = substr( $ts, 6, 2 ) -1;
1019 # Days passed from the beginning (including leap years)
1021 +
floor( ( $gy +
3 ) / 4 )
1022 - floor( ( $gy +
99 ) / 100 )
1023 +
floor( ( $gy +
399 ) / 400 );
1026 // Add days of the past months of this year
1027 for ( $i = 0; $i < $gm; $i++
) {
1028 $gDayNo +
= self
::$GREG_DAYS[$i];
1032 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1036 // Days passed in current month
1039 $jDayNo = $gDayNo - 79;
1041 $jNp = floor( $jDayNo / 12053 );
1044 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1047 if ( $jDayNo >= 366 ) {
1048 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1049 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1052 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1053 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1059 return array( $jy, $jm, $jd );
1063 * Converting Gregorian dates to Hijri dates.
1065 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1067 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1069 private static function tsToHijri( $ts ) {
1070 $year = substr( $ts, 0, 4 );
1071 $month = substr( $ts, 4, 2 );
1072 $day = substr( $ts, 6, 2 );
1080 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1081 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1084 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1085 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1086 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1089 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1090 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1093 $zl = $zjd -1948440 +
10632;
1094 $zn = (int)( ( $zl - 1 ) / 10631 );
1095 $zl = $zl - 10631 * $zn +
354;
1096 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1097 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1098 $zm = (int)( ( 24 * $zl ) / 709 );
1099 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1100 $zy = 30 * $zn +
$zj - 30;
1102 return array( $zy, $zm, $zd );
1106 * Converting Gregorian dates to Hebrew dates.
1108 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1109 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1110 * to translate the relevant functions into PHP and release them under
1113 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1114 * and Adar II is 14. In a non-leap year, Adar is 6.
1116 private static function tsToHebrew( $ts ) {
1118 $year = substr( $ts, 0, 4 );
1119 $month = substr( $ts, 4, 2 );
1120 $day = substr( $ts, 6, 2 );
1122 # Calculate Hebrew year
1123 $hebrewYear = $year +
3760;
1125 # Month number when September = 1, August = 12
1127 if ( $month > 12 ) {
1134 # Calculate day of year from 1 September
1136 for ( $i = 1; $i < $month; $i++
) {
1140 # Check if the year is leap
1141 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1144 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1151 # Calculate the start of the Hebrew year
1152 $start = self
::hebrewYearStart( $hebrewYear );
1154 # Calculate next year's start
1155 if ( $dayOfYear <= $start ) {
1156 # Day is before the start of the year - it is the previous year
1158 $nextStart = $start;
1162 # Add days since previous year's 1 September
1164 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1168 # Start of the new (previous) year
1169 $start = self
::hebrewYearStart( $hebrewYear );
1172 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1175 # Calculate Hebrew day of year
1176 $hebrewDayOfYear = $dayOfYear - $start;
1178 # Difference between year's days
1179 $diff = $nextStart - $start;
1180 # Add 12 (or 13 for leap years) days to ignore the difference between
1181 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1182 # difference is only about the year type
1183 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1189 # Check the year pattern, and is leap year
1190 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1191 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1192 # and non-leap years
1193 $yearPattern = $diff %
30;
1194 # Check if leap year
1195 $isLeap = $diff >= 30;
1197 # Calculate day in the month from number of day in the Hebrew year
1198 # Don't check Adar - if the day is not in Adar, we will stop before;
1199 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1200 $hebrewDay = $hebrewDayOfYear;
1203 while ( $hebrewMonth <= 12 ) {
1204 # Calculate days in this month
1205 if ( $isLeap && $hebrewMonth == 6 ) {
1206 # Adar in a leap year
1208 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1210 if ( $hebrewDay <= $days ) {
1214 # Subtract the days of Adar I
1215 $hebrewDay -= $days;
1218 if ( $hebrewDay <= $days ) {
1224 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1225 # Cheshvan in a complete year (otherwise as the rule below)
1227 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1228 # Kislev in an incomplete year (otherwise as the rule below)
1231 # Odd months have 30 days, even have 29
1232 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1234 if ( $hebrewDay <= $days ) {
1235 # In the current month
1238 # Subtract the days of the current month
1239 $hebrewDay -= $days;
1240 # Try in the next month
1245 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1249 * This calculates the Hebrew year start, as days since 1 September.
1250 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1251 * Used for Hebrew date.
1253 private static function hebrewYearStart( $year ) {
1254 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1255 $b = intval( ( $year - 1 ) %
4 );
1256 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1260 $Mar = intval( $m );
1266 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1267 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1269 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1271 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1275 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1280 * Algorithm to convert Gregorian dates to Thai solar dates,
1281 * Minguo dates or Minguo dates.
1283 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1284 * http://en.wikipedia.org/wiki/Minguo_calendar
1285 * http://en.wikipedia.org/wiki/Japanese_era_name
1287 * @param $ts String: 14-character timestamp
1288 * @param $cName String: calender name
1289 * @return Array: converted year, month, day
1291 private static function tsToYear( $ts, $cName ) {
1292 $gy = substr( $ts, 0, 4 );
1293 $gm = substr( $ts, 4, 2 );
1294 $gd = substr( $ts, 6, 2 );
1296 if ( !strcmp( $cName, 'thai' ) ) {
1298 # Add 543 years to the Gregorian calendar
1299 # Months and days are identical
1300 $gy_offset = $gy +
543;
1301 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1303 # Deduct 1911 years from the Gregorian calendar
1304 # Months and days are identical
1305 $gy_offset = $gy - 1911;
1306 } else if ( !strcmp( $cName, 'tenno' ) ) {
1307 # Nengō dates up to Meiji period
1308 # Deduct years from the Gregorian calendar
1309 # depending on the nengo periods
1310 # Months and days are identical
1311 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1313 $gy_gannen = $gy - 1868 +
1;
1314 $gy_offset = $gy_gannen;
1315 if ( $gy_gannen == 1 ) {
1318 $gy_offset = '明治' . $gy_offset;
1320 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1321 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1322 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1323 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1324 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1328 $gy_gannen = $gy - 1912 +
1;
1329 $gy_offset = $gy_gannen;
1330 if ( $gy_gannen == 1 ) {
1333 $gy_offset = '大正' . $gy_offset;
1335 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1336 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1337 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1341 $gy_gannen = $gy - 1926 +
1;
1342 $gy_offset = $gy_gannen;
1343 if ( $gy_gannen == 1 ) {
1346 $gy_offset = '昭和' . $gy_offset;
1349 $gy_gannen = $gy - 1989 +
1;
1350 $gy_offset = $gy_gannen;
1351 if ( $gy_gannen == 1 ) {
1354 $gy_offset = '平成' . $gy_offset;
1360 return array( $gy_offset, $gm, $gd );
1364 * Roman number formatting up to 3000
1366 static function romanNumeral( $num ) {
1367 static $table = array(
1368 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1369 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1370 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1371 array( '', 'M', 'MM', 'MMM' )
1374 $num = intval( $num );
1375 if ( $num > 3000 ||
$num <= 0 ) {
1380 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1381 if ( $num >= $pow10 ) {
1382 $s .= $table[$i][floor( $num / $pow10 )];
1384 $num = $num %
$pow10;
1390 * Hebrew Gematria number formatting up to 9999
1392 static function hebrewNumeral( $num ) {
1393 static $table = array(
1394 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1395 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1396 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1397 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1400 $num = intval( $num );
1401 if ( $num > 9999 ||
$num <= 0 ) {
1406 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1407 if ( $num >= $pow10 ) {
1408 if ( $num == 15 ||
$num == 16 ) {
1409 $s .= $table[0][9] . $table[0][$num - 9];
1412 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1413 if ( $pow10 == 1000 ) {
1418 $num = $num %
$pow10;
1420 if ( strlen( $s ) == 2 ) {
1423 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1424 $str .= substr( $s, strlen( $s ) - 2, 2 );
1426 $start = substr( $str, 0, strlen( $str ) - 2 );
1427 $end = substr( $str, strlen( $str ) - 2 );
1430 $str = $start . 'ך';
1433 $str = $start . 'ם';
1436 $str = $start . 'ן';
1439 $str = $start . 'ף';
1442 $str = $start . 'ץ';
1449 * This is meant to be used by time(), date(), and timeanddate() to get
1450 * the date preference they're supposed to use, it should be used in
1454 * function timeanddate([...], $format = true) {
1455 * $datePreference = $this->dateFormat($format);
1460 * @param $usePrefs Mixed: if true, the user's preference is used
1461 * if false, the site/language default is used
1462 * if int/string, assumed to be a format.
1465 function dateFormat( $usePrefs = true ) {
1468 if ( is_bool( $usePrefs ) ) {
1470 $datePreference = $wgUser->getDatePreference();
1472 $datePreference = (string)User
::getDefaultOption( 'date' );
1475 $datePreference = (string)$usePrefs;
1479 if ( $datePreference == '' ) {
1483 return $datePreference;
1487 * Get a format string for a given type and preference
1488 * @param $type May be date, time or both
1489 * @param $pref The format name as it appears in Messages*.php
1491 function getDateFormatString( $type, $pref ) {
1492 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1493 if ( $pref == 'default' ) {
1494 $pref = $this->getDefaultDateFormat();
1495 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1497 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1498 if ( is_null( $df ) ) {
1499 $pref = $this->getDefaultDateFormat();
1500 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1503 $this->dateFormatStrings
[$type][$pref] = $df;
1505 return $this->dateFormatStrings
[$type][$pref];
1509 * @param $ts Mixed: the time format which needs to be turned into a
1510 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1511 * @param $adj Bool: whether to adjust the time output according to the
1512 * user configured offset ($timecorrection)
1513 * @param $format Mixed: true to use user's date format preference
1514 * @param $timecorrection String: the time offset as returned by
1515 * validateTimeZone() in Special:Preferences
1518 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1519 $ts = wfTimestamp( TS_MW
, $ts );
1521 $ts = $this->userAdjust( $ts, $timecorrection );
1523 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1524 return $this->sprintfDate( $df, $ts );
1528 * @param $ts Mixed: the time format which needs to be turned into a
1529 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1530 * @param $adj Bool: whether to adjust the time output according to the
1531 * user configured offset ($timecorrection)
1532 * @param $format Mixed: true to use user's date format preference
1533 * @param $timecorrection String: the time offset as returned by
1534 * validateTimeZone() in Special:Preferences
1537 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1538 $ts = wfTimestamp( TS_MW
, $ts );
1540 $ts = $this->userAdjust( $ts, $timecorrection );
1542 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1543 return $this->sprintfDate( $df, $ts );
1547 * @param $ts Mixed: the time format which needs to be turned into a
1548 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1549 * @param $adj Bool: whether to adjust the time output according to the
1550 * user configured offset ($timecorrection)
1551 * @param $format Mixed: what format to return, if it's false output the
1552 * default one (default true)
1553 * @param $timecorrection String: the time offset as returned by
1554 * validateTimeZone() in Special:Preferences
1557 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1558 $ts = wfTimestamp( TS_MW
, $ts );
1560 $ts = $this->userAdjust( $ts, $timecorrection );
1562 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1563 return $this->sprintfDate( $df, $ts );
1566 function getMessage( $key ) {
1567 return self
::$dataCache->getSubitem( $this->getCodeForMessage(), 'messages', $key );
1570 function getAllMessages() {
1571 return self
::$dataCache->getItem( $this->getCodeForMessage(), 'messages' );
1574 function iconv( $in, $out, $string ) {
1575 # This is a wrapper for iconv in all languages except esperanto,
1576 # which does some nasty x-conversions beforehand
1578 # Even with //IGNORE iconv can whine about illegal characters in
1579 # *input* string. We just ignore those too.
1580 # REF: http://bugs.php.net/bug.php?id=37166
1581 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1582 wfSuppressWarnings();
1583 $text = iconv( $in, $out . '//IGNORE', $string );
1584 wfRestoreWarnings();
1588 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1589 function ucwordbreaksCallbackAscii( $matches ) {
1590 return $this->ucfirst( $matches[1] );
1593 function ucwordbreaksCallbackMB( $matches ) {
1594 return mb_strtoupper( $matches[0] );
1597 function ucCallback( $matches ) {
1598 list( $wikiUpperChars ) = self
::getCaseMaps();
1599 return strtr( $matches[1], $wikiUpperChars );
1602 function lcCallback( $matches ) {
1603 list( , $wikiLowerChars ) = self
::getCaseMaps();
1604 return strtr( $matches[1], $wikiLowerChars );
1607 function ucwordsCallbackMB( $matches ) {
1608 return mb_strtoupper( $matches[0] );
1611 function ucwordsCallbackWiki( $matches ) {
1612 list( $wikiUpperChars ) = self
::getCaseMaps();
1613 return strtr( $matches[0], $wikiUpperChars );
1617 * Make a string's first character uppercase
1619 function ucfirst( $str ) {
1621 if ( $o < 96 ) { // if already uppercase...
1623 } elseif ( $o < 128 ) {
1624 return ucfirst( $str ); // use PHP's ucfirst()
1626 // fall back to more complex logic in case of multibyte strings
1627 return $this->uc( $str, true );
1632 * Convert a string to uppercase
1634 function uc( $str, $first = false ) {
1635 if ( function_exists( 'mb_strtoupper' ) ) {
1637 if ( $this->isMultibyte( $str ) ) {
1638 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1640 return ucfirst( $str );
1643 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1646 if ( $this->isMultibyte( $str ) ) {
1647 $x = $first ?
'^' : '';
1648 return preg_replace_callback(
1649 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1650 array( $this, 'ucCallback' ),
1654 return $first ?
ucfirst( $str ) : strtoupper( $str );
1659 function lcfirst( $str ) {
1662 return strval( $str );
1663 } elseif ( $o >= 128 ) {
1664 return $this->lc( $str, true );
1665 } elseif ( $o > 96 ) {
1668 $str[0] = strtolower( $str[0] );
1673 function lc( $str, $first = false ) {
1674 if ( function_exists( 'mb_strtolower' ) ) {
1676 if ( $this->isMultibyte( $str ) ) {
1677 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1679 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1682 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1685 if ( $this->isMultibyte( $str ) ) {
1686 $x = $first ?
'^' : '';
1687 return preg_replace_callback(
1688 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1689 array( $this, 'lcCallback' ),
1693 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1698 function isMultibyte( $str ) {
1699 return (bool)preg_match( '/[\x80-\xff]/', $str );
1702 function ucwords( $str ) {
1703 if ( $this->isMultibyte( $str ) ) {
1704 $str = $this->lc( $str );
1706 // regexp to find first letter in each word (i.e. after each space)
1707 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1709 // function to use to capitalize a single char
1710 if ( function_exists( 'mb_strtoupper' ) ) {
1711 return preg_replace_callback(
1713 array( $this, 'ucwordsCallbackMB' ),
1717 return preg_replace_callback(
1719 array( $this, 'ucwordsCallbackWiki' ),
1724 return ucwords( strtolower( $str ) );
1728 # capitalize words at word breaks
1729 function ucwordbreaks( $str ) {
1730 if ( $this->isMultibyte( $str ) ) {
1731 $str = $this->lc( $str );
1733 // since \b doesn't work for UTF-8, we explicitely define word break chars
1734 $breaks = "[ \-\(\)\}\{\.,\?!]";
1736 // find first letter after word break
1737 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1739 if ( function_exists( 'mb_strtoupper' ) ) {
1740 return preg_replace_callback(
1742 array( $this, 'ucwordbreaksCallbackMB' ),
1746 return preg_replace_callback(
1748 array( $this, 'ucwordsCallbackWiki' ),
1753 return preg_replace_callback(
1754 '/\b([\w\x80-\xff]+)\b/',
1755 array( $this, 'ucwordbreaksCallbackAscii' ),
1762 * Return a case-folded representation of $s
1764 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1765 * and $s2 are the same except for the case of their characters. It is not
1766 * necessary for the value returned to make sense when displayed.
1768 * Do *not* perform any other normalisation in this function. If a caller
1769 * uses this function when it should be using a more general normalisation
1770 * function, then fix the caller.
1772 function caseFold( $s ) {
1773 return $this->uc( $s );
1776 function checkTitleEncoding( $s ) {
1777 if ( is_array( $s ) ) {
1778 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1780 # Check for non-UTF-8 URLs
1781 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1786 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1787 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1792 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1795 function fallback8bitEncoding() {
1796 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1800 * Most writing systems use whitespace to break up words.
1801 * Some languages such as Chinese don't conventionally do this,
1802 * which requires special handling when breaking up words for
1805 function hasWordBreaks() {
1810 * Some languages such as Chinese require word segmentation,
1811 * Specify such segmentation when overridden in derived class.
1813 * @param $string String
1816 function segmentByWord( $string ) {
1821 * Some languages have special punctuation need to be normalized.
1822 * Make such changes here.
1824 * @param $string String
1827 function normalizeForSearch( $string ) {
1828 return self
::convertDoubleWidth( $string );
1832 * convert double-width roman characters to single-width.
1833 * range: ff00-ff5f ~= 0020-007f
1835 protected static function convertDoubleWidth( $string ) {
1836 static $full = null;
1837 static $half = null;
1839 if ( $full === null ) {
1840 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1841 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1842 $full = str_split( $fullWidth, 3 );
1843 $half = str_split( $halfWidth );
1846 $string = str_replace( $full, $half, $string );
1850 protected static function insertSpace( $string, $pattern ) {
1851 $string = preg_replace( $pattern, " $1 ", $string );
1852 $string = preg_replace( '/ +/', ' ', $string );
1856 function convertForSearchResult( $termsArray ) {
1857 # some languages, e.g. Chinese, need to do a conversion
1858 # in order for search results to be displayed correctly
1863 * Get the first character of a string.
1868 function firstChar( $s ) {
1871 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1872 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1877 if ( isset( $matches[1] ) ) {
1878 if ( strlen( $matches[1] ) != 3 ) {
1882 // Break down Hangul syllables to grab the first jamo
1883 $code = utf8ToCodepoint( $matches[1] );
1884 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1886 } elseif ( $code < 0xb098 ) {
1887 return "\xe3\x84\xb1";
1888 } elseif ( $code < 0xb2e4 ) {
1889 return "\xe3\x84\xb4";
1890 } elseif ( $code < 0xb77c ) {
1891 return "\xe3\x84\xb7";
1892 } elseif ( $code < 0xb9c8 ) {
1893 return "\xe3\x84\xb9";
1894 } elseif ( $code < 0xbc14 ) {
1895 return "\xe3\x85\x81";
1896 } elseif ( $code < 0xc0ac ) {
1897 return "\xe3\x85\x82";
1898 } elseif ( $code < 0xc544 ) {
1899 return "\xe3\x85\x85";
1900 } elseif ( $code < 0xc790 ) {
1901 return "\xe3\x85\x87";
1902 } elseif ( $code < 0xcc28 ) {
1903 return "\xe3\x85\x88";
1904 } elseif ( $code < 0xce74 ) {
1905 return "\xe3\x85\x8a";
1906 } elseif ( $code < 0xd0c0 ) {
1907 return "\xe3\x85\x8b";
1908 } elseif ( $code < 0xd30c ) {
1909 return "\xe3\x85\x8c";
1910 } elseif ( $code < 0xd558 ) {
1911 return "\xe3\x85\x8d";
1913 return "\xe3\x85\x8e";
1920 function initEncoding() {
1921 # Some languages may have an alternate char encoding option
1922 # (Esperanto X-coding, Japanese furigana conversion, etc)
1923 # If this language is used as the primary content language,
1924 # an override to the defaults can be set here on startup.
1927 function recodeForEdit( $s ) {
1928 # For some languages we'll want to explicitly specify
1929 # which characters make it into the edit box raw
1930 # or are converted in some way or another.
1931 # Note that if wgOutputEncoding is different from
1932 # wgInputEncoding, this text will be further converted
1933 # to wgOutputEncoding.
1934 global $wgEditEncoding;
1935 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1938 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1942 function recodeInput( $s ) {
1943 # Take the previous into account.
1944 global $wgEditEncoding;
1945 if ( $wgEditEncoding != '' ) {
1946 $enc = $wgEditEncoding;
1950 if ( $enc == 'UTF-8' ) {
1953 return $this->iconv( $enc, 'UTF-8', $s );
1958 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1959 * also cleans up certain backwards-compatible sequences, converting them
1960 * to the modern Unicode equivalent.
1962 * This is language-specific for performance reasons only.
1964 function normalize( $s ) {
1965 global $wgAllUnicodeFixes;
1966 $s = UtfNormal
::cleanUp( $s );
1967 if ( $wgAllUnicodeFixes ) {
1968 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1969 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1976 * Transform a string using serialized data stored in the given file (which
1977 * must be in the serialized subdirectory of $IP). The file contains pairs
1978 * mapping source characters to destination characters.
1980 * The data is cached in process memory. This will go faster if you have the
1981 * FastStringSearch extension.
1983 function transformUsingPairFile( $file, $string ) {
1984 if ( !isset( $this->transformData
[$file] ) ) {
1985 $data = wfGetPrecompiledData( $file );
1986 if ( $data === false ) {
1987 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1989 $this->transformData
[$file] = new ReplacementArray( $data );
1991 return $this->transformData
[$file]->replace( $string );
1995 * For right-to-left language support
2000 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2004 * Return the correct HTML 'dir' attribute value for this language.
2008 return $this->isRTL() ?
'rtl' : 'ltr';
2012 * Return 'left' or 'right' as appropriate alignment for line-start
2013 * for this language's text direction.
2015 * Should be equivalent to CSS3 'start' text-align value....
2019 function alignStart() {
2020 return $this->isRTL() ?
'right' : 'left';
2024 * Return 'right' or 'left' as appropriate alignment for line-end
2025 * for this language's text direction.
2027 * Should be equivalent to CSS3 'end' text-align value....
2031 function alignEnd() {
2032 return $this->isRTL() ?
'left' : 'right';
2036 * A hidden direction mark (LRM or RLM), depending on the language direction
2040 function getDirMark() {
2041 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2044 function capitalizeAllNouns() {
2045 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2049 * An arrow, depending on the language direction
2053 function getArrow() {
2054 return $this->isRTL() ?
'←' : '→';
2058 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2062 function linkPrefixExtension() {
2063 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2066 function getMagicWords() {
2067 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2070 # Fill a MagicWord object with data from here
2071 function getMagic( $mw ) {
2072 if ( !$this->mMagicHookDone
) {
2073 $this->mMagicHookDone
= true;
2074 wfProfileIn( 'LanguageGetMagic' );
2075 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2076 wfProfileOut( 'LanguageGetMagic' );
2078 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2079 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2081 $magicWords = $this->getMagicWords();
2082 if ( isset( $magicWords[$mw->mId
] ) ) {
2083 $rawEntry = $magicWords[$mw->mId
];
2089 if ( !is_array( $rawEntry ) ) {
2090 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2092 $mw->mCaseSensitive
= $rawEntry[0];
2093 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2098 * Add magic words to the extension array
2100 function addMagicWordsByLang( $newWords ) {
2101 $code = $this->getCode();
2102 $fallbackChain = array();
2103 while ( $code && !in_array( $code, $fallbackChain ) ) {
2104 $fallbackChain[] = $code;
2105 $code = self
::getFallbackFor( $code );
2107 if ( !in_array( 'en', $fallbackChain ) ) {
2108 $fallbackChain[] = 'en';
2110 $fallbackChain = array_reverse( $fallbackChain );
2111 foreach ( $fallbackChain as $code ) {
2112 if ( isset( $newWords[$code] ) ) {
2113 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2119 * Get special page names, as an associative array
2120 * case folded alias => real name
2122 function getSpecialPageAliases() {
2123 // Cache aliases because it may be slow to load them
2124 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2126 $this->mExtendedSpecialPageAliases
=
2127 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2128 wfRunHooks( 'LanguageGetSpecialPageAliases',
2129 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2132 return $this->mExtendedSpecialPageAliases
;
2136 * Italic is unsuitable for some languages
2138 * @param $text String: the text to be emphasized.
2141 function emphasize( $text ) {
2142 return "<em>$text</em>";
2146 * Normally we output all numbers in plain en_US style, that is
2147 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2148 * point twohundredthirtyfive. However this is not sutable for all
2149 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2150 * Icelandic just want to use commas instead of dots, and dots instead
2151 * of commas like "293.291,235".
2153 * An example of this function being called:
2155 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2158 * See LanguageGu.php for the Gujarati implementation and
2159 * $separatorTransformTable on MessageIs.php for
2160 * the , => . and . => , implementation.
2162 * @todo check if it's viable to use localeconv() for the decimal
2164 * @param $number Mixed: the string to be formatted, should be an integer
2165 * or a floating point number.
2166 * @param $nocommafy Bool: set to true for special numbers like dates
2169 function formatNum( $number, $nocommafy = false ) {
2170 global $wgTranslateNumerals;
2171 if ( !$nocommafy ) {
2172 $number = $this->commafy( $number );
2173 $s = $this->separatorTransformTable();
2175 $number = strtr( $number, $s );
2179 if ( $wgTranslateNumerals ) {
2180 $s = $this->digitTransformTable();
2182 $number = strtr( $number, $s );
2189 function parseFormattedNumber( $number ) {
2190 $s = $this->digitTransformTable();
2192 $number = strtr( $number, array_flip( $s ) );
2195 $s = $this->separatorTransformTable();
2197 $number = strtr( $number, array_flip( $s ) );
2200 $number = strtr( $number, array( ',' => '' ) );
2205 * Adds commas to a given number
2210 function commafy( $_ ) {
2211 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2214 function digitTransformTable() {
2215 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2218 function separatorTransformTable() {
2219 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2223 * Take a list of strings and build a locale-friendly comma-separated
2224 * list, using the local comma-separator message.
2225 * The last two strings are chained with an "and".
2230 function listToText( $l ) {
2232 $m = count( $l ) - 1;
2234 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2236 for ( $i = $m; $i >= 0; $i-- ) {
2239 } else if ( $i == $m - 1 ) {
2240 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2242 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2250 * Take a list of strings and build a locale-friendly comma-separated
2251 * list, using the local comma-separator message.
2252 * @param $list array of strings to put in a comma list
2255 function commaList( $list ) {
2260 array( 'parsemag', 'escapenoentities', 'language' => $this )
2266 * Take a list of strings and build a locale-friendly semicolon-separated
2267 * list, using the local semicolon-separator message.
2268 * @param $list array of strings to put in a semicolon list
2271 function semicolonList( $list ) {
2275 'semicolon-separator',
2276 array( 'parsemag', 'escapenoentities', 'language' => $this )
2282 * Same as commaList, but separate it with the pipe instead.
2283 * @param $list array of strings to put in a pipe list
2286 function pipeList( $list ) {
2291 array( 'escapenoentities', 'language' => $this )
2297 * Truncate a string to a specified length in bytes, appending an optional
2298 * string (e.g. for ellipses)
2300 * The database offers limited byte lengths for some columns in the database;
2301 * multi-byte character sets mean we need to ensure that only whole characters
2302 * are included, otherwise broken characters can be passed to the user
2304 * If $length is negative, the string will be truncated from the beginning
2306 * @param $string String to truncate
2307 * @param $length Int: maximum length (excluding ellipses)
2308 * @param $ellipsis String to append to the truncated text
2311 function truncate( $string, $length, $ellipsis = '...' ) {
2312 # Use the localized ellipsis character
2313 if ( $ellipsis == '...' ) {
2314 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2316 # Check if there is no need to truncate
2317 if ( $length == 0 ) {
2319 } elseif ( strlen( $string ) <= abs( $length ) ) {
2322 $stringOriginal = $string;
2323 if ( $length > 0 ) {
2324 $string = substr( $string, 0, $length ); // xyz...
2325 $string = $this->removeBadCharLast( $string );
2326 $string = $string . $ellipsis;
2328 $string = substr( $string, $length ); // ...xyz
2329 $string = $this->removeBadCharFirst( $string );
2330 $string = $ellipsis . $string;
2332 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2333 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2336 return $stringOriginal;
2341 * Remove bytes that represent an incomplete Unicode character
2342 * at the end of string (e.g. bytes of the char are missing)
2344 * @param $string String
2347 protected function removeBadCharLast( $string ) {
2348 $char = ord( $string[strlen( $string ) - 1] );
2350 if ( $char >= 0xc0 ) {
2351 # We got the first byte only of a multibyte char; remove it.
2352 $string = substr( $string, 0, -1 );
2353 } elseif ( $char >= 0x80 &&
2354 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2355 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2357 # We chopped in the middle of a character; remove it
2364 * Remove bytes that represent an incomplete Unicode character
2365 * at the start of string (e.g. bytes of the char are missing)
2367 * @param $string String
2370 protected function removeBadCharFirst( $string ) {
2371 $char = ord( $string[0] );
2372 if ( $char >= 0x80 && $char < 0xc0 ) {
2373 # We chopped in the middle of a character; remove the whole thing
2374 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2380 * Truncate a string of valid HTML to a specified length in bytes,
2381 * appending an optional string (e.g. for ellipses), and return valid HTML
2383 * This is only intended for styled/linked text, such as HTML with
2384 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2386 * Note: tries to fix broken HTML with MWTidy
2388 * @param string $text HTML string to truncate
2389 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2390 * @param string $ellipsis String to append to the truncated text
2393 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2394 # Use the localized ellipsis character
2395 if ( $ellipsis == '...' ) {
2396 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2398 # Check if there is no need to truncate
2399 if ( $length <= 0 ) {
2400 return $ellipsis; // no text shown, nothing to format
2401 } elseif ( strlen( $text ) <= $length ) {
2402 return $text; // string short enough even *with* HTML
2404 $text = MWTidy
::tidy( $text ); // fix tags
2405 $displayLen = 0; // innerHTML legth so far
2406 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2407 $tagType = 0; // 0-open, 1-close
2408 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2409 $entityState = 0; // 0-not entity, 1-entity
2411 $openTags = array(); // open tag stack
2412 $textLen = strlen( $text );
2413 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2415 $lastCh = $pos ?
$text[$pos - 1] : '';
2416 $ret .= $ch; // add to result string
2418 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2419 $entityState = 0; // for bad HTML
2420 $bracketState = 1; // tag started (checking for backslash)
2421 } elseif ( $ch == '>' ) {
2422 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2423 $entityState = 0; // for bad HTML
2424 $bracketState = 0; // out of brackets
2425 } elseif ( $bracketState == 1 ) {
2427 $tagType = 1; // close tag (e.g. "</span>")
2429 $tagType = 0; // open tag (e.g. "<span>")
2432 $bracketState = 2; // building tag name
2433 } elseif ( $bracketState == 2 ) {
2437 // Name found (e.g. "<a href=..."), add on tag attributes...
2438 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2440 } elseif ( $bracketState == 0 ) {
2441 if ( $entityState ) {
2444 $displayLen++
; // entity is one displayed char
2448 $entityState = 1; // entity found, (e.g. " ")
2450 $displayLen++
; // this char is displayed
2451 // Add on the other display text after this...
2452 $skipped = $this->truncate_skip(
2453 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2454 $displayLen +
= $skipped;
2459 # Consider truncation once the display length has reached the maximim.
2460 # Double-check that we're not in the middle of a bracket/entity...
2461 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2462 if ( !$testingEllipsis ) {
2463 $testingEllipsis = true;
2464 # Save where we are; we will truncate here unless
2465 # the ellipsis actually makes the string longer.
2466 $pOpenTags = $openTags; // save state
2467 $pRet = $ret; // save state
2468 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2469 # Ellipsis won't make string longer/equal, the truncation point was OK.
2470 $openTags = $pOpenTags; // reload state
2471 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2472 $ret .= $ellipsis; // add ellipsis
2477 if ( $displayLen == 0 ) {
2478 return ''; // no text shown, nothing to format
2480 // Close the last tag if left unclosed by bad HTML
2481 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2482 while ( count( $openTags ) > 0 ) {
2483 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2488 // truncateHtml() helper function
2489 // like strcspn() but adds the skipped chars to $ret
2490 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2492 if ( $start < strlen( $text ) ) {
2493 $skipCount = strcspn( $text, $search, $start, $len );
2494 $ret .= substr( $text, $start, $skipCount );
2500 * truncateHtml() helper function
2501 * (a) push or pop $tag from $openTags as needed
2502 * (b) clear $tag value
2503 * @param String &$tag Current HTML tag name we are looking at
2504 * @param int $tagType (0-open tag, 1-close tag)
2505 * @param char $lastCh Character before the '>' that ended this tag
2506 * @param array &$openTags Open tag stack (not accounting for $tag)
2508 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2509 $tag = ltrim( $tag );
2511 if ( $tagType == 0 && $lastCh != '/' ) {
2512 $openTags[] = $tag; // tag opened (didn't close itself)
2513 } else if ( $tagType == 1 ) {
2514 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2515 array_pop( $openTags ); // tag closed
2523 * Grammatical transformations, needed for inflected languages
2524 * Invoked by putting {{grammar:case|word}} in a message
2526 * @param $word string
2527 * @param $case string
2530 function convertGrammar( $word, $case ) {
2531 global $wgGrammarForms;
2532 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2533 return $wgGrammarForms[$this->getCode()][$case][$word];
2539 * Provides an alternative text depending on specified gender.
2540 * Usage {{gender:username|masculine|feminine|neutral}}.
2541 * username is optional, in which case the gender of current user is used,
2542 * but only in (some) interface messages; otherwise default gender is used.
2543 * If second or third parameter are not specified, masculine is used.
2544 * These details may be overriden per language.
2546 function gender( $gender, $forms ) {
2547 if ( !count( $forms ) ) {
2550 $forms = $this->preConvertPlural( $forms, 2 );
2551 if ( $gender === 'male' ) {
2554 if ( $gender === 'female' ) {
2557 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2561 * Plural form transformations, needed for some languages.
2562 * For example, there are 3 form of plural in Russian and Polish,
2563 * depending on "count mod 10". See [[w:Plural]]
2564 * For English it is pretty simple.
2566 * Invoked by putting {{plural:count|wordform1|wordform2}}
2567 * or {{plural:count|wordform1|wordform2|wordform3}}
2569 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2571 * @param $count Integer: non-localized number
2572 * @param $forms Array: different plural forms
2573 * @return string Correct form of plural for $count in this language
2575 function convertPlural( $count, $forms ) {
2576 if ( !count( $forms ) ) {
2579 $forms = $this->preConvertPlural( $forms, 2 );
2581 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2585 * Checks that convertPlural was given an array and pads it to requested
2586 * amound of forms by copying the last one.
2588 * @param $count Integer: How many forms should there be at least
2589 * @param $forms Array of forms given to convertPlural
2590 * @return array Padded array of forms or an exception if not an array
2592 protected function preConvertPlural( /* Array */ $forms, $count ) {
2593 while ( count( $forms ) < $count ) {
2594 $forms[] = $forms[count( $forms ) - 1];
2600 * For translating of expiry times
2601 * @param $str String: the validated block time in English
2602 * @return Somehow translated block time
2603 * @see LanguageFi.php for example implementation
2605 function translateBlockExpiry( $str ) {
2606 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2608 if ( $scBlockExpiryOptions == '-' ) {
2612 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2613 if ( strpos( $option, ':' ) === false ) {
2616 list( $show, $value ) = explode( ':', $option );
2617 if ( strcmp( $str, $value ) == 0 ) {
2618 return htmlspecialchars( trim( $show ) );
2626 * languages like Chinese need to be segmented in order for the diff
2629 * @param $text String
2632 function segmentForDiff( $text ) {
2637 * and unsegment to show the result
2639 * @param $text String
2642 function unsegmentForDiff( $text ) {
2646 # convert text to all supported variants
2647 function autoConvertToAllVariants( $text ) {
2648 return $this->mConverter
->autoConvertToAllVariants( $text );
2651 # convert text to different variants of a language.
2652 function convert( $text ) {
2653 return $this->mConverter
->convert( $text );
2656 # Convert a Title object to a string in the preferred variant
2657 function convertTitle( $title ) {
2658 return $this->mConverter
->convertTitle( $title );
2661 # Check if this is a language with variants
2662 function hasVariants() {
2663 return sizeof( $this->getVariants() ) > 1;
2666 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2667 function armourMath( $text ) {
2668 return $this->mConverter
->armourMath( $text );
2672 * Perform output conversion on a string, and encode for safe HTML output.
2673 * @param $text String text to be converted
2674 * @param $isTitle Bool whether this conversion is for the article title
2676 * @todo this should get integrated somewhere sane
2678 function convertHtml( $text, $isTitle = false ) {
2679 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2682 function convertCategoryKey( $key ) {
2683 return $this->mConverter
->convertCategoryKey( $key );
2687 * Get the list of variants supported by this language
2688 * see sample implementation in LanguageZh.php
2690 * @return array an array of language codes
2692 function getVariants() {
2693 return $this->mConverter
->getVariants();
2696 function getPreferredVariant() {
2697 return $this->mConverter
->getPreferredVariant();
2700 function getDefaultVariant() {
2701 return $this->mConverter
->getDefaultVariant();
2704 function getURLVariant() {
2705 return $this->mConverter
->getURLVariant();
2709 * If a language supports multiple variants, it is
2710 * possible that non-existing link in one variant
2711 * actually exists in another variant. this function
2712 * tries to find it. See e.g. LanguageZh.php
2714 * @param $link String: the name of the link
2715 * @param $nt Mixed: the title object of the link
2716 * @param $ignoreOtherCond Boolean: to disable other conditions when
2717 * we need to transclude a template or update a category's link
2718 * @return null the input parameters may be modified upon return
2720 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2721 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2725 * If a language supports multiple variants, converts text
2726 * into an array of all possible variants of the text:
2727 * 'variant' => text in that variant
2729 * @deprecated Use autoConvertToAllVariants()
2731 function convertLinkToAllVariants( $text ) {
2732 return $this->mConverter
->convertLinkToAllVariants( $text );
2736 * returns language specific options used by User::getPageRenderHash()
2737 * for example, the preferred language variant
2741 function getExtraHashOptions() {
2742 return $this->mConverter
->getExtraHashOptions();
2746 * For languages that support multiple variants, the title of an
2747 * article may be displayed differently in different variants. this
2748 * function returns the apporiate title defined in the body of the article.
2752 function getParsedTitle() {
2753 return $this->mConverter
->getParsedTitle();
2757 * Enclose a string with the "no conversion" tag. This is used by
2758 * various functions in the Parser
2760 * @param $text String: text to be tagged for no conversion
2762 * @return string the tagged text
2764 function markNoConversion( $text, $noParse = false ) {
2765 return $this->mConverter
->markNoConversion( $text, $noParse );
2769 * A regular expression to match legal word-trailing characters
2770 * which should be merged onto a link of the form [[foo]]bar.
2774 function linkTrail() {
2775 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2778 function getLangObj() {
2783 * Get the RFC 3066 code for this language object
2785 function getCode() {
2786 return $this->mCode
;
2790 * Get langcode for message
2791 * Some language, like Chinese (zh, without any suffix), has multiple
2792 * interface languages, we could choose a better one for user.
2793 * Inherit class can override this function if necessary.
2797 function getCodeForMessage() {
2798 return $this->getPreferredVariant();
2801 function setCode( $code ) {
2802 $this->mCode
= $code;
2806 * Get the name of a file for a certain language code
2807 * @param $prefix string Prepend this to the filename
2808 * @param $code string Language code
2809 * @param $suffix string Append this to the filename
2810 * @return string $prefix . $mangledCode . $suffix
2812 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2813 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2817 * Get the language code from a file name. Inverse of getFileName()
2818 * @param $filename string $prefix . $languageCode . $suffix
2819 * @param $prefix string Prefix before the language code
2820 * @param $suffix string Suffix after the language code
2821 * @return Language code, or false if $prefix or $suffix isn't found
2823 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2825 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2826 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2827 if ( !count( $m ) ) {
2830 return str_replace( '_', '-', strtolower( $m[1] ) );
2833 static function getMessagesFileName( $code ) {
2835 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2838 static function getClassFileName( $code ) {
2840 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2844 * Get the fallback for a given language
2846 static function getFallbackFor( $code ) {
2847 if ( $code === 'en' ) {
2851 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2856 * Get all messages for a given language
2857 * WARNING: this may take a long time
2859 static function getMessagesFor( $code ) {
2860 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2864 * Get a message for a given language
2866 static function getMessageFor( $key, $code ) {
2867 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2870 function fixVariableInNamespace( $talk ) {
2871 if ( strpos( $talk, '$1' ) === false ) {
2875 global $wgMetaNamespace;
2876 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2878 # Allow grammar transformations
2879 # Allowing full message-style parsing would make simple requests
2880 # such as action=raw much more expensive than they need to be.
2881 # This will hopefully cover most cases.
2882 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2883 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2884 return str_replace( ' ', '_', $talk );
2887 function replaceGrammarInNamespace( $m ) {
2888 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2891 static function getCaseMaps() {
2892 static $wikiUpperChars, $wikiLowerChars;
2893 if ( isset( $wikiUpperChars ) ) {
2894 return array( $wikiUpperChars, $wikiLowerChars );
2897 wfProfileIn( __METHOD__
);
2898 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2899 if ( $arr === false ) {
2900 throw new MWException(
2901 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2903 $wikiUpperChars = $arr['wikiUpperChars'];
2904 $wikiLowerChars = $arr['wikiLowerChars'];
2905 wfProfileOut( __METHOD__
);
2906 return array( $wikiUpperChars, $wikiLowerChars );
2909 function formatTimePeriod( $seconds ) {
2910 if ( round( $seconds * 10 ) < 100 ) {
2911 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2912 } elseif ( round( $seconds ) < 60 ) {
2913 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2914 } elseif ( round( $seconds ) < 3600 ) {
2915 $minutes = floor( $seconds / 60 );
2916 $secondsPart = round( fmod( $seconds, 60 ) );
2917 if ( $secondsPart == 60 ) {
2921 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2922 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2924 $hours = floor( $seconds / 3600 );
2925 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2926 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2927 if ( $secondsPart == 60 ) {
2931 if ( $minutes == 60 ) {
2935 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2936 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2937 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2941 function formatBitrate( $bps ) {
2942 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2944 return $this->formatNum( $bps ) . $units[0];
2946 $unitIndex = floor( log10( $bps ) / 3 );
2947 $mantissa = $bps / pow( 1000, $unitIndex );
2948 if ( $mantissa < 10 ) {
2949 $mantissa = round( $mantissa, 1 );
2951 $mantissa = round( $mantissa );
2953 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2957 * Format a size in bytes for output, using an appropriate
2958 * unit (B, KB, MB or GB) according to the magnitude in question
2960 * @param $size Size to format
2961 * @return string Plain text (not HTML)
2963 function formatSize( $size ) {
2964 // For small sizes no decimal places necessary
2966 if ( $size > 1024 ) {
2967 $size = $size / 1024;
2968 if ( $size > 1024 ) {
2969 $size = $size / 1024;
2970 // For MB and bigger two decimal places are smarter
2972 if ( $size > 1024 ) {
2973 $size = $size / 1024;
2974 $msg = 'size-gigabytes';
2976 $msg = 'size-megabytes';
2979 $msg = 'size-kilobytes';
2982 $msg = 'size-bytes';
2984 $size = round( $size, $round );
2985 $text = $this->getMessageFromDB( $msg );
2986 return str_replace( '$1', $this->formatNum( $size ), $text );
2990 * Get the conversion rule title, if any.
2992 function getConvRuleTitle() {
2993 return $this->mConverter
->getConvRuleTitle();
2997 * Given a string, convert it to a (hopefully short) key that can be used
2998 * for efficient sorting. A binary sort according to the sortkeys
2999 * corresponds to a logical sort of the corresponding strings. Current
3000 * code expects that a null character should sort before all others, but
3001 * has no other particular expectations (and that one can be changed if
3004 * @param string $string UTF-8 string
3005 * @return string Binary sortkey
3007 public function convertToSortkey( $string ) {
3008 # Fake function for now
3009 return strtoupper( $string );
3013 * Given a string, return the logical "first letter" to be used for
3014 * grouping on category pages and so on. This has to be coordinated
3015 * carefully with convertToSortkey(), or else the sorted list might jump
3016 * back and forth between the same "initial letters" or other pathological
3017 * behavior. For instance, if you just return the first character, but "a"
3018 * sorts the same as "A" based on convertToSortkey(), then you might get a
3030 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
3032 * @param string $string UTF-8 string
3033 * @return string UTF-8 string corresponding to the first letter of input
3035 public function firstLetterForLists( $string ) {
3036 if ( $string[0] == "\0" ) {
3037 $string = substr( $string, 1 );
3039 return strtoupper( $this->firstChar( $string ) );