Update migrateUserGroup to deal with primary key issue
[mediawiki.git] / languages / Language.php
blobb531f2a376c4ece038cea40d1c0915b0b091b062
1 <?php
2 /**
3 * Internationalisation code.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Language
24 /**
25 * @defgroup Language Language
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
30 exit( 1 );
33 # Read language names
34 global $wgLanguageNames;
35 require_once( dirname( __FILE__ ) . '/Names.php' );
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
41 /**
42 * a fake language converter
44 * @ingroup Language
46 class FakeConverter {
48 /**
49 * @var Language
51 var $mLang;
52 function __construct( $langobj ) { $this->mLang = $langobj; }
53 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
54 function convert( $t ) { return $t; }
55 function convertTo( $text, $variant ) { return $text; }
56 function convertTitle( $t ) { return $t->getPrefixedText(); }
57 function getVariants() { return array( $this->mLang->getCode() ); }
58 function getPreferredVariant() { return $this->mLang->getCode(); }
59 function getDefaultVariant() { return $this->mLang->getCode(); }
60 function getURLVariant() { return ''; }
61 function getConvRuleTitle() { return false; }
62 function findVariantLink( &$l, &$n, $ignoreOtherCond = false ) { }
63 function getExtraHashOptions() { return ''; }
64 function getParsedTitle() { return ''; }
65 function markNoConversion( $text, $noParse = false ) { return $text; }
66 function convertCategoryKey( $key ) { return $key; }
67 function convertLinkToAllVariants( $text ) { return $this->autoConvertToAllVariants( $text ); }
68 function armourMath( $text ) { return $text; }
71 /**
72 * Internationalisation code
73 * @ingroup Language
75 class Language {
77 /**
78 * @var LanguageConverter
80 var $mConverter;
82 var $mVariants, $mCode, $mLoaded = false;
83 var $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
86 var $dateFormatStrings = array();
87 var $mExtendedSpecialPageAliases;
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
91 /**
92 * ReplacementArray object caches
94 var $transformData = array();
96 /**
97 * @var LocalisationCache
99 static public $dataCache;
101 static public $mLangObjCache = array();
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
105 'friday', 'saturday'
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
115 'december'
117 static public $mMonthGenMsgs = array(
118 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
119 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
120 'december-gen'
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
127 static public $mIranianCalendarMonthMsgs = array(
128 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
129 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
130 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
131 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
134 static public $mHebrewCalendarMonthMsgs = array(
135 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
136 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
137 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
138 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
139 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
142 static public $mHebrewCalendarMonthGenMsgs = array(
143 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
144 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
145 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
146 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
147 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
150 static public $mHijriCalendarMonthMsgs = array(
151 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
152 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
153 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
154 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
158 * @since 1.20
159 * @var array
161 static public $durationIntervals = array(
162 'millennia' => 31557600000,
163 'centuries' => 3155760000,
164 'decades' => 315576000,
165 'years' => 31557600, // 86400 * 365.25
166 'weeks' => 604800,
167 'days' => 86400,
168 'hours' => 3600,
169 'minutes' => 60,
170 'seconds' => 1,
174 * Get a cached language object for a given language code
175 * @param $code String
176 * @return Language
178 static function factory( $code ) {
179 if ( !isset( self::$mLangObjCache[$code] ) ) {
180 if ( count( self::$mLangObjCache ) > 10 ) {
181 // Don't keep a billion objects around, that's stupid.
182 self::$mLangObjCache = array();
184 self::$mLangObjCache[$code] = self::newFromCode( $code );
186 return self::$mLangObjCache[$code];
190 * Create a language object for a given language code
191 * @param $code String
192 * @throws MWException
193 * @return Language
195 protected static function newFromCode( $code ) {
196 // Protect against path traversal below
197 if ( !Language::isValidCode( $code )
198 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
200 throw new MWException( "Invalid language code \"$code\"" );
203 if ( !Language::isValidBuiltInCode( $code ) ) {
204 // It's not possible to customise this code with class files, so
205 // just return a Language object. This is to support uselang= hacks.
206 $lang = new Language;
207 $lang->setCode( $code );
208 return $lang;
211 // Check if there is a language class for the code
212 $class = self::classFromCode( $code );
213 self::preloadLanguageClass( $class );
214 if ( MWInit::classExists( $class ) ) {
215 $lang = new $class;
216 return $lang;
219 // Keep trying the fallback list until we find an existing class
220 $fallbacks = Language::getFallbacksFor( $code );
221 foreach ( $fallbacks as $fallbackCode ) {
222 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
223 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
226 $class = self::classFromCode( $fallbackCode );
227 self::preloadLanguageClass( $class );
228 if ( MWInit::classExists( $class ) ) {
229 $lang = Language::newFromCode( $fallbackCode );
230 $lang->setCode( $code );
231 return $lang;
235 throw new MWException( "Invalid fallback sequence for language '$code'" );
239 * Returns true if a language code string is of a valid form, whether or
240 * not it exists. This includes codes which are used solely for
241 * customisation via the MediaWiki namespace.
243 * @param $code string
245 * @return bool
247 public static function isValidCode( $code ) {
248 return
249 strcspn( $code, ":/\\\000" ) === strlen( $code )
250 && !preg_match( Title::getTitleInvalidRegex(), $code );
254 * Returns true if a language code is of a valid form for the purposes of
255 * internal customisation of MediaWiki, via Messages*.php.
257 * @param $code string
259 * @throws MWException
260 * @since 1.18
261 * @return bool
263 public static function isValidBuiltInCode( $code ) {
265 if( !is_string($code) ) {
266 $type = gettype( $code );
267 if( $type === 'object' ) {
268 $addmsg = " of class " . get_class( $code );
269 } else {
270 $addmsg = '';
272 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
275 return preg_match( '/^[a-z0-9-]+$/i', $code );
279 * @param $code
280 * @return String Name of the language class
282 public static function classFromCode( $code ) {
283 if ( $code == 'en' ) {
284 return 'Language';
285 } else {
286 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
291 * Includes language class files
293 * @param $class string Name of the language class
295 public static function preloadLanguageClass( $class ) {
296 global $IP;
298 if ( $class === 'Language' ) {
299 return;
302 if ( !defined( 'MW_COMPILED' ) ) {
303 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
304 include_once( "$IP/languages/classes/$class.php" );
310 * Get the LocalisationCache instance
312 * @return LocalisationCache
314 public static function getLocalisationCache() {
315 if ( is_null( self::$dataCache ) ) {
316 global $wgLocalisationCacheConf;
317 $class = $wgLocalisationCacheConf['class'];
318 self::$dataCache = new $class( $wgLocalisationCacheConf );
320 return self::$dataCache;
323 function __construct() {
324 $this->mConverter = new FakeConverter( $this );
325 // Set the code to the name of the descendant
326 if ( get_class( $this ) == 'Language' ) {
327 $this->mCode = 'en';
328 } else {
329 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
331 self::getLocalisationCache();
335 * Reduce memory usage
337 function __destruct() {
338 foreach ( $this as $name => $value ) {
339 unset( $this->$name );
344 * Hook which will be called if this is the content language.
345 * Descendants can use this to register hook functions or modify globals
347 function initContLang() { }
350 * Same as getFallbacksFor for current language.
351 * @return array|bool
352 * @deprecated in 1.19
354 function getFallbackLanguageCode() {
355 wfDeprecated( __METHOD__ );
356 return self::getFallbackFor( $this->mCode );
360 * @return array
361 * @since 1.19
363 function getFallbackLanguages() {
364 return self::getFallbacksFor( $this->mCode );
368 * Exports $wgBookstoreListEn
369 * @return array
371 function getBookstoreList() {
372 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
376 * @return array
378 public function getNamespaces() {
379 if ( is_null( $this->namespaceNames ) ) {
380 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
382 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
383 $validNamespaces = MWNamespace::getCanonicalNamespaces();
385 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
387 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
388 if ( $wgMetaNamespaceTalk ) {
389 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
390 } else {
391 $talk = $this->namespaceNames[NS_PROJECT_TALK];
392 $this->namespaceNames[NS_PROJECT_TALK] =
393 $this->fixVariableInNamespace( $talk );
396 # Sometimes a language will be localised but not actually exist on this wiki.
397 foreach ( $this->namespaceNames as $key => $text ) {
398 if ( !isset( $validNamespaces[$key] ) ) {
399 unset( $this->namespaceNames[$key] );
403 # The above mixing may leave namespaces out of canonical order.
404 # Re-order by namespace ID number...
405 ksort( $this->namespaceNames );
407 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
409 return $this->namespaceNames;
413 * Arbitrarily set all of the namespace names at once. Mainly used for testing
414 * @param $namespaces Array of namespaces (id => name)
416 public function setNamespaces( array $namespaces ) {
417 $this->namespaceNames = $namespaces;
421 * A convenience function that returns the same thing as
422 * getNamespaces() except with the array values changed to ' '
423 * where it found '_', useful for producing output to be displayed
424 * e.g. in <select> forms.
426 * @return array
428 function getFormattedNamespaces() {
429 $ns = $this->getNamespaces();
430 foreach ( $ns as $k => $v ) {
431 $ns[$k] = strtr( $v, '_', ' ' );
433 return $ns;
437 * Get a namespace value by key
438 * <code>
439 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
440 * echo $mw_ns; // prints 'MediaWiki'
441 * </code>
443 * @param $index Int: the array key of the namespace to return
444 * @return mixed, string if the namespace value exists, otherwise false
446 function getNsText( $index ) {
447 $ns = $this->getNamespaces();
448 return isset( $ns[$index] ) ? $ns[$index] : false;
452 * A convenience function that returns the same thing as
453 * getNsText() except with '_' changed to ' ', useful for
454 * producing output.
456 * @param $index string
458 * @return array
460 function getFormattedNsText( $index ) {
461 $ns = $this->getNsText( $index );
462 return strtr( $ns, '_', ' ' );
466 * Returns gender-dependent namespace alias if available.
467 * @param $index Int: namespace index
468 * @param $gender String: gender key (male, female... )
469 * @return String
470 * @since 1.18
472 function getGenderNsText( $index, $gender ) {
473 global $wgExtraGenderNamespaces;
475 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
476 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
480 * Whether this language makes distinguishes genders for example in
481 * namespaces.
482 * @return bool
483 * @since 1.18
485 function needsGenderDistinction() {
486 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
487 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
488 // $wgExtraGenderNamespaces overrides everything
489 return true;
490 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
491 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
492 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
493 return false;
494 } else {
495 // Check what is in i18n files
496 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
497 return count( $aliases ) > 0;
502 * Get a namespace key by value, case insensitive.
503 * Only matches namespace names for the current language, not the
504 * canonical ones defined in Namespace.php.
506 * @param $text String
507 * @return mixed An integer if $text is a valid value otherwise false
509 function getLocalNsIndex( $text ) {
510 $lctext = $this->lc( $text );
511 $ids = $this->getNamespaceIds();
512 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
516 * @return array
518 function getNamespaceAliases() {
519 if ( is_null( $this->namespaceAliases ) ) {
520 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
521 if ( !$aliases ) {
522 $aliases = array();
523 } else {
524 foreach ( $aliases as $name => $index ) {
525 if ( $index === NS_PROJECT_TALK ) {
526 unset( $aliases[$name] );
527 $name = $this->fixVariableInNamespace( $name );
528 $aliases[$name] = $index;
533 global $wgExtraGenderNamespaces;
534 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
535 foreach ( $genders as $index => $forms ) {
536 foreach ( $forms as $alias ) {
537 $aliases[$alias] = $index;
541 $this->namespaceAliases = $aliases;
543 return $this->namespaceAliases;
547 * @return array
549 function getNamespaceIds() {
550 if ( is_null( $this->mNamespaceIds ) ) {
551 global $wgNamespaceAliases;
552 # Put namespace names and aliases into a hashtable.
553 # If this is too slow, then we should arrange it so that it is done
554 # before caching. The catch is that at pre-cache time, the above
555 # class-specific fixup hasn't been done.
556 $this->mNamespaceIds = array();
557 foreach ( $this->getNamespaces() as $index => $name ) {
558 $this->mNamespaceIds[$this->lc( $name )] = $index;
560 foreach ( $this->getNamespaceAliases() as $name => $index ) {
561 $this->mNamespaceIds[$this->lc( $name )] = $index;
563 if ( $wgNamespaceAliases ) {
564 foreach ( $wgNamespaceAliases as $name => $index ) {
565 $this->mNamespaceIds[$this->lc( $name )] = $index;
569 return $this->mNamespaceIds;
573 * Get a namespace key by value, case insensitive. Canonical namespace
574 * names override custom ones defined for the current language.
576 * @param $text String
577 * @return mixed An integer if $text is a valid value otherwise false
579 function getNsIndex( $text ) {
580 $lctext = $this->lc( $text );
581 $ns = MWNamespace::getCanonicalIndex( $lctext );
582 if ( $ns !== null ) {
583 return $ns;
585 $ids = $this->getNamespaceIds();
586 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
590 * short names for language variants used for language conversion links.
592 * @param $code String
593 * @param $usemsg bool Use the "variantname-xyz" message if it exists
594 * @return string
596 function getVariantname( $code, $usemsg = true ) {
597 $msg = "variantname-$code";
598 if ( $usemsg && wfMessage( $msg )->exists() ) {
599 return $this->getMessageFromDB( $msg );
601 $name = self::fetchLanguageName( $code );
602 if ( $name ) {
603 return $name; # if it's defined as a language name, show that
604 } else {
605 # otherwise, output the language code
606 return $code;
611 * @param $name string
612 * @return string
614 function specialPage( $name ) {
615 $aliases = $this->getSpecialPageAliases();
616 if ( isset( $aliases[$name][0] ) ) {
617 $name = $aliases[$name][0];
619 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
623 * @return array
625 function getQuickbarSettings() {
626 return array(
627 $this->getMessage( 'qbsettings-none' ),
628 $this->getMessage( 'qbsettings-fixedleft' ),
629 $this->getMessage( 'qbsettings-fixedright' ),
630 $this->getMessage( 'qbsettings-floatingleft' ),
631 $this->getMessage( 'qbsettings-floatingright' ),
632 $this->getMessage( 'qbsettings-directionality' )
637 * @return array
639 function getDatePreferences() {
640 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
644 * @return array
646 function getDateFormats() {
647 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
651 * @return array|string
653 function getDefaultDateFormat() {
654 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
655 if ( $df === 'dmy or mdy' ) {
656 global $wgAmericanDates;
657 return $wgAmericanDates ? 'mdy' : 'dmy';
658 } else {
659 return $df;
664 * @return array
666 function getDatePreferenceMigrationMap() {
667 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
671 * @param $image
672 * @return array|null
674 function getImageFile( $image ) {
675 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
679 * @return array
681 function getExtraUserToggles() {
682 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
686 * @param $tog
687 * @return string
689 function getUserToggle( $tog ) {
690 return $this->getMessageFromDB( "tog-$tog" );
694 * Get native language names, indexed by code.
695 * Only those defined in MediaWiki, no other data like CLDR.
696 * If $customisedOnly is true, only returns codes with a messages file
698 * @param $customisedOnly bool
700 * @return array
701 * @deprecated in 1.20, use fetchLanguageNames()
703 public static function getLanguageNames( $customisedOnly = false ) {
704 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
708 * Get translated language names. This is done on best effort and
709 * by default this is exactly the same as Language::getLanguageNames.
710 * The CLDR extension provides translated names.
711 * @param $code String Language code.
712 * @return Array language code => language name
713 * @since 1.18.0
714 * @deprecated in 1.20, use fetchLanguageNames()
716 public static function getTranslatedLanguageNames( $code ) {
717 return self::fetchLanguageNames( $code, 'all' );
721 * Get an array of language names, indexed by code.
722 * @param $inLanguage null|string: Code of language in which to return the names
723 * Use null for autonyms (native names)
724 * @param $include string:
725 * 'all' all available languages
726 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
727 * 'mwfile' only if the language is in 'mw' *and* has a message file
728 * @return array: language code => language name
729 * @since 1.20
731 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
732 global $wgExtraLanguageNames;
733 static $coreLanguageNames;
735 if ( $coreLanguageNames === null ) {
736 include( MWInit::compiledPath( 'languages/Names.php' ) );
739 $names = array();
741 if( $inLanguage ) {
742 # TODO: also include when $inLanguage is null, when this code is more efficient
743 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
746 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
747 foreach ( $mwNames as $mwCode => $mwName ) {
748 # - Prefer own MediaWiki native name when not using the hook
749 # - For other names just add if not added through the hook
750 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
751 $names[$mwCode] = $mwName;
755 if ( $include === 'all' ) {
756 return $names;
759 $returnMw = array();
760 $coreCodes = array_keys( $mwNames );
761 foreach( $coreCodes as $coreCode ) {
762 $returnMw[$coreCode] = $names[$coreCode];
765 if( $include === 'mwfile' ) {
766 $namesMwFile = array();
767 # We do this using a foreach over the codes instead of a directory
768 # loop so that messages files in extensions will work correctly.
769 foreach ( $returnMw as $code => $value ) {
770 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
771 $namesMwFile[$code] = $names[$code];
774 return $namesMwFile;
776 # 'mw' option; default if it's not one of the other two options (all/mwfile)
777 return $returnMw;
781 * @param $code string: The code of the language for which to get the name
782 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
783 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
784 * @return string: Language name or empty
785 * @since 1.20
787 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
788 $array = self::fetchLanguageNames( $inLanguage, $include );
789 return !array_key_exists( $code, $array ) ? '' : $array[$code];
793 * Get a message from the MediaWiki namespace.
795 * @param $msg String: message name
796 * @return string
798 function getMessageFromDB( $msg ) {
799 return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
803 * Get the native language name of $code.
804 * Only if defined in MediaWiki, no other data like CLDR.
805 * @param $code string
806 * @return string
807 * @deprecated in 1.20, use fetchLanguageName()
809 function getLanguageName( $code ) {
810 return self::fetchLanguageName( $code );
814 * @param $key string
815 * @return string
817 function getMonthName( $key ) {
818 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
822 * @return array
824 function getMonthNamesArray() {
825 $monthNames = array( '' );
826 for ( $i = 1; $i < 13; $i++ ) {
827 $monthNames[] = $this->getMonthName( $i );
829 return $monthNames;
833 * @param $key string
834 * @return string
836 function getMonthNameGen( $key ) {
837 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
841 * @param $key string
842 * @return string
844 function getMonthAbbreviation( $key ) {
845 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
849 * @return array
851 function getMonthAbbreviationsArray() {
852 $monthNames = array( '' );
853 for ( $i = 1; $i < 13; $i++ ) {
854 $monthNames[] = $this->getMonthAbbreviation( $i );
856 return $monthNames;
860 * @param $key string
861 * @return string
863 function getWeekdayName( $key ) {
864 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
868 * @param $key string
869 * @return string
871 function getWeekdayAbbreviation( $key ) {
872 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
876 * @param $key string
877 * @return string
879 function getIranianCalendarMonthName( $key ) {
880 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
884 * @param $key string
885 * @return string
887 function getHebrewCalendarMonthName( $key ) {
888 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
892 * @param $key string
893 * @return string
895 function getHebrewCalendarMonthNameGen( $key ) {
896 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
900 * @param $key string
901 * @return string
903 function getHijriCalendarMonthName( $key ) {
904 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
908 * This is a workalike of PHP's date() function, but with better
909 * internationalisation, a reduced set of format characters, and a better
910 * escaping format.
912 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
913 * PHP manual for definitions. There are a number of extensions, which
914 * start with "x":
916 * xn Do not translate digits of the next numeric format character
917 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
918 * xr Use roman numerals for the next numeric format character
919 * xh Use hebrew numerals for the next numeric format character
920 * xx Literal x
921 * xg Genitive month name
923 * xij j (day number) in Iranian calendar
924 * xiF F (month name) in Iranian calendar
925 * xin n (month number) in Iranian calendar
926 * xiy y (two digit year) in Iranian calendar
927 * xiY Y (full year) in Iranian calendar
929 * xjj j (day number) in Hebrew calendar
930 * xjF F (month name) in Hebrew calendar
931 * xjt t (days in month) in Hebrew calendar
932 * xjx xg (genitive month name) in Hebrew calendar
933 * xjn n (month number) in Hebrew calendar
934 * xjY Y (full year) in Hebrew calendar
936 * xmj j (day number) in Hijri calendar
937 * xmF F (month name) in Hijri calendar
938 * xmn n (month number) in Hijri calendar
939 * xmY Y (full year) in Hijri calendar
941 * xkY Y (full year) in Thai solar calendar. Months and days are
942 * identical to the Gregorian calendar
943 * xoY Y (full year) in Minguo calendar or Juche year.
944 * Months and days are identical to the
945 * Gregorian calendar
946 * xtY Y (full year) in Japanese nengo. Months and days are
947 * identical to the Gregorian calendar
949 * Characters enclosed in double quotes will be considered literal (with
950 * the quotes themselves removed). Unmatched quotes will be considered
951 * literal quotes. Example:
953 * "The month is" F => The month is January
954 * i's" => 20'11"
956 * Backslash escaping is also supported.
958 * Input timestamp is assumed to be pre-normalized to the desired local
959 * time zone, if any.
961 * @param $format String
962 * @param $ts String: 14-character timestamp
963 * YYYYMMDDHHMMSS
964 * 01234567890123
965 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
967 * @return string
969 function sprintfDate( $format, $ts ) {
970 $s = '';
971 $raw = false;
972 $roman = false;
973 $hebrewNum = false;
974 $unix = false;
975 $rawToggle = false;
976 $iranian = false;
977 $hebrew = false;
978 $hijri = false;
979 $thai = false;
980 $minguo = false;
981 $tenno = false;
982 for ( $p = 0; $p < strlen( $format ); $p++ ) {
983 $num = false;
984 $code = $format[$p];
985 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
986 $code .= $format[++$p];
989 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
990 $code .= $format[++$p];
993 switch ( $code ) {
994 case 'xx':
995 $s .= 'x';
996 break;
997 case 'xn':
998 $raw = true;
999 break;
1000 case 'xN':
1001 $rawToggle = !$rawToggle;
1002 break;
1003 case 'xr':
1004 $roman = true;
1005 break;
1006 case 'xh':
1007 $hebrewNum = true;
1008 break;
1009 case 'xg':
1010 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1011 break;
1012 case 'xjx':
1013 if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
1014 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1015 break;
1016 case 'd':
1017 $num = substr( $ts, 6, 2 );
1018 break;
1019 case 'D':
1020 if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
1021 $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
1022 break;
1023 case 'j':
1024 $num = intval( substr( $ts, 6, 2 ) );
1025 break;
1026 case 'xij':
1027 if ( !$iranian ) {
1028 $iranian = self::tsToIranian( $ts );
1030 $num = $iranian[2];
1031 break;
1032 case 'xmj':
1033 if ( !$hijri ) {
1034 $hijri = self::tsToHijri( $ts );
1036 $num = $hijri[2];
1037 break;
1038 case 'xjj':
1039 if ( !$hebrew ) {
1040 $hebrew = self::tsToHebrew( $ts );
1042 $num = $hebrew[2];
1043 break;
1044 case 'l':
1045 if ( !$unix ) {
1046 $unix = wfTimestamp( TS_UNIX, $ts );
1048 $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
1049 break;
1050 case 'N':
1051 if ( !$unix ) {
1052 $unix = wfTimestamp( TS_UNIX, $ts );
1054 $w = gmdate( 'w', $unix );
1055 $num = $w ? $w : 7;
1056 break;
1057 case 'w':
1058 if ( !$unix ) {
1059 $unix = wfTimestamp( TS_UNIX, $ts );
1061 $num = gmdate( 'w', $unix );
1062 break;
1063 case 'z':
1064 if ( !$unix ) {
1065 $unix = wfTimestamp( TS_UNIX, $ts );
1067 $num = gmdate( 'z', $unix );
1068 break;
1069 case 'W':
1070 if ( !$unix ) {
1071 $unix = wfTimestamp( TS_UNIX, $ts );
1073 $num = gmdate( 'W', $unix );
1074 break;
1075 case 'F':
1076 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1077 break;
1078 case 'xiF':
1079 if ( !$iranian ) {
1080 $iranian = self::tsToIranian( $ts );
1082 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1083 break;
1084 case 'xmF':
1085 if ( !$hijri ) {
1086 $hijri = self::tsToHijri( $ts );
1088 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1089 break;
1090 case 'xjF':
1091 if ( !$hebrew ) {
1092 $hebrew = self::tsToHebrew( $ts );
1094 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1095 break;
1096 case 'm':
1097 $num = substr( $ts, 4, 2 );
1098 break;
1099 case 'M':
1100 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1101 break;
1102 case 'n':
1103 $num = intval( substr( $ts, 4, 2 ) );
1104 break;
1105 case 'xin':
1106 if ( !$iranian ) {
1107 $iranian = self::tsToIranian( $ts );
1109 $num = $iranian[1];
1110 break;
1111 case 'xmn':
1112 if ( !$hijri ) {
1113 $hijri = self::tsToHijri ( $ts );
1115 $num = $hijri[1];
1116 break;
1117 case 'xjn':
1118 if ( !$hebrew ) {
1119 $hebrew = self::tsToHebrew( $ts );
1121 $num = $hebrew[1];
1122 break;
1123 case 't':
1124 if ( !$unix ) {
1125 $unix = wfTimestamp( TS_UNIX, $ts );
1127 $num = gmdate( 't', $unix );
1128 break;
1129 case 'xjt':
1130 if ( !$hebrew ) {
1131 $hebrew = self::tsToHebrew( $ts );
1133 $num = $hebrew[3];
1134 break;
1135 case 'L':
1136 if ( !$unix ) {
1137 $unix = wfTimestamp( TS_UNIX, $ts );
1139 $num = gmdate( 'L', $unix );
1140 break;
1141 case 'o':
1142 if ( !$unix ) {
1143 $unix = wfTimestamp( TS_UNIX, $ts );
1145 $num = gmdate( 'o', $unix );
1146 break;
1147 case 'Y':
1148 $num = substr( $ts, 0, 4 );
1149 break;
1150 case 'xiY':
1151 if ( !$iranian ) {
1152 $iranian = self::tsToIranian( $ts );
1154 $num = $iranian[0];
1155 break;
1156 case 'xmY':
1157 if ( !$hijri ) {
1158 $hijri = self::tsToHijri( $ts );
1160 $num = $hijri[0];
1161 break;
1162 case 'xjY':
1163 if ( !$hebrew ) {
1164 $hebrew = self::tsToHebrew( $ts );
1166 $num = $hebrew[0];
1167 break;
1168 case 'xkY':
1169 if ( !$thai ) {
1170 $thai = self::tsToYear( $ts, 'thai' );
1172 $num = $thai[0];
1173 break;
1174 case 'xoY':
1175 if ( !$minguo ) {
1176 $minguo = self::tsToYear( $ts, 'minguo' );
1178 $num = $minguo[0];
1179 break;
1180 case 'xtY':
1181 if ( !$tenno ) {
1182 $tenno = self::tsToYear( $ts, 'tenno' );
1184 $num = $tenno[0];
1185 break;
1186 case 'y':
1187 $num = substr( $ts, 2, 2 );
1188 break;
1189 case 'xiy':
1190 if ( !$iranian ) {
1191 $iranian = self::tsToIranian( $ts );
1193 $num = substr( $iranian[0], -2 );
1194 break;
1195 case 'a':
1196 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1197 break;
1198 case 'A':
1199 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1200 break;
1201 case 'g':
1202 $h = substr( $ts, 8, 2 );
1203 $num = $h % 12 ? $h % 12 : 12;
1204 break;
1205 case 'G':
1206 $num = intval( substr( $ts, 8, 2 ) );
1207 break;
1208 case 'h':
1209 $h = substr( $ts, 8, 2 );
1210 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1211 break;
1212 case 'H':
1213 $num = substr( $ts, 8, 2 );
1214 break;
1215 case 'i':
1216 $num = substr( $ts, 10, 2 );
1217 break;
1218 case 's':
1219 $num = substr( $ts, 12, 2 );
1220 break;
1221 case 'c':
1222 if ( !$unix ) {
1223 $unix = wfTimestamp( TS_UNIX, $ts );
1225 $s .= gmdate( 'c', $unix );
1226 break;
1227 case 'r':
1228 if ( !$unix ) {
1229 $unix = wfTimestamp( TS_UNIX, $ts );
1231 $s .= gmdate( 'r', $unix );
1232 break;
1233 case 'U':
1234 if ( !$unix ) {
1235 $unix = wfTimestamp( TS_UNIX, $ts );
1237 $num = $unix;
1238 break;
1239 case '\\':
1240 # Backslash escaping
1241 if ( $p < strlen( $format ) - 1 ) {
1242 $s .= $format[++$p];
1243 } else {
1244 $s .= '\\';
1246 break;
1247 case '"':
1248 # Quoted literal
1249 if ( $p < strlen( $format ) - 1 ) {
1250 $endQuote = strpos( $format, '"', $p + 1 );
1251 if ( $endQuote === false ) {
1252 # No terminating quote, assume literal "
1253 $s .= '"';
1254 } else {
1255 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1256 $p = $endQuote;
1258 } else {
1259 # Quote at end of string, assume literal "
1260 $s .= '"';
1262 break;
1263 default:
1264 $s .= $format[$p];
1266 if ( $num !== false ) {
1267 if ( $rawToggle || $raw ) {
1268 $s .= $num;
1269 $raw = false;
1270 } elseif ( $roman ) {
1271 $s .= self::romanNumeral( $num );
1272 $roman = false;
1273 } elseif ( $hebrewNum ) {
1274 $s .= self::hebrewNumeral( $num );
1275 $hebrewNum = false;
1276 } else {
1277 $s .= $this->formatNum( $num, true );
1281 return $s;
1284 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1285 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1288 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1289 * Gregorian dates to Iranian dates. Originally written in C, it
1290 * is released under the terms of GNU Lesser General Public
1291 * License. Conversion to PHP was performed by Niklas Laxström.
1293 * Link: http://www.farsiweb.info/jalali/jalali.c
1295 * @param $ts string
1297 * @return string
1299 private static function tsToIranian( $ts ) {
1300 $gy = substr( $ts, 0, 4 ) -1600;
1301 $gm = substr( $ts, 4, 2 ) -1;
1302 $gd = substr( $ts, 6, 2 ) -1;
1304 # Days passed from the beginning (including leap years)
1305 $gDayNo = 365 * $gy
1306 + floor( ( $gy + 3 ) / 4 )
1307 - floor( ( $gy + 99 ) / 100 )
1308 + floor( ( $gy + 399 ) / 400 );
1310 // Add days of the past months of this year
1311 for ( $i = 0; $i < $gm; $i++ ) {
1312 $gDayNo += self::$GREG_DAYS[$i];
1315 // Leap years
1316 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1317 $gDayNo++;
1320 // Days passed in current month
1321 $gDayNo += (int)$gd;
1323 $jDayNo = $gDayNo - 79;
1325 $jNp = floor( $jDayNo / 12053 );
1326 $jDayNo %= 12053;
1328 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1329 $jDayNo %= 1461;
1331 if ( $jDayNo >= 366 ) {
1332 $jy += floor( ( $jDayNo - 1 ) / 365 );
1333 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1336 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1337 $jDayNo -= self::$IRANIAN_DAYS[$i];
1340 $jm = $i + 1;
1341 $jd = $jDayNo + 1;
1343 return array( $jy, $jm, $jd );
1347 * Converting Gregorian dates to Hijri dates.
1349 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1351 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1353 * @param $ts string
1355 * @return string
1357 private static function tsToHijri( $ts ) {
1358 $year = substr( $ts, 0, 4 );
1359 $month = substr( $ts, 4, 2 );
1360 $day = substr( $ts, 6, 2 );
1362 $zyr = $year;
1363 $zd = $day;
1364 $zm = $month;
1365 $zy = $zyr;
1367 if (
1368 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1369 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1372 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1373 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1374 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1375 $zd - 32075;
1376 } else {
1377 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1378 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1381 $zl = $zjd -1948440 + 10632;
1382 $zn = (int)( ( $zl - 1 ) / 10631 );
1383 $zl = $zl - 10631 * $zn + 354;
1384 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1385 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1386 $zm = (int)( ( 24 * $zl ) / 709 );
1387 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1388 $zy = 30 * $zn + $zj - 30;
1390 return array( $zy, $zm, $zd );
1394 * Converting Gregorian dates to Hebrew dates.
1396 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1397 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1398 * to translate the relevant functions into PHP and release them under
1399 * GNU GPL.
1401 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1402 * and Adar II is 14. In a non-leap year, Adar is 6.
1404 * @param $ts string
1406 * @return string
1408 private static function tsToHebrew( $ts ) {
1409 # Parse date
1410 $year = substr( $ts, 0, 4 );
1411 $month = substr( $ts, 4, 2 );
1412 $day = substr( $ts, 6, 2 );
1414 # Calculate Hebrew year
1415 $hebrewYear = $year + 3760;
1417 # Month number when September = 1, August = 12
1418 $month += 4;
1419 if ( $month > 12 ) {
1420 # Next year
1421 $month -= 12;
1422 $year++;
1423 $hebrewYear++;
1426 # Calculate day of year from 1 September
1427 $dayOfYear = $day;
1428 for ( $i = 1; $i < $month; $i++ ) {
1429 if ( $i == 6 ) {
1430 # February
1431 $dayOfYear += 28;
1432 # Check if the year is leap
1433 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1434 $dayOfYear++;
1436 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1437 $dayOfYear += 30;
1438 } else {
1439 $dayOfYear += 31;
1443 # Calculate the start of the Hebrew year
1444 $start = self::hebrewYearStart( $hebrewYear );
1446 # Calculate next year's start
1447 if ( $dayOfYear <= $start ) {
1448 # Day is before the start of the year - it is the previous year
1449 # Next year's start
1450 $nextStart = $start;
1451 # Previous year
1452 $year--;
1453 $hebrewYear--;
1454 # Add days since previous year's 1 September
1455 $dayOfYear += 365;
1456 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1457 # Leap year
1458 $dayOfYear++;
1460 # Start of the new (previous) year
1461 $start = self::hebrewYearStart( $hebrewYear );
1462 } else {
1463 # Next year's start
1464 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1467 # Calculate Hebrew day of year
1468 $hebrewDayOfYear = $dayOfYear - $start;
1470 # Difference between year's days
1471 $diff = $nextStart - $start;
1472 # Add 12 (or 13 for leap years) days to ignore the difference between
1473 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1474 # difference is only about the year type
1475 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1476 $diff += 13;
1477 } else {
1478 $diff += 12;
1481 # Check the year pattern, and is leap year
1482 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1483 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1484 # and non-leap years
1485 $yearPattern = $diff % 30;
1486 # Check if leap year
1487 $isLeap = $diff >= 30;
1489 # Calculate day in the month from number of day in the Hebrew year
1490 # Don't check Adar - if the day is not in Adar, we will stop before;
1491 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1492 $hebrewDay = $hebrewDayOfYear;
1493 $hebrewMonth = 1;
1494 $days = 0;
1495 while ( $hebrewMonth <= 12 ) {
1496 # Calculate days in this month
1497 if ( $isLeap && $hebrewMonth == 6 ) {
1498 # Adar in a leap year
1499 if ( $isLeap ) {
1500 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1501 $days = 30;
1502 if ( $hebrewDay <= $days ) {
1503 # Day in Adar I
1504 $hebrewMonth = 13;
1505 } else {
1506 # Subtract the days of Adar I
1507 $hebrewDay -= $days;
1508 # Try Adar II
1509 $days = 29;
1510 if ( $hebrewDay <= $days ) {
1511 # Day in Adar II
1512 $hebrewMonth = 14;
1516 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1517 # Cheshvan in a complete year (otherwise as the rule below)
1518 $days = 30;
1519 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1520 # Kislev in an incomplete year (otherwise as the rule below)
1521 $days = 29;
1522 } else {
1523 # Odd months have 30 days, even have 29
1524 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1526 if ( $hebrewDay <= $days ) {
1527 # In the current month
1528 break;
1529 } else {
1530 # Subtract the days of the current month
1531 $hebrewDay -= $days;
1532 # Try in the next month
1533 $hebrewMonth++;
1537 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1541 * This calculates the Hebrew year start, as days since 1 September.
1542 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1543 * Used for Hebrew date.
1545 * @param $year int
1547 * @return string
1549 private static function hebrewYearStart( $year ) {
1550 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1551 $b = intval( ( $year - 1 ) % 4 );
1552 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1553 if ( $m < 0 ) {
1554 $m--;
1556 $Mar = intval( $m );
1557 if ( $m < 0 ) {
1558 $m++;
1560 $m -= $Mar;
1562 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1563 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1564 $Mar++;
1565 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1566 $Mar += 2;
1567 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1568 $Mar++;
1571 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1572 return $Mar;
1576 * Algorithm to convert Gregorian dates to Thai solar dates,
1577 * Minguo dates or Minguo dates.
1579 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1580 * http://en.wikipedia.org/wiki/Minguo_calendar
1581 * http://en.wikipedia.org/wiki/Japanese_era_name
1583 * @param $ts String: 14-character timestamp
1584 * @param $cName String: calender name
1585 * @return Array: converted year, month, day
1587 private static function tsToYear( $ts, $cName ) {
1588 $gy = substr( $ts, 0, 4 );
1589 $gm = substr( $ts, 4, 2 );
1590 $gd = substr( $ts, 6, 2 );
1592 if ( !strcmp( $cName, 'thai' ) ) {
1593 # Thai solar dates
1594 # Add 543 years to the Gregorian calendar
1595 # Months and days are identical
1596 $gy_offset = $gy + 543;
1597 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1598 # Minguo dates
1599 # Deduct 1911 years from the Gregorian calendar
1600 # Months and days are identical
1601 $gy_offset = $gy - 1911;
1602 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1603 # Nengō dates up to Meiji period
1604 # Deduct years from the Gregorian calendar
1605 # depending on the nengo periods
1606 # Months and days are identical
1607 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1608 # Meiji period
1609 $gy_gannen = $gy - 1868 + 1;
1610 $gy_offset = $gy_gannen;
1611 if ( $gy_gannen == 1 ) {
1612 $gy_offset = '元';
1614 $gy_offset = '明治' . $gy_offset;
1615 } elseif (
1616 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1617 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1618 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1619 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1620 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1623 # Taishō period
1624 $gy_gannen = $gy - 1912 + 1;
1625 $gy_offset = $gy_gannen;
1626 if ( $gy_gannen == 1 ) {
1627 $gy_offset = '元';
1629 $gy_offset = '大正' . $gy_offset;
1630 } elseif (
1631 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1632 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1633 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1636 # Shōwa period
1637 $gy_gannen = $gy - 1926 + 1;
1638 $gy_offset = $gy_gannen;
1639 if ( $gy_gannen == 1 ) {
1640 $gy_offset = '元';
1642 $gy_offset = '昭和' . $gy_offset;
1643 } else {
1644 # Heisei period
1645 $gy_gannen = $gy - 1989 + 1;
1646 $gy_offset = $gy_gannen;
1647 if ( $gy_gannen == 1 ) {
1648 $gy_offset = '元';
1650 $gy_offset = '平成' . $gy_offset;
1652 } else {
1653 $gy_offset = $gy;
1656 return array( $gy_offset, $gm, $gd );
1660 * Roman number formatting up to 3000
1662 * @param $num int
1664 * @return string
1666 static function romanNumeral( $num ) {
1667 static $table = array(
1668 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1669 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1670 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1671 array( '', 'M', 'MM', 'MMM' )
1674 $num = intval( $num );
1675 if ( $num > 3000 || $num <= 0 ) {
1676 return $num;
1679 $s = '';
1680 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1681 if ( $num >= $pow10 ) {
1682 $s .= $table[$i][(int)floor( $num / $pow10 )];
1684 $num = $num % $pow10;
1686 return $s;
1690 * Hebrew Gematria number formatting up to 9999
1692 * @param $num int
1694 * @return string
1696 static function hebrewNumeral( $num ) {
1697 static $table = array(
1698 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1699 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1700 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1701 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1704 $num = intval( $num );
1705 if ( $num > 9999 || $num <= 0 ) {
1706 return $num;
1709 $s = '';
1710 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1711 if ( $num >= $pow10 ) {
1712 if ( $num == 15 || $num == 16 ) {
1713 $s .= $table[0][9] . $table[0][$num - 9];
1714 $num = 0;
1715 } else {
1716 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1717 if ( $pow10 == 1000 ) {
1718 $s .= "'";
1722 $num = $num % $pow10;
1724 if ( strlen( $s ) == 2 ) {
1725 $str = $s . "'";
1726 } else {
1727 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1728 $str .= substr( $s, strlen( $s ) - 2, 2 );
1730 $start = substr( $str, 0, strlen( $str ) - 2 );
1731 $end = substr( $str, strlen( $str ) - 2 );
1732 switch( $end ) {
1733 case 'כ':
1734 $str = $start . 'ך';
1735 break;
1736 case 'מ':
1737 $str = $start . 'ם';
1738 break;
1739 case 'נ':
1740 $str = $start . 'ן';
1741 break;
1742 case 'פ':
1743 $str = $start . 'ף';
1744 break;
1745 case 'צ':
1746 $str = $start . 'ץ';
1747 break;
1749 return $str;
1753 * Used by date() and time() to adjust the time output.
1755 * @param $ts Int the time in date('YmdHis') format
1756 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1757 * get user timecorrection setting)
1758 * @return int
1760 function userAdjust( $ts, $tz = false ) {
1761 global $wgUser, $wgLocalTZoffset;
1763 if ( $tz === false ) {
1764 $tz = $wgUser->getOption( 'timecorrection' );
1767 $data = explode( '|', $tz, 3 );
1769 if ( $data[0] == 'ZoneInfo' ) {
1770 wfSuppressWarnings();
1771 $userTZ = timezone_open( $data[2] );
1772 wfRestoreWarnings();
1773 if ( $userTZ !== false ) {
1774 $date = date_create( $ts, timezone_open( 'UTC' ) );
1775 date_timezone_set( $date, $userTZ );
1776 $date = date_format( $date, 'YmdHis' );
1777 return $date;
1779 # Unrecognized timezone, default to 'Offset' with the stored offset.
1780 $data[0] = 'Offset';
1783 $minDiff = 0;
1784 if ( $data[0] == 'System' || $tz == '' ) {
1785 #  Global offset in minutes.
1786 if ( isset( $wgLocalTZoffset ) ) {
1787 $minDiff = $wgLocalTZoffset;
1789 } elseif ( $data[0] == 'Offset' ) {
1790 $minDiff = intval( $data[1] );
1791 } else {
1792 $data = explode( ':', $tz );
1793 if ( count( $data ) == 2 ) {
1794 $data[0] = intval( $data[0] );
1795 $data[1] = intval( $data[1] );
1796 $minDiff = abs( $data[0] ) * 60 + $data[1];
1797 if ( $data[0] < 0 ) {
1798 $minDiff = -$minDiff;
1800 } else {
1801 $minDiff = intval( $data[0] ) * 60;
1805 # No difference ? Return time unchanged
1806 if ( 0 == $minDiff ) {
1807 return $ts;
1810 wfSuppressWarnings(); // E_STRICT system time bitching
1811 # Generate an adjusted date; take advantage of the fact that mktime
1812 # will normalize out-of-range values so we don't have to split $minDiff
1813 # into hours and minutes.
1814 $t = mktime( (
1815 (int)substr( $ts, 8, 2 ) ), # Hours
1816 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1817 (int)substr( $ts, 12, 2 ), # Seconds
1818 (int)substr( $ts, 4, 2 ), # Month
1819 (int)substr( $ts, 6, 2 ), # Day
1820 (int)substr( $ts, 0, 4 ) ); # Year
1822 $date = date( 'YmdHis', $t );
1823 wfRestoreWarnings();
1825 return $date;
1829 * This is meant to be used by time(), date(), and timeanddate() to get
1830 * the date preference they're supposed to use, it should be used in
1831 * all children.
1833 *<code>
1834 * function timeanddate([...], $format = true) {
1835 * $datePreference = $this->dateFormat($format);
1836 * [...]
1838 *</code>
1840 * @param $usePrefs Mixed: if true, the user's preference is used
1841 * if false, the site/language default is used
1842 * if int/string, assumed to be a format.
1843 * @return string
1845 function dateFormat( $usePrefs = true ) {
1846 global $wgUser;
1848 if ( is_bool( $usePrefs ) ) {
1849 if ( $usePrefs ) {
1850 $datePreference = $wgUser->getDatePreference();
1851 } else {
1852 $datePreference = (string)User::getDefaultOption( 'date' );
1854 } else {
1855 $datePreference = (string)$usePrefs;
1858 // return int
1859 if ( $datePreference == '' ) {
1860 return 'default';
1863 return $datePreference;
1867 * Get a format string for a given type and preference
1868 * @param $type string May be date, time or both
1869 * @param $pref string The format name as it appears in Messages*.php
1871 * @return string
1873 function getDateFormatString( $type, $pref ) {
1874 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1875 if ( $pref == 'default' ) {
1876 $pref = $this->getDefaultDateFormat();
1877 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1878 } else {
1879 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1880 if ( is_null( $df ) ) {
1881 $pref = $this->getDefaultDateFormat();
1882 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1885 $this->dateFormatStrings[$type][$pref] = $df;
1887 return $this->dateFormatStrings[$type][$pref];
1891 * @param $ts Mixed: the time format which needs to be turned into a
1892 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1893 * @param $adj Bool: whether to adjust the time output according to the
1894 * user configured offset ($timecorrection)
1895 * @param $format Mixed: true to use user's date format preference
1896 * @param $timecorrection String|bool the time offset as returned by
1897 * validateTimeZone() in Special:Preferences
1898 * @return string
1900 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1901 $ts = wfTimestamp( TS_MW, $ts );
1902 if ( $adj ) {
1903 $ts = $this->userAdjust( $ts, $timecorrection );
1905 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1906 return $this->sprintfDate( $df, $ts );
1910 * @param $ts Mixed: the time format which needs to be turned into a
1911 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1912 * @param $adj Bool: whether to adjust the time output according to the
1913 * user configured offset ($timecorrection)
1914 * @param $format Mixed: true to use user's date format preference
1915 * @param $timecorrection String|bool the time offset as returned by
1916 * validateTimeZone() in Special:Preferences
1917 * @return string
1919 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1920 $ts = wfTimestamp( TS_MW, $ts );
1921 if ( $adj ) {
1922 $ts = $this->userAdjust( $ts, $timecorrection );
1924 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1925 return $this->sprintfDate( $df, $ts );
1929 * @param $ts Mixed: the time format which needs to be turned into a
1930 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1931 * @param $adj Bool: whether to adjust the time output according to the
1932 * user configured offset ($timecorrection)
1933 * @param $format Mixed: what format to return, if it's false output the
1934 * default one (default true)
1935 * @param $timecorrection String|bool the time offset as returned by
1936 * validateTimeZone() in Special:Preferences
1937 * @return string
1939 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1940 $ts = wfTimestamp( TS_MW, $ts );
1941 if ( $adj ) {
1942 $ts = $this->userAdjust( $ts, $timecorrection );
1944 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1945 return $this->sprintfDate( $df, $ts );
1949 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
1951 * @since 1.20
1953 * @param integer $seconds The amount of seconds.
1954 * @param array $chosenIntervals The intervals to enable.
1956 * @return string
1958 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
1959 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
1961 $segments = array();
1963 foreach ( $intervals as $intervalName => $intervalValue ) {
1964 $message = new Message( 'duration-' . $intervalName, array( $intervalValue ) );
1965 $segments[] = $message->inLanguage( $this )->escaped();
1968 return $this->listToText( $segments );
1972 * Takes a number of seconds and returns an array with a set of corresponding intervals.
1973 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
1975 * @since 1.20
1977 * @param integer $seconds The amount of seconds.
1978 * @param array $chosenIntervals The intervals to enable.
1980 * @return array
1982 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
1983 if ( empty( $chosenIntervals ) ) {
1984 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
1987 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
1988 $sortedNames = array_keys( $intervals );
1989 $smallestInterval = array_pop( $sortedNames );
1991 $segments = array();
1993 foreach ( $intervals as $name => $length ) {
1994 $value = floor( $seconds / $length );
1996 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
1997 $seconds -= $value * $length;
1998 $segments[$name] = $value;
2002 return $segments;
2006 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2008 * @param $type String: can be 'date', 'time' or 'both'
2009 * @param $ts Mixed: the time format which needs to be turned into a
2010 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2011 * @param $user User object used to get preferences for timezone and format
2012 * @param $options Array, can contain the following keys:
2013 * - 'timecorrection': time correction, can have the following values:
2014 * - true: use user's preference
2015 * - false: don't use time correction
2016 * - integer: value of time correction in minutes
2017 * - 'format': format to use, can have the following values:
2018 * - true: use user's preference
2019 * - false: use default preference
2020 * - string: format to use
2021 * @since 1.19
2022 * @return String
2024 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2025 $ts = wfTimestamp( TS_MW, $ts );
2026 $options += array( 'timecorrection' => true, 'format' => true );
2027 if ( $options['timecorrection'] !== false ) {
2028 if ( $options['timecorrection'] === true ) {
2029 $offset = $user->getOption( 'timecorrection' );
2030 } else {
2031 $offset = $options['timecorrection'];
2033 $ts = $this->userAdjust( $ts, $offset );
2035 if ( $options['format'] === true ) {
2036 $format = $user->getDatePreference();
2037 } else {
2038 $format = $options['format'];
2040 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2041 return $this->sprintfDate( $df, $ts );
2045 * Get the formatted date for the given timestamp and formatted for
2046 * the given user.
2048 * @param $ts Mixed: the time format which needs to be turned into a
2049 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2050 * @param $user User object used to get preferences for timezone and format
2051 * @param $options Array, can contain the following keys:
2052 * - 'timecorrection': time correction, can have the following values:
2053 * - true: use user's preference
2054 * - false: don't use time correction
2055 * - integer: value of time correction in minutes
2056 * - 'format': format to use, can have the following values:
2057 * - true: use user's preference
2058 * - false: use default preference
2059 * - string: format to use
2060 * @since 1.19
2061 * @return String
2063 public function userDate( $ts, User $user, array $options = array() ) {
2064 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2068 * Get the formatted time for the given timestamp and formatted for
2069 * the given user.
2071 * @param $ts Mixed: the time format which needs to be turned into a
2072 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2073 * @param $user User object used to get preferences for timezone and format
2074 * @param $options Array, can contain the following keys:
2075 * - 'timecorrection': time correction, can have the following values:
2076 * - true: use user's preference
2077 * - false: don't use time correction
2078 * - integer: value of time correction in minutes
2079 * - 'format': format to use, can have the following values:
2080 * - true: use user's preference
2081 * - false: use default preference
2082 * - string: format to use
2083 * @since 1.19
2084 * @return String
2086 public function userTime( $ts, User $user, array $options = array() ) {
2087 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2091 * Get the formatted date and time for the given timestamp and formatted for
2092 * the given user.
2094 * @param $ts Mixed: the time format which needs to be turned into a
2095 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2096 * @param $user User object used to get preferences for timezone and format
2097 * @param $options Array, can contain the following keys:
2098 * - 'timecorrection': time correction, can have the following values:
2099 * - true: use user's preference
2100 * - false: don't use time correction
2101 * - integer: value of time correction in minutes
2102 * - 'format': format to use, can have the following values:
2103 * - true: use user's preference
2104 * - false: use default preference
2105 * - string: format to use
2106 * @since 1.19
2107 * @return String
2109 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2110 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2114 * @param $key string
2115 * @return array|null
2117 function getMessage( $key ) {
2118 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2122 * @return array
2124 function getAllMessages() {
2125 return self::$dataCache->getItem( $this->mCode, 'messages' );
2129 * @param $in
2130 * @param $out
2131 * @param $string
2132 * @return string
2134 function iconv( $in, $out, $string ) {
2135 # This is a wrapper for iconv in all languages except esperanto,
2136 # which does some nasty x-conversions beforehand
2138 # Even with //IGNORE iconv can whine about illegal characters in
2139 # *input* string. We just ignore those too.
2140 # REF: http://bugs.php.net/bug.php?id=37166
2141 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2142 wfSuppressWarnings();
2143 $text = iconv( $in, $out . '//IGNORE', $string );
2144 wfRestoreWarnings();
2145 return $text;
2148 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2151 * @param $matches array
2152 * @return mixed|string
2154 function ucwordbreaksCallbackAscii( $matches ) {
2155 return $this->ucfirst( $matches[1] );
2159 * @param $matches array
2160 * @return string
2162 function ucwordbreaksCallbackMB( $matches ) {
2163 return mb_strtoupper( $matches[0] );
2167 * @param $matches array
2168 * @return string
2170 function ucCallback( $matches ) {
2171 list( $wikiUpperChars ) = self::getCaseMaps();
2172 return strtr( $matches[1], $wikiUpperChars );
2176 * @param $matches array
2177 * @return string
2179 function lcCallback( $matches ) {
2180 list( , $wikiLowerChars ) = self::getCaseMaps();
2181 return strtr( $matches[1], $wikiLowerChars );
2185 * @param $matches array
2186 * @return string
2188 function ucwordsCallbackMB( $matches ) {
2189 return mb_strtoupper( $matches[0] );
2193 * @param $matches array
2194 * @return string
2196 function ucwordsCallbackWiki( $matches ) {
2197 list( $wikiUpperChars ) = self::getCaseMaps();
2198 return strtr( $matches[0], $wikiUpperChars );
2202 * Make a string's first character uppercase
2204 * @param $str string
2206 * @return string
2208 function ucfirst( $str ) {
2209 $o = ord( $str );
2210 if ( $o < 96 ) { // if already uppercase...
2211 return $str;
2212 } elseif ( $o < 128 ) {
2213 return ucfirst( $str ); // use PHP's ucfirst()
2214 } else {
2215 // fall back to more complex logic in case of multibyte strings
2216 return $this->uc( $str, true );
2221 * Convert a string to uppercase
2223 * @param $str string
2224 * @param $first bool
2226 * @return string
2228 function uc( $str, $first = false ) {
2229 if ( function_exists( 'mb_strtoupper' ) ) {
2230 if ( $first ) {
2231 if ( $this->isMultibyte( $str ) ) {
2232 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2233 } else {
2234 return ucfirst( $str );
2236 } else {
2237 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2239 } else {
2240 if ( $this->isMultibyte( $str ) ) {
2241 $x = $first ? '^' : '';
2242 return preg_replace_callback(
2243 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2244 array( $this, 'ucCallback' ),
2245 $str
2247 } else {
2248 return $first ? ucfirst( $str ) : strtoupper( $str );
2254 * @param $str string
2255 * @return mixed|string
2257 function lcfirst( $str ) {
2258 $o = ord( $str );
2259 if ( !$o ) {
2260 return strval( $str );
2261 } elseif ( $o >= 128 ) {
2262 return $this->lc( $str, true );
2263 } elseif ( $o > 96 ) {
2264 return $str;
2265 } else {
2266 $str[0] = strtolower( $str[0] );
2267 return $str;
2272 * @param $str string
2273 * @param $first bool
2274 * @return mixed|string
2276 function lc( $str, $first = false ) {
2277 if ( function_exists( 'mb_strtolower' ) ) {
2278 if ( $first ) {
2279 if ( $this->isMultibyte( $str ) ) {
2280 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2281 } else {
2282 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2284 } else {
2285 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2287 } else {
2288 if ( $this->isMultibyte( $str ) ) {
2289 $x = $first ? '^' : '';
2290 return preg_replace_callback(
2291 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2292 array( $this, 'lcCallback' ),
2293 $str
2295 } else {
2296 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2302 * @param $str string
2303 * @return bool
2305 function isMultibyte( $str ) {
2306 return (bool)preg_match( '/[\x80-\xff]/', $str );
2310 * @param $str string
2311 * @return mixed|string
2313 function ucwords( $str ) {
2314 if ( $this->isMultibyte( $str ) ) {
2315 $str = $this->lc( $str );
2317 // regexp to find first letter in each word (i.e. after each space)
2318 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2320 // function to use to capitalize a single char
2321 if ( function_exists( 'mb_strtoupper' ) ) {
2322 return preg_replace_callback(
2323 $replaceRegexp,
2324 array( $this, 'ucwordsCallbackMB' ),
2325 $str
2327 } else {
2328 return preg_replace_callback(
2329 $replaceRegexp,
2330 array( $this, 'ucwordsCallbackWiki' ),
2331 $str
2334 } else {
2335 return ucwords( strtolower( $str ) );
2340 * capitalize words at word breaks
2342 * @param $str string
2343 * @return mixed
2345 function ucwordbreaks( $str ) {
2346 if ( $this->isMultibyte( $str ) ) {
2347 $str = $this->lc( $str );
2349 // since \b doesn't work for UTF-8, we explicitely define word break chars
2350 $breaks = "[ \-\(\)\}\{\.,\?!]";
2352 // find first letter after word break
2353 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2355 if ( function_exists( 'mb_strtoupper' ) ) {
2356 return preg_replace_callback(
2357 $replaceRegexp,
2358 array( $this, 'ucwordbreaksCallbackMB' ),
2359 $str
2361 } else {
2362 return preg_replace_callback(
2363 $replaceRegexp,
2364 array( $this, 'ucwordsCallbackWiki' ),
2365 $str
2368 } else {
2369 return preg_replace_callback(
2370 '/\b([\w\x80-\xff]+)\b/',
2371 array( $this, 'ucwordbreaksCallbackAscii' ),
2372 $str
2378 * Return a case-folded representation of $s
2380 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2381 * and $s2 are the same except for the case of their characters. It is not
2382 * necessary for the value returned to make sense when displayed.
2384 * Do *not* perform any other normalisation in this function. If a caller
2385 * uses this function when it should be using a more general normalisation
2386 * function, then fix the caller.
2388 * @param $s string
2390 * @return string
2392 function caseFold( $s ) {
2393 return $this->uc( $s );
2397 * @param $s string
2398 * @return string
2400 function checkTitleEncoding( $s ) {
2401 if ( is_array( $s ) ) {
2402 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2404 # Check for non-UTF-8 URLs
2405 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2406 if ( !$ishigh ) {
2407 return $s;
2410 if ( function_exists( 'mb_check_encoding' ) ) {
2411 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2412 } else {
2413 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2414 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2416 if ( $isutf8 ) {
2417 return $s;
2420 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2424 * @return array
2426 function fallback8bitEncoding() {
2427 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2431 * Most writing systems use whitespace to break up words.
2432 * Some languages such as Chinese don't conventionally do this,
2433 * which requires special handling when breaking up words for
2434 * searching etc.
2436 * @return bool
2438 function hasWordBreaks() {
2439 return true;
2443 * Some languages such as Chinese require word segmentation,
2444 * Specify such segmentation when overridden in derived class.
2446 * @param $string String
2447 * @return String
2449 function segmentByWord( $string ) {
2450 return $string;
2454 * Some languages have special punctuation need to be normalized.
2455 * Make such changes here.
2457 * @param $string String
2458 * @return String
2460 function normalizeForSearch( $string ) {
2461 return self::convertDoubleWidth( $string );
2465 * convert double-width roman characters to single-width.
2466 * range: ff00-ff5f ~= 0020-007f
2468 * @param $string string
2470 * @return string
2472 protected static function convertDoubleWidth( $string ) {
2473 static $full = null;
2474 static $half = null;
2476 if ( $full === null ) {
2477 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2478 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2479 $full = str_split( $fullWidth, 3 );
2480 $half = str_split( $halfWidth );
2483 $string = str_replace( $full, $half, $string );
2484 return $string;
2488 * @param $string string
2489 * @param $pattern string
2490 * @return string
2492 protected static function insertSpace( $string, $pattern ) {
2493 $string = preg_replace( $pattern, " $1 ", $string );
2494 $string = preg_replace( '/ +/', ' ', $string );
2495 return $string;
2499 * @param $termsArray array
2500 * @return array
2502 function convertForSearchResult( $termsArray ) {
2503 # some languages, e.g. Chinese, need to do a conversion
2504 # in order for search results to be displayed correctly
2505 return $termsArray;
2509 * Get the first character of a string.
2511 * @param $s string
2512 * @return string
2514 function firstChar( $s ) {
2515 $matches = array();
2516 preg_match(
2517 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2518 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2520 $matches
2523 if ( isset( $matches[1] ) ) {
2524 if ( strlen( $matches[1] ) != 3 ) {
2525 return $matches[1];
2528 // Break down Hangul syllables to grab the first jamo
2529 $code = utf8ToCodepoint( $matches[1] );
2530 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2531 return $matches[1];
2532 } elseif ( $code < 0xb098 ) {
2533 return "\xe3\x84\xb1";
2534 } elseif ( $code < 0xb2e4 ) {
2535 return "\xe3\x84\xb4";
2536 } elseif ( $code < 0xb77c ) {
2537 return "\xe3\x84\xb7";
2538 } elseif ( $code < 0xb9c8 ) {
2539 return "\xe3\x84\xb9";
2540 } elseif ( $code < 0xbc14 ) {
2541 return "\xe3\x85\x81";
2542 } elseif ( $code < 0xc0ac ) {
2543 return "\xe3\x85\x82";
2544 } elseif ( $code < 0xc544 ) {
2545 return "\xe3\x85\x85";
2546 } elseif ( $code < 0xc790 ) {
2547 return "\xe3\x85\x87";
2548 } elseif ( $code < 0xcc28 ) {
2549 return "\xe3\x85\x88";
2550 } elseif ( $code < 0xce74 ) {
2551 return "\xe3\x85\x8a";
2552 } elseif ( $code < 0xd0c0 ) {
2553 return "\xe3\x85\x8b";
2554 } elseif ( $code < 0xd30c ) {
2555 return "\xe3\x85\x8c";
2556 } elseif ( $code < 0xd558 ) {
2557 return "\xe3\x85\x8d";
2558 } else {
2559 return "\xe3\x85\x8e";
2561 } else {
2562 return '';
2566 function initEncoding() {
2567 # Some languages may have an alternate char encoding option
2568 # (Esperanto X-coding, Japanese furigana conversion, etc)
2569 # If this language is used as the primary content language,
2570 # an override to the defaults can be set here on startup.
2574 * @param $s string
2575 * @return string
2577 function recodeForEdit( $s ) {
2578 # For some languages we'll want to explicitly specify
2579 # which characters make it into the edit box raw
2580 # or are converted in some way or another.
2581 global $wgEditEncoding;
2582 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2583 return $s;
2584 } else {
2585 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2590 * @param $s string
2591 * @return string
2593 function recodeInput( $s ) {
2594 # Take the previous into account.
2595 global $wgEditEncoding;
2596 if ( $wgEditEncoding != '' ) {
2597 $enc = $wgEditEncoding;
2598 } else {
2599 $enc = 'UTF-8';
2601 if ( $enc == 'UTF-8' ) {
2602 return $s;
2603 } else {
2604 return $this->iconv( $enc, 'UTF-8', $s );
2609 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2610 * also cleans up certain backwards-compatible sequences, converting them
2611 * to the modern Unicode equivalent.
2613 * This is language-specific for performance reasons only.
2615 * @param $s string
2617 * @return string
2619 function normalize( $s ) {
2620 global $wgAllUnicodeFixes;
2621 $s = UtfNormal::cleanUp( $s );
2622 if ( $wgAllUnicodeFixes ) {
2623 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2624 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2627 return $s;
2631 * Transform a string using serialized data stored in the given file (which
2632 * must be in the serialized subdirectory of $IP). The file contains pairs
2633 * mapping source characters to destination characters.
2635 * The data is cached in process memory. This will go faster if you have the
2636 * FastStringSearch extension.
2638 * @param $file string
2639 * @param $string string
2641 * @throws MWException
2642 * @return string
2644 function transformUsingPairFile( $file, $string ) {
2645 if ( !isset( $this->transformData[$file] ) ) {
2646 $data = wfGetPrecompiledData( $file );
2647 if ( $data === false ) {
2648 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2650 $this->transformData[$file] = new ReplacementArray( $data );
2652 return $this->transformData[$file]->replace( $string );
2656 * For right-to-left language support
2658 * @return bool
2660 function isRTL() {
2661 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2665 * Return the correct HTML 'dir' attribute value for this language.
2666 * @return String
2668 function getDir() {
2669 return $this->isRTL() ? 'rtl' : 'ltr';
2673 * Return 'left' or 'right' as appropriate alignment for line-start
2674 * for this language's text direction.
2676 * Should be equivalent to CSS3 'start' text-align value....
2678 * @return String
2680 function alignStart() {
2681 return $this->isRTL() ? 'right' : 'left';
2685 * Return 'right' or 'left' as appropriate alignment for line-end
2686 * for this language's text direction.
2688 * Should be equivalent to CSS3 'end' text-align value....
2690 * @return String
2692 function alignEnd() {
2693 return $this->isRTL() ? 'left' : 'right';
2697 * A hidden direction mark (LRM or RLM), depending on the language direction.
2698 * Unlike getDirMark(), this function returns the character as an HTML entity.
2699 * This function should be used when the output is guaranteed to be HTML,
2700 * because it makes the output HTML source code more readable. When
2701 * the output is plain text or can be escaped, getDirMark() should be used.
2703 * @param $opposite Boolean Get the direction mark opposite to your language
2704 * @return string
2706 function getDirMarkEntity( $opposite = false ) {
2707 if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
2708 return $this->isRTL() ? '&rlm;' : '&lrm;';
2712 * A hidden direction mark (LRM or RLM), depending on the language direction.
2713 * This function produces them as invisible Unicode characters and
2714 * the output may be hard to read and debug, so it should only be used
2715 * when the output is plain text or can be escaped. When the output is
2716 * HTML, use getDirMarkEntity() instead.
2718 * @param $opposite Boolean Get the direction mark opposite to your language
2719 * @return string
2721 function getDirMark( $opposite = false ) {
2722 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2723 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2724 if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
2725 return $this->isRTL() ? $rlm : $lrm;
2729 * @return array
2731 function capitalizeAllNouns() {
2732 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2736 * An arrow, depending on the language direction.
2738 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2739 * @return string
2741 function getArrow( $direction = 'forwards' ) {
2742 switch ( $direction ) {
2743 case 'forwards':
2744 return $this->isRTL() ? '←' : '→';
2745 case 'backwards':
2746 return $this->isRTL() ? '→' : '←';
2747 case 'left':
2748 return '←';
2749 case 'right':
2750 return '→';
2751 case 'up':
2752 return '↑';
2753 case 'down':
2754 return '↓';
2759 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2761 * @return bool
2763 function linkPrefixExtension() {
2764 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2768 * @return array
2770 function getMagicWords() {
2771 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2774 protected function doMagicHook() {
2775 if ( $this->mMagicHookDone ) {
2776 return;
2778 $this->mMagicHookDone = true;
2779 wfProfileIn( 'LanguageGetMagic' );
2780 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2781 wfProfileOut( 'LanguageGetMagic' );
2785 * Fill a MagicWord object with data from here
2787 * @param $mw
2789 function getMagic( $mw ) {
2790 $this->doMagicHook();
2792 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2793 $rawEntry = $this->mMagicExtensions[$mw->mId];
2794 } else {
2795 $magicWords = $this->getMagicWords();
2796 if ( isset( $magicWords[$mw->mId] ) ) {
2797 $rawEntry = $magicWords[$mw->mId];
2798 } else {
2799 $rawEntry = false;
2803 if ( !is_array( $rawEntry ) ) {
2804 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2805 } else {
2806 $mw->mCaseSensitive = $rawEntry[0];
2807 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2812 * Add magic words to the extension array
2814 * @param $newWords array
2816 function addMagicWordsByLang( $newWords ) {
2817 $fallbackChain = $this->getFallbackLanguages();
2818 $fallbackChain = array_reverse( $fallbackChain );
2819 foreach ( $fallbackChain as $code ) {
2820 if ( isset( $newWords[$code] ) ) {
2821 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2827 * Get special page names, as an associative array
2828 * case folded alias => real name
2830 function getSpecialPageAliases() {
2831 // Cache aliases because it may be slow to load them
2832 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2833 // Initialise array
2834 $this->mExtendedSpecialPageAliases =
2835 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2836 wfRunHooks( 'LanguageGetSpecialPageAliases',
2837 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2840 return $this->mExtendedSpecialPageAliases;
2844 * Italic is unsuitable for some languages
2846 * @param $text String: the text to be emphasized.
2847 * @return string
2849 function emphasize( $text ) {
2850 return "<em>$text</em>";
2854 * Normally we output all numbers in plain en_US style, that is
2855 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2856 * point twohundredthirtyfive. However this is not suitable for all
2857 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2858 * Icelandic just want to use commas instead of dots, and dots instead
2859 * of commas like "293.291,235".
2861 * An example of this function being called:
2862 * <code>
2863 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2864 * </code>
2866 * See LanguageGu.php for the Gujarati implementation and
2867 * $separatorTransformTable on MessageIs.php for
2868 * the , => . and . => , implementation.
2870 * @todo check if it's viable to use localeconv() for the decimal
2871 * separator thing.
2872 * @param $number Mixed: the string to be formatted, should be an integer
2873 * or a floating point number.
2874 * @param $nocommafy Bool: set to true for special numbers like dates
2875 * @return string
2877 public function formatNum( $number, $nocommafy = false ) {
2878 global $wgTranslateNumerals;
2879 if ( !$nocommafy ) {
2880 $number = $this->commafy( $number );
2881 $s = $this->separatorTransformTable();
2882 if ( $s ) {
2883 $number = strtr( $number, $s );
2887 if ( $wgTranslateNumerals ) {
2888 $s = $this->digitTransformTable();
2889 if ( $s ) {
2890 $number = strtr( $number, $s );
2894 return $number;
2898 * @param $number string
2899 * @return string
2901 function parseFormattedNumber( $number ) {
2902 $s = $this->digitTransformTable();
2903 if ( $s ) {
2904 $number = strtr( $number, array_flip( $s ) );
2907 $s = $this->separatorTransformTable();
2908 if ( $s ) {
2909 $number = strtr( $number, array_flip( $s ) );
2912 $number = strtr( $number, array( ',' => '' ) );
2913 return $number;
2917 * Adds commas to a given number
2918 * @since 1.19
2919 * @param $_ mixed
2920 * @return string
2922 function commafy( $_ ) {
2923 $digitGroupingPattern = $this->digitGroupingPattern();
2924 if ( $_ === null ) {
2925 return '';
2928 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2929 // default grouping is at thousands, use the same for ###,###,### pattern too.
2930 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2931 } else {
2932 // Ref: http://cldr.unicode.org/translation/number-patterns
2933 $sign = "";
2934 if ( intval( $_ ) < 0 ) {
2935 // For negative numbers apply the algorithm like positive number and add sign.
2936 $sign = "-";
2937 $_ = substr( $_, 1 );
2939 $numberpart = array();
2940 $decimalpart = array();
2941 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2942 preg_match( "/\d+/", $_, $numberpart );
2943 preg_match( "/\.\d*/", $_, $decimalpart );
2944 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2945 if ( $groupedNumber === $_ ) {
2946 // the string does not have any number part. Eg: .12345
2947 return $sign . $groupedNumber;
2949 $start = $end = strlen( $numberpart[0] );
2950 while ( $start > 0 ) {
2951 $match = $matches[0][$numMatches -1] ;
2952 $matchLen = strlen( $match );
2953 $start = $end - $matchLen;
2954 if ( $start < 0 ) {
2955 $start = 0;
2957 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2958 $end = $start;
2959 if ( $numMatches > 1 ) {
2960 // use the last pattern for the rest of the number
2961 $numMatches--;
2963 if ( $start > 0 ) {
2964 $groupedNumber = "," . $groupedNumber;
2967 return $sign . $groupedNumber;
2971 * @return String
2973 function digitGroupingPattern() {
2974 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
2978 * @return array
2980 function digitTransformTable() {
2981 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2985 * @return array
2987 function separatorTransformTable() {
2988 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2992 * Take a list of strings and build a locale-friendly comma-separated
2993 * list, using the local comma-separator message.
2994 * The last two strings are chained with an "and".
2996 * @param $l Array
2997 * @return string
2999 function listToText( array $l ) {
3000 $s = '';
3001 $m = count( $l ) - 1;
3002 if ( $m == 1 ) {
3003 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3004 } else {
3005 for ( $i = $m; $i >= 0; $i-- ) {
3006 if ( $i == $m ) {
3007 $s = $l[$i];
3008 } elseif ( $i == $m - 1 ) {
3009 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3010 } else {
3011 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3014 return $s;
3019 * Take a list of strings and build a locale-friendly comma-separated
3020 * list, using the local comma-separator message.
3021 * @param $list array of strings to put in a comma list
3022 * @return string
3024 function commaList( array $list ) {
3025 return implode(
3026 wfMsgExt(
3027 'comma-separator',
3028 array( 'parsemag', 'escapenoentities', 'language' => $this )
3030 $list
3035 * Take a list of strings and build a locale-friendly semicolon-separated
3036 * list, using the local semicolon-separator message.
3037 * @param $list array of strings to put in a semicolon list
3038 * @return string
3040 function semicolonList( array $list ) {
3041 return implode(
3042 wfMsgExt(
3043 'semicolon-separator',
3044 array( 'parsemag', 'escapenoentities', 'language' => $this )
3046 $list
3051 * Same as commaList, but separate it with the pipe instead.
3052 * @param $list array of strings to put in a pipe list
3053 * @return string
3055 function pipeList( array $list ) {
3056 return implode(
3057 wfMsgExt(
3058 'pipe-separator',
3059 array( 'escapenoentities', 'language' => $this )
3061 $list
3066 * Truncate a string to a specified length in bytes, appending an optional
3067 * string (e.g. for ellipses)
3069 * The database offers limited byte lengths for some columns in the database;
3070 * multi-byte character sets mean we need to ensure that only whole characters
3071 * are included, otherwise broken characters can be passed to the user
3073 * If $length is negative, the string will be truncated from the beginning
3075 * @param $string String to truncate
3076 * @param $length Int: maximum length (including ellipses)
3077 * @param $ellipsis String to append to the truncated text
3078 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3079 * $adjustLength was introduced in 1.18, before that behaved as if false.
3080 * @return string
3082 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3083 # Use the localized ellipsis character
3084 if ( $ellipsis == '...' ) {
3085 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3087 # Check if there is no need to truncate
3088 if ( $length == 0 ) {
3089 return $ellipsis; // convention
3090 } elseif ( strlen( $string ) <= abs( $length ) ) {
3091 return $string; // no need to truncate
3093 $stringOriginal = $string;
3094 # If ellipsis length is >= $length then we can't apply $adjustLength
3095 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3096 $string = $ellipsis; // this can be slightly unexpected
3097 # Otherwise, truncate and add ellipsis...
3098 } else {
3099 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3100 if ( $length > 0 ) {
3101 $length -= $eLength;
3102 $string = substr( $string, 0, $length ); // xyz...
3103 $string = $this->removeBadCharLast( $string );
3104 $string = $string . $ellipsis;
3105 } else {
3106 $length += $eLength;
3107 $string = substr( $string, $length ); // ...xyz
3108 $string = $this->removeBadCharFirst( $string );
3109 $string = $ellipsis . $string;
3112 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3113 # This check is *not* redundant if $adjustLength, due to the single case where
3114 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3115 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3116 return $string;
3117 } else {
3118 return $stringOriginal;
3123 * Remove bytes that represent an incomplete Unicode character
3124 * at the end of string (e.g. bytes of the char are missing)
3126 * @param $string String
3127 * @return string
3129 protected function removeBadCharLast( $string ) {
3130 if ( $string != '' ) {
3131 $char = ord( $string[strlen( $string ) - 1] );
3132 $m = array();
3133 if ( $char >= 0xc0 ) {
3134 # We got the first byte only of a multibyte char; remove it.
3135 $string = substr( $string, 0, -1 );
3136 } elseif ( $char >= 0x80 &&
3137 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3138 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3140 # We chopped in the middle of a character; remove it
3141 $string = $m[1];
3144 return $string;
3148 * Remove bytes that represent an incomplete Unicode character
3149 * at the start of string (e.g. bytes of the char are missing)
3151 * @param $string String
3152 * @return string
3154 protected function removeBadCharFirst( $string ) {
3155 if ( $string != '' ) {
3156 $char = ord( $string[0] );
3157 if ( $char >= 0x80 && $char < 0xc0 ) {
3158 # We chopped in the middle of a character; remove the whole thing
3159 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3162 return $string;
3166 * Truncate a string of valid HTML to a specified length in bytes,
3167 * appending an optional string (e.g. for ellipses), and return valid HTML
3169 * This is only intended for styled/linked text, such as HTML with
3170 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3171 * Also, this will not detect things like "display:none" CSS.
3173 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3175 * @param string $text HTML string to truncate
3176 * @param int $length (zero/positive) Maximum length (including ellipses)
3177 * @param string $ellipsis String to append to the truncated text
3178 * @return string
3180 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3181 # Use the localized ellipsis character
3182 if ( $ellipsis == '...' ) {
3183 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
3185 # Check if there is clearly no need to truncate
3186 if ( $length <= 0 ) {
3187 return $ellipsis; // no text shown, nothing to format (convention)
3188 } elseif ( strlen( $text ) <= $length ) {
3189 return $text; // string short enough even *with* HTML (short-circuit)
3192 $dispLen = 0; // innerHTML legth so far
3193 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3194 $tagType = 0; // 0-open, 1-close
3195 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3196 $entityState = 0; // 0-not entity, 1-entity
3197 $tag = $ret = ''; // accumulated tag name, accumulated result string
3198 $openTags = array(); // open tag stack
3199 $maybeState = null; // possible truncation state
3201 $textLen = strlen( $text );
3202 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3203 for ( $pos = 0; true; ++$pos ) {
3204 # Consider truncation once the display length has reached the maximim.
3205 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3206 # Check that we're not in the middle of a bracket/entity...
3207 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3208 if ( !$testingEllipsis ) {
3209 $testingEllipsis = true;
3210 # Save where we are; we will truncate here unless there turn out to
3211 # be so few remaining characters that truncation is not necessary.
3212 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3213 $maybeState = array( $ret, $openTags ); // save state
3215 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3216 # String in fact does need truncation, the truncation point was OK.
3217 list( $ret, $openTags ) = $maybeState; // reload state
3218 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3219 $ret .= $ellipsis; // add ellipsis
3220 break;
3223 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3225 # Read the next char...
3226 $ch = $text[$pos];
3227 $lastCh = $pos ? $text[$pos - 1] : '';
3228 $ret .= $ch; // add to result string
3229 if ( $ch == '<' ) {
3230 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3231 $entityState = 0; // for bad HTML
3232 $bracketState = 1; // tag started (checking for backslash)
3233 } elseif ( $ch == '>' ) {
3234 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3235 $entityState = 0; // for bad HTML
3236 $bracketState = 0; // out of brackets
3237 } elseif ( $bracketState == 1 ) {
3238 if ( $ch == '/' ) {
3239 $tagType = 1; // close tag (e.g. "</span>")
3240 } else {
3241 $tagType = 0; // open tag (e.g. "<span>")
3242 $tag .= $ch;
3244 $bracketState = 2; // building tag name
3245 } elseif ( $bracketState == 2 ) {
3246 if ( $ch != ' ' ) {
3247 $tag .= $ch;
3248 } else {
3249 // Name found (e.g. "<a href=..."), add on tag attributes...
3250 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3252 } elseif ( $bracketState == 0 ) {
3253 if ( $entityState ) {
3254 if ( $ch == ';' ) {
3255 $entityState = 0;
3256 $dispLen++; // entity is one displayed char
3258 } else {
3259 if ( $neLength == 0 && !$maybeState ) {
3260 // Save state without $ch. We want to *hit* the first
3261 // display char (to get tags) but not *use* it if truncating.
3262 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3264 if ( $ch == '&' ) {
3265 $entityState = 1; // entity found, (e.g. "&#160;")
3266 } else {
3267 $dispLen++; // this char is displayed
3268 // Add the next $max display text chars after this in one swoop...
3269 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3270 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3271 $dispLen += $skipped;
3272 $pos += $skipped;
3277 // Close the last tag if left unclosed by bad HTML
3278 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3279 while ( count( $openTags ) > 0 ) {
3280 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3282 return $ret;
3286 * truncateHtml() helper function
3287 * like strcspn() but adds the skipped chars to $ret
3289 * @param $ret
3290 * @param $text
3291 * @param $search
3292 * @param $start
3293 * @param $len
3294 * @return int
3296 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3297 if ( $len === null ) {
3298 $len = -1; // -1 means "no limit" for strcspn
3299 } elseif ( $len < 0 ) {
3300 $len = 0; // sanity
3302 $skipCount = 0;
3303 if ( $start < strlen( $text ) ) {
3304 $skipCount = strcspn( $text, $search, $start, $len );
3305 $ret .= substr( $text, $start, $skipCount );
3307 return $skipCount;
3311 * truncateHtml() helper function
3312 * (a) push or pop $tag from $openTags as needed
3313 * (b) clear $tag value
3314 * @param &$tag string Current HTML tag name we are looking at
3315 * @param $tagType int (0-open tag, 1-close tag)
3316 * @param $lastCh string Character before the '>' that ended this tag
3317 * @param &$openTags array Open tag stack (not accounting for $tag)
3319 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3320 $tag = ltrim( $tag );
3321 if ( $tag != '' ) {
3322 if ( $tagType == 0 && $lastCh != '/' ) {
3323 $openTags[] = $tag; // tag opened (didn't close itself)
3324 } elseif ( $tagType == 1 ) {
3325 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3326 array_pop( $openTags ); // tag closed
3329 $tag = '';
3334 * Grammatical transformations, needed for inflected languages
3335 * Invoked by putting {{grammar:case|word}} in a message
3337 * @param $word string
3338 * @param $case string
3339 * @return string
3341 function convertGrammar( $word, $case ) {
3342 global $wgGrammarForms;
3343 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3344 return $wgGrammarForms[$this->getCode()][$case][$word];
3346 return $word;
3349 * Get the grammar forms for the content language
3350 * @return array of grammar forms
3351 * @since 1.20
3353 function getGrammarForms() {
3354 global $wgGrammarForms;
3355 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3356 return $wgGrammarForms[$this->getCode()];
3358 return array();
3361 * Provides an alternative text depending on specified gender.
3362 * Usage {{gender:username|masculine|feminine|neutral}}.
3363 * username is optional, in which case the gender of current user is used,
3364 * but only in (some) interface messages; otherwise default gender is used.
3366 * If no forms are given, an empty string is returned. If only one form is
3367 * given, it will be returned unconditionally. These details are implied by
3368 * the caller and cannot be overridden in subclasses.
3370 * If more than one form is given, the default is to use the neutral one
3371 * if it is specified, and to use the masculine one otherwise. These
3372 * details can be overridden in subclasses.
3374 * @param $gender string
3375 * @param $forms array
3377 * @return string
3379 function gender( $gender, $forms ) {
3380 if ( !count( $forms ) ) {
3381 return '';
3383 $forms = $this->preConvertPlural( $forms, 2 );
3384 if ( $gender === 'male' ) {
3385 return $forms[0];
3387 if ( $gender === 'female' ) {
3388 return $forms[1];
3390 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3394 * Plural form transformations, needed for some languages.
3395 * For example, there are 3 form of plural in Russian and Polish,
3396 * depending on "count mod 10". See [[w:Plural]]
3397 * For English it is pretty simple.
3399 * Invoked by putting {{plural:count|wordform1|wordform2}}
3400 * or {{plural:count|wordform1|wordform2|wordform3}}
3402 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3404 * @param $count Integer: non-localized number
3405 * @param $forms Array: different plural forms
3406 * @return string Correct form of plural for $count in this language
3408 function convertPlural( $count, $forms ) {
3409 if ( !count( $forms ) ) {
3410 return '';
3412 $forms = $this->preConvertPlural( $forms, 2 );
3414 return ( $count == 1 ) ? $forms[0] : $forms[1];
3418 * Checks that convertPlural was given an array and pads it to requested
3419 * amount of forms by copying the last one.
3421 * @param $count Integer: How many forms should there be at least
3422 * @param $forms Array of forms given to convertPlural
3423 * @return array Padded array of forms or an exception if not an array
3425 protected function preConvertPlural( /* Array */ $forms, $count ) {
3426 while ( count( $forms ) < $count ) {
3427 $forms[] = $forms[count( $forms ) - 1];
3429 return $forms;
3433 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3434 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3435 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3436 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3437 * match up with it.
3439 * @param $str String: the validated block duration in English
3440 * @return string Somehow translated block duration
3441 * @see LanguageFi.php for example implementation
3443 function translateBlockExpiry( $str ) {
3444 $duration = SpecialBlock::getSuggestedDurations( $this );
3445 foreach ( $duration as $show => $value ) {
3446 if ( strcmp( $str, $value ) == 0 ) {
3447 return htmlspecialchars( trim( $show ) );
3451 // Since usually only infinite or indefinite is only on list, so try
3452 // equivalents if still here.
3453 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3454 if ( in_array( $str, $indefs ) ) {
3455 foreach ( $indefs as $val ) {
3456 $show = array_search( $val, $duration, true );
3457 if ( $show !== false ) {
3458 return htmlspecialchars( trim( $show ) );
3462 // If all else fails, return the original string.
3463 return $str;
3467 * languages like Chinese need to be segmented in order for the diff
3468 * to be of any use
3470 * @param $text String
3471 * @return String
3473 public function segmentForDiff( $text ) {
3474 return $text;
3478 * and unsegment to show the result
3480 * @param $text String
3481 * @return String
3483 public function unsegmentForDiff( $text ) {
3484 return $text;
3488 * Return the LanguageConverter used in the Language
3490 * @since 1.19
3491 * @return LanguageConverter
3493 public function getConverter() {
3494 return $this->mConverter;
3498 * convert text to all supported variants
3500 * @param $text string
3501 * @return array
3503 public function autoConvertToAllVariants( $text ) {
3504 return $this->mConverter->autoConvertToAllVariants( $text );
3508 * convert text to different variants of a language.
3510 * @param $text string
3511 * @return string
3513 public function convert( $text ) {
3514 return $this->mConverter->convert( $text );
3518 * Convert a Title object to a string in the preferred variant
3520 * @param $title Title
3521 * @return string
3523 public function convertTitle( $title ) {
3524 return $this->mConverter->convertTitle( $title );
3528 * Check if this is a language with variants
3530 * @return bool
3532 public function hasVariants() {
3533 return sizeof( $this->getVariants() ) > 1;
3537 * Check if the language has the specific variant
3539 * @since 1.19
3540 * @param $variant string
3541 * @return bool
3543 public function hasVariant( $variant ) {
3544 return (bool)$this->mConverter->validateVariant( $variant );
3548 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3550 * @param $text string
3551 * @return string
3553 public function armourMath( $text ) {
3554 return $this->mConverter->armourMath( $text );
3558 * Perform output conversion on a string, and encode for safe HTML output.
3559 * @param $text String text to be converted
3560 * @param $isTitle Bool whether this conversion is for the article title
3561 * @return string
3562 * @todo this should get integrated somewhere sane
3564 public function convertHtml( $text, $isTitle = false ) {
3565 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3569 * @param $key string
3570 * @return string
3572 public function convertCategoryKey( $key ) {
3573 return $this->mConverter->convertCategoryKey( $key );
3577 * Get the list of variants supported by this language
3578 * see sample implementation in LanguageZh.php
3580 * @return array an array of language codes
3582 public function getVariants() {
3583 return $this->mConverter->getVariants();
3587 * @return string
3589 public function getPreferredVariant() {
3590 return $this->mConverter->getPreferredVariant();
3594 * @return string
3596 public function getDefaultVariant() {
3597 return $this->mConverter->getDefaultVariant();
3601 * @return string
3603 public function getURLVariant() {
3604 return $this->mConverter->getURLVariant();
3608 * If a language supports multiple variants, it is
3609 * possible that non-existing link in one variant
3610 * actually exists in another variant. this function
3611 * tries to find it. See e.g. LanguageZh.php
3613 * @param $link String: the name of the link
3614 * @param $nt Mixed: the title object of the link
3615 * @param $ignoreOtherCond Boolean: to disable other conditions when
3616 * we need to transclude a template or update a category's link
3617 * @return null the input parameters may be modified upon return
3619 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3620 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3624 * If a language supports multiple variants, converts text
3625 * into an array of all possible variants of the text:
3626 * 'variant' => text in that variant
3628 * @deprecated since 1.17 Use autoConvertToAllVariants()
3630 * @param $text string
3632 * @return string
3634 public function convertLinkToAllVariants( $text ) {
3635 return $this->mConverter->convertLinkToAllVariants( $text );
3639 * returns language specific options used by User::getPageRenderHash()
3640 * for example, the preferred language variant
3642 * @return string
3644 function getExtraHashOptions() {
3645 return $this->mConverter->getExtraHashOptions();
3649 * For languages that support multiple variants, the title of an
3650 * article may be displayed differently in different variants. this
3651 * function returns the apporiate title defined in the body of the article.
3653 * @return string
3655 public function getParsedTitle() {
3656 return $this->mConverter->getParsedTitle();
3660 * Enclose a string with the "no conversion" tag. This is used by
3661 * various functions in the Parser
3663 * @param $text String: text to be tagged for no conversion
3664 * @param $noParse bool
3665 * @return string the tagged text
3667 public function markNoConversion( $text, $noParse = false ) {
3668 return $this->mConverter->markNoConversion( $text, $noParse );
3672 * A regular expression to match legal word-trailing characters
3673 * which should be merged onto a link of the form [[foo]]bar.
3675 * @return string
3677 public function linkTrail() {
3678 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3682 * @return Language
3684 function getLangObj() {
3685 return $this;
3689 * Get the RFC 3066 code for this language object
3691 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3692 * htmlspecialchars() or similar
3694 * @return string
3696 public function getCode() {
3697 return $this->mCode;
3701 * Get the code in Bcp47 format which we can use
3702 * inside of html lang="" tags.
3704 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3705 * htmlspecialchars() or similar.
3707 * @since 1.19
3708 * @return string
3710 public function getHtmlCode() {
3711 if ( is_null( $this->mHtmlCode ) ) {
3712 $this->mHtmlCode = wfBCP47( $this->getCode() );
3714 return $this->mHtmlCode;
3718 * @param $code string
3720 public function setCode( $code ) {
3721 $this->mCode = $code;
3722 // Ensure we don't leave an incorrect html code lying around
3723 $this->mHtmlCode = null;
3727 * Get the name of a file for a certain language code
3728 * @param $prefix string Prepend this to the filename
3729 * @param $code string Language code
3730 * @param $suffix string Append this to the filename
3731 * @throws MWException
3732 * @return string $prefix . $mangledCode . $suffix
3734 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3735 // Protect against path traversal
3736 if ( !Language::isValidCode( $code )
3737 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3739 throw new MWException( "Invalid language code \"$code\"" );
3742 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3746 * Get the language code from a file name. Inverse of getFileName()
3747 * @param $filename string $prefix . $languageCode . $suffix
3748 * @param $prefix string Prefix before the language code
3749 * @param $suffix string Suffix after the language code
3750 * @return string Language code, or false if $prefix or $suffix isn't found
3752 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3753 $m = null;
3754 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3755 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3756 if ( !count( $m ) ) {
3757 return false;
3759 return str_replace( '_', '-', strtolower( $m[1] ) );
3763 * @param $code string
3764 * @return string
3766 public static function getMessagesFileName( $code ) {
3767 global $IP;
3768 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3769 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3770 return $file;
3774 * @param $code string
3775 * @return string
3777 public static function getClassFileName( $code ) {
3778 global $IP;
3779 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3783 * Get the first fallback for a given language.
3785 * @param $code string
3787 * @return bool|string
3789 public static function getFallbackFor( $code ) {
3790 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3791 return false;
3792 } else {
3793 $fallbacks = self::getFallbacksFor( $code );
3794 $first = array_shift( $fallbacks );
3795 return $first;
3800 * Get the ordered list of fallback languages.
3802 * @since 1.19
3803 * @param $code string Language code
3804 * @return array
3806 public static function getFallbacksFor( $code ) {
3807 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3808 return array();
3809 } else {
3810 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3811 $v = array_map( 'trim', explode( ',', $v ) );
3812 if ( $v[count( $v ) - 1] !== 'en' ) {
3813 $v[] = 'en';
3815 return $v;
3820 * Get all messages for a given language
3821 * WARNING: this may take a long time. If you just need all message *keys*
3822 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3824 * @param $code string
3826 * @return array
3828 public static function getMessagesFor( $code ) {
3829 return self::getLocalisationCache()->getItem( $code, 'messages' );
3833 * Get a message for a given language
3835 * @param $key string
3836 * @param $code string
3838 * @return string
3840 public static function getMessageFor( $key, $code ) {
3841 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3845 * Get all message keys for a given language. This is a faster alternative to
3846 * array_keys( Language::getMessagesFor( $code ) )
3848 * @since 1.19
3849 * @param $code string Language code
3850 * @return array of message keys (strings)
3852 public static function getMessageKeysFor( $code ) {
3853 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3857 * @param $talk
3858 * @return mixed
3860 function fixVariableInNamespace( $talk ) {
3861 if ( strpos( $talk, '$1' ) === false ) {
3862 return $talk;
3865 global $wgMetaNamespace;
3866 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3868 # Allow grammar transformations
3869 # Allowing full message-style parsing would make simple requests
3870 # such as action=raw much more expensive than they need to be.
3871 # This will hopefully cover most cases.
3872 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3873 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3874 return str_replace( ' ', '_', $talk );
3878 * @param $m string
3879 * @return string
3881 function replaceGrammarInNamespace( $m ) {
3882 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3886 * @throws MWException
3887 * @return array
3889 static function getCaseMaps() {
3890 static $wikiUpperChars, $wikiLowerChars;
3891 if ( isset( $wikiUpperChars ) ) {
3892 return array( $wikiUpperChars, $wikiLowerChars );
3895 wfProfileIn( __METHOD__ );
3896 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3897 if ( $arr === false ) {
3898 throw new MWException(
3899 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3901 $wikiUpperChars = $arr['wikiUpperChars'];
3902 $wikiLowerChars = $arr['wikiLowerChars'];
3903 wfProfileOut( __METHOD__ );
3904 return array( $wikiUpperChars, $wikiLowerChars );
3908 * Decode an expiry (block, protection, etc) which has come from the DB
3910 * @FIXME: why are we returnings DBMS-dependent strings???
3912 * @param $expiry String: Database expiry String
3913 * @param $format Bool|Int true to process using language functions, or TS_ constant
3914 * to return the expiry in a given timestamp
3915 * @return String
3917 public function formatExpiry( $expiry, $format = true ) {
3918 static $infinity, $infinityMsg;
3919 if ( $infinity === null ) {
3920 $infinityMsg = wfMessage( 'infiniteblock' );
3921 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3924 if ( $expiry == '' || $expiry == $infinity ) {
3925 return $format === true
3926 ? $infinityMsg
3927 : $infinity;
3928 } else {
3929 return $format === true
3930 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3931 : wfTimestamp( $format, $expiry );
3936 * @todo Document
3937 * @param $seconds int|float
3938 * @param $format Array Optional
3939 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
3940 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
3941 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
3942 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
3943 * @return string
3945 function formatTimePeriod( $seconds, $format = array() ) {
3946 if ( !is_array( $format ) ) {
3947 $format = array( 'avoid' => $format ); // For backwards compatibility
3949 if ( !isset( $format['avoid'] ) ) {
3950 $format['avoid'] = false;
3952 if ( !isset( $format['noabbrevs' ] ) ) {
3953 $format['noabbrevs'] = false;
3955 $secondsMsg = wfMessage(
3956 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
3957 $minutesMsg = wfMessage(
3958 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
3959 $hoursMsg = wfMessage(
3960 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
3961 $daysMsg = wfMessage(
3962 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
3964 if ( round( $seconds * 10 ) < 100 ) {
3965 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3966 $s = $secondsMsg->params( $s )->text();
3967 } elseif ( round( $seconds ) < 60 ) {
3968 $s = $this->formatNum( round( $seconds ) );
3969 $s = $secondsMsg->params( $s )->text();
3970 } elseif ( round( $seconds ) < 3600 ) {
3971 $minutes = floor( $seconds / 60 );
3972 $secondsPart = round( fmod( $seconds, 60 ) );
3973 if ( $secondsPart == 60 ) {
3974 $secondsPart = 0;
3975 $minutes++;
3977 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3978 $s .= ' ';
3979 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3980 } elseif ( round( $seconds ) <= 2 * 86400 ) {
3981 $hours = floor( $seconds / 3600 );
3982 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3983 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3984 if ( $secondsPart == 60 ) {
3985 $secondsPart = 0;
3986 $minutes++;
3988 if ( $minutes == 60 ) {
3989 $minutes = 0;
3990 $hours++;
3992 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
3993 $s .= ' ';
3994 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
3995 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
3996 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
3998 } else {
3999 $days = floor( $seconds / 86400 );
4000 if ( $format['avoid'] === 'avoidminutes' ) {
4001 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4002 if ( $hours == 24 ) {
4003 $hours = 0;
4004 $days++;
4006 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4007 $s .= ' ';
4008 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4009 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4010 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4011 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4012 if ( $minutes == 60 ) {
4013 $minutes = 0;
4014 $hours++;
4016 if ( $hours == 24 ) {
4017 $hours = 0;
4018 $days++;
4020 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4021 $s .= ' ';
4022 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4023 $s .= ' ';
4024 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4025 } else {
4026 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4027 $s .= ' ';
4028 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4031 return $s;
4035 * Format a bitrate for output, using an appropriate
4036 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4038 * This use base 1000. For base 1024 use formatSize(), for another base
4039 * see formatComputingNumbers()
4041 * @param $bps int
4042 * @return string
4044 function formatBitrate( $bps ) {
4045 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4049 * @param $size int Size of the unit
4050 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4051 * @param $messageKey string Message key to be uesd
4052 * @return string
4054 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4055 if ( $size <= 0 ) {
4056 return str_replace( '$1', $this->formatNum( $size ),
4057 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4060 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4061 $index = 0;
4063 $maxIndex = count( $sizes ) - 1;
4064 while ( $size >= $boundary && $index < $maxIndex ) {
4065 $index++;
4066 $size /= $boundary;
4069 // For small sizes no decimal places necessary
4070 $round = 0;
4071 if ( $index > 1 ) {
4072 // For MB and bigger two decimal places are smarter
4073 $round = 2;
4075 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4077 $size = round( $size, $round );
4078 $text = $this->getMessageFromDB( $msg );
4079 return str_replace( '$1', $this->formatNum( $size ), $text );
4083 * Format a size in bytes for output, using an appropriate
4084 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4086 * This method use base 1024. For base 1000 use formatBitrate(), for
4087 * another base see formatComputingNumbers()
4089 * @param $size int Size to format
4090 * @return string Plain text (not HTML)
4092 function formatSize( $size ) {
4093 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4097 * Make a list item, used by various special pages
4099 * @param $page String Page link
4100 * @param $details String Text between brackets
4101 * @param $oppositedm Boolean Add the direction mark opposite to your
4102 * language, to display text properly
4103 * @return String
4105 function specialList( $page, $details, $oppositedm = true ) {
4106 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4107 $this->getDirMark();
4108 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4109 wfMsgExt( 'parentheses', array( 'escape', 'replaceafter', 'language' => $this ), $details ) : '';
4110 return $page . $details;
4114 * Generate (prev x| next x) (20|50|100...) type links for paging
4116 * @param $title Title object to link
4117 * @param $offset Integer offset parameter
4118 * @param $limit Integer limit parameter
4119 * @param $query array|String optional URL query parameter string
4120 * @param $atend Bool optional param for specified if this is the last page
4121 * @return String
4123 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4124 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4126 # Make 'previous' link
4127 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4128 if ( $offset > 0 ) {
4129 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4130 $query, $prev, 'prevn-title', 'mw-prevlink' );
4131 } else {
4132 $plink = htmlspecialchars( $prev );
4135 # Make 'next' link
4136 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4137 if ( $atend ) {
4138 $nlink = htmlspecialchars( $next );
4139 } else {
4140 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4141 $query, $next, 'prevn-title', 'mw-nextlink' );
4144 # Make links to set number of items per page
4145 $numLinks = array();
4146 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4147 $numLinks[] = $this->numLink( $title, $offset, $num,
4148 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4151 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4152 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4156 * Helper function for viewPrevNext() that generates links
4158 * @param $title Title object to link
4159 * @param $offset Integer offset parameter
4160 * @param $limit Integer limit parameter
4161 * @param $query Array extra query parameters
4162 * @param $link String text to use for the link; will be escaped
4163 * @param $tooltipMsg String name of the message to use as tooltip
4164 * @param $class String value of the "class" attribute of the link
4165 * @return String HTML fragment
4167 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4168 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4169 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4170 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4171 'title' => $tooltip, 'class' => $class ), $link );
4175 * Get the conversion rule title, if any.
4177 * @return string
4179 public function getConvRuleTitle() {
4180 return $this->mConverter->getConvRuleTitle();