3 * @defgroup Language Language
9 if ( !defined( 'MEDIAWIKI' ) ) {
10 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 global $wgLanguageNames;
16 require_once( dirname( __FILE__
) . '/Names.php' );
18 global $wgInputEncoding, $wgOutputEncoding;
21 * These are always UTF-8, they exist only for backwards compatibility
23 $wgInputEncoding = 'UTF-8';
24 $wgOutputEncoding = 'UTF-8';
26 if ( function_exists( 'mb_strtoupper' ) ) {
27 mb_internal_encoding( 'UTF-8' );
31 * a fake language converter
37 function FakeConverter( $langobj ) { $this->mLang
= $langobj; }
38 function autoConvertToAllVariants( $text ) { return $text; }
39 function convert( $t ) { return $t; }
40 function convertTitle( $t ) { return $t->getPrefixedText(); }
41 function getVariants() { return array( $this->mLang
->getCode() ); }
42 function getPreferredVariant() { return $this->mLang
->getCode(); }
43 function getConvRuleTitle() { return false; }
44 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
45 function getExtraHashOptions() { return ''; }
46 function getParsedTitle() { return ''; }
47 function markNoConversion( $text, $noParse = false ) { return $text; }
48 function convertCategoryKey( $key ) { return $key; }
49 function convertLinkToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
50 function armourMath( $text ) { return $text; }
54 * Internationalisation code
58 var $mConverter, $mVariants, $mCode, $mLoaded = false;
59 var $mMagicExtensions = array(), $mMagicHookDone = false;
61 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
62 var $dateFormatStrings = array();
63 var $mExtendedSpecialPageAliases;
66 * ReplacementArray object caches
68 var $transformData = array();
70 static public $dataCache;
71 static public $mLangObjCache = array();
73 static public $mWeekdayMsgs = array(
74 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
78 static public $mWeekdayAbbrevMsgs = array(
79 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
82 static public $mMonthMsgs = array(
83 'january', 'february', 'march', 'april', 'may_long', 'june',
84 'july', 'august', 'september', 'october', 'november',
87 static public $mMonthGenMsgs = array(
88 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
89 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
92 static public $mMonthAbbrevMsgs = array(
93 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
94 'sep', 'oct', 'nov', 'dec'
97 static public $mIranianCalendarMonthMsgs = array(
98 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
99 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
100 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
101 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
104 static public $mHebrewCalendarMonthMsgs = array(
105 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
106 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
107 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
108 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
109 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
112 static public $mHebrewCalendarMonthGenMsgs = array(
113 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
114 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
115 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
116 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
117 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
120 static public $mHijriCalendarMonthMsgs = array(
121 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
122 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
123 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
124 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
128 * Get a cached language object for a given language code
130 static function factory( $code ) {
131 if ( !isset( self
::$mLangObjCache[$code] ) ) {
132 if ( count( self
::$mLangObjCache ) > 10 ) {
133 // Don't keep a billion objects around, that's stupid.
134 self
::$mLangObjCache = array();
136 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
138 return self
::$mLangObjCache[$code];
142 * Create a language object for a given language code
144 protected static function newFromCode( $code ) {
146 static $recursionLevel = 0;
147 if ( $code == 'en' ) {
150 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
151 // Preload base classes to work around APC/PHP5 bug
152 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
153 include_once( "$IP/languages/classes/$class.deps.php" );
155 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
156 include_once( "$IP/languages/classes/$class.php" );
160 if ( $recursionLevel > 5 ) {
161 throw new MWException( "Language fallback loop detected when creating class $class\n" );
164 if ( !class_exists( $class ) ) {
165 $fallback = Language
::getFallbackFor( $code );
167 $lang = Language
::newFromCode( $fallback );
169 $lang->setCode( $code );
177 * Get the LocalisationCache instance
179 public static function getLocalisationCache() {
180 if ( is_null( self
::$dataCache ) ) {
181 global $wgLocalisationCacheConf;
182 $class = $wgLocalisationCacheConf['class'];
183 self
::$dataCache = new $class( $wgLocalisationCacheConf );
185 return self
::$dataCache;
188 function __construct() {
189 $this->mConverter
= new FakeConverter( $this );
190 // Set the code to the name of the descendant
191 if ( get_class( $this ) == 'Language' ) {
194 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
196 self
::getLocalisationCache();
200 * Reduce memory usage
202 function __destruct() {
203 foreach ( $this as $name => $value ) {
204 unset( $this->$name );
209 * Hook which will be called if this is the content language.
210 * Descendants can use this to register hook functions or modify globals
212 function initContLang() { }
215 * @deprecated Use User::getDefaultOptions()
218 function getDefaultUserOptions() {
219 wfDeprecated( __METHOD__
);
220 return User
::getDefaultOptions();
223 function getFallbackLanguageCode() {
224 if ( $this->mCode
=== 'en' ) {
227 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
232 * Exports $wgBookstoreListEn
235 function getBookstoreList() {
236 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
242 function getNamespaces() {
243 if ( is_null( $this->namespaceNames
) ) {
244 global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk;
246 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
247 if ( $wgExtraNamespaces ) {
248 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames
;
251 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
252 if ( $wgMetaNamespaceTalk ) {
253 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
255 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
256 $this->namespaceNames
[NS_PROJECT_TALK
] =
257 $this->fixVariableInNamespace( $talk );
260 # Sometimes a language will be localised but not actually exist on this wiki.
261 $validNamespaces = MWNamespace
::getValidNamespaces();
262 foreach( $this->namespaceNames
as $key => $text ) {
263 if ( ! in_array( $key, $validNamespaces ) ) {
264 unset( $this->namespaceNames
[$key] );
268 # The above mixing may leave namespaces out of canonical order.
269 # Re-order by namespace ID number...
270 ksort( $this->namespaceNames
);
272 return $this->namespaceNames
;
276 * A convenience function that returns the same thing as
277 * getNamespaces() except with the array values changed to ' '
278 * where it found '_', useful for producing output to be displayed
279 * e.g. in <select> forms.
283 function getFormattedNamespaces() {
284 $ns = $this->getNamespaces();
285 foreach ( $ns as $k => $v ) {
286 $ns[$k] = strtr( $v, '_', ' ' );
292 * Get a namespace value by key
294 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
295 * echo $mw_ns; // prints 'MediaWiki'
298 * @param $index Int: the array key of the namespace to return
299 * @return mixed, string if the namespace value exists, otherwise false
301 function getNsText( $index ) {
302 $ns = $this->getNamespaces();
303 return isset( $ns[$index] ) ?
$ns[$index] : false;
307 * A convenience function that returns the same thing as
308 * getNsText() except with '_' changed to ' ', useful for
313 function getFormattedNsText( $index ) {
314 $ns = $this->getNsText( $index );
315 return strtr( $ns, '_', ' ' );
319 * Get a namespace key by value, case insensitive.
320 * Only matches namespace names for the current language, not the
321 * canonical ones defined in Namespace.php.
323 * @param $text String
324 * @return mixed An integer if $text is a valid value otherwise false
326 function getLocalNsIndex( $text ) {
327 $lctext = $this->lc( $text );
328 $ids = $this->getNamespaceIds();
329 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
332 function getNamespaceAliases() {
333 if ( is_null( $this->namespaceAliases
) ) {
334 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
338 foreach ( $aliases as $name => $index ) {
339 if ( $index === NS_PROJECT_TALK
) {
340 unset( $aliases[$name] );
341 $name = $this->fixVariableInNamespace( $name );
342 $aliases[$name] = $index;
346 $this->namespaceAliases
= $aliases;
348 return $this->namespaceAliases
;
351 function getNamespaceIds() {
352 if ( is_null( $this->mNamespaceIds
) ) {
353 global $wgNamespaceAliases;
354 # Put namespace names and aliases into a hashtable.
355 # If this is too slow, then we should arrange it so that it is done
356 # before caching. The catch is that at pre-cache time, the above
357 # class-specific fixup hasn't been done.
358 $this->mNamespaceIds
= array();
359 foreach ( $this->getNamespaces() as $index => $name ) {
360 $this->mNamespaceIds
[$this->lc( $name )] = $index;
362 foreach ( $this->getNamespaceAliases() as $name => $index ) {
363 $this->mNamespaceIds
[$this->lc( $name )] = $index;
365 if ( $wgNamespaceAliases ) {
366 foreach ( $wgNamespaceAliases as $name => $index ) {
367 $this->mNamespaceIds
[$this->lc( $name )] = $index;
371 return $this->mNamespaceIds
;
376 * Get a namespace key by value, case insensitive. Canonical namespace
377 * names override custom ones defined for the current language.
379 * @param $text String
380 * @return mixed An integer if $text is a valid value otherwise false
382 function getNsIndex( $text ) {
383 $lctext = $this->lc( $text );
384 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
387 $ids = $this->getNamespaceIds();
388 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
392 * short names for language variants used for language conversion links.
394 * @param $code String
397 function getVariantname( $code ) {
398 return $this->getMessageFromDB( "variantname-$code" );
401 function specialPage( $name ) {
402 $aliases = $this->getSpecialPageAliases();
403 if ( isset( $aliases[$name][0] ) ) {
404 $name = $aliases[$name][0];
406 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
409 function getQuickbarSettings() {
411 $this->getMessage( 'qbsettings-none' ),
412 $this->getMessage( 'qbsettings-fixedleft' ),
413 $this->getMessage( 'qbsettings-fixedright' ),
414 $this->getMessage( 'qbsettings-floatingleft' ),
415 $this->getMessage( 'qbsettings-floatingright' )
419 function getMathNames() {
420 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
423 function getDatePreferences() {
424 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
427 function getDateFormats() {
428 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
431 function getDefaultDateFormat() {
432 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
433 if ( $df === 'dmy or mdy' ) {
434 global $wgAmericanDates;
435 return $wgAmericanDates ?
'mdy' : 'dmy';
441 function getDatePreferenceMigrationMap() {
442 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
445 function getImageFile( $image ) {
446 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
449 function getDefaultUserOptionOverrides() {
450 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
453 function getExtraUserToggles() {
454 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
457 function getUserToggle( $tog ) {
458 return $this->getMessageFromDB( "tog-$tog" );
462 * Get language names, indexed by code.
463 * If $customisedOnly is true, only returns codes with a messages file
465 public static function getLanguageNames( $customisedOnly = false ) {
466 global $wgLanguageNames, $wgExtraLanguageNames;
467 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
468 if ( !$customisedOnly ) {
474 $dir = opendir( "$IP/languages/messages" );
475 while ( false !== ( $file = readdir( $dir ) ) ) {
476 $code = self
::getCodeFromFileName( $file, 'Messages' );
477 if ( $code && isset( $allNames[$code] ) ) {
478 $names[$code] = $allNames[$code];
486 * Get a message from the MediaWiki namespace.
488 * @param $msg String: message name
491 function getMessageFromDB( $msg ) {
492 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
495 function getLanguageName( $code ) {
496 $names = self
::getLanguageNames();
497 if ( !array_key_exists( $code, $names ) ) {
500 return $names[$code];
503 function getMonthName( $key ) {
504 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
507 function getMonthNameGen( $key ) {
508 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
511 function getMonthAbbreviation( $key ) {
512 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
515 function getWeekdayName( $key ) {
516 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
519 function getWeekdayAbbreviation( $key ) {
520 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
523 function getIranianCalendarMonthName( $key ) {
524 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
527 function getHebrewCalendarMonthName( $key ) {
528 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
531 function getHebrewCalendarMonthNameGen( $key ) {
532 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
535 function getHijriCalendarMonthName( $key ) {
536 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
540 * Used by date() and time() to adjust the time output.
542 * @param $ts Int the time in date('YmdHis') format
543 * @param $tz Mixed: adjust the time by this amount (default false, mean we
544 * get user timecorrection setting)
547 function userAdjust( $ts, $tz = false ) {
548 global $wgUser, $wgLocalTZoffset;
550 if ( $tz === false ) {
551 $tz = $wgUser->getOption( 'timecorrection' );
554 $data = explode( '|', $tz, 3 );
556 if ( $data[0] == 'ZoneInfo' ) {
557 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
558 $date = date_create( $ts, timezone_open( 'UTC' ) );
559 date_timezone_set( $date, timezone_open( $data[2] ) );
560 $date = date_format( $date, 'YmdHis' );
563 # Unrecognized timezone, default to 'Offset' with the stored offset.
568 if ( $data[0] == 'System' ||
$tz == '' ) {
569 # Global offset in minutes.
570 if ( isset( $wgLocalTZoffset ) ) {
571 $minDiff = $wgLocalTZoffset;
573 } else if ( $data[0] == 'Offset' ) {
574 $minDiff = intval( $data[1] );
576 $data = explode( ':', $tz );
577 if ( count( $data ) == 2 ) {
578 $data[0] = intval( $data[0] );
579 $data[1] = intval( $data[1] );
580 $minDiff = abs( $data[0] ) * 60 +
$data[1];
581 if ( $data[0] < 0 ) {
582 $minDiff = -$minDiff;
585 $minDiff = intval( $data[0] ) * 60;
589 # No difference ? Return time unchanged
590 if ( 0 == $minDiff ) {
594 wfSuppressWarnings(); // E_STRICT system time bitching
595 # Generate an adjusted date; take advantage of the fact that mktime
596 # will normalize out-of-range values so we don't have to split $minDiff
597 # into hours and minutes.
599 (int)substr( $ts, 8, 2 ) ), # Hours
600 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
601 (int)substr( $ts, 12, 2 ), # Seconds
602 (int)substr( $ts, 4, 2 ), # Month
603 (int)substr( $ts, 6, 2 ), # Day
604 (int)substr( $ts, 0, 4 ) ); # Year
606 $date = date( 'YmdHis', $t );
613 * This is a workalike of PHP's date() function, but with better
614 * internationalisation, a reduced set of format characters, and a better
617 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
618 * PHP manual for definitions. "o" format character is supported since
619 * PHP 5.1.0, previous versions return literal o.
620 * There are a number of extensions, which start with "x":
622 * xn Do not translate digits of the next numeric format character
623 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
624 * xr Use roman numerals for the next numeric format character
625 * xh Use hebrew numerals for the next numeric format character
627 * xg Genitive month name
629 * xij j (day number) in Iranian calendar
630 * xiF F (month name) in Iranian calendar
631 * xin n (month number) in Iranian calendar
632 * xiY Y (full year) in Iranian calendar
634 * xjj j (day number) in Hebrew calendar
635 * xjF F (month name) in Hebrew calendar
636 * xjt t (days in month) in Hebrew calendar
637 * xjx xg (genitive month name) in Hebrew calendar
638 * xjn n (month number) in Hebrew calendar
639 * xjY Y (full year) in Hebrew calendar
641 * xmj j (day number) in Hijri calendar
642 * xmF F (month name) in Hijri calendar
643 * xmn n (month number) in Hijri calendar
644 * xmY Y (full year) in Hijri calendar
646 * xkY Y (full year) in Thai solar calendar. Months and days are
647 * identical to the Gregorian calendar
648 * xoY Y (full year) in Minguo calendar or Juche year.
649 * Months and days are identical to the
651 * xtY Y (full year) in Japanese nengo. Months and days are
652 * identical to the Gregorian calendar
654 * Characters enclosed in double quotes will be considered literal (with
655 * the quotes themselves removed). Unmatched quotes will be considered
656 * literal quotes. Example:
658 * "The month is" F => The month is January
661 * Backslash escaping is also supported.
663 * Input timestamp is assumed to be pre-normalized to the desired local
666 * @param $format String
667 * @param $ts String: 14-character timestamp
670 * @todo emulation of "o" format character for PHP pre 5.1.0
671 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
673 function sprintfDate( $format, $ts ) {
686 for ( $p = 0; $p < strlen( $format ); $p++
) {
689 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
690 $code .= $format[++
$p];
693 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
694 $code .= $format[++
$p];
705 $rawToggle = !$rawToggle;
714 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
717 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
718 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
721 $num = substr( $ts, 6, 2 );
724 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
725 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
728 $num = intval( substr( $ts, 6, 2 ) );
732 $iranian = self
::tsToIranian( $ts );
738 $hijri = self
::tsToHijri( $ts );
744 $hebrew = self
::tsToHebrew( $ts );
750 $unix = wfTimestamp( TS_UNIX
, $ts );
752 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
756 $unix = wfTimestamp( TS_UNIX
, $ts );
758 $w = gmdate( 'w', $unix );
763 $unix = wfTimestamp( TS_UNIX
, $ts );
765 $num = gmdate( 'w', $unix );
769 $unix = wfTimestamp( TS_UNIX
, $ts );
771 $num = gmdate( 'z', $unix );
775 $unix = wfTimestamp( TS_UNIX
, $ts );
777 $num = gmdate( 'W', $unix );
780 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
784 $iranian = self
::tsToIranian( $ts );
786 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
790 $hijri = self
::tsToHijri( $ts );
792 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
796 $hebrew = self
::tsToHebrew( $ts );
798 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
801 $num = substr( $ts, 4, 2 );
804 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
807 $num = intval( substr( $ts, 4, 2 ) );
811 $iranian = self
::tsToIranian( $ts );
817 $hijri = self
::tsToHijri ( $ts );
823 $hebrew = self
::tsToHebrew( $ts );
829 $unix = wfTimestamp( TS_UNIX
, $ts );
831 $num = gmdate( 't', $unix );
835 $hebrew = self
::tsToHebrew( $ts );
841 $unix = wfTimestamp( TS_UNIX
, $ts );
843 $num = gmdate( 'L', $unix );
845 # 'o' is supported since PHP 5.1.0
846 # return literal if not supported
847 # TODO: emulation for pre 5.1.0 versions
850 $unix = wfTimestamp( TS_UNIX
, $ts );
852 if ( version_compare( PHP_VERSION
, '5.1.0' ) === 1 ) {
853 $num = date( 'o', $unix );
859 $num = substr( $ts, 0, 4 );
863 $iranian = self
::tsToIranian( $ts );
869 $hijri = self
::tsToHijri( $ts );
875 $hebrew = self
::tsToHebrew( $ts );
881 $thai = self
::tsToYear( $ts, 'thai' );
887 $minguo = self
::tsToYear( $ts, 'minguo' );
893 $tenno = self
::tsToYear( $ts, 'tenno' );
898 $num = substr( $ts, 2, 2 );
901 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
904 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
907 $h = substr( $ts, 8, 2 );
908 $num = $h %
12 ?
$h %
12 : 12;
911 $num = intval( substr( $ts, 8, 2 ) );
914 $h = substr( $ts, 8, 2 );
915 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
918 $num = substr( $ts, 8, 2 );
921 $num = substr( $ts, 10, 2 );
924 $num = substr( $ts, 12, 2 );
928 $unix = wfTimestamp( TS_UNIX
, $ts );
930 $s .= gmdate( 'c', $unix );
934 $unix = wfTimestamp( TS_UNIX
, $ts );
936 $s .= gmdate( 'r', $unix );
940 $unix = wfTimestamp( TS_UNIX
, $ts );
946 if ( $p < strlen( $format ) - 1 ) {
954 if ( $p < strlen( $format ) - 1 ) {
955 $endQuote = strpos( $format, '"', $p +
1 );
956 if ( $endQuote === false ) {
957 # No terminating quote, assume literal "
960 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
964 # Quote at end of string, assume literal "
971 if ( $num !== false ) {
972 if ( $rawToggle ||
$raw ) {
975 } elseif ( $roman ) {
976 $s .= self
::romanNumeral( $num );
978 } elseif ( $hebrewNum ) {
979 $s .= self
::hebrewNumeral( $num );
982 $s .= $this->formatNum( $num, true );
990 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
991 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
993 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
994 * Gregorian dates to Iranian dates. Originally written in C, it
995 * is released under the terms of GNU Lesser General Public
996 * License. Conversion to PHP was performed by Niklas Laxström.
998 * Link: http://www.farsiweb.info/jalali/jalali.c
1000 private static function tsToIranian( $ts ) {
1001 $gy = substr( $ts, 0, 4 ) -1600;
1002 $gm = substr( $ts, 4, 2 ) -1;
1003 $gd = substr( $ts, 6, 2 ) -1;
1005 # Days passed from the beginning (including leap years)
1007 +
floor( ( $gy +
3 ) / 4 )
1008 - floor( ( $gy +
99 ) / 100 )
1009 +
floor( ( $gy +
399 ) / 400 );
1012 // Add days of the past months of this year
1013 for ( $i = 0; $i < $gm; $i++
) {
1014 $gDayNo +
= self
::$GREG_DAYS[$i];
1018 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1022 // Days passed in current month
1025 $jDayNo = $gDayNo - 79;
1027 $jNp = floor( $jDayNo / 12053 );
1030 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1033 if ( $jDayNo >= 366 ) {
1034 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1035 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1038 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1039 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1045 return array( $jy, $jm, $jd );
1049 * Converting Gregorian dates to Hijri dates.
1051 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1053 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1055 private static function tsToHijri( $ts ) {
1056 $year = substr( $ts, 0, 4 );
1057 $month = substr( $ts, 4, 2 );
1058 $day = substr( $ts, 6, 2 );
1066 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1067 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1070 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1071 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1072 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1075 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1076 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1079 $zl = $zjd -1948440 +
10632;
1080 $zn = (int)( ( $zl - 1 ) / 10631 );
1081 $zl = $zl - 10631 * $zn +
354;
1082 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1083 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1084 $zm = (int)( ( 24 * $zl ) / 709 );
1085 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1086 $zy = 30 * $zn +
$zj - 30;
1088 return array( $zy, $zm, $zd );
1092 * Converting Gregorian dates to Hebrew dates.
1094 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1095 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1096 * to translate the relevant functions into PHP and release them under
1099 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1100 * and Adar II is 14. In a non-leap year, Adar is 6.
1102 private static function tsToHebrew( $ts ) {
1104 $year = substr( $ts, 0, 4 );
1105 $month = substr( $ts, 4, 2 );
1106 $day = substr( $ts, 6, 2 );
1108 # Calculate Hebrew year
1109 $hebrewYear = $year +
3760;
1111 # Month number when September = 1, August = 12
1113 if ( $month > 12 ) {
1120 # Calculate day of year from 1 September
1122 for ( $i = 1; $i < $month; $i++
) {
1126 # Check if the year is leap
1127 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1130 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1137 # Calculate the start of the Hebrew year
1138 $start = self
::hebrewYearStart( $hebrewYear );
1140 # Calculate next year's start
1141 if ( $dayOfYear <= $start ) {
1142 # Day is before the start of the year - it is the previous year
1144 $nextStart = $start;
1148 # Add days since previous year's 1 September
1150 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1154 # Start of the new (previous) year
1155 $start = self
::hebrewYearStart( $hebrewYear );
1158 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1161 # Calculate Hebrew day of year
1162 $hebrewDayOfYear = $dayOfYear - $start;
1164 # Difference between year's days
1165 $diff = $nextStart - $start;
1166 # Add 12 (or 13 for leap years) days to ignore the difference between
1167 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1168 # difference is only about the year type
1169 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1175 # Check the year pattern, and is leap year
1176 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1177 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1178 # and non-leap years
1179 $yearPattern = $diff %
30;
1180 # Check if leap year
1181 $isLeap = $diff >= 30;
1183 # Calculate day in the month from number of day in the Hebrew year
1184 # Don't check Adar - if the day is not in Adar, we will stop before;
1185 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1186 $hebrewDay = $hebrewDayOfYear;
1189 while ( $hebrewMonth <= 12 ) {
1190 # Calculate days in this month
1191 if ( $isLeap && $hebrewMonth == 6 ) {
1192 # Adar in a leap year
1194 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1196 if ( $hebrewDay <= $days ) {
1200 # Subtract the days of Adar I
1201 $hebrewDay -= $days;
1204 if ( $hebrewDay <= $days ) {
1210 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1211 # Cheshvan in a complete year (otherwise as the rule below)
1213 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1214 # Kislev in an incomplete year (otherwise as the rule below)
1217 # Odd months have 30 days, even have 29
1218 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1220 if ( $hebrewDay <= $days ) {
1221 # In the current month
1224 # Subtract the days of the current month
1225 $hebrewDay -= $days;
1226 # Try in the next month
1231 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1235 * This calculates the Hebrew year start, as days since 1 September.
1236 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1237 * Used for Hebrew date.
1239 private static function hebrewYearStart( $year ) {
1240 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1241 $b = intval( ( $year - 1 ) %
4 );
1242 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1246 $Mar = intval( $m );
1252 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1253 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1255 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1257 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1261 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1266 * Algorithm to convert Gregorian dates to Thai solar dates,
1267 * Minguo dates or Minguo dates.
1269 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1270 * http://en.wikipedia.org/wiki/Minguo_calendar
1271 * http://en.wikipedia.org/wiki/Japanese_era_name
1273 * @param $ts String: 14-character timestamp
1274 * @param $cName String: calender name
1275 * @return Array: converted year, month, day
1277 private static function tsToYear( $ts, $cName ) {
1278 $gy = substr( $ts, 0, 4 );
1279 $gm = substr( $ts, 4, 2 );
1280 $gd = substr( $ts, 6, 2 );
1282 if ( !strcmp( $cName, 'thai' ) ) {
1284 # Add 543 years to the Gregorian calendar
1285 # Months and days are identical
1286 $gy_offset = $gy +
543;
1287 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1289 # Deduct 1911 years from the Gregorian calendar
1290 # Months and days are identical
1291 $gy_offset = $gy - 1911;
1292 } else if ( !strcmp( $cName, 'tenno' ) ) {
1293 # Nengō dates up to Meiji period
1294 # Deduct years from the Gregorian calendar
1295 # depending on the nengo periods
1296 # Months and days are identical
1297 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1299 $gy_gannen = $gy - 1868 +
1;
1300 $gy_offset = $gy_gannen;
1301 if ( $gy_gannen == 1 ) {
1304 $gy_offset = '明治' . $gy_offset;
1306 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1307 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1308 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1309 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1310 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1314 $gy_gannen = $gy - 1912 +
1;
1315 $gy_offset = $gy_gannen;
1316 if ( $gy_gannen == 1 ) {
1319 $gy_offset = '大正' . $gy_offset;
1321 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1322 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1323 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1327 $gy_gannen = $gy - 1926 +
1;
1328 $gy_offset = $gy_gannen;
1329 if ( $gy_gannen == 1 ) {
1332 $gy_offset = '昭和' . $gy_offset;
1335 $gy_gannen = $gy - 1989 +
1;
1336 $gy_offset = $gy_gannen;
1337 if ( $gy_gannen == 1 ) {
1340 $gy_offset = '平成' . $gy_offset;
1346 return array( $gy_offset, $gm, $gd );
1350 * Roman number formatting up to 3000
1352 static function romanNumeral( $num ) {
1353 static $table = array(
1354 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1355 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1356 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1357 array( '', 'M', 'MM', 'MMM' )
1360 $num = intval( $num );
1361 if ( $num > 3000 ||
$num <= 0 ) {
1366 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1367 if ( $num >= $pow10 ) {
1368 $s .= $table[$i][floor( $num / $pow10 )];
1370 $num = $num %
$pow10;
1376 * Hebrew Gematria number formatting up to 9999
1378 static function hebrewNumeral( $num ) {
1379 static $table = array(
1380 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1381 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1382 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1383 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1386 $num = intval( $num );
1387 if ( $num > 9999 ||
$num <= 0 ) {
1392 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1393 if ( $num >= $pow10 ) {
1394 if ( $num == 15 ||
$num == 16 ) {
1395 $s .= $table[0][9] . $table[0][$num - 9];
1398 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1399 if ( $pow10 == 1000 ) {
1404 $num = $num %
$pow10;
1406 if ( strlen( $s ) == 2 ) {
1409 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1410 $str .= substr( $s, strlen( $s ) - 2, 2 );
1412 $start = substr( $str, 0, strlen( $str ) - 2 );
1413 $end = substr( $str, strlen( $str ) - 2 );
1416 $str = $start . 'ך';
1419 $str = $start . 'ם';
1422 $str = $start . 'ן';
1425 $str = $start . 'ף';
1428 $str = $start . 'ץ';
1435 * This is meant to be used by time(), date(), and timeanddate() to get
1436 * the date preference they're supposed to use, it should be used in
1440 * function timeanddate([...], $format = true) {
1441 * $datePreference = $this->dateFormat($format);
1446 * @param $usePrefs Mixed: if true, the user's preference is used
1447 * if false, the site/language default is used
1448 * if int/string, assumed to be a format.
1451 function dateFormat( $usePrefs = true ) {
1454 if ( is_bool( $usePrefs ) ) {
1456 $datePreference = $wgUser->getDatePreference();
1458 $datePreference = (string)User
::getDefaultOption( 'date' );
1461 $datePreference = (string)$usePrefs;
1465 if ( $datePreference == '' ) {
1469 return $datePreference;
1473 * Get a format string for a given type and preference
1474 * @param $type May be date, time or both
1475 * @param $pref The format name as it appears in Messages*.php
1477 function getDateFormatString( $type, $pref ) {
1478 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1479 if ( $pref == 'default' ) {
1480 $pref = $this->getDefaultDateFormat();
1481 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1483 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1484 if ( is_null( $df ) ) {
1485 $pref = $this->getDefaultDateFormat();
1486 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1489 $this->dateFormatStrings
[$type][$pref] = $df;
1491 return $this->dateFormatStrings
[$type][$pref];
1495 * @param $ts Mixed: the time format which needs to be turned into a
1496 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1497 * @param $adj Bool: whether to adjust the time output according to the
1498 * user configured offset ($timecorrection)
1499 * @param $format Mixed: true to use user's date format preference
1500 * @param $timecorrection String: the time offset as returned by
1501 * validateTimeZone() in Special:Preferences
1504 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1506 $ts = $this->userAdjust( $ts, $timecorrection );
1508 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1509 return $this->sprintfDate( $df, $ts );
1513 * @param $ts Mixed: the time format which needs to be turned into a
1514 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1515 * @param $adj Bool: whether to adjust the time output according to the
1516 * user configured offset ($timecorrection)
1517 * @param $format Mixed: true to use user's date format preference
1518 * @param $timecorrection String: the time offset as returned by
1519 * validateTimeZone() in Special:Preferences
1522 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1524 $ts = $this->userAdjust( $ts, $timecorrection );
1526 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1527 return $this->sprintfDate( $df, $ts );
1531 * @param $ts Mixed: the time format which needs to be turned into a
1532 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1533 * @param $adj Bool: whether to adjust the time output according to the
1534 * user configured offset ($timecorrection)
1535 * @param $format Mixed: what format to return, if it's false output the
1536 * default one (default true)
1537 * @param $timecorrection String: the time offset as returned by
1538 * validateTimeZone() in Special:Preferences
1541 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1542 $ts = wfTimestamp( TS_MW
, $ts );
1544 $ts = $this->userAdjust( $ts, $timecorrection );
1546 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1547 return $this->sprintfDate( $df, $ts );
1550 function getMessage( $key ) {
1551 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1554 function getAllMessages() {
1555 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1558 function iconv( $in, $out, $string ) {
1559 # This is a wrapper for iconv in all languages except esperanto,
1560 # which does some nasty x-conversions beforehand
1562 # Even with //IGNORE iconv can whine about illegal characters in
1563 # *input* string. We just ignore those too.
1564 # REF: http://bugs.php.net/bug.php?id=37166
1565 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1566 wfSuppressWarnings();
1567 $text = iconv( $in, $out . '//IGNORE', $string );
1568 wfRestoreWarnings();
1572 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1573 function ucwordbreaksCallbackAscii( $matches ) {
1574 return $this->ucfirst( $matches[1] );
1577 function ucwordbreaksCallbackMB( $matches ) {
1578 return mb_strtoupper( $matches[0] );
1581 function ucCallback( $matches ) {
1582 list( $wikiUpperChars ) = self
::getCaseMaps();
1583 return strtr( $matches[1], $wikiUpperChars );
1586 function lcCallback( $matches ) {
1587 list( , $wikiLowerChars ) = self
::getCaseMaps();
1588 return strtr( $matches[1], $wikiLowerChars );
1591 function ucwordsCallbackMB( $matches ) {
1592 return mb_strtoupper( $matches[0] );
1595 function ucwordsCallbackWiki( $matches ) {
1596 list( $wikiUpperChars ) = self
::getCaseMaps();
1597 return strtr( $matches[0], $wikiUpperChars );
1600 function ucfirst( $str ) {
1604 } elseif ( $o < 128 ) {
1605 return ucfirst( $str );
1607 // fall back to more complex logic in case of multibyte strings
1608 return $this->uc( $str, true );
1612 function uc( $str, $first = false ) {
1613 if ( function_exists( 'mb_strtoupper' ) ) {
1615 if ( $this->isMultibyte( $str ) ) {
1616 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1618 return ucfirst( $str );
1621 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1624 if ( $this->isMultibyte( $str ) ) {
1625 $x = $first ?
'^' : '';
1626 return preg_replace_callback(
1627 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1628 array( $this, 'ucCallback' ),
1632 return $first ?
ucfirst( $str ) : strtoupper( $str );
1637 function lcfirst( $str ) {
1640 return strval( $str );
1641 } elseif ( $o >= 128 ) {
1642 return $this->lc( $str, true );
1643 } elseif ( $o > 96 ) {
1646 $str[0] = strtolower( $str[0] );
1651 function lc( $str, $first = false ) {
1652 if ( function_exists( 'mb_strtolower' ) ) {
1654 if ( $this->isMultibyte( $str ) ) {
1655 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1657 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1660 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1663 if ( $this->isMultibyte( $str ) ) {
1664 $x = $first ?
'^' : '';
1665 return preg_replace_callback(
1666 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1667 array( $this, 'lcCallback' ),
1671 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1676 function isMultibyte( $str ) {
1677 return (bool)preg_match( '/[\x80-\xff]/', $str );
1680 function ucwords( $str ) {
1681 if ( $this->isMultibyte( $str ) ) {
1682 $str = $this->lc( $str );
1684 // regexp to find first letter in each word (i.e. after each space)
1685 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1687 // function to use to capitalize a single char
1688 if ( function_exists( 'mb_strtoupper' ) ) {
1689 return preg_replace_callback(
1691 array( $this, 'ucwordsCallbackMB' ),
1695 return preg_replace_callback(
1697 array( $this, 'ucwordsCallbackWiki' ),
1702 return ucwords( strtolower( $str ) );
1706 # capitalize words at word breaks
1707 function ucwordbreaks( $str ) {
1708 if ( $this->isMultibyte( $str ) ) {
1709 $str = $this->lc( $str );
1711 // since \b doesn't work for UTF-8, we explicitely define word break chars
1712 $breaks = "[ \-\(\)\}\{\.,\?!]";
1714 // find first letter after word break
1715 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1717 if ( function_exists( 'mb_strtoupper' ) ) {
1718 return preg_replace_callback(
1720 array( $this, 'ucwordbreaksCallbackMB' ),
1724 return preg_replace_callback(
1726 array( $this, 'ucwordsCallbackWiki' ),
1731 return preg_replace_callback(
1732 '/\b([\w\x80-\xff]+)\b/',
1733 array( $this, 'ucwordbreaksCallbackAscii' ),
1740 * Return a case-folded representation of $s
1742 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1743 * and $s2 are the same except for the case of their characters. It is not
1744 * necessary for the value returned to make sense when displayed.
1746 * Do *not* perform any other normalisation in this function. If a caller
1747 * uses this function when it should be using a more general normalisation
1748 * function, then fix the caller.
1750 function caseFold( $s ) {
1751 return $this->uc( $s );
1754 function checkTitleEncoding( $s ) {
1755 if ( is_array( $s ) ) {
1756 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1758 # Check for non-UTF-8 URLs
1759 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1764 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1765 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1770 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1773 function fallback8bitEncoding() {
1774 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1778 * Most writing systems use whitespace to break up words.
1779 * Some languages such as Chinese don't conventionally do this,
1780 * which requires special handling when breaking up words for
1783 function hasWordBreaks() {
1788 * Some languages such as Chinese require word segmentation,
1789 * Specify such segmentation when overridden in derived class.
1791 * @param $string String
1794 function segmentByWord( $string ) {
1799 * Some languages have special punctuation need to be normalized.
1800 * Make such changes here.
1802 * @param $string String
1805 function normalizeForSearch( $string ) {
1806 return self
::convertDoubleWidth( $string );
1810 * convert double-width roman characters to single-width.
1811 * range: ff00-ff5f ~= 0020-007f
1813 protected static function convertDoubleWidth( $string ) {
1814 static $full = null;
1815 static $half = null;
1817 if ( $full === null ) {
1818 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1819 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1820 $full = str_split( $fullWidth, 3 );
1821 $half = str_split( $halfWidth );
1824 $string = str_replace( $full, $half, $string );
1828 protected static function insertSpace( $string, $pattern ) {
1829 $string = preg_replace( $pattern, " $1 ", $string );
1830 $string = preg_replace( '/ +/', ' ', $string );
1834 function convertForSearchResult( $termsArray ) {
1835 # some languages, e.g. Chinese, need to do a conversion
1836 # in order for search results to be displayed correctly
1841 * Get the first character of a string.
1846 function firstChar( $s ) {
1849 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1850 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1855 if ( isset( $matches[1] ) ) {
1856 if ( strlen( $matches[1] ) != 3 ) {
1860 // Break down Hangul syllables to grab the first jamo
1861 $code = utf8ToCodepoint( $matches[1] );
1862 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1864 } elseif ( $code < 0xb098 ) {
1865 return "\xe3\x84\xb1";
1866 } elseif ( $code < 0xb2e4 ) {
1867 return "\xe3\x84\xb4";
1868 } elseif ( $code < 0xb77c ) {
1869 return "\xe3\x84\xb7";
1870 } elseif ( $code < 0xb9c8 ) {
1871 return "\xe3\x84\xb9";
1872 } elseif ( $code < 0xbc14 ) {
1873 return "\xe3\x85\x81";
1874 } elseif ( $code < 0xc0ac ) {
1875 return "\xe3\x85\x82";
1876 } elseif ( $code < 0xc544 ) {
1877 return "\xe3\x85\x85";
1878 } elseif ( $code < 0xc790 ) {
1879 return "\xe3\x85\x87";
1880 } elseif ( $code < 0xcc28 ) {
1881 return "\xe3\x85\x88";
1882 } elseif ( $code < 0xce74 ) {
1883 return "\xe3\x85\x8a";
1884 } elseif ( $code < 0xd0c0 ) {
1885 return "\xe3\x85\x8b";
1886 } elseif ( $code < 0xd30c ) {
1887 return "\xe3\x85\x8c";
1888 } elseif ( $code < 0xd558 ) {
1889 return "\xe3\x85\x8d";
1891 return "\xe3\x85\x8e";
1898 function initEncoding() {
1899 # Some languages may have an alternate char encoding option
1900 # (Esperanto X-coding, Japanese furigana conversion, etc)
1901 # If this language is used as the primary content language,
1902 # an override to the defaults can be set here on startup.
1905 function recodeForEdit( $s ) {
1906 # For some languages we'll want to explicitly specify
1907 # which characters make it into the edit box raw
1908 # or are converted in some way or another.
1909 # Note that if wgOutputEncoding is different from
1910 # wgInputEncoding, this text will be further converted
1911 # to wgOutputEncoding.
1912 global $wgEditEncoding;
1913 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1916 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1920 function recodeInput( $s ) {
1921 # Take the previous into account.
1922 global $wgEditEncoding;
1923 if ( $wgEditEncoding != '' ) {
1924 $enc = $wgEditEncoding;
1928 if ( $enc == 'UTF-8' ) {
1931 return $this->iconv( $enc, 'UTF-8', $s );
1936 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1937 * also cleans up certain backwards-compatible sequences, converting them
1938 * to the modern Unicode equivalent.
1940 * This is language-specific for performance reasons only.
1942 function normalize( $s ) {
1943 global $wgAllUnicodeFixes;
1944 $s = UtfNormal
::cleanUp( $s );
1945 if ( $wgAllUnicodeFixes ) {
1946 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1947 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1954 * Transform a string using serialized data stored in the given file (which
1955 * must be in the serialized subdirectory of $IP). The file contains pairs
1956 * mapping source characters to destination characters.
1958 * The data is cached in process memory. This will go faster if you have the
1959 * FastStringSearch extension.
1961 function transformUsingPairFile( $file, $string ) {
1962 if ( !isset( $this->transformData
[$file] ) ) {
1963 $data = wfGetPrecompiledData( $file );
1964 if ( $data === false ) {
1965 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1967 $this->transformData
[$file] = new ReplacementArray( $data );
1969 return $this->transformData
[$file]->replace( $string );
1973 * For right-to-left language support
1978 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1982 * Return the correct HTML 'dir' attribute value for this language.
1986 return $this->isRTL() ?
'rtl' : 'ltr';
1990 * Return 'left' or 'right' as appropriate alignment for line-start
1991 * for this language's text direction.
1993 * Should be equivalent to CSS3 'start' text-align value....
1997 function alignStart() {
1998 return $this->isRTL() ?
'right' : 'left';
2002 * Return 'right' or 'left' as appropriate alignment for line-end
2003 * for this language's text direction.
2005 * Should be equivalent to CSS3 'end' text-align value....
2009 function alignEnd() {
2010 return $this->isRTL() ?
'left' : 'right';
2014 * A hidden direction mark (LRM or RLM), depending on the language direction
2018 function getDirMark() {
2019 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2022 function capitalizeAllNouns() {
2023 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2027 * An arrow, depending on the language direction
2031 function getArrow() {
2032 return $this->isRTL() ?
'←' : '→';
2036 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2040 function linkPrefixExtension() {
2041 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2044 function getMagicWords() {
2045 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2048 # Fill a MagicWord object with data from here
2049 function getMagic( $mw ) {
2050 if ( !$this->mMagicHookDone
) {
2051 $this->mMagicHookDone
= true;
2052 wfProfileIn( 'LanguageGetMagic' );
2053 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2054 wfProfileOut( 'LanguageGetMagic' );
2056 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2057 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2059 $magicWords = $this->getMagicWords();
2060 if ( isset( $magicWords[$mw->mId
] ) ) {
2061 $rawEntry = $magicWords[$mw->mId
];
2067 if ( !is_array( $rawEntry ) ) {
2068 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2070 $mw->mCaseSensitive
= $rawEntry[0];
2071 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2076 * Add magic words to the extension array
2078 function addMagicWordsByLang( $newWords ) {
2079 $code = $this->getCode();
2080 $fallbackChain = array();
2081 while ( $code && !in_array( $code, $fallbackChain ) ) {
2082 $fallbackChain[] = $code;
2083 $code = self
::getFallbackFor( $code );
2085 if ( !in_array( 'en', $fallbackChain ) ) {
2086 $fallbackChain[] = 'en';
2088 $fallbackChain = array_reverse( $fallbackChain );
2089 foreach ( $fallbackChain as $code ) {
2090 if ( isset( $newWords[$code] ) ) {
2091 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2097 * Get special page names, as an associative array
2098 * case folded alias => real name
2100 function getSpecialPageAliases() {
2101 // Cache aliases because it may be slow to load them
2102 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2104 $this->mExtendedSpecialPageAliases
=
2105 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2106 wfRunHooks( 'LanguageGetSpecialPageAliases',
2107 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2110 return $this->mExtendedSpecialPageAliases
;
2114 * Italic is unsuitable for some languages
2116 * @param $text String: the text to be emphasized.
2119 function emphasize( $text ) {
2120 return "<em>$text</em>";
2124 * Normally we output all numbers in plain en_US style, that is
2125 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2126 * point twohundredthirtyfive. However this is not sutable for all
2127 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2128 * Icelandic just want to use commas instead of dots, and dots instead
2129 * of commas like "293.291,235".
2131 * An example of this function being called:
2133 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2136 * See LanguageGu.php for the Gujarati implementation and
2137 * $separatorTransformTable on MessageIs.php for
2138 * the , => . and . => , implementation.
2140 * @todo check if it's viable to use localeconv() for the decimal
2142 * @param $number Mixed: the string to be formatted, should be an integer
2143 * or a floating point number.
2144 * @param $nocommafy Bool: set to true for special numbers like dates
2147 function formatNum( $number, $nocommafy = false ) {
2148 global $wgTranslateNumerals;
2149 if ( !$nocommafy ) {
2150 $number = $this->commafy( $number );
2151 $s = $this->separatorTransformTable();
2153 $number = strtr( $number, $s );
2157 if ( $wgTranslateNumerals ) {
2158 $s = $this->digitTransformTable();
2160 $number = strtr( $number, $s );
2167 function parseFormattedNumber( $number ) {
2168 $s = $this->digitTransformTable();
2170 $number = strtr( $number, array_flip( $s ) );
2173 $s = $this->separatorTransformTable();
2175 $number = strtr( $number, array_flip( $s ) );
2178 $number = strtr( $number, array( ',' => '' ) );
2183 * Adds commas to a given number
2188 function commafy( $_ ) {
2189 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2192 function digitTransformTable() {
2193 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2196 function separatorTransformTable() {
2197 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2201 * Take a list of strings and build a locale-friendly comma-separated
2202 * list, using the local comma-separator message.
2203 * The last two strings are chained with an "and".
2208 function listToText( $l ) {
2210 $m = count( $l ) - 1;
2212 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2214 for ( $i = $m; $i >= 0; $i-- ) {
2217 } else if ( $i == $m - 1 ) {
2218 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2220 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2228 * Take a list of strings and build a locale-friendly comma-separated
2229 * list, using the local comma-separator message.
2230 * @param $list array of strings to put in a comma list
2233 function commaList( $list ) {
2238 array( 'parsemag', 'escapenoentities', 'language' => $this )
2244 * Take a list of strings and build a locale-friendly semicolon-separated
2245 * list, using the local semicolon-separator message.
2246 * @param $list array of strings to put in a semicolon list
2249 function semicolonList( $list ) {
2253 'semicolon-separator',
2254 array( 'parsemag', 'escapenoentities', 'language' => $this )
2260 * Same as commaList, but separate it with the pipe instead.
2261 * @param $list array of strings to put in a pipe list
2264 function pipeList( $list ) {
2269 array( 'escapenoentities', 'language' => $this )
2275 * Truncate a string to a specified length in bytes, appending an optional
2276 * string (e.g. for ellipses)
2278 * The database offers limited byte lengths for some columns in the database;
2279 * multi-byte character sets mean we need to ensure that only whole characters
2280 * are included, otherwise broken characters can be passed to the user
2282 * If $length is negative, the string will be truncated from the beginning
2284 * @param $string String to truncate
2285 * @param $length Int: maximum length (excluding ellipses)
2286 * @param $ellipsis String to append to the truncated text
2289 function truncate( $string, $length, $ellipsis = '...' ) {
2290 # Use the localized ellipsis character
2291 if ( $ellipsis == '...' ) {
2292 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2294 # Check if there is no need to truncate
2295 if ( $length == 0 ) {
2297 } elseif ( strlen( $string ) <= abs( $length ) ) {
2300 $stringOriginal = $string;
2301 if ( $length > 0 ) {
2302 $string = substr( $string, 0, $length ); // xyz...
2303 $string = $this->removeBadCharLast( $string );
2304 $string = $string . $ellipsis;
2306 $string = substr( $string, $length ); // ...xyz
2307 $string = $this->removeBadCharFirst( $string );
2308 $string = $ellipsis . $string;
2310 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2311 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2314 return $stringOriginal;
2319 * Remove bytes that represent an incomplete Unicode character
2320 * at the end of string (e.g. bytes of the char are missing)
2322 * @param $string String
2325 protected function removeBadCharLast( $string ) {
2326 $char = ord( $string[strlen( $string ) - 1] );
2328 if ( $char >= 0xc0 ) {
2329 # We got the first byte only of a multibyte char; remove it.
2330 $string = substr( $string, 0, -1 );
2331 } elseif ( $char >= 0x80 &&
2332 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2333 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2335 # We chopped in the middle of a character; remove it
2342 * Remove bytes that represent an incomplete Unicode character
2343 * at the start of string (e.g. bytes of the char are missing)
2345 * @param $string String
2348 protected function removeBadCharFirst( $string ) {
2349 $char = ord( $string[0] );
2350 if ( $char >= 0x80 && $char < 0xc0 ) {
2351 # We chopped in the middle of a character; remove the whole thing
2352 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2358 * Truncate a string of valid HTML to a specified length in bytes,
2359 * appending an optional string (e.g. for ellipses), and return valid HTML
2361 * This is only intended for styled/linked text, such as HTML with
2362 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2364 * Note: tries to fix broken HTML with MWTidy
2366 * @param string $text String to truncate
2367 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2368 * @param string $ellipsis String to append to the truncated text
2371 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2372 # Use the localized ellipsis character
2373 if ( $ellipsis == '...' ) {
2374 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2376 # Check if there is no need to truncate
2377 if ( $length <= 0 ) {
2378 return $ellipsis; // no text shown, nothing to format
2379 } elseif ( strlen( $text ) <= $length ) {
2380 return $text; // string short enough even *with* HTML
2382 $text = MWTidy
::tidy( $text ); // fix tags
2383 $displayLen = 0; // innerHTML legth so far
2384 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2385 $tagType = 0; // 0-open, 1-close
2386 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2387 $entityState = 0; // 0-not entity, 1-entity
2388 $tag = $ret = $ch = '';
2389 $openTags = array();
2390 $textLen = strlen( $text );
2391 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2393 $lastCh = $pos ?
$text[$pos - 1] : '';
2394 $ret .= $ch; // add to result string
2396 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2397 $entityState = 0; // for bad HTML
2398 $bracketState = 1; // tag started (checking for backslash)
2399 } elseif ( $ch == '>' ) {
2400 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2401 $entityState = 0; // for bad HTML
2402 $bracketState = 0; // out of brackets
2403 } elseif ( $bracketState == 1 ) {
2405 $tagType = 1; // close tag (e.g. "</span>")
2407 $tagType = 0; // open tag (e.g. "<span>")
2410 $bracketState = 2; // building tag name
2411 } elseif ( $bracketState == 2 ) {
2415 // Name found (e.g. "<a href=..."), add on tag attributes...
2416 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2418 } elseif ( $bracketState == 0 ) {
2419 if ( $entityState ) {
2422 $displayLen++
; // entity is one displayed char
2426 $entityState = 1; // entity found, (e.g. " ")
2428 $displayLen++
; // this char is displayed
2429 // Add on the other display text after this...
2430 $skipped = $this->truncate_skip(
2431 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2432 $displayLen +
= $skipped;
2437 # Consider truncation once the display length has reached the maximim.
2438 # Double-check that we're not in the middle of a bracket/entity...
2439 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2440 if ( !$testingEllipsis ) {
2441 $testingEllipsis = true;
2442 # Save where we are; we will truncate here unless
2443 # the ellipsis actually makes the string longer.
2444 $pOpenTags = $openTags; // save state
2445 $pRet = $ret; // save state
2446 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2447 # Ellipsis won't make string longer/equal, the truncation point was OK.
2448 $openTags = $pOpenTags; // reload state
2449 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2450 $ret .= $ellipsis; // add ellipsis
2455 if ( $displayLen == 0 ) {
2456 return ''; // no text shown, nothing to format
2458 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
2459 while ( count( $openTags ) > 0 ) {
2460 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2465 // truncateHtml() helper function
2466 // like strcspn() but adds the skipped chars to $ret
2467 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2469 if ( $start < strlen( $text ) ) {
2470 $skipCount = strcspn( $text, $search, $start, $len );
2471 $ret .= substr( $text, $start, $skipCount );
2476 // truncateHtml() helper function
2477 // (a) push or pop $tag from $openTags as needed
2478 // (b) clear $tag value
2479 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2480 $tag = ltrim( $tag );
2482 if ( $tagType == 0 && $lastCh != '/' ) {
2483 $openTags[] = $tag; // tag opened (didn't close itself)
2484 } else if ( $tagType == 1 ) {
2485 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2486 array_pop( $openTags ); // tag closed
2494 * Grammatical transformations, needed for inflected languages
2495 * Invoked by putting {{grammar:case|word}} in a message
2497 * @param $word string
2498 * @param $case string
2501 function convertGrammar( $word, $case ) {
2502 global $wgGrammarForms;
2503 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2504 return $wgGrammarForms[$this->getCode()][$case][$word];
2510 * Provides an alternative text depending on specified gender.
2511 * Usage {{gender:username|masculine|feminine|neutral}}.
2512 * username is optional, in which case the gender of current user is used,
2513 * but only in (some) interface messages; otherwise default gender is used.
2514 * If second or third parameter are not specified, masculine is used.
2515 * These details may be overriden per language.
2517 function gender( $gender, $forms ) {
2518 if ( !count( $forms ) ) {
2521 $forms = $this->preConvertPlural( $forms, 2 );
2522 if ( $gender === 'male' ) {
2525 if ( $gender === 'female' ) {
2528 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2532 * Plural form transformations, needed for some languages.
2533 * For example, there are 3 form of plural in Russian and Polish,
2534 * depending on "count mod 10". See [[w:Plural]]
2535 * For English it is pretty simple.
2537 * Invoked by putting {{plural:count|wordform1|wordform2}}
2538 * or {{plural:count|wordform1|wordform2|wordform3}}
2540 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2542 * @param $count Integer: non-localized number
2543 * @param $forms Array: different plural forms
2544 * @return string Correct form of plural for $count in this language
2546 function convertPlural( $count, $forms ) {
2547 if ( !count( $forms ) ) {
2550 $forms = $this->preConvertPlural( $forms, 2 );
2552 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2556 * Checks that convertPlural was given an array and pads it to requested
2557 * amound of forms by copying the last one.
2559 * @param $count Integer: How many forms should there be at least
2560 * @param $forms Array of forms given to convertPlural
2561 * @return array Padded array of forms or an exception if not an array
2563 protected function preConvertPlural( /* Array */ $forms, $count ) {
2564 while ( count( $forms ) < $count ) {
2565 $forms[] = $forms[count( $forms ) - 1];
2571 * For translating of expiry times
2572 * @param $str String: the validated block time in English
2573 * @return Somehow translated block time
2574 * @see LanguageFi.php for example implementation
2576 function translateBlockExpiry( $str ) {
2577 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2579 if ( $scBlockExpiryOptions == '-' ) {
2583 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2584 if ( strpos( $option, ':' ) === false ) {
2587 list( $show, $value ) = explode( ':', $option );
2588 if ( strcmp( $str, $value ) == 0 ) {
2589 return htmlspecialchars( trim( $show ) );
2597 * languages like Chinese need to be segmented in order for the diff
2600 * @param $text String
2603 function segmentForDiff( $text ) {
2608 * and unsegment to show the result
2610 * @param $text String
2613 function unsegmentForDiff( $text ) {
2617 # convert text to all supported variants
2618 function autoConvertToAllVariants( $text ) {
2619 return $this->mConverter
->autoConvertToAllVariants( $text );
2622 # convert text to different variants of a language.
2623 function convert( $text ) {
2624 return $this->mConverter
->convert( $text );
2627 # Convert a Title object to a string in the preferred variant
2628 function convertTitle( $title ) {
2629 return $this->mConverter
->convertTitle( $title );
2632 # Check if this is a language with variants
2633 function hasVariants() {
2634 return sizeof( $this->getVariants() ) > 1;
2637 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2638 function armourMath( $text ) {
2639 return $this->mConverter
->armourMath( $text );
2643 * Perform output conversion on a string, and encode for safe HTML output.
2644 * @param $text String text to be converted
2645 * @param $isTitle Bool whether this conversion is for the article title
2647 * @todo this should get integrated somewhere sane
2649 function convertHtml( $text, $isTitle = false ) {
2650 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2653 function convertCategoryKey( $key ) {
2654 return $this->mConverter
->convertCategoryKey( $key );
2658 * Get the list of variants supported by this langauge
2659 * see sample implementation in LanguageZh.php
2661 * @return array an array of language codes
2663 function getVariants() {
2664 return $this->mConverter
->getVariants();
2667 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2668 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2672 * If a language supports multiple variants, it is
2673 * possible that non-existing link in one variant
2674 * actually exists in another variant. this function
2675 * tries to find it. See e.g. LanguageZh.php
2677 * @param $link String: the name of the link
2678 * @param $nt Mixed: the title object of the link
2679 * @param $ignoreOtherCond Boolean: to disable other conditions when
2680 * we need to transclude a template or update a category's link
2681 * @return null the input parameters may be modified upon return
2683 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2684 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2688 * If a language supports multiple variants, converts text
2689 * into an array of all possible variants of the text:
2690 * 'variant' => text in that variant
2692 function convertLinkToAllVariants( $text ) {
2693 return $this->mConverter
->convertLinkToAllVariants( $text );
2697 * returns language specific options used by User::getPageRenderHash()
2698 * for example, the preferred language variant
2702 function getExtraHashOptions() {
2703 return $this->mConverter
->getExtraHashOptions();
2707 * For languages that support multiple variants, the title of an
2708 * article may be displayed differently in different variants. this
2709 * function returns the apporiate title defined in the body of the article.
2713 function getParsedTitle() {
2714 return $this->mConverter
->getParsedTitle();
2718 * Enclose a string with the "no conversion" tag. This is used by
2719 * various functions in the Parser
2721 * @param $text String: text to be tagged for no conversion
2723 * @return string the tagged text
2725 function markNoConversion( $text, $noParse = false ) {
2726 return $this->mConverter
->markNoConversion( $text, $noParse );
2730 * A regular expression to match legal word-trailing characters
2731 * which should be merged onto a link of the form [[foo]]bar.
2735 function linkTrail() {
2736 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2739 function getLangObj() {
2744 * Get the RFC 3066 code for this language object
2746 function getCode() {
2747 return $this->mCode
;
2750 function setCode( $code ) {
2751 $this->mCode
= $code;
2755 * Get the name of a file for a certain language code
2756 * @param $prefix string Prepend this to the filename
2757 * @param $code string Language code
2758 * @param $suffix string Append this to the filename
2759 * @return string $prefix . $mangledCode . $suffix
2761 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2762 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2766 * Get the language code from a file name. Inverse of getFileName()
2767 * @param $filename string $prefix . $languageCode . $suffix
2768 * @param $prefix string Prefix before the language code
2769 * @param $suffix string Suffix after the language code
2770 * @return Language code, or false if $prefix or $suffix isn't found
2772 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2774 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2775 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2776 if ( !count( $m ) ) {
2779 return str_replace( '_', '-', strtolower( $m[1] ) );
2782 static function getMessagesFileName( $code ) {
2784 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2787 static function getClassFileName( $code ) {
2789 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2793 * Get the fallback for a given language
2795 static function getFallbackFor( $code ) {
2796 if ( $code === 'en' ) {
2800 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2805 * Get all messages for a given language
2806 * WARNING: this may take a long time
2808 static function getMessagesFor( $code ) {
2809 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2813 * Get a message for a given language
2815 static function getMessageFor( $key, $code ) {
2816 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2819 function fixVariableInNamespace( $talk ) {
2820 if ( strpos( $talk, '$1' ) === false ) {
2824 global $wgMetaNamespace;
2825 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2827 # Allow grammar transformations
2828 # Allowing full message-style parsing would make simple requests
2829 # such as action=raw much more expensive than they need to be.
2830 # This will hopefully cover most cases.
2831 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2832 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2833 return str_replace( ' ', '_', $talk );
2836 function replaceGrammarInNamespace( $m ) {
2837 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2840 static function getCaseMaps() {
2841 static $wikiUpperChars, $wikiLowerChars;
2842 if ( isset( $wikiUpperChars ) ) {
2843 return array( $wikiUpperChars, $wikiLowerChars );
2846 wfProfileIn( __METHOD__
);
2847 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2848 if ( $arr === false ) {
2849 throw new MWException(
2850 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2853 wfProfileOut( __METHOD__
);
2854 return array( $wikiUpperChars, $wikiLowerChars );
2857 function formatTimePeriod( $seconds ) {
2858 if ( $seconds < 10 ) {
2859 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2860 } elseif ( $seconds < 60 ) {
2861 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2862 } elseif ( $seconds < 3600 ) {
2863 $minutes = floor( $seconds / 60 );
2864 $secondsPart = round( fmod( $seconds, 60 ) );
2865 if ( $secondsPart == 60 ) {
2869 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2870 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2872 $hours = floor( $seconds / 3600 );
2873 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2874 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2875 if ( $secondsPart == 60 ) {
2879 if ( $minutes == 60 ) {
2883 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2884 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2885 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2889 function formatBitrate( $bps ) {
2890 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2892 return $this->formatNum( $bps ) . $units[0];
2894 $unitIndex = floor( log10( $bps ) / 3 );
2895 $mantissa = $bps / pow( 1000, $unitIndex );
2896 if ( $mantissa < 10 ) {
2897 $mantissa = round( $mantissa, 1 );
2899 $mantissa = round( $mantissa );
2901 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2905 * Format a size in bytes for output, using an appropriate
2906 * unit (B, KB, MB or GB) according to the magnitude in question
2908 * @param $size Size to format
2909 * @return string Plain text (not HTML)
2911 function formatSize( $size ) {
2912 // For small sizes no decimal places necessary
2914 if ( $size > 1024 ) {
2915 $size = $size / 1024;
2916 if ( $size > 1024 ) {
2917 $size = $size / 1024;
2918 // For MB and bigger two decimal places are smarter
2920 if ( $size > 1024 ) {
2921 $size = $size / 1024;
2922 $msg = 'size-gigabytes';
2924 $msg = 'size-megabytes';
2927 $msg = 'size-kilobytes';
2930 $msg = 'size-bytes';
2932 $size = round( $size, $round );
2933 $text = $this->getMessageFromDB( $msg );
2934 return str_replace( '$1', $this->formatNum( $size ), $text );
2938 * Get the conversion rule title, if any.
2940 function getConvRuleTitle() {
2941 return $this->mConverter
->getConvRuleTitle();
2945 * Given a string, convert it to a (hopefully short) key that can be used
2946 * for efficient sorting. A binary sort according to the sortkeys
2947 * corresponds to a logical sort of the corresponding strings. Current
2948 * code expects that a null character should sort before all others, but
2949 * has no other particular expectations (and that one can be changed if
2952 * @param string $string UTF-8 string
2953 * @return string Binary sortkey
2955 public function convertToSortkey( $string ) {
2956 # Fake function for now
2957 return strtoupper( $string );
2961 * Does it make sense for lists to be split up into sections based on their
2962 * first letter? Logogram-based scripts probably want to return false.
2964 * TODO: Use this in CategoryPage.php.
2968 public function usesFirstLettersInLists() {
2973 * Given a string, return the logical "first letter" to be used for
2974 * grouping on category pages and so on. This has to be coordinated
2975 * carefully with convertToSortkey(), or else the sorted list might jump
2976 * back and forth between the same "initial letters" or other pathological
2977 * behavior. For instance, if you just return the first character, but "a"
2978 * sorts the same as "A" based on convertToSortkey(), then you might get a
2990 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2991 * Obviously, this is ignored if usesFirstLettersInLists() is false.
2993 * @param string $string UTF-8 string
2994 * @return string UTF-8 string corresponding to the first letter of input
2996 public function firstLetterForLists( $string ) {
2997 if ( $string[0] == "\0" ) {
2998 $string = substr( $string, 1 );
3000 return strtoupper( $this->firstChar( $string ) );