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 # The above mixing may leave namespaces out of canonical order.
261 # Re-order by namespace ID number...
262 ksort( $this->namespaceNames
);
264 return $this->namespaceNames
;
268 * A convenience function that returns the same thing as
269 * getNamespaces() except with the array values changed to ' '
270 * where it found '_', useful for producing output to be displayed
271 * e.g. in <select> forms.
275 function getFormattedNamespaces() {
276 $ns = $this->getNamespaces();
277 foreach ( $ns as $k => $v ) {
278 $ns[$k] = strtr( $v, '_', ' ' );
284 * Get a namespace value by key
286 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
287 * echo $mw_ns; // prints 'MediaWiki'
290 * @param $index Int: the array key of the namespace to return
291 * @return mixed, string if the namespace value exists, otherwise false
293 function getNsText( $index ) {
294 $ns = $this->getNamespaces();
295 return isset( $ns[$index] ) ?
$ns[$index] : false;
299 * A convenience function that returns the same thing as
300 * getNsText() except with '_' changed to ' ', useful for
305 function getFormattedNsText( $index ) {
306 $ns = $this->getNsText( $index );
307 return strtr( $ns, '_', ' ' );
311 * Get a namespace key by value, case insensitive.
312 * Only matches namespace names for the current language, not the
313 * canonical ones defined in Namespace.php.
315 * @param $text String
316 * @return mixed An integer if $text is a valid value otherwise false
318 function getLocalNsIndex( $text ) {
319 $lctext = $this->lc( $text );
320 $ids = $this->getNamespaceIds();
321 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
324 function getNamespaceAliases() {
325 if ( is_null( $this->namespaceAliases
) ) {
326 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
330 foreach ( $aliases as $name => $index ) {
331 if ( $index === NS_PROJECT_TALK
) {
332 unset( $aliases[$name] );
333 $name = $this->fixVariableInNamespace( $name );
334 $aliases[$name] = $index;
338 $this->namespaceAliases
= $aliases;
340 return $this->namespaceAliases
;
343 function getNamespaceIds() {
344 if ( is_null( $this->mNamespaceIds
) ) {
345 global $wgNamespaceAliases;
346 # Put namespace names and aliases into a hashtable.
347 # If this is too slow, then we should arrange it so that it is done
348 # before caching. The catch is that at pre-cache time, the above
349 # class-specific fixup hasn't been done.
350 $this->mNamespaceIds
= array();
351 foreach ( $this->getNamespaces() as $index => $name ) {
352 $this->mNamespaceIds
[$this->lc( $name )] = $index;
354 foreach ( $this->getNamespaceAliases() as $name => $index ) {
355 $this->mNamespaceIds
[$this->lc( $name )] = $index;
357 if ( $wgNamespaceAliases ) {
358 foreach ( $wgNamespaceAliases as $name => $index ) {
359 $this->mNamespaceIds
[$this->lc( $name )] = $index;
363 return $this->mNamespaceIds
;
368 * Get a namespace key by value, case insensitive. Canonical namespace
369 * names override custom ones defined for the current language.
371 * @param $text String
372 * @return mixed An integer if $text is a valid value otherwise false
374 function getNsIndex( $text ) {
375 $lctext = $this->lc( $text );
376 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
379 $ids = $this->getNamespaceIds();
380 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
384 * short names for language variants used for language conversion links.
386 * @param $code String
389 function getVariantname( $code ) {
390 return $this->getMessageFromDB( "variantname-$code" );
393 function specialPage( $name ) {
394 $aliases = $this->getSpecialPageAliases();
395 if ( isset( $aliases[$name][0] ) ) {
396 $name = $aliases[$name][0];
398 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
401 function getQuickbarSettings() {
403 $this->getMessage( 'qbsettings-none' ),
404 $this->getMessage( 'qbsettings-fixedleft' ),
405 $this->getMessage( 'qbsettings-fixedright' ),
406 $this->getMessage( 'qbsettings-floatingleft' ),
407 $this->getMessage( 'qbsettings-floatingright' )
411 function getMathNames() {
412 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
415 function getDatePreferences() {
416 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
419 function getDateFormats() {
420 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
423 function getDefaultDateFormat() {
424 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
425 if ( $df === 'dmy or mdy' ) {
426 global $wgAmericanDates;
427 return $wgAmericanDates ?
'mdy' : 'dmy';
433 function getDatePreferenceMigrationMap() {
434 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
437 function getImageFile( $image ) {
438 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
441 function getDefaultUserOptionOverrides() {
442 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
445 function getExtraUserToggles() {
446 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
449 function getUserToggle( $tog ) {
450 return $this->getMessageFromDB( "tog-$tog" );
454 * Get language names, indexed by code.
455 * If $customisedOnly is true, only returns codes with a messages file
457 public static function getLanguageNames( $customisedOnly = false ) {
458 global $wgLanguageNames, $wgExtraLanguageNames;
459 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
460 if ( !$customisedOnly ) {
466 $dir = opendir( "$IP/languages/messages" );
467 while ( false !== ( $file = readdir( $dir ) ) ) {
468 $code = self
::getCodeFromFileName( $file, 'Messages' );
469 if ( $code && isset( $allNames[$code] ) ) {
470 $names[$code] = $allNames[$code];
478 * Get a message from the MediaWiki namespace.
480 * @param $msg String: message name
483 function getMessageFromDB( $msg ) {
484 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
487 function getLanguageName( $code ) {
488 $names = self
::getLanguageNames();
489 if ( !array_key_exists( $code, $names ) ) {
492 return $names[$code];
495 function getMonthName( $key ) {
496 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
499 function getMonthNameGen( $key ) {
500 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
503 function getMonthAbbreviation( $key ) {
504 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
507 function getWeekdayName( $key ) {
508 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
511 function getWeekdayAbbreviation( $key ) {
512 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
515 function getIranianCalendarMonthName( $key ) {
516 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
519 function getHebrewCalendarMonthName( $key ) {
520 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
523 function getHebrewCalendarMonthNameGen( $key ) {
524 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
527 function getHijriCalendarMonthName( $key ) {
528 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
532 * Used by date() and time() to adjust the time output.
534 * @param $ts Int the time in date('YmdHis') format
535 * @param $tz Mixed: adjust the time by this amount (default false, mean we
536 * get user timecorrection setting)
539 function userAdjust( $ts, $tz = false ) {
540 global $wgUser, $wgLocalTZoffset;
542 if ( $tz === false ) {
543 $tz = $wgUser->getOption( 'timecorrection' );
546 $data = explode( '|', $tz, 3 );
548 if ( $data[0] == 'ZoneInfo' ) {
549 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
550 $date = date_create( $ts, timezone_open( 'UTC' ) );
551 date_timezone_set( $date, timezone_open( $data[2] ) );
552 $date = date_format( $date, 'YmdHis' );
555 # Unrecognized timezone, default to 'Offset' with the stored offset.
560 if ( $data[0] == 'System' ||
$tz == '' ) {
561 # Global offset in minutes.
562 if ( isset( $wgLocalTZoffset ) ) {
563 $minDiff = $wgLocalTZoffset;
565 } else if ( $data[0] == 'Offset' ) {
566 $minDiff = intval( $data[1] );
568 $data = explode( ':', $tz );
569 if ( count( $data ) == 2 ) {
570 $data[0] = intval( $data[0] );
571 $data[1] = intval( $data[1] );
572 $minDiff = abs( $data[0] ) * 60 +
$data[1];
573 if ( $data[0] < 0 ) {
574 $minDiff = -$minDiff;
577 $minDiff = intval( $data[0] ) * 60;
581 # No difference ? Return time unchanged
582 if ( 0 == $minDiff ) {
586 wfSuppressWarnings(); // E_STRICT system time bitching
587 # Generate an adjusted date; take advantage of the fact that mktime
588 # will normalize out-of-range values so we don't have to split $minDiff
589 # into hours and minutes.
591 (int)substr( $ts, 8, 2 ) ), # Hours
592 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
593 (int)substr( $ts, 12, 2 ), # Seconds
594 (int)substr( $ts, 4, 2 ), # Month
595 (int)substr( $ts, 6, 2 ), # Day
596 (int)substr( $ts, 0, 4 ) ); # Year
598 $date = date( 'YmdHis', $t );
605 * This is a workalike of PHP's date() function, but with better
606 * internationalisation, a reduced set of format characters, and a better
609 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
610 * PHP manual for definitions. "o" format character is supported since
611 * PHP 5.1.0, previous versions return literal o.
612 * There are a number of extensions, which start with "x":
614 * xn Do not translate digits of the next numeric format character
615 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
616 * xr Use roman numerals for the next numeric format character
617 * xh Use hebrew numerals for the next numeric format character
619 * xg Genitive month name
621 * xij j (day number) in Iranian calendar
622 * xiF F (month name) in Iranian calendar
623 * xin n (month number) in Iranian calendar
624 * xiY Y (full year) in Iranian calendar
626 * xjj j (day number) in Hebrew calendar
627 * xjF F (month name) in Hebrew calendar
628 * xjt t (days in month) in Hebrew calendar
629 * xjx xg (genitive month name) in Hebrew calendar
630 * xjn n (month number) in Hebrew calendar
631 * xjY Y (full year) in Hebrew calendar
633 * xmj j (day number) in Hijri calendar
634 * xmF F (month name) in Hijri calendar
635 * xmn n (month number) in Hijri calendar
636 * xmY Y (full year) in Hijri calendar
638 * xkY Y (full year) in Thai solar calendar. Months and days are
639 * identical to the Gregorian calendar
640 * xoY Y (full year) in Minguo calendar or Juche year.
641 * Months and days are identical to the
643 * xtY Y (full year) in Japanese nengo. Months and days are
644 * identical to the Gregorian calendar
646 * Characters enclosed in double quotes will be considered literal (with
647 * the quotes themselves removed). Unmatched quotes will be considered
648 * literal quotes. Example:
650 * "The month is" F => The month is January
653 * Backslash escaping is also supported.
655 * Input timestamp is assumed to be pre-normalized to the desired local
658 * @param $format String
659 * @param $ts String: 14-character timestamp
662 * @todo emulation of "o" format character for PHP pre 5.1.0
663 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
665 function sprintfDate( $format, $ts ) {
678 for ( $p = 0; $p < strlen( $format ); $p++
) {
681 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
682 $code .= $format[++
$p];
685 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
686 $code .= $format[++
$p];
697 $rawToggle = !$rawToggle;
706 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
709 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
710 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
713 $num = substr( $ts, 6, 2 );
716 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
717 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
720 $num = intval( substr( $ts, 6, 2 ) );
724 $iranian = self
::tsToIranian( $ts );
730 $hijri = self
::tsToHijri( $ts );
736 $hebrew = self
::tsToHebrew( $ts );
742 $unix = wfTimestamp( TS_UNIX
, $ts );
744 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
748 $unix = wfTimestamp( TS_UNIX
, $ts );
750 $w = gmdate( 'w', $unix );
755 $unix = wfTimestamp( TS_UNIX
, $ts );
757 $num = gmdate( 'w', $unix );
761 $unix = wfTimestamp( TS_UNIX
, $ts );
763 $num = gmdate( 'z', $unix );
767 $unix = wfTimestamp( TS_UNIX
, $ts );
769 $num = gmdate( 'W', $unix );
772 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
776 $iranian = self
::tsToIranian( $ts );
778 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
782 $hijri = self
::tsToHijri( $ts );
784 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
788 $hebrew = self
::tsToHebrew( $ts );
790 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
793 $num = substr( $ts, 4, 2 );
796 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
799 $num = intval( substr( $ts, 4, 2 ) );
803 $iranian = self
::tsToIranian( $ts );
809 $hijri = self
::tsToHijri ( $ts );
815 $hebrew = self
::tsToHebrew( $ts );
821 $unix = wfTimestamp( TS_UNIX
, $ts );
823 $num = gmdate( 't', $unix );
827 $hebrew = self
::tsToHebrew( $ts );
833 $unix = wfTimestamp( TS_UNIX
, $ts );
835 $num = gmdate( 'L', $unix );
837 # 'o' is supported since PHP 5.1.0
838 # return literal if not supported
839 # TODO: emulation for pre 5.1.0 versions
842 $unix = wfTimestamp( TS_UNIX
, $ts );
844 if ( version_compare( PHP_VERSION
, '5.1.0' ) === 1 ) {
845 $num = date( 'o', $unix );
851 $num = substr( $ts, 0, 4 );
855 $iranian = self
::tsToIranian( $ts );
861 $hijri = self
::tsToHijri( $ts );
867 $hebrew = self
::tsToHebrew( $ts );
873 $thai = self
::tsToYear( $ts, 'thai' );
879 $minguo = self
::tsToYear( $ts, 'minguo' );
885 $tenno = self
::tsToYear( $ts, 'tenno' );
890 $num = substr( $ts, 2, 2 );
893 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
896 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
899 $h = substr( $ts, 8, 2 );
900 $num = $h %
12 ?
$h %
12 : 12;
903 $num = intval( substr( $ts, 8, 2 ) );
906 $h = substr( $ts, 8, 2 );
907 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
910 $num = substr( $ts, 8, 2 );
913 $num = substr( $ts, 10, 2 );
916 $num = substr( $ts, 12, 2 );
920 $unix = wfTimestamp( TS_UNIX
, $ts );
922 $s .= gmdate( 'c', $unix );
926 $unix = wfTimestamp( TS_UNIX
, $ts );
928 $s .= gmdate( 'r', $unix );
932 $unix = wfTimestamp( TS_UNIX
, $ts );
938 if ( $p < strlen( $format ) - 1 ) {
946 if ( $p < strlen( $format ) - 1 ) {
947 $endQuote = strpos( $format, '"', $p +
1 );
948 if ( $endQuote === false ) {
949 # No terminating quote, assume literal "
952 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
956 # Quote at end of string, assume literal "
963 if ( $num !== false ) {
964 if ( $rawToggle ||
$raw ) {
967 } elseif ( $roman ) {
968 $s .= self
::romanNumeral( $num );
970 } elseif ( $hebrewNum ) {
971 $s .= self
::hebrewNumeral( $num );
974 $s .= $this->formatNum( $num, true );
982 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
983 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
985 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
986 * Gregorian dates to Iranian dates. Originally written in C, it
987 * is released under the terms of GNU Lesser General Public
988 * License. Conversion to PHP was performed by Niklas Laxström.
990 * Link: http://www.farsiweb.info/jalali/jalali.c
992 private static function tsToIranian( $ts ) {
993 $gy = substr( $ts, 0, 4 ) -1600;
994 $gm = substr( $ts, 4, 2 ) -1;
995 $gd = substr( $ts, 6, 2 ) -1;
997 # Days passed from the beginning (including leap years)
999 +
floor( ( $gy +
3 ) / 4 )
1000 - floor( ( $gy +
99 ) / 100 )
1001 +
floor( ( $gy +
399 ) / 400 );
1004 // Add days of the past months of this year
1005 for ( $i = 0; $i < $gm; $i++
) {
1006 $gDayNo +
= self
::$GREG_DAYS[$i];
1010 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1014 // Days passed in current month
1017 $jDayNo = $gDayNo - 79;
1019 $jNp = floor( $jDayNo / 12053 );
1022 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1025 if ( $jDayNo >= 366 ) {
1026 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1027 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1030 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1031 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1037 return array( $jy, $jm, $jd );
1041 * Converting Gregorian dates to Hijri dates.
1043 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1045 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1047 private static function tsToHijri( $ts ) {
1048 $year = substr( $ts, 0, 4 );
1049 $month = substr( $ts, 4, 2 );
1050 $day = substr( $ts, 6, 2 );
1058 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1059 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1062 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1063 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1064 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1067 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1068 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1071 $zl = $zjd -1948440 +
10632;
1072 $zn = (int)( ( $zl - 1 ) / 10631 );
1073 $zl = $zl - 10631 * $zn +
354;
1074 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1075 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1076 $zm = (int)( ( 24 * $zl ) / 709 );
1077 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1078 $zy = 30 * $zn +
$zj - 30;
1080 return array( $zy, $zm, $zd );
1084 * Converting Gregorian dates to Hebrew dates.
1086 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1087 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1088 * to translate the relevant functions into PHP and release them under
1091 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1092 * and Adar II is 14. In a non-leap year, Adar is 6.
1094 private static function tsToHebrew( $ts ) {
1096 $year = substr( $ts, 0, 4 );
1097 $month = substr( $ts, 4, 2 );
1098 $day = substr( $ts, 6, 2 );
1100 # Calculate Hebrew year
1101 $hebrewYear = $year +
3760;
1103 # Month number when September = 1, August = 12
1105 if ( $month > 12 ) {
1112 # Calculate day of year from 1 September
1114 for ( $i = 1; $i < $month; $i++
) {
1118 # Check if the year is leap
1119 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1122 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1129 # Calculate the start of the Hebrew year
1130 $start = self
::hebrewYearStart( $hebrewYear );
1132 # Calculate next year's start
1133 if ( $dayOfYear <= $start ) {
1134 # Day is before the start of the year - it is the previous year
1136 $nextStart = $start;
1140 # Add days since previous year's 1 September
1142 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1146 # Start of the new (previous) year
1147 $start = self
::hebrewYearStart( $hebrewYear );
1150 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1153 # Calculate Hebrew day of year
1154 $hebrewDayOfYear = $dayOfYear - $start;
1156 # Difference between year's days
1157 $diff = $nextStart - $start;
1158 # Add 12 (or 13 for leap years) days to ignore the difference between
1159 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1160 # difference is only about the year type
1161 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1167 # Check the year pattern, and is leap year
1168 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1169 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1170 # and non-leap years
1171 $yearPattern = $diff %
30;
1172 # Check if leap year
1173 $isLeap = $diff >= 30;
1175 # Calculate day in the month from number of day in the Hebrew year
1176 # Don't check Adar - if the day is not in Adar, we will stop before;
1177 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1178 $hebrewDay = $hebrewDayOfYear;
1181 while ( $hebrewMonth <= 12 ) {
1182 # Calculate days in this month
1183 if ( $isLeap && $hebrewMonth == 6 ) {
1184 # Adar in a leap year
1186 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1188 if ( $hebrewDay <= $days ) {
1192 # Subtract the days of Adar I
1193 $hebrewDay -= $days;
1196 if ( $hebrewDay <= $days ) {
1202 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1203 # Cheshvan in a complete year (otherwise as the rule below)
1205 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1206 # Kislev in an incomplete year (otherwise as the rule below)
1209 # Odd months have 30 days, even have 29
1210 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1212 if ( $hebrewDay <= $days ) {
1213 # In the current month
1216 # Subtract the days of the current month
1217 $hebrewDay -= $days;
1218 # Try in the next month
1223 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1227 * This calculates the Hebrew year start, as days since 1 September.
1228 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1229 * Used for Hebrew date.
1231 private static function hebrewYearStart( $year ) {
1232 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1233 $b = intval( ( $year - 1 ) %
4 );
1234 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1238 $Mar = intval( $m );
1244 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1245 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1247 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1249 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1253 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1258 * Algorithm to convert Gregorian dates to Thai solar dates,
1259 * Minguo dates or Minguo dates.
1261 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1262 * http://en.wikipedia.org/wiki/Minguo_calendar
1263 * http://en.wikipedia.org/wiki/Japanese_era_name
1265 * @param $ts String: 14-character timestamp
1266 * @param $cName String: calender name
1267 * @return Array: converted year, month, day
1269 private static function tsToYear( $ts, $cName ) {
1270 $gy = substr( $ts, 0, 4 );
1271 $gm = substr( $ts, 4, 2 );
1272 $gd = substr( $ts, 6, 2 );
1274 if ( !strcmp( $cName, 'thai' ) ) {
1276 # Add 543 years to the Gregorian calendar
1277 # Months and days are identical
1278 $gy_offset = $gy +
543;
1279 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1281 # Deduct 1911 years from the Gregorian calendar
1282 # Months and days are identical
1283 $gy_offset = $gy - 1911;
1284 } else if ( !strcmp( $cName, 'tenno' ) ) {
1285 # Nengō dates up to Meiji period
1286 # Deduct years from the Gregorian calendar
1287 # depending on the nengo periods
1288 # Months and days are identical
1289 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1291 $gy_gannen = $gy - 1868 +
1;
1292 $gy_offset = $gy_gannen;
1293 if ( $gy_gannen == 1 ) {
1296 $gy_offset = '明治' . $gy_offset;
1298 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1299 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1300 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1301 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1302 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1306 $gy_gannen = $gy - 1912 +
1;
1307 $gy_offset = $gy_gannen;
1308 if ( $gy_gannen == 1 ) {
1311 $gy_offset = '大正' . $gy_offset;
1313 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1314 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1315 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1319 $gy_gannen = $gy - 1926 +
1;
1320 $gy_offset = $gy_gannen;
1321 if ( $gy_gannen == 1 ) {
1324 $gy_offset = '昭和' . $gy_offset;
1327 $gy_gannen = $gy - 1989 +
1;
1328 $gy_offset = $gy_gannen;
1329 if ( $gy_gannen == 1 ) {
1332 $gy_offset = '平成' . $gy_offset;
1338 return array( $gy_offset, $gm, $gd );
1342 * Roman number formatting up to 3000
1344 static function romanNumeral( $num ) {
1345 static $table = array(
1346 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1347 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1348 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1349 array( '', 'M', 'MM', 'MMM' )
1352 $num = intval( $num );
1353 if ( $num > 3000 ||
$num <= 0 ) {
1358 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1359 if ( $num >= $pow10 ) {
1360 $s .= $table[$i][floor( $num / $pow10 )];
1362 $num = $num %
$pow10;
1368 * Hebrew Gematria number formatting up to 9999
1370 static function hebrewNumeral( $num ) {
1371 static $table = array(
1372 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1373 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1374 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1375 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1378 $num = intval( $num );
1379 if ( $num > 9999 ||
$num <= 0 ) {
1384 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1385 if ( $num >= $pow10 ) {
1386 if ( $num == 15 ||
$num == 16 ) {
1387 $s .= $table[0][9] . $table[0][$num - 9];
1390 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1391 if ( $pow10 == 1000 ) {
1396 $num = $num %
$pow10;
1398 if ( strlen( $s ) == 2 ) {
1401 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1402 $str .= substr( $s, strlen( $s ) - 2, 2 );
1404 $start = substr( $str, 0, strlen( $str ) - 2 );
1405 $end = substr( $str, strlen( $str ) - 2 );
1408 $str = $start . 'ך';
1411 $str = $start . 'ם';
1414 $str = $start . 'ן';
1417 $str = $start . 'ף';
1420 $str = $start . 'ץ';
1427 * This is meant to be used by time(), date(), and timeanddate() to get
1428 * the date preference they're supposed to use, it should be used in
1432 * function timeanddate([...], $format = true) {
1433 * $datePreference = $this->dateFormat($format);
1438 * @param $usePrefs Mixed: if true, the user's preference is used
1439 * if false, the site/language default is used
1440 * if int/string, assumed to be a format.
1443 function dateFormat( $usePrefs = true ) {
1446 if ( is_bool( $usePrefs ) ) {
1448 $datePreference = $wgUser->getDatePreference();
1450 $datePreference = (string)User
::getDefaultOption( 'date' );
1453 $datePreference = (string)$usePrefs;
1457 if ( $datePreference == '' ) {
1461 return $datePreference;
1465 * Get a format string for a given type and preference
1466 * @param $type May be date, time or both
1467 * @param $pref The format name as it appears in Messages*.php
1469 function getDateFormatString( $type, $pref ) {
1470 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1471 if ( $pref == 'default' ) {
1472 $pref = $this->getDefaultDateFormat();
1473 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1475 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1476 if ( is_null( $df ) ) {
1477 $pref = $this->getDefaultDateFormat();
1478 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1481 $this->dateFormatStrings
[$type][$pref] = $df;
1483 return $this->dateFormatStrings
[$type][$pref];
1487 * @param $ts Mixed: the time format which needs to be turned into a
1488 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1489 * @param $adj Bool: whether to adjust the time output according to the
1490 * user configured offset ($timecorrection)
1491 * @param $format Mixed: true to use user's date format preference
1492 * @param $timecorrection String: the time offset as returned by
1493 * validateTimeZone() in Special:Preferences
1496 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1498 $ts = $this->userAdjust( $ts, $timecorrection );
1500 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1501 return $this->sprintfDate( $df, $ts );
1505 * @param $ts Mixed: the time format which needs to be turned into a
1506 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1507 * @param $adj Bool: whether to adjust the time output according to the
1508 * user configured offset ($timecorrection)
1509 * @param $format Mixed: true to use user's date format preference
1510 * @param $timecorrection String: the time offset as returned by
1511 * validateTimeZone() in Special:Preferences
1514 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1516 $ts = $this->userAdjust( $ts, $timecorrection );
1518 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1519 return $this->sprintfDate( $df, $ts );
1523 * @param $ts Mixed: the time format which needs to be turned into a
1524 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1525 * @param $adj Bool: whether to adjust the time output according to the
1526 * user configured offset ($timecorrection)
1527 * @param $format Mixed: what format to return, if it's false output the
1528 * default one (default true)
1529 * @param $timecorrection String: the time offset as returned by
1530 * validateTimeZone() in Special:Preferences
1533 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1534 $ts = wfTimestamp( TS_MW
, $ts );
1536 $ts = $this->userAdjust( $ts, $timecorrection );
1538 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1539 return $this->sprintfDate( $df, $ts );
1542 function getMessage( $key ) {
1543 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1546 function getAllMessages() {
1547 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1550 function iconv( $in, $out, $string ) {
1551 # This is a wrapper for iconv in all languages except esperanto,
1552 # which does some nasty x-conversions beforehand
1554 # Even with //IGNORE iconv can whine about illegal characters in
1555 # *input* string. We just ignore those too.
1556 # REF: http://bugs.php.net/bug.php?id=37166
1557 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1558 wfSuppressWarnings();
1559 $text = iconv( $in, $out . '//IGNORE', $string );
1560 wfRestoreWarnings();
1564 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1565 function ucwordbreaksCallbackAscii( $matches ) {
1566 return $this->ucfirst( $matches[1] );
1569 function ucwordbreaksCallbackMB( $matches ) {
1570 return mb_strtoupper( $matches[0] );
1573 function ucCallback( $matches ) {
1574 list( $wikiUpperChars ) = self
::getCaseMaps();
1575 return strtr( $matches[1], $wikiUpperChars );
1578 function lcCallback( $matches ) {
1579 list( , $wikiLowerChars ) = self
::getCaseMaps();
1580 return strtr( $matches[1], $wikiLowerChars );
1583 function ucwordsCallbackMB( $matches ) {
1584 return mb_strtoupper( $matches[0] );
1587 function ucwordsCallbackWiki( $matches ) {
1588 list( $wikiUpperChars ) = self
::getCaseMaps();
1589 return strtr( $matches[0], $wikiUpperChars );
1592 function ucfirst( $str ) {
1596 } elseif ( $o < 128 ) {
1597 return ucfirst( $str );
1599 // fall back to more complex logic in case of multibyte strings
1600 return $this->uc( $str, true );
1604 function uc( $str, $first = false ) {
1605 if ( function_exists( 'mb_strtoupper' ) ) {
1607 if ( $this->isMultibyte( $str ) ) {
1608 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1610 return ucfirst( $str );
1613 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1616 if ( $this->isMultibyte( $str ) ) {
1617 $x = $first ?
'^' : '';
1618 return preg_replace_callback(
1619 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1620 array( $this, 'ucCallback' ),
1624 return $first ?
ucfirst( $str ) : strtoupper( $str );
1629 function lcfirst( $str ) {
1632 return strval( $str );
1633 } elseif ( $o >= 128 ) {
1634 return $this->lc( $str, true );
1635 } elseif ( $o > 96 ) {
1638 $str[0] = strtolower( $str[0] );
1643 function lc( $str, $first = false ) {
1644 if ( function_exists( 'mb_strtolower' ) ) {
1646 if ( $this->isMultibyte( $str ) ) {
1647 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1649 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1652 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1655 if ( $this->isMultibyte( $str ) ) {
1656 $x = $first ?
'^' : '';
1657 return preg_replace_callback(
1658 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1659 array( $this, 'lcCallback' ),
1663 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1668 function isMultibyte( $str ) {
1669 return (bool)preg_match( '/[\x80-\xff]/', $str );
1672 function ucwords( $str ) {
1673 if ( $this->isMultibyte( $str ) ) {
1674 $str = $this->lc( $str );
1676 // regexp to find first letter in each word (i.e. after each space)
1677 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1679 // function to use to capitalize a single char
1680 if ( function_exists( 'mb_strtoupper' ) ) {
1681 return preg_replace_callback(
1683 array( $this, 'ucwordsCallbackMB' ),
1687 return preg_replace_callback(
1689 array( $this, 'ucwordsCallbackWiki' ),
1694 return ucwords( strtolower( $str ) );
1698 # capitalize words at word breaks
1699 function ucwordbreaks( $str ) {
1700 if ( $this->isMultibyte( $str ) ) {
1701 $str = $this->lc( $str );
1703 // since \b doesn't work for UTF-8, we explicitely define word break chars
1704 $breaks = "[ \-\(\)\}\{\.,\?!]";
1706 // find first letter after word break
1707 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1709 if ( function_exists( 'mb_strtoupper' ) ) {
1710 return preg_replace_callback(
1712 array( $this, 'ucwordbreaksCallbackMB' ),
1716 return preg_replace_callback(
1718 array( $this, 'ucwordsCallbackWiki' ),
1723 return preg_replace_callback(
1724 '/\b([\w\x80-\xff]+)\b/',
1725 array( $this, 'ucwordbreaksCallbackAscii' ),
1732 * Return a case-folded representation of $s
1734 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1735 * and $s2 are the same except for the case of their characters. It is not
1736 * necessary for the value returned to make sense when displayed.
1738 * Do *not* perform any other normalisation in this function. If a caller
1739 * uses this function when it should be using a more general normalisation
1740 * function, then fix the caller.
1742 function caseFold( $s ) {
1743 return $this->uc( $s );
1746 function checkTitleEncoding( $s ) {
1747 if ( is_array( $s ) ) {
1748 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1750 # Check for non-UTF-8 URLs
1751 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1756 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1757 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1762 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1765 function fallback8bitEncoding() {
1766 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1770 * Most writing systems use whitespace to break up words.
1771 * Some languages such as Chinese don't conventionally do this,
1772 * which requires special handling when breaking up words for
1775 function hasWordBreaks() {
1780 * Some languages such as Chinese require word segmentation,
1781 * Specify such segmentation when overridden in derived class.
1783 * @param $string String
1786 function segmentByWord( $string ) {
1791 * Some languages have special punctuation need to be normalized.
1792 * Make such changes here.
1794 * @param $string String
1797 function normalizeForSearch( $string ) {
1798 return self
::convertDoubleWidth( $string );
1802 * convert double-width roman characters to single-width.
1803 * range: ff00-ff5f ~= 0020-007f
1805 protected static function convertDoubleWidth( $string ) {
1806 static $full = null;
1807 static $half = null;
1809 if ( $full === null ) {
1810 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1811 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1812 $full = str_split( $fullWidth, 3 );
1813 $half = str_split( $halfWidth );
1816 $string = str_replace( $full, $half, $string );
1820 protected static function insertSpace( $string, $pattern ) {
1821 $string = preg_replace( $pattern, " $1 ", $string );
1822 $string = preg_replace( '/ +/', ' ', $string );
1826 function convertForSearchResult( $termsArray ) {
1827 # some languages, e.g. Chinese, need to do a conversion
1828 # in order for search results to be displayed correctly
1833 * Get the first character of a string.
1838 function firstChar( $s ) {
1841 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1842 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1847 if ( isset( $matches[1] ) ) {
1848 if ( strlen( $matches[1] ) != 3 ) {
1852 // Break down Hangul syllables to grab the first jamo
1853 $code = utf8ToCodepoint( $matches[1] );
1854 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1856 } elseif ( $code < 0xb098 ) {
1857 return "\xe3\x84\xb1";
1858 } elseif ( $code < 0xb2e4 ) {
1859 return "\xe3\x84\xb4";
1860 } elseif ( $code < 0xb77c ) {
1861 return "\xe3\x84\xb7";
1862 } elseif ( $code < 0xb9c8 ) {
1863 return "\xe3\x84\xb9";
1864 } elseif ( $code < 0xbc14 ) {
1865 return "\xe3\x85\x81";
1866 } elseif ( $code < 0xc0ac ) {
1867 return "\xe3\x85\x82";
1868 } elseif ( $code < 0xc544 ) {
1869 return "\xe3\x85\x85";
1870 } elseif ( $code < 0xc790 ) {
1871 return "\xe3\x85\x87";
1872 } elseif ( $code < 0xcc28 ) {
1873 return "\xe3\x85\x88";
1874 } elseif ( $code < 0xce74 ) {
1875 return "\xe3\x85\x8a";
1876 } elseif ( $code < 0xd0c0 ) {
1877 return "\xe3\x85\x8b";
1878 } elseif ( $code < 0xd30c ) {
1879 return "\xe3\x85\x8c";
1880 } elseif ( $code < 0xd558 ) {
1881 return "\xe3\x85\x8d";
1883 return "\xe3\x85\x8e";
1890 function initEncoding() {
1891 # Some languages may have an alternate char encoding option
1892 # (Esperanto X-coding, Japanese furigana conversion, etc)
1893 # If this language is used as the primary content language,
1894 # an override to the defaults can be set here on startup.
1897 function recodeForEdit( $s ) {
1898 # For some languages we'll want to explicitly specify
1899 # which characters make it into the edit box raw
1900 # or are converted in some way or another.
1901 # Note that if wgOutputEncoding is different from
1902 # wgInputEncoding, this text will be further converted
1903 # to wgOutputEncoding.
1904 global $wgEditEncoding;
1905 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1908 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1912 function recodeInput( $s ) {
1913 # Take the previous into account.
1914 global $wgEditEncoding;
1915 if ( $wgEditEncoding != '' ) {
1916 $enc = $wgEditEncoding;
1920 if ( $enc == 'UTF-8' ) {
1923 return $this->iconv( $enc, 'UTF-8', $s );
1928 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1929 * also cleans up certain backwards-compatible sequences, converting them
1930 * to the modern Unicode equivalent.
1932 * This is language-specific for performance reasons only.
1934 function normalize( $s ) {
1935 global $wgAllUnicodeFixes;
1936 $s = UtfNormal
::cleanUp( $s );
1937 if ( $wgAllUnicodeFixes ) {
1938 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1939 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1946 * Transform a string using serialized data stored in the given file (which
1947 * must be in the serialized subdirectory of $IP). The file contains pairs
1948 * mapping source characters to destination characters.
1950 * The data is cached in process memory. This will go faster if you have the
1951 * FastStringSearch extension.
1953 function transformUsingPairFile( $file, $string ) {
1954 if ( !isset( $this->transformData
[$file] ) ) {
1955 $data = wfGetPrecompiledData( $file );
1956 if ( $data === false ) {
1957 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
1959 $this->transformData
[$file] = new ReplacementArray( $data );
1961 return $this->transformData
[$file]->replace( $string );
1965 * For right-to-left language support
1970 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
1974 * Return the correct HTML 'dir' attribute value for this language.
1978 return $this->isRTL() ?
'rtl' : 'ltr';
1982 * Return 'left' or 'right' as appropriate alignment for line-start
1983 * for this language's text direction.
1985 * Should be equivalent to CSS3 'start' text-align value....
1989 function alignStart() {
1990 return $this->isRTL() ?
'right' : 'left';
1994 * Return 'right' or 'left' as appropriate alignment for line-end
1995 * for this language's text direction.
1997 * Should be equivalent to CSS3 'end' text-align value....
2001 function alignEnd() {
2002 return $this->isRTL() ?
'left' : 'right';
2006 * A hidden direction mark (LRM or RLM), depending on the language direction
2010 function getDirMark() {
2011 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2014 function capitalizeAllNouns() {
2015 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2019 * An arrow, depending on the language direction
2023 function getArrow() {
2024 return $this->isRTL() ?
'←' : '→';
2028 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2032 function linkPrefixExtension() {
2033 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2036 function getMagicWords() {
2037 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2040 # Fill a MagicWord object with data from here
2041 function getMagic( $mw ) {
2042 if ( !$this->mMagicHookDone
) {
2043 $this->mMagicHookDone
= true;
2044 wfProfileIn( 'LanguageGetMagic' );
2045 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2046 wfProfileOut( 'LanguageGetMagic' );
2048 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2049 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2051 $magicWords = $this->getMagicWords();
2052 if ( isset( $magicWords[$mw->mId
] ) ) {
2053 $rawEntry = $magicWords[$mw->mId
];
2059 if ( !is_array( $rawEntry ) ) {
2060 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2062 $mw->mCaseSensitive
= $rawEntry[0];
2063 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2068 * Add magic words to the extension array
2070 function addMagicWordsByLang( $newWords ) {
2071 $code = $this->getCode();
2072 $fallbackChain = array();
2073 while ( $code && !in_array( $code, $fallbackChain ) ) {
2074 $fallbackChain[] = $code;
2075 $code = self
::getFallbackFor( $code );
2077 if ( !in_array( 'en', $fallbackChain ) ) {
2078 $fallbackChain[] = 'en';
2080 $fallbackChain = array_reverse( $fallbackChain );
2081 foreach ( $fallbackChain as $code ) {
2082 if ( isset( $newWords[$code] ) ) {
2083 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2089 * Get special page names, as an associative array
2090 * case folded alias => real name
2092 function getSpecialPageAliases() {
2093 // Cache aliases because it may be slow to load them
2094 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2096 $this->mExtendedSpecialPageAliases
=
2097 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2098 wfRunHooks( 'LanguageGetSpecialPageAliases',
2099 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2102 return $this->mExtendedSpecialPageAliases
;
2106 * Italic is unsuitable for some languages
2108 * @param $text String: the text to be emphasized.
2111 function emphasize( $text ) {
2112 return "<em>$text</em>";
2116 * Normally we output all numbers in plain en_US style, that is
2117 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2118 * point twohundredthirtyfive. However this is not sutable for all
2119 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2120 * Icelandic just want to use commas instead of dots, and dots instead
2121 * of commas like "293.291,235".
2123 * An example of this function being called:
2125 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2128 * See LanguageGu.php for the Gujarati implementation and
2129 * $separatorTransformTable on MessageIs.php for
2130 * the , => . and . => , implementation.
2132 * @todo check if it's viable to use localeconv() for the decimal
2134 * @param $number Mixed: the string to be formatted, should be an integer
2135 * or a floating point number.
2136 * @param $nocommafy Bool: set to true for special numbers like dates
2139 function formatNum( $number, $nocommafy = false ) {
2140 global $wgTranslateNumerals;
2141 if ( !$nocommafy ) {
2142 $number = $this->commafy( $number );
2143 $s = $this->separatorTransformTable();
2145 $number = strtr( $number, $s );
2149 if ( $wgTranslateNumerals ) {
2150 $s = $this->digitTransformTable();
2152 $number = strtr( $number, $s );
2159 function parseFormattedNumber( $number ) {
2160 $s = $this->digitTransformTable();
2162 $number = strtr( $number, array_flip( $s ) );
2165 $s = $this->separatorTransformTable();
2167 $number = strtr( $number, array_flip( $s ) );
2170 $number = strtr( $number, array( ',' => '' ) );
2175 * Adds commas to a given number
2180 function commafy( $_ ) {
2181 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2184 function digitTransformTable() {
2185 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2188 function separatorTransformTable() {
2189 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2193 * Take a list of strings and build a locale-friendly comma-separated
2194 * list, using the local comma-separator message.
2195 * The last two strings are chained with an "and".
2200 function listToText( $l ) {
2202 $m = count( $l ) - 1;
2204 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2206 for ( $i = $m; $i >= 0; $i-- ) {
2209 } else if ( $i == $m - 1 ) {
2210 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2212 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2220 * Take a list of strings and build a locale-friendly comma-separated
2221 * list, using the local comma-separator message.
2222 * @param $list array of strings to put in a comma list
2225 function commaList( $list ) {
2230 array( 'parsemag', 'escapenoentities', 'language' => $this )
2236 * Take a list of strings and build a locale-friendly semicolon-separated
2237 * list, using the local semicolon-separator message.
2238 * @param $list array of strings to put in a semicolon list
2241 function semicolonList( $list ) {
2245 'semicolon-separator',
2246 array( 'parsemag', 'escapenoentities', 'language' => $this )
2252 * Same as commaList, but separate it with the pipe instead.
2253 * @param $list array of strings to put in a pipe list
2256 function pipeList( $list ) {
2261 array( 'escapenoentities', 'language' => $this )
2267 * Truncate a string to a specified length in bytes, appending an optional
2268 * string (e.g. for ellipses)
2270 * The database offers limited byte lengths for some columns in the database;
2271 * multi-byte character sets mean we need to ensure that only whole characters
2272 * are included, otherwise broken characters can be passed to the user
2274 * If $length is negative, the string will be truncated from the beginning
2276 * @param $string String to truncate
2277 * @param $length Int: maximum length (excluding ellipses)
2278 * @param $ellipsis String to append to the truncated text
2281 function truncate( $string, $length, $ellipsis = '...' ) {
2282 # Use the localized ellipsis character
2283 if ( $ellipsis == '...' ) {
2284 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2286 # Check if there is no need to truncate
2287 if ( $length == 0 ) {
2289 } elseif ( strlen( $string ) <= abs( $length ) ) {
2292 $stringOriginal = $string;
2293 if ( $length > 0 ) {
2294 $string = substr( $string, 0, $length ); // xyz...
2295 $string = $this->removeBadCharLast( $string );
2296 $string = $string . $ellipsis;
2298 $string = substr( $string, $length ); // ...xyz
2299 $string = $this->removeBadCharFirst( $string );
2300 $string = $ellipsis . $string;
2302 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2303 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2306 return $stringOriginal;
2311 * Remove bytes that represent an incomplete Unicode character
2312 * at the end of string (e.g. bytes of the char are missing)
2314 * @param $string String
2317 protected function removeBadCharLast( $string ) {
2318 $char = ord( $string[strlen( $string ) - 1] );
2320 if ( $char >= 0xc0 ) {
2321 # We got the first byte only of a multibyte char; remove it.
2322 $string = substr( $string, 0, -1 );
2323 } elseif ( $char >= 0x80 &&
2324 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2325 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2327 # We chopped in the middle of a character; remove it
2334 * Remove bytes that represent an incomplete Unicode character
2335 * at the start of string (e.g. bytes of the char are missing)
2337 * @param $string String
2340 protected function removeBadCharFirst( $string ) {
2341 $char = ord( $string[0] );
2342 if ( $char >= 0x80 && $char < 0xc0 ) {
2343 # We chopped in the middle of a character; remove the whole thing
2344 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2350 * Truncate a string of valid HTML to a specified length in bytes,
2351 * appending an optional string (e.g. for ellipses), and return valid HTML
2353 * This is only intended for styled/linked text, such as HTML with
2354 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2356 * Note: tries to fix broken HTML with MWTidy
2358 * @param string $text String to truncate
2359 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2360 * @param string $ellipsis String to append to the truncated text
2363 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2364 # Use the localized ellipsis character
2365 if ( $ellipsis == '...' ) {
2366 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2368 # Check if there is no need to truncate
2369 if ( $length <= 0 ) {
2370 return $ellipsis; // no text shown, nothing to format
2371 } elseif ( strlen( $text ) <= $length ) {
2372 return $text; // string short enough even *with* HTML
2374 $text = MWTidy
::tidy( $text ); // fix tags
2375 $displayLen = 0; // innerHTML legth so far
2376 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2377 $tagType = 0; // 0-open, 1-close
2378 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2379 $entityState = 0; // 0-not entity, 1-entity
2380 $tag = $ret = $ch = '';
2381 $openTags = array();
2382 $textLen = strlen( $text );
2383 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2385 $lastCh = $pos ?
$text[$pos - 1] : '';
2386 $ret .= $ch; // add to result string
2388 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2389 $entityState = 0; // for bad HTML
2390 $bracketState = 1; // tag started (checking for backslash)
2391 } elseif ( $ch == '>' ) {
2392 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2393 $entityState = 0; // for bad HTML
2394 $bracketState = 0; // out of brackets
2395 } elseif ( $bracketState == 1 ) {
2397 $tagType = 1; // close tag (e.g. "</span>")
2399 $tagType = 0; // open tag (e.g. "<span>")
2402 $bracketState = 2; // building tag name
2403 } elseif ( $bracketState == 2 ) {
2407 // Name found (e.g. "<a href=..."), add on tag attributes...
2408 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2410 } elseif ( $bracketState == 0 ) {
2411 if ( $entityState ) {
2414 $displayLen++
; // entity is one displayed char
2418 $entityState = 1; // entity found, (e.g. " ")
2420 $displayLen++
; // this char is displayed
2421 // Add on the other display text after this...
2422 $skipped = $this->truncate_skip(
2423 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2424 $displayLen +
= $skipped;
2429 # Consider truncation once the display length has reached the maximim.
2430 # Double-check that we're not in the middle of a bracket/entity...
2431 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2432 if ( !$testingEllipsis ) {
2433 $testingEllipsis = true;
2434 # Save where we are; we will truncate here unless
2435 # the ellipsis actually makes the string longer.
2436 $pOpenTags = $openTags; // save state
2437 $pRet = $ret; // save state
2438 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2439 # Ellipsis won't make string longer/equal, the truncation point was OK.
2440 $openTags = $pOpenTags; // reload state
2441 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2442 $ret .= $ellipsis; // add ellipsis
2447 if ( $displayLen == 0 ) {
2448 return ''; // no text shown, nothing to format
2450 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags ); // for bad HTML
2451 while ( count( $openTags ) > 0 ) {
2452 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2457 // truncateHtml() helper function
2458 // like strcspn() but adds the skipped chars to $ret
2459 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2461 if ( $start < strlen( $text ) ) {
2462 $skipCount = strcspn( $text, $search, $start, $len );
2463 $ret .= substr( $text, $start, $skipCount );
2468 // truncateHtml() helper function
2469 // (a) push or pop $tag from $openTags as needed
2470 // (b) clear $tag value
2471 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2472 $tag = ltrim( $tag );
2474 if ( $tagType == 0 && $lastCh != '/' ) {
2475 $openTags[] = $tag; // tag opened (didn't close itself)
2476 } else if ( $tagType == 1 ) {
2477 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2478 array_pop( $openTags ); // tag closed
2486 * Grammatical transformations, needed for inflected languages
2487 * Invoked by putting {{grammar:case|word}} in a message
2489 * @param $word string
2490 * @param $case string
2493 function convertGrammar( $word, $case ) {
2494 global $wgGrammarForms;
2495 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2496 return $wgGrammarForms[$this->getCode()][$case][$word];
2502 * Provides an alternative text depending on specified gender.
2503 * Usage {{gender:username|masculine|feminine|neutral}}.
2504 * username is optional, in which case the gender of current user is used,
2505 * but only in (some) interface messages; otherwise default gender is used.
2506 * If second or third parameter are not specified, masculine is used.
2507 * These details may be overriden per language.
2509 function gender( $gender, $forms ) {
2510 if ( !count( $forms ) ) {
2513 $forms = $this->preConvertPlural( $forms, 2 );
2514 if ( $gender === 'male' ) {
2517 if ( $gender === 'female' ) {
2520 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2524 * Plural form transformations, needed for some languages.
2525 * For example, there are 3 form of plural in Russian and Polish,
2526 * depending on "count mod 10". See [[w:Plural]]
2527 * For English it is pretty simple.
2529 * Invoked by putting {{plural:count|wordform1|wordform2}}
2530 * or {{plural:count|wordform1|wordform2|wordform3}}
2532 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2534 * @param $count Integer: non-localized number
2535 * @param $forms Array: different plural forms
2536 * @return string Correct form of plural for $count in this language
2538 function convertPlural( $count, $forms ) {
2539 if ( !count( $forms ) ) {
2542 $forms = $this->preConvertPlural( $forms, 2 );
2544 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2548 * Checks that convertPlural was given an array and pads it to requested
2549 * amound of forms by copying the last one.
2551 * @param $count Integer: How many forms should there be at least
2552 * @param $forms Array of forms given to convertPlural
2553 * @return array Padded array of forms or an exception if not an array
2555 protected function preConvertPlural( /* Array */ $forms, $count ) {
2556 while ( count( $forms ) < $count ) {
2557 $forms[] = $forms[count( $forms ) - 1];
2563 * For translating of expiry times
2564 * @param $str String: the validated block time in English
2565 * @return Somehow translated block time
2566 * @see LanguageFi.php for example implementation
2568 function translateBlockExpiry( $str ) {
2569 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2571 if ( $scBlockExpiryOptions == '-' ) {
2575 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2576 if ( strpos( $option, ':' ) === false ) {
2579 list( $show, $value ) = explode( ':', $option );
2580 if ( strcmp( $str, $value ) == 0 ) {
2581 return htmlspecialchars( trim( $show ) );
2589 * languages like Chinese need to be segmented in order for the diff
2592 * @param $text String
2595 function segmentForDiff( $text ) {
2600 * and unsegment to show the result
2602 * @param $text String
2605 function unsegmentForDiff( $text ) {
2609 # convert text to all supported variants
2610 function autoConvertToAllVariants( $text ) {
2611 return $this->mConverter
->autoConvertToAllVariants( $text );
2614 # convert text to different variants of a language.
2615 function convert( $text ) {
2616 return $this->mConverter
->convert( $text );
2619 # Convert a Title object to a string in the preferred variant
2620 function convertTitle( $title ) {
2621 return $this->mConverter
->convertTitle( $title );
2624 # Check if this is a language with variants
2625 function hasVariants() {
2626 return sizeof( $this->getVariants() ) > 1;
2629 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2630 function armourMath( $text ) {
2631 return $this->mConverter
->armourMath( $text );
2635 * Perform output conversion on a string, and encode for safe HTML output.
2636 * @param $text String text to be converted
2637 * @param $isTitle Bool whether this conversion is for the article title
2639 * @todo this should get integrated somewhere sane
2641 function convertHtml( $text, $isTitle = false ) {
2642 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2645 function convertCategoryKey( $key ) {
2646 return $this->mConverter
->convertCategoryKey( $key );
2650 * Get the list of variants supported by this langauge
2651 * see sample implementation in LanguageZh.php
2653 * @return array an array of language codes
2655 function getVariants() {
2656 return $this->mConverter
->getVariants();
2659 function getPreferredVariant( $fromUser = true, $fromHeader = false ) {
2660 return $this->mConverter
->getPreferredVariant( $fromUser, $fromHeader );
2664 * If a language supports multiple variants, it is
2665 * possible that non-existing link in one variant
2666 * actually exists in another variant. this function
2667 * tries to find it. See e.g. LanguageZh.php
2669 * @param $link String: the name of the link
2670 * @param $nt Mixed: the title object of the link
2671 * @param $ignoreOtherCond Boolean: to disable other conditions when
2672 * we need to transclude a template or update a category's link
2673 * @return null the input parameters may be modified upon return
2675 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2676 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2680 * If a language supports multiple variants, converts text
2681 * into an array of all possible variants of the text:
2682 * 'variant' => text in that variant
2684 function convertLinkToAllVariants( $text ) {
2685 return $this->mConverter
->convertLinkToAllVariants( $text );
2689 * returns language specific options used by User::getPageRenderHash()
2690 * for example, the preferred language variant
2694 function getExtraHashOptions() {
2695 return $this->mConverter
->getExtraHashOptions();
2699 * For languages that support multiple variants, the title of an
2700 * article may be displayed differently in different variants. this
2701 * function returns the apporiate title defined in the body of the article.
2705 function getParsedTitle() {
2706 return $this->mConverter
->getParsedTitle();
2710 * Enclose a string with the "no conversion" tag. This is used by
2711 * various functions in the Parser
2713 * @param $text String: text to be tagged for no conversion
2715 * @return string the tagged text
2717 function markNoConversion( $text, $noParse = false ) {
2718 return $this->mConverter
->markNoConversion( $text, $noParse );
2722 * A regular expression to match legal word-trailing characters
2723 * which should be merged onto a link of the form [[foo]]bar.
2727 function linkTrail() {
2728 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2731 function getLangObj() {
2736 * Get the RFC 3066 code for this language object
2738 function getCode() {
2739 return $this->mCode
;
2742 function setCode( $code ) {
2743 $this->mCode
= $code;
2747 * Get the name of a file for a certain language code
2748 * @param $prefix string Prepend this to the filename
2749 * @param $code string Language code
2750 * @param $suffix string Append this to the filename
2751 * @return string $prefix . $mangledCode . $suffix
2753 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2754 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2758 * Get the language code from a file name. Inverse of getFileName()
2759 * @param $filename string $prefix . $languageCode . $suffix
2760 * @param $prefix string Prefix before the language code
2761 * @param $suffix string Suffix after the language code
2762 * @return Language code, or false if $prefix or $suffix isn't found
2764 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2766 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2767 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2768 if ( !count( $m ) ) {
2771 return str_replace( '_', '-', strtolower( $m[1] ) );
2774 static function getMessagesFileName( $code ) {
2776 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2779 static function getClassFileName( $code ) {
2781 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2785 * Get the fallback for a given language
2787 static function getFallbackFor( $code ) {
2788 if ( $code === 'en' ) {
2792 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2797 * Get all messages for a given language
2798 * WARNING: this may take a long time
2800 static function getMessagesFor( $code ) {
2801 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2805 * Get a message for a given language
2807 static function getMessageFor( $key, $code ) {
2808 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2811 function fixVariableInNamespace( $talk ) {
2812 if ( strpos( $talk, '$1' ) === false ) {
2816 global $wgMetaNamespace;
2817 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2819 # Allow grammar transformations
2820 # Allowing full message-style parsing would make simple requests
2821 # such as action=raw much more expensive than they need to be.
2822 # This will hopefully cover most cases.
2823 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2824 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2825 return str_replace( ' ', '_', $talk );
2828 function replaceGrammarInNamespace( $m ) {
2829 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2832 static function getCaseMaps() {
2833 static $wikiUpperChars, $wikiLowerChars;
2834 if ( isset( $wikiUpperChars ) ) {
2835 return array( $wikiUpperChars, $wikiLowerChars );
2838 wfProfileIn( __METHOD__
);
2839 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2840 if ( $arr === false ) {
2841 throw new MWException(
2842 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2845 wfProfileOut( __METHOD__
);
2846 return array( $wikiUpperChars, $wikiLowerChars );
2849 function formatTimePeriod( $seconds ) {
2850 if ( $seconds < 10 ) {
2851 return $this->formatNum( sprintf( "%.1f", $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2852 } elseif ( $seconds < 60 ) {
2853 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2854 } elseif ( $seconds < 3600 ) {
2855 $minutes = floor( $seconds / 60 );
2856 $secondsPart = round( fmod( $seconds, 60 ) );
2857 if ( $secondsPart == 60 ) {
2861 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2862 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2864 $hours = floor( $seconds / 3600 );
2865 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2866 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2867 if ( $secondsPart == 60 ) {
2871 if ( $minutes == 60 ) {
2875 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2876 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2877 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2881 function formatBitrate( $bps ) {
2882 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2884 return $this->formatNum( $bps ) . $units[0];
2886 $unitIndex = floor( log10( $bps ) / 3 );
2887 $mantissa = $bps / pow( 1000, $unitIndex );
2888 if ( $mantissa < 10 ) {
2889 $mantissa = round( $mantissa, 1 );
2891 $mantissa = round( $mantissa );
2893 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2897 * Format a size in bytes for output, using an appropriate
2898 * unit (B, KB, MB or GB) according to the magnitude in question
2900 * @param $size Size to format
2901 * @return string Plain text (not HTML)
2903 function formatSize( $size ) {
2904 // For small sizes no decimal places necessary
2906 if ( $size > 1024 ) {
2907 $size = $size / 1024;
2908 if ( $size > 1024 ) {
2909 $size = $size / 1024;
2910 // For MB and bigger two decimal places are smarter
2912 if ( $size > 1024 ) {
2913 $size = $size / 1024;
2914 $msg = 'size-gigabytes';
2916 $msg = 'size-megabytes';
2919 $msg = 'size-kilobytes';
2922 $msg = 'size-bytes';
2924 $size = round( $size, $round );
2925 $text = $this->getMessageFromDB( $msg );
2926 return str_replace( '$1', $this->formatNum( $size ), $text );
2930 * Get the conversion rule title, if any.
2932 function getConvRuleTitle() {
2933 return $this->mConverter
->getConvRuleTitle();
2937 * Given a string, convert it to a (hopefully short) key that can be used
2938 * for efficient sorting. A binary sort according to the sortkeys
2939 * corresponds to a logical sort of the corresponding strings. Current
2940 * code expects that a null character should sort before all others, but
2941 * has no other particular expectations (and that one can be changed if
2944 * @param string $string UTF-8 string
2945 * @return string Binary sortkey
2947 public function convertToSortkey( $string ) {
2948 # Fake function for now
2949 return strtoupper( $string );
2953 * Does it make sense for lists to be split up into sections based on their
2954 * first letter? Logogram-based scripts probably want to return false.
2956 * TODO: Use this in CategoryPage.php.
2960 public function usesFirstLettersInLists() {
2965 * Given a string, return the logical "first letter" to be used for
2966 * grouping on category pages and so on. This has to be coordinated
2967 * carefully with convertToSortkey(), or else the sorted list might jump
2968 * back and forth between the same "initial letters" or other pathological
2969 * behavior. For instance, if you just return the first character, but "a"
2970 * sorts the same as "A" based on convertToSortkey(), then you might get a
2982 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2983 * Obviously, this is ignored if usesFirstLettersInLists() is false.
2985 * @param string $string UTF-8 string
2986 * @return string UTF-8 string corresponding to the first letter of input
2988 public function firstLetterForLists( $string ) {
2989 if ( $string[0] == "\0" ) {
2990 $string = substr( $string, 1 );
2992 return strtoupper( $this->firstChar( $string ) );