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 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 a message from the MediaWiki namespace.
493 * @param $msg String: message name
496 function getMessageFromDB( $msg ) {
497 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
500 function getLanguageName( $code ) {
501 $names = self
::getLanguageNames();
502 if ( !array_key_exists( $code, $names ) ) {
505 return $names[$code];
508 function getMonthName( $key ) {
509 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
512 function getMonthNameGen( $key ) {
513 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
516 function getMonthAbbreviation( $key ) {
517 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
520 function getWeekdayName( $key ) {
521 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
524 function getWeekdayAbbreviation( $key ) {
525 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
528 function getIranianCalendarMonthName( $key ) {
529 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
532 function getHebrewCalendarMonthName( $key ) {
533 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
536 function getHebrewCalendarMonthNameGen( $key ) {
537 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
540 function getHijriCalendarMonthName( $key ) {
541 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
545 * Used by date() and time() to adjust the time output.
547 * @param $ts Int the time in date('YmdHis') format
548 * @param $tz Mixed: adjust the time by this amount (default false, mean we
549 * get user timecorrection setting)
552 function userAdjust( $ts, $tz = false ) {
553 global $wgUser, $wgLocalTZoffset;
555 if ( $tz === false ) {
556 $tz = $wgUser->getOption( 'timecorrection' );
559 $data = explode( '|', $tz, 3 );
561 if ( $data[0] == 'ZoneInfo' ) {
562 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
563 $date = date_create( $ts, timezone_open( 'UTC' ) );
564 date_timezone_set( $date, timezone_open( $data[2] ) );
565 $date = date_format( $date, 'YmdHis' );
568 # Unrecognized timezone, default to 'Offset' with the stored offset.
573 if ( $data[0] == 'System' ||
$tz == '' ) {
574 # Global offset in minutes.
575 if ( isset( $wgLocalTZoffset ) ) {
576 $minDiff = $wgLocalTZoffset;
578 } else if ( $data[0] == 'Offset' ) {
579 $minDiff = intval( $data[1] );
581 $data = explode( ':', $tz );
582 if ( count( $data ) == 2 ) {
583 $data[0] = intval( $data[0] );
584 $data[1] = intval( $data[1] );
585 $minDiff = abs( $data[0] ) * 60 +
$data[1];
586 if ( $data[0] < 0 ) {
587 $minDiff = -$minDiff;
590 $minDiff = intval( $data[0] ) * 60;
594 # No difference ? Return time unchanged
595 if ( 0 == $minDiff ) {
599 wfSuppressWarnings(); // E_STRICT system time bitching
600 # Generate an adjusted date; take advantage of the fact that mktime
601 # will normalize out-of-range values so we don't have to split $minDiff
602 # into hours and minutes.
604 (int)substr( $ts, 8, 2 ) ), # Hours
605 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
606 (int)substr( $ts, 12, 2 ), # Seconds
607 (int)substr( $ts, 4, 2 ), # Month
608 (int)substr( $ts, 6, 2 ), # Day
609 (int)substr( $ts, 0, 4 ) ); # Year
611 $date = date( 'YmdHis', $t );
618 * This is a workalike of PHP's date() function, but with better
619 * internationalisation, a reduced set of format characters, and a better
622 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
623 * PHP manual for definitions. There are a number of extensions, which
626 * xn Do not translate digits of the next numeric format character
627 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
628 * xr Use roman numerals for the next numeric format character
629 * xh Use hebrew numerals for the next numeric format character
631 * xg Genitive month name
633 * xij j (day number) in Iranian calendar
634 * xiF F (month name) in Iranian calendar
635 * xin n (month number) in Iranian calendar
636 * xiY Y (full year) in Iranian calendar
638 * xjj j (day number) in Hebrew calendar
639 * xjF F (month name) in Hebrew calendar
640 * xjt t (days in month) in Hebrew calendar
641 * xjx xg (genitive month name) in Hebrew calendar
642 * xjn n (month number) in Hebrew calendar
643 * xjY Y (full year) in Hebrew calendar
645 * xmj j (day number) in Hijri calendar
646 * xmF F (month name) in Hijri calendar
647 * xmn n (month number) in Hijri calendar
648 * xmY Y (full year) in Hijri calendar
650 * xkY Y (full year) in Thai solar calendar. Months and days are
651 * identical to the Gregorian calendar
652 * xoY Y (full year) in Minguo calendar or Juche year.
653 * Months and days are identical to the
655 * xtY Y (full year) in Japanese nengo. Months and days are
656 * identical to the Gregorian calendar
658 * Characters enclosed in double quotes will be considered literal (with
659 * the quotes themselves removed). Unmatched quotes will be considered
660 * literal quotes. Example:
662 * "The month is" F => The month is January
665 * Backslash escaping is also supported.
667 * Input timestamp is assumed to be pre-normalized to the desired local
670 * @param $format String
671 * @param $ts String: 14-character timestamp
674 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
676 function sprintfDate( $format, $ts ) {
689 for ( $p = 0; $p < strlen( $format ); $p++
) {
692 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
693 $code .= $format[++
$p];
696 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
697 $code .= $format[++
$p];
708 $rawToggle = !$rawToggle;
717 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
720 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
721 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
724 $num = substr( $ts, 6, 2 );
727 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
728 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
731 $num = intval( substr( $ts, 6, 2 ) );
735 $iranian = self
::tsToIranian( $ts );
741 $hijri = self
::tsToHijri( $ts );
747 $hebrew = self
::tsToHebrew( $ts );
753 $unix = wfTimestamp( TS_UNIX
, $ts );
755 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
759 $unix = wfTimestamp( TS_UNIX
, $ts );
761 $w = gmdate( 'w', $unix );
766 $unix = wfTimestamp( TS_UNIX
, $ts );
768 $num = gmdate( 'w', $unix );
772 $unix = wfTimestamp( TS_UNIX
, $ts );
774 $num = gmdate( 'z', $unix );
778 $unix = wfTimestamp( TS_UNIX
, $ts );
780 $num = gmdate( 'W', $unix );
783 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
787 $iranian = self
::tsToIranian( $ts );
789 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
793 $hijri = self
::tsToHijri( $ts );
795 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
799 $hebrew = self
::tsToHebrew( $ts );
801 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
804 $num = substr( $ts, 4, 2 );
807 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
810 $num = intval( substr( $ts, 4, 2 ) );
814 $iranian = self
::tsToIranian( $ts );
820 $hijri = self
::tsToHijri ( $ts );
826 $hebrew = self
::tsToHebrew( $ts );
832 $unix = wfTimestamp( TS_UNIX
, $ts );
834 $num = gmdate( 't', $unix );
838 $hebrew = self
::tsToHebrew( $ts );
844 $unix = wfTimestamp( TS_UNIX
, $ts );
846 $num = gmdate( 'L', $unix );
850 $unix = wfTimestamp( TS_UNIX
, $ts );
852 $num = date( 'o', $unix );
855 $num = substr( $ts, 0, 4 );
859 $iranian = self
::tsToIranian( $ts );
865 $hijri = self
::tsToHijri( $ts );
871 $hebrew = self
::tsToHebrew( $ts );
877 $thai = self
::tsToYear( $ts, 'thai' );
883 $minguo = self
::tsToYear( $ts, 'minguo' );
889 $tenno = self
::tsToYear( $ts, 'tenno' );
894 $num = substr( $ts, 2, 2 );
897 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
900 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
903 $h = substr( $ts, 8, 2 );
904 $num = $h %
12 ?
$h %
12 : 12;
907 $num = intval( substr( $ts, 8, 2 ) );
910 $h = substr( $ts, 8, 2 );
911 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
914 $num = substr( $ts, 8, 2 );
917 $num = substr( $ts, 10, 2 );
920 $num = substr( $ts, 12, 2 );
924 $unix = wfTimestamp( TS_UNIX
, $ts );
926 $s .= gmdate( 'c', $unix );
930 $unix = wfTimestamp( TS_UNIX
, $ts );
932 $s .= gmdate( 'r', $unix );
936 $unix = wfTimestamp( TS_UNIX
, $ts );
942 if ( $p < strlen( $format ) - 1 ) {
950 if ( $p < strlen( $format ) - 1 ) {
951 $endQuote = strpos( $format, '"', $p +
1 );
952 if ( $endQuote === false ) {
953 # No terminating quote, assume literal "
956 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
960 # Quote at end of string, assume literal "
967 if ( $num !== false ) {
968 if ( $rawToggle ||
$raw ) {
971 } elseif ( $roman ) {
972 $s .= self
::romanNumeral( $num );
974 } elseif ( $hebrewNum ) {
975 $s .= self
::hebrewNumeral( $num );
978 $s .= $this->formatNum( $num, true );
986 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
987 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
989 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
990 * Gregorian dates to Iranian dates. Originally written in C, it
991 * is released under the terms of GNU Lesser General Public
992 * License. Conversion to PHP was performed by Niklas Laxström.
994 * Link: http://www.farsiweb.info/jalali/jalali.c
996 private static function tsToIranian( $ts ) {
997 $gy = substr( $ts, 0, 4 ) -1600;
998 $gm = substr( $ts, 4, 2 ) -1;
999 $gd = substr( $ts, 6, 2 ) -1;
1001 # Days passed from the beginning (including leap years)
1003 +
floor( ( $gy +
3 ) / 4 )
1004 - floor( ( $gy +
99 ) / 100 )
1005 +
floor( ( $gy +
399 ) / 400 );
1008 // Add days of the past months of this year
1009 for ( $i = 0; $i < $gm; $i++
) {
1010 $gDayNo +
= self
::$GREG_DAYS[$i];
1014 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1018 // Days passed in current month
1021 $jDayNo = $gDayNo - 79;
1023 $jNp = floor( $jDayNo / 12053 );
1026 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1029 if ( $jDayNo >= 366 ) {
1030 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1031 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1034 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1035 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1041 return array( $jy, $jm, $jd );
1045 * Converting Gregorian dates to Hijri dates.
1047 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1049 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1051 private static function tsToHijri( $ts ) {
1052 $year = substr( $ts, 0, 4 );
1053 $month = substr( $ts, 4, 2 );
1054 $day = substr( $ts, 6, 2 );
1062 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1063 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1066 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1067 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1068 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1071 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1072 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1075 $zl = $zjd -1948440 +
10632;
1076 $zn = (int)( ( $zl - 1 ) / 10631 );
1077 $zl = $zl - 10631 * $zn +
354;
1078 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1079 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1080 $zm = (int)( ( 24 * $zl ) / 709 );
1081 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1082 $zy = 30 * $zn +
$zj - 30;
1084 return array( $zy, $zm, $zd );
1088 * Converting Gregorian dates to Hebrew dates.
1090 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1091 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1092 * to translate the relevant functions into PHP and release them under
1095 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1096 * and Adar II is 14. In a non-leap year, Adar is 6.
1098 private static function tsToHebrew( $ts ) {
1100 $year = substr( $ts, 0, 4 );
1101 $month = substr( $ts, 4, 2 );
1102 $day = substr( $ts, 6, 2 );
1104 # Calculate Hebrew year
1105 $hebrewYear = $year +
3760;
1107 # Month number when September = 1, August = 12
1109 if ( $month > 12 ) {
1116 # Calculate day of year from 1 September
1118 for ( $i = 1; $i < $month; $i++
) {
1122 # Check if the year is leap
1123 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1126 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1133 # Calculate the start of the Hebrew year
1134 $start = self
::hebrewYearStart( $hebrewYear );
1136 # Calculate next year's start
1137 if ( $dayOfYear <= $start ) {
1138 # Day is before the start of the year - it is the previous year
1140 $nextStart = $start;
1144 # Add days since previous year's 1 September
1146 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1150 # Start of the new (previous) year
1151 $start = self
::hebrewYearStart( $hebrewYear );
1154 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1157 # Calculate Hebrew day of year
1158 $hebrewDayOfYear = $dayOfYear - $start;
1160 # Difference between year's days
1161 $diff = $nextStart - $start;
1162 # Add 12 (or 13 for leap years) days to ignore the difference between
1163 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1164 # difference is only about the year type
1165 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1171 # Check the year pattern, and is leap year
1172 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1173 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1174 # and non-leap years
1175 $yearPattern = $diff %
30;
1176 # Check if leap year
1177 $isLeap = $diff >= 30;
1179 # Calculate day in the month from number of day in the Hebrew year
1180 # Don't check Adar - if the day is not in Adar, we will stop before;
1181 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1182 $hebrewDay = $hebrewDayOfYear;
1185 while ( $hebrewMonth <= 12 ) {
1186 # Calculate days in this month
1187 if ( $isLeap && $hebrewMonth == 6 ) {
1188 # Adar in a leap year
1190 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1192 if ( $hebrewDay <= $days ) {
1196 # Subtract the days of Adar I
1197 $hebrewDay -= $days;
1200 if ( $hebrewDay <= $days ) {
1206 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1207 # Cheshvan in a complete year (otherwise as the rule below)
1209 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1210 # Kislev in an incomplete year (otherwise as the rule below)
1213 # Odd months have 30 days, even have 29
1214 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1216 if ( $hebrewDay <= $days ) {
1217 # In the current month
1220 # Subtract the days of the current month
1221 $hebrewDay -= $days;
1222 # Try in the next month
1227 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1231 * This calculates the Hebrew year start, as days since 1 September.
1232 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1233 * Used for Hebrew date.
1235 private static function hebrewYearStart( $year ) {
1236 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1237 $b = intval( ( $year - 1 ) %
4 );
1238 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1242 $Mar = intval( $m );
1248 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1249 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1251 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1253 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1257 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1262 * Algorithm to convert Gregorian dates to Thai solar dates,
1263 * Minguo dates or Minguo dates.
1265 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1266 * http://en.wikipedia.org/wiki/Minguo_calendar
1267 * http://en.wikipedia.org/wiki/Japanese_era_name
1269 * @param $ts String: 14-character timestamp
1270 * @param $cName String: calender name
1271 * @return Array: converted year, month, day
1273 private static function tsToYear( $ts, $cName ) {
1274 $gy = substr( $ts, 0, 4 );
1275 $gm = substr( $ts, 4, 2 );
1276 $gd = substr( $ts, 6, 2 );
1278 if ( !strcmp( $cName, 'thai' ) ) {
1280 # Add 543 years to the Gregorian calendar
1281 # Months and days are identical
1282 $gy_offset = $gy +
543;
1283 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1285 # Deduct 1911 years from the Gregorian calendar
1286 # Months and days are identical
1287 $gy_offset = $gy - 1911;
1288 } else if ( !strcmp( $cName, 'tenno' ) ) {
1289 # Nengō dates up to Meiji period
1290 # Deduct years from the Gregorian calendar
1291 # depending on the nengo periods
1292 # Months and days are identical
1293 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1295 $gy_gannen = $gy - 1868 +
1;
1296 $gy_offset = $gy_gannen;
1297 if ( $gy_gannen == 1 ) {
1300 $gy_offset = '明治' . $gy_offset;
1302 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1303 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1304 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1305 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1306 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1310 $gy_gannen = $gy - 1912 +
1;
1311 $gy_offset = $gy_gannen;
1312 if ( $gy_gannen == 1 ) {
1315 $gy_offset = '大正' . $gy_offset;
1317 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1318 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1319 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1323 $gy_gannen = $gy - 1926 +
1;
1324 $gy_offset = $gy_gannen;
1325 if ( $gy_gannen == 1 ) {
1328 $gy_offset = '昭和' . $gy_offset;
1331 $gy_gannen = $gy - 1989 +
1;
1332 $gy_offset = $gy_gannen;
1333 if ( $gy_gannen == 1 ) {
1336 $gy_offset = '平成' . $gy_offset;
1342 return array( $gy_offset, $gm, $gd );
1346 * Roman number formatting up to 3000
1348 static function romanNumeral( $num ) {
1349 static $table = array(
1350 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1351 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1352 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1353 array( '', 'M', 'MM', 'MMM' )
1356 $num = intval( $num );
1357 if ( $num > 3000 ||
$num <= 0 ) {
1362 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1363 if ( $num >= $pow10 ) {
1364 $s .= $table[$i][floor( $num / $pow10 )];
1366 $num = $num %
$pow10;
1372 * Hebrew Gematria number formatting up to 9999
1374 static function hebrewNumeral( $num ) {
1375 static $table = array(
1376 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1377 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1378 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1379 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1382 $num = intval( $num );
1383 if ( $num > 9999 ||
$num <= 0 ) {
1388 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1389 if ( $num >= $pow10 ) {
1390 if ( $num == 15 ||
$num == 16 ) {
1391 $s .= $table[0][9] . $table[0][$num - 9];
1394 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1395 if ( $pow10 == 1000 ) {
1400 $num = $num %
$pow10;
1402 if ( strlen( $s ) == 2 ) {
1405 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1406 $str .= substr( $s, strlen( $s ) - 2, 2 );
1408 $start = substr( $str, 0, strlen( $str ) - 2 );
1409 $end = substr( $str, strlen( $str ) - 2 );
1412 $str = $start . 'ך';
1415 $str = $start . 'ם';
1418 $str = $start . 'ן';
1421 $str = $start . 'ף';
1424 $str = $start . 'ץ';
1431 * This is meant to be used by time(), date(), and timeanddate() to get
1432 * the date preference they're supposed to use, it should be used in
1436 * function timeanddate([...], $format = true) {
1437 * $datePreference = $this->dateFormat($format);
1442 * @param $usePrefs Mixed: if true, the user's preference is used
1443 * if false, the site/language default is used
1444 * if int/string, assumed to be a format.
1447 function dateFormat( $usePrefs = true ) {
1450 if ( is_bool( $usePrefs ) ) {
1452 $datePreference = $wgUser->getDatePreference();
1454 $datePreference = (string)User
::getDefaultOption( 'date' );
1457 $datePreference = (string)$usePrefs;
1461 if ( $datePreference == '' ) {
1465 return $datePreference;
1469 * Get a format string for a given type and preference
1470 * @param $type May be date, time or both
1471 * @param $pref The format name as it appears in Messages*.php
1473 function getDateFormatString( $type, $pref ) {
1474 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1475 if ( $pref == 'default' ) {
1476 $pref = $this->getDefaultDateFormat();
1477 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1479 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1480 if ( is_null( $df ) ) {
1481 $pref = $this->getDefaultDateFormat();
1482 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1485 $this->dateFormatStrings
[$type][$pref] = $df;
1487 return $this->dateFormatStrings
[$type][$pref];
1491 * @param $ts Mixed: the time format which needs to be turned into a
1492 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1493 * @param $adj Bool: whether to adjust the time output according to the
1494 * user configured offset ($timecorrection)
1495 * @param $format Mixed: true to use user's date format preference
1496 * @param $timecorrection String: the time offset as returned by
1497 * validateTimeZone() in Special:Preferences
1500 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1501 $ts = wfTimestamp( TS_MW
, $ts );
1503 $ts = $this->userAdjust( $ts, $timecorrection );
1505 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1506 return $this->sprintfDate( $df, $ts );
1510 * @param $ts Mixed: the time format which needs to be turned into a
1511 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1512 * @param $adj Bool: whether to adjust the time output according to the
1513 * user configured offset ($timecorrection)
1514 * @param $format Mixed: true to use user's date format preference
1515 * @param $timecorrection String: the time offset as returned by
1516 * validateTimeZone() in Special:Preferences
1519 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1520 $ts = wfTimestamp( TS_MW
, $ts );
1522 $ts = $this->userAdjust( $ts, $timecorrection );
1524 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1525 return $this->sprintfDate( $df, $ts );
1529 * @param $ts Mixed: the time format which needs to be turned into a
1530 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1531 * @param $adj Bool: whether to adjust the time output according to the
1532 * user configured offset ($timecorrection)
1533 * @param $format Mixed: what format to return, if it's false output the
1534 * default one (default true)
1535 * @param $timecorrection String: the time offset as returned by
1536 * validateTimeZone() in Special:Preferences
1539 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1540 $ts = wfTimestamp( TS_MW
, $ts );
1542 $ts = $this->userAdjust( $ts, $timecorrection );
1544 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1545 return $this->sprintfDate( $df, $ts );
1548 function getMessage( $key ) {
1549 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1552 function getAllMessages() {
1553 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1556 function iconv( $in, $out, $string ) {
1557 # This is a wrapper for iconv in all languages except esperanto,
1558 # which does some nasty x-conversions beforehand
1560 # Even with //IGNORE iconv can whine about illegal characters in
1561 # *input* string. We just ignore those too.
1562 # REF: http://bugs.php.net/bug.php?id=37166
1563 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1564 wfSuppressWarnings();
1565 $text = iconv( $in, $out . '//IGNORE', $string );
1566 wfRestoreWarnings();
1570 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1571 function ucwordbreaksCallbackAscii( $matches ) {
1572 return $this->ucfirst( $matches[1] );
1575 function ucwordbreaksCallbackMB( $matches ) {
1576 return mb_strtoupper( $matches[0] );
1579 function ucCallback( $matches ) {
1580 list( $wikiUpperChars ) = self
::getCaseMaps();
1581 return strtr( $matches[1], $wikiUpperChars );
1584 function lcCallback( $matches ) {
1585 list( , $wikiLowerChars ) = self
::getCaseMaps();
1586 return strtr( $matches[1], $wikiLowerChars );
1589 function ucwordsCallbackMB( $matches ) {
1590 return mb_strtoupper( $matches[0] );
1593 function ucwordsCallbackWiki( $matches ) {
1594 list( $wikiUpperChars ) = self
::getCaseMaps();
1595 return strtr( $matches[0], $wikiUpperChars );
1599 * Make a string's first character uppercase
1601 function ucfirst( $str ) {
1603 if ( $o < 96 ) { // if already uppercase...
1605 } elseif ( $o < 128 ) {
1606 return ucfirst( $str ); // use PHP's ucfirst()
1608 // fall back to more complex logic in case of multibyte strings
1609 return $this->uc( $str, true );
1614 * Convert a string to uppercase
1616 function uc( $str, $first = false ) {
1617 if ( function_exists( 'mb_strtoupper' ) ) {
1619 if ( $this->isMultibyte( $str ) ) {
1620 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1622 return ucfirst( $str );
1625 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1628 if ( $this->isMultibyte( $str ) ) {
1629 $x = $first ?
'^' : '';
1630 return preg_replace_callback(
1631 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1632 array( $this, 'ucCallback' ),
1636 return $first ?
ucfirst( $str ) : strtoupper( $str );
1641 function lcfirst( $str ) {
1644 return strval( $str );
1645 } elseif ( $o >= 128 ) {
1646 return $this->lc( $str, true );
1647 } elseif ( $o > 96 ) {
1650 $str[0] = strtolower( $str[0] );
1655 function lc( $str, $first = false ) {
1656 if ( function_exists( 'mb_strtolower' ) ) {
1658 if ( $this->isMultibyte( $str ) ) {
1659 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1661 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1664 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1667 if ( $this->isMultibyte( $str ) ) {
1668 $x = $first ?
'^' : '';
1669 return preg_replace_callback(
1670 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1671 array( $this, 'lcCallback' ),
1675 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1680 function isMultibyte( $str ) {
1681 return (bool)preg_match( '/[\x80-\xff]/', $str );
1684 function ucwords( $str ) {
1685 if ( $this->isMultibyte( $str ) ) {
1686 $str = $this->lc( $str );
1688 // regexp to find first letter in each word (i.e. after each space)
1689 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1691 // function to use to capitalize a single char
1692 if ( function_exists( 'mb_strtoupper' ) ) {
1693 return preg_replace_callback(
1695 array( $this, 'ucwordsCallbackMB' ),
1699 return preg_replace_callback(
1701 array( $this, 'ucwordsCallbackWiki' ),
1706 return ucwords( strtolower( $str ) );
1710 # capitalize words at word breaks
1711 function ucwordbreaks( $str ) {
1712 if ( $this->isMultibyte( $str ) ) {
1713 $str = $this->lc( $str );
1715 // since \b doesn't work for UTF-8, we explicitely define word break chars
1716 $breaks = "[ \-\(\)\}\{\.,\?!]";
1718 // find first letter after word break
1719 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1721 if ( function_exists( 'mb_strtoupper' ) ) {
1722 return preg_replace_callback(
1724 array( $this, 'ucwordbreaksCallbackMB' ),
1728 return preg_replace_callback(
1730 array( $this, 'ucwordsCallbackWiki' ),
1735 return preg_replace_callback(
1736 '/\b([\w\x80-\xff]+)\b/',
1737 array( $this, 'ucwordbreaksCallbackAscii' ),
1744 * Return a case-folded representation of $s
1746 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1747 * and $s2 are the same except for the case of their characters. It is not
1748 * necessary for the value returned to make sense when displayed.
1750 * Do *not* perform any other normalisation in this function. If a caller
1751 * uses this function when it should be using a more general normalisation
1752 * function, then fix the caller.
1754 function caseFold( $s ) {
1755 return $this->uc( $s );
1758 function checkTitleEncoding( $s ) {
1759 if ( is_array( $s ) ) {
1760 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1762 # Check for non-UTF-8 URLs
1763 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1768 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1769 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1774 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1777 function fallback8bitEncoding() {
1778 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1782 * Most writing systems use whitespace to break up words.
1783 * Some languages such as Chinese don't conventionally do this,
1784 * which requires special handling when breaking up words for
1787 function hasWordBreaks() {
1792 * Some languages such as Chinese require word segmentation,
1793 * Specify such segmentation when overridden in derived class.
1795 * @param $string String
1798 function segmentByWord( $string ) {
1803 * Some languages have special punctuation need to be normalized.
1804 * Make such changes here.
1806 * @param $string String
1809 function normalizeForSearch( $string ) {
1810 return self
::convertDoubleWidth( $string );
1814 * convert double-width roman characters to single-width.
1815 * range: ff00-ff5f ~= 0020-007f
1817 protected static function convertDoubleWidth( $string ) {
1818 static $full = null;
1819 static $half = null;
1821 if ( $full === null ) {
1822 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1823 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1824 $full = str_split( $fullWidth, 3 );
1825 $half = str_split( $halfWidth );
1828 $string = str_replace( $full, $half, $string );
1832 protected static function insertSpace( $string, $pattern ) {
1833 $string = preg_replace( $pattern, " $1 ", $string );
1834 $string = preg_replace( '/ +/', ' ', $string );
1838 function convertForSearchResult( $termsArray ) {
1839 # some languages, e.g. Chinese, need to do a conversion
1840 # in order for search results to be displayed correctly
1845 * Get the first character of a string.
1850 function firstChar( $s ) {
1853 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1854 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1859 if ( isset( $matches[1] ) ) {
1860 if ( strlen( $matches[1] ) != 3 ) {
1864 // Break down Hangul syllables to grab the first jamo
1865 $code = utf8ToCodepoint( $matches[1] );
1866 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1868 } elseif ( $code < 0xb098 ) {
1869 return "\xe3\x84\xb1";
1870 } elseif ( $code < 0xb2e4 ) {
1871 return "\xe3\x84\xb4";
1872 } elseif ( $code < 0xb77c ) {
1873 return "\xe3\x84\xb7";
1874 } elseif ( $code < 0xb9c8 ) {
1875 return "\xe3\x84\xb9";
1876 } elseif ( $code < 0xbc14 ) {
1877 return "\xe3\x85\x81";
1878 } elseif ( $code < 0xc0ac ) {
1879 return "\xe3\x85\x82";
1880 } elseif ( $code < 0xc544 ) {
1881 return "\xe3\x85\x85";
1882 } elseif ( $code < 0xc790 ) {
1883 return "\xe3\x85\x87";
1884 } elseif ( $code < 0xcc28 ) {
1885 return "\xe3\x85\x88";
1886 } elseif ( $code < 0xce74 ) {
1887 return "\xe3\x85\x8a";
1888 } elseif ( $code < 0xd0c0 ) {
1889 return "\xe3\x85\x8b";
1890 } elseif ( $code < 0xd30c ) {
1891 return "\xe3\x85\x8c";
1892 } elseif ( $code < 0xd558 ) {
1893 return "\xe3\x85\x8d";
1895 return "\xe3\x85\x8e";
1902 function initEncoding() {
1903 # Some languages may have an alternate char encoding option
1904 # (Esperanto X-coding, Japanese furigana conversion, etc)
1905 # If this language is used as the primary content language,
1906 # an override to the defaults can be set here on startup.
1909 function recodeForEdit( $s ) {
1910 # For some languages we'll want to explicitly specify
1911 # which characters make it into the edit box raw
1912 # or are converted in some way or another.
1913 # Note that if wgOutputEncoding is different from
1914 # wgInputEncoding, this text will be further converted
1915 # to wgOutputEncoding.
1916 global $wgEditEncoding;
1917 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1920 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1924 function recodeInput( $s ) {
1925 # Take the previous into account.
1926 global $wgEditEncoding;
1927 if ( $wgEditEncoding != '' ) {
1928 $enc = $wgEditEncoding;
1932 if ( $enc == 'UTF-8' ) {
1935 return $this->iconv( $enc, 'UTF-8', $s );
1940 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1941 * also cleans up certain backwards-compatible sequences, converting them
1942 * to the modern Unicode equivalent.
1944 * This is language-specific for performance reasons only.
1946 function normalize( $s ) {
1947 global $wgAllUnicodeFixes;
1948 $s = UtfNormal
::cleanUp( $s );
1949 if ( $wgAllUnicodeFixes ) {
1950 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1951 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1958 * Transform a string using serialized data stored in the given file (which
1959 * must be in the serialized subdirectory of $IP). The file contains pairs
1960 * mapping source characters to destination characters.
1962 * The data is cached in process memory. This will go faster if you have the
1963 * FastStringSearch extension.
1965 function transformUsingPairFile( $file, $string ) {
1966 if ( !isset( $this->transformData
[$file] ) ) {
1967 $data = wfGetPrecompiledData( $file );
1968 if ( $data === false ) {
1969 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1971 $this->transformData
[$file] = new ReplacementArray( $data );
1973 return $this->transformData
[$file]->replace( $string );
1977 * For right-to-left language support
1982 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1986 * Return the correct HTML 'dir' attribute value for this language.
1990 return $this->isRTL() ?
'rtl' : 'ltr';
1994 * Return 'left' or 'right' as appropriate alignment for line-start
1995 * for this language's text direction.
1997 * Should be equivalent to CSS3 'start' text-align value....
2001 function alignStart() {
2002 return $this->isRTL() ?
'right' : 'left';
2006 * Return 'right' or 'left' as appropriate alignment for line-end
2007 * for this language's text direction.
2009 * Should be equivalent to CSS3 'end' text-align value....
2013 function alignEnd() {
2014 return $this->isRTL() ?
'left' : 'right';
2018 * A hidden direction mark (LRM or RLM), depending on the language direction
2022 function getDirMark() {
2023 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2026 function capitalizeAllNouns() {
2027 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2031 * An arrow, depending on the language direction
2035 function getArrow() {
2036 return $this->isRTL() ?
'←' : '→';
2040 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2044 function linkPrefixExtension() {
2045 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2048 function getMagicWords() {
2049 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2052 # Fill a MagicWord object with data from here
2053 function getMagic( $mw ) {
2054 if ( !$this->mMagicHookDone
) {
2055 $this->mMagicHookDone
= true;
2056 wfProfileIn( 'LanguageGetMagic' );
2057 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2058 wfProfileOut( 'LanguageGetMagic' );
2060 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2061 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2063 $magicWords = $this->getMagicWords();
2064 if ( isset( $magicWords[$mw->mId
] ) ) {
2065 $rawEntry = $magicWords[$mw->mId
];
2071 if ( !is_array( $rawEntry ) ) {
2072 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2074 $mw->mCaseSensitive
= $rawEntry[0];
2075 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2080 * Add magic words to the extension array
2082 function addMagicWordsByLang( $newWords ) {
2083 $code = $this->getCode();
2084 $fallbackChain = array();
2085 while ( $code && !in_array( $code, $fallbackChain ) ) {
2086 $fallbackChain[] = $code;
2087 $code = self
::getFallbackFor( $code );
2089 if ( !in_array( 'en', $fallbackChain ) ) {
2090 $fallbackChain[] = 'en';
2092 $fallbackChain = array_reverse( $fallbackChain );
2093 foreach ( $fallbackChain as $code ) {
2094 if ( isset( $newWords[$code] ) ) {
2095 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2101 * Get special page names, as an associative array
2102 * case folded alias => real name
2104 function getSpecialPageAliases() {
2105 // Cache aliases because it may be slow to load them
2106 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2108 $this->mExtendedSpecialPageAliases
=
2109 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2110 wfRunHooks( 'LanguageGetSpecialPageAliases',
2111 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2114 return $this->mExtendedSpecialPageAliases
;
2118 * Italic is unsuitable for some languages
2120 * @param $text String: the text to be emphasized.
2123 function emphasize( $text ) {
2124 return "<em>$text</em>";
2128 * Normally we output all numbers in plain en_US style, that is
2129 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2130 * point twohundredthirtyfive. However this is not sutable for all
2131 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2132 * Icelandic just want to use commas instead of dots, and dots instead
2133 * of commas like "293.291,235".
2135 * An example of this function being called:
2137 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2140 * See LanguageGu.php for the Gujarati implementation and
2141 * $separatorTransformTable on MessageIs.php for
2142 * the , => . and . => , implementation.
2144 * @todo check if it's viable to use localeconv() for the decimal
2146 * @param $number Mixed: the string to be formatted, should be an integer
2147 * or a floating point number.
2148 * @param $nocommafy Bool: set to true for special numbers like dates
2151 function formatNum( $number, $nocommafy = false ) {
2152 global $wgTranslateNumerals;
2153 if ( !$nocommafy ) {
2154 $number = $this->commafy( $number );
2155 $s = $this->separatorTransformTable();
2157 $number = strtr( $number, $s );
2161 if ( $wgTranslateNumerals ) {
2162 $s = $this->digitTransformTable();
2164 $number = strtr( $number, $s );
2171 function parseFormattedNumber( $number ) {
2172 $s = $this->digitTransformTable();
2174 $number = strtr( $number, array_flip( $s ) );
2177 $s = $this->separatorTransformTable();
2179 $number = strtr( $number, array_flip( $s ) );
2182 $number = strtr( $number, array( ',' => '' ) );
2187 * Adds commas to a given number
2192 function commafy( $_ ) {
2193 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2196 function digitTransformTable() {
2197 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2200 function separatorTransformTable() {
2201 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2205 * Take a list of strings and build a locale-friendly comma-separated
2206 * list, using the local comma-separator message.
2207 * The last two strings are chained with an "and".
2212 function listToText( $l ) {
2214 $m = count( $l ) - 1;
2216 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2218 for ( $i = $m; $i >= 0; $i-- ) {
2221 } else if ( $i == $m - 1 ) {
2222 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2224 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2232 * Take a list of strings and build a locale-friendly comma-separated
2233 * list, using the local comma-separator message.
2234 * @param $list array of strings to put in a comma list
2237 function commaList( $list ) {
2242 array( 'parsemag', 'escapenoentities', 'language' => $this )
2248 * Take a list of strings and build a locale-friendly semicolon-separated
2249 * list, using the local semicolon-separator message.
2250 * @param $list array of strings to put in a semicolon list
2253 function semicolonList( $list ) {
2257 'semicolon-separator',
2258 array( 'parsemag', 'escapenoentities', 'language' => $this )
2264 * Same as commaList, but separate it with the pipe instead.
2265 * @param $list array of strings to put in a pipe list
2268 function pipeList( $list ) {
2273 array( 'escapenoentities', 'language' => $this )
2279 * Truncate a string to a specified length in bytes, appending an optional
2280 * string (e.g. for ellipses)
2282 * The database offers limited byte lengths for some columns in the database;
2283 * multi-byte character sets mean we need to ensure that only whole characters
2284 * are included, otherwise broken characters can be passed to the user
2286 * If $length is negative, the string will be truncated from the beginning
2288 * @param $string String to truncate
2289 * @param $length Int: maximum length (excluding ellipses)
2290 * @param $ellipsis String to append to the truncated text
2293 function truncate( $string, $length, $ellipsis = '...' ) {
2294 # Use the localized ellipsis character
2295 if ( $ellipsis == '...' ) {
2296 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2298 # Check if there is no need to truncate
2299 if ( $length == 0 ) {
2301 } elseif ( strlen( $string ) <= abs( $length ) ) {
2304 $stringOriginal = $string;
2305 if ( $length > 0 ) {
2306 $string = substr( $string, 0, $length ); // xyz...
2307 $string = $this->removeBadCharLast( $string );
2308 $string = $string . $ellipsis;
2310 $string = substr( $string, $length ); // ...xyz
2311 $string = $this->removeBadCharFirst( $string );
2312 $string = $ellipsis . $string;
2314 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2315 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2318 return $stringOriginal;
2323 * Remove bytes that represent an incomplete Unicode character
2324 * at the end of string (e.g. bytes of the char are missing)
2326 * @param $string String
2329 protected function removeBadCharLast( $string ) {
2330 $char = ord( $string[strlen( $string ) - 1] );
2332 if ( $char >= 0xc0 ) {
2333 # We got the first byte only of a multibyte char; remove it.
2334 $string = substr( $string, 0, -1 );
2335 } elseif ( $char >= 0x80 &&
2336 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2337 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2339 # We chopped in the middle of a character; remove it
2346 * Remove bytes that represent an incomplete Unicode character
2347 * at the start of string (e.g. bytes of the char are missing)
2349 * @param $string String
2352 protected function removeBadCharFirst( $string ) {
2353 $char = ord( $string[0] );
2354 if ( $char >= 0x80 && $char < 0xc0 ) {
2355 # We chopped in the middle of a character; remove the whole thing
2356 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2362 * Truncate a string of valid HTML to a specified length in bytes,
2363 * appending an optional string (e.g. for ellipses), and return valid HTML
2365 * This is only intended for styled/linked text, such as HTML with
2366 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2368 * Note: tries to fix broken HTML with MWTidy
2370 * @param string $text HTML string to truncate
2371 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2372 * @param string $ellipsis String to append to the truncated text
2375 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2376 # Use the localized ellipsis character
2377 if ( $ellipsis == '...' ) {
2378 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2380 # Check if there is no need to truncate
2381 if ( $length <= 0 ) {
2382 return $ellipsis; // no text shown, nothing to format
2383 } elseif ( strlen( $text ) <= $length ) {
2384 return $text; // string short enough even *with* HTML
2386 $text = MWTidy
::tidy( $text ); // fix tags
2387 $displayLen = 0; // innerHTML legth so far
2388 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2389 $tagType = 0; // 0-open, 1-close
2390 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2391 $entityState = 0; // 0-not entity, 1-entity
2393 $openTags = array(); // open tag stack
2394 $textLen = strlen( $text );
2395 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2397 $lastCh = $pos ?
$text[$pos - 1] : '';
2398 $ret .= $ch; // add to result string
2400 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2401 $entityState = 0; // for bad HTML
2402 $bracketState = 1; // tag started (checking for backslash)
2403 } elseif ( $ch == '>' ) {
2404 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2405 $entityState = 0; // for bad HTML
2406 $bracketState = 0; // out of brackets
2407 } elseif ( $bracketState == 1 ) {
2409 $tagType = 1; // close tag (e.g. "</span>")
2411 $tagType = 0; // open tag (e.g. "<span>")
2414 $bracketState = 2; // building tag name
2415 } elseif ( $bracketState == 2 ) {
2419 // Name found (e.g. "<a href=..."), add on tag attributes...
2420 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2422 } elseif ( $bracketState == 0 ) {
2423 if ( $entityState ) {
2426 $displayLen++
; // entity is one displayed char
2430 $entityState = 1; // entity found, (e.g. " ")
2432 $displayLen++
; // this char is displayed
2433 // Add on the other display text after this...
2434 $skipped = $this->truncate_skip(
2435 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2436 $displayLen +
= $skipped;
2441 # Consider truncation once the display length has reached the maximim.
2442 # Double-check that we're not in the middle of a bracket/entity...
2443 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2444 if ( !$testingEllipsis ) {
2445 $testingEllipsis = true;
2446 # Save where we are; we will truncate here unless
2447 # the ellipsis actually makes the string longer.
2448 $pOpenTags = $openTags; // save state
2449 $pRet = $ret; // save state
2450 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2451 # Ellipsis won't make string longer/equal, the truncation point was OK.
2452 $openTags = $pOpenTags; // reload state
2453 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2454 $ret .= $ellipsis; // add ellipsis
2459 if ( $displayLen == 0 ) {
2460 return ''; // no text shown, nothing to format
2462 // Close the last tag if left unclosed by bad HTML
2463 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2464 while ( count( $openTags ) > 0 ) {
2465 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2470 // truncateHtml() helper function
2471 // like strcspn() but adds the skipped chars to $ret
2472 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2474 if ( $start < strlen( $text ) ) {
2475 $skipCount = strcspn( $text, $search, $start, $len );
2476 $ret .= substr( $text, $start, $skipCount );
2482 * truncateHtml() helper function
2483 * (a) push or pop $tag from $openTags as needed
2484 * (b) clear $tag value
2485 * @param String &$tag Current HTML tag name we are looking at
2486 * @param int $tagType (0-open tag, 1-close tag)
2487 * @param char $lastCh Character before the '>' that ended this tag
2488 * @param array &$openTags Open tag stack (not accounting for $tag)
2490 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2491 $tag = ltrim( $tag );
2493 if ( $tagType == 0 && $lastCh != '/' ) {
2494 $openTags[] = $tag; // tag opened (didn't close itself)
2495 } else if ( $tagType == 1 ) {
2496 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2497 array_pop( $openTags ); // tag closed
2505 * Grammatical transformations, needed for inflected languages
2506 * Invoked by putting {{grammar:case|word}} in a message
2508 * @param $word string
2509 * @param $case string
2512 function convertGrammar( $word, $case ) {
2513 global $wgGrammarForms;
2514 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2515 return $wgGrammarForms[$this->getCode()][$case][$word];
2521 * Provides an alternative text depending on specified gender.
2522 * Usage {{gender:username|masculine|feminine|neutral}}.
2523 * username is optional, in which case the gender of current user is used,
2524 * but only in (some) interface messages; otherwise default gender is used.
2525 * If second or third parameter are not specified, masculine is used.
2526 * These details may be overriden per language.
2528 function gender( $gender, $forms ) {
2529 if ( !count( $forms ) ) {
2532 $forms = $this->preConvertPlural( $forms, 2 );
2533 if ( $gender === 'male' ) {
2536 if ( $gender === 'female' ) {
2539 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2543 * Plural form transformations, needed for some languages.
2544 * For example, there are 3 form of plural in Russian and Polish,
2545 * depending on "count mod 10". See [[w:Plural]]
2546 * For English it is pretty simple.
2548 * Invoked by putting {{plural:count|wordform1|wordform2}}
2549 * or {{plural:count|wordform1|wordform2|wordform3}}
2551 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2553 * @param $count Integer: non-localized number
2554 * @param $forms Array: different plural forms
2555 * @return string Correct form of plural for $count in this language
2557 function convertPlural( $count, $forms ) {
2558 if ( !count( $forms ) ) {
2561 $forms = $this->preConvertPlural( $forms, 2 );
2563 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2567 * Checks that convertPlural was given an array and pads it to requested
2568 * amound of forms by copying the last one.
2570 * @param $count Integer: How many forms should there be at least
2571 * @param $forms Array of forms given to convertPlural
2572 * @return array Padded array of forms or an exception if not an array
2574 protected function preConvertPlural( /* Array */ $forms, $count ) {
2575 while ( count( $forms ) < $count ) {
2576 $forms[] = $forms[count( $forms ) - 1];
2582 * For translating of expiry times
2583 * @param $str String: the validated block time in English
2584 * @return Somehow translated block time
2585 * @see LanguageFi.php for example implementation
2587 function translateBlockExpiry( $str ) {
2588 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2590 if ( $scBlockExpiryOptions == '-' ) {
2594 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2595 if ( strpos( $option, ':' ) === false ) {
2598 list( $show, $value ) = explode( ':', $option );
2599 if ( strcmp( $str, $value ) == 0 ) {
2600 return htmlspecialchars( trim( $show ) );
2608 * languages like Chinese need to be segmented in order for the diff
2611 * @param $text String
2614 function segmentForDiff( $text ) {
2619 * and unsegment to show the result
2621 * @param $text String
2624 function unsegmentForDiff( $text ) {
2628 # convert text to all supported variants
2629 function autoConvertToAllVariants( $text ) {
2630 return $this->mConverter
->autoConvertToAllVariants( $text );
2633 # convert text to different variants of a language.
2634 function convert( $text ) {
2635 return $this->mConverter
->convert( $text );
2638 # Convert a Title object to a string in the preferred variant
2639 function convertTitle( $title ) {
2640 return $this->mConverter
->convertTitle( $title );
2643 # Check if this is a language with variants
2644 function hasVariants() {
2645 return sizeof( $this->getVariants() ) > 1;
2648 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2649 function armourMath( $text ) {
2650 return $this->mConverter
->armourMath( $text );
2654 * Perform output conversion on a string, and encode for safe HTML output.
2655 * @param $text String text to be converted
2656 * @param $isTitle Bool whether this conversion is for the article title
2658 * @todo this should get integrated somewhere sane
2660 function convertHtml( $text, $isTitle = false ) {
2661 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2664 function convertCategoryKey( $key ) {
2665 return $this->mConverter
->convertCategoryKey( $key );
2669 * Get the list of variants supported by this langauge
2670 * see sample implementation in LanguageZh.php
2672 * @return array an array of language codes
2674 function getVariants() {
2675 return $this->mConverter
->getVariants();
2678 function getPreferredVariant() {
2679 return $this->mConverter
->getPreferredVariant();
2682 function getDefaultVariant() {
2683 return $this->mConverter
->getDefaultVariant();
2686 function getURLVariant() {
2687 return $this->mConverter
->getURLVariant();
2691 * If a language supports multiple variants, it is
2692 * possible that non-existing link in one variant
2693 * actually exists in another variant. this function
2694 * tries to find it. See e.g. LanguageZh.php
2696 * @param $link String: the name of the link
2697 * @param $nt Mixed: the title object of the link
2698 * @param $ignoreOtherCond Boolean: to disable other conditions when
2699 * we need to transclude a template or update a category's link
2700 * @return null the input parameters may be modified upon return
2702 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2703 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2707 * If a language supports multiple variants, converts text
2708 * into an array of all possible variants of the text:
2709 * 'variant' => text in that variant
2711 function convertLinkToAllVariants( $text ) {
2712 return $this->mConverter
->convertLinkToAllVariants( $text );
2716 * returns language specific options used by User::getPageRenderHash()
2717 * for example, the preferred language variant
2721 function getExtraHashOptions() {
2722 return $this->mConverter
->getExtraHashOptions();
2726 * For languages that support multiple variants, the title of an
2727 * article may be displayed differently in different variants. this
2728 * function returns the apporiate title defined in the body of the article.
2732 function getParsedTitle() {
2733 return $this->mConverter
->getParsedTitle();
2737 * Enclose a string with the "no conversion" tag. This is used by
2738 * various functions in the Parser
2740 * @param $text String: text to be tagged for no conversion
2742 * @return string the tagged text
2744 function markNoConversion( $text, $noParse = false ) {
2745 return $this->mConverter
->markNoConversion( $text, $noParse );
2749 * A regular expression to match legal word-trailing characters
2750 * which should be merged onto a link of the form [[foo]]bar.
2754 function linkTrail() {
2755 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2758 function getLangObj() {
2763 * Get the RFC 3066 code for this language object
2765 function getCode() {
2766 return $this->mCode
;
2769 function setCode( $code ) {
2770 $this->mCode
= $code;
2774 * Get the name of a file for a certain language code
2775 * @param $prefix string Prepend this to the filename
2776 * @param $code string Language code
2777 * @param $suffix string Append this to the filename
2778 * @return string $prefix . $mangledCode . $suffix
2780 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2781 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2785 * Get the language code from a file name. Inverse of getFileName()
2786 * @param $filename string $prefix . $languageCode . $suffix
2787 * @param $prefix string Prefix before the language code
2788 * @param $suffix string Suffix after the language code
2789 * @return Language code, or false if $prefix or $suffix isn't found
2791 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2793 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2794 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2795 if ( !count( $m ) ) {
2798 return str_replace( '_', '-', strtolower( $m[1] ) );
2801 static function getMessagesFileName( $code ) {
2803 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2806 static function getClassFileName( $code ) {
2808 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2812 * Get the fallback for a given language
2814 static function getFallbackFor( $code ) {
2815 if ( $code === 'en' ) {
2819 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2824 * Get all messages for a given language
2825 * WARNING: this may take a long time
2827 static function getMessagesFor( $code ) {
2828 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2832 * Get a message for a given language
2834 static function getMessageFor( $key, $code ) {
2835 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2838 function fixVariableInNamespace( $talk ) {
2839 if ( strpos( $talk, '$1' ) === false ) {
2843 global $wgMetaNamespace;
2844 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2846 # Allow grammar transformations
2847 # Allowing full message-style parsing would make simple requests
2848 # such as action=raw much more expensive than they need to be.
2849 # This will hopefully cover most cases.
2850 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2851 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2852 return str_replace( ' ', '_', $talk );
2855 function replaceGrammarInNamespace( $m ) {
2856 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2859 static function getCaseMaps() {
2860 static $wikiUpperChars, $wikiLowerChars;
2861 if ( isset( $wikiUpperChars ) ) {
2862 return array( $wikiUpperChars, $wikiLowerChars );
2865 wfProfileIn( __METHOD__
);
2866 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2867 if ( $arr === false ) {
2868 throw new MWException(
2869 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2872 wfProfileOut( __METHOD__
);
2873 return array( $wikiUpperChars, $wikiLowerChars );
2876 function formatTimePeriod( $seconds ) {
2877 if ( $seconds < 10 ) {
2878 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2879 } elseif ( $seconds < 60 ) {
2880 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2881 } elseif ( $seconds < 3600 ) {
2882 $minutes = floor( $seconds / 60 );
2883 $secondsPart = round( fmod( $seconds, 60 ) );
2884 if ( $secondsPart == 60 ) {
2888 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2889 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2891 $hours = floor( $seconds / 3600 );
2892 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2893 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2894 if ( $secondsPart == 60 ) {
2898 if ( $minutes == 60 ) {
2902 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2903 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2904 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2908 function formatBitrate( $bps ) {
2909 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2911 return $this->formatNum( $bps ) . $units[0];
2913 $unitIndex = floor( log10( $bps ) / 3 );
2914 $mantissa = $bps / pow( 1000, $unitIndex );
2915 if ( $mantissa < 10 ) {
2916 $mantissa = round( $mantissa, 1 );
2918 $mantissa = round( $mantissa );
2920 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2924 * Format a size in bytes for output, using an appropriate
2925 * unit (B, KB, MB or GB) according to the magnitude in question
2927 * @param $size Size to format
2928 * @return string Plain text (not HTML)
2930 function formatSize( $size ) {
2931 // For small sizes no decimal places necessary
2933 if ( $size > 1024 ) {
2934 $size = $size / 1024;
2935 if ( $size > 1024 ) {
2936 $size = $size / 1024;
2937 // For MB and bigger two decimal places are smarter
2939 if ( $size > 1024 ) {
2940 $size = $size / 1024;
2941 $msg = 'size-gigabytes';
2943 $msg = 'size-megabytes';
2946 $msg = 'size-kilobytes';
2949 $msg = 'size-bytes';
2951 $size = round( $size, $round );
2952 $text = $this->getMessageFromDB( $msg );
2953 return str_replace( '$1', $this->formatNum( $size ), $text );
2957 * Get the conversion rule title, if any.
2959 function getConvRuleTitle() {
2960 return $this->mConverter
->getConvRuleTitle();
2964 * Given a string, convert it to a (hopefully short) key that can be used
2965 * for efficient sorting. A binary sort according to the sortkeys
2966 * corresponds to a logical sort of the corresponding strings. Current
2967 * code expects that a null character should sort before all others, but
2968 * has no other particular expectations (and that one can be changed if
2971 * @param string $string UTF-8 string
2972 * @return string Binary sortkey
2974 public function convertToSortkey( $string ) {
2975 # Fake function for now
2976 return strtoupper( $string );
2980 * Given a string, return the logical "first letter" to be used for
2981 * grouping on category pages and so on. This has to be coordinated
2982 * carefully with convertToSortkey(), or else the sorted list might jump
2983 * back and forth between the same "initial letters" or other pathological
2984 * behavior. For instance, if you just return the first character, but "a"
2985 * sorts the same as "A" based on convertToSortkey(), then you might get a
2997 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2999 * @param string $string UTF-8 string
3000 * @return string UTF-8 string corresponding to the first letter of input
3002 public function firstLetterForLists( $string ) {
3003 if ( $string[0] == "\0" ) {
3004 $string = substr( $string, 1 );
3006 return strtoupper( $this->firstChar( $string ) );