3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 global $wgInputEncoding, $wgOutputEncoding;
25 * These are always UTF-8, they exist only for backwards compatibility
27 $wgInputEncoding = 'UTF-8';
28 $wgOutputEncoding = 'UTF-8';
30 if ( function_exists( 'mb_strtoupper' ) ) {
31 mb_internal_encoding( 'UTF-8' );
35 * a fake language converter
41 function __construct( $langobj ) { $this->mLang
= $langobj; }
42 function autoConvertToAllVariants( $text ) { return array( $this->mLang
->getCode() => $text ); }
43 function convert( $t ) { return $t; }
44 function convertTitle( $t ) { return $t->getPrefixedText(); }
45 function getVariants() { return array( $this->mLang
->getCode() ); }
46 function getPreferredVariant() { return $this->mLang
->getCode(); }
47 function getDefaultVariant() { return $this->mLang
->getCode(); }
48 function getURLVariant() { return ''; }
49 function getConvRuleTitle() { return false; }
50 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
51 function getExtraHashOptions() { return ''; }
52 function getParsedTitle() { return ''; }
53 function markNoConversion( $text, $noParse = false ) { return $text; }
54 function convertCategoryKey( $key ) { return $key; }
55 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
56 function armourMath( $text ) { return $text; }
60 * Internationalisation code
64 var $mConverter, $mVariants, $mCode, $mLoaded = false;
65 var $mMagicExtensions = array(), $mMagicHookDone = false;
67 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
68 var $dateFormatStrings = array();
69 var $mExtendedSpecialPageAliases;
72 * ReplacementArray object caches
74 var $transformData = array();
76 static public $dataCache;
77 static public $mLangObjCache = array();
79 static public $mWeekdayMsgs = array(
80 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
84 static public $mWeekdayAbbrevMsgs = array(
85 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
88 static public $mMonthMsgs = array(
89 'january', 'february', 'march', 'april', 'may_long', 'june',
90 'july', 'august', 'september', 'october', 'november',
93 static public $mMonthGenMsgs = array(
94 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
95 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
98 static public $mMonthAbbrevMsgs = array(
99 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
100 'sep', 'oct', 'nov', 'dec'
103 static public $mIranianCalendarMonthMsgs = array(
104 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
105 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
106 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
107 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
110 static public $mHebrewCalendarMonthMsgs = array(
111 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
112 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
113 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
114 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
115 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
118 static public $mHebrewCalendarMonthGenMsgs = array(
119 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
120 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
121 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
122 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
123 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
126 static public $mHijriCalendarMonthMsgs = array(
127 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
128 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
129 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
130 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
134 * Get a cached language object for a given language code
135 * @param $code String
138 static function factory( $code ) {
139 if ( !isset( self
::$mLangObjCache[$code] ) ) {
140 if ( count( self
::$mLangObjCache ) > 10 ) {
141 // Don't keep a billion objects around, that's stupid.
142 self
::$mLangObjCache = array();
144 self
::$mLangObjCache[$code] = self
::newFromCode( $code );
146 return self
::$mLangObjCache[$code];
150 * Create a language object for a given language code
151 * @param $code String
154 protected static function newFromCode( $code ) {
156 static $recursionLevel = 0;
158 // Protect against path traversal below
159 if ( !Language
::isValidCode( $code ) ) {
160 throw new MWException( "Invalid language code \"$code\"" );
163 if ( $code == 'en' ) {
166 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
167 // Preload base classes to work around APC/PHP5 bug
168 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
169 include_once( "$IP/languages/classes/$class.deps.php" );
171 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
172 include_once( "$IP/languages/classes/$class.php" );
176 if ( $recursionLevel > 5 ) {
177 throw new MWException( "Language fallback loop detected when creating class $class\n" );
180 if ( !class_exists( $class ) ) {
181 $fallback = Language
::getFallbackFor( $code );
183 $lang = Language
::newFromCode( $fallback );
185 $lang->setCode( $code );
193 * Returns true if a language code string is of a valid form, whether or
196 public static function isValidCode( $code ) {
197 return strcspn( $code, "/\\\000" ) === strlen( $code );
201 * Get the LocalisationCache instance
203 public static function getLocalisationCache() {
204 if ( is_null( self
::$dataCache ) ) {
205 global $wgLocalisationCacheConf;
206 $class = $wgLocalisationCacheConf['class'];
207 self
::$dataCache = new $class( $wgLocalisationCacheConf );
209 return self
::$dataCache;
212 function __construct() {
213 $this->mConverter
= new FakeConverter( $this );
214 // Set the code to the name of the descendant
215 if ( get_class( $this ) == 'Language' ) {
218 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
220 self
::getLocalisationCache();
224 * Reduce memory usage
226 function __destruct() {
227 foreach ( $this as $name => $value ) {
228 unset( $this->$name );
233 * Hook which will be called if this is the content language.
234 * Descendants can use this to register hook functions or modify globals
236 function initContLang() { }
239 * @deprecated Use User::getDefaultOptions()
242 function getDefaultUserOptions() {
243 wfDeprecated( __METHOD__
);
244 return User
::getDefaultOptions();
247 function getFallbackLanguageCode() {
248 if ( $this->mCode
=== 'en' ) {
251 return self
::$dataCache->getItem( $this->mCode
, 'fallback' );
256 * Exports $wgBookstoreListEn
259 function getBookstoreList() {
260 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
266 function getNamespaces() {
267 if ( is_null( $this->namespaceNames
) ) {
268 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
270 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
271 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
273 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
275 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
276 if ( $wgMetaNamespaceTalk ) {
277 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
279 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
280 $this->namespaceNames
[NS_PROJECT_TALK
] =
281 $this->fixVariableInNamespace( $talk );
284 # Sometimes a language will be localised but not actually exist on this wiki.
285 foreach( $this->namespaceNames
as $key => $text ) {
286 if ( !isset( $validNamespaces[$key] ) ) {
287 unset( $this->namespaceNames
[$key] );
291 # The above mixing may leave namespaces out of canonical order.
292 # Re-order by namespace ID number...
293 ksort( $this->namespaceNames
);
295 return $this->namespaceNames
;
299 * A convenience function that returns the same thing as
300 * getNamespaces() except with the array values changed to ' '
301 * where it found '_', useful for producing output to be displayed
302 * e.g. in <select> forms.
306 function getFormattedNamespaces() {
307 $ns = $this->getNamespaces();
308 foreach ( $ns as $k => $v ) {
309 $ns[$k] = strtr( $v, '_', ' ' );
315 * Get a namespace value by key
317 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
318 * echo $mw_ns; // prints 'MediaWiki'
321 * @param $index Int: the array key of the namespace to return
322 * @return mixed, string if the namespace value exists, otherwise false
324 function getNsText( $index ) {
325 $ns = $this->getNamespaces();
326 return isset( $ns[$index] ) ?
$ns[$index] : false;
330 * A convenience function that returns the same thing as
331 * getNsText() except with '_' changed to ' ', useful for
336 function getFormattedNsText( $index ) {
337 $ns = $this->getNsText( $index );
338 return strtr( $ns, '_', ' ' );
342 * Get a namespace key by value, case insensitive.
343 * Only matches namespace names for the current language, not the
344 * canonical ones defined in Namespace.php.
346 * @param $text String
347 * @return mixed An integer if $text is a valid value otherwise false
349 function getLocalNsIndex( $text ) {
350 $lctext = $this->lc( $text );
351 $ids = $this->getNamespaceIds();
352 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
355 function getNamespaceAliases() {
356 if ( is_null( $this->namespaceAliases
) ) {
357 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
361 foreach ( $aliases as $name => $index ) {
362 if ( $index === NS_PROJECT_TALK
) {
363 unset( $aliases[$name] );
364 $name = $this->fixVariableInNamespace( $name );
365 $aliases[$name] = $index;
369 $this->namespaceAliases
= $aliases;
371 return $this->namespaceAliases
;
374 function getNamespaceIds() {
375 if ( is_null( $this->mNamespaceIds
) ) {
376 global $wgNamespaceAliases;
377 # Put namespace names and aliases into a hashtable.
378 # If this is too slow, then we should arrange it so that it is done
379 # before caching. The catch is that at pre-cache time, the above
380 # class-specific fixup hasn't been done.
381 $this->mNamespaceIds
= array();
382 foreach ( $this->getNamespaces() as $index => $name ) {
383 $this->mNamespaceIds
[$this->lc( $name )] = $index;
385 foreach ( $this->getNamespaceAliases() as $name => $index ) {
386 $this->mNamespaceIds
[$this->lc( $name )] = $index;
388 if ( $wgNamespaceAliases ) {
389 foreach ( $wgNamespaceAliases as $name => $index ) {
390 $this->mNamespaceIds
[$this->lc( $name )] = $index;
394 return $this->mNamespaceIds
;
399 * Get a namespace key by value, case insensitive. Canonical namespace
400 * names override custom ones defined for the current language.
402 * @param $text String
403 * @return mixed An integer if $text is a valid value otherwise false
405 function getNsIndex( $text ) {
406 $lctext = $this->lc( $text );
407 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
410 $ids = $this->getNamespaceIds();
411 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
415 * short names for language variants used for language conversion links.
417 * @param $code String
420 function getVariantname( $code ) {
421 return $this->getMessageFromDB( "variantname-$code" );
424 function specialPage( $name ) {
425 $aliases = $this->getSpecialPageAliases();
426 if ( isset( $aliases[$name][0] ) ) {
427 $name = $aliases[$name][0];
429 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
432 function getQuickbarSettings() {
434 $this->getMessage( 'qbsettings-none' ),
435 $this->getMessage( 'qbsettings-fixedleft' ),
436 $this->getMessage( 'qbsettings-fixedright' ),
437 $this->getMessage( 'qbsettings-floatingleft' ),
438 $this->getMessage( 'qbsettings-floatingright' )
442 function getMathNames() {
443 return self
::$dataCache->getItem( $this->mCode
, 'mathNames' );
446 function getDatePreferences() {
447 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
450 function getDateFormats() {
451 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
454 function getDefaultDateFormat() {
455 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
456 if ( $df === 'dmy or mdy' ) {
457 global $wgAmericanDates;
458 return $wgAmericanDates ?
'mdy' : 'dmy';
464 function getDatePreferenceMigrationMap() {
465 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
468 function getImageFile( $image ) {
469 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
472 function getDefaultUserOptionOverrides() {
473 return self
::$dataCache->getItem( $this->mCode
, 'defaultUserOptionOverrides' );
476 function getExtraUserToggles() {
477 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
480 function getUserToggle( $tog ) {
481 return $this->getMessageFromDB( "tog-$tog" );
485 * Get language names, indexed by code.
486 * If $customisedOnly is true, only returns codes with a messages file
488 public static function getLanguageNames( $customisedOnly = false ) {
489 global $wgLanguageNames, $wgExtraLanguageNames;
490 $allNames = $wgExtraLanguageNames +
$wgLanguageNames;
491 if ( !$customisedOnly ) {
497 $dir = opendir( "$IP/languages/messages" );
498 while ( false !== ( $file = readdir( $dir ) ) ) {
499 $code = self
::getCodeFromFileName( $file, 'Messages' );
500 if ( $code && isset( $allNames[$code] ) ) {
501 $names[$code] = $allNames[$code];
509 * Get translated language names. This is done on best effort and
510 * by default this is exactly the same as Language::getLanguageNames.
511 * The CLDR extension provides translated names.
512 * @param $code String Language code.
513 * @return Array language code => language name
516 public static function getTranslatedLanguageNames( $code ) {
518 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
520 foreach ( self
::getLanguageNames() as $code => $name ) {
521 if ( !isset( $names[$code] ) ) $names[$code] = $name;
528 * Get a message from the MediaWiki namespace.
530 * @param $msg String: message name
533 function getMessageFromDB( $msg ) {
534 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
537 function getLanguageName( $code ) {
538 $names = self
::getLanguageNames();
539 if ( !array_key_exists( $code, $names ) ) {
542 return $names[$code];
545 function getMonthName( $key ) {
546 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
549 function getMonthNameGen( $key ) {
550 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
553 function getMonthAbbreviation( $key ) {
554 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
557 function getWeekdayName( $key ) {
558 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
561 function getWeekdayAbbreviation( $key ) {
562 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
565 function getIranianCalendarMonthName( $key ) {
566 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
569 function getHebrewCalendarMonthName( $key ) {
570 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
573 function getHebrewCalendarMonthNameGen( $key ) {
574 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
577 function getHijriCalendarMonthName( $key ) {
578 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
582 * Used by date() and time() to adjust the time output.
584 * @param $ts Int the time in date('YmdHis') format
585 * @param $tz Mixed: adjust the time by this amount (default false, mean we
586 * get user timecorrection setting)
589 function userAdjust( $ts, $tz = false ) {
590 global $wgUser, $wgLocalTZoffset;
592 if ( $tz === false ) {
593 $tz = $wgUser->getOption( 'timecorrection' );
596 $data = explode( '|', $tz, 3 );
598 if ( $data[0] == 'ZoneInfo' ) {
599 if ( function_exists( 'timezone_open' ) && @timezone_open
( $data[2] ) !== false ) {
600 $date = date_create( $ts, timezone_open( 'UTC' ) );
601 date_timezone_set( $date, timezone_open( $data[2] ) );
602 $date = date_format( $date, 'YmdHis' );
605 # Unrecognized timezone, default to 'Offset' with the stored offset.
610 if ( $data[0] == 'System' ||
$tz == '' ) {
611 # Global offset in minutes.
612 if ( isset( $wgLocalTZoffset ) ) {
613 $minDiff = $wgLocalTZoffset;
615 } else if ( $data[0] == 'Offset' ) {
616 $minDiff = intval( $data[1] );
618 $data = explode( ':', $tz );
619 if ( count( $data ) == 2 ) {
620 $data[0] = intval( $data[0] );
621 $data[1] = intval( $data[1] );
622 $minDiff = abs( $data[0] ) * 60 +
$data[1];
623 if ( $data[0] < 0 ) {
624 $minDiff = -$minDiff;
627 $minDiff = intval( $data[0] ) * 60;
631 # No difference ? Return time unchanged
632 if ( 0 == $minDiff ) {
636 wfSuppressWarnings(); // E_STRICT system time bitching
637 # Generate an adjusted date; take advantage of the fact that mktime
638 # will normalize out-of-range values so we don't have to split $minDiff
639 # into hours and minutes.
641 (int)substr( $ts, 8, 2 ) ), # Hours
642 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
643 (int)substr( $ts, 12, 2 ), # Seconds
644 (int)substr( $ts, 4, 2 ), # Month
645 (int)substr( $ts, 6, 2 ), # Day
646 (int)substr( $ts, 0, 4 ) ); # Year
648 $date = date( 'YmdHis', $t );
655 * This is a workalike of PHP's date() function, but with better
656 * internationalisation, a reduced set of format characters, and a better
659 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
660 * PHP manual for definitions. There are a number of extensions, which
663 * xn Do not translate digits of the next numeric format character
664 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
665 * xr Use roman numerals for the next numeric format character
666 * xh Use hebrew numerals for the next numeric format character
668 * xg Genitive month name
670 * xij j (day number) in Iranian calendar
671 * xiF F (month name) in Iranian calendar
672 * xin n (month number) in Iranian calendar
673 * xiY Y (full year) in Iranian calendar
675 * xjj j (day number) in Hebrew calendar
676 * xjF F (month name) in Hebrew calendar
677 * xjt t (days in month) in Hebrew calendar
678 * xjx xg (genitive month name) in Hebrew calendar
679 * xjn n (month number) in Hebrew calendar
680 * xjY Y (full year) in Hebrew calendar
682 * xmj j (day number) in Hijri calendar
683 * xmF F (month name) in Hijri calendar
684 * xmn n (month number) in Hijri calendar
685 * xmY Y (full year) in Hijri calendar
687 * xkY Y (full year) in Thai solar calendar. Months and days are
688 * identical to the Gregorian calendar
689 * xoY Y (full year) in Minguo calendar or Juche year.
690 * Months and days are identical to the
692 * xtY Y (full year) in Japanese nengo. Months and days are
693 * identical to the Gregorian calendar
695 * Characters enclosed in double quotes will be considered literal (with
696 * the quotes themselves removed). Unmatched quotes will be considered
697 * literal quotes. Example:
699 * "The month is" F => The month is January
702 * Backslash escaping is also supported.
704 * Input timestamp is assumed to be pre-normalized to the desired local
707 * @param $format String
708 * @param $ts String: 14-character timestamp
711 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
713 function sprintfDate( $format, $ts ) {
726 for ( $p = 0; $p < strlen( $format ); $p++
) {
729 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
730 $code .= $format[++
$p];
733 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
734 $code .= $format[++
$p];
745 $rawToggle = !$rawToggle;
754 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
757 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
758 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
761 $num = substr( $ts, 6, 2 );
764 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
765 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
768 $num = intval( substr( $ts, 6, 2 ) );
772 $iranian = self
::tsToIranian( $ts );
778 $hijri = self
::tsToHijri( $ts );
784 $hebrew = self
::tsToHebrew( $ts );
790 $unix = wfTimestamp( TS_UNIX
, $ts );
792 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
796 $unix = wfTimestamp( TS_UNIX
, $ts );
798 $w = gmdate( 'w', $unix );
803 $unix = wfTimestamp( TS_UNIX
, $ts );
805 $num = gmdate( 'w', $unix );
809 $unix = wfTimestamp( TS_UNIX
, $ts );
811 $num = gmdate( 'z', $unix );
815 $unix = wfTimestamp( TS_UNIX
, $ts );
817 $num = gmdate( 'W', $unix );
820 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
824 $iranian = self
::tsToIranian( $ts );
826 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
830 $hijri = self
::tsToHijri( $ts );
832 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
836 $hebrew = self
::tsToHebrew( $ts );
838 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
841 $num = substr( $ts, 4, 2 );
844 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
847 $num = intval( substr( $ts, 4, 2 ) );
851 $iranian = self
::tsToIranian( $ts );
857 $hijri = self
::tsToHijri ( $ts );
863 $hebrew = self
::tsToHebrew( $ts );
869 $unix = wfTimestamp( TS_UNIX
, $ts );
871 $num = gmdate( 't', $unix );
875 $hebrew = self
::tsToHebrew( $ts );
881 $unix = wfTimestamp( TS_UNIX
, $ts );
883 $num = gmdate( 'L', $unix );
887 $unix = wfTimestamp( TS_UNIX
, $ts );
889 $num = date( 'o', $unix );
892 $num = substr( $ts, 0, 4 );
896 $iranian = self
::tsToIranian( $ts );
902 $hijri = self
::tsToHijri( $ts );
908 $hebrew = self
::tsToHebrew( $ts );
914 $thai = self
::tsToYear( $ts, 'thai' );
920 $minguo = self
::tsToYear( $ts, 'minguo' );
926 $tenno = self
::tsToYear( $ts, 'tenno' );
931 $num = substr( $ts, 2, 2 );
934 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
937 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
940 $h = substr( $ts, 8, 2 );
941 $num = $h %
12 ?
$h %
12 : 12;
944 $num = intval( substr( $ts, 8, 2 ) );
947 $h = substr( $ts, 8, 2 );
948 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
951 $num = substr( $ts, 8, 2 );
954 $num = substr( $ts, 10, 2 );
957 $num = substr( $ts, 12, 2 );
961 $unix = wfTimestamp( TS_UNIX
, $ts );
963 $s .= gmdate( 'c', $unix );
967 $unix = wfTimestamp( TS_UNIX
, $ts );
969 $s .= gmdate( 'r', $unix );
973 $unix = wfTimestamp( TS_UNIX
, $ts );
979 if ( $p < strlen( $format ) - 1 ) {
987 if ( $p < strlen( $format ) - 1 ) {
988 $endQuote = strpos( $format, '"', $p +
1 );
989 if ( $endQuote === false ) {
990 # No terminating quote, assume literal "
993 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
997 # Quote at end of string, assume literal "
1004 if ( $num !== false ) {
1005 if ( $rawToggle ||
$raw ) {
1008 } elseif ( $roman ) {
1009 $s .= self
::romanNumeral( $num );
1011 } elseif ( $hebrewNum ) {
1012 $s .= self
::hebrewNumeral( $num );
1015 $s .= $this->formatNum( $num, true );
1022 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1023 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1025 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1026 * Gregorian dates to Iranian dates. Originally written in C, it
1027 * is released under the terms of GNU Lesser General Public
1028 * License. Conversion to PHP was performed by Niklas Laxström.
1030 * Link: http://www.farsiweb.info/jalali/jalali.c
1032 private static function tsToIranian( $ts ) {
1033 $gy = substr( $ts, 0, 4 ) -1600;
1034 $gm = substr( $ts, 4, 2 ) -1;
1035 $gd = substr( $ts, 6, 2 ) -1;
1037 # Days passed from the beginning (including leap years)
1039 +
floor( ( $gy +
3 ) / 4 )
1040 - floor( ( $gy +
99 ) / 100 )
1041 +
floor( ( $gy +
399 ) / 400 );
1044 // Add days of the past months of this year
1045 for ( $i = 0; $i < $gm; $i++
) {
1046 $gDayNo +
= self
::$GREG_DAYS[$i];
1050 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1054 // Days passed in current month
1057 $jDayNo = $gDayNo - 79;
1059 $jNp = floor( $jDayNo / 12053 );
1062 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1065 if ( $jDayNo >= 366 ) {
1066 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1067 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1070 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1071 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1077 return array( $jy, $jm, $jd );
1081 * Converting Gregorian dates to Hijri dates.
1083 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1085 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1087 private static function tsToHijri( $ts ) {
1088 $year = substr( $ts, 0, 4 );
1089 $month = substr( $ts, 4, 2 );
1090 $day = substr( $ts, 6, 2 );
1098 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1099 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1102 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1103 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1104 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1107 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1108 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1111 $zl = $zjd -1948440 +
10632;
1112 $zn = (int)( ( $zl - 1 ) / 10631 );
1113 $zl = $zl - 10631 * $zn +
354;
1114 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1115 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1116 $zm = (int)( ( 24 * $zl ) / 709 );
1117 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1118 $zy = 30 * $zn +
$zj - 30;
1120 return array( $zy, $zm, $zd );
1124 * Converting Gregorian dates to Hebrew dates.
1126 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1127 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1128 * to translate the relevant functions into PHP and release them under
1131 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1132 * and Adar II is 14. In a non-leap year, Adar is 6.
1134 private static function tsToHebrew( $ts ) {
1136 $year = substr( $ts, 0, 4 );
1137 $month = substr( $ts, 4, 2 );
1138 $day = substr( $ts, 6, 2 );
1140 # Calculate Hebrew year
1141 $hebrewYear = $year +
3760;
1143 # Month number when September = 1, August = 12
1145 if ( $month > 12 ) {
1152 # Calculate day of year from 1 September
1154 for ( $i = 1; $i < $month; $i++
) {
1158 # Check if the year is leap
1159 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1162 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1169 # Calculate the start of the Hebrew year
1170 $start = self
::hebrewYearStart( $hebrewYear );
1172 # Calculate next year's start
1173 if ( $dayOfYear <= $start ) {
1174 # Day is before the start of the year - it is the previous year
1176 $nextStart = $start;
1180 # Add days since previous year's 1 September
1182 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1186 # Start of the new (previous) year
1187 $start = self
::hebrewYearStart( $hebrewYear );
1190 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1193 # Calculate Hebrew day of year
1194 $hebrewDayOfYear = $dayOfYear - $start;
1196 # Difference between year's days
1197 $diff = $nextStart - $start;
1198 # Add 12 (or 13 for leap years) days to ignore the difference between
1199 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1200 # difference is only about the year type
1201 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1207 # Check the year pattern, and is leap year
1208 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1209 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1210 # and non-leap years
1211 $yearPattern = $diff %
30;
1212 # Check if leap year
1213 $isLeap = $diff >= 30;
1215 # Calculate day in the month from number of day in the Hebrew year
1216 # Don't check Adar - if the day is not in Adar, we will stop before;
1217 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1218 $hebrewDay = $hebrewDayOfYear;
1221 while ( $hebrewMonth <= 12 ) {
1222 # Calculate days in this month
1223 if ( $isLeap && $hebrewMonth == 6 ) {
1224 # Adar in a leap year
1226 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1228 if ( $hebrewDay <= $days ) {
1232 # Subtract the days of Adar I
1233 $hebrewDay -= $days;
1236 if ( $hebrewDay <= $days ) {
1242 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1243 # Cheshvan in a complete year (otherwise as the rule below)
1245 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1246 # Kislev in an incomplete year (otherwise as the rule below)
1249 # Odd months have 30 days, even have 29
1250 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1252 if ( $hebrewDay <= $days ) {
1253 # In the current month
1256 # Subtract the days of the current month
1257 $hebrewDay -= $days;
1258 # Try in the next month
1263 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1267 * This calculates the Hebrew year start, as days since 1 September.
1268 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1269 * Used for Hebrew date.
1271 private static function hebrewYearStart( $year ) {
1272 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1273 $b = intval( ( $year - 1 ) %
4 );
1274 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1278 $Mar = intval( $m );
1284 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1285 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1287 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1289 } else if ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1293 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1298 * Algorithm to convert Gregorian dates to Thai solar dates,
1299 * Minguo dates or Minguo dates.
1301 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1302 * http://en.wikipedia.org/wiki/Minguo_calendar
1303 * http://en.wikipedia.org/wiki/Japanese_era_name
1305 * @param $ts String: 14-character timestamp
1306 * @param $cName String: calender name
1307 * @return Array: converted year, month, day
1309 private static function tsToYear( $ts, $cName ) {
1310 $gy = substr( $ts, 0, 4 );
1311 $gm = substr( $ts, 4, 2 );
1312 $gd = substr( $ts, 6, 2 );
1314 if ( !strcmp( $cName, 'thai' ) ) {
1316 # Add 543 years to the Gregorian calendar
1317 # Months and days are identical
1318 $gy_offset = $gy +
543;
1319 } else if ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1321 # Deduct 1911 years from the Gregorian calendar
1322 # Months and days are identical
1323 $gy_offset = $gy - 1911;
1324 } else if ( !strcmp( $cName, 'tenno' ) ) {
1325 # Nengō dates up to Meiji period
1326 # Deduct years from the Gregorian calendar
1327 # depending on the nengo periods
1328 # Months and days are identical
1329 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1331 $gy_gannen = $gy - 1868 +
1;
1332 $gy_offset = $gy_gannen;
1333 if ( $gy_gannen == 1 ) {
1336 $gy_offset = '明治' . $gy_offset;
1338 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1339 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1340 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1341 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1342 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1346 $gy_gannen = $gy - 1912 +
1;
1347 $gy_offset = $gy_gannen;
1348 if ( $gy_gannen == 1 ) {
1351 $gy_offset = '大正' . $gy_offset;
1353 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1354 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1355 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1359 $gy_gannen = $gy - 1926 +
1;
1360 $gy_offset = $gy_gannen;
1361 if ( $gy_gannen == 1 ) {
1364 $gy_offset = '昭和' . $gy_offset;
1367 $gy_gannen = $gy - 1989 +
1;
1368 $gy_offset = $gy_gannen;
1369 if ( $gy_gannen == 1 ) {
1372 $gy_offset = '平成' . $gy_offset;
1378 return array( $gy_offset, $gm, $gd );
1382 * Roman number formatting up to 3000
1384 static function romanNumeral( $num ) {
1385 static $table = array(
1386 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1387 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1388 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1389 array( '', 'M', 'MM', 'MMM' )
1392 $num = intval( $num );
1393 if ( $num > 3000 ||
$num <= 0 ) {
1398 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1399 if ( $num >= $pow10 ) {
1400 $s .= $table[$i][floor( $num / $pow10 )];
1402 $num = $num %
$pow10;
1408 * Hebrew Gematria number formatting up to 9999
1410 static function hebrewNumeral( $num ) {
1411 static $table = array(
1412 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1413 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1414 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1415 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1418 $num = intval( $num );
1419 if ( $num > 9999 ||
$num <= 0 ) {
1424 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1425 if ( $num >= $pow10 ) {
1426 if ( $num == 15 ||
$num == 16 ) {
1427 $s .= $table[0][9] . $table[0][$num - 9];
1430 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1431 if ( $pow10 == 1000 ) {
1436 $num = $num %
$pow10;
1438 if ( strlen( $s ) == 2 ) {
1441 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1442 $str .= substr( $s, strlen( $s ) - 2, 2 );
1444 $start = substr( $str, 0, strlen( $str ) - 2 );
1445 $end = substr( $str, strlen( $str ) - 2 );
1448 $str = $start . 'ך';
1451 $str = $start . 'ם';
1454 $str = $start . 'ן';
1457 $str = $start . 'ף';
1460 $str = $start . 'ץ';
1467 * This is meant to be used by time(), date(), and timeanddate() to get
1468 * the date preference they're supposed to use, it should be used in
1472 * function timeanddate([...], $format = true) {
1473 * $datePreference = $this->dateFormat($format);
1478 * @param $usePrefs Mixed: if true, the user's preference is used
1479 * if false, the site/language default is used
1480 * if int/string, assumed to be a format.
1483 function dateFormat( $usePrefs = true ) {
1486 if ( is_bool( $usePrefs ) ) {
1488 $datePreference = $wgUser->getDatePreference();
1490 $datePreference = (string)User
::getDefaultOption( 'date' );
1493 $datePreference = (string)$usePrefs;
1497 if ( $datePreference == '' ) {
1501 return $datePreference;
1505 * Get a format string for a given type and preference
1506 * @param $type May be date, time or both
1507 * @param $pref The format name as it appears in Messages*.php
1509 function getDateFormatString( $type, $pref ) {
1510 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1511 if ( $pref == 'default' ) {
1512 $pref = $this->getDefaultDateFormat();
1513 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1515 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1516 if ( is_null( $df ) ) {
1517 $pref = $this->getDefaultDateFormat();
1518 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1521 $this->dateFormatStrings
[$type][$pref] = $df;
1523 return $this->dateFormatStrings
[$type][$pref];
1527 * @param $ts Mixed: the time format which needs to be turned into a
1528 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1529 * @param $adj Bool: whether to adjust the time output according to the
1530 * user configured offset ($timecorrection)
1531 * @param $format Mixed: true to use user's date format preference
1532 * @param $timecorrection String: the time offset as returned by
1533 * validateTimeZone() in Special:Preferences
1536 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1537 $ts = wfTimestamp( TS_MW
, $ts );
1539 $ts = $this->userAdjust( $ts, $timecorrection );
1541 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1542 return $this->sprintfDate( $df, $ts );
1546 * @param $ts Mixed: the time format which needs to be turned into a
1547 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1548 * @param $adj Bool: whether to adjust the time output according to the
1549 * user configured offset ($timecorrection)
1550 * @param $format Mixed: true to use user's date format preference
1551 * @param $timecorrection String: the time offset as returned by
1552 * validateTimeZone() in Special:Preferences
1555 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1556 $ts = wfTimestamp( TS_MW
, $ts );
1558 $ts = $this->userAdjust( $ts, $timecorrection );
1560 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1561 return $this->sprintfDate( $df, $ts );
1565 * @param $ts Mixed: the time format which needs to be turned into a
1566 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1567 * @param $adj Bool: whether to adjust the time output according to the
1568 * user configured offset ($timecorrection)
1569 * @param $format Mixed: what format to return, if it's false output the
1570 * default one (default true)
1571 * @param $timecorrection String: the time offset as returned by
1572 * validateTimeZone() in Special:Preferences
1575 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1576 $ts = wfTimestamp( TS_MW
, $ts );
1578 $ts = $this->userAdjust( $ts, $timecorrection );
1580 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1581 return $this->sprintfDate( $df, $ts );
1584 function getMessage( $key ) {
1585 // Don't change getPreferredVariant() to getCode() / mCode, because:
1587 // 1. Some language like Chinese has multiple variant languages. Only
1588 // getPreferredVariant() (in LanguageConverter) could return a
1589 // sub-language which would be more suitable for the user.
1590 // 2. To languages without multiple variants, getPreferredVariant()
1591 // (in FakeConverter) functions exactly same as getCode() / mCode,
1592 // it won't break anything.
1595 return self
::$dataCache->getSubitem( $this->getPreferredVariant(), 'messages', $key );
1598 function getAllMessages() {
1599 return self
::$dataCache->getItem( $this->getPreferredVariant(), 'messages' );
1602 function iconv( $in, $out, $string ) {
1603 # This is a wrapper for iconv in all languages except esperanto,
1604 # which does some nasty x-conversions beforehand
1606 # Even with //IGNORE iconv can whine about illegal characters in
1607 # *input* string. We just ignore those too.
1608 # REF: http://bugs.php.net/bug.php?id=37166
1609 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1610 wfSuppressWarnings();
1611 $text = iconv( $in, $out . '//IGNORE', $string );
1612 wfRestoreWarnings();
1616 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1617 function ucwordbreaksCallbackAscii( $matches ) {
1618 return $this->ucfirst( $matches[1] );
1621 function ucwordbreaksCallbackMB( $matches ) {
1622 return mb_strtoupper( $matches[0] );
1625 function ucCallback( $matches ) {
1626 list( $wikiUpperChars ) = self
::getCaseMaps();
1627 return strtr( $matches[1], $wikiUpperChars );
1630 function lcCallback( $matches ) {
1631 list( , $wikiLowerChars ) = self
::getCaseMaps();
1632 return strtr( $matches[1], $wikiLowerChars );
1635 function ucwordsCallbackMB( $matches ) {
1636 return mb_strtoupper( $matches[0] );
1639 function ucwordsCallbackWiki( $matches ) {
1640 list( $wikiUpperChars ) = self
::getCaseMaps();
1641 return strtr( $matches[0], $wikiUpperChars );
1645 * Make a string's first character uppercase
1647 function ucfirst( $str ) {
1649 if ( $o < 96 ) { // if already uppercase...
1651 } elseif ( $o < 128 ) {
1652 return ucfirst( $str ); // use PHP's ucfirst()
1654 // fall back to more complex logic in case of multibyte strings
1655 return $this->uc( $str, true );
1660 * Convert a string to uppercase
1662 function uc( $str, $first = false ) {
1663 if ( function_exists( 'mb_strtoupper' ) ) {
1665 if ( $this->isMultibyte( $str ) ) {
1666 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1668 return ucfirst( $str );
1671 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1674 if ( $this->isMultibyte( $str ) ) {
1675 $x = $first ?
'^' : '';
1676 return preg_replace_callback(
1677 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1678 array( $this, 'ucCallback' ),
1682 return $first ?
ucfirst( $str ) : strtoupper( $str );
1687 function lcfirst( $str ) {
1690 return strval( $str );
1691 } elseif ( $o >= 128 ) {
1692 return $this->lc( $str, true );
1693 } elseif ( $o > 96 ) {
1696 $str[0] = strtolower( $str[0] );
1701 function lc( $str, $first = false ) {
1702 if ( function_exists( 'mb_strtolower' ) ) {
1704 if ( $this->isMultibyte( $str ) ) {
1705 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1707 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1710 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1713 if ( $this->isMultibyte( $str ) ) {
1714 $x = $first ?
'^' : '';
1715 return preg_replace_callback(
1716 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1717 array( $this, 'lcCallback' ),
1721 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1726 function isMultibyte( $str ) {
1727 return (bool)preg_match( '/[\x80-\xff]/', $str );
1730 function ucwords( $str ) {
1731 if ( $this->isMultibyte( $str ) ) {
1732 $str = $this->lc( $str );
1734 // regexp to find first letter in each word (i.e. after each space)
1735 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1737 // function to use to capitalize a single char
1738 if ( function_exists( 'mb_strtoupper' ) ) {
1739 return preg_replace_callback(
1741 array( $this, 'ucwordsCallbackMB' ),
1745 return preg_replace_callback(
1747 array( $this, 'ucwordsCallbackWiki' ),
1752 return ucwords( strtolower( $str ) );
1756 # capitalize words at word breaks
1757 function ucwordbreaks( $str ) {
1758 if ( $this->isMultibyte( $str ) ) {
1759 $str = $this->lc( $str );
1761 // since \b doesn't work for UTF-8, we explicitely define word break chars
1762 $breaks = "[ \-\(\)\}\{\.,\?!]";
1764 // find first letter after word break
1765 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1767 if ( function_exists( 'mb_strtoupper' ) ) {
1768 return preg_replace_callback(
1770 array( $this, 'ucwordbreaksCallbackMB' ),
1774 return preg_replace_callback(
1776 array( $this, 'ucwordsCallbackWiki' ),
1781 return preg_replace_callback(
1782 '/\b([\w\x80-\xff]+)\b/',
1783 array( $this, 'ucwordbreaksCallbackAscii' ),
1790 * Return a case-folded representation of $s
1792 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1793 * and $s2 are the same except for the case of their characters. It is not
1794 * necessary for the value returned to make sense when displayed.
1796 * Do *not* perform any other normalisation in this function. If a caller
1797 * uses this function when it should be using a more general normalisation
1798 * function, then fix the caller.
1800 function caseFold( $s ) {
1801 return $this->uc( $s );
1804 function checkTitleEncoding( $s ) {
1805 if ( is_array( $s ) ) {
1806 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1808 # Check for non-UTF-8 URLs
1809 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1814 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1815 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1820 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1823 function fallback8bitEncoding() {
1824 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
1828 * Most writing systems use whitespace to break up words.
1829 * Some languages such as Chinese don't conventionally do this,
1830 * which requires special handling when breaking up words for
1833 function hasWordBreaks() {
1838 * Some languages such as Chinese require word segmentation,
1839 * Specify such segmentation when overridden in derived class.
1841 * @param $string String
1844 function segmentByWord( $string ) {
1849 * Some languages have special punctuation need to be normalized.
1850 * Make such changes here.
1852 * @param $string String
1855 function normalizeForSearch( $string ) {
1856 return self
::convertDoubleWidth( $string );
1860 * convert double-width roman characters to single-width.
1861 * range: ff00-ff5f ~= 0020-007f
1863 protected static function convertDoubleWidth( $string ) {
1864 static $full = null;
1865 static $half = null;
1867 if ( $full === null ) {
1868 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1869 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1870 $full = str_split( $fullWidth, 3 );
1871 $half = str_split( $halfWidth );
1874 $string = str_replace( $full, $half, $string );
1878 protected static function insertSpace( $string, $pattern ) {
1879 $string = preg_replace( $pattern, " $1 ", $string );
1880 $string = preg_replace( '/ +/', ' ', $string );
1884 function convertForSearchResult( $termsArray ) {
1885 # some languages, e.g. Chinese, need to do a conversion
1886 # in order for search results to be displayed correctly
1891 * Get the first character of a string.
1896 function firstChar( $s ) {
1899 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1900 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1905 if ( isset( $matches[1] ) ) {
1906 if ( strlen( $matches[1] ) != 3 ) {
1910 // Break down Hangul syllables to grab the first jamo
1911 $code = utf8ToCodepoint( $matches[1] );
1912 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
1914 } elseif ( $code < 0xb098 ) {
1915 return "\xe3\x84\xb1";
1916 } elseif ( $code < 0xb2e4 ) {
1917 return "\xe3\x84\xb4";
1918 } elseif ( $code < 0xb77c ) {
1919 return "\xe3\x84\xb7";
1920 } elseif ( $code < 0xb9c8 ) {
1921 return "\xe3\x84\xb9";
1922 } elseif ( $code < 0xbc14 ) {
1923 return "\xe3\x85\x81";
1924 } elseif ( $code < 0xc0ac ) {
1925 return "\xe3\x85\x82";
1926 } elseif ( $code < 0xc544 ) {
1927 return "\xe3\x85\x85";
1928 } elseif ( $code < 0xc790 ) {
1929 return "\xe3\x85\x87";
1930 } elseif ( $code < 0xcc28 ) {
1931 return "\xe3\x85\x88";
1932 } elseif ( $code < 0xce74 ) {
1933 return "\xe3\x85\x8a";
1934 } elseif ( $code < 0xd0c0 ) {
1935 return "\xe3\x85\x8b";
1936 } elseif ( $code < 0xd30c ) {
1937 return "\xe3\x85\x8c";
1938 } elseif ( $code < 0xd558 ) {
1939 return "\xe3\x85\x8d";
1941 return "\xe3\x85\x8e";
1948 function initEncoding() {
1949 # Some languages may have an alternate char encoding option
1950 # (Esperanto X-coding, Japanese furigana conversion, etc)
1951 # If this language is used as the primary content language,
1952 # an override to the defaults can be set here on startup.
1955 function recodeForEdit( $s ) {
1956 # For some languages we'll want to explicitly specify
1957 # which characters make it into the edit box raw
1958 # or are converted in some way or another.
1959 # Note that if wgOutputEncoding is different from
1960 # wgInputEncoding, this text will be further converted
1961 # to wgOutputEncoding.
1962 global $wgEditEncoding;
1963 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
1966 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1970 function recodeInput( $s ) {
1971 # Take the previous into account.
1972 global $wgEditEncoding;
1973 if ( $wgEditEncoding != '' ) {
1974 $enc = $wgEditEncoding;
1978 if ( $enc == 'UTF-8' ) {
1981 return $this->iconv( $enc, 'UTF-8', $s );
1986 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1987 * also cleans up certain backwards-compatible sequences, converting them
1988 * to the modern Unicode equivalent.
1990 * This is language-specific for performance reasons only.
1992 function normalize( $s ) {
1993 global $wgAllUnicodeFixes;
1994 $s = UtfNormal
::cleanUp( $s );
1995 if ( $wgAllUnicodeFixes ) {
1996 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1997 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2004 * Transform a string using serialized data stored in the given file (which
2005 * must be in the serialized subdirectory of $IP). The file contains pairs
2006 * mapping source characters to destination characters.
2008 * The data is cached in process memory. This will go faster if you have the
2009 * FastStringSearch extension.
2011 function transformUsingPairFile( $file, $string ) {
2012 if ( !isset( $this->transformData
[$file] ) ) {
2013 $data = wfGetPrecompiledData( $file );
2014 if ( $data === false ) {
2015 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2017 $this->transformData
[$file] = new ReplacementArray( $data );
2019 return $this->transformData
[$file]->replace( $string );
2023 * For right-to-left language support
2028 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2032 * Return the correct HTML 'dir' attribute value for this language.
2036 return $this->isRTL() ?
'rtl' : 'ltr';
2040 * Return 'left' or 'right' as appropriate alignment for line-start
2041 * for this language's text direction.
2043 * Should be equivalent to CSS3 'start' text-align value....
2047 function alignStart() {
2048 return $this->isRTL() ?
'right' : 'left';
2052 * Return 'right' or 'left' as appropriate alignment for line-end
2053 * for this language's text direction.
2055 * Should be equivalent to CSS3 'end' text-align value....
2059 function alignEnd() {
2060 return $this->isRTL() ?
'left' : 'right';
2064 * A hidden direction mark (LRM or RLM), depending on the language direction
2068 function getDirMark() {
2069 return $this->isRTL() ?
"\xE2\x80\x8F" : "\xE2\x80\x8E";
2072 function capitalizeAllNouns() {
2073 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2077 * An arrow, depending on the language direction
2081 function getArrow() {
2082 return $this->isRTL() ?
'←' : '→';
2086 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2090 function linkPrefixExtension() {
2091 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2094 function getMagicWords() {
2095 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2098 protected function doMagicHook() {
2099 if ( $this->mMagicHookDone
) {
2102 $this->mMagicHookDone
= true;
2103 wfProfileIn( 'LanguageGetMagic' );
2104 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2105 wfProfileOut( 'LanguageGetMagic' );
2108 # Fill a MagicWord object with data from here
2109 function getMagic( $mw ) {
2110 $this->doMagicHook();
2112 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2113 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2115 $magicWords = $this->getMagicWords();
2116 if ( isset( $magicWords[$mw->mId
] ) ) {
2117 $rawEntry = $magicWords[$mw->mId
];
2123 if ( !is_array( $rawEntry ) ) {
2124 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2126 $mw->mCaseSensitive
= $rawEntry[0];
2127 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2132 * Add magic words to the extension array
2134 function addMagicWordsByLang( $newWords ) {
2135 $code = $this->getCode();
2136 $fallbackChain = array();
2137 while ( $code && !in_array( $code, $fallbackChain ) ) {
2138 $fallbackChain[] = $code;
2139 $code = self
::getFallbackFor( $code );
2141 if ( !in_array( 'en', $fallbackChain ) ) {
2142 $fallbackChain[] = 'en';
2144 $fallbackChain = array_reverse( $fallbackChain );
2145 foreach ( $fallbackChain as $code ) {
2146 if ( isset( $newWords[$code] ) ) {
2147 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2153 * Get special page names, as an associative array
2154 * case folded alias => real name
2156 function getSpecialPageAliases() {
2157 // Cache aliases because it may be slow to load them
2158 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2160 $this->mExtendedSpecialPageAliases
=
2161 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2162 wfRunHooks( 'LanguageGetSpecialPageAliases',
2163 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2166 return $this->mExtendedSpecialPageAliases
;
2170 * Italic is unsuitable for some languages
2172 * @param $text String: the text to be emphasized.
2175 function emphasize( $text ) {
2176 return "<em>$text</em>";
2180 * Normally we output all numbers in plain en_US style, that is
2181 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2182 * point twohundredthirtyfive. However this is not sutable for all
2183 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2184 * Icelandic just want to use commas instead of dots, and dots instead
2185 * of commas like "293.291,235".
2187 * An example of this function being called:
2189 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2192 * See LanguageGu.php for the Gujarati implementation and
2193 * $separatorTransformTable on MessageIs.php for
2194 * the , => . and . => , implementation.
2196 * @todo check if it's viable to use localeconv() for the decimal
2198 * @param $number Mixed: the string to be formatted, should be an integer
2199 * or a floating point number.
2200 * @param $nocommafy Bool: set to true for special numbers like dates
2203 function formatNum( $number, $nocommafy = false ) {
2204 global $wgTranslateNumerals;
2205 if ( !$nocommafy ) {
2206 $number = $this->commafy( $number );
2207 $s = $this->separatorTransformTable();
2209 $number = strtr( $number, $s );
2213 if ( $wgTranslateNumerals ) {
2214 $s = $this->digitTransformTable();
2216 $number = strtr( $number, $s );
2223 function parseFormattedNumber( $number ) {
2224 $s = $this->digitTransformTable();
2226 $number = strtr( $number, array_flip( $s ) );
2229 $s = $this->separatorTransformTable();
2231 $number = strtr( $number, array_flip( $s ) );
2234 $number = strtr( $number, array( ',' => '' ) );
2239 * Adds commas to a given number
2244 function commafy( $_ ) {
2245 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2248 function digitTransformTable() {
2249 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2252 function separatorTransformTable() {
2253 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2257 * Take a list of strings and build a locale-friendly comma-separated
2258 * list, using the local comma-separator message.
2259 * The last two strings are chained with an "and".
2264 function listToText( $l ) {
2266 $m = count( $l ) - 1;
2268 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2270 for ( $i = $m; $i >= 0; $i-- ) {
2273 } else if ( $i == $m - 1 ) {
2274 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2276 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2284 * Take a list of strings and build a locale-friendly comma-separated
2285 * list, using the local comma-separator message.
2286 * @param $list array of strings to put in a comma list
2289 function commaList( $list ) {
2294 array( 'parsemag', 'escapenoentities', 'language' => $this )
2300 * Take a list of strings and build a locale-friendly semicolon-separated
2301 * list, using the local semicolon-separator message.
2302 * @param $list array of strings to put in a semicolon list
2305 function semicolonList( $list ) {
2309 'semicolon-separator',
2310 array( 'parsemag', 'escapenoentities', 'language' => $this )
2316 * Same as commaList, but separate it with the pipe instead.
2317 * @param $list array of strings to put in a pipe list
2320 function pipeList( $list ) {
2325 array( 'escapenoentities', 'language' => $this )
2331 * Truncate a string to a specified length in bytes, appending an optional
2332 * string (e.g. for ellipses)
2334 * The database offers limited byte lengths for some columns in the database;
2335 * multi-byte character sets mean we need to ensure that only whole characters
2336 * are included, otherwise broken characters can be passed to the user
2338 * If $length is negative, the string will be truncated from the beginning
2340 * @param $string String to truncate
2341 * @param $length Int: maximum length (excluding ellipses)
2342 * @param $ellipsis String to append to the truncated text
2345 function truncate( $string, $length, $ellipsis = '...' ) {
2346 # Use the localized ellipsis character
2347 if ( $ellipsis == '...' ) {
2348 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2350 # Check if there is no need to truncate
2351 if ( $length == 0 ) {
2353 } elseif ( strlen( $string ) <= abs( $length ) ) {
2356 $stringOriginal = $string;
2357 if ( $length > 0 ) {
2358 $string = substr( $string, 0, $length ); // xyz...
2359 $string = $this->removeBadCharLast( $string );
2360 $string = $string . $ellipsis;
2362 $string = substr( $string, $length ); // ...xyz
2363 $string = $this->removeBadCharFirst( $string );
2364 $string = $ellipsis . $string;
2366 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2367 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2370 return $stringOriginal;
2375 * Remove bytes that represent an incomplete Unicode character
2376 * at the end of string (e.g. bytes of the char are missing)
2378 * @param $string String
2381 protected function removeBadCharLast( $string ) {
2382 $char = ord( $string[strlen( $string ) - 1] );
2384 if ( $char >= 0xc0 ) {
2385 # We got the first byte only of a multibyte char; remove it.
2386 $string = substr( $string, 0, -1 );
2387 } elseif ( $char >= 0x80 &&
2388 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2389 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2391 # We chopped in the middle of a character; remove it
2398 * Remove bytes that represent an incomplete Unicode character
2399 * at the start of string (e.g. bytes of the char are missing)
2401 * @param $string String
2404 protected function removeBadCharFirst( $string ) {
2405 $char = ord( $string[0] );
2406 if ( $char >= 0x80 && $char < 0xc0 ) {
2407 # We chopped in the middle of a character; remove the whole thing
2408 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2414 * Truncate a string of valid HTML to a specified length in bytes,
2415 * appending an optional string (e.g. for ellipses), and return valid HTML
2417 * This is only intended for styled/linked text, such as HTML with
2418 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2420 * Note: tries to fix broken HTML with MWTidy
2422 * @param string $text HTML string to truncate
2423 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2424 * @param string $ellipsis String to append to the truncated text
2427 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2428 # Use the localized ellipsis character
2429 if ( $ellipsis == '...' ) {
2430 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2432 # Check if there is no need to truncate
2433 if ( $length <= 0 ) {
2434 return $ellipsis; // no text shown, nothing to format
2435 } elseif ( strlen( $text ) <= $length ) {
2436 return $text; // string short enough even *with* HTML
2438 $text = MWTidy
::tidy( $text ); // fix tags
2439 $displayLen = 0; // innerHTML legth so far
2440 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2441 $tagType = 0; // 0-open, 1-close
2442 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2443 $entityState = 0; // 0-not entity, 1-entity
2445 $openTags = array(); // open tag stack
2446 $textLen = strlen( $text );
2447 for ( $pos = 0; $pos < $textLen; ++
$pos ) {
2449 $lastCh = $pos ?
$text[$pos - 1] : '';
2450 $ret .= $ch; // add to result string
2452 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2453 $entityState = 0; // for bad HTML
2454 $bracketState = 1; // tag started (checking for backslash)
2455 } elseif ( $ch == '>' ) {
2456 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2457 $entityState = 0; // for bad HTML
2458 $bracketState = 0; // out of brackets
2459 } elseif ( $bracketState == 1 ) {
2461 $tagType = 1; // close tag (e.g. "</span>")
2463 $tagType = 0; // open tag (e.g. "<span>")
2466 $bracketState = 2; // building tag name
2467 } elseif ( $bracketState == 2 ) {
2471 // Name found (e.g. "<a href=..."), add on tag attributes...
2472 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2474 } elseif ( $bracketState == 0 ) {
2475 if ( $entityState ) {
2478 $displayLen++
; // entity is one displayed char
2482 $entityState = 1; // entity found, (e.g. " ")
2484 $displayLen++
; // this char is displayed
2485 // Add on the other display text after this...
2486 $skipped = $this->truncate_skip(
2487 $ret, $text, "<>&", $pos +
1, $length - $displayLen );
2488 $displayLen +
= $skipped;
2493 # Consider truncation once the display length has reached the maximim.
2494 # Double-check that we're not in the middle of a bracket/entity...
2495 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2496 if ( !$testingEllipsis ) {
2497 $testingEllipsis = true;
2498 # Save where we are; we will truncate here unless
2499 # the ellipsis actually makes the string longer.
2500 $pOpenTags = $openTags; // save state
2501 $pRet = $ret; // save state
2502 } elseif ( $displayLen > ( $length +
strlen( $ellipsis ) ) ) {
2503 # Ellipsis won't make string longer/equal, the truncation point was OK.
2504 $openTags = $pOpenTags; // reload state
2505 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2506 $ret .= $ellipsis; // add ellipsis
2511 if ( $displayLen == 0 ) {
2512 return ''; // no text shown, nothing to format
2514 // Close the last tag if left unclosed by bad HTML
2515 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2516 while ( count( $openTags ) > 0 ) {
2517 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2522 // truncateHtml() helper function
2523 // like strcspn() but adds the skipped chars to $ret
2524 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2526 if ( $start < strlen( $text ) ) {
2527 $skipCount = strcspn( $text, $search, $start, $len );
2528 $ret .= substr( $text, $start, $skipCount );
2534 * truncateHtml() helper function
2535 * (a) push or pop $tag from $openTags as needed
2536 * (b) clear $tag value
2537 * @param String &$tag Current HTML tag name we are looking at
2538 * @param int $tagType (0-open tag, 1-close tag)
2539 * @param char $lastCh Character before the '>' that ended this tag
2540 * @param array &$openTags Open tag stack (not accounting for $tag)
2542 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2543 $tag = ltrim( $tag );
2545 if ( $tagType == 0 && $lastCh != '/' ) {
2546 $openTags[] = $tag; // tag opened (didn't close itself)
2547 } else if ( $tagType == 1 ) {
2548 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2549 array_pop( $openTags ); // tag closed
2557 * Grammatical transformations, needed for inflected languages
2558 * Invoked by putting {{grammar:case|word}} in a message
2560 * @param $word string
2561 * @param $case string
2564 function convertGrammar( $word, $case ) {
2565 global $wgGrammarForms;
2566 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2567 return $wgGrammarForms[$this->getCode()][$case][$word];
2573 * Provides an alternative text depending on specified gender.
2574 * Usage {{gender:username|masculine|feminine|neutral}}.
2575 * username is optional, in which case the gender of current user is used,
2576 * but only in (some) interface messages; otherwise default gender is used.
2577 * If second or third parameter are not specified, masculine is used.
2578 * These details may be overriden per language.
2580 function gender( $gender, $forms ) {
2581 if ( !count( $forms ) ) {
2584 $forms = $this->preConvertPlural( $forms, 2 );
2585 if ( $gender === 'male' ) {
2588 if ( $gender === 'female' ) {
2591 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2595 * Plural form transformations, needed for some languages.
2596 * For example, there are 3 form of plural in Russian and Polish,
2597 * depending on "count mod 10". See [[w:Plural]]
2598 * For English it is pretty simple.
2600 * Invoked by putting {{plural:count|wordform1|wordform2}}
2601 * or {{plural:count|wordform1|wordform2|wordform3}}
2603 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2605 * @param $count Integer: non-localized number
2606 * @param $forms Array: different plural forms
2607 * @return string Correct form of plural for $count in this language
2609 function convertPlural( $count, $forms ) {
2610 if ( !count( $forms ) ) {
2613 $forms = $this->preConvertPlural( $forms, 2 );
2615 return ( $count == 1 ) ?
$forms[0] : $forms[1];
2619 * Checks that convertPlural was given an array and pads it to requested
2620 * amound of forms by copying the last one.
2622 * @param $count Integer: How many forms should there be at least
2623 * @param $forms Array of forms given to convertPlural
2624 * @return array Padded array of forms or an exception if not an array
2626 protected function preConvertPlural( /* Array */ $forms, $count ) {
2627 while ( count( $forms ) < $count ) {
2628 $forms[] = $forms[count( $forms ) - 1];
2634 * For translating of expiry times
2635 * @param $str String: the validated block time in English
2636 * @return Somehow translated block time
2637 * @see LanguageFi.php for example implementation
2639 function translateBlockExpiry( $str ) {
2640 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2642 if ( $scBlockExpiryOptions == '-' ) {
2646 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2647 if ( strpos( $option, ':' ) === false ) {
2650 list( $show, $value ) = explode( ':', $option );
2651 if ( strcmp( $str, $value ) == 0 ) {
2652 return htmlspecialchars( trim( $show ) );
2660 * languages like Chinese need to be segmented in order for the diff
2663 * @param $text String
2666 function segmentForDiff( $text ) {
2671 * and unsegment to show the result
2673 * @param $text String
2676 function unsegmentForDiff( $text ) {
2680 # convert text to all supported variants
2681 function autoConvertToAllVariants( $text ) {
2682 return $this->mConverter
->autoConvertToAllVariants( $text );
2685 # convert text to different variants of a language.
2686 function convert( $text ) {
2687 return $this->mConverter
->convert( $text );
2690 # Convert a Title object to a string in the preferred variant
2691 function convertTitle( $title ) {
2692 return $this->mConverter
->convertTitle( $title );
2695 # Check if this is a language with variants
2696 function hasVariants() {
2697 return sizeof( $this->getVariants() ) > 1;
2700 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2701 function armourMath( $text ) {
2702 return $this->mConverter
->armourMath( $text );
2706 * Perform output conversion on a string, and encode for safe HTML output.
2707 * @param $text String text to be converted
2708 * @param $isTitle Bool whether this conversion is for the article title
2710 * @todo this should get integrated somewhere sane
2712 function convertHtml( $text, $isTitle = false ) {
2713 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2716 function convertCategoryKey( $key ) {
2717 return $this->mConverter
->convertCategoryKey( $key );
2721 * Get the list of variants supported by this language
2722 * see sample implementation in LanguageZh.php
2724 * @return array an array of language codes
2726 function getVariants() {
2727 return $this->mConverter
->getVariants();
2730 function getPreferredVariant() {
2731 return $this->mConverter
->getPreferredVariant();
2734 function getDefaultVariant() {
2735 return $this->mConverter
->getDefaultVariant();
2738 function getURLVariant() {
2739 return $this->mConverter
->getURLVariant();
2743 * If a language supports multiple variants, it is
2744 * possible that non-existing link in one variant
2745 * actually exists in another variant. this function
2746 * tries to find it. See e.g. LanguageZh.php
2748 * @param $link String: the name of the link
2749 * @param $nt Mixed: the title object of the link
2750 * @param $ignoreOtherCond Boolean: to disable other conditions when
2751 * we need to transclude a template or update a category's link
2752 * @return null the input parameters may be modified upon return
2754 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2755 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
2759 * If a language supports multiple variants, converts text
2760 * into an array of all possible variants of the text:
2761 * 'variant' => text in that variant
2763 * @deprecated Use autoConvertToAllVariants()
2765 function convertLinkToAllVariants( $text ) {
2766 return $this->mConverter
->convertLinkToAllVariants( $text );
2770 * returns language specific options used by User::getPageRenderHash()
2771 * for example, the preferred language variant
2775 function getExtraHashOptions() {
2776 return $this->mConverter
->getExtraHashOptions();
2780 * For languages that support multiple variants, the title of an
2781 * article may be displayed differently in different variants. this
2782 * function returns the apporiate title defined in the body of the article.
2786 function getParsedTitle() {
2787 return $this->mConverter
->getParsedTitle();
2791 * Enclose a string with the "no conversion" tag. This is used by
2792 * various functions in the Parser
2794 * @param $text String: text to be tagged for no conversion
2796 * @return string the tagged text
2798 function markNoConversion( $text, $noParse = false ) {
2799 return $this->mConverter
->markNoConversion( $text, $noParse );
2803 * A regular expression to match legal word-trailing characters
2804 * which should be merged onto a link of the form [[foo]]bar.
2808 function linkTrail() {
2809 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
2812 function getLangObj() {
2817 * Get the RFC 3066 code for this language object
2819 function getCode() {
2820 return $this->mCode
;
2823 function setCode( $code ) {
2824 $this->mCode
= $code;
2828 * Get the name of a file for a certain language code
2829 * @param $prefix string Prepend this to the filename
2830 * @param $code string Language code
2831 * @param $suffix string Append this to the filename
2832 * @return string $prefix . $mangledCode . $suffix
2834 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2835 // Protect against path traversal
2836 if ( !Language
::isValidCode( $code ) ) {
2837 throw new MWException( "Invalid language code \"$code\"" );
2840 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2844 * Get the language code from a file name. Inverse of getFileName()
2845 * @param $filename string $prefix . $languageCode . $suffix
2846 * @param $prefix string Prefix before the language code
2847 * @param $suffix string Suffix after the language code
2848 * @return Language code, or false if $prefix or $suffix isn't found
2850 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2852 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2853 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2854 if ( !count( $m ) ) {
2857 return str_replace( '_', '-', strtolower( $m[1] ) );
2860 static function getMessagesFileName( $code ) {
2862 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2865 static function getClassFileName( $code ) {
2867 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2871 * Get the fallback for a given language
2873 static function getFallbackFor( $code ) {
2874 if ( $code === 'en' ) {
2878 return self
::getLocalisationCache()->getItem( $code, 'fallback' );
2883 * Get all messages for a given language
2884 * WARNING: this may take a long time
2886 static function getMessagesFor( $code ) {
2887 return self
::getLocalisationCache()->getItem( $code, 'messages' );
2891 * Get a message for a given language
2893 static function getMessageFor( $key, $code ) {
2894 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2897 function fixVariableInNamespace( $talk ) {
2898 if ( strpos( $talk, '$1' ) === false ) {
2902 global $wgMetaNamespace;
2903 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2905 # Allow grammar transformations
2906 # Allowing full message-style parsing would make simple requests
2907 # such as action=raw much more expensive than they need to be.
2908 # This will hopefully cover most cases.
2909 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2910 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2911 return str_replace( ' ', '_', $talk );
2914 function replaceGrammarInNamespace( $m ) {
2915 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2918 static function getCaseMaps() {
2919 static $wikiUpperChars, $wikiLowerChars;
2920 if ( isset( $wikiUpperChars ) ) {
2921 return array( $wikiUpperChars, $wikiLowerChars );
2924 wfProfileIn( __METHOD__
);
2925 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2926 if ( $arr === false ) {
2927 throw new MWException(
2928 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2930 $wikiUpperChars = $arr['wikiUpperChars'];
2931 $wikiLowerChars = $arr['wikiLowerChars'];
2932 wfProfileOut( __METHOD__
);
2933 return array( $wikiUpperChars, $wikiLowerChars );
2936 function formatTimePeriod( $seconds ) {
2937 if ( round( $seconds * 10 ) < 100 ) {
2938 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2939 } elseif ( round( $seconds ) < 60 ) {
2940 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2941 } elseif ( round( $seconds ) < 3600 ) {
2942 $minutes = floor( $seconds / 60 );
2943 $secondsPart = round( fmod( $seconds, 60 ) );
2944 if ( $secondsPart == 60 ) {
2948 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2949 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2951 $hours = floor( $seconds / 3600 );
2952 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2953 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2954 if ( $secondsPart == 60 ) {
2958 if ( $minutes == 60 ) {
2962 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2963 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2964 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2968 function formatBitrate( $bps ) {
2969 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2971 return $this->formatNum( $bps ) . $units[0];
2973 $unitIndex = floor( log10( $bps ) / 3 );
2974 $mantissa = $bps / pow( 1000, $unitIndex );
2975 if ( $mantissa < 10 ) {
2976 $mantissa = round( $mantissa, 1 );
2978 $mantissa = round( $mantissa );
2980 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2984 * Format a size in bytes for output, using an appropriate
2985 * unit (B, KB, MB or GB) according to the magnitude in question
2987 * @param $size Size to format
2988 * @return string Plain text (not HTML)
2990 function formatSize( $size ) {
2991 // For small sizes no decimal places necessary
2993 if ( $size > 1024 ) {
2994 $size = $size / 1024;
2995 if ( $size > 1024 ) {
2996 $size = $size / 1024;
2997 // For MB and bigger two decimal places are smarter
2999 if ( $size > 1024 ) {
3000 $size = $size / 1024;
3001 $msg = 'size-gigabytes';
3003 $msg = 'size-megabytes';
3006 $msg = 'size-kilobytes';
3009 $msg = 'size-bytes';
3011 $size = round( $size, $round );
3012 $text = $this->getMessageFromDB( $msg );
3013 return str_replace( '$1', $this->formatNum( $size ), $text );
3017 * Get the conversion rule title, if any.
3019 function getConvRuleTitle() {
3020 return $this->mConverter
->getConvRuleTitle();