3 * Internationalisation code
10 * @defgroup Language Language
13 if ( !defined( 'MEDIAWIKI' ) ) {
14 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
19 global $wgLanguageNames;
20 require_once( dirname( __FILE__
) . '/Names.php' );
22 if ( function_exists( 'mb_strtoupper' ) ) {
23 mb_internal_encoding( 'UTF-8' );
27 * a fake language converter
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; }
52 * Internationalisation code
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;
64 * ReplacementArray object caches
66 var $transformData = array();
69 * @var LocalisationCache
71 static public $dataCache;
73 static public $mLangObjCache = array();
75 static public $mWeekdayMsgs = array(
76 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
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',
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',
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
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
150 protected static function newFromCode( $code ) {
151 // Protect against path traversal below
152 if ( !Language
::isValidCode( $code )
153 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
155 throw new MWException( "Invalid language code \"$code\"" );
158 if ( !Language
::isValidBuiltInCode( $code ) ) {
159 // It's not possible to customise this code with class files, so
160 // just return a Language object. This is to support uselang= hacks.
161 $lang = new Language
;
162 $lang->setCode( $code );
166 // Check if there is a language class for the code
167 $class = self
::classFromCode( $code );
168 self
::preloadLanguageClass( $class );
169 if ( MWInit
::classExists( $class ) ) {
174 // Keep trying the fallback list until we find an existing class
175 $fallbacks = Language
::getFallbacksFor( $code );
176 foreach ( $fallbacks as $fallbackCode ) {
177 if ( !Language
::isValidBuiltInCode( $fallbackCode ) ) {
178 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
181 $class = self
::classFromCode( $fallbackCode );
182 self
::preloadLanguageClass( $class );
183 if ( MWInit
::classExists( $class ) ) {
184 $lang = Language
::newFromCode( $fallbackCode );
185 $lang->setCode( $code );
190 throw new MWException( "Invalid fallback sequence for language '$code'" );
194 * Returns true if a language code string is of a valid form, whether or
195 * not it exists. This includes codes which are used solely for
196 * customisation via the MediaWiki namespace.
198 * @param $code string
202 public static function isValidCode( $code ) {
204 strcspn( $code, ":/\\\000" ) === strlen( $code )
205 && !preg_match( Title
::getTitleInvalidRegex(), $code );
209 * Returns true if a language code is of a valid form for the purposes of
210 * internal customisation of MediaWiki, via Messages*.php.
212 * @param $code string
217 public static function isValidBuiltInCode( $code ) {
218 return preg_match( '/^[a-z0-9-]+$/i', $code );
221 public static function classFromCode( $code ) {
222 if ( $code == 'en' ) {
225 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
229 public static function preloadLanguageClass( $class ) {
232 if ( $class === 'Language' ) {
236 if ( !defined( 'MW_COMPILED' ) ) {
237 // Preload base classes to work around APC/PHP5 bug
238 if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
239 include_once( "$IP/languages/classes/$class.deps.php" );
241 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
242 include_once( "$IP/languages/classes/$class.php" );
248 * Get the LocalisationCache instance
250 * @return LocalisationCache
252 public static function getLocalisationCache() {
253 if ( is_null( self
::$dataCache ) ) {
254 global $wgLocalisationCacheConf;
255 $class = $wgLocalisationCacheConf['class'];
256 self
::$dataCache = new $class( $wgLocalisationCacheConf );
258 return self
::$dataCache;
261 function __construct() {
262 $this->mConverter
= new FakeConverter( $this );
263 // Set the code to the name of the descendant
264 if ( get_class( $this ) == 'Language' ) {
267 $this->mCode
= str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
269 self
::getLocalisationCache();
273 * Reduce memory usage
275 function __destruct() {
276 foreach ( $this as $name => $value ) {
277 unset( $this->$name );
282 * Hook which will be called if this is the content language.
283 * Descendants can use this to register hook functions or modify globals
285 function initContLang() { }
288 * Same as getFallbacksFor for current language.
290 * @deprecated in 1.19
292 function getFallbackLanguageCode() {
293 wfDeprecated( __METHOD__
);
294 return self
::getFallbackFor( $this->mCode
);
301 function getFallbackLanguages() {
302 return self
::getFallbacksFor( $this->mCode
);
306 * Exports $wgBookstoreListEn
309 function getBookstoreList() {
310 return self
::$dataCache->getItem( $this->mCode
, 'bookstoreList' );
316 function getNamespaces() {
317 if ( is_null( $this->namespaceNames
) ) {
318 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
320 $this->namespaceNames
= self
::$dataCache->getItem( $this->mCode
, 'namespaceNames' );
321 $validNamespaces = MWNamespace
::getCanonicalNamespaces();
323 $this->namespaceNames
= $wgExtraNamespaces +
$this->namespaceNames +
$validNamespaces;
325 $this->namespaceNames
[NS_PROJECT
] = $wgMetaNamespace;
326 if ( $wgMetaNamespaceTalk ) {
327 $this->namespaceNames
[NS_PROJECT_TALK
] = $wgMetaNamespaceTalk;
329 $talk = $this->namespaceNames
[NS_PROJECT_TALK
];
330 $this->namespaceNames
[NS_PROJECT_TALK
] =
331 $this->fixVariableInNamespace( $talk );
334 # Sometimes a language will be localised but not actually exist on this wiki.
335 foreach( $this->namespaceNames
as $key => $text ) {
336 if ( !isset( $validNamespaces[$key] ) ) {
337 unset( $this->namespaceNames
[$key] );
341 # The above mixing may leave namespaces out of canonical order.
342 # Re-order by namespace ID number...
343 ksort( $this->namespaceNames
);
345 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames
) );
347 return $this->namespaceNames
;
351 * A convenience function that returns the same thing as
352 * getNamespaces() except with the array values changed to ' '
353 * where it found '_', useful for producing output to be displayed
354 * e.g. in <select> forms.
358 function getFormattedNamespaces() {
359 $ns = $this->getNamespaces();
360 foreach ( $ns as $k => $v ) {
361 $ns[$k] = strtr( $v, '_', ' ' );
367 * Get a namespace value by key
369 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
370 * echo $mw_ns; // prints 'MediaWiki'
373 * @param $index Int: the array key of the namespace to return
374 * @return mixed, string if the namespace value exists, otherwise false
376 function getNsText( $index ) {
377 $ns = $this->getNamespaces();
378 return isset( $ns[$index] ) ?
$ns[$index] : false;
382 * A convenience function that returns the same thing as
383 * getNsText() except with '_' changed to ' ', useful for
386 * @param $index string
390 function getFormattedNsText( $index ) {
391 $ns = $this->getNsText( $index );
392 return strtr( $ns, '_', ' ' );
396 * Returns gender-dependent namespace alias if available.
397 * @param $index Int: namespace index
398 * @param $gender String: gender key (male, female... )
402 function getGenderNsText( $index, $gender ) {
403 $ns = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
404 return isset( $ns[$index][$gender] ) ?
$ns[$index][$gender] : $this->getNsText( $index );
408 * Whether this language makes distinguishes genders for example in
413 function needsGenderDistinction() {
414 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
415 return count( $aliases ) > 0;
419 * Get a namespace key by value, case insensitive.
420 * Only matches namespace names for the current language, not the
421 * canonical ones defined in Namespace.php.
423 * @param $text String
424 * @return mixed An integer if $text is a valid value otherwise false
426 function getLocalNsIndex( $text ) {
427 $lctext = $this->lc( $text );
428 $ids = $this->getNamespaceIds();
429 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
435 function getNamespaceAliases() {
436 if ( is_null( $this->namespaceAliases
) ) {
437 $aliases = self
::$dataCache->getItem( $this->mCode
, 'namespaceAliases' );
441 foreach ( $aliases as $name => $index ) {
442 if ( $index === NS_PROJECT_TALK
) {
443 unset( $aliases[$name] );
444 $name = $this->fixVariableInNamespace( $name );
445 $aliases[$name] = $index;
450 $genders = self
::$dataCache->getItem( $this->mCode
, 'namespaceGenderAliases' );
451 foreach ( $genders as $index => $forms ) {
452 foreach ( $forms as $alias ) {
453 $aliases[$alias] = $index;
457 $this->namespaceAliases
= $aliases;
459 return $this->namespaceAliases
;
465 function getNamespaceIds() {
466 if ( is_null( $this->mNamespaceIds
) ) {
467 global $wgNamespaceAliases;
468 # Put namespace names and aliases into a hashtable.
469 # If this is too slow, then we should arrange it so that it is done
470 # before caching. The catch is that at pre-cache time, the above
471 # class-specific fixup hasn't been done.
472 $this->mNamespaceIds
= array();
473 foreach ( $this->getNamespaces() as $index => $name ) {
474 $this->mNamespaceIds
[$this->lc( $name )] = $index;
476 foreach ( $this->getNamespaceAliases() as $name => $index ) {
477 $this->mNamespaceIds
[$this->lc( $name )] = $index;
479 if ( $wgNamespaceAliases ) {
480 foreach ( $wgNamespaceAliases as $name => $index ) {
481 $this->mNamespaceIds
[$this->lc( $name )] = $index;
485 return $this->mNamespaceIds
;
490 * Get a namespace key by value, case insensitive. Canonical namespace
491 * names override custom ones defined for the current language.
493 * @param $text String
494 * @return mixed An integer if $text is a valid value otherwise false
496 function getNsIndex( $text ) {
497 $lctext = $this->lc( $text );
498 if ( ( $ns = MWNamespace
::getCanonicalIndex( $lctext ) ) !== null ) {
501 $ids = $this->getNamespaceIds();
502 return isset( $ids[$lctext] ) ?
$ids[$lctext] : false;
506 * short names for language variants used for language conversion links.
508 * @param $code String
509 * @param $usemsg Use the "variantname-xyz" message if it exists
512 function getVariantname( $code, $usemsg = true ) {
513 $msg = "variantname-$code";
514 $codeArray = list( $rootCode ) = explode( '-', $code );
515 if( $usemsg && wfMessage( $msg )->exists() ) {
516 return $this->getMessageFromDB( $msg );
517 } elseif( $name = self
::getLanguageName( $code ) ) {
518 return $name; # if it's defined as a language name, show that
520 # otherwise, output the language code
526 * @param $name string
529 function specialPage( $name ) {
530 $aliases = $this->getSpecialPageAliases();
531 if ( isset( $aliases[$name][0] ) ) {
532 $name = $aliases[$name][0];
534 return $this->getNsText( NS_SPECIAL
) . ':' . $name;
540 function getQuickbarSettings() {
542 $this->getMessage( 'qbsettings-none' ),
543 $this->getMessage( 'qbsettings-fixedleft' ),
544 $this->getMessage( 'qbsettings-fixedright' ),
545 $this->getMessage( 'qbsettings-floatingleft' ),
546 $this->getMessage( 'qbsettings-floatingright' ),
547 $this->getMessage( 'qbsettings-directionality' )
554 function getDatePreferences() {
555 return self
::$dataCache->getItem( $this->mCode
, 'datePreferences' );
561 function getDateFormats() {
562 return self
::$dataCache->getItem( $this->mCode
, 'dateFormats' );
566 * @return array|string
568 function getDefaultDateFormat() {
569 $df = self
::$dataCache->getItem( $this->mCode
, 'defaultDateFormat' );
570 if ( $df === 'dmy or mdy' ) {
571 global $wgAmericanDates;
572 return $wgAmericanDates ?
'mdy' : 'dmy';
581 function getDatePreferenceMigrationMap() {
582 return self
::$dataCache->getItem( $this->mCode
, 'datePreferenceMigrationMap' );
589 function getImageFile( $image ) {
590 return self
::$dataCache->getSubitem( $this->mCode
, 'imageFiles', $image );
596 function getExtraUserToggles() {
597 return self
::$dataCache->getItem( $this->mCode
, 'extraUserToggles' );
604 function getUserToggle( $tog ) {
605 return $this->getMessageFromDB( "tog-$tog" );
609 * Get language names, indexed by code.
610 * If $customisedOnly is true, only returns codes with a messages file
612 * @param $customisedOnly bool
616 public static function getLanguageNames( $customisedOnly = false ) {
617 global $wgExtraLanguageNames;
618 static $coreLanguageNames;
620 if ( $coreLanguageNames === null ) {
621 include( MWInit
::compiledPath( 'languages/Names.php' ) );
624 $allNames = $wgExtraLanguageNames +
$coreLanguageNames;
625 if ( !$customisedOnly ) {
631 $dir = opendir( "$IP/languages/messages" );
632 while ( false !== ( $file = readdir( $dir ) ) ) {
633 $code = self
::getCodeFromFileName( $file, 'Messages' );
634 if ( $code && isset( $allNames[$code] ) ) {
635 $names[$code] = $allNames[$code];
643 * Get translated language names. This is done on best effort and
644 * by default this is exactly the same as Language::getLanguageNames.
645 * The CLDR extension provides translated names.
646 * @param $code String Language code.
647 * @return Array language code => language name
650 public static function getTranslatedLanguageNames( $code ) {
652 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $code ) );
654 foreach ( self
::getLanguageNames() as $code => $name ) {
655 if ( !isset( $names[$code] ) ) $names[$code] = $name;
662 * Get a message from the MediaWiki namespace.
664 * @param $msg String: message name
667 function getMessageFromDB( $msg ) {
668 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
672 * @param $code string
675 function getLanguageName( $code ) {
676 $names = self
::getLanguageNames();
677 if ( !array_key_exists( $code, $names ) ) {
680 return $names[$code];
687 function getMonthName( $key ) {
688 return $this->getMessageFromDB( self
::$mMonthMsgs[$key - 1] );
694 function getMonthNamesArray() {
695 $monthNames = array( '' );
696 for ( $i=1; $i < 13; $i++
) {
697 $monthNames[] = $this->getMonthName( $i );
706 function getMonthNameGen( $key ) {
707 return $this->getMessageFromDB( self
::$mMonthGenMsgs[$key - 1] );
714 function getMonthAbbreviation( $key ) {
715 return $this->getMessageFromDB( self
::$mMonthAbbrevMsgs[$key - 1] );
721 function getMonthAbbreviationsArray() {
722 $monthNames = array( '' );
723 for ( $i=1; $i < 13; $i++
) {
724 $monthNames[] = $this->getMonthAbbreviation( $i );
733 function getWeekdayName( $key ) {
734 return $this->getMessageFromDB( self
::$mWeekdayMsgs[$key - 1] );
741 function getWeekdayAbbreviation( $key ) {
742 return $this->getMessageFromDB( self
::$mWeekdayAbbrevMsgs[$key - 1] );
749 function getIranianCalendarMonthName( $key ) {
750 return $this->getMessageFromDB( self
::$mIranianCalendarMonthMsgs[$key - 1] );
757 function getHebrewCalendarMonthName( $key ) {
758 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthMsgs[$key - 1] );
765 function getHebrewCalendarMonthNameGen( $key ) {
766 return $this->getMessageFromDB( self
::$mHebrewCalendarMonthGenMsgs[$key - 1] );
773 function getHijriCalendarMonthName( $key ) {
774 return $this->getMessageFromDB( self
::$mHijriCalendarMonthMsgs[$key - 1] );
778 * Used by date() and time() to adjust the time output.
780 * @param $ts Int the time in date('YmdHis') format
781 * @param $tz Mixed: adjust the time by this amount (default false, mean we
782 * get user timecorrection setting)
785 function userAdjust( $ts, $tz = false ) {
786 global $wgUser, $wgLocalTZoffset;
788 if ( $tz === false ) {
789 $tz = $wgUser->getOption( 'timecorrection' );
792 $data = explode( '|', $tz, 3 );
794 if ( $data[0] == 'ZoneInfo' ) {
795 wfSuppressWarnings();
796 $userTZ = timezone_open( $data[2] );
798 if ( $userTZ !== false ) {
799 $date = date_create( $ts, timezone_open( 'UTC' ) );
800 date_timezone_set( $date, $userTZ );
801 $date = date_format( $date, 'YmdHis' );
804 # Unrecognized timezone, default to 'Offset' with the stored offset.
809 if ( $data[0] == 'System' ||
$tz == '' ) {
810 # Global offset in minutes.
811 if ( isset( $wgLocalTZoffset ) ) {
812 $minDiff = $wgLocalTZoffset;
814 } elseif ( $data[0] == 'Offset' ) {
815 $minDiff = intval( $data[1] );
817 $data = explode( ':', $tz );
818 if ( count( $data ) == 2 ) {
819 $data[0] = intval( $data[0] );
820 $data[1] = intval( $data[1] );
821 $minDiff = abs( $data[0] ) * 60 +
$data[1];
822 if ( $data[0] < 0 ) {
823 $minDiff = -$minDiff;
826 $minDiff = intval( $data[0] ) * 60;
830 # No difference ? Return time unchanged
831 if ( 0 == $minDiff ) {
835 wfSuppressWarnings(); // E_STRICT system time bitching
836 # Generate an adjusted date; take advantage of the fact that mktime
837 # will normalize out-of-range values so we don't have to split $minDiff
838 # into hours and minutes.
840 (int)substr( $ts, 8, 2 ) ), # Hours
841 (int)substr( $ts, 10, 2 ) +
$minDiff, # Minutes
842 (int)substr( $ts, 12, 2 ), # Seconds
843 (int)substr( $ts, 4, 2 ), # Month
844 (int)substr( $ts, 6, 2 ), # Day
845 (int)substr( $ts, 0, 4 ) ); # Year
847 $date = date( 'YmdHis', $t );
854 * This is a workalike of PHP's date() function, but with better
855 * internationalisation, a reduced set of format characters, and a better
858 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
859 * PHP manual for definitions. There are a number of extensions, which
862 * xn Do not translate digits of the next numeric format character
863 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
864 * xr Use roman numerals for the next numeric format character
865 * xh Use hebrew numerals for the next numeric format character
867 * xg Genitive month name
869 * xij j (day number) in Iranian calendar
870 * xiF F (month name) in Iranian calendar
871 * xin n (month number) in Iranian calendar
872 * xiY Y (full year) in Iranian calendar
874 * xjj j (day number) in Hebrew calendar
875 * xjF F (month name) in Hebrew calendar
876 * xjt t (days in month) in Hebrew calendar
877 * xjx xg (genitive month name) in Hebrew calendar
878 * xjn n (month number) in Hebrew calendar
879 * xjY Y (full year) in Hebrew calendar
881 * xmj j (day number) in Hijri calendar
882 * xmF F (month name) in Hijri calendar
883 * xmn n (month number) in Hijri calendar
884 * xmY Y (full year) in Hijri calendar
886 * xkY Y (full year) in Thai solar calendar. Months and days are
887 * identical to the Gregorian calendar
888 * xoY Y (full year) in Minguo calendar or Juche year.
889 * Months and days are identical to the
891 * xtY Y (full year) in Japanese nengo. Months and days are
892 * identical to the Gregorian calendar
894 * Characters enclosed in double quotes will be considered literal (with
895 * the quotes themselves removed). Unmatched quotes will be considered
896 * literal quotes. Example:
898 * "The month is" F => The month is January
901 * Backslash escaping is also supported.
903 * Input timestamp is assumed to be pre-normalized to the desired local
906 * @param $format String
907 * @param $ts String: 14-character timestamp
910 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
914 function sprintfDate( $format, $ts ) {
927 for ( $p = 0; $p < strlen( $format ); $p++
) {
930 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
931 $code .= $format[++
$p];
934 if ( ( $code === 'xi' ||
$code == 'xj' ||
$code == 'xk' ||
$code == 'xm' ||
$code == 'xo' ||
$code == 'xt' ) && $p < strlen( $format ) - 1 ) {
935 $code .= $format[++
$p];
946 $rawToggle = !$rawToggle;
955 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
958 if ( !$hebrew ) $hebrew = self
::tsToHebrew( $ts );
959 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
962 $num = substr( $ts, 6, 2 );
965 if ( !$unix ) $unix = wfTimestamp( TS_UNIX
, $ts );
966 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) +
1 );
969 $num = intval( substr( $ts, 6, 2 ) );
973 $iranian = self
::tsToIranian( $ts );
979 $hijri = self
::tsToHijri( $ts );
985 $hebrew = self
::tsToHebrew( $ts );
991 $unix = wfTimestamp( TS_UNIX
, $ts );
993 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) +
1 );
997 $unix = wfTimestamp( TS_UNIX
, $ts );
999 $w = gmdate( 'w', $unix );
1004 $unix = wfTimestamp( TS_UNIX
, $ts );
1006 $num = gmdate( 'w', $unix );
1010 $unix = wfTimestamp( TS_UNIX
, $ts );
1012 $num = gmdate( 'z', $unix );
1016 $unix = wfTimestamp( TS_UNIX
, $ts );
1018 $num = gmdate( 'W', $unix );
1021 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1025 $iranian = self
::tsToIranian( $ts );
1027 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1031 $hijri = self
::tsToHijri( $ts );
1033 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1037 $hebrew = self
::tsToHebrew( $ts );
1039 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1042 $num = substr( $ts, 4, 2 );
1045 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1048 $num = intval( substr( $ts, 4, 2 ) );
1052 $iranian = self
::tsToIranian( $ts );
1058 $hijri = self
::tsToHijri ( $ts );
1064 $hebrew = self
::tsToHebrew( $ts );
1070 $unix = wfTimestamp( TS_UNIX
, $ts );
1072 $num = gmdate( 't', $unix );
1076 $hebrew = self
::tsToHebrew( $ts );
1082 $unix = wfTimestamp( TS_UNIX
, $ts );
1084 $num = gmdate( 'L', $unix );
1088 $unix = wfTimestamp( TS_UNIX
, $ts );
1090 $num = date( 'o', $unix );
1093 $num = substr( $ts, 0, 4 );
1097 $iranian = self
::tsToIranian( $ts );
1103 $hijri = self
::tsToHijri( $ts );
1109 $hebrew = self
::tsToHebrew( $ts );
1115 $thai = self
::tsToYear( $ts, 'thai' );
1121 $minguo = self
::tsToYear( $ts, 'minguo' );
1127 $tenno = self
::tsToYear( $ts, 'tenno' );
1132 $num = substr( $ts, 2, 2 );
1135 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'am' : 'pm';
1138 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ?
'AM' : 'PM';
1141 $h = substr( $ts, 8, 2 );
1142 $num = $h %
12 ?
$h %
12 : 12;
1145 $num = intval( substr( $ts, 8, 2 ) );
1148 $h = substr( $ts, 8, 2 );
1149 $num = sprintf( '%02d', $h %
12 ?
$h %
12 : 12 );
1152 $num = substr( $ts, 8, 2 );
1155 $num = substr( $ts, 10, 2 );
1158 $num = substr( $ts, 12, 2 );
1162 $unix = wfTimestamp( TS_UNIX
, $ts );
1164 $s .= gmdate( 'c', $unix );
1168 $unix = wfTimestamp( TS_UNIX
, $ts );
1170 $s .= gmdate( 'r', $unix );
1174 $unix = wfTimestamp( TS_UNIX
, $ts );
1179 # Backslash escaping
1180 if ( $p < strlen( $format ) - 1 ) {
1181 $s .= $format[++
$p];
1188 if ( $p < strlen( $format ) - 1 ) {
1189 $endQuote = strpos( $format, '"', $p +
1 );
1190 if ( $endQuote === false ) {
1191 # No terminating quote, assume literal "
1194 $s .= substr( $format, $p +
1, $endQuote - $p - 1 );
1198 # Quote at end of string, assume literal "
1205 if ( $num !== false ) {
1206 if ( $rawToggle ||
$raw ) {
1209 } elseif ( $roman ) {
1210 $s .= self
::romanNumeral( $num );
1212 } elseif ( $hebrewNum ) {
1213 $s .= self
::hebrewNumeral( $num );
1216 $s .= $this->formatNum( $num, true );
1223 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1224 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1227 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1228 * Gregorian dates to Iranian dates. Originally written in C, it
1229 * is released under the terms of GNU Lesser General Public
1230 * License. Conversion to PHP was performed by Niklas Laxström.
1232 * Link: http://www.farsiweb.info/jalali/jalali.c
1238 private static function tsToIranian( $ts ) {
1239 $gy = substr( $ts, 0, 4 ) -1600;
1240 $gm = substr( $ts, 4, 2 ) -1;
1241 $gd = substr( $ts, 6, 2 ) -1;
1243 # Days passed from the beginning (including leap years)
1245 +
floor( ( $gy +
3 ) / 4 )
1246 - floor( ( $gy +
99 ) / 100 )
1247 +
floor( ( $gy +
399 ) / 400 );
1250 // Add days of the past months of this year
1251 for ( $i = 0; $i < $gm; $i++
) {
1252 $gDayNo +
= self
::$GREG_DAYS[$i];
1256 if ( $gm > 1 && ( ( $gy %
4 === 0 && $gy %
100 !== 0 ||
( $gy %
400 == 0 ) ) ) ) {
1260 // Days passed in current month
1263 $jDayNo = $gDayNo - 79;
1265 $jNp = floor( $jDayNo / 12053 );
1268 $jy = 979 +
33 * $jNp +
4 * floor( $jDayNo / 1461 );
1271 if ( $jDayNo >= 366 ) {
1272 $jy +
= floor( ( $jDayNo - 1 ) / 365 );
1273 $jDayNo = floor( ( $jDayNo - 1 ) %
365 );
1276 for ( $i = 0; $i < 11 && $jDayNo >= self
::$IRANIAN_DAYS[$i]; $i++
) {
1277 $jDayNo -= self
::$IRANIAN_DAYS[$i];
1283 return array( $jy, $jm, $jd );
1287 * Converting Gregorian dates to Hijri dates.
1289 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1291 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1297 private static function tsToHijri( $ts ) {
1298 $year = substr( $ts, 0, 4 );
1299 $month = substr( $ts, 4, 2 );
1300 $day = substr( $ts, 6, 2 );
1308 ( $zy > 1582 ) ||
( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1309 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1312 $zjd = (int)( ( 1461 * ( $zy +
4800 +
(int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1313 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1314 (int)( ( 3 * (int)( ( ( $zy +
4900 +
(int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1317 $zjd = 367 * $zy - (int)( ( 7 * ( $zy +
5001 +
(int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1318 (int)( ( 275 * $zm ) / 9 ) +
$zd +
1729777;
1321 $zl = $zjd -1948440 +
10632;
1322 $zn = (int)( ( $zl - 1 ) / 10631 );
1323 $zl = $zl - 10631 * $zn +
354;
1324 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1325 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) +
29;
1326 $zm = (int)( ( 24 * $zl ) / 709 );
1327 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1328 $zy = 30 * $zn +
$zj - 30;
1330 return array( $zy, $zm, $zd );
1334 * Converting Gregorian dates to Hebrew dates.
1336 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1337 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1338 * to translate the relevant functions into PHP and release them under
1341 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1342 * and Adar II is 14. In a non-leap year, Adar is 6.
1348 private static function tsToHebrew( $ts ) {
1350 $year = substr( $ts, 0, 4 );
1351 $month = substr( $ts, 4, 2 );
1352 $day = substr( $ts, 6, 2 );
1354 # Calculate Hebrew year
1355 $hebrewYear = $year +
3760;
1357 # Month number when September = 1, August = 12
1359 if ( $month > 12 ) {
1366 # Calculate day of year from 1 September
1368 for ( $i = 1; $i < $month; $i++
) {
1372 # Check if the year is leap
1373 if ( $year %
400 == 0 ||
( $year %
4 == 0 && $year %
100 > 0 ) ) {
1376 } elseif ( $i == 8 ||
$i == 10 ||
$i == 1 ||
$i == 3 ) {
1383 # Calculate the start of the Hebrew year
1384 $start = self
::hebrewYearStart( $hebrewYear );
1386 # Calculate next year's start
1387 if ( $dayOfYear <= $start ) {
1388 # Day is before the start of the year - it is the previous year
1390 $nextStart = $start;
1394 # Add days since previous year's 1 September
1396 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1400 # Start of the new (previous) year
1401 $start = self
::hebrewYearStart( $hebrewYear );
1404 $nextStart = self
::hebrewYearStart( $hebrewYear +
1 );
1407 # Calculate Hebrew day of year
1408 $hebrewDayOfYear = $dayOfYear - $start;
1410 # Difference between year's days
1411 $diff = $nextStart - $start;
1412 # Add 12 (or 13 for leap years) days to ignore the difference between
1413 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1414 # difference is only about the year type
1415 if ( ( $year %
400 == 0 ) ||
( $year %
100 != 0 && $year %
4 == 0 ) ) {
1421 # Check the year pattern, and is leap year
1422 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1423 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1424 # and non-leap years
1425 $yearPattern = $diff %
30;
1426 # Check if leap year
1427 $isLeap = $diff >= 30;
1429 # Calculate day in the month from number of day in the Hebrew year
1430 # Don't check Adar - if the day is not in Adar, we will stop before;
1431 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1432 $hebrewDay = $hebrewDayOfYear;
1435 while ( $hebrewMonth <= 12 ) {
1436 # Calculate days in this month
1437 if ( $isLeap && $hebrewMonth == 6 ) {
1438 # Adar in a leap year
1440 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1442 if ( $hebrewDay <= $days ) {
1446 # Subtract the days of Adar I
1447 $hebrewDay -= $days;
1450 if ( $hebrewDay <= $days ) {
1456 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1457 # Cheshvan in a complete year (otherwise as the rule below)
1459 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1460 # Kislev in an incomplete year (otherwise as the rule below)
1463 # Odd months have 30 days, even have 29
1464 $days = 30 - ( $hebrewMonth - 1 ) %
2;
1466 if ( $hebrewDay <= $days ) {
1467 # In the current month
1470 # Subtract the days of the current month
1471 $hebrewDay -= $days;
1472 # Try in the next month
1477 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1481 * This calculates the Hebrew year start, as days since 1 September.
1482 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1483 * Used for Hebrew date.
1489 private static function hebrewYearStart( $year ) {
1490 $a = intval( ( 12 * ( $year - 1 ) +
17 ) %
19 );
1491 $b = intval( ( $year - 1 ) %
4 );
1492 $m = 32.044093161144 +
1.5542417966212 * $a +
$b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1496 $Mar = intval( $m );
1502 $c = intval( ( $Mar +
3 * ( $year - 1 ) +
5 * $b +
5 ) %
7 );
1503 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1505 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1507 } elseif ( $c == 2 ||
$c == 4 ||
$c == 6 ) {
1511 $Mar +
= intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1516 * Algorithm to convert Gregorian dates to Thai solar dates,
1517 * Minguo dates or Minguo dates.
1519 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1520 * http://en.wikipedia.org/wiki/Minguo_calendar
1521 * http://en.wikipedia.org/wiki/Japanese_era_name
1523 * @param $ts String: 14-character timestamp
1524 * @param $cName String: calender name
1525 * @return Array: converted year, month, day
1527 private static function tsToYear( $ts, $cName ) {
1528 $gy = substr( $ts, 0, 4 );
1529 $gm = substr( $ts, 4, 2 );
1530 $gd = substr( $ts, 6, 2 );
1532 if ( !strcmp( $cName, 'thai' ) ) {
1534 # Add 543 years to the Gregorian calendar
1535 # Months and days are identical
1536 $gy_offset = $gy +
543;
1537 } elseif ( ( !strcmp( $cName, 'minguo' ) ) ||
!strcmp( $cName, 'juche' ) ) {
1539 # Deduct 1911 years from the Gregorian calendar
1540 # Months and days are identical
1541 $gy_offset = $gy - 1911;
1542 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1543 # Nengō dates up to Meiji period
1544 # Deduct years from the Gregorian calendar
1545 # depending on the nengo periods
1546 # Months and days are identical
1547 if ( ( $gy < 1912 ) ||
( ( $gy == 1912 ) && ( $gm < 7 ) ) ||
( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1549 $gy_gannen = $gy - 1868 +
1;
1550 $gy_offset = $gy_gannen;
1551 if ( $gy_gannen == 1 ) {
1554 $gy_offset = '明治' . $gy_offset;
1556 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1557 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1558 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1559 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1560 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1564 $gy_gannen = $gy - 1912 +
1;
1565 $gy_offset = $gy_gannen;
1566 if ( $gy_gannen == 1 ) {
1569 $gy_offset = '大正' . $gy_offset;
1571 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1572 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1573 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1577 $gy_gannen = $gy - 1926 +
1;
1578 $gy_offset = $gy_gannen;
1579 if ( $gy_gannen == 1 ) {
1582 $gy_offset = '昭和' . $gy_offset;
1585 $gy_gannen = $gy - 1989 +
1;
1586 $gy_offset = $gy_gannen;
1587 if ( $gy_gannen == 1 ) {
1590 $gy_offset = '平成' . $gy_offset;
1596 return array( $gy_offset, $gm, $gd );
1600 * Roman number formatting up to 3000
1606 static function romanNumeral( $num ) {
1607 static $table = array(
1608 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1609 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1610 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1611 array( '', 'M', 'MM', 'MMM' )
1614 $num = intval( $num );
1615 if ( $num > 3000 ||
$num <= 0 ) {
1620 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1621 if ( $num >= $pow10 ) {
1622 $s .= $table[$i][floor( $num / $pow10 )];
1624 $num = $num %
$pow10;
1630 * Hebrew Gematria number formatting up to 9999
1636 static function hebrewNumeral( $num ) {
1637 static $table = array(
1638 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1639 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1640 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1641 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1644 $num = intval( $num );
1645 if ( $num > 9999 ||
$num <= 0 ) {
1650 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1651 if ( $num >= $pow10 ) {
1652 if ( $num == 15 ||
$num == 16 ) {
1653 $s .= $table[0][9] . $table[0][$num - 9];
1656 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1657 if ( $pow10 == 1000 ) {
1662 $num = $num %
$pow10;
1664 if ( strlen( $s ) == 2 ) {
1667 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1668 $str .= substr( $s, strlen( $s ) - 2, 2 );
1670 $start = substr( $str, 0, strlen( $str ) - 2 );
1671 $end = substr( $str, strlen( $str ) - 2 );
1674 $str = $start . 'ך';
1677 $str = $start . 'ם';
1680 $str = $start . 'ן';
1683 $str = $start . 'ף';
1686 $str = $start . 'ץ';
1693 * This is meant to be used by time(), date(), and timeanddate() to get
1694 * the date preference they're supposed to use, it should be used in
1698 * function timeanddate([...], $format = true) {
1699 * $datePreference = $this->dateFormat($format);
1704 * @param $usePrefs Mixed: if true, the user's preference is used
1705 * if false, the site/language default is used
1706 * if int/string, assumed to be a format.
1709 function dateFormat( $usePrefs = true ) {
1712 if ( is_bool( $usePrefs ) ) {
1714 $datePreference = $wgUser->getDatePreference();
1716 $datePreference = (string)User
::getDefaultOption( 'date' );
1719 $datePreference = (string)$usePrefs;
1723 if ( $datePreference == '' ) {
1727 return $datePreference;
1731 * Get a format string for a given type and preference
1732 * @param $type string May be date, time or both
1733 * @param $pref string The format name as it appears in Messages*.php
1737 function getDateFormatString( $type, $pref ) {
1738 if ( !isset( $this->dateFormatStrings
[$type][$pref] ) ) {
1739 if ( $pref == 'default' ) {
1740 $pref = $this->getDefaultDateFormat();
1741 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1743 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1744 if ( is_null( $df ) ) {
1745 $pref = $this->getDefaultDateFormat();
1746 $df = self
::$dataCache->getSubitem( $this->mCode
, 'dateFormats', "$pref $type" );
1749 $this->dateFormatStrings
[$type][$pref] = $df;
1751 return $this->dateFormatStrings
[$type][$pref];
1755 * @param $ts Mixed: the time format which needs to be turned into a
1756 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1757 * @param $adj Bool: whether to adjust the time output according to the
1758 * user configured offset ($timecorrection)
1759 * @param $format Mixed: true to use user's date format preference
1760 * @param $timecorrection String|bool the time offset as returned by
1761 * validateTimeZone() in Special:Preferences
1764 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1765 $ts = wfTimestamp( TS_MW
, $ts );
1767 $ts = $this->userAdjust( $ts, $timecorrection );
1769 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1770 return $this->sprintfDate( $df, $ts );
1774 * @param $ts Mixed: the time format which needs to be turned into a
1775 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1776 * @param $adj Bool: whether to adjust the time output according to the
1777 * user configured offset ($timecorrection)
1778 * @param $format Mixed: true to use user's date format preference
1779 * @param $timecorrection String|bool the time offset as returned by
1780 * validateTimeZone() in Special:Preferences
1783 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1784 $ts = wfTimestamp( TS_MW
, $ts );
1786 $ts = $this->userAdjust( $ts, $timecorrection );
1788 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1789 return $this->sprintfDate( $df, $ts );
1793 * @param $ts Mixed: the time format which needs to be turned into a
1794 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1795 * @param $adj Bool: whether to adjust the time output according to the
1796 * user configured offset ($timecorrection)
1797 * @param $format Mixed: what format to return, if it's false output the
1798 * default one (default true)
1799 * @param $timecorrection String|bool the time offset as returned by
1800 * validateTimeZone() in Special:Preferences
1803 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1804 $ts = wfTimestamp( TS_MW
, $ts );
1806 $ts = $this->userAdjust( $ts, $timecorrection );
1808 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1809 return $this->sprintfDate( $df, $ts );
1813 * @param $key string
1814 * @return array|null
1816 function getMessage( $key ) {
1817 return self
::$dataCache->getSubitem( $this->mCode
, 'messages', $key );
1823 function getAllMessages() {
1824 return self
::$dataCache->getItem( $this->mCode
, 'messages' );
1833 function iconv( $in, $out, $string ) {
1834 # This is a wrapper for iconv in all languages except esperanto,
1835 # which does some nasty x-conversions beforehand
1837 # Even with //IGNORE iconv can whine about illegal characters in
1838 # *input* string. We just ignore those too.
1839 # REF: http://bugs.php.net/bug.php?id=37166
1840 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1841 wfSuppressWarnings();
1842 $text = iconv( $in, $out . '//IGNORE', $string );
1843 wfRestoreWarnings();
1847 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1850 * @param $matches array
1851 * @return mixed|string
1853 function ucwordbreaksCallbackAscii( $matches ) {
1854 return $this->ucfirst( $matches[1] );
1858 * @param $matches array
1861 function ucwordbreaksCallbackMB( $matches ) {
1862 return mb_strtoupper( $matches[0] );
1866 * @param $matches array
1869 function ucCallback( $matches ) {
1870 list( $wikiUpperChars ) = self
::getCaseMaps();
1871 return strtr( $matches[1], $wikiUpperChars );
1875 * @param $matches array
1878 function lcCallback( $matches ) {
1879 list( , $wikiLowerChars ) = self
::getCaseMaps();
1880 return strtr( $matches[1], $wikiLowerChars );
1884 * @param $matches array
1887 function ucwordsCallbackMB( $matches ) {
1888 return mb_strtoupper( $matches[0] );
1892 * @param $matches array
1895 function ucwordsCallbackWiki( $matches ) {
1896 list( $wikiUpperChars ) = self
::getCaseMaps();
1897 return strtr( $matches[0], $wikiUpperChars );
1901 * Make a string's first character uppercase
1903 * @param $str string
1907 function ucfirst( $str ) {
1909 if ( $o < 96 ) { // if already uppercase...
1911 } elseif ( $o < 128 ) {
1912 return ucfirst( $str ); // use PHP's ucfirst()
1914 // fall back to more complex logic in case of multibyte strings
1915 return $this->uc( $str, true );
1920 * Convert a string to uppercase
1922 * @param $str string
1923 * @param $first bool
1927 function uc( $str, $first = false ) {
1928 if ( function_exists( 'mb_strtoupper' ) ) {
1930 if ( $this->isMultibyte( $str ) ) {
1931 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1933 return ucfirst( $str );
1936 return $this->isMultibyte( $str ) ?
mb_strtoupper( $str ) : strtoupper( $str );
1939 if ( $this->isMultibyte( $str ) ) {
1940 $x = $first ?
'^' : '';
1941 return preg_replace_callback(
1942 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1943 array( $this, 'ucCallback' ),
1947 return $first ?
ucfirst( $str ) : strtoupper( $str );
1953 * @param $str string
1954 * @return mixed|string
1956 function lcfirst( $str ) {
1959 return strval( $str );
1960 } elseif ( $o >= 128 ) {
1961 return $this->lc( $str, true );
1962 } elseif ( $o > 96 ) {
1965 $str[0] = strtolower( $str[0] );
1971 * @param $str string
1972 * @param $first bool
1973 * @return mixed|string
1975 function lc( $str, $first = false ) {
1976 if ( function_exists( 'mb_strtolower' ) ) {
1978 if ( $this->isMultibyte( $str ) ) {
1979 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1981 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1984 return $this->isMultibyte( $str ) ?
mb_strtolower( $str ) : strtolower( $str );
1987 if ( $this->isMultibyte( $str ) ) {
1988 $x = $first ?
'^' : '';
1989 return preg_replace_callback(
1990 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1991 array( $this, 'lcCallback' ),
1995 return $first ?
strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2001 * @param $str string
2004 function isMultibyte( $str ) {
2005 return (bool)preg_match( '/[\x80-\xff]/', $str );
2009 * @param $str string
2010 * @return mixed|string
2012 function ucwords( $str ) {
2013 if ( $this->isMultibyte( $str ) ) {
2014 $str = $this->lc( $str );
2016 // regexp to find first letter in each word (i.e. after each space)
2017 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2019 // function to use to capitalize a single char
2020 if ( function_exists( 'mb_strtoupper' ) ) {
2021 return preg_replace_callback(
2023 array( $this, 'ucwordsCallbackMB' ),
2027 return preg_replace_callback(
2029 array( $this, 'ucwordsCallbackWiki' ),
2034 return ucwords( strtolower( $str ) );
2039 * capitalize words at word breaks
2041 * @param $str string
2044 function ucwordbreaks( $str ) {
2045 if ( $this->isMultibyte( $str ) ) {
2046 $str = $this->lc( $str );
2048 // since \b doesn't work for UTF-8, we explicitely define word break chars
2049 $breaks = "[ \-\(\)\}\{\.,\?!]";
2051 // find first letter after word break
2052 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2054 if ( function_exists( 'mb_strtoupper' ) ) {
2055 return preg_replace_callback(
2057 array( $this, 'ucwordbreaksCallbackMB' ),
2061 return preg_replace_callback(
2063 array( $this, 'ucwordsCallbackWiki' ),
2068 return preg_replace_callback(
2069 '/\b([\w\x80-\xff]+)\b/',
2070 array( $this, 'ucwordbreaksCallbackAscii' ),
2077 * Return a case-folded representation of $s
2079 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2080 * and $s2 are the same except for the case of their characters. It is not
2081 * necessary for the value returned to make sense when displayed.
2083 * Do *not* perform any other normalisation in this function. If a caller
2084 * uses this function when it should be using a more general normalisation
2085 * function, then fix the caller.
2091 function caseFold( $s ) {
2092 return $this->uc( $s );
2099 function checkTitleEncoding( $s ) {
2100 if ( is_array( $s ) ) {
2101 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2103 # Check for non-UTF-8 URLs
2104 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2109 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2110 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2115 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2121 function fallback8bitEncoding() {
2122 return self
::$dataCache->getItem( $this->mCode
, 'fallback8bitEncoding' );
2126 * Most writing systems use whitespace to break up words.
2127 * Some languages such as Chinese don't conventionally do this,
2128 * which requires special handling when breaking up words for
2133 function hasWordBreaks() {
2138 * Some languages such as Chinese require word segmentation,
2139 * Specify such segmentation when overridden in derived class.
2141 * @param $string String
2144 function segmentByWord( $string ) {
2149 * Some languages have special punctuation need to be normalized.
2150 * Make such changes here.
2152 * @param $string String
2155 function normalizeForSearch( $string ) {
2156 return self
::convertDoubleWidth( $string );
2160 * convert double-width roman characters to single-width.
2161 * range: ff00-ff5f ~= 0020-007f
2163 * @param $string string
2167 protected static function convertDoubleWidth( $string ) {
2168 static $full = null;
2169 static $half = null;
2171 if ( $full === null ) {
2172 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2173 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2174 $full = str_split( $fullWidth, 3 );
2175 $half = str_split( $halfWidth );
2178 $string = str_replace( $full, $half, $string );
2183 * @param $string string
2184 * @param $pattern string
2187 protected static function insertSpace( $string, $pattern ) {
2188 $string = preg_replace( $pattern, " $1 ", $string );
2189 $string = preg_replace( '/ +/', ' ', $string );
2194 * @param $termsArray array
2197 function convertForSearchResult( $termsArray ) {
2198 # some languages, e.g. Chinese, need to do a conversion
2199 # in order for search results to be displayed correctly
2204 * Get the first character of a string.
2209 function firstChar( $s ) {
2212 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2213 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2218 if ( isset( $matches[1] ) ) {
2219 if ( strlen( $matches[1] ) != 3 ) {
2223 // Break down Hangul syllables to grab the first jamo
2224 $code = utf8ToCodepoint( $matches[1] );
2225 if ( $code < 0xac00 ||
0xd7a4 <= $code ) {
2227 } elseif ( $code < 0xb098 ) {
2228 return "\xe3\x84\xb1";
2229 } elseif ( $code < 0xb2e4 ) {
2230 return "\xe3\x84\xb4";
2231 } elseif ( $code < 0xb77c ) {
2232 return "\xe3\x84\xb7";
2233 } elseif ( $code < 0xb9c8 ) {
2234 return "\xe3\x84\xb9";
2235 } elseif ( $code < 0xbc14 ) {
2236 return "\xe3\x85\x81";
2237 } elseif ( $code < 0xc0ac ) {
2238 return "\xe3\x85\x82";
2239 } elseif ( $code < 0xc544 ) {
2240 return "\xe3\x85\x85";
2241 } elseif ( $code < 0xc790 ) {
2242 return "\xe3\x85\x87";
2243 } elseif ( $code < 0xcc28 ) {
2244 return "\xe3\x85\x88";
2245 } elseif ( $code < 0xce74 ) {
2246 return "\xe3\x85\x8a";
2247 } elseif ( $code < 0xd0c0 ) {
2248 return "\xe3\x85\x8b";
2249 } elseif ( $code < 0xd30c ) {
2250 return "\xe3\x85\x8c";
2251 } elseif ( $code < 0xd558 ) {
2252 return "\xe3\x85\x8d";
2254 return "\xe3\x85\x8e";
2261 function initEncoding() {
2262 # Some languages may have an alternate char encoding option
2263 # (Esperanto X-coding, Japanese furigana conversion, etc)
2264 # If this language is used as the primary content language,
2265 # an override to the defaults can be set here on startup.
2272 function recodeForEdit( $s ) {
2273 # For some languages we'll want to explicitly specify
2274 # which characters make it into the edit box raw
2275 # or are converted in some way or another.
2276 global $wgEditEncoding;
2277 if ( $wgEditEncoding == '' ||
$wgEditEncoding == 'UTF-8' ) {
2280 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2288 function recodeInput( $s ) {
2289 # Take the previous into account.
2290 global $wgEditEncoding;
2291 if ( $wgEditEncoding != '' ) {
2292 $enc = $wgEditEncoding;
2296 if ( $enc == 'UTF-8' ) {
2299 return $this->iconv( $enc, 'UTF-8', $s );
2304 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2305 * also cleans up certain backwards-compatible sequences, converting them
2306 * to the modern Unicode equivalent.
2308 * This is language-specific for performance reasons only.
2314 function normalize( $s ) {
2315 global $wgAllUnicodeFixes;
2316 $s = UtfNormal
::cleanUp( $s );
2317 if ( $wgAllUnicodeFixes ) {
2318 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2319 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2326 * Transform a string using serialized data stored in the given file (which
2327 * must be in the serialized subdirectory of $IP). The file contains pairs
2328 * mapping source characters to destination characters.
2330 * The data is cached in process memory. This will go faster if you have the
2331 * FastStringSearch extension.
2333 * @param $file string
2334 * @param $string string
2338 function transformUsingPairFile( $file, $string ) {
2339 if ( !isset( $this->transformData
[$file] ) ) {
2340 $data = wfGetPrecompiledData( $file );
2341 if ( $data === false ) {
2342 throw new MWException( __METHOD__
. ": The transformation file $file is missing" );
2344 $this->transformData
[$file] = new ReplacementArray( $data );
2346 return $this->transformData
[$file]->replace( $string );
2350 * For right-to-left language support
2355 return self
::$dataCache->getItem( $this->mCode
, 'rtl' );
2359 * Return the correct HTML 'dir' attribute value for this language.
2363 return $this->isRTL() ?
'rtl' : 'ltr';
2367 * Return 'left' or 'right' as appropriate alignment for line-start
2368 * for this language's text direction.
2370 * Should be equivalent to CSS3 'start' text-align value....
2374 function alignStart() {
2375 return $this->isRTL() ?
'right' : 'left';
2379 * Return 'right' or 'left' as appropriate alignment for line-end
2380 * for this language's text direction.
2382 * Should be equivalent to CSS3 'end' text-align value....
2386 function alignEnd() {
2387 return $this->isRTL() ?
'left' : 'right';
2391 * A hidden direction mark (LRM or RLM), depending on the language direction
2393 * @param $opposite Boolean Get the direction mark opposite to your language
2396 function getDirMark( $opposite = false ) {
2397 $rtl = "\xE2\x80\x8F";
2398 $ltr = "\xE2\x80\x8E";
2399 if( $opposite ) { return $this->isRTL() ?
$ltr : $rtl; }
2400 return $this->isRTL() ?
$rtl : $ltr;
2406 function capitalizeAllNouns() {
2407 return self
::$dataCache->getItem( $this->mCode
, 'capitalizeAllNouns' );
2411 * An arrow, depending on the language direction
2415 function getArrow() {
2416 return $this->isRTL() ?
'←' : '→';
2420 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2424 function linkPrefixExtension() {
2425 return self
::$dataCache->getItem( $this->mCode
, 'linkPrefixExtension' );
2431 function getMagicWords() {
2432 return self
::$dataCache->getItem( $this->mCode
, 'magicWords' );
2435 protected function doMagicHook() {
2436 if ( $this->mMagicHookDone
) {
2439 $this->mMagicHookDone
= true;
2440 wfProfileIn( 'LanguageGetMagic' );
2441 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions
, $this->getCode() ) );
2442 wfProfileOut( 'LanguageGetMagic' );
2446 * Fill a MagicWord object with data from here
2450 function getMagic( $mw ) {
2451 $this->doMagicHook();
2453 if ( isset( $this->mMagicExtensions
[$mw->mId
] ) ) {
2454 $rawEntry = $this->mMagicExtensions
[$mw->mId
];
2456 $magicWords = $this->getMagicWords();
2457 if ( isset( $magicWords[$mw->mId
] ) ) {
2458 $rawEntry = $magicWords[$mw->mId
];
2464 if ( !is_array( $rawEntry ) ) {
2465 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2467 $mw->mCaseSensitive
= $rawEntry[0];
2468 $mw->mSynonyms
= array_slice( $rawEntry, 1 );
2473 * Add magic words to the extension array
2475 * @param $newWords array
2477 function addMagicWordsByLang( $newWords ) {
2478 $fallbackChain = $this->getFallbackLanguages();
2479 $fallbackChain = array_reverse( $fallbackChain );
2480 foreach ( $fallbackChain as $code ) {
2481 if ( isset( $newWords[$code] ) ) {
2482 $this->mMagicExtensions
= $newWords[$code] +
$this->mMagicExtensions
;
2488 * Get special page names, as an associative array
2489 * case folded alias => real name
2491 function getSpecialPageAliases() {
2492 // Cache aliases because it may be slow to load them
2493 if ( is_null( $this->mExtendedSpecialPageAliases
) ) {
2495 $this->mExtendedSpecialPageAliases
=
2496 self
::$dataCache->getItem( $this->mCode
, 'specialPageAliases' );
2497 wfRunHooks( 'LanguageGetSpecialPageAliases',
2498 array( &$this->mExtendedSpecialPageAliases
, $this->getCode() ) );
2501 return $this->mExtendedSpecialPageAliases
;
2505 * Italic is unsuitable for some languages
2507 * @param $text String: the text to be emphasized.
2510 function emphasize( $text ) {
2511 return "<em>$text</em>";
2515 * Normally we output all numbers in plain en_US style, that is
2516 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2517 * point twohundredthirtyfive. However this is not suitable for all
2518 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2519 * Icelandic just want to use commas instead of dots, and dots instead
2520 * of commas like "293.291,235".
2522 * An example of this function being called:
2524 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2527 * See LanguageGu.php for the Gujarati implementation and
2528 * $separatorTransformTable on MessageIs.php for
2529 * the , => . and . => , implementation.
2531 * @todo check if it's viable to use localeconv() for the decimal
2533 * @param $number Mixed: the string to be formatted, should be an integer
2534 * or a floating point number.
2535 * @param $nocommafy Bool: set to true for special numbers like dates
2538 function formatNum( $number, $nocommafy = false ) {
2539 global $wgTranslateNumerals;
2540 if ( !$nocommafy ) {
2541 $number = $this->commafy( $number );
2542 $s = $this->separatorTransformTable();
2544 $number = strtr( $number, $s );
2548 if ( $wgTranslateNumerals ) {
2549 $s = $this->digitTransformTable();
2551 $number = strtr( $number, $s );
2559 * @param $number string
2562 function parseFormattedNumber( $number ) {
2563 $s = $this->digitTransformTable();
2565 $number = strtr( $number, array_flip( $s ) );
2568 $s = $this->separatorTransformTable();
2570 $number = strtr( $number, array_flip( $s ) );
2573 $number = strtr( $number, array( ',' => '' ) );
2578 * Adds commas to a given number
2583 function commafy( $_ ) {
2584 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2590 function digitTransformTable() {
2591 return self
::$dataCache->getItem( $this->mCode
, 'digitTransformTable' );
2597 function separatorTransformTable() {
2598 return self
::$dataCache->getItem( $this->mCode
, 'separatorTransformTable' );
2602 * Take a list of strings and build a locale-friendly comma-separated
2603 * list, using the local comma-separator message.
2604 * The last two strings are chained with an "and".
2609 function listToText( $l ) {
2611 $m = count( $l ) - 1;
2613 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2615 for ( $i = $m; $i >= 0; $i-- ) {
2618 } elseif ( $i == $m - 1 ) {
2619 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2621 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2629 * Take a list of strings and build a locale-friendly comma-separated
2630 * list, using the local comma-separator message.
2631 * @param $list array of strings to put in a comma list
2634 function commaList( $list ) {
2639 array( 'parsemag', 'escapenoentities', 'language' => $this )
2645 * Take a list of strings and build a locale-friendly semicolon-separated
2646 * list, using the local semicolon-separator message.
2647 * @param $list array of strings to put in a semicolon list
2650 function semicolonList( $list ) {
2654 'semicolon-separator',
2655 array( 'parsemag', 'escapenoentities', 'language' => $this )
2661 * Same as commaList, but separate it with the pipe instead.
2662 * @param $list array of strings to put in a pipe list
2665 function pipeList( $list ) {
2670 array( 'escapenoentities', 'language' => $this )
2676 * Truncate a string to a specified length in bytes, appending an optional
2677 * string (e.g. for ellipses)
2679 * The database offers limited byte lengths for some columns in the database;
2680 * multi-byte character sets mean we need to ensure that only whole characters
2681 * are included, otherwise broken characters can be passed to the user
2683 * If $length is negative, the string will be truncated from the beginning
2685 * @param $string String to truncate
2686 * @param $length Int: maximum length (including ellipses)
2687 * @param $ellipsis String to append to the truncated text
2688 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2689 * $adjustLength was introduced in 1.18, before that behaved as if false.
2692 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2693 # Use the localized ellipsis character
2694 if ( $ellipsis == '...' ) {
2695 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2697 # Check if there is no need to truncate
2698 if ( $length == 0 ) {
2699 return $ellipsis; // convention
2700 } elseif ( strlen( $string ) <= abs( $length ) ) {
2701 return $string; // no need to truncate
2703 $stringOriginal = $string;
2704 # If ellipsis length is >= $length then we can't apply $adjustLength
2705 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2706 $string = $ellipsis; // this can be slightly unexpected
2707 # Otherwise, truncate and add ellipsis...
2709 $eLength = $adjustLength ?
strlen( $ellipsis ) : 0;
2710 if ( $length > 0 ) {
2711 $length -= $eLength;
2712 $string = substr( $string, 0, $length ); // xyz...
2713 $string = $this->removeBadCharLast( $string );
2714 $string = $string . $ellipsis;
2716 $length +
= $eLength;
2717 $string = substr( $string, $length ); // ...xyz
2718 $string = $this->removeBadCharFirst( $string );
2719 $string = $ellipsis . $string;
2722 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2723 # This check is *not* redundant if $adjustLength, due to the single case where
2724 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2725 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2728 return $stringOriginal;
2733 * Remove bytes that represent an incomplete Unicode character
2734 * at the end of string (e.g. bytes of the char are missing)
2736 * @param $string String
2739 protected function removeBadCharLast( $string ) {
2740 if ( $string != '' ) {
2741 $char = ord( $string[strlen( $string ) - 1] );
2743 if ( $char >= 0xc0 ) {
2744 # We got the first byte only of a multibyte char; remove it.
2745 $string = substr( $string, 0, -1 );
2746 } elseif ( $char >= 0x80 &&
2747 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2748 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2750 # We chopped in the middle of a character; remove it
2758 * Remove bytes that represent an incomplete Unicode character
2759 * at the start of string (e.g. bytes of the char are missing)
2761 * @param $string String
2764 protected function removeBadCharFirst( $string ) {
2765 if ( $string != '' ) {
2766 $char = ord( $string[0] );
2767 if ( $char >= 0x80 && $char < 0xc0 ) {
2768 # We chopped in the middle of a character; remove the whole thing
2769 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2776 * Truncate a string of valid HTML to a specified length in bytes,
2777 * appending an optional string (e.g. for ellipses), and return valid HTML
2779 * This is only intended for styled/linked text, such as HTML with
2780 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2781 * Also, this will not detect things like "display:none" CSS.
2783 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2785 * @param string $text HTML string to truncate
2786 * @param int $length (zero/positive) Maximum length (including ellipses)
2787 * @param string $ellipsis String to append to the truncated text
2790 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2791 # Use the localized ellipsis character
2792 if ( $ellipsis == '...' ) {
2793 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2795 # Check if there is clearly no need to truncate
2796 if ( $length <= 0 ) {
2797 return $ellipsis; // no text shown, nothing to format (convention)
2798 } elseif ( strlen( $text ) <= $length ) {
2799 return $text; // string short enough even *with* HTML (short-circuit)
2802 $dispLen = 0; // innerHTML legth so far
2803 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2804 $tagType = 0; // 0-open, 1-close
2805 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2806 $entityState = 0; // 0-not entity, 1-entity
2807 $tag = $ret = ''; // accumulated tag name, accumulated result string
2808 $openTags = array(); // open tag stack
2809 $maybeState = null; // possible truncation state
2811 $textLen = strlen( $text );
2812 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2813 for ( $pos = 0; true; ++
$pos ) {
2814 # Consider truncation once the display length has reached the maximim.
2815 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2816 # Check that we're not in the middle of a bracket/entity...
2817 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2818 if ( !$testingEllipsis ) {
2819 $testingEllipsis = true;
2820 # Save where we are; we will truncate here unless there turn out to
2821 # be so few remaining characters that truncation is not necessary.
2822 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2823 $maybeState = array( $ret, $openTags ); // save state
2825 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2826 # String in fact does need truncation, the truncation point was OK.
2827 list( $ret, $openTags ) = $maybeState; // reload state
2828 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2829 $ret .= $ellipsis; // add ellipsis
2833 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2835 # Read the next char...
2837 $lastCh = $pos ?
$text[$pos - 1] : '';
2838 $ret .= $ch; // add to result string
2840 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2841 $entityState = 0; // for bad HTML
2842 $bracketState = 1; // tag started (checking for backslash)
2843 } elseif ( $ch == '>' ) {
2844 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2845 $entityState = 0; // for bad HTML
2846 $bracketState = 0; // out of brackets
2847 } elseif ( $bracketState == 1 ) {
2849 $tagType = 1; // close tag (e.g. "</span>")
2851 $tagType = 0; // open tag (e.g. "<span>")
2854 $bracketState = 2; // building tag name
2855 } elseif ( $bracketState == 2 ) {
2859 // Name found (e.g. "<a href=..."), add on tag attributes...
2860 $pos +
= $this->truncate_skip( $ret, $text, "<>", $pos +
1 );
2862 } elseif ( $bracketState == 0 ) {
2863 if ( $entityState ) {
2866 $dispLen++
; // entity is one displayed char
2869 if ( $neLength == 0 && !$maybeState ) {
2870 // Save state without $ch. We want to *hit* the first
2871 // display char (to get tags) but not *use* it if truncating.
2872 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2875 $entityState = 1; // entity found, (e.g. " ")
2877 $dispLen++
; // this char is displayed
2878 // Add the next $max display text chars after this in one swoop...
2879 $max = ( $testingEllipsis ?
$length : $neLength ) - $dispLen;
2880 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos +
1, $max );
2881 $dispLen +
= $skipped;
2887 // Close the last tag if left unclosed by bad HTML
2888 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2889 while ( count( $openTags ) > 0 ) {
2890 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2896 * truncateHtml() helper function
2897 * like strcspn() but adds the skipped chars to $ret
2906 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2907 if ( $len === null ) {
2908 $len = -1; // -1 means "no limit" for strcspn
2909 } elseif ( $len < 0 ) {
2913 if ( $start < strlen( $text ) ) {
2914 $skipCount = strcspn( $text, $search, $start, $len );
2915 $ret .= substr( $text, $start, $skipCount );
2921 * truncateHtml() helper function
2922 * (a) push or pop $tag from $openTags as needed
2923 * (b) clear $tag value
2924 * @param String &$tag Current HTML tag name we are looking at
2925 * @param int $tagType (0-open tag, 1-close tag)
2926 * @param char $lastCh Character before the '>' that ended this tag
2927 * @param array &$openTags Open tag stack (not accounting for $tag)
2929 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2930 $tag = ltrim( $tag );
2932 if ( $tagType == 0 && $lastCh != '/' ) {
2933 $openTags[] = $tag; // tag opened (didn't close itself)
2934 } elseif ( $tagType == 1 ) {
2935 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2936 array_pop( $openTags ); // tag closed
2944 * Grammatical transformations, needed for inflected languages
2945 * Invoked by putting {{grammar:case|word}} in a message
2947 * @param $word string
2948 * @param $case string
2951 function convertGrammar( $word, $case ) {
2952 global $wgGrammarForms;
2953 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2954 return $wgGrammarForms[$this->getCode()][$case][$word];
2960 * Provides an alternative text depending on specified gender.
2961 * Usage {{gender:username|masculine|feminine|neutral}}.
2962 * username is optional, in which case the gender of current user is used,
2963 * but only in (some) interface messages; otherwise default gender is used.
2964 * If second or third parameter are not specified, masculine is used.
2965 * These details may be overriden per language.
2967 * @param $gender string
2968 * @param $forms array
2972 function gender( $gender, $forms ) {
2973 if ( !count( $forms ) ) {
2976 $forms = $this->preConvertPlural( $forms, 2 );
2977 if ( $gender === 'male' ) {
2980 if ( $gender === 'female' ) {
2983 return isset( $forms[2] ) ?
$forms[2] : $forms[0];
2987 * Plural form transformations, needed for some languages.
2988 * For example, there are 3 form of plural in Russian and Polish,
2989 * depending on "count mod 10". See [[w:Plural]]
2990 * For English it is pretty simple.
2992 * Invoked by putting {{plural:count|wordform1|wordform2}}
2993 * or {{plural:count|wordform1|wordform2|wordform3}}
2995 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2997 * @param $count Integer: non-localized number
2998 * @param $forms Array: different plural forms
2999 * @return string Correct form of plural for $count in this language
3001 function convertPlural( $count, $forms ) {
3002 if ( !count( $forms ) ) {
3005 $forms = $this->preConvertPlural( $forms, 2 );
3007 return ( $count == 1 ) ?
$forms[0] : $forms[1];
3011 * Checks that convertPlural was given an array and pads it to requested
3012 * amount of forms by copying the last one.
3014 * @param $count Integer: How many forms should there be at least
3015 * @param $forms Array of forms given to convertPlural
3016 * @return array Padded array of forms or an exception if not an array
3018 protected function preConvertPlural( /* Array */ $forms, $count ) {
3019 while ( count( $forms ) < $count ) {
3020 $forms[] = $forms[count( $forms ) - 1];
3026 * This translates the duration ("1 week", "4 days", etc)
3027 * as well as the expiry time (which is an absolute timestamp).
3028 * @param $str String: the validated block duration in English
3029 * @return Somehow translated block duration
3030 * @see LanguageFi.php for example implementation
3032 function translateBlockExpiry( $str ) {
3033 $duration = SpecialBlock
::getSuggestedDurations( $this );
3034 foreach( $duration as $show => $value ){
3035 if ( strcmp( $str, $value ) == 0 ) {
3036 return htmlspecialchars( trim( $show ) );
3040 // Since usually only infinite or indefinite is only on list, so try
3041 // equivalents if still here.
3042 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3043 if ( in_array( $str, $indefs ) ) {
3044 foreach( $indefs as $val ) {
3045 $show = array_search( $val, $duration, true );
3046 if ( $show !== false ) {
3047 return htmlspecialchars( trim( $show ) );
3051 // If no duration is given, but a timestamp, display that
3052 return ( strtotime( $str ) ?
$this->timeanddate( strtotime( $str ) ) : $str );
3056 * languages like Chinese need to be segmented in order for the diff
3059 * @param $text String
3062 function segmentForDiff( $text ) {
3067 * and unsegment to show the result
3069 * @param $text String
3072 function unsegmentForDiff( $text ) {
3077 * convert text to all supported variants
3079 * @param $text string
3082 function autoConvertToAllVariants( $text ) {
3083 return $this->mConverter
->autoConvertToAllVariants( $text );
3087 * convert text to different variants of a language.
3089 * @param $text string
3092 function convert( $text ) {
3093 return $this->mConverter
->convert( $text );
3098 * Convert a Title object to a string in the preferred variant
3100 * @param $title Title
3103 function convertTitle( $title ) {
3104 return $this->mConverter
->convertTitle( $title );
3108 * Check if this is a language with variants
3112 function hasVariants() {
3113 return sizeof( $this->getVariants() ) > 1;
3117 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3119 * @param $text string
3122 function armourMath( $text ) {
3123 return $this->mConverter
->armourMath( $text );
3127 * Perform output conversion on a string, and encode for safe HTML output.
3128 * @param $text String text to be converted
3129 * @param $isTitle Bool whether this conversion is for the article title
3131 * @todo this should get integrated somewhere sane
3133 function convertHtml( $text, $isTitle = false ) {
3134 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3138 * @param $key string
3141 function convertCategoryKey( $key ) {
3142 return $this->mConverter
->convertCategoryKey( $key );
3146 * Get the list of variants supported by this language
3147 * see sample implementation in LanguageZh.php
3149 * @return array an array of language codes
3151 function getVariants() {
3152 return $this->mConverter
->getVariants();
3158 function getPreferredVariant() {
3159 return $this->mConverter
->getPreferredVariant();
3165 function getDefaultVariant() {
3166 return $this->mConverter
->getDefaultVariant();
3172 function getURLVariant() {
3173 return $this->mConverter
->getURLVariant();
3177 * If a language supports multiple variants, it is
3178 * possible that non-existing link in one variant
3179 * actually exists in another variant. this function
3180 * tries to find it. See e.g. LanguageZh.php
3182 * @param $link String: the name of the link
3183 * @param $nt Mixed: the title object of the link
3184 * @param $ignoreOtherCond Boolean: to disable other conditions when
3185 * we need to transclude a template or update a category's link
3186 * @return null the input parameters may be modified upon return
3188 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3189 $this->mConverter
->findVariantLink( $link, $nt, $ignoreOtherCond );
3193 * If a language supports multiple variants, converts text
3194 * into an array of all possible variants of the text:
3195 * 'variant' => text in that variant
3197 * @deprecated since 1.17 Use autoConvertToAllVariants()
3199 * @param $text string
3203 function convertLinkToAllVariants( $text ) {
3204 return $this->mConverter
->convertLinkToAllVariants( $text );
3208 * returns language specific options used by User::getPageRenderHash()
3209 * for example, the preferred language variant
3213 function getExtraHashOptions() {
3214 return $this->mConverter
->getExtraHashOptions();
3218 * For languages that support multiple variants, the title of an
3219 * article may be displayed differently in different variants. this
3220 * function returns the apporiate title defined in the body of the article.
3224 function getParsedTitle() {
3225 return $this->mConverter
->getParsedTitle();
3229 * Enclose a string with the "no conversion" tag. This is used by
3230 * various functions in the Parser
3232 * @param $text String: text to be tagged for no conversion
3233 * @param $noParse bool
3234 * @return string the tagged text
3236 function markNoConversion( $text, $noParse = false ) {
3237 return $this->mConverter
->markNoConversion( $text, $noParse );
3241 * A regular expression to match legal word-trailing characters
3242 * which should be merged onto a link of the form [[foo]]bar.
3246 function linkTrail() {
3247 return self
::$dataCache->getItem( $this->mCode
, 'linkTrail' );
3253 function getLangObj() {
3258 * Get the RFC 3066 code for this language object
3262 function getCode() {
3263 return $this->mCode
;
3267 * @param $code string
3269 function setCode( $code ) {
3270 $this->mCode
= $code;
3274 * Get the name of a file for a certain language code
3275 * @param $prefix string Prepend this to the filename
3276 * @param $code string Language code
3277 * @param $suffix string Append this to the filename
3278 * @return string $prefix . $mangledCode . $suffix
3280 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3281 // Protect against path traversal
3282 if ( !Language
::isValidCode( $code )
3283 ||
strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3285 throw new MWException( "Invalid language code \"$code\"" );
3288 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3292 * Get the language code from a file name. Inverse of getFileName()
3293 * @param $filename string $prefix . $languageCode . $suffix
3294 * @param $prefix string Prefix before the language code
3295 * @param $suffix string Suffix after the language code
3296 * @return string Language code, or false if $prefix or $suffix isn't found
3298 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3300 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3301 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3302 if ( !count( $m ) ) {
3305 return str_replace( '_', '-', strtolower( $m[1] ) );
3309 * @param $code string
3312 static function getMessagesFileName( $code ) {
3314 return self
::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3318 * @param $code string
3321 static function getClassFileName( $code ) {
3323 return self
::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3327 * Get the first fallback for a given language.
3329 * @param $code string
3331 * @return false|string
3333 static function getFallbackFor( $code ) {
3334 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3337 $fallbacks = self
::getFallbacksFor( $code );
3338 $first = array_shift( $fallbacks );
3344 * Get the ordered list of fallback languages.
3347 * @param $code string Language code
3350 static function getFallbacksFor( $code ) {
3351 if ( $code === 'en' ||
!Language
::isValidBuiltInCode( $code ) ) {
3354 $v = self
::getLocalisationCache()->getItem( $code, 'fallback' );
3355 $v = array_map( 'trim', explode( ',', $v ) );
3356 if ( $v[count( $v ) - 1] !== 'en' ) {
3364 * Get all messages for a given language
3365 * WARNING: this may take a long time
3367 * @param $code string
3371 static function getMessagesFor( $code ) {
3372 return self
::getLocalisationCache()->getItem( $code, 'messages' );
3376 * Get a message for a given language
3378 * @param $key string
3379 * @param $code string
3383 static function getMessageFor( $key, $code ) {
3384 return self
::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3391 function fixVariableInNamespace( $talk ) {
3392 if ( strpos( $talk, '$1' ) === false ) {
3396 global $wgMetaNamespace;
3397 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3399 # Allow grammar transformations
3400 # Allowing full message-style parsing would make simple requests
3401 # such as action=raw much more expensive than they need to be.
3402 # This will hopefully cover most cases.
3403 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3404 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3405 return str_replace( ' ', '_', $talk );
3412 function replaceGrammarInNamespace( $m ) {
3413 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3417 * @throws MWException
3420 static function getCaseMaps() {
3421 static $wikiUpperChars, $wikiLowerChars;
3422 if ( isset( $wikiUpperChars ) ) {
3423 return array( $wikiUpperChars, $wikiLowerChars );
3426 wfProfileIn( __METHOD__
);
3427 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3428 if ( $arr === false ) {
3429 throw new MWException(
3430 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3432 $wikiUpperChars = $arr['wikiUpperChars'];
3433 $wikiLowerChars = $arr['wikiLowerChars'];
3434 wfProfileOut( __METHOD__
);
3435 return array( $wikiUpperChars, $wikiLowerChars );
3439 * Decode an expiry (block, protection, etc) which has come from the DB
3441 * @param $expiry String: Database expiry String
3442 * @param $format Bool|Int true to process using language functions, or TS_ constant
3443 * to return the expiry in a given timestamp
3446 public function formatExpiry( $expiry, $format = true ) {
3447 static $infinity, $infinityMsg;
3448 if( $infinity === null ){
3449 $infinityMsg = wfMessage( 'infiniteblock' );
3450 $infinity = wfGetDB( DB_SLAVE
)->getInfinity();
3453 if ( $expiry == '' ||
$expiry == $infinity ) {
3454 return $format === true
3458 return $format === true
3459 ?
$this->timeanddate( $expiry )
3460 : wfTimestamp( $format, $expiry );
3466 * @param $seconds int|float
3467 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3468 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3469 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3472 function formatTimePeriod( $seconds, $format = false ) {
3473 if ( round( $seconds * 10 ) < 100 ) {
3474 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3475 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3476 } elseif ( round( $seconds ) < 60 ) {
3477 $s = $this->formatNum( round( $seconds ) );
3478 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3479 } elseif ( round( $seconds ) < 3600 ) {
3480 $minutes = floor( $seconds / 60 );
3481 $secondsPart = round( fmod( $seconds, 60 ) );
3482 if ( $secondsPart == 60 ) {
3486 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3488 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3489 } elseif ( round( $seconds ) <= 2*86400 ) {
3490 $hours = floor( $seconds / 3600 );
3491 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3492 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3493 if ( $secondsPart == 60 ) {
3497 if ( $minutes == 60 ) {
3501 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3503 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3504 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3505 $s .= ' ' . $this->formatNum( $secondsPart ) .
3506 $this->getMessageFromDB( 'seconds-abbrev' );
3509 $days = floor( $seconds / 86400 );
3510 if ( $format === 'avoidminutes' ) {
3511 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3512 if ( $hours == 24 ) {
3516 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3518 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3519 } elseif ( $format === 'avoidseconds' ) {
3520 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3521 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3522 if ( $minutes == 60 ) {
3526 if ( $hours == 24 ) {
3530 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3532 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3534 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3536 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3538 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3548 function formatBitrate( $bps ) {
3549 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3551 return $this->formatNum( $bps ) . $units[0];
3553 $unitIndex = floor( log10( $bps ) / 3 );
3554 $mantissa = $bps / pow( 1000, $unitIndex );
3555 if ( $mantissa < 10 ) {
3556 $mantissa = round( $mantissa, 1 );
3558 $mantissa = round( $mantissa );
3560 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3564 * Format a size in bytes for output, using an appropriate
3565 * unit (B, KB, MB or GB) according to the magnitude in question
3567 * @param $size int Size to format
3568 * @return string Plain text (not HTML)
3570 function formatSize( $size ) {
3571 // For small sizes no decimal places necessary
3573 if ( $size > 1024 ) {
3574 $size = $size / 1024;
3575 if ( $size > 1024 ) {
3576 $size = $size / 1024;
3577 // For MB and bigger two decimal places are smarter
3579 if ( $size > 1024 ) {
3580 $size = $size / 1024;
3581 $msg = 'size-gigabytes';
3583 $msg = 'size-megabytes';
3586 $msg = 'size-kilobytes';
3589 $msg = 'size-bytes';
3591 $size = round( $size, $round );
3592 $text = $this->getMessageFromDB( $msg );
3593 return str_replace( '$1', $this->formatNum( $size ), $text );
3597 * Get the conversion rule title, if any.
3601 function getConvRuleTitle() {
3602 return $this->mConverter
->getConvRuleTitle();