* Changed OutputPage::$mIsArticle flag to be false by default. A lot of actions don...
[mediawiki.git] / languages / Language.php
blob55a2ee792cb08143b7efe55cf2b6a5a970977151
1 <?php
2 /**
3 * Internationalisation code
5 * @file
6 * @ingroup Language
7 */
9 /**
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
15 exit( 1 );
18 # Read language names
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__ ) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
26 /**
27 * a fake language converter
29 * @ingroup Language
31 class FakeConverter {
32 var $mLang;
33 function __construct( $langobj ) { $this->mLang = $langobj; }
34 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
35 function convert( $t ) { return $t; }
36 function convertTitle( $t ) { return $t->getPrefixedText(); }
37 function getVariants() { return array( $this->mLang->getCode() ); }
38 function getPreferredVariant() { return $this->mLang->getCode(); }
39 function getDefaultVariant() { return $this->mLang->getCode(); }
40 function getURLVariant() { return ''; }
41 function getConvRuleTitle() { return false; }
42 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
43 function getExtraHashOptions() { return ''; }
44 function getParsedTitle() { return ''; }
45 function markNoConversion( $text, $noParse = false ) { return $text; }
46 function convertCategoryKey( $key ) { return $key; }
47 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
48 function armourMath( $text ) { return $text; }
51 /**
52 * Internationalisation code
53 * @ingroup Language
55 class Language {
56 var $mConverter, $mVariants, $mCode, $mLoaded = false;
57 var $mMagicExtensions = array(), $mMagicHookDone = false;
59 var $mNamespaceIds, $namespaceNames, $namespaceAliases;
60 var $dateFormatStrings = array();
61 var $mExtendedSpecialPageAliases;
63 /**
64 * ReplacementArray object caches
66 var $transformData = array();
68 /**
69 * @var LocalisationCache
71 static public $dataCache;
73 static public $mLangObjCache = array();
75 static public $mWeekdayMsgs = array(
76 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
77 'friday', 'saturday'
80 static public $mWeekdayAbbrevMsgs = array(
81 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
84 static public $mMonthMsgs = array(
85 'january', 'february', 'march', 'april', 'may_long', 'june',
86 'july', 'august', 'september', 'october', 'november',
87 'december'
89 static public $mMonthGenMsgs = array(
90 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
91 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
92 'december-gen'
94 static public $mMonthAbbrevMsgs = array(
95 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
96 'sep', 'oct', 'nov', 'dec'
99 static public $mIranianCalendarMonthMsgs = array(
100 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
101 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
102 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
103 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
106 static public $mHebrewCalendarMonthMsgs = array(
107 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
108 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
109 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
110 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
111 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
114 static public $mHebrewCalendarMonthGenMsgs = array(
115 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
116 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
117 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
118 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
119 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
122 static public $mHijriCalendarMonthMsgs = array(
123 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
124 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
125 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
126 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
130 * Get a cached language object for a given language code
131 * @param $code String
132 * @return Language
134 static function factory( $code ) {
135 if ( !isset( self::$mLangObjCache[$code] ) ) {
136 if ( count( self::$mLangObjCache ) > 10 ) {
137 // Don't keep a billion objects around, that's stupid.
138 self::$mLangObjCache = array();
140 self::$mLangObjCache[$code] = self::newFromCode( $code );
142 return self::$mLangObjCache[$code];
146 * Create a language object for a given language code
147 * @param $code String
148 * @return Language
150 protected static function newFromCode( $code ) {
151 global $IP;
152 static $recursionLevel = 0;
154 // Protect against path traversal below
155 if ( !Language::isValidCode( $code )
156 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
158 throw new MWException( "Invalid language code \"$code\"" );
161 if ( !Language::isValidBuiltInCode( $code ) ) {
162 // It's not possible to customise this code with class files, so
163 // just return a Language object. This is to support uselang= hacks.
164 $lang = new Language;
165 $lang->setCode( $code );
166 return $lang;
169 if ( $code == 'en' ) {
170 $class = 'Language';
171 } else {
172 $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
173 if ( !defined( 'MW_COMPILED' ) ) {
174 // Preload base classes to work around APC/PHP5 bug
175 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
176 include_once( "$IP/languages/classes/$class.deps.php" );
178 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
179 include_once( "$IP/languages/classes/$class.php" );
184 if ( $recursionLevel > 5 ) {
185 throw new MWException( "Language fallback loop detected when creating class $class\n" );
188 if ( !MWInit::classExists( $class ) ) {
189 $fallback = Language::getFallbackFor( $code );
190 ++$recursionLevel;
191 $lang = Language::newFromCode( $fallback );
192 --$recursionLevel;
193 $lang->setCode( $code );
194 } else {
195 $lang = new $class;
197 return $lang;
201 * Returns true if a language code string is of a valid form, whether or
202 * not it exists. This includes codes which are used solely for
203 * customisation via the MediaWiki namespace.
205 * @param $code string
207 * @return bool
209 public static function isValidCode( $code ) {
210 return
211 strcspn( $code, ":/\\\000" ) === strlen( $code )
212 && !preg_match( Title::getTitleInvalidRegex(), $code );
216 * Returns true if a language code is of a valid form for the purposes of
217 * internal customisation of MediaWiki, via Messages*.php.
219 * @param $code string
221 * @return bool
223 public static function isValidBuiltInCode( $code ) {
224 return preg_match( '/^[a-z0-9-]*$/i', $code );
228 * Get the LocalisationCache instance
230 * @return LocalisationCache
232 public static function getLocalisationCache() {
233 if ( is_null( self::$dataCache ) ) {
234 global $wgLocalisationCacheConf;
235 $class = $wgLocalisationCacheConf['class'];
236 self::$dataCache = new $class( $wgLocalisationCacheConf );
238 return self::$dataCache;
241 function __construct() {
242 $this->mConverter = new FakeConverter( $this );
243 // Set the code to the name of the descendant
244 if ( get_class( $this ) == 'Language' ) {
245 $this->mCode = 'en';
246 } else {
247 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
249 self::getLocalisationCache();
253 * Reduce memory usage
255 function __destruct() {
256 foreach ( $this as $name => $value ) {
257 unset( $this->$name );
262 * Hook which will be called if this is the content language.
263 * Descendants can use this to register hook functions or modify globals
265 function initContLang() { }
268 * @return array|bool
270 function getFallbackLanguageCode() {
271 if ( $this->mCode === 'en' ) {
272 return false;
273 } else {
274 return self::$dataCache->getItem( $this->mCode, 'fallback' );
279 * Exports $wgBookstoreListEn
280 * @return array
282 function getBookstoreList() {
283 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
287 * @return array
289 function getNamespaces() {
290 if ( is_null( $this->namespaceNames ) ) {
291 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
293 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
294 $validNamespaces = MWNamespace::getCanonicalNamespaces();
296 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
298 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
299 if ( $wgMetaNamespaceTalk ) {
300 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
301 } else {
302 $talk = $this->namespaceNames[NS_PROJECT_TALK];
303 $this->namespaceNames[NS_PROJECT_TALK] =
304 $this->fixVariableInNamespace( $talk );
307 # Sometimes a language will be localised but not actually exist on this wiki.
308 foreach( $this->namespaceNames as $key => $text ) {
309 if ( !isset( $validNamespaces[$key] ) ) {
310 unset( $this->namespaceNames[$key] );
314 # The above mixing may leave namespaces out of canonical order.
315 # Re-order by namespace ID number...
316 ksort( $this->namespaceNames );
318 return $this->namespaceNames;
322 * A convenience function that returns the same thing as
323 * getNamespaces() except with the array values changed to ' '
324 * where it found '_', useful for producing output to be displayed
325 * e.g. in <select> forms.
327 * @return array
329 function getFormattedNamespaces() {
330 $ns = $this->getNamespaces();
331 foreach ( $ns as $k => $v ) {
332 $ns[$k] = strtr( $v, '_', ' ' );
334 return $ns;
338 * Get a namespace value by key
339 * <code>
340 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
341 * echo $mw_ns; // prints 'MediaWiki'
342 * </code>
344 * @param $index Int: the array key of the namespace to return
345 * @return mixed, string if the namespace value exists, otherwise false
347 function getNsText( $index ) {
348 $ns = $this->getNamespaces();
349 return isset( $ns[$index] ) ? $ns[$index] : false;
353 * A convenience function that returns the same thing as
354 * getNsText() except with '_' changed to ' ', useful for
355 * producing output.
357 * @param $index string
359 * @return array
361 function getFormattedNsText( $index ) {
362 $ns = $this->getNsText( $index );
363 return strtr( $ns, '_', ' ' );
367 * Returns gender-dependent namespace alias if available.
368 * @param $index Int: namespace index
369 * @param $gender String: gender key (male, female... )
370 * @return String
371 * @since 1.18
373 function getGenderNsText( $index, $gender ) {
374 $ns = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
375 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
379 * Whether this language makes distinguishes genders for example in
380 * namespaces.
381 * @return bool
382 * @since 1.18
384 function needsGenderDistinction() {
385 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
386 return count( $aliases ) > 0;
390 * Get a namespace key by value, case insensitive.
391 * Only matches namespace names for the current language, not the
392 * canonical ones defined in Namespace.php.
394 * @param $text String
395 * @return mixed An integer if $text is a valid value otherwise false
397 function getLocalNsIndex( $text ) {
398 $lctext = $this->lc( $text );
399 $ids = $this->getNamespaceIds();
400 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
404 * @return array
406 function getNamespaceAliases() {
407 if ( is_null( $this->namespaceAliases ) ) {
408 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
409 if ( !$aliases ) {
410 $aliases = array();
411 } else {
412 foreach ( $aliases as $name => $index ) {
413 if ( $index === NS_PROJECT_TALK ) {
414 unset( $aliases[$name] );
415 $name = $this->fixVariableInNamespace( $name );
416 $aliases[$name] = $index;
421 $genders = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
422 foreach ( $genders as $index => $forms ) {
423 foreach ( $forms as $alias ) {
424 $aliases[$alias] = $index;
428 $this->namespaceAliases = $aliases;
430 return $this->namespaceAliases;
434 * @return array
436 function getNamespaceIds() {
437 if ( is_null( $this->mNamespaceIds ) ) {
438 global $wgNamespaceAliases;
439 # Put namespace names and aliases into a hashtable.
440 # If this is too slow, then we should arrange it so that it is done
441 # before caching. The catch is that at pre-cache time, the above
442 # class-specific fixup hasn't been done.
443 $this->mNamespaceIds = array();
444 foreach ( $this->getNamespaces() as $index => $name ) {
445 $this->mNamespaceIds[$this->lc( $name )] = $index;
447 foreach ( $this->getNamespaceAliases() as $name => $index ) {
448 $this->mNamespaceIds[$this->lc( $name )] = $index;
450 if ( $wgNamespaceAliases ) {
451 foreach ( $wgNamespaceAliases as $name => $index ) {
452 $this->mNamespaceIds[$this->lc( $name )] = $index;
456 return $this->mNamespaceIds;
461 * Get a namespace key by value, case insensitive. Canonical namespace
462 * names override custom ones defined for the current language.
464 * @param $text String
465 * @return mixed An integer if $text is a valid value otherwise false
467 function getNsIndex( $text ) {
468 $lctext = $this->lc( $text );
469 if ( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) {
470 return $ns;
472 $ids = $this->getNamespaceIds();
473 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
477 * short names for language variants used for language conversion links.
479 * @param $code String
480 * @return string
482 function getVariantname( $code ) {
483 return $this->getMessageFromDB( "variantname-$code" );
487 * @param $name string
488 * @return string
490 function specialPage( $name ) {
491 $aliases = $this->getSpecialPageAliases();
492 if ( isset( $aliases[$name][0] ) ) {
493 $name = $aliases[$name][0];
495 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
499 * @return array
501 function getQuickbarSettings() {
502 return array(
503 $this->getMessage( 'qbsettings-none' ),
504 $this->getMessage( 'qbsettings-fixedleft' ),
505 $this->getMessage( 'qbsettings-fixedright' ),
506 $this->getMessage( 'qbsettings-floatingleft' ),
507 $this->getMessage( 'qbsettings-floatingright' ),
508 $this->getMessage( 'qbsettings-directionality' )
513 * @return array
515 function getDatePreferences() {
516 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
520 * @return array
522 function getDateFormats() {
523 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
527 * @return array|string
529 function getDefaultDateFormat() {
530 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
531 if ( $df === 'dmy or mdy' ) {
532 global $wgAmericanDates;
533 return $wgAmericanDates ? 'mdy' : 'dmy';
534 } else {
535 return $df;
540 * @return array
542 function getDatePreferenceMigrationMap() {
543 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
547 * @param $image
548 * @return array|null
550 function getImageFile( $image ) {
551 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
555 * @return array
557 function getExtraUserToggles() {
558 return self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
562 * @param $tog
563 * @return string
565 function getUserToggle( $tog ) {
566 return $this->getMessageFromDB( "tog-$tog" );
570 * Get language names, indexed by code.
571 * If $customisedOnly is true, only returns codes with a messages file
573 * @param $customisedOnly bool
575 * @return array
577 public static function getLanguageNames( $customisedOnly = false ) {
578 global $wgExtraLanguageNames;
579 static $coreLanguageNames;
581 if ( $coreLanguageNames === null ) {
582 include( MWInit::compiledPath( 'languages/Names.php' ) );
585 $allNames = $wgExtraLanguageNames + $coreLanguageNames;
586 if ( !$customisedOnly ) {
587 return $allNames;
590 global $IP;
591 $names = array();
592 $dir = opendir( "$IP/languages/messages" );
593 while ( false !== ( $file = readdir( $dir ) ) ) {
594 $code = self::getCodeFromFileName( $file, 'Messages' );
595 if ( $code && isset( $allNames[$code] ) ) {
596 $names[$code] = $allNames[$code];
599 closedir( $dir );
600 return $names;
604 * Get translated language names. This is done on best effort and
605 * by default this is exactly the same as Language::getLanguageNames.
606 * The CLDR extension provides translated names.
607 * @param $code String Language code.
608 * @return Array language code => language name
609 * @since 1.18.0
611 public static function getTranslatedLanguageNames( $code ) {
612 $names = array();
613 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
615 foreach ( self::getLanguageNames() as $code => $name ) {
616 if ( !isset( $names[$code] ) ) $names[$code] = $name;
619 return $names;
623 * Get a message from the MediaWiki namespace.
625 * @param $msg String: message name
626 * @return string
628 function getMessageFromDB( $msg ) {
629 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
633 * @param $code string
634 * @return string
636 function getLanguageName( $code ) {
637 $names = self::getLanguageNames();
638 if ( !array_key_exists( $code, $names ) ) {
639 return '';
641 return $names[$code];
645 * @param $key string
646 * @return string
648 function getMonthName( $key ) {
649 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
653 * @return array
655 function getMonthNamesArray() {
656 $monthNames = array( '' );
657 for ( $i=1; $i < 13; $i++ ) {
658 $monthNames[] = $this->getMonthName( $i );
660 return $monthNames;
664 * @param $key string
665 * @return string
667 function getMonthNameGen( $key ) {
668 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
672 * @param $key string
673 * @return string
675 function getMonthAbbreviation( $key ) {
676 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
680 * @return array
682 function getMonthAbbreviationsArray() {
683 $monthNames = array( '' );
684 for ( $i=1; $i < 13; $i++ ) {
685 $monthNames[] = $this->getMonthAbbreviation( $i );
687 return $monthNames;
691 * @param $key string
692 * @return string
694 function getWeekdayName( $key ) {
695 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
699 * @param $key string
700 * @return string
702 function getWeekdayAbbreviation( $key ) {
703 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
707 * @param $key string
708 * @return string
710 function getIranianCalendarMonthName( $key ) {
711 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
715 * @param $key string
716 * @return string
718 function getHebrewCalendarMonthName( $key ) {
719 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
723 * @param $key string
724 * @return string
726 function getHebrewCalendarMonthNameGen( $key ) {
727 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
731 * @param $key string
732 * @return string
734 function getHijriCalendarMonthName( $key ) {
735 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
739 * Used by date() and time() to adjust the time output.
741 * @param $ts Int the time in date('YmdHis') format
742 * @param $tz Mixed: adjust the time by this amount (default false, mean we
743 * get user timecorrection setting)
744 * @return int
746 function userAdjust( $ts, $tz = false ) {
747 global $wgUser, $wgLocalTZoffset;
749 if ( $tz === false ) {
750 $tz = $wgUser->getOption( 'timecorrection' );
753 $data = explode( '|', $tz, 3 );
755 if ( $data[0] == 'ZoneInfo' ) {
756 wfSuppressWarnings();
757 $userTZ = timezone_open( $data[2] );
758 wfRestoreWarnings();
759 if ( $userTZ !== false ) {
760 $date = date_create( $ts, timezone_open( 'UTC' ) );
761 date_timezone_set( $date, $userTZ );
762 $date = date_format( $date, 'YmdHis' );
763 return $date;
765 # Unrecognized timezone, default to 'Offset' with the stored offset.
766 $data[0] = 'Offset';
769 $minDiff = 0;
770 if ( $data[0] == 'System' || $tz == '' ) {
771 #  Global offset in minutes.
772 if ( isset( $wgLocalTZoffset ) ) {
773 $minDiff = $wgLocalTZoffset;
775 } elseif ( $data[0] == 'Offset' ) {
776 $minDiff = intval( $data[1] );
777 } else {
778 $data = explode( ':', $tz );
779 if ( count( $data ) == 2 ) {
780 $data[0] = intval( $data[0] );
781 $data[1] = intval( $data[1] );
782 $minDiff = abs( $data[0] ) * 60 + $data[1];
783 if ( $data[0] < 0 ) {
784 $minDiff = -$minDiff;
786 } else {
787 $minDiff = intval( $data[0] ) * 60;
791 # No difference ? Return time unchanged
792 if ( 0 == $minDiff ) {
793 return $ts;
796 wfSuppressWarnings(); // E_STRICT system time bitching
797 # Generate an adjusted date; take advantage of the fact that mktime
798 # will normalize out-of-range values so we don't have to split $minDiff
799 # into hours and minutes.
800 $t = mktime( (
801 (int)substr( $ts, 8, 2 ) ), # Hours
802 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
803 (int)substr( $ts, 12, 2 ), # Seconds
804 (int)substr( $ts, 4, 2 ), # Month
805 (int)substr( $ts, 6, 2 ), # Day
806 (int)substr( $ts, 0, 4 ) ); # Year
808 $date = date( 'YmdHis', $t );
809 wfRestoreWarnings();
811 return $date;
815 * This is a workalike of PHP's date() function, but with better
816 * internationalisation, a reduced set of format characters, and a better
817 * escaping format.
819 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
820 * PHP manual for definitions. There are a number of extensions, which
821 * start with "x":
823 * xn Do not translate digits of the next numeric format character
824 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
825 * xr Use roman numerals for the next numeric format character
826 * xh Use hebrew numerals for the next numeric format character
827 * xx Literal x
828 * xg Genitive month name
830 * xij j (day number) in Iranian calendar
831 * xiF F (month name) in Iranian calendar
832 * xin n (month number) in Iranian calendar
833 * xiY Y (full year) in Iranian calendar
835 * xjj j (day number) in Hebrew calendar
836 * xjF F (month name) in Hebrew calendar
837 * xjt t (days in month) in Hebrew calendar
838 * xjx xg (genitive month name) in Hebrew calendar
839 * xjn n (month number) in Hebrew calendar
840 * xjY Y (full year) in Hebrew calendar
842 * xmj j (day number) in Hijri calendar
843 * xmF F (month name) in Hijri calendar
844 * xmn n (month number) in Hijri calendar
845 * xmY Y (full year) in Hijri calendar
847 * xkY Y (full year) in Thai solar calendar. Months and days are
848 * identical to the Gregorian calendar
849 * xoY Y (full year) in Minguo calendar or Juche year.
850 * Months and days are identical to the
851 * Gregorian calendar
852 * xtY Y (full year) in Japanese nengo. Months and days are
853 * identical to the Gregorian calendar
855 * Characters enclosed in double quotes will be considered literal (with
856 * the quotes themselves removed). Unmatched quotes will be considered
857 * literal quotes. Example:
859 * "The month is" F => The month is January
860 * i's" => 20'11"
862 * Backslash escaping is also supported.
864 * Input timestamp is assumed to be pre-normalized to the desired local
865 * time zone, if any.
867 * @param $format String
868 * @param $ts String: 14-character timestamp
869 * YYYYMMDDHHMMSS
870 * 01234567890123
871 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
873 * @return string
875 function sprintfDate( $format, $ts ) {
876 $s = '';
877 $raw = false;
878 $roman = false;
879 $hebrewNum = false;
880 $unix = false;
881 $rawToggle = false;
882 $iranian = false;
883 $hebrew = false;
884 $hijri = false;
885 $thai = false;
886 $minguo = false;
887 $tenno = false;
888 for ( $p = 0; $p < strlen( $format ); $p++ ) {
889 $num = false;
890 $code = $format[$p];
891 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
892 $code .= $format[++$p];
895 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
896 $code .= $format[++$p];
899 switch ( $code ) {
900 case 'xx':
901 $s .= 'x';
902 break;
903 case 'xn':
904 $raw = true;
905 break;
906 case 'xN':
907 $rawToggle = !$rawToggle;
908 break;
909 case 'xr':
910 $roman = true;
911 break;
912 case 'xh':
913 $hebrewNum = true;
914 break;
915 case 'xg':
916 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
917 break;
918 case 'xjx':
919 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
920 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
921 break;
922 case 'd':
923 $num = substr( $ts, 6, 2 );
924 break;
925 case 'D':
926 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
927 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
928 break;
929 case 'j':
930 $num = intval( substr( $ts, 6, 2 ) );
931 break;
932 case 'xij':
933 if ( !$iranian ) {
934 $iranian = self::tsToIranian( $ts );
936 $num = $iranian[2];
937 break;
938 case 'xmj':
939 if ( !$hijri ) {
940 $hijri = self::tsToHijri( $ts );
942 $num = $hijri[2];
943 break;
944 case 'xjj':
945 if ( !$hebrew ) {
946 $hebrew = self::tsToHebrew( $ts );
948 $num = $hebrew[2];
949 break;
950 case 'l':
951 if ( !$unix ) {
952 $unix = wfTimestamp( TS_UNIX, $ts );
954 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
955 break;
956 case 'N':
957 if ( !$unix ) {
958 $unix = wfTimestamp( TS_UNIX, $ts );
960 $w = gmdate( 'w', $unix );
961 $num = $w ? $w : 7;
962 break;
963 case 'w':
964 if ( !$unix ) {
965 $unix = wfTimestamp( TS_UNIX, $ts );
967 $num = gmdate( 'w', $unix );
968 break;
969 case 'z':
970 if ( !$unix ) {
971 $unix = wfTimestamp( TS_UNIX, $ts );
973 $num = gmdate( 'z', $unix );
974 break;
975 case 'W':
976 if ( !$unix ) {
977 $unix = wfTimestamp( TS_UNIX, $ts );
979 $num = gmdate( 'W', $unix );
980 break;
981 case 'F':
982 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
983 break;
984 case 'xiF':
985 if ( !$iranian ) {
986 $iranian = self::tsToIranian( $ts );
988 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
989 break;
990 case 'xmF':
991 if ( !$hijri ) {
992 $hijri = self::tsToHijri( $ts );
994 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
995 break;
996 case 'xjF':
997 if ( !$hebrew ) {
998 $hebrew = self::tsToHebrew( $ts );
1000 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1001 break;
1002 case 'm':
1003 $num = substr( $ts, 4, 2 );
1004 break;
1005 case 'M':
1006 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1007 break;
1008 case 'n':
1009 $num = intval( substr( $ts, 4, 2 ) );
1010 break;
1011 case 'xin':
1012 if ( !$iranian ) {
1013 $iranian = self::tsToIranian( $ts );
1015 $num = $iranian[1];
1016 break;
1017 case 'xmn':
1018 if ( !$hijri ) {
1019 $hijri = self::tsToHijri ( $ts );
1021 $num = $hijri[1];
1022 break;
1023 case 'xjn':
1024 if ( !$hebrew ) {
1025 $hebrew = self::tsToHebrew( $ts );
1027 $num = $hebrew[1];
1028 break;
1029 case 't':
1030 if ( !$unix ) {
1031 $unix = wfTimestamp( TS_UNIX, $ts );
1033 $num = gmdate( 't', $unix );
1034 break;
1035 case 'xjt':
1036 if ( !$hebrew ) {
1037 $hebrew = self::tsToHebrew( $ts );
1039 $num = $hebrew[3];
1040 break;
1041 case 'L':
1042 if ( !$unix ) {
1043 $unix = wfTimestamp( TS_UNIX, $ts );
1045 $num = gmdate( 'L', $unix );
1046 break;
1047 case 'o':
1048 if ( !$unix ) {
1049 $unix = wfTimestamp( TS_UNIX, $ts );
1051 $num = date( 'o', $unix );
1052 break;
1053 case 'Y':
1054 $num = substr( $ts, 0, 4 );
1055 break;
1056 case 'xiY':
1057 if ( !$iranian ) {
1058 $iranian = self::tsToIranian( $ts );
1060 $num = $iranian[0];
1061 break;
1062 case 'xmY':
1063 if ( !$hijri ) {
1064 $hijri = self::tsToHijri( $ts );
1066 $num = $hijri[0];
1067 break;
1068 case 'xjY':
1069 if ( !$hebrew ) {
1070 $hebrew = self::tsToHebrew( $ts );
1072 $num = $hebrew[0];
1073 break;
1074 case 'xkY':
1075 if ( !$thai ) {
1076 $thai = self::tsToYear( $ts, 'thai' );
1078 $num = $thai[0];
1079 break;
1080 case 'xoY':
1081 if ( !$minguo ) {
1082 $minguo = self::tsToYear( $ts, 'minguo' );
1084 $num = $minguo[0];
1085 break;
1086 case 'xtY':
1087 if ( !$tenno ) {
1088 $tenno = self::tsToYear( $ts, 'tenno' );
1090 $num = $tenno[0];
1091 break;
1092 case 'y':
1093 $num = substr( $ts, 2, 2 );
1094 break;
1095 case 'a':
1096 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1097 break;
1098 case 'A':
1099 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1100 break;
1101 case 'g':
1102 $h = substr( $ts, 8, 2 );
1103 $num = $h % 12 ? $h % 12 : 12;
1104 break;
1105 case 'G':
1106 $num = intval( substr( $ts, 8, 2 ) );
1107 break;
1108 case 'h':
1109 $h = substr( $ts, 8, 2 );
1110 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1111 break;
1112 case 'H':
1113 $num = substr( $ts, 8, 2 );
1114 break;
1115 case 'i':
1116 $num = substr( $ts, 10, 2 );
1117 break;
1118 case 's':
1119 $num = substr( $ts, 12, 2 );
1120 break;
1121 case 'c':
1122 if ( !$unix ) {
1123 $unix = wfTimestamp( TS_UNIX, $ts );
1125 $s .= gmdate( 'c', $unix );
1126 break;
1127 case 'r':
1128 if ( !$unix ) {
1129 $unix = wfTimestamp( TS_UNIX, $ts );
1131 $s .= gmdate( 'r', $unix );
1132 break;
1133 case 'U':
1134 if ( !$unix ) {
1135 $unix = wfTimestamp( TS_UNIX, $ts );
1137 $num = $unix;
1138 break;
1139 case '\\':
1140 # Backslash escaping
1141 if ( $p < strlen( $format ) - 1 ) {
1142 $s .= $format[++$p];
1143 } else {
1144 $s .= '\\';
1146 break;
1147 case '"':
1148 # Quoted literal
1149 if ( $p < strlen( $format ) - 1 ) {
1150 $endQuote = strpos( $format, '"', $p + 1 );
1151 if ( $endQuote === false ) {
1152 # No terminating quote, assume literal "
1153 $s .= '"';
1154 } else {
1155 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1156 $p = $endQuote;
1158 } else {
1159 # Quote at end of string, assume literal "
1160 $s .= '"';
1162 break;
1163 default:
1164 $s .= $format[$p];
1166 if ( $num !== false ) {
1167 if ( $rawToggle || $raw ) {
1168 $s .= $num;
1169 $raw = false;
1170 } elseif ( $roman ) {
1171 $s .= self::romanNumeral( $num );
1172 $roman = false;
1173 } elseif ( $hebrewNum ) {
1174 $s .= self::hebrewNumeral( $num );
1175 $hebrewNum = false;
1176 } else {
1177 $s .= $this->formatNum( $num, true );
1181 return $s;
1184 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1185 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1188 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1189 * Gregorian dates to Iranian dates. Originally written in C, it
1190 * is released under the terms of GNU Lesser General Public
1191 * License. Conversion to PHP was performed by Niklas Laxström.
1193 * Link: http://www.farsiweb.info/jalali/jalali.c
1195 * @param $ts string
1197 * @return string
1199 private static function tsToIranian( $ts ) {
1200 $gy = substr( $ts, 0, 4 ) -1600;
1201 $gm = substr( $ts, 4, 2 ) -1;
1202 $gd = substr( $ts, 6, 2 ) -1;
1204 # Days passed from the beginning (including leap years)
1205 $gDayNo = 365 * $gy
1206 + floor( ( $gy + 3 ) / 4 )
1207 - floor( ( $gy + 99 ) / 100 )
1208 + floor( ( $gy + 399 ) / 400 );
1211 // Add days of the past months of this year
1212 for ( $i = 0; $i < $gm; $i++ ) {
1213 $gDayNo += self::$GREG_DAYS[$i];
1216 // Leap years
1217 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1218 $gDayNo++;
1221 // Days passed in current month
1222 $gDayNo += $gd;
1224 $jDayNo = $gDayNo - 79;
1226 $jNp = floor( $jDayNo / 12053 );
1227 $jDayNo %= 12053;
1229 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1230 $jDayNo %= 1461;
1232 if ( $jDayNo >= 366 ) {
1233 $jy += floor( ( $jDayNo - 1 ) / 365 );
1234 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1237 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1238 $jDayNo -= self::$IRANIAN_DAYS[$i];
1241 $jm = $i + 1;
1242 $jd = $jDayNo + 1;
1244 return array( $jy, $jm, $jd );
1248 * Converting Gregorian dates to Hijri dates.
1250 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1252 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1254 * @param $ts string
1256 * @return string
1258 private static function tsToHijri( $ts ) {
1259 $year = substr( $ts, 0, 4 );
1260 $month = substr( $ts, 4, 2 );
1261 $day = substr( $ts, 6, 2 );
1263 $zyr = $year;
1264 $zd = $day;
1265 $zm = $month;
1266 $zy = $zyr;
1268 if (
1269 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1270 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1273 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1274 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1275 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1276 $zd - 32075;
1277 } else {
1278 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1279 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1282 $zl = $zjd -1948440 + 10632;
1283 $zn = (int)( ( $zl - 1 ) / 10631 );
1284 $zl = $zl - 10631 * $zn + 354;
1285 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1286 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1287 $zm = (int)( ( 24 * $zl ) / 709 );
1288 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1289 $zy = 30 * $zn + $zj - 30;
1291 return array( $zy, $zm, $zd );
1295 * Converting Gregorian dates to Hebrew dates.
1297 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1298 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1299 * to translate the relevant functions into PHP and release them under
1300 * GNU GPL.
1302 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1303 * and Adar II is 14. In a non-leap year, Adar is 6.
1305 * @param $ts string
1307 * @return string
1309 private static function tsToHebrew( $ts ) {
1310 # Parse date
1311 $year = substr( $ts, 0, 4 );
1312 $month = substr( $ts, 4, 2 );
1313 $day = substr( $ts, 6, 2 );
1315 # Calculate Hebrew year
1316 $hebrewYear = $year + 3760;
1318 # Month number when September = 1, August = 12
1319 $month += 4;
1320 if ( $month > 12 ) {
1321 # Next year
1322 $month -= 12;
1323 $year++;
1324 $hebrewYear++;
1327 # Calculate day of year from 1 September
1328 $dayOfYear = $day;
1329 for ( $i = 1; $i < $month; $i++ ) {
1330 if ( $i == 6 ) {
1331 # February
1332 $dayOfYear += 28;
1333 # Check if the year is leap
1334 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1335 $dayOfYear++;
1337 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1338 $dayOfYear += 30;
1339 } else {
1340 $dayOfYear += 31;
1344 # Calculate the start of the Hebrew year
1345 $start = self::hebrewYearStart( $hebrewYear );
1347 # Calculate next year's start
1348 if ( $dayOfYear <= $start ) {
1349 # Day is before the start of the year - it is the previous year
1350 # Next year's start
1351 $nextStart = $start;
1352 # Previous year
1353 $year--;
1354 $hebrewYear--;
1355 # Add days since previous year's 1 September
1356 $dayOfYear += 365;
1357 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1358 # Leap year
1359 $dayOfYear++;
1361 # Start of the new (previous) year
1362 $start = self::hebrewYearStart( $hebrewYear );
1363 } else {
1364 # Next year's start
1365 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1368 # Calculate Hebrew day of year
1369 $hebrewDayOfYear = $dayOfYear - $start;
1371 # Difference between year's days
1372 $diff = $nextStart - $start;
1373 # Add 12 (or 13 for leap years) days to ignore the difference between
1374 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1375 # difference is only about the year type
1376 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1377 $diff += 13;
1378 } else {
1379 $diff += 12;
1382 # Check the year pattern, and is leap year
1383 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1384 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1385 # and non-leap years
1386 $yearPattern = $diff % 30;
1387 # Check if leap year
1388 $isLeap = $diff >= 30;
1390 # Calculate day in the month from number of day in the Hebrew year
1391 # Don't check Adar - if the day is not in Adar, we will stop before;
1392 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1393 $hebrewDay = $hebrewDayOfYear;
1394 $hebrewMonth = 1;
1395 $days = 0;
1396 while ( $hebrewMonth <= 12 ) {
1397 # Calculate days in this month
1398 if ( $isLeap && $hebrewMonth == 6 ) {
1399 # Adar in a leap year
1400 if ( $isLeap ) {
1401 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1402 $days = 30;
1403 if ( $hebrewDay <= $days ) {
1404 # Day in Adar I
1405 $hebrewMonth = 13;
1406 } else {
1407 # Subtract the days of Adar I
1408 $hebrewDay -= $days;
1409 # Try Adar II
1410 $days = 29;
1411 if ( $hebrewDay <= $days ) {
1412 # Day in Adar II
1413 $hebrewMonth = 14;
1417 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1418 # Cheshvan in a complete year (otherwise as the rule below)
1419 $days = 30;
1420 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1421 # Kislev in an incomplete year (otherwise as the rule below)
1422 $days = 29;
1423 } else {
1424 # Odd months have 30 days, even have 29
1425 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1427 if ( $hebrewDay <= $days ) {
1428 # In the current month
1429 break;
1430 } else {
1431 # Subtract the days of the current month
1432 $hebrewDay -= $days;
1433 # Try in the next month
1434 $hebrewMonth++;
1438 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1442 * This calculates the Hebrew year start, as days since 1 September.
1443 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1444 * Used for Hebrew date.
1446 * @param $year int
1448 * @return string
1450 private static function hebrewYearStart( $year ) {
1451 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1452 $b = intval( ( $year - 1 ) % 4 );
1453 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1454 if ( $m < 0 ) {
1455 $m--;
1457 $Mar = intval( $m );
1458 if ( $m < 0 ) {
1459 $m++;
1461 $m -= $Mar;
1463 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1464 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1465 $Mar++;
1466 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1467 $Mar += 2;
1468 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1469 $Mar++;
1472 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1473 return $Mar;
1477 * Algorithm to convert Gregorian dates to Thai solar dates,
1478 * Minguo dates or Minguo dates.
1480 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1481 * http://en.wikipedia.org/wiki/Minguo_calendar
1482 * http://en.wikipedia.org/wiki/Japanese_era_name
1484 * @param $ts String: 14-character timestamp
1485 * @param $cName String: calender name
1486 * @return Array: converted year, month, day
1488 private static function tsToYear( $ts, $cName ) {
1489 $gy = substr( $ts, 0, 4 );
1490 $gm = substr( $ts, 4, 2 );
1491 $gd = substr( $ts, 6, 2 );
1493 if ( !strcmp( $cName, 'thai' ) ) {
1494 # Thai solar dates
1495 # Add 543 years to the Gregorian calendar
1496 # Months and days are identical
1497 $gy_offset = $gy + 543;
1498 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1499 # Minguo dates
1500 # Deduct 1911 years from the Gregorian calendar
1501 # Months and days are identical
1502 $gy_offset = $gy - 1911;
1503 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1504 # Nengō dates up to Meiji period
1505 # Deduct years from the Gregorian calendar
1506 # depending on the nengo periods
1507 # Months and days are identical
1508 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1509 # Meiji period
1510 $gy_gannen = $gy - 1868 + 1;
1511 $gy_offset = $gy_gannen;
1512 if ( $gy_gannen == 1 ) {
1513 $gy_offset = '元';
1515 $gy_offset = '明治' . $gy_offset;
1516 } elseif (
1517 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1518 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1519 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1520 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1521 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1524 # Taishō period
1525 $gy_gannen = $gy - 1912 + 1;
1526 $gy_offset = $gy_gannen;
1527 if ( $gy_gannen == 1 ) {
1528 $gy_offset = '元';
1530 $gy_offset = '大正' . $gy_offset;
1531 } elseif (
1532 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1533 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1534 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1537 # Shōwa period
1538 $gy_gannen = $gy - 1926 + 1;
1539 $gy_offset = $gy_gannen;
1540 if ( $gy_gannen == 1 ) {
1541 $gy_offset = '元';
1543 $gy_offset = '昭和' . $gy_offset;
1544 } else {
1545 # Heisei period
1546 $gy_gannen = $gy - 1989 + 1;
1547 $gy_offset = $gy_gannen;
1548 if ( $gy_gannen == 1 ) {
1549 $gy_offset = '元';
1551 $gy_offset = '平成' . $gy_offset;
1553 } else {
1554 $gy_offset = $gy;
1557 return array( $gy_offset, $gm, $gd );
1561 * Roman number formatting up to 3000
1563 * @param $num int
1565 * @return string
1567 static function romanNumeral( $num ) {
1568 static $table = array(
1569 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1570 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1571 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1572 array( '', 'M', 'MM', 'MMM' )
1575 $num = intval( $num );
1576 if ( $num > 3000 || $num <= 0 ) {
1577 return $num;
1580 $s = '';
1581 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1582 if ( $num >= $pow10 ) {
1583 $s .= $table[$i][floor( $num / $pow10 )];
1585 $num = $num % $pow10;
1587 return $s;
1591 * Hebrew Gematria number formatting up to 9999
1593 * @param $num int
1595 * @return string
1597 static function hebrewNumeral( $num ) {
1598 static $table = array(
1599 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1600 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1601 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1602 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1605 $num = intval( $num );
1606 if ( $num > 9999 || $num <= 0 ) {
1607 return $num;
1610 $s = '';
1611 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1612 if ( $num >= $pow10 ) {
1613 if ( $num == 15 || $num == 16 ) {
1614 $s .= $table[0][9] . $table[0][$num - 9];
1615 $num = 0;
1616 } else {
1617 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1618 if ( $pow10 == 1000 ) {
1619 $s .= "'";
1623 $num = $num % $pow10;
1625 if ( strlen( $s ) == 2 ) {
1626 $str = $s . "'";
1627 } else {
1628 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1629 $str .= substr( $s, strlen( $s ) - 2, 2 );
1631 $start = substr( $str, 0, strlen( $str ) - 2 );
1632 $end = substr( $str, strlen( $str ) - 2 );
1633 switch( $end ) {
1634 case 'כ':
1635 $str = $start . 'ך';
1636 break;
1637 case 'מ':
1638 $str = $start . 'ם';
1639 break;
1640 case 'נ':
1641 $str = $start . 'ן';
1642 break;
1643 case 'פ':
1644 $str = $start . 'ף';
1645 break;
1646 case 'צ':
1647 $str = $start . 'ץ';
1648 break;
1650 return $str;
1654 * This is meant to be used by time(), date(), and timeanddate() to get
1655 * the date preference they're supposed to use, it should be used in
1656 * all children.
1658 *<code>
1659 * function timeanddate([...], $format = true) {
1660 * $datePreference = $this->dateFormat($format);
1661 * [...]
1663 *</code>
1665 * @param $usePrefs Mixed: if true, the user's preference is used
1666 * if false, the site/language default is used
1667 * if int/string, assumed to be a format.
1668 * @return string
1670 function dateFormat( $usePrefs = true ) {
1671 global $wgUser;
1673 if ( is_bool( $usePrefs ) ) {
1674 if ( $usePrefs ) {
1675 $datePreference = $wgUser->getDatePreference();
1676 } else {
1677 $datePreference = (string)User::getDefaultOption( 'date' );
1679 } else {
1680 $datePreference = (string)$usePrefs;
1683 // return int
1684 if ( $datePreference == '' ) {
1685 return 'default';
1688 return $datePreference;
1692 * Get a format string for a given type and preference
1693 * @param $type string May be date, time or both
1694 * @param $pref string The format name as it appears in Messages*.php
1696 * @return string
1698 function getDateFormatString( $type, $pref ) {
1699 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1700 if ( $pref == 'default' ) {
1701 $pref = $this->getDefaultDateFormat();
1702 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1703 } else {
1704 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1705 if ( is_null( $df ) ) {
1706 $pref = $this->getDefaultDateFormat();
1707 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1710 $this->dateFormatStrings[$type][$pref] = $df;
1712 return $this->dateFormatStrings[$type][$pref];
1716 * @param $ts Mixed: the time format which needs to be turned into a
1717 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1718 * @param $adj Bool: whether to adjust the time output according to the
1719 * user configured offset ($timecorrection)
1720 * @param $format Mixed: true to use user's date format preference
1721 * @param $timecorrection String|bool the time offset as returned by
1722 * validateTimeZone() in Special:Preferences
1723 * @return string
1725 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1726 $ts = wfTimestamp( TS_MW, $ts );
1727 if ( $adj ) {
1728 $ts = $this->userAdjust( $ts, $timecorrection );
1730 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1731 return $this->sprintfDate( $df, $ts );
1735 * @param $ts Mixed: the time format which needs to be turned into a
1736 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1737 * @param $adj Bool: whether to adjust the time output according to the
1738 * user configured offset ($timecorrection)
1739 * @param $format Mixed: true to use user's date format preference
1740 * @param $timecorrection String|bool the time offset as returned by
1741 * validateTimeZone() in Special:Preferences
1742 * @return string
1744 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1745 $ts = wfTimestamp( TS_MW, $ts );
1746 if ( $adj ) {
1747 $ts = $this->userAdjust( $ts, $timecorrection );
1749 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1750 return $this->sprintfDate( $df, $ts );
1754 * @param $ts Mixed: the time format which needs to be turned into a
1755 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1756 * @param $adj Bool: whether to adjust the time output according to the
1757 * user configured offset ($timecorrection)
1758 * @param $format Mixed: what format to return, if it's false output the
1759 * default one (default true)
1760 * @param $timecorrection String|bool the time offset as returned by
1761 * validateTimeZone() in Special:Preferences
1762 * @return string
1764 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1765 $ts = wfTimestamp( TS_MW, $ts );
1766 if ( $adj ) {
1767 $ts = $this->userAdjust( $ts, $timecorrection );
1769 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1770 return $this->sprintfDate( $df, $ts );
1774 * @param $key string
1775 * @return array|null
1777 function getMessage( $key ) {
1778 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
1782 * @return array
1784 function getAllMessages() {
1785 return self::$dataCache->getItem( $this->mCode, 'messages' );
1789 * @param $in
1790 * @param $out
1791 * @param $string
1792 * @return string
1794 function iconv( $in, $out, $string ) {
1795 # This is a wrapper for iconv in all languages except esperanto,
1796 # which does some nasty x-conversions beforehand
1798 # Even with //IGNORE iconv can whine about illegal characters in
1799 # *input* string. We just ignore those too.
1800 # REF: http://bugs.php.net/bug.php?id=37166
1801 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1802 wfSuppressWarnings();
1803 $text = iconv( $in, $out . '//IGNORE', $string );
1804 wfRestoreWarnings();
1805 return $text;
1808 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1811 * @param $matches array
1812 * @return mixed|string
1814 function ucwordbreaksCallbackAscii( $matches ) {
1815 return $this->ucfirst( $matches[1] );
1819 * @param $matches array
1820 * @return string
1822 function ucwordbreaksCallbackMB( $matches ) {
1823 return mb_strtoupper( $matches[0] );
1827 * @param $matches array
1828 * @return string
1830 function ucCallback( $matches ) {
1831 list( $wikiUpperChars ) = self::getCaseMaps();
1832 return strtr( $matches[1], $wikiUpperChars );
1836 * @param $matches array
1837 * @return string
1839 function lcCallback( $matches ) {
1840 list( , $wikiLowerChars ) = self::getCaseMaps();
1841 return strtr( $matches[1], $wikiLowerChars );
1845 * @param $matches array
1846 * @return string
1848 function ucwordsCallbackMB( $matches ) {
1849 return mb_strtoupper( $matches[0] );
1853 * @param $matches array
1854 * @return string
1856 function ucwordsCallbackWiki( $matches ) {
1857 list( $wikiUpperChars ) = self::getCaseMaps();
1858 return strtr( $matches[0], $wikiUpperChars );
1862 * Make a string's first character uppercase
1864 * @param $str string
1866 * @return string
1868 function ucfirst( $str ) {
1869 $o = ord( $str );
1870 if ( $o < 96 ) { // if already uppercase...
1871 return $str;
1872 } elseif ( $o < 128 ) {
1873 return ucfirst( $str ); // use PHP's ucfirst()
1874 } else {
1875 // fall back to more complex logic in case of multibyte strings
1876 return $this->uc( $str, true );
1881 * Convert a string to uppercase
1883 * @param $str string
1884 * @param $first bool
1886 * @return string
1888 function uc( $str, $first = false ) {
1889 if ( function_exists( 'mb_strtoupper' ) ) {
1890 if ( $first ) {
1891 if ( $this->isMultibyte( $str ) ) {
1892 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1893 } else {
1894 return ucfirst( $str );
1896 } else {
1897 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1899 } else {
1900 if ( $this->isMultibyte( $str ) ) {
1901 $x = $first ? '^' : '';
1902 return preg_replace_callback(
1903 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1904 array( $this, 'ucCallback' ),
1905 $str
1907 } else {
1908 return $first ? ucfirst( $str ) : strtoupper( $str );
1914 * @param $str string
1915 * @return mixed|string
1917 function lcfirst( $str ) {
1918 $o = ord( $str );
1919 if ( !$o ) {
1920 return strval( $str );
1921 } elseif ( $o >= 128 ) {
1922 return $this->lc( $str, true );
1923 } elseif ( $o > 96 ) {
1924 return $str;
1925 } else {
1926 $str[0] = strtolower( $str[0] );
1927 return $str;
1932 * @param $str string
1933 * @param $first bool
1934 * @return mixed|string
1936 function lc( $str, $first = false ) {
1937 if ( function_exists( 'mb_strtolower' ) ) {
1938 if ( $first ) {
1939 if ( $this->isMultibyte( $str ) ) {
1940 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1941 } else {
1942 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1944 } else {
1945 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1947 } else {
1948 if ( $this->isMultibyte( $str ) ) {
1949 $x = $first ? '^' : '';
1950 return preg_replace_callback(
1951 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1952 array( $this, 'lcCallback' ),
1953 $str
1955 } else {
1956 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1962 * @param $str string
1963 * @return bool
1965 function isMultibyte( $str ) {
1966 return (bool)preg_match( '/[\x80-\xff]/', $str );
1970 * @param $str string
1971 * @return mixed|string
1973 function ucwords( $str ) {
1974 if ( $this->isMultibyte( $str ) ) {
1975 $str = $this->lc( $str );
1977 // regexp to find first letter in each word (i.e. after each space)
1978 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1980 // function to use to capitalize a single char
1981 if ( function_exists( 'mb_strtoupper' ) ) {
1982 return preg_replace_callback(
1983 $replaceRegexp,
1984 array( $this, 'ucwordsCallbackMB' ),
1985 $str
1987 } else {
1988 return preg_replace_callback(
1989 $replaceRegexp,
1990 array( $this, 'ucwordsCallbackWiki' ),
1991 $str
1994 } else {
1995 return ucwords( strtolower( $str ) );
2000 * capitalize words at word breaks
2002 * @param $str string
2003 * @return mixed
2005 function ucwordbreaks( $str ) {
2006 if ( $this->isMultibyte( $str ) ) {
2007 $str = $this->lc( $str );
2009 // since \b doesn't work for UTF-8, we explicitely define word break chars
2010 $breaks = "[ \-\(\)\}\{\.,\?!]";
2012 // find first letter after word break
2013 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2015 if ( function_exists( 'mb_strtoupper' ) ) {
2016 return preg_replace_callback(
2017 $replaceRegexp,
2018 array( $this, 'ucwordbreaksCallbackMB' ),
2019 $str
2021 } else {
2022 return preg_replace_callback(
2023 $replaceRegexp,
2024 array( $this, 'ucwordsCallbackWiki' ),
2025 $str
2028 } else {
2029 return preg_replace_callback(
2030 '/\b([\w\x80-\xff]+)\b/',
2031 array( $this, 'ucwordbreaksCallbackAscii' ),
2032 $str
2038 * Return a case-folded representation of $s
2040 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2041 * and $s2 are the same except for the case of their characters. It is not
2042 * necessary for the value returned to make sense when displayed.
2044 * Do *not* perform any other normalisation in this function. If a caller
2045 * uses this function when it should be using a more general normalisation
2046 * function, then fix the caller.
2048 * @param $s string
2050 * @return string
2052 function caseFold( $s ) {
2053 return $this->uc( $s );
2057 * @param $s string
2058 * @return string
2060 function checkTitleEncoding( $s ) {
2061 if ( is_array( $s ) ) {
2062 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2064 # Check for non-UTF-8 URLs
2065 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2066 if ( !$ishigh ) {
2067 return $s;
2070 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2071 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2072 if ( $isutf8 ) {
2073 return $s;
2076 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2080 * @return array
2082 function fallback8bitEncoding() {
2083 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2087 * Most writing systems use whitespace to break up words.
2088 * Some languages such as Chinese don't conventionally do this,
2089 * which requires special handling when breaking up words for
2090 * searching etc.
2092 * @return bool
2094 function hasWordBreaks() {
2095 return true;
2099 * Some languages such as Chinese require word segmentation,
2100 * Specify such segmentation when overridden in derived class.
2102 * @param $string String
2103 * @return String
2105 function segmentByWord( $string ) {
2106 return $string;
2110 * Some languages have special punctuation need to be normalized.
2111 * Make such changes here.
2113 * @param $string String
2114 * @return String
2116 function normalizeForSearch( $string ) {
2117 return self::convertDoubleWidth( $string );
2121 * convert double-width roman characters to single-width.
2122 * range: ff00-ff5f ~= 0020-007f
2124 * @param $string string
2126 * @return string
2128 protected static function convertDoubleWidth( $string ) {
2129 static $full = null;
2130 static $half = null;
2132 if ( $full === null ) {
2133 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2134 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2135 $full = str_split( $fullWidth, 3 );
2136 $half = str_split( $halfWidth );
2139 $string = str_replace( $full, $half, $string );
2140 return $string;
2144 * @param $string string
2145 * @param $pattern string
2146 * @return string
2148 protected static function insertSpace( $string, $pattern ) {
2149 $string = preg_replace( $pattern, " $1 ", $string );
2150 $string = preg_replace( '/ +/', ' ', $string );
2151 return $string;
2155 * @param $termsArray array
2156 * @return array
2158 function convertForSearchResult( $termsArray ) {
2159 # some languages, e.g. Chinese, need to do a conversion
2160 # in order for search results to be displayed correctly
2161 return $termsArray;
2165 * Get the first character of a string.
2167 * @param $s string
2168 * @return string
2170 function firstChar( $s ) {
2171 $matches = array();
2172 preg_match(
2173 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2174 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2176 $matches
2179 if ( isset( $matches[1] ) ) {
2180 if ( strlen( $matches[1] ) != 3 ) {
2181 return $matches[1];
2184 // Break down Hangul syllables to grab the first jamo
2185 $code = utf8ToCodepoint( $matches[1] );
2186 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2187 return $matches[1];
2188 } elseif ( $code < 0xb098 ) {
2189 return "\xe3\x84\xb1";
2190 } elseif ( $code < 0xb2e4 ) {
2191 return "\xe3\x84\xb4";
2192 } elseif ( $code < 0xb77c ) {
2193 return "\xe3\x84\xb7";
2194 } elseif ( $code < 0xb9c8 ) {
2195 return "\xe3\x84\xb9";
2196 } elseif ( $code < 0xbc14 ) {
2197 return "\xe3\x85\x81";
2198 } elseif ( $code < 0xc0ac ) {
2199 return "\xe3\x85\x82";
2200 } elseif ( $code < 0xc544 ) {
2201 return "\xe3\x85\x85";
2202 } elseif ( $code < 0xc790 ) {
2203 return "\xe3\x85\x87";
2204 } elseif ( $code < 0xcc28 ) {
2205 return "\xe3\x85\x88";
2206 } elseif ( $code < 0xce74 ) {
2207 return "\xe3\x85\x8a";
2208 } elseif ( $code < 0xd0c0 ) {
2209 return "\xe3\x85\x8b";
2210 } elseif ( $code < 0xd30c ) {
2211 return "\xe3\x85\x8c";
2212 } elseif ( $code < 0xd558 ) {
2213 return "\xe3\x85\x8d";
2214 } else {
2215 return "\xe3\x85\x8e";
2217 } else {
2218 return '';
2222 function initEncoding() {
2223 # Some languages may have an alternate char encoding option
2224 # (Esperanto X-coding, Japanese furigana conversion, etc)
2225 # If this language is used as the primary content language,
2226 # an override to the defaults can be set here on startup.
2230 * @param $s string
2231 * @return string
2233 function recodeForEdit( $s ) {
2234 # For some languages we'll want to explicitly specify
2235 # which characters make it into the edit box raw
2236 # or are converted in some way or another.
2237 global $wgEditEncoding;
2238 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2239 return $s;
2240 } else {
2241 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2246 * @param $s string
2247 * @return string
2249 function recodeInput( $s ) {
2250 # Take the previous into account.
2251 global $wgEditEncoding;
2252 if ( $wgEditEncoding != '' ) {
2253 $enc = $wgEditEncoding;
2254 } else {
2255 $enc = 'UTF-8';
2257 if ( $enc == 'UTF-8' ) {
2258 return $s;
2259 } else {
2260 return $this->iconv( $enc, 'UTF-8', $s );
2265 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2266 * also cleans up certain backwards-compatible sequences, converting them
2267 * to the modern Unicode equivalent.
2269 * This is language-specific for performance reasons only.
2271 * @param $s string
2273 * @return string
2275 function normalize( $s ) {
2276 global $wgAllUnicodeFixes;
2277 $s = UtfNormal::cleanUp( $s );
2278 if ( $wgAllUnicodeFixes ) {
2279 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2280 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2283 return $s;
2287 * Transform a string using serialized data stored in the given file (which
2288 * must be in the serialized subdirectory of $IP). The file contains pairs
2289 * mapping source characters to destination characters.
2291 * The data is cached in process memory. This will go faster if you have the
2292 * FastStringSearch extension.
2294 * @param $file string
2295 * @param $string string
2297 * @return string
2299 function transformUsingPairFile( $file, $string ) {
2300 if ( !isset( $this->transformData[$file] ) ) {
2301 $data = wfGetPrecompiledData( $file );
2302 if ( $data === false ) {
2303 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2305 $this->transformData[$file] = new ReplacementArray( $data );
2307 return $this->transformData[$file]->replace( $string );
2311 * For right-to-left language support
2313 * @return bool
2315 function isRTL() {
2316 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2320 * Return the correct HTML 'dir' attribute value for this language.
2321 * @return String
2323 function getDir() {
2324 return $this->isRTL() ? 'rtl' : 'ltr';
2328 * Return 'left' or 'right' as appropriate alignment for line-start
2329 * for this language's text direction.
2331 * Should be equivalent to CSS3 'start' text-align value....
2333 * @return String
2335 function alignStart() {
2336 return $this->isRTL() ? 'right' : 'left';
2340 * Return 'right' or 'left' as appropriate alignment for line-end
2341 * for this language's text direction.
2343 * Should be equivalent to CSS3 'end' text-align value....
2345 * @return String
2347 function alignEnd() {
2348 return $this->isRTL() ? 'left' : 'right';
2352 * A hidden direction mark (LRM or RLM), depending on the language direction
2354 * @param $opposite Boolean Get the direction mark opposite to your language
2355 * @return string
2357 function getDirMark( $opposite = false ) {
2358 $rtl = "\xE2\x80\x8F";
2359 $ltr = "\xE2\x80\x8E";
2360 if( $opposite ) { return $this->isRTL() ? $ltr : $rtl; }
2361 return $this->isRTL() ? $rtl : $ltr;
2365 * @return array
2367 function capitalizeAllNouns() {
2368 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2372 * An arrow, depending on the language direction
2374 * @return string
2376 function getArrow() {
2377 return $this->isRTL() ? '←' : '→';
2381 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2383 * @return bool
2385 function linkPrefixExtension() {
2386 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2390 * @return array
2392 function getMagicWords() {
2393 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2396 protected function doMagicHook() {
2397 if ( $this->mMagicHookDone ) {
2398 return;
2400 $this->mMagicHookDone = true;
2401 wfProfileIn( 'LanguageGetMagic' );
2402 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2403 wfProfileOut( 'LanguageGetMagic' );
2407 * Fill a MagicWord object with data from here
2409 * @param $mw
2411 function getMagic( $mw ) {
2412 $this->doMagicHook();
2414 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2415 $rawEntry = $this->mMagicExtensions[$mw->mId];
2416 } else {
2417 $magicWords = $this->getMagicWords();
2418 if ( isset( $magicWords[$mw->mId] ) ) {
2419 $rawEntry = $magicWords[$mw->mId];
2420 } else {
2421 $rawEntry = false;
2425 if ( !is_array( $rawEntry ) ) {
2426 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2427 } else {
2428 $mw->mCaseSensitive = $rawEntry[0];
2429 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2434 * Add magic words to the extension array
2436 * @param $newWords array
2438 function addMagicWordsByLang( $newWords ) {
2439 $code = $this->getCode();
2440 $fallbackChain = array();
2441 while ( $code && !in_array( $code, $fallbackChain ) ) {
2442 $fallbackChain[] = $code;
2443 $code = self::getFallbackFor( $code );
2445 if ( !in_array( 'en', $fallbackChain ) ) {
2446 $fallbackChain[] = 'en';
2448 $fallbackChain = array_reverse( $fallbackChain );
2449 foreach ( $fallbackChain as $code ) {
2450 if ( isset( $newWords[$code] ) ) {
2451 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2457 * Get special page names, as an associative array
2458 * case folded alias => real name
2460 function getSpecialPageAliases() {
2461 // Cache aliases because it may be slow to load them
2462 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2463 // Initialise array
2464 $this->mExtendedSpecialPageAliases =
2465 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2466 wfRunHooks( 'LanguageGetSpecialPageAliases',
2467 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2470 return $this->mExtendedSpecialPageAliases;
2474 * Italic is unsuitable for some languages
2476 * @param $text String: the text to be emphasized.
2477 * @return string
2479 function emphasize( $text ) {
2480 return "<em>$text</em>";
2484 * Normally we output all numbers in plain en_US style, that is
2485 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2486 * point twohundredthirtyfive. However this is not sutable for all
2487 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2488 * Icelandic just want to use commas instead of dots, and dots instead
2489 * of commas like "293.291,235".
2491 * An example of this function being called:
2492 * <code>
2493 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2494 * </code>
2496 * See LanguageGu.php for the Gujarati implementation and
2497 * $separatorTransformTable on MessageIs.php for
2498 * the , => . and . => , implementation.
2500 * @todo check if it's viable to use localeconv() for the decimal
2501 * separator thing.
2502 * @param $number Mixed: the string to be formatted, should be an integer
2503 * or a floating point number.
2504 * @param $nocommafy Bool: set to true for special numbers like dates
2505 * @return string
2507 function formatNum( $number, $nocommafy = false ) {
2508 global $wgTranslateNumerals;
2509 if ( !$nocommafy ) {
2510 $number = $this->commafy( $number );
2511 $s = $this->separatorTransformTable();
2512 if ( $s ) {
2513 $number = strtr( $number, $s );
2517 if ( $wgTranslateNumerals ) {
2518 $s = $this->digitTransformTable();
2519 if ( $s ) {
2520 $number = strtr( $number, $s );
2524 return $number;
2528 * @param $number string
2529 * @return string
2531 function parseFormattedNumber( $number ) {
2532 $s = $this->digitTransformTable();
2533 if ( $s ) {
2534 $number = strtr( $number, array_flip( $s ) );
2537 $s = $this->separatorTransformTable();
2538 if ( $s ) {
2539 $number = strtr( $number, array_flip( $s ) );
2542 $number = strtr( $number, array( ',' => '' ) );
2543 return $number;
2547 * Adds commas to a given number
2549 * @param $_ mixed
2550 * @return string
2552 function commafy( $_ ) {
2553 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2557 * @return array
2559 function digitTransformTable() {
2560 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2564 * @return array
2566 function separatorTransformTable() {
2567 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2571 * Take a list of strings and build a locale-friendly comma-separated
2572 * list, using the local comma-separator message.
2573 * The last two strings are chained with an "and".
2575 * @param $l Array
2576 * @return string
2578 function listToText( $l ) {
2579 $s = '';
2580 $m = count( $l ) - 1;
2581 if ( $m == 1 ) {
2582 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2583 } else {
2584 for ( $i = $m; $i >= 0; $i-- ) {
2585 if ( $i == $m ) {
2586 $s = $l[$i];
2587 } elseif ( $i == $m - 1 ) {
2588 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2589 } else {
2590 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2593 return $s;
2598 * Take a list of strings and build a locale-friendly comma-separated
2599 * list, using the local comma-separator message.
2600 * @param $list array of strings to put in a comma list
2601 * @return string
2603 function commaList( $list ) {
2604 return implode(
2605 $list,
2606 wfMsgExt(
2607 'comma-separator',
2608 array( 'parsemag', 'escapenoentities', 'language' => $this )
2614 * Take a list of strings and build a locale-friendly semicolon-separated
2615 * list, using the local semicolon-separator message.
2616 * @param $list array of strings to put in a semicolon list
2617 * @return string
2619 function semicolonList( $list ) {
2620 return implode(
2621 $list,
2622 wfMsgExt(
2623 'semicolon-separator',
2624 array( 'parsemag', 'escapenoentities', 'language' => $this )
2630 * Same as commaList, but separate it with the pipe instead.
2631 * @param $list array of strings to put in a pipe list
2632 * @return string
2634 function pipeList( $list ) {
2635 return implode(
2636 $list,
2637 wfMsgExt(
2638 'pipe-separator',
2639 array( 'escapenoentities', 'language' => $this )
2645 * Truncate a string to a specified length in bytes, appending an optional
2646 * string (e.g. for ellipses)
2648 * The database offers limited byte lengths for some columns in the database;
2649 * multi-byte character sets mean we need to ensure that only whole characters
2650 * are included, otherwise broken characters can be passed to the user
2652 * If $length is negative, the string will be truncated from the beginning
2654 * @param $string String to truncate
2655 * @param $length Int: maximum length (including ellipses)
2656 * @param $ellipsis String to append to the truncated text
2657 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2658 * $adjustLength was introduced in 1.18, before that behaved as if false.
2659 * @return string
2661 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2662 # Use the localized ellipsis character
2663 if ( $ellipsis == '...' ) {
2664 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2666 # Check if there is no need to truncate
2667 if ( $length == 0 ) {
2668 return $ellipsis; // convention
2669 } elseif ( strlen( $string ) <= abs( $length ) ) {
2670 return $string; // no need to truncate
2672 $stringOriginal = $string;
2673 # If ellipsis length is >= $length then we can't apply $adjustLength
2674 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2675 $string = $ellipsis; // this can be slightly unexpected
2676 # Otherwise, truncate and add ellipsis...
2677 } else {
2678 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
2679 if ( $length > 0 ) {
2680 $length -= $eLength;
2681 $string = substr( $string, 0, $length ); // xyz...
2682 $string = $this->removeBadCharLast( $string );
2683 $string = $string . $ellipsis;
2684 } else {
2685 $length += $eLength;
2686 $string = substr( $string, $length ); // ...xyz
2687 $string = $this->removeBadCharFirst( $string );
2688 $string = $ellipsis . $string;
2691 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2692 # This check is *not* redundant if $adjustLength, due to the single case where
2693 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2694 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2695 return $string;
2696 } else {
2697 return $stringOriginal;
2702 * Remove bytes that represent an incomplete Unicode character
2703 * at the end of string (e.g. bytes of the char are missing)
2705 * @param $string String
2706 * @return string
2708 protected function removeBadCharLast( $string ) {
2709 if ( $string != '' ) {
2710 $char = ord( $string[strlen( $string ) - 1] );
2711 $m = array();
2712 if ( $char >= 0xc0 ) {
2713 # We got the first byte only of a multibyte char; remove it.
2714 $string = substr( $string, 0, -1 );
2715 } elseif ( $char >= 0x80 &&
2716 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2717 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2719 # We chopped in the middle of a character; remove it
2720 $string = $m[1];
2723 return $string;
2727 * Remove bytes that represent an incomplete Unicode character
2728 * at the start of string (e.g. bytes of the char are missing)
2730 * @param $string String
2731 * @return string
2733 protected function removeBadCharFirst( $string ) {
2734 if ( $string != '' ) {
2735 $char = ord( $string[0] );
2736 if ( $char >= 0x80 && $char < 0xc0 ) {
2737 # We chopped in the middle of a character; remove the whole thing
2738 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2741 return $string;
2745 * Truncate a string of valid HTML to a specified length in bytes,
2746 * appending an optional string (e.g. for ellipses), and return valid HTML
2748 * This is only intended for styled/linked text, such as HTML with
2749 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2750 * Also, this will not detect things like "display:none" CSS.
2752 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2754 * @param string $text HTML string to truncate
2755 * @param int $length (zero/positive) Maximum length (including ellipses)
2756 * @param string $ellipsis String to append to the truncated text
2757 * @return string
2759 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2760 # Use the localized ellipsis character
2761 if ( $ellipsis == '...' ) {
2762 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2764 # Check if there is clearly no need to truncate
2765 if ( $length <= 0 ) {
2766 return $ellipsis; // no text shown, nothing to format (convention)
2767 } elseif ( strlen( $text ) <= $length ) {
2768 return $text; // string short enough even *with* HTML (short-circuit)
2771 $dispLen = 0; // innerHTML legth so far
2772 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2773 $tagType = 0; // 0-open, 1-close
2774 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2775 $entityState = 0; // 0-not entity, 1-entity
2776 $tag = $ret = ''; // accumulated tag name, accumulated result string
2777 $openTags = array(); // open tag stack
2778 $maybeState = null; // possible truncation state
2780 $textLen = strlen( $text );
2781 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2782 for ( $pos = 0; true; ++$pos ) {
2783 # Consider truncation once the display length has reached the maximim.
2784 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2785 # Check that we're not in the middle of a bracket/entity...
2786 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2787 if ( !$testingEllipsis ) {
2788 $testingEllipsis = true;
2789 # Save where we are; we will truncate here unless there turn out to
2790 # be so few remaining characters that truncation is not necessary.
2791 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2792 $maybeState = array( $ret, $openTags ); // save state
2794 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2795 # String in fact does need truncation, the truncation point was OK.
2796 list( $ret, $openTags ) = $maybeState; // reload state
2797 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2798 $ret .= $ellipsis; // add ellipsis
2799 break;
2802 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2804 # Read the next char...
2805 $ch = $text[$pos];
2806 $lastCh = $pos ? $text[$pos - 1] : '';
2807 $ret .= $ch; // add to result string
2808 if ( $ch == '<' ) {
2809 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2810 $entityState = 0; // for bad HTML
2811 $bracketState = 1; // tag started (checking for backslash)
2812 } elseif ( $ch == '>' ) {
2813 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2814 $entityState = 0; // for bad HTML
2815 $bracketState = 0; // out of brackets
2816 } elseif ( $bracketState == 1 ) {
2817 if ( $ch == '/' ) {
2818 $tagType = 1; // close tag (e.g. "</span>")
2819 } else {
2820 $tagType = 0; // open tag (e.g. "<span>")
2821 $tag .= $ch;
2823 $bracketState = 2; // building tag name
2824 } elseif ( $bracketState == 2 ) {
2825 if ( $ch != ' ' ) {
2826 $tag .= $ch;
2827 } else {
2828 // Name found (e.g. "<a href=..."), add on tag attributes...
2829 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2831 } elseif ( $bracketState == 0 ) {
2832 if ( $entityState ) {
2833 if ( $ch == ';' ) {
2834 $entityState = 0;
2835 $dispLen++; // entity is one displayed char
2837 } else {
2838 if ( $neLength == 0 && !$maybeState ) {
2839 // Save state without $ch. We want to *hit* the first
2840 // display char (to get tags) but not *use* it if truncating.
2841 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2843 if ( $ch == '&' ) {
2844 $entityState = 1; // entity found, (e.g. "&#160;")
2845 } else {
2846 $dispLen++; // this char is displayed
2847 // Add the next $max display text chars after this in one swoop...
2848 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
2849 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
2850 $dispLen += $skipped;
2851 $pos += $skipped;
2856 // Close the last tag if left unclosed by bad HTML
2857 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2858 while ( count( $openTags ) > 0 ) {
2859 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2861 return $ret;
2865 * truncateHtml() helper function
2866 * like strcspn() but adds the skipped chars to $ret
2868 * @param $ret
2869 * @param $text
2870 * @param $search
2871 * @param $start
2872 * @param $len
2873 * @return int
2875 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2876 if ( $len === null ) {
2877 $len = -1; // -1 means "no limit" for strcspn
2878 } elseif ( $len < 0 ) {
2879 $len = 0; // sanity
2881 $skipCount = 0;
2882 if ( $start < strlen( $text ) ) {
2883 $skipCount = strcspn( $text, $search, $start, $len );
2884 $ret .= substr( $text, $start, $skipCount );
2886 return $skipCount;
2890 * truncateHtml() helper function
2891 * (a) push or pop $tag from $openTags as needed
2892 * (b) clear $tag value
2893 * @param String &$tag Current HTML tag name we are looking at
2894 * @param int $tagType (0-open tag, 1-close tag)
2895 * @param char $lastCh Character before the '>' that ended this tag
2896 * @param array &$openTags Open tag stack (not accounting for $tag)
2898 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2899 $tag = ltrim( $tag );
2900 if ( $tag != '' ) {
2901 if ( $tagType == 0 && $lastCh != '/' ) {
2902 $openTags[] = $tag; // tag opened (didn't close itself)
2903 } elseif ( $tagType == 1 ) {
2904 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2905 array_pop( $openTags ); // tag closed
2908 $tag = '';
2913 * Grammatical transformations, needed for inflected languages
2914 * Invoked by putting {{grammar:case|word}} in a message
2916 * @param $word string
2917 * @param $case string
2918 * @return string
2920 function convertGrammar( $word, $case ) {
2921 global $wgGrammarForms;
2922 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2923 return $wgGrammarForms[$this->getCode()][$case][$word];
2925 return $word;
2929 * Provides an alternative text depending on specified gender.
2930 * Usage {{gender:username|masculine|feminine|neutral}}.
2931 * username is optional, in which case the gender of current user is used,
2932 * but only in (some) interface messages; otherwise default gender is used.
2933 * If second or third parameter are not specified, masculine is used.
2934 * These details may be overriden per language.
2936 * @param $gender string
2937 * @param $forms array
2939 * @return string
2941 function gender( $gender, $forms ) {
2942 if ( !count( $forms ) ) {
2943 return '';
2945 $forms = $this->preConvertPlural( $forms, 2 );
2946 if ( $gender === 'male' ) {
2947 return $forms[0];
2949 if ( $gender === 'female' ) {
2950 return $forms[1];
2952 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2956 * Plural form transformations, needed for some languages.
2957 * For example, there are 3 form of plural in Russian and Polish,
2958 * depending on "count mod 10". See [[w:Plural]]
2959 * For English it is pretty simple.
2961 * Invoked by putting {{plural:count|wordform1|wordform2}}
2962 * or {{plural:count|wordform1|wordform2|wordform3}}
2964 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2966 * @param $count Integer: non-localized number
2967 * @param $forms Array: different plural forms
2968 * @return string Correct form of plural for $count in this language
2970 function convertPlural( $count, $forms ) {
2971 if ( !count( $forms ) ) {
2972 return '';
2974 $forms = $this->preConvertPlural( $forms, 2 );
2976 return ( $count == 1 ) ? $forms[0] : $forms[1];
2980 * Checks that convertPlural was given an array and pads it to requested
2981 * amount of forms by copying the last one.
2983 * @param $count Integer: How many forms should there be at least
2984 * @param $forms Array of forms given to convertPlural
2985 * @return array Padded array of forms or an exception if not an array
2987 protected function preConvertPlural( /* Array */ $forms, $count ) {
2988 while ( count( $forms ) < $count ) {
2989 $forms[] = $forms[count( $forms ) - 1];
2991 return $forms;
2995 * This translates the duration ("1 week", "4 days", etc)
2996 * as well as the expiry time (which is an absolute timestamp).
2997 * @param $str String: the validated block duration in English
2998 * @return Somehow translated block duration
2999 * @see LanguageFi.php for example implementation
3001 function translateBlockExpiry( $str ) {
3002 $duration = SpecialBlock::getSuggestedDurations( $this );
3003 foreach( $duration as $show => $value ){
3004 if ( strcmp( $str, $value ) == 0 ) {
3005 return htmlspecialchars( trim( $show ) );
3009 // Since usually only infinite or indefinite is only on list, so try
3010 // equivalents if still here.
3011 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3012 if ( in_array( $str, $indefs ) ) {
3013 foreach( $indefs as $val ) {
3014 $show = array_search( $val, $duration, true );
3015 if ( $show !== false ) {
3016 return htmlspecialchars( trim( $show ) );
3020 // If no duration is given, but a timestamp, display that
3021 return ( strtotime( $str ) ? $this->timeanddate( strtotime( $str ) ) : $str );
3025 * languages like Chinese need to be segmented in order for the diff
3026 * to be of any use
3028 * @param $text String
3029 * @return String
3031 function segmentForDiff( $text ) {
3032 return $text;
3036 * and unsegment to show the result
3038 * @param $text String
3039 * @return String
3041 function unsegmentForDiff( $text ) {
3042 return $text;
3046 * convert text to all supported variants
3048 * @param $text string
3049 * @return array
3051 function autoConvertToAllVariants( $text ) {
3052 return $this->mConverter->autoConvertToAllVariants( $text );
3056 * convert text to different variants of a language.
3058 * @param $text string
3059 * @return string
3061 function convert( $text ) {
3062 return $this->mConverter->convert( $text );
3067 * Convert a Title object to a string in the preferred variant
3069 * @param $title Title
3070 * @return string
3072 function convertTitle( $title ) {
3073 return $this->mConverter->convertTitle( $title );
3077 * Check if this is a language with variants
3079 * @return bool
3081 function hasVariants() {
3082 return sizeof( $this->getVariants() ) > 1;
3086 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3088 * @param $text string
3089 * @return string
3091 function armourMath( $text ) {
3092 return $this->mConverter->armourMath( $text );
3096 * Perform output conversion on a string, and encode for safe HTML output.
3097 * @param $text String text to be converted
3098 * @param $isTitle Bool whether this conversion is for the article title
3099 * @return string
3100 * @todo this should get integrated somewhere sane
3102 function convertHtml( $text, $isTitle = false ) {
3103 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3107 * @param $key string
3108 * @return string
3110 function convertCategoryKey( $key ) {
3111 return $this->mConverter->convertCategoryKey( $key );
3115 * Get the list of variants supported by this language
3116 * see sample implementation in LanguageZh.php
3118 * @return array an array of language codes
3120 function getVariants() {
3121 return $this->mConverter->getVariants();
3125 * @return string
3127 function getPreferredVariant() {
3128 return $this->mConverter->getPreferredVariant();
3132 * @return string
3134 function getDefaultVariant() {
3135 return $this->mConverter->getDefaultVariant();
3139 * @return string
3141 function getURLVariant() {
3142 return $this->mConverter->getURLVariant();
3146 * If a language supports multiple variants, it is
3147 * possible that non-existing link in one variant
3148 * actually exists in another variant. this function
3149 * tries to find it. See e.g. LanguageZh.php
3151 * @param $link String: the name of the link
3152 * @param $nt Mixed: the title object of the link
3153 * @param $ignoreOtherCond Boolean: to disable other conditions when
3154 * we need to transclude a template or update a category's link
3155 * @return null the input parameters may be modified upon return
3157 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3158 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3162 * If a language supports multiple variants, converts text
3163 * into an array of all possible variants of the text:
3164 * 'variant' => text in that variant
3166 * @deprecated since 1.17 Use autoConvertToAllVariants()
3168 * @param $text string
3170 * @return string
3172 function convertLinkToAllVariants( $text ) {
3173 return $this->mConverter->convertLinkToAllVariants( $text );
3177 * returns language specific options used by User::getPageRenderHash()
3178 * for example, the preferred language variant
3180 * @return string
3182 function getExtraHashOptions() {
3183 return $this->mConverter->getExtraHashOptions();
3187 * For languages that support multiple variants, the title of an
3188 * article may be displayed differently in different variants. this
3189 * function returns the apporiate title defined in the body of the article.
3191 * @return string
3193 function getParsedTitle() {
3194 return $this->mConverter->getParsedTitle();
3198 * Enclose a string with the "no conversion" tag. This is used by
3199 * various functions in the Parser
3201 * @param $text String: text to be tagged for no conversion
3202 * @param $noParse bool
3203 * @return string the tagged text
3205 function markNoConversion( $text, $noParse = false ) {
3206 return $this->mConverter->markNoConversion( $text, $noParse );
3210 * A regular expression to match legal word-trailing characters
3211 * which should be merged onto a link of the form [[foo]]bar.
3213 * @return string
3215 function linkTrail() {
3216 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3220 * @return Language
3222 function getLangObj() {
3223 return $this;
3227 * Get the RFC 3066 code for this language object
3229 * @return string
3231 function getCode() {
3232 return $this->mCode;
3236 * @param $code string
3238 function setCode( $code ) {
3239 $this->mCode = $code;
3243 * Get the name of a file for a certain language code
3244 * @param $prefix string Prepend this to the filename
3245 * @param $code string Language code
3246 * @param $suffix string Append this to the filename
3247 * @return string $prefix . $mangledCode . $suffix
3249 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3250 // Protect against path traversal
3251 if ( !Language::isValidCode( $code )
3252 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3254 throw new MWException( "Invalid language code \"$code\"" );
3257 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3261 * Get the language code from a file name. Inverse of getFileName()
3262 * @param $filename string $prefix . $languageCode . $suffix
3263 * @param $prefix string Prefix before the language code
3264 * @param $suffix string Suffix after the language code
3265 * @return string Language code, or false if $prefix or $suffix isn't found
3267 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3268 $m = null;
3269 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3270 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3271 if ( !count( $m ) ) {
3272 return false;
3274 return str_replace( '_', '-', strtolower( $m[1] ) );
3278 * @param $code string
3279 * @return string
3281 static function getMessagesFileName( $code ) {
3282 global $IP;
3283 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3287 * @param $code string
3288 * @return string
3290 static function getClassFileName( $code ) {
3291 global $IP;
3292 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3296 * Get the fallback for a given language
3298 * @param $code string
3300 * @return false|string
3302 static function getFallbackFor( $code ) {
3303 if ( $code === 'en' ) {
3304 // Shortcut
3305 return false;
3306 } else {
3307 return self::getLocalisationCache()->getItem( $code, 'fallback' );
3312 * Get all messages for a given language
3313 * WARNING: this may take a long time
3315 * @param $code string
3317 * @return array
3319 static function getMessagesFor( $code ) {
3320 return self::getLocalisationCache()->getItem( $code, 'messages' );
3324 * Get a message for a given language
3326 * @param $key string
3327 * @param $code string
3329 * @return string
3331 static function getMessageFor( $key, $code ) {
3332 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3336 * @param $talk
3337 * @return mixed
3339 function fixVariableInNamespace( $talk ) {
3340 if ( strpos( $talk, '$1' ) === false ) {
3341 return $talk;
3344 global $wgMetaNamespace;
3345 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3347 # Allow grammar transformations
3348 # Allowing full message-style parsing would make simple requests
3349 # such as action=raw much more expensive than they need to be.
3350 # This will hopefully cover most cases.
3351 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3352 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3353 return str_replace( ' ', '_', $talk );
3357 * @param $m string
3358 * @return string
3360 function replaceGrammarInNamespace( $m ) {
3361 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3365 * @throws MWException
3366 * @return array
3368 static function getCaseMaps() {
3369 static $wikiUpperChars, $wikiLowerChars;
3370 if ( isset( $wikiUpperChars ) ) {
3371 return array( $wikiUpperChars, $wikiLowerChars );
3374 wfProfileIn( __METHOD__ );
3375 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3376 if ( $arr === false ) {
3377 throw new MWException(
3378 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3380 $wikiUpperChars = $arr['wikiUpperChars'];
3381 $wikiLowerChars = $arr['wikiLowerChars'];
3382 wfProfileOut( __METHOD__ );
3383 return array( $wikiUpperChars, $wikiLowerChars );
3387 * Decode an expiry (block, protection, etc) which has come from the DB
3389 * @param $expiry String: Database expiry String
3390 * @param $format Bool|Int true to process using language functions, or TS_ constant
3391 * to return the expiry in a given timestamp
3392 * @return String
3394 public function formatExpiry( $expiry, $format = true ) {
3395 static $infinity, $infinityMsg;
3396 if( $infinity === null ){
3397 $infinityMsg = wfMessage( 'infiniteblock' );
3398 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3401 if ( $expiry == '' || $expiry == $infinity ) {
3402 return $format === true
3403 ? $infinityMsg
3404 : $infinity;
3405 } else {
3406 return $format === true
3407 ? $this->timeanddate( $expiry )
3408 : wfTimestamp( $format, $expiry );
3413 * @todo Document
3414 * @param $seconds int|float
3415 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3416 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3417 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3418 * @return string
3420 function formatTimePeriod( $seconds, $format = false ) {
3421 if ( round( $seconds * 10 ) < 100 ) {
3422 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3423 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3424 } elseif ( round( $seconds ) < 60 ) {
3425 $s = $this->formatNum( round( $seconds ) );
3426 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3427 } elseif ( round( $seconds ) < 3600 ) {
3428 $minutes = floor( $seconds / 60 );
3429 $secondsPart = round( fmod( $seconds, 60 ) );
3430 if ( $secondsPart == 60 ) {
3431 $secondsPart = 0;
3432 $minutes++;
3434 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3435 $s .= ' ';
3436 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3437 } elseif ( round( $seconds ) <= 2*86400 ) {
3438 $hours = floor( $seconds / 3600 );
3439 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3440 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3441 if ( $secondsPart == 60 ) {
3442 $secondsPart = 0;
3443 $minutes++;
3445 if ( $minutes == 60 ) {
3446 $minutes = 0;
3447 $hours++;
3449 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3450 $s .= ' ';
3451 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3452 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3453 $s .= ' ' . $this->formatNum( $secondsPart ) .
3454 $this->getMessageFromDB( 'seconds-abbrev' );
3456 } else {
3457 $days = floor( $seconds / 86400 );
3458 if ( $format === 'avoidminutes' ) {
3459 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3460 if ( $hours == 24 ) {
3461 $hours = 0;
3462 $days++;
3464 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3465 $s .= ' ';
3466 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3467 } elseif ( $format === 'avoidseconds' ) {
3468 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3469 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3470 if ( $minutes == 60 ) {
3471 $minutes = 0;
3472 $hours++;
3474 if ( $hours == 24 ) {
3475 $hours = 0;
3476 $days++;
3478 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3479 $s .= ' ';
3480 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3481 $s .= ' ';
3482 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3483 } else {
3484 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3485 $s .= ' ';
3486 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3489 return $s;
3493 * @param $bps int
3494 * @return string
3496 function formatBitrate( $bps ) {
3497 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3498 if ( $bps <= 0 ) {
3499 return $this->formatNum( $bps ) . $units[0];
3501 $unitIndex = floor( log10( $bps ) / 3 );
3502 $mantissa = $bps / pow( 1000, $unitIndex );
3503 if ( $mantissa < 10 ) {
3504 $mantissa = round( $mantissa, 1 );
3505 } else {
3506 $mantissa = round( $mantissa );
3508 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3512 * Format a size in bytes for output, using an appropriate
3513 * unit (B, KB, MB or GB) according to the magnitude in question
3515 * @param $size Size to format
3516 * @return string Plain text (not HTML)
3518 function formatSize( $size ) {
3519 // For small sizes no decimal places necessary
3520 $round = 0;
3521 if ( $size > 1024 ) {
3522 $size = $size / 1024;
3523 if ( $size > 1024 ) {
3524 $size = $size / 1024;
3525 // For MB and bigger two decimal places are smarter
3526 $round = 2;
3527 if ( $size > 1024 ) {
3528 $size = $size / 1024;
3529 $msg = 'size-gigabytes';
3530 } else {
3531 $msg = 'size-megabytes';
3533 } else {
3534 $msg = 'size-kilobytes';
3536 } else {
3537 $msg = 'size-bytes';
3539 $size = round( $size, $round );
3540 $text = $this->getMessageFromDB( $msg );
3541 return str_replace( '$1', $this->formatNum( $size ), $text );
3545 * Get the conversion rule title, if any.
3547 * @return string
3549 function getConvRuleTitle() {
3550 return $this->mConverter->getConvRuleTitle();