Partly disable title conversion if variant == main language code
[lhc/web/wiklou.git] / languages / Language.php
1 <?php
2 /**
3 * Internationalisation code.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Language
22 */
23
24 /**
25 * @defgroup Language Language
26 */
27
28 if ( !defined( 'MEDIAWIKI' ) ) {
29 echo "This file is part of MediaWiki, it is not a valid entry point.\n";
30 exit( 1 );
31 }
32
33 # Read language names
34 global $wgLanguageNames;
35 require_once( __DIR__ . '/Names.php' );
36
37 if ( function_exists( 'mb_strtoupper' ) ) {
38 mb_internal_encoding( 'UTF-8' );
39 }
40
41 /**
42 * a fake language converter
43 *
44 * @ingroup Language
45 */
46 class FakeConverter {
47 /**
48 * @var Language
49 */
50 public $mLang;
51 function __construct( $langobj ) { $this->mLang = $langobj; }
52 function autoConvertToAllVariants( $text ) { return array( $this->mLang->getCode() => $text ); }
53 function convert( $t ) { return $t; }
54 function convertTo( $text, $variant ) { return $text; }
55 function convertTitle( $t ) { return $t->getPrefixedText(); }
56 function convertNamespace( $ns ) { return $this->mLang->getFormattedNsText( $ns ); }
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; }
69 }
70
71 /**
72 * Internationalisation code
73 * @ingroup Language
74 */
75 class Language {
76
77 /**
78 * @var LanguageConverter
79 */
80 public $mConverter;
81
82 public $mVariants, $mCode, $mLoaded = false;
83 public $mMagicExtensions = array(), $mMagicHookDone = false;
84 private $mHtmlCode = null;
85
86 public $dateFormatStrings = array();
87 public $mExtendedSpecialPageAliases;
88
89 protected $namespaceNames, $mNamespaceIds, $namespaceAliases;
90
91 /**
92 * ReplacementArray object caches
93 */
94 public $transformData = array();
95
96 /**
97 * @var LocalisationCache
98 */
99 static public $dataCache;
100
101 static public $mLangObjCache = array();
102
103 static public $mWeekdayMsgs = array(
104 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
105 'friday', 'saturday'
106 );
107
108 static public $mWeekdayAbbrevMsgs = array(
109 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
110 );
111
112 static public $mMonthMsgs = array(
113 'january', 'february', 'march', 'april', 'may_long', 'june',
114 'july', 'august', 'september', 'october', 'november',
115 'december'
116 );
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'
121 );
122 static public $mMonthAbbrevMsgs = array(
123 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
124 'sep', 'oct', 'nov', 'dec'
125 );
126
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'
132 );
133
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'
140 );
141
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'
148 );
149
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'
155 );
156
157 /**
158 * @since 1.20
159 * @var array
160 */
161 static public $durationIntervals = array(
162 'millennia' => 31556952000,
163 'centuries' => 3155695200,
164 'decades' => 315569520,
165 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
166 'weeks' => 604800,
167 'days' => 86400,
168 'hours' => 3600,
169 'minutes' => 60,
170 'seconds' => 1,
171 );
172
173 /**
174 * Get a cached or new language object for a given language code
175 * @param $code String
176 * @return Language
177 */
178 static function factory( $code ) {
179 global $wgDummyLanguageCodes, $wgLangObjCacheSize;
180
181 if ( isset( $wgDummyLanguageCodes[$code] ) ) {
182 $code = $wgDummyLanguageCodes[$code];
183 }
184
185 // get the language object to process
186 $langObj = isset( self::$mLangObjCache[$code] )
187 ? self::$mLangObjCache[$code]
188 : self::newFromCode( $code );
189
190 // merge the language object in to get it up front in the cache
191 self::$mLangObjCache = array_merge( array( $code => $langObj ), self::$mLangObjCache );
192 // get rid of the oldest ones in case we have an overflow
193 self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
194
195 return $langObj;
196 }
197
198 /**
199 * Create a language object for a given language code
200 * @param $code String
201 * @throws MWException
202 * @return Language
203 */
204 protected static function newFromCode( $code ) {
205 // Protect against path traversal below
206 if ( !Language::isValidCode( $code )
207 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
208 {
209 throw new MWException( "Invalid language code \"$code\"" );
210 }
211
212 if ( !Language::isValidBuiltInCode( $code ) ) {
213 // It's not possible to customise this code with class files, so
214 // just return a Language object. This is to support uselang= hacks.
215 $lang = new Language;
216 $lang->setCode( $code );
217 return $lang;
218 }
219
220 // Check if there is a language class for the code
221 $class = self::classFromCode( $code );
222 self::preloadLanguageClass( $class );
223 if ( MWInit::classExists( $class ) ) {
224 $lang = new $class;
225 return $lang;
226 }
227
228 // Keep trying the fallback list until we find an existing class
229 $fallbacks = Language::getFallbacksFor( $code );
230 foreach ( $fallbacks as $fallbackCode ) {
231 if ( !Language::isValidBuiltInCode( $fallbackCode ) ) {
232 throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
233 }
234
235 $class = self::classFromCode( $fallbackCode );
236 self::preloadLanguageClass( $class );
237 if ( MWInit::classExists( $class ) ) {
238 $lang = Language::newFromCode( $fallbackCode );
239 $lang->setCode( $code );
240 return $lang;
241 }
242 }
243
244 throw new MWException( "Invalid fallback sequence for language '$code'" );
245 }
246
247 /**
248 * Checks whether any localisation is available for that language tag
249 * in MediaWiki (MessagesXx.php exists).
250 *
251 * @param string $code Language tag (in lower case)
252 * @return bool Whether language is supported
253 * @since 1.21
254 */
255 public static function isSupportedLanguage( $code ) {
256 return $code === strtolower( $code ) && is_readable( self::getMessagesFileName( $code ) );
257 }
258
259 /**
260 * Returns true if a language code string is a well-formed language tag
261 * according to RFC 5646.
262 * This function only checks well-formedness; it doesn't check that
263 * language, script or variant codes actually exist in the repositories.
264 *
265 * Based on regexes by Mark Davis of the Unicode Consortium:
266 * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
267 *
268 * @param $code string
269 * @param $lenient boolean Whether to allow '_' as separator. The default is only '-'.
270 *
271 * @return bool
272 * @since 1.21
273 */
274 public static function isWellFormedLanguageTag( $code, $lenient = false ) {
275 $alpha = '[a-z]';
276 $digit = '[0-9]';
277 $alphanum = '[a-z0-9]';
278 $x = 'x'; # private use singleton
279 $singleton = '[a-wy-z]'; # other singleton
280 $s = $lenient ? '[-_]' : '-';
281
282 $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
283 $script = "$alpha{4}"; # ISO 15924
284 $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
285 $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
286 $extension = "$singleton(?:$s$alphanum{2,8})+";
287 $privateUse = "$x(?:$s$alphanum{1,8})+";
288
289 # Define certain grandfathered codes, since otherwise the regex is pretty useless.
290 # Since these are limited, this is safe even later changes to the registry --
291 # the only oddity is that it might change the type of the tag, and thus
292 # the results from the capturing groups.
293 # http://www.iana.org/assignments/language-subtag-registry
294
295 $grandfathered = "en{$s}GB{$s}oed"
296 . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
297 . "|no{$s}(?:bok|nyn)"
298 . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
299 . "|zh{$s}min{$s}nan";
300
301 $variantList = "$variant(?:$s$variant)*";
302 $extensionList = "$extension(?:$s$extension)*";
303
304 $langtag = "(?:($language)"
305 . "(?:$s$script)?"
306 . "(?:$s$region)?"
307 . "(?:$s$variantList)?"
308 . "(?:$s$extensionList)?"
309 . "(?:$s$privateUse)?)";
310
311 # The final breakdown, with capturing groups for each of these components
312 # The variants, extensions, grandfathered, and private-use may have interior '-'
313
314 $root = "^(?:$langtag|$privateUse|$grandfathered)$";
315
316 return (bool)preg_match( "/$root/", strtolower( $code ) );
317 }
318
319 /**
320 * Returns true if a language code string is of a valid form, whether or
321 * not it exists. This includes codes which are used solely for
322 * customisation via the MediaWiki namespace.
323 *
324 * @param $code string
325 *
326 * @return bool
327 */
328 public static function isValidCode( $code ) {
329 static $cache = array();
330 if( isset( $cache[$code] ) ) {
331 return $cache[$code];
332 }
333 // People think language codes are html safe, so enforce it.
334 // Ideally we should only allow a-zA-Z0-9-
335 // but, .+ and other chars are often used for {{int:}} hacks
336 // see bugs 37564, 37587, 36938
337 $return =
338 strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
339 && !preg_match( Title::getTitleInvalidRegex(), $code );
340 $cache[ $code ] = $return;
341 return $return;
342 }
343
344 /**
345 * Returns true if a language code is of a valid form for the purposes of
346 * internal customisation of MediaWiki, via Messages*.php.
347 *
348 * @param $code string
349 *
350 * @throws MWException
351 * @since 1.18
352 * @return bool
353 */
354 public static function isValidBuiltInCode( $code ) {
355
356 if ( !is_string( $code ) ) {
357 if ( is_object( $code ) ) {
358 $addmsg = " of class " . get_class( $code );
359 } else {
360 $addmsg = '';
361 }
362 $type = gettype( $code );
363 throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
364 }
365
366 return (bool)preg_match( '/^[a-z0-9-]{2,}$/i', $code );
367 }
368
369 /**
370 * Returns true if a language code is an IETF tag known to MediaWiki.
371 *
372 * @param $code string
373 *
374 * @since 1.21
375 * @return bool
376 */
377 public static function isKnownLanguageTag( $tag ) {
378 static $coreLanguageNames;
379
380 if ( $coreLanguageNames === null ) {
381 include( MWInit::compiledPath( 'languages/Names.php' ) );
382 }
383
384 if ( isset( $coreLanguageNames[$tag] )
385 || self::fetchLanguageName( $tag, $tag ) !== ''
386 ) {
387 return true;
388 }
389
390 return false;
391 }
392
393 /**
394 * @param $code
395 * @return String Name of the language class
396 */
397 public static function classFromCode( $code ) {
398 if ( $code == 'en' ) {
399 return 'Language';
400 } else {
401 return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
402 }
403 }
404
405 /**
406 * Includes language class files
407 *
408 * @param $class string Name of the language class
409 */
410 public static function preloadLanguageClass( $class ) {
411 global $IP;
412
413 if ( $class === 'Language' ) {
414 return;
415 }
416
417 if ( !defined( 'MW_COMPILED' ) ) {
418 if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
419 include_once( "$IP/languages/classes/$class.php" );
420 }
421 }
422 }
423
424 /**
425 * Get the LocalisationCache instance
426 *
427 * @return LocalisationCache
428 */
429 public static function getLocalisationCache() {
430 if ( is_null( self::$dataCache ) ) {
431 global $wgLocalisationCacheConf;
432 $class = $wgLocalisationCacheConf['class'];
433 self::$dataCache = new $class( $wgLocalisationCacheConf );
434 }
435 return self::$dataCache;
436 }
437
438 function __construct() {
439 $this->mConverter = new FakeConverter( $this );
440 // Set the code to the name of the descendant
441 if ( get_class( $this ) == 'Language' ) {
442 $this->mCode = 'en';
443 } else {
444 $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
445 }
446 self::getLocalisationCache();
447 }
448
449 /**
450 * Reduce memory usage
451 */
452 function __destruct() {
453 foreach ( $this as $name => $value ) {
454 unset( $this->$name );
455 }
456 }
457
458 /**
459 * Hook which will be called if this is the content language.
460 * Descendants can use this to register hook functions or modify globals
461 */
462 function initContLang() { }
463
464 /**
465 * Same as getFallbacksFor for current language.
466 * @return array|bool
467 * @deprecated in 1.19
468 */
469 function getFallbackLanguageCode() {
470 wfDeprecated( __METHOD__, '1.19' );
471 return self::getFallbackFor( $this->mCode );
472 }
473
474 /**
475 * @return array
476 * @since 1.19
477 */
478 function getFallbackLanguages() {
479 return self::getFallbacksFor( $this->mCode );
480 }
481
482 /**
483 * Exports $wgBookstoreListEn
484 * @return array
485 */
486 function getBookstoreList() {
487 return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
488 }
489
490 /**
491 * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
492 * available in localised form, it will be included in English.
493 *
494 * @return array
495 */
496 public function getNamespaces() {
497 if ( is_null( $this->namespaceNames ) ) {
498 global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
499
500 $this->namespaceNames = self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
501 $validNamespaces = MWNamespace::getCanonicalNamespaces();
502
503 $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames + $validNamespaces;
504
505 $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
506 if ( $wgMetaNamespaceTalk ) {
507 $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
508 } else {
509 $talk = $this->namespaceNames[NS_PROJECT_TALK];
510 $this->namespaceNames[NS_PROJECT_TALK] =
511 $this->fixVariableInNamespace( $talk );
512 }
513
514 # Sometimes a language will be localised but not actually exist on this wiki.
515 foreach ( $this->namespaceNames as $key => $text ) {
516 if ( !isset( $validNamespaces[$key] ) ) {
517 unset( $this->namespaceNames[$key] );
518 }
519 }
520
521 # The above mixing may leave namespaces out of canonical order.
522 # Re-order by namespace ID number...
523 ksort( $this->namespaceNames );
524
525 wfRunHooks( 'LanguageGetNamespaces', array( &$this->namespaceNames ) );
526 }
527 return $this->namespaceNames;
528 }
529
530 /**
531 * Arbitrarily set all of the namespace names at once. Mainly used for testing
532 * @param $namespaces Array of namespaces (id => name)
533 */
534 public function setNamespaces( array $namespaces ) {
535 $this->namespaceNames = $namespaces;
536 $this->mNamespaceIds = null;
537 }
538
539 /**
540 * Resets all of the namespace caches. Mainly used for testing
541 */
542 public function resetNamespaces() {
543 $this->namespaceNames = null;
544 $this->mNamespaceIds = null;
545 $this->namespaceAliases = null;
546 }
547
548 /**
549 * A convenience function that returns the same thing as
550 * getNamespaces() except with the array values changed to ' '
551 * where it found '_', useful for producing output to be displayed
552 * e.g. in <select> forms.
553 *
554 * @return array
555 */
556 function getFormattedNamespaces() {
557 $ns = $this->getNamespaces();
558 foreach ( $ns as $k => $v ) {
559 $ns[$k] = strtr( $v, '_', ' ' );
560 }
561 return $ns;
562 }
563
564 /**
565 * Get a namespace value by key
566 * <code>
567 * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
568 * echo $mw_ns; // prints 'MediaWiki'
569 * </code>
570 *
571 * @param $index Int: the array key of the namespace to return
572 * @return mixed, string if the namespace value exists, otherwise false
573 */
574 function getNsText( $index ) {
575 $ns = $this->getNamespaces();
576 return isset( $ns[$index] ) ? $ns[$index] : false;
577 }
578
579 /**
580 * A convenience function that returns the same thing as
581 * getNsText() except with '_' changed to ' ', useful for
582 * producing output.
583 *
584 * <code>
585 * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
586 * echo $mw_ns; // prints 'MediaWiki talk'
587 * </code>
588 *
589 * @param int $index The array key of the namespace to return
590 * @return string Namespace name without underscores (empty string if namespace does not exist)
591 */
592 function getFormattedNsText( $index ) {
593 $ns = $this->getNsText( $index );
594 return strtr( $ns, '_', ' ' );
595 }
596
597 /**
598 * Returns gender-dependent namespace alias if available.
599 * @param $index Int: namespace index
600 * @param $gender String: gender key (male, female... )
601 * @return String
602 * @since 1.18
603 */
604 function getGenderNsText( $index, $gender ) {
605 global $wgExtraGenderNamespaces;
606
607 $ns = $wgExtraGenderNamespaces + self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
608 return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
609 }
610
611 /**
612 * Whether this language makes distinguishes genders for example in
613 * namespaces.
614 * @return bool
615 * @since 1.18
616 */
617 function needsGenderDistinction() {
618 global $wgExtraGenderNamespaces, $wgExtraNamespaces;
619 if ( count( $wgExtraGenderNamespaces ) > 0 ) {
620 // $wgExtraGenderNamespaces overrides everything
621 return true;
622 } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
623 /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
624 // $wgExtraNamespaces overrides any gender aliases specified in i18n files
625 return false;
626 } else {
627 // Check what is in i18n files
628 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
629 return count( $aliases ) > 0;
630 }
631 }
632
633 /**
634 * Get a namespace key by value, case insensitive.
635 * Only matches namespace names for the current language, not the
636 * canonical ones defined in Namespace.php.
637 *
638 * @param $text String
639 * @return mixed An integer if $text is a valid value otherwise false
640 */
641 function getLocalNsIndex( $text ) {
642 $lctext = $this->lc( $text );
643 $ids = $this->getNamespaceIds();
644 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
645 }
646
647 /**
648 * @return array
649 */
650 function getNamespaceAliases() {
651 if ( is_null( $this->namespaceAliases ) ) {
652 $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
653 if ( !$aliases ) {
654 $aliases = array();
655 } else {
656 foreach ( $aliases as $name => $index ) {
657 if ( $index === NS_PROJECT_TALK ) {
658 unset( $aliases[$name] );
659 $name = $this->fixVariableInNamespace( $name );
660 $aliases[$name] = $index;
661 }
662 }
663 }
664
665 global $wgExtraGenderNamespaces;
666 $genders = $wgExtraGenderNamespaces + (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
667 foreach ( $genders as $index => $forms ) {
668 foreach ( $forms as $alias ) {
669 $aliases[$alias] = $index;
670 }
671 }
672
673 $this->namespaceAliases = $aliases;
674 }
675 return $this->namespaceAliases;
676 }
677
678 /**
679 * @return array
680 */
681 function getNamespaceIds() {
682 if ( is_null( $this->mNamespaceIds ) ) {
683 global $wgNamespaceAliases;
684 # Put namespace names and aliases into a hashtable.
685 # If this is too slow, then we should arrange it so that it is done
686 # before caching. The catch is that at pre-cache time, the above
687 # class-specific fixup hasn't been done.
688 $this->mNamespaceIds = array();
689 foreach ( $this->getNamespaces() as $index => $name ) {
690 $this->mNamespaceIds[$this->lc( $name )] = $index;
691 }
692 foreach ( $this->getNamespaceAliases() as $name => $index ) {
693 $this->mNamespaceIds[$this->lc( $name )] = $index;
694 }
695 if ( $wgNamespaceAliases ) {
696 foreach ( $wgNamespaceAliases as $name => $index ) {
697 $this->mNamespaceIds[$this->lc( $name )] = $index;
698 }
699 }
700 }
701 return $this->mNamespaceIds;
702 }
703
704 /**
705 * Get a namespace key by value, case insensitive. Canonical namespace
706 * names override custom ones defined for the current language.
707 *
708 * @param $text String
709 * @return mixed An integer if $text is a valid value otherwise false
710 */
711 function getNsIndex( $text ) {
712 $lctext = $this->lc( $text );
713 $ns = MWNamespace::getCanonicalIndex( $lctext );
714 if ( $ns !== null ) {
715 return $ns;
716 }
717 $ids = $this->getNamespaceIds();
718 return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
719 }
720
721 /**
722 * short names for language variants used for language conversion links.
723 *
724 * @param $code String
725 * @param $usemsg bool Use the "variantname-xyz" message if it exists
726 * @return string
727 */
728 function getVariantname( $code, $usemsg = true ) {
729 $msg = "variantname-$code";
730 if ( $usemsg && wfMessage( $msg )->exists() ) {
731 return $this->getMessageFromDB( $msg );
732 }
733 $name = self::fetchLanguageName( $code );
734 if ( $name ) {
735 return $name; # if it's defined as a language name, show that
736 } else {
737 # otherwise, output the language code
738 return $code;
739 }
740 }
741
742 /**
743 * @param $name string
744 * @return string
745 */
746 function specialPage( $name ) {
747 $aliases = $this->getSpecialPageAliases();
748 if ( isset( $aliases[$name][0] ) ) {
749 $name = $aliases[$name][0];
750 }
751 return $this->getNsText( NS_SPECIAL ) . ':' . $name;
752 }
753
754 /**
755 * @return array
756 */
757 function getDatePreferences() {
758 return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
759 }
760
761 /**
762 * @return array
763 */
764 function getDateFormats() {
765 return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
766 }
767
768 /**
769 * @return array|string
770 */
771 function getDefaultDateFormat() {
772 $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
773 if ( $df === 'dmy or mdy' ) {
774 global $wgAmericanDates;
775 return $wgAmericanDates ? 'mdy' : 'dmy';
776 } else {
777 return $df;
778 }
779 }
780
781 /**
782 * @return array
783 */
784 function getDatePreferenceMigrationMap() {
785 return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
786 }
787
788 /**
789 * @param $image
790 * @return array|null
791 */
792 function getImageFile( $image ) {
793 return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
794 }
795
796 /**
797 * @return array
798 */
799 function getExtraUserToggles() {
800 return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
801 }
802
803 /**
804 * @param $tog
805 * @return string
806 */
807 function getUserToggle( $tog ) {
808 return $this->getMessageFromDB( "tog-$tog" );
809 }
810
811 /**
812 * Get native language names, indexed by code.
813 * Only those defined in MediaWiki, no other data like CLDR.
814 * If $customisedOnly is true, only returns codes with a messages file
815 *
816 * @param $customisedOnly bool
817 *
818 * @return array
819 * @deprecated in 1.20, use fetchLanguageNames()
820 */
821 public static function getLanguageNames( $customisedOnly = false ) {
822 return self::fetchLanguageNames( null, $customisedOnly ? 'mwfile' : 'mw' );
823 }
824
825 /**
826 * Get translated language names. This is done on best effort and
827 * by default this is exactly the same as Language::getLanguageNames.
828 * The CLDR extension provides translated names.
829 * @param $code String Language code.
830 * @return Array language code => language name
831 * @since 1.18.0
832 * @deprecated in 1.20, use fetchLanguageNames()
833 */
834 public static function getTranslatedLanguageNames( $code ) {
835 return self::fetchLanguageNames( $code, 'all' );
836 }
837
838 /**
839 * Get an array of language names, indexed by code.
840 * @param $inLanguage null|string: Code of language in which to return the names
841 * Use null for autonyms (native names)
842 * @param $include string:
843 * 'all' all available languages
844 * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
845 * 'mwfile' only if the language is in 'mw' *and* has a message file
846 * @return array: language code => language name
847 * @since 1.20
848 */
849 public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
850 global $wgExtraLanguageNames;
851 static $coreLanguageNames;
852
853 if ( $coreLanguageNames === null ) {
854 include( MWInit::compiledPath( 'languages/Names.php' ) );
855 }
856
857 $names = array();
858
859 if ( $inLanguage ) {
860 # TODO: also include when $inLanguage is null, when this code is more efficient
861 wfRunHooks( 'LanguageGetTranslatedLanguageNames', array( &$names, $inLanguage ) );
862 }
863
864 $mwNames = $wgExtraLanguageNames + $coreLanguageNames;
865 foreach ( $mwNames as $mwCode => $mwName ) {
866 # - Prefer own MediaWiki native name when not using the hook
867 # - For other names just add if not added through the hook
868 if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
869 $names[$mwCode] = $mwName;
870 }
871 }
872
873 if ( $include === 'all' ) {
874 return $names;
875 }
876
877 $returnMw = array();
878 $coreCodes = array_keys( $mwNames );
879 foreach ( $coreCodes as $coreCode ) {
880 $returnMw[$coreCode] = $names[$coreCode];
881 }
882
883 if ( $include === 'mwfile' ) {
884 $namesMwFile = array();
885 # We do this using a foreach over the codes instead of a directory
886 # loop so that messages files in extensions will work correctly.
887 foreach ( $returnMw as $code => $value ) {
888 if ( is_readable( self::getMessagesFileName( $code ) ) ) {
889 $namesMwFile[$code] = $names[$code];
890 }
891 }
892 return $namesMwFile;
893 }
894 # 'mw' option; default if it's not one of the other two options (all/mwfile)
895 return $returnMw;
896 }
897
898 /**
899 * @param $code string: The code of the language for which to get the name
900 * @param $inLanguage null|string: Code of language in which to return the name (null for autonyms)
901 * @param $include string: 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
902 * @return string: Language name or empty
903 * @since 1.20
904 */
905 public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
906 $array = self::fetchLanguageNames( $inLanguage, $include );
907 return !array_key_exists( $code, $array ) ? '' : $array[$code];
908 }
909
910 /**
911 * Get a message from the MediaWiki namespace.
912 *
913 * @param $msg String: message name
914 * @return string
915 */
916 function getMessageFromDB( $msg ) {
917 return wfMessage( $msg )->inLanguage( $this )->text();
918 }
919
920 /**
921 * Get the native language name of $code.
922 * Only if defined in MediaWiki, no other data like CLDR.
923 * @param $code string
924 * @return string
925 * @deprecated in 1.20, use fetchLanguageName()
926 */
927 function getLanguageName( $code ) {
928 return self::fetchLanguageName( $code );
929 }
930
931 /**
932 * @param $key string
933 * @return string
934 */
935 function getMonthName( $key ) {
936 return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
937 }
938
939 /**
940 * @return array
941 */
942 function getMonthNamesArray() {
943 $monthNames = array( '' );
944 for ( $i = 1; $i < 13; $i++ ) {
945 $monthNames[] = $this->getMonthName( $i );
946 }
947 return $monthNames;
948 }
949
950 /**
951 * @param $key string
952 * @return string
953 */
954 function getMonthNameGen( $key ) {
955 return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
956 }
957
958 /**
959 * @param $key string
960 * @return string
961 */
962 function getMonthAbbreviation( $key ) {
963 return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
964 }
965
966 /**
967 * @return array
968 */
969 function getMonthAbbreviationsArray() {
970 $monthNames = array( '' );
971 for ( $i = 1; $i < 13; $i++ ) {
972 $monthNames[] = $this->getMonthAbbreviation( $i );
973 }
974 return $monthNames;
975 }
976
977 /**
978 * @param $key string
979 * @return string
980 */
981 function getWeekdayName( $key ) {
982 return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
983 }
984
985 /**
986 * @param $key string
987 * @return string
988 */
989 function getWeekdayAbbreviation( $key ) {
990 return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
991 }
992
993 /**
994 * @param $key string
995 * @return string
996 */
997 function getIranianCalendarMonthName( $key ) {
998 return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
999 }
1000
1001 /**
1002 * @param $key string
1003 * @return string
1004 */
1005 function getHebrewCalendarMonthName( $key ) {
1006 return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
1007 }
1008
1009 /**
1010 * @param $key string
1011 * @return string
1012 */
1013 function getHebrewCalendarMonthNameGen( $key ) {
1014 return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
1015 }
1016
1017 /**
1018 * @param $key string
1019 * @return string
1020 */
1021 function getHijriCalendarMonthName( $key ) {
1022 return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
1023 }
1024
1025 /**
1026 * This is a workalike of PHP's date() function, but with better
1027 * internationalisation, a reduced set of format characters, and a better
1028 * escaping format.
1029 *
1030 * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
1031 * the PHP manual for definitions. There are a number of extensions, which
1032 * start with "x":
1033 *
1034 * xn Do not translate digits of the next numeric format character
1035 * xN Toggle raw digit (xn) flag, stays set until explicitly unset
1036 * xr Use roman numerals for the next numeric format character
1037 * xh Use hebrew numerals for the next numeric format character
1038 * xx Literal x
1039 * xg Genitive month name
1040 *
1041 * xij j (day number) in Iranian calendar
1042 * xiF F (month name) in Iranian calendar
1043 * xin n (month number) in Iranian calendar
1044 * xiy y (two digit year) in Iranian calendar
1045 * xiY Y (full year) in Iranian calendar
1046 *
1047 * xjj j (day number) in Hebrew calendar
1048 * xjF F (month name) in Hebrew calendar
1049 * xjt t (days in month) in Hebrew calendar
1050 * xjx xg (genitive month name) in Hebrew calendar
1051 * xjn n (month number) in Hebrew calendar
1052 * xjY Y (full year) in Hebrew calendar
1053 *
1054 * xmj j (day number) in Hijri calendar
1055 * xmF F (month name) in Hijri calendar
1056 * xmn n (month number) in Hijri calendar
1057 * xmY Y (full year) in Hijri calendar
1058 *
1059 * xkY Y (full year) in Thai solar calendar. Months and days are
1060 * identical to the Gregorian calendar
1061 * xoY Y (full year) in Minguo calendar or Juche year.
1062 * Months and days are identical to the
1063 * Gregorian calendar
1064 * xtY Y (full year) in Japanese nengo. Months and days are
1065 * identical to the Gregorian calendar
1066 *
1067 * Characters enclosed in double quotes will be considered literal (with
1068 * the quotes themselves removed). Unmatched quotes will be considered
1069 * literal quotes. Example:
1070 *
1071 * "The month is" F => The month is January
1072 * i's" => 20'11"
1073 *
1074 * Backslash escaping is also supported.
1075 *
1076 * Input timestamp is assumed to be pre-normalized to the desired local
1077 * time zone, if any. Note that the format characters crUeIOPTZ will assume
1078 * $ts is UTC if $zone is not given.
1079 *
1080 * @param $format String
1081 * @param $ts String: 14-character timestamp
1082 * YYYYMMDDHHMMSS
1083 * 01234567890123
1084 * @param $zone DateTimeZone: Timezone of $ts
1085 * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
1086 *
1087 * @throws MWException
1088 * @return string
1089 */
1090 function sprintfDate( $format, $ts, DateTimeZone $zone = null ) {
1091 $s = '';
1092 $raw = false;
1093 $roman = false;
1094 $hebrewNum = false;
1095 $dateTimeObj = false;
1096 $rawToggle = false;
1097 $iranian = false;
1098 $hebrew = false;
1099 $hijri = false;
1100 $thai = false;
1101 $minguo = false;
1102 $tenno = false;
1103
1104 if ( strlen( $ts ) !== 14 ) {
1105 throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
1106 }
1107
1108 if ( !ctype_digit( $ts ) ) {
1109 throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
1110 }
1111
1112 for ( $p = 0; $p < strlen( $format ); $p++ ) {
1113 $num = false;
1114 $code = $format[$p];
1115 if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
1116 $code .= $format[++$p];
1117 }
1118
1119 if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' || $code == 'xo' || $code == 'xt' ) && $p < strlen( $format ) - 1 ) {
1120 $code .= $format[++$p];
1121 }
1122
1123 switch ( $code ) {
1124 case 'xx':
1125 $s .= 'x';
1126 break;
1127 case 'xn':
1128 $raw = true;
1129 break;
1130 case 'xN':
1131 $rawToggle = !$rawToggle;
1132 break;
1133 case 'xr':
1134 $roman = true;
1135 break;
1136 case 'xh':
1137 $hebrewNum = true;
1138 break;
1139 case 'xg':
1140 $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
1141 break;
1142 case 'xjx':
1143 if ( !$hebrew ) {
1144 $hebrew = self::tsToHebrew( $ts );
1145 }
1146 $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
1147 break;
1148 case 'd':
1149 $num = substr( $ts, 6, 2 );
1150 break;
1151 case 'D':
1152 if ( !$dateTimeObj ) {
1153 $dateTimeObj = DateTime::createFromFormat(
1154 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1155 );
1156 }
1157 $s .= $this->getWeekdayAbbreviation( $dateTimeObj->format( 'w' ) + 1 );
1158 break;
1159 case 'j':
1160 $num = intval( substr( $ts, 6, 2 ) );
1161 break;
1162 case 'xij':
1163 if ( !$iranian ) {
1164 $iranian = self::tsToIranian( $ts );
1165 }
1166 $num = $iranian[2];
1167 break;
1168 case 'xmj':
1169 if ( !$hijri ) {
1170 $hijri = self::tsToHijri( $ts );
1171 }
1172 $num = $hijri[2];
1173 break;
1174 case 'xjj':
1175 if ( !$hebrew ) {
1176 $hebrew = self::tsToHebrew( $ts );
1177 }
1178 $num = $hebrew[2];
1179 break;
1180 case 'l':
1181 if ( !$dateTimeObj ) {
1182 $dateTimeObj = DateTime::createFromFormat(
1183 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1184 );
1185 }
1186 $s .= $this->getWeekdayName( $dateTimeObj->format( 'w' ) + 1 );
1187 break;
1188 case 'F':
1189 $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
1190 break;
1191 case 'xiF':
1192 if ( !$iranian ) {
1193 $iranian = self::tsToIranian( $ts );
1194 }
1195 $s .= $this->getIranianCalendarMonthName( $iranian[1] );
1196 break;
1197 case 'xmF':
1198 if ( !$hijri ) {
1199 $hijri = self::tsToHijri( $ts );
1200 }
1201 $s .= $this->getHijriCalendarMonthName( $hijri[1] );
1202 break;
1203 case 'xjF':
1204 if ( !$hebrew ) {
1205 $hebrew = self::tsToHebrew( $ts );
1206 }
1207 $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
1208 break;
1209 case 'm':
1210 $num = substr( $ts, 4, 2 );
1211 break;
1212 case 'M':
1213 $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
1214 break;
1215 case 'n':
1216 $num = intval( substr( $ts, 4, 2 ) );
1217 break;
1218 case 'xin':
1219 if ( !$iranian ) {
1220 $iranian = self::tsToIranian( $ts );
1221 }
1222 $num = $iranian[1];
1223 break;
1224 case 'xmn':
1225 if ( !$hijri ) {
1226 $hijri = self::tsToHijri ( $ts );
1227 }
1228 $num = $hijri[1];
1229 break;
1230 case 'xjn':
1231 if ( !$hebrew ) {
1232 $hebrew = self::tsToHebrew( $ts );
1233 }
1234 $num = $hebrew[1];
1235 break;
1236 case 'xjt':
1237 if ( !$hebrew ) {
1238 $hebrew = self::tsToHebrew( $ts );
1239 }
1240 $num = $hebrew[3];
1241 break;
1242 case 'Y':
1243 $num = substr( $ts, 0, 4 );
1244 break;
1245 case 'xiY':
1246 if ( !$iranian ) {
1247 $iranian = self::tsToIranian( $ts );
1248 }
1249 $num = $iranian[0];
1250 break;
1251 case 'xmY':
1252 if ( !$hijri ) {
1253 $hijri = self::tsToHijri( $ts );
1254 }
1255 $num = $hijri[0];
1256 break;
1257 case 'xjY':
1258 if ( !$hebrew ) {
1259 $hebrew = self::tsToHebrew( $ts );
1260 }
1261 $num = $hebrew[0];
1262 break;
1263 case 'xkY':
1264 if ( !$thai ) {
1265 $thai = self::tsToYear( $ts, 'thai' );
1266 }
1267 $num = $thai[0];
1268 break;
1269 case 'xoY':
1270 if ( !$minguo ) {
1271 $minguo = self::tsToYear( $ts, 'minguo' );
1272 }
1273 $num = $minguo[0];
1274 break;
1275 case 'xtY':
1276 if ( !$tenno ) {
1277 $tenno = self::tsToYear( $ts, 'tenno' );
1278 }
1279 $num = $tenno[0];
1280 break;
1281 case 'y':
1282 $num = substr( $ts, 2, 2 );
1283 break;
1284 case 'xiy':
1285 if ( !$iranian ) {
1286 $iranian = self::tsToIranian( $ts );
1287 }
1288 $num = substr( $iranian[0], -2 );
1289 break;
1290 case 'a':
1291 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
1292 break;
1293 case 'A':
1294 $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
1295 break;
1296 case 'g':
1297 $h = substr( $ts, 8, 2 );
1298 $num = $h % 12 ? $h % 12 : 12;
1299 break;
1300 case 'G':
1301 $num = intval( substr( $ts, 8, 2 ) );
1302 break;
1303 case 'h':
1304 $h = substr( $ts, 8, 2 );
1305 $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
1306 break;
1307 case 'H':
1308 $num = substr( $ts, 8, 2 );
1309 break;
1310 case 'i':
1311 $num = substr( $ts, 10, 2 );
1312 break;
1313 case 's':
1314 $num = substr( $ts, 12, 2 );
1315 break;
1316 case 'c':
1317 case 'r':
1318 case 'e':
1319 case 'O':
1320 case 'P':
1321 case 'T':
1322 // Pass through string from $dateTimeObj->format()
1323 if ( !$dateTimeObj ) {
1324 $dateTimeObj = DateTime::createFromFormat(
1325 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1326 );
1327 }
1328 $s .= $dateTimeObj->format( $code );
1329 break;
1330 case 'w':
1331 case 'N':
1332 case 'z':
1333 case 'W':
1334 case 't':
1335 case 'L':
1336 case 'o':
1337 case 'U':
1338 case 'I':
1339 case 'Z':
1340 // Pass through number from $dateTimeObj->format()
1341 if ( !$dateTimeObj ) {
1342 $dateTimeObj = DateTime::createFromFormat(
1343 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
1344 );
1345 }
1346 $num = $dateTimeObj->format( $code );
1347 break;
1348 case '\\':
1349 # Backslash escaping
1350 if ( $p < strlen( $format ) - 1 ) {
1351 $s .= $format[++$p];
1352 } else {
1353 $s .= '\\';
1354 }
1355 break;
1356 case '"':
1357 # Quoted literal
1358 if ( $p < strlen( $format ) - 1 ) {
1359 $endQuote = strpos( $format, '"', $p + 1 );
1360 if ( $endQuote === false ) {
1361 # No terminating quote, assume literal "
1362 $s .= '"';
1363 } else {
1364 $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
1365 $p = $endQuote;
1366 }
1367 } else {
1368 # Quote at end of string, assume literal "
1369 $s .= '"';
1370 }
1371 break;
1372 default:
1373 $s .= $format[$p];
1374 }
1375 if ( $num !== false ) {
1376 if ( $rawToggle || $raw ) {
1377 $s .= $num;
1378 $raw = false;
1379 } elseif ( $roman ) {
1380 $s .= Language::romanNumeral( $num );
1381 $roman = false;
1382 } elseif ( $hebrewNum ) {
1383 $s .= self::hebrewNumeral( $num );
1384 $hebrewNum = false;
1385 } else {
1386 $s .= $this->formatNum( $num, true );
1387 }
1388 }
1389 }
1390 return $s;
1391 }
1392
1393 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
1394 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
1395
1396 /**
1397 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
1398 * Gregorian dates to Iranian dates. Originally written in C, it
1399 * is released under the terms of GNU Lesser General Public
1400 * License. Conversion to PHP was performed by Niklas Laxström.
1401 *
1402 * Link: http://www.farsiweb.info/jalali/jalali.c
1403 *
1404 * @param $ts string
1405 *
1406 * @return string
1407 */
1408 private static function tsToIranian( $ts ) {
1409 $gy = substr( $ts, 0, 4 ) -1600;
1410 $gm = substr( $ts, 4, 2 ) -1;
1411 $gd = substr( $ts, 6, 2 ) -1;
1412
1413 # Days passed from the beginning (including leap years)
1414 $gDayNo = 365 * $gy
1415 + floor( ( $gy + 3 ) / 4 )
1416 - floor( ( $gy + 99 ) / 100 )
1417 + floor( ( $gy + 399 ) / 400 );
1418
1419 // Add days of the past months of this year
1420 for ( $i = 0; $i < $gm; $i++ ) {
1421 $gDayNo += self::$GREG_DAYS[$i];
1422 }
1423
1424 // Leap years
1425 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1426 $gDayNo++;
1427 }
1428
1429 // Days passed in current month
1430 $gDayNo += (int)$gd;
1431
1432 $jDayNo = $gDayNo - 79;
1433
1434 $jNp = floor( $jDayNo / 12053 );
1435 $jDayNo %= 12053;
1436
1437 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1438 $jDayNo %= 1461;
1439
1440 if ( $jDayNo >= 366 ) {
1441 $jy += floor( ( $jDayNo - 1 ) / 365 );
1442 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1443 }
1444
1445 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1446 $jDayNo -= self::$IRANIAN_DAYS[$i];
1447 }
1448
1449 $jm = $i + 1;
1450 $jd = $jDayNo + 1;
1451
1452 return array( $jy, $jm, $jd );
1453 }
1454
1455 /**
1456 * Converting Gregorian dates to Hijri dates.
1457 *
1458 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1459 *
1460 * @see http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1461 *
1462 * @param $ts string
1463 *
1464 * @return string
1465 */
1466 private static function tsToHijri( $ts ) {
1467 $year = substr( $ts, 0, 4 );
1468 $month = substr( $ts, 4, 2 );
1469 $day = substr( $ts, 6, 2 );
1470
1471 $zyr = $year;
1472 $zd = $day;
1473 $zm = $month;
1474 $zy = $zyr;
1475
1476 if (
1477 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1478 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1479 )
1480 {
1481 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1482 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1483 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1484 $zd - 32075;
1485 } else {
1486 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1487 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1488 }
1489
1490 $zl = $zjd -1948440 + 10632;
1491 $zn = (int)( ( $zl - 1 ) / 10631 );
1492 $zl = $zl - 10631 * $zn + 354;
1493 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1494 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1495 $zm = (int)( ( 24 * $zl ) / 709 );
1496 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1497 $zy = 30 * $zn + $zj - 30;
1498
1499 return array( $zy, $zm, $zd );
1500 }
1501
1502 /**
1503 * Converting Gregorian dates to Hebrew dates.
1504 *
1505 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1506 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1507 * to translate the relevant functions into PHP and release them under
1508 * GNU GPL.
1509 *
1510 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1511 * and Adar II is 14. In a non-leap year, Adar is 6.
1512 *
1513 * @param $ts string
1514 *
1515 * @return string
1516 */
1517 private static function tsToHebrew( $ts ) {
1518 # Parse date
1519 $year = substr( $ts, 0, 4 );
1520 $month = substr( $ts, 4, 2 );
1521 $day = substr( $ts, 6, 2 );
1522
1523 # Calculate Hebrew year
1524 $hebrewYear = $year + 3760;
1525
1526 # Month number when September = 1, August = 12
1527 $month += 4;
1528 if ( $month > 12 ) {
1529 # Next year
1530 $month -= 12;
1531 $year++;
1532 $hebrewYear++;
1533 }
1534
1535 # Calculate day of year from 1 September
1536 $dayOfYear = $day;
1537 for ( $i = 1; $i < $month; $i++ ) {
1538 if ( $i == 6 ) {
1539 # February
1540 $dayOfYear += 28;
1541 # Check if the year is leap
1542 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1543 $dayOfYear++;
1544 }
1545 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1546 $dayOfYear += 30;
1547 } else {
1548 $dayOfYear += 31;
1549 }
1550 }
1551
1552 # Calculate the start of the Hebrew year
1553 $start = self::hebrewYearStart( $hebrewYear );
1554
1555 # Calculate next year's start
1556 if ( $dayOfYear <= $start ) {
1557 # Day is before the start of the year - it is the previous year
1558 # Next year's start
1559 $nextStart = $start;
1560 # Previous year
1561 $year--;
1562 $hebrewYear--;
1563 # Add days since previous year's 1 September
1564 $dayOfYear += 365;
1565 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1566 # Leap year
1567 $dayOfYear++;
1568 }
1569 # Start of the new (previous) year
1570 $start = self::hebrewYearStart( $hebrewYear );
1571 } else {
1572 # Next year's start
1573 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1574 }
1575
1576 # Calculate Hebrew day of year
1577 $hebrewDayOfYear = $dayOfYear - $start;
1578
1579 # Difference between year's days
1580 $diff = $nextStart - $start;
1581 # Add 12 (or 13 for leap years) days to ignore the difference between
1582 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1583 # difference is only about the year type
1584 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1585 $diff += 13;
1586 } else {
1587 $diff += 12;
1588 }
1589
1590 # Check the year pattern, and is leap year
1591 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1592 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1593 # and non-leap years
1594 $yearPattern = $diff % 30;
1595 # Check if leap year
1596 $isLeap = $diff >= 30;
1597
1598 # Calculate day in the month from number of day in the Hebrew year
1599 # Don't check Adar - if the day is not in Adar, we will stop before;
1600 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1601 $hebrewDay = $hebrewDayOfYear;
1602 $hebrewMonth = 1;
1603 $days = 0;
1604 while ( $hebrewMonth <= 12 ) {
1605 # Calculate days in this month
1606 if ( $isLeap && $hebrewMonth == 6 ) {
1607 # Adar in a leap year
1608 if ( $isLeap ) {
1609 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1610 $days = 30;
1611 if ( $hebrewDay <= $days ) {
1612 # Day in Adar I
1613 $hebrewMonth = 13;
1614 } else {
1615 # Subtract the days of Adar I
1616 $hebrewDay -= $days;
1617 # Try Adar II
1618 $days = 29;
1619 if ( $hebrewDay <= $days ) {
1620 # Day in Adar II
1621 $hebrewMonth = 14;
1622 }
1623 }
1624 }
1625 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1626 # Cheshvan in a complete year (otherwise as the rule below)
1627 $days = 30;
1628 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1629 # Kislev in an incomplete year (otherwise as the rule below)
1630 $days = 29;
1631 } else {
1632 # Odd months have 30 days, even have 29
1633 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1634 }
1635 if ( $hebrewDay <= $days ) {
1636 # In the current month
1637 break;
1638 } else {
1639 # Subtract the days of the current month
1640 $hebrewDay -= $days;
1641 # Try in the next month
1642 $hebrewMonth++;
1643 }
1644 }
1645
1646 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1647 }
1648
1649 /**
1650 * This calculates the Hebrew year start, as days since 1 September.
1651 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1652 * Used for Hebrew date.
1653 *
1654 * @param $year int
1655 *
1656 * @return string
1657 */
1658 private static function hebrewYearStart( $year ) {
1659 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1660 $b = intval( ( $year - 1 ) % 4 );
1661 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1662 if ( $m < 0 ) {
1663 $m--;
1664 }
1665 $Mar = intval( $m );
1666 if ( $m < 0 ) {
1667 $m++;
1668 }
1669 $m -= $Mar;
1670
1671 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1672 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1673 $Mar++;
1674 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1675 $Mar += 2;
1676 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1677 $Mar++;
1678 }
1679
1680 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1681 return $Mar;
1682 }
1683
1684 /**
1685 * Algorithm to convert Gregorian dates to Thai solar dates,
1686 * Minguo dates or Minguo dates.
1687 *
1688 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1689 * http://en.wikipedia.org/wiki/Minguo_calendar
1690 * http://en.wikipedia.org/wiki/Japanese_era_name
1691 *
1692 * @param $ts String: 14-character timestamp
1693 * @param $cName String: calender name
1694 * @return Array: converted year, month, day
1695 */
1696 private static function tsToYear( $ts, $cName ) {
1697 $gy = substr( $ts, 0, 4 );
1698 $gm = substr( $ts, 4, 2 );
1699 $gd = substr( $ts, 6, 2 );
1700
1701 if ( !strcmp( $cName, 'thai' ) ) {
1702 # Thai solar dates
1703 # Add 543 years to the Gregorian calendar
1704 # Months and days are identical
1705 $gy_offset = $gy + 543;
1706 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1707 # Minguo dates
1708 # Deduct 1911 years from the Gregorian calendar
1709 # Months and days are identical
1710 $gy_offset = $gy - 1911;
1711 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1712 # Nengō dates up to Meiji period
1713 # Deduct years from the Gregorian calendar
1714 # depending on the nengo periods
1715 # Months and days are identical
1716 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1717 # Meiji period
1718 $gy_gannen = $gy - 1868 + 1;
1719 $gy_offset = $gy_gannen;
1720 if ( $gy_gannen == 1 ) {
1721 $gy_offset = '元';
1722 }
1723 $gy_offset = '明治' . $gy_offset;
1724 } elseif (
1725 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1726 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1727 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1728 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1729 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1730 )
1731 {
1732 # Taishō period
1733 $gy_gannen = $gy - 1912 + 1;
1734 $gy_offset = $gy_gannen;
1735 if ( $gy_gannen == 1 ) {
1736 $gy_offset = '元';
1737 }
1738 $gy_offset = '大正' . $gy_offset;
1739 } elseif (
1740 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1741 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1742 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1743 )
1744 {
1745 # Shōwa period
1746 $gy_gannen = $gy - 1926 + 1;
1747 $gy_offset = $gy_gannen;
1748 if ( $gy_gannen == 1 ) {
1749 $gy_offset = '元';
1750 }
1751 $gy_offset = '昭和' . $gy_offset;
1752 } else {
1753 # Heisei period
1754 $gy_gannen = $gy - 1989 + 1;
1755 $gy_offset = $gy_gannen;
1756 if ( $gy_gannen == 1 ) {
1757 $gy_offset = '元';
1758 }
1759 $gy_offset = '平成' . $gy_offset;
1760 }
1761 } else {
1762 $gy_offset = $gy;
1763 }
1764
1765 return array( $gy_offset, $gm, $gd );
1766 }
1767
1768 /**
1769 * Roman number formatting up to 10000
1770 *
1771 * @param $num int
1772 *
1773 * @return string
1774 */
1775 static function romanNumeral( $num ) {
1776 static $table = array(
1777 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1778 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1779 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1780 array( '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' )
1781 );
1782
1783 $num = intval( $num );
1784 if ( $num > 10000 || $num <= 0 ) {
1785 return $num;
1786 }
1787
1788 $s = '';
1789 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1790 if ( $num >= $pow10 ) {
1791 $s .= $table[$i][(int)floor( $num / $pow10 )];
1792 }
1793 $num = $num % $pow10;
1794 }
1795 return $s;
1796 }
1797
1798 /**
1799 * Hebrew Gematria number formatting up to 9999
1800 *
1801 * @param $num int
1802 *
1803 * @return string
1804 */
1805 static function hebrewNumeral( $num ) {
1806 static $table = array(
1807 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1808 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1809 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1810 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1811 );
1812
1813 $num = intval( $num );
1814 if ( $num > 9999 || $num <= 0 ) {
1815 return $num;
1816 }
1817
1818 $s = '';
1819 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1820 if ( $num >= $pow10 ) {
1821 if ( $num == 15 || $num == 16 ) {
1822 $s .= $table[0][9] . $table[0][$num - 9];
1823 $num = 0;
1824 } else {
1825 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1826 if ( $pow10 == 1000 ) {
1827 $s .= "'";
1828 }
1829 }
1830 }
1831 $num = $num % $pow10;
1832 }
1833 if ( strlen( $s ) == 2 ) {
1834 $str = $s . "'";
1835 } else {
1836 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1837 $str .= substr( $s, strlen( $s ) - 2, 2 );
1838 }
1839 $start = substr( $str, 0, strlen( $str ) - 2 );
1840 $end = substr( $str, strlen( $str ) - 2 );
1841 switch ( $end ) {
1842 case 'כ':
1843 $str = $start . 'ך';
1844 break;
1845 case 'מ':
1846 $str = $start . 'ם';
1847 break;
1848 case 'נ':
1849 $str = $start . 'ן';
1850 break;
1851 case 'פ':
1852 $str = $start . 'ף';
1853 break;
1854 case 'צ':
1855 $str = $start . 'ץ';
1856 break;
1857 }
1858 return $str;
1859 }
1860
1861 /**
1862 * Used by date() and time() to adjust the time output.
1863 *
1864 * @param $ts Int the time in date('YmdHis') format
1865 * @param $tz Mixed: adjust the time by this amount (default false, mean we
1866 * get user timecorrection setting)
1867 * @return int
1868 */
1869 function userAdjust( $ts, $tz = false ) {
1870 global $wgUser, $wgLocalTZoffset;
1871
1872 if ( $tz === false ) {
1873 $tz = $wgUser->getOption( 'timecorrection' );
1874 }
1875
1876 $data = explode( '|', $tz, 3 );
1877
1878 if ( $data[0] == 'ZoneInfo' ) {
1879 wfSuppressWarnings();
1880 $userTZ = timezone_open( $data[2] );
1881 wfRestoreWarnings();
1882 if ( $userTZ !== false ) {
1883 $date = date_create( $ts, timezone_open( 'UTC' ) );
1884 date_timezone_set( $date, $userTZ );
1885 $date = date_format( $date, 'YmdHis' );
1886 return $date;
1887 }
1888 # Unrecognized timezone, default to 'Offset' with the stored offset.
1889 $data[0] = 'Offset';
1890 }
1891
1892 $minDiff = 0;
1893 if ( $data[0] == 'System' || $tz == '' ) {
1894 #  Global offset in minutes.
1895 if ( isset( $wgLocalTZoffset ) ) {
1896 $minDiff = $wgLocalTZoffset;
1897 }
1898 } elseif ( $data[0] == 'Offset' ) {
1899 $minDiff = intval( $data[1] );
1900 } else {
1901 $data = explode( ':', $tz );
1902 if ( count( $data ) == 2 ) {
1903 $data[0] = intval( $data[0] );
1904 $data[1] = intval( $data[1] );
1905 $minDiff = abs( $data[0] ) * 60 + $data[1];
1906 if ( $data[0] < 0 ) {
1907 $minDiff = -$minDiff;
1908 }
1909 } else {
1910 $minDiff = intval( $data[0] ) * 60;
1911 }
1912 }
1913
1914 # No difference ? Return time unchanged
1915 if ( 0 == $minDiff ) {
1916 return $ts;
1917 }
1918
1919 wfSuppressWarnings(); // E_STRICT system time bitching
1920 # Generate an adjusted date; take advantage of the fact that mktime
1921 # will normalize out-of-range values so we don't have to split $minDiff
1922 # into hours and minutes.
1923 $t = mktime( (
1924 (int)substr( $ts, 8, 2 ) ), # Hours
1925 (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
1926 (int)substr( $ts, 12, 2 ), # Seconds
1927 (int)substr( $ts, 4, 2 ), # Month
1928 (int)substr( $ts, 6, 2 ), # Day
1929 (int)substr( $ts, 0, 4 ) ); # Year
1930
1931 $date = date( 'YmdHis', $t );
1932 wfRestoreWarnings();
1933
1934 return $date;
1935 }
1936
1937 /**
1938 * This is meant to be used by time(), date(), and timeanddate() to get
1939 * the date preference they're supposed to use, it should be used in
1940 * all children.
1941 *
1942 *<code>
1943 * function timeanddate([...], $format = true) {
1944 * $datePreference = $this->dateFormat($format);
1945 * [...]
1946 * }
1947 *</code>
1948 *
1949 * @param $usePrefs Mixed: if true, the user's preference is used
1950 * if false, the site/language default is used
1951 * if int/string, assumed to be a format.
1952 * @return string
1953 */
1954 function dateFormat( $usePrefs = true ) {
1955 global $wgUser;
1956
1957 if ( is_bool( $usePrefs ) ) {
1958 if ( $usePrefs ) {
1959 $datePreference = $wgUser->getDatePreference();
1960 } else {
1961 $datePreference = (string)User::getDefaultOption( 'date' );
1962 }
1963 } else {
1964 $datePreference = (string)$usePrefs;
1965 }
1966
1967 // return int
1968 if ( $datePreference == '' ) {
1969 return 'default';
1970 }
1971
1972 return $datePreference;
1973 }
1974
1975 /**
1976 * Get a format string for a given type and preference
1977 * @param $type string May be date, time or both
1978 * @param $pref string The format name as it appears in Messages*.php
1979 *
1980 * @since 1.22 New type 'pretty' that provides a more readable timestamp format
1981 *
1982 * @return string
1983 */
1984 function getDateFormatString( $type, $pref ) {
1985 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1986 if ( $pref == 'default' ) {
1987 $pref = $this->getDefaultDateFormat();
1988 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1989 } else {
1990 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1991
1992 if ( $type === 'pretty' && $df === null ) {
1993 $df = $this->getDateFormatString( 'date', $pref );
1994 }
1995
1996 if ( $df === null ) {
1997 $pref = $this->getDefaultDateFormat();
1998 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1999 }
2000 }
2001 $this->dateFormatStrings[$type][$pref] = $df;
2002 }
2003 return $this->dateFormatStrings[$type][$pref];
2004 }
2005
2006 /**
2007 * @param $ts Mixed: the time format which needs to be turned into a
2008 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2009 * @param $adj Bool: whether to adjust the time output according to the
2010 * user configured offset ($timecorrection)
2011 * @param $format Mixed: true to use user's date format preference
2012 * @param $timecorrection String|bool the time offset as returned by
2013 * validateTimeZone() in Special:Preferences
2014 * @return string
2015 */
2016 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
2017 $ts = wfTimestamp( TS_MW, $ts );
2018 if ( $adj ) {
2019 $ts = $this->userAdjust( $ts, $timecorrection );
2020 }
2021 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
2022 return $this->sprintfDate( $df, $ts );
2023 }
2024
2025 /**
2026 * @param $ts Mixed: the time format which needs to be turned into a
2027 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2028 * @param $adj Bool: whether to adjust the time output according to the
2029 * user configured offset ($timecorrection)
2030 * @param $format Mixed: true to use user's date format preference
2031 * @param $timecorrection String|bool the time offset as returned by
2032 * validateTimeZone() in Special:Preferences
2033 * @return string
2034 */
2035 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
2036 $ts = wfTimestamp( TS_MW, $ts );
2037 if ( $adj ) {
2038 $ts = $this->userAdjust( $ts, $timecorrection );
2039 }
2040 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
2041 return $this->sprintfDate( $df, $ts );
2042 }
2043
2044 /**
2045 * @param $ts Mixed: the time format which needs to be turned into a
2046 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2047 * @param $adj Bool: whether to adjust the time output according to the
2048 * user configured offset ($timecorrection)
2049 * @param $format Mixed: what format to return, if it's false output the
2050 * default one (default true)
2051 * @param $timecorrection String|bool the time offset as returned by
2052 * validateTimeZone() in Special:Preferences
2053 * @return string
2054 */
2055 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
2056 $ts = wfTimestamp( TS_MW, $ts );
2057 if ( $adj ) {
2058 $ts = $this->userAdjust( $ts, $timecorrection );
2059 }
2060 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
2061 return $this->sprintfDate( $df, $ts );
2062 }
2063
2064 /**
2065 * Takes a number of seconds and turns it into a text using values such as hours and minutes.
2066 *
2067 * @since 1.20
2068 *
2069 * @param integer $seconds The amount of seconds.
2070 * @param array $chosenIntervals The intervals to enable.
2071 *
2072 * @return string
2073 */
2074 public function formatDuration( $seconds, array $chosenIntervals = array() ) {
2075 $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
2076
2077 $segments = array();
2078
2079 foreach ( $intervals as $intervalName => $intervalValue ) {
2080 $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
2081 $segments[] = $message->inLanguage( $this )->escaped();
2082 }
2083
2084 return $this->listToText( $segments );
2085 }
2086
2087 /**
2088 * Takes a number of seconds and returns an array with a set of corresponding intervals.
2089 * For example 65 will be turned into array( minutes => 1, seconds => 5 ).
2090 *
2091 * @since 1.20
2092 *
2093 * @param integer $seconds The amount of seconds.
2094 * @param array $chosenIntervals The intervals to enable.
2095 *
2096 * @return array
2097 */
2098 public function getDurationIntervals( $seconds, array $chosenIntervals = array() ) {
2099 if ( empty( $chosenIntervals ) ) {
2100 $chosenIntervals = array( 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', 'seconds' );
2101 }
2102
2103 $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
2104 $sortedNames = array_keys( $intervals );
2105 $smallestInterval = array_pop( $sortedNames );
2106
2107 $segments = array();
2108
2109 foreach ( $intervals as $name => $length ) {
2110 $value = floor( $seconds / $length );
2111
2112 if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
2113 $seconds -= $value * $length;
2114 $segments[$name] = $value;
2115 }
2116 }
2117
2118 return $segments;
2119 }
2120
2121 /**
2122 * Internal helper function for userDate(), userTime() and userTimeAndDate()
2123 *
2124 * @param $type String: can be 'date', 'time' or 'both'
2125 * @param $ts Mixed: the time format which needs to be turned into a
2126 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2127 * @param $user User object used to get preferences for timezone and format
2128 * @param $options Array, can contain the following keys:
2129 * - 'timecorrection': time correction, can have the following values:
2130 * - true: use user's preference
2131 * - false: don't use time correction
2132 * - integer: value of time correction in minutes
2133 * - 'format': format to use, can have the following values:
2134 * - true: use user's preference
2135 * - false: use default preference
2136 * - string: format to use
2137 * @since 1.19
2138 * @return String
2139 */
2140 private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
2141 $ts = wfTimestamp( TS_MW, $ts );
2142 $options += array( 'timecorrection' => true, 'format' => true );
2143 if ( $options['timecorrection'] !== false ) {
2144 if ( $options['timecorrection'] === true ) {
2145 $offset = $user->getOption( 'timecorrection' );
2146 } else {
2147 $offset = $options['timecorrection'];
2148 }
2149 $ts = $this->userAdjust( $ts, $offset );
2150 }
2151 if ( $options['format'] === true ) {
2152 $format = $user->getDatePreference();
2153 } else {
2154 $format = $options['format'];
2155 }
2156 $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
2157 return $this->sprintfDate( $df, $ts );
2158 }
2159
2160 /**
2161 * Get the formatted date for the given timestamp and formatted for
2162 * the given user.
2163 *
2164 * @param $ts Mixed: the time format which needs to be turned into a
2165 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2166 * @param $user User object used to get preferences for timezone and format
2167 * @param $options Array, can contain the following keys:
2168 * - 'timecorrection': time correction, can have the following values:
2169 * - true: use user's preference
2170 * - false: don't use time correction
2171 * - integer: value of time correction in minutes
2172 * - 'format': format to use, can have the following values:
2173 * - true: use user's preference
2174 * - false: use default preference
2175 * - string: format to use
2176 * @since 1.19
2177 * @return String
2178 */
2179 public function userDate( $ts, User $user, array $options = array() ) {
2180 return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
2181 }
2182
2183 /**
2184 * Get the formatted time for the given timestamp and formatted for
2185 * the given user.
2186 *
2187 * @param $ts Mixed: the time format which needs to be turned into a
2188 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2189 * @param $user User object used to get preferences for timezone and format
2190 * @param $options Array, can contain the following keys:
2191 * - 'timecorrection': time correction, can have the following values:
2192 * - true: use user's preference
2193 * - false: don't use time correction
2194 * - integer: value of time correction in minutes
2195 * - 'format': format to use, can have the following values:
2196 * - true: use user's preference
2197 * - false: use default preference
2198 * - string: format to use
2199 * @since 1.19
2200 * @return String
2201 */
2202 public function userTime( $ts, User $user, array $options = array() ) {
2203 return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
2204 }
2205
2206 /**
2207 * Get the formatted date and time for the given timestamp and formatted for
2208 * the given user.
2209 *
2210 * @param $ts Mixed: the time format which needs to be turned into a
2211 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
2212 * @param $user User object used to get preferences for timezone and format
2213 * @param $options Array, can contain the following keys:
2214 * - 'timecorrection': time correction, can have the following values:
2215 * - true: use user's preference
2216 * - false: don't use time correction
2217 * - integer: value of time correction in minutes
2218 * - 'format': format to use, can have the following values:
2219 * - true: use user's preference
2220 * - false: use default preference
2221 * - string: format to use
2222 * @since 1.19
2223 * @return String
2224 */
2225 public function userTimeAndDate( $ts, User $user, array $options = array() ) {
2226 return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
2227 }
2228
2229 /**
2230 * Convert an MWTimestamp into a pretty human-readable timestamp using
2231 * the given user preferences and relative base time.
2232 *
2233 * DO NOT USE THIS FUNCTION DIRECTLY. Instead, call MWTimestamp::getHumanTimestamp
2234 * on your timestamp object, which will then call this function. Calling
2235 * this function directly will cause hooks to be skipped over.
2236 *
2237 * @see MWTimestamp::getHumanTimestamp
2238 * @param MWTimestamp $ts Timestamp to prettify
2239 * @param MWTimestamp $relativeTo Base timestamp
2240 * @param User $user User preferences to use
2241 * @return string Human timestamp
2242 * @since 1.21
2243 */
2244 public function getHumanTimestamp( MWTimestamp $ts, MWTimestamp $relativeTo, User $user ) {
2245 $diff = $ts->diff( $relativeTo );
2246 $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) - (int)$relativeTo->timestamp->format( 'w' ) );
2247 $days = $diff->days ?: (int)$diffDay;
2248 if ( $diff->invert || $days > 5 && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' ) ) {
2249 // Timestamps are in different years: use full timestamp
2250 // Also do full timestamp for future dates
2251 /**
2252 * @FIXME Add better handling of future timestamps.
2253 */
2254 $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
2255 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2256 } elseif ( $days > 5 ) {
2257 // Timestamps are in same year, but more than 5 days ago: show day and month only.
2258 $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
2259 $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
2260 } elseif ( $days > 1 ) {
2261 // Timestamp within the past week: show the day of the week and time
2262 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2263 $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
2264 $ts = wfMessage( "$weekday-at" )
2265 ->inLanguage( $this )
2266 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2267 ->text();
2268 } elseif ( $days == 1 ) {
2269 // Timestamp was yesterday: say 'yesterday' and the time.
2270 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2271 $ts = wfMessage( 'yesterday-at' )
2272 ->inLanguage( $this )
2273 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2274 ->text();
2275 } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
2276 // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
2277 $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
2278 $ts = wfMessage( 'today-at' )
2279 ->inLanguage( $this )
2280 ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
2281 ->text();
2282
2283 // From here on in, the timestamp was soon enough ago so that we can simply say
2284 // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
2285 } elseif ( $diff->h == 1 ) {
2286 // Less than 90 minutes, but more than an hour ago.
2287 $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
2288 } elseif ( $diff->i >= 1 ) {
2289 // A few minutes ago.
2290 $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
2291 } elseif ( $diff->s >= 30 ) {
2292 // Less than a minute, but more than 30 sec ago.
2293 $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
2294 } else {
2295 // Less than 30 seconds ago.
2296 $ts = wfMessage( 'just-now' )->text();
2297 }
2298
2299 return $ts;
2300 }
2301
2302 /**
2303 * @param $key string
2304 * @return array|null
2305 */
2306 function getMessage( $key ) {
2307 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
2308 }
2309
2310 /**
2311 * @return array
2312 */
2313 function getAllMessages() {
2314 return self::$dataCache->getItem( $this->mCode, 'messages' );
2315 }
2316
2317 /**
2318 * @param $in
2319 * @param $out
2320 * @param $string
2321 * @return string
2322 */
2323 function iconv( $in, $out, $string ) {
2324 # This is a wrapper for iconv in all languages except esperanto,
2325 # which does some nasty x-conversions beforehand
2326
2327 # Even with //IGNORE iconv can whine about illegal characters in
2328 # *input* string. We just ignore those too.
2329 # REF: http://bugs.php.net/bug.php?id=37166
2330 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
2331 wfSuppressWarnings();
2332 $text = iconv( $in, $out . '//IGNORE', $string );
2333 wfRestoreWarnings();
2334 return $text;
2335 }
2336
2337 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
2338
2339 /**
2340 * @param $matches array
2341 * @return mixed|string
2342 */
2343 function ucwordbreaksCallbackAscii( $matches ) {
2344 return $this->ucfirst( $matches[1] );
2345 }
2346
2347 /**
2348 * @param $matches array
2349 * @return string
2350 */
2351 function ucwordbreaksCallbackMB( $matches ) {
2352 return mb_strtoupper( $matches[0] );
2353 }
2354
2355 /**
2356 * @param $matches array
2357 * @return string
2358 */
2359 function ucCallback( $matches ) {
2360 list( $wikiUpperChars ) = self::getCaseMaps();
2361 return strtr( $matches[1], $wikiUpperChars );
2362 }
2363
2364 /**
2365 * @param $matches array
2366 * @return string
2367 */
2368 function lcCallback( $matches ) {
2369 list( , $wikiLowerChars ) = self::getCaseMaps();
2370 return strtr( $matches[1], $wikiLowerChars );
2371 }
2372
2373 /**
2374 * @param $matches array
2375 * @return string
2376 */
2377 function ucwordsCallbackMB( $matches ) {
2378 return mb_strtoupper( $matches[0] );
2379 }
2380
2381 /**
2382 * @param $matches array
2383 * @return string
2384 */
2385 function ucwordsCallbackWiki( $matches ) {
2386 list( $wikiUpperChars ) = self::getCaseMaps();
2387 return strtr( $matches[0], $wikiUpperChars );
2388 }
2389
2390 /**
2391 * Make a string's first character uppercase
2392 *
2393 * @param $str string
2394 *
2395 * @return string
2396 */
2397 function ucfirst( $str ) {
2398 $o = ord( $str );
2399 if ( $o < 96 ) { // if already uppercase...
2400 return $str;
2401 } elseif ( $o < 128 ) {
2402 return ucfirst( $str ); // use PHP's ucfirst()
2403 } else {
2404 // fall back to more complex logic in case of multibyte strings
2405 return $this->uc( $str, true );
2406 }
2407 }
2408
2409 /**
2410 * Convert a string to uppercase
2411 *
2412 * @param $str string
2413 * @param $first bool
2414 *
2415 * @return string
2416 */
2417 function uc( $str, $first = false ) {
2418 if ( function_exists( 'mb_strtoupper' ) ) {
2419 if ( $first ) {
2420 if ( $this->isMultibyte( $str ) ) {
2421 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2422 } else {
2423 return ucfirst( $str );
2424 }
2425 } else {
2426 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
2427 }
2428 } else {
2429 if ( $this->isMultibyte( $str ) ) {
2430 $x = $first ? '^' : '';
2431 return preg_replace_callback(
2432 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2433 array( $this, 'ucCallback' ),
2434 $str
2435 );
2436 } else {
2437 return $first ? ucfirst( $str ) : strtoupper( $str );
2438 }
2439 }
2440 }
2441
2442 /**
2443 * @param $str string
2444 * @return mixed|string
2445 */
2446 function lcfirst( $str ) {
2447 $o = ord( $str );
2448 if ( !$o ) {
2449 return strval( $str );
2450 } elseif ( $o >= 128 ) {
2451 return $this->lc( $str, true );
2452 } elseif ( $o > 96 ) {
2453 return $str;
2454 } else {
2455 $str[0] = strtolower( $str[0] );
2456 return $str;
2457 }
2458 }
2459
2460 /**
2461 * @param $str string
2462 * @param $first bool
2463 * @return mixed|string
2464 */
2465 function lc( $str, $first = false ) {
2466 if ( function_exists( 'mb_strtolower' ) ) {
2467 if ( $first ) {
2468 if ( $this->isMultibyte( $str ) ) {
2469 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
2470 } else {
2471 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
2472 }
2473 } else {
2474 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
2475 }
2476 } else {
2477 if ( $this->isMultibyte( $str ) ) {
2478 $x = $first ? '^' : '';
2479 return preg_replace_callback(
2480 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2481 array( $this, 'lcCallback' ),
2482 $str
2483 );
2484 } else {
2485 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2486 }
2487 }
2488 }
2489
2490 /**
2491 * @param $str string
2492 * @return bool
2493 */
2494 function isMultibyte( $str ) {
2495 return (bool)preg_match( '/[\x80-\xff]/', $str );
2496 }
2497
2498 /**
2499 * @param $str string
2500 * @return mixed|string
2501 */
2502 function ucwords( $str ) {
2503 if ( $this->isMultibyte( $str ) ) {
2504 $str = $this->lc( $str );
2505
2506 // regexp to find first letter in each word (i.e. after each space)
2507 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2508
2509 // function to use to capitalize a single char
2510 if ( function_exists( 'mb_strtoupper' ) ) {
2511 return preg_replace_callback(
2512 $replaceRegexp,
2513 array( $this, 'ucwordsCallbackMB' ),
2514 $str
2515 );
2516 } else {
2517 return preg_replace_callback(
2518 $replaceRegexp,
2519 array( $this, 'ucwordsCallbackWiki' ),
2520 $str
2521 );
2522 }
2523 } else {
2524 return ucwords( strtolower( $str ) );
2525 }
2526 }
2527
2528 /**
2529 * capitalize words at word breaks
2530 *
2531 * @param $str string
2532 * @return mixed
2533 */
2534 function ucwordbreaks( $str ) {
2535 if ( $this->isMultibyte( $str ) ) {
2536 $str = $this->lc( $str );
2537
2538 // since \b doesn't work for UTF-8, we explicitely define word break chars
2539 $breaks = "[ \-\(\)\}\{\.,\?!]";
2540
2541 // find first letter after word break
2542 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2543
2544 if ( function_exists( 'mb_strtoupper' ) ) {
2545 return preg_replace_callback(
2546 $replaceRegexp,
2547 array( $this, 'ucwordbreaksCallbackMB' ),
2548 $str
2549 );
2550 } else {
2551 return preg_replace_callback(
2552 $replaceRegexp,
2553 array( $this, 'ucwordsCallbackWiki' ),
2554 $str
2555 );
2556 }
2557 } else {
2558 return preg_replace_callback(
2559 '/\b([\w\x80-\xff]+)\b/',
2560 array( $this, 'ucwordbreaksCallbackAscii' ),
2561 $str
2562 );
2563 }
2564 }
2565
2566 /**
2567 * Return a case-folded representation of $s
2568 *
2569 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2570 * and $s2 are the same except for the case of their characters. It is not
2571 * necessary for the value returned to make sense when displayed.
2572 *
2573 * Do *not* perform any other normalisation in this function. If a caller
2574 * uses this function when it should be using a more general normalisation
2575 * function, then fix the caller.
2576 *
2577 * @param $s string
2578 *
2579 * @return string
2580 */
2581 function caseFold( $s ) {
2582 return $this->uc( $s );
2583 }
2584
2585 /**
2586 * @param $s string
2587 * @return string
2588 */
2589 function checkTitleEncoding( $s ) {
2590 if ( is_array( $s ) ) {
2591 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2592 }
2593 if ( StringUtils::isUtf8( $s ) ) {
2594 return $s;
2595 }
2596
2597 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2598 }
2599
2600 /**
2601 * @return array
2602 */
2603 function fallback8bitEncoding() {
2604 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2605 }
2606
2607 /**
2608 * Most writing systems use whitespace to break up words.
2609 * Some languages such as Chinese don't conventionally do this,
2610 * which requires special handling when breaking up words for
2611 * searching etc.
2612 *
2613 * @return bool
2614 */
2615 function hasWordBreaks() {
2616 return true;
2617 }
2618
2619 /**
2620 * Some languages such as Chinese require word segmentation,
2621 * Specify such segmentation when overridden in derived class.
2622 *
2623 * @param $string String
2624 * @return String
2625 */
2626 function segmentByWord( $string ) {
2627 return $string;
2628 }
2629
2630 /**
2631 * Some languages have special punctuation need to be normalized.
2632 * Make such changes here.
2633 *
2634 * @param $string String
2635 * @return String
2636 */
2637 function normalizeForSearch( $string ) {
2638 return self::convertDoubleWidth( $string );
2639 }
2640
2641 /**
2642 * convert double-width roman characters to single-width.
2643 * range: ff00-ff5f ~= 0020-007f
2644 *
2645 * @param $string string
2646 *
2647 * @return string
2648 */
2649 protected static function convertDoubleWidth( $string ) {
2650 static $full = null;
2651 static $half = null;
2652
2653 if ( $full === null ) {
2654 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2655 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2656 $full = str_split( $fullWidth, 3 );
2657 $half = str_split( $halfWidth );
2658 }
2659
2660 $string = str_replace( $full, $half, $string );
2661 return $string;
2662 }
2663
2664 /**
2665 * @param $string string
2666 * @param $pattern string
2667 * @return string
2668 */
2669 protected static function insertSpace( $string, $pattern ) {
2670 $string = preg_replace( $pattern, " $1 ", $string );
2671 $string = preg_replace( '/ +/', ' ', $string );
2672 return $string;
2673 }
2674
2675 /**
2676 * @param $termsArray array
2677 * @return array
2678 */
2679 function convertForSearchResult( $termsArray ) {
2680 # some languages, e.g. Chinese, need to do a conversion
2681 # in order for search results to be displayed correctly
2682 return $termsArray;
2683 }
2684
2685 /**
2686 * Get the first character of a string.
2687 *
2688 * @param $s string
2689 * @return string
2690 */
2691 function firstChar( $s ) {
2692 $matches = array();
2693 preg_match(
2694 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2695 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2696 $s,
2697 $matches
2698 );
2699
2700 if ( isset( $matches[1] ) ) {
2701 if ( strlen( $matches[1] ) != 3 ) {
2702 return $matches[1];
2703 }
2704
2705 // Break down Hangul syllables to grab the first jamo
2706 $code = utf8ToCodepoint( $matches[1] );
2707 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2708 return $matches[1];
2709 } elseif ( $code < 0xb098 ) {
2710 return "\xe3\x84\xb1";
2711 } elseif ( $code < 0xb2e4 ) {
2712 return "\xe3\x84\xb4";
2713 } elseif ( $code < 0xb77c ) {
2714 return "\xe3\x84\xb7";
2715 } elseif ( $code < 0xb9c8 ) {
2716 return "\xe3\x84\xb9";
2717 } elseif ( $code < 0xbc14 ) {
2718 return "\xe3\x85\x81";
2719 } elseif ( $code < 0xc0ac ) {
2720 return "\xe3\x85\x82";
2721 } elseif ( $code < 0xc544 ) {
2722 return "\xe3\x85\x85";
2723 } elseif ( $code < 0xc790 ) {
2724 return "\xe3\x85\x87";
2725 } elseif ( $code < 0xcc28 ) {
2726 return "\xe3\x85\x88";
2727 } elseif ( $code < 0xce74 ) {
2728 return "\xe3\x85\x8a";
2729 } elseif ( $code < 0xd0c0 ) {
2730 return "\xe3\x85\x8b";
2731 } elseif ( $code < 0xd30c ) {
2732 return "\xe3\x85\x8c";
2733 } elseif ( $code < 0xd558 ) {
2734 return "\xe3\x85\x8d";
2735 } else {
2736 return "\xe3\x85\x8e";
2737 }
2738 } else {
2739 return '';
2740 }
2741 }
2742
2743 function initEncoding() {
2744 # Some languages may have an alternate char encoding option
2745 # (Esperanto X-coding, Japanese furigana conversion, etc)
2746 # If this language is used as the primary content language,
2747 # an override to the defaults can be set here on startup.
2748 }
2749
2750 /**
2751 * @param $s string
2752 * @return string
2753 */
2754 function recodeForEdit( $s ) {
2755 # For some languages we'll want to explicitly specify
2756 # which characters make it into the edit box raw
2757 # or are converted in some way or another.
2758 global $wgEditEncoding;
2759 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2760 return $s;
2761 } else {
2762 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2763 }
2764 }
2765
2766 /**
2767 * @param $s string
2768 * @return string
2769 */
2770 function recodeInput( $s ) {
2771 # Take the previous into account.
2772 global $wgEditEncoding;
2773 if ( $wgEditEncoding != '' ) {
2774 $enc = $wgEditEncoding;
2775 } else {
2776 $enc = 'UTF-8';
2777 }
2778 if ( $enc == 'UTF-8' ) {
2779 return $s;
2780 } else {
2781 return $this->iconv( $enc, 'UTF-8', $s );
2782 }
2783 }
2784
2785 /**
2786 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2787 * also cleans up certain backwards-compatible sequences, converting them
2788 * to the modern Unicode equivalent.
2789 *
2790 * This is language-specific for performance reasons only.
2791 *
2792 * @param $s string
2793 *
2794 * @return string
2795 */
2796 function normalize( $s ) {
2797 global $wgAllUnicodeFixes;
2798 $s = UtfNormal::cleanUp( $s );
2799 if ( $wgAllUnicodeFixes ) {
2800 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2801 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2802 }
2803
2804 return $s;
2805 }
2806
2807 /**
2808 * Transform a string using serialized data stored in the given file (which
2809 * must be in the serialized subdirectory of $IP). The file contains pairs
2810 * mapping source characters to destination characters.
2811 *
2812 * The data is cached in process memory. This will go faster if you have the
2813 * FastStringSearch extension.
2814 *
2815 * @param $file string
2816 * @param $string string
2817 *
2818 * @throws MWException
2819 * @return string
2820 */
2821 function transformUsingPairFile( $file, $string ) {
2822 if ( !isset( $this->transformData[$file] ) ) {
2823 $data = wfGetPrecompiledData( $file );
2824 if ( $data === false ) {
2825 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2826 }
2827 $this->transformData[$file] = new ReplacementArray( $data );
2828 }
2829 return $this->transformData[$file]->replace( $string );
2830 }
2831
2832 /**
2833 * For right-to-left language support
2834 *
2835 * @return bool
2836 */
2837 function isRTL() {
2838 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2839 }
2840
2841 /**
2842 * Return the correct HTML 'dir' attribute value for this language.
2843 * @return String
2844 */
2845 function getDir() {
2846 return $this->isRTL() ? 'rtl' : 'ltr';
2847 }
2848
2849 /**
2850 * Return 'left' or 'right' as appropriate alignment for line-start
2851 * for this language's text direction.
2852 *
2853 * Should be equivalent to CSS3 'start' text-align value....
2854 *
2855 * @return String
2856 */
2857 function alignStart() {
2858 return $this->isRTL() ? 'right' : 'left';
2859 }
2860
2861 /**
2862 * Return 'right' or 'left' as appropriate alignment for line-end
2863 * for this language's text direction.
2864 *
2865 * Should be equivalent to CSS3 'end' text-align value....
2866 *
2867 * @return String
2868 */
2869 function alignEnd() {
2870 return $this->isRTL() ? 'left' : 'right';
2871 }
2872
2873 /**
2874 * A hidden direction mark (LRM or RLM), depending on the language direction.
2875 * Unlike getDirMark(), this function returns the character as an HTML entity.
2876 * This function should be used when the output is guaranteed to be HTML,
2877 * because it makes the output HTML source code more readable. When
2878 * the output is plain text or can be escaped, getDirMark() should be used.
2879 *
2880 * @param $opposite Boolean Get the direction mark opposite to your language
2881 * @return string
2882 * @since 1.20
2883 */
2884 function getDirMarkEntity( $opposite = false ) {
2885 if ( $opposite ) {
2886 return $this->isRTL() ? '&lrm;' : '&rlm;';
2887 }
2888 return $this->isRTL() ? '&rlm;' : '&lrm;';
2889 }
2890
2891 /**
2892 * A hidden direction mark (LRM or RLM), depending on the language direction.
2893 * This function produces them as invisible Unicode characters and
2894 * the output may be hard to read and debug, so it should only be used
2895 * when the output is plain text or can be escaped. When the output is
2896 * HTML, use getDirMarkEntity() instead.
2897 *
2898 * @param $opposite Boolean Get the direction mark opposite to your language
2899 * @return string
2900 */
2901 function getDirMark( $opposite = false ) {
2902 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2903 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2904 if ( $opposite ) {
2905 return $this->isRTL() ? $lrm : $rlm;
2906 }
2907 return $this->isRTL() ? $rlm : $lrm;
2908 }
2909
2910 /**
2911 * @return array
2912 */
2913 function capitalizeAllNouns() {
2914 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2915 }
2916
2917 /**
2918 * An arrow, depending on the language direction.
2919 *
2920 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2921 * @return string
2922 */
2923 function getArrow( $direction = 'forwards' ) {
2924 switch ( $direction ) {
2925 case 'forwards':
2926 return $this->isRTL() ? '←' : '→';
2927 case 'backwards':
2928 return $this->isRTL() ? '→' : '←';
2929 case 'left':
2930 return '←';
2931 case 'right':
2932 return '→';
2933 case 'up':
2934 return '↑';
2935 case 'down':
2936 return '↓';
2937 }
2938 }
2939
2940 /**
2941 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2942 *
2943 * @return bool
2944 */
2945 function linkPrefixExtension() {
2946 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2947 }
2948
2949 /**
2950 * @return array
2951 */
2952 function getMagicWords() {
2953 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2954 }
2955
2956 protected function doMagicHook() {
2957 if ( $this->mMagicHookDone ) {
2958 return;
2959 }
2960 $this->mMagicHookDone = true;
2961 wfProfileIn( 'LanguageGetMagic' );
2962 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2963 wfProfileOut( 'LanguageGetMagic' );
2964 }
2965
2966 /**
2967 * Fill a MagicWord object with data from here
2968 *
2969 * @param $mw
2970 */
2971 function getMagic( $mw ) {
2972 $this->doMagicHook();
2973
2974 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2975 $rawEntry = $this->mMagicExtensions[$mw->mId];
2976 } else {
2977 $magicWords = $this->getMagicWords();
2978 if ( isset( $magicWords[$mw->mId] ) ) {
2979 $rawEntry = $magicWords[$mw->mId];
2980 } else {
2981 $rawEntry = false;
2982 }
2983 }
2984
2985 if ( !is_array( $rawEntry ) ) {
2986 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2987 } else {
2988 $mw->mCaseSensitive = $rawEntry[0];
2989 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2990 }
2991 }
2992
2993 /**
2994 * Add magic words to the extension array
2995 *
2996 * @param $newWords array
2997 */
2998 function addMagicWordsByLang( $newWords ) {
2999 $fallbackChain = $this->getFallbackLanguages();
3000 $fallbackChain = array_reverse( $fallbackChain );
3001 foreach ( $fallbackChain as $code ) {
3002 if ( isset( $newWords[$code] ) ) {
3003 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
3004 }
3005 }
3006 }
3007
3008 /**
3009 * Get special page names, as an associative array
3010 * case folded alias => real name
3011 */
3012 function getSpecialPageAliases() {
3013 // Cache aliases because it may be slow to load them
3014 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
3015 // Initialise array
3016 $this->mExtendedSpecialPageAliases =
3017 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
3018 wfRunHooks( 'LanguageGetSpecialPageAliases',
3019 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
3020 }
3021
3022 return $this->mExtendedSpecialPageAliases;
3023 }
3024
3025 /**
3026 * Italic is unsuitable for some languages
3027 *
3028 * @param $text String: the text to be emphasized.
3029 * @return string
3030 */
3031 function emphasize( $text ) {
3032 return "<em>$text</em>";
3033 }
3034
3035 /**
3036 * Normally we output all numbers in plain en_US style, that is
3037 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
3038 * point twohundredthirtyfive. However this is not suitable for all
3039 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
3040 * Icelandic just want to use commas instead of dots, and dots instead
3041 * of commas like "293.291,235".
3042 *
3043 * An example of this function being called:
3044 * <code>
3045 * wfMessage( 'message' )->numParams( $num )->text()
3046 * </code>
3047 *
3048 * See LanguageGu.php for the Gujarati implementation and
3049 * $separatorTransformTable on MessageIs.php for
3050 * the , => . and . => , implementation.
3051 *
3052 * @todo check if it's viable to use localeconv() for the decimal
3053 * separator thing.
3054 * @param $number Mixed: the string to be formatted, should be an integer
3055 * or a floating point number.
3056 * @param $nocommafy Bool: set to true for special numbers like dates
3057 * @return string
3058 */
3059 public function formatNum( $number, $nocommafy = false ) {
3060 global $wgTranslateNumerals;
3061 if ( !$nocommafy ) {
3062 $number = $this->commafy( $number );
3063 $s = $this->separatorTransformTable();
3064 if ( $s ) {
3065 $number = strtr( $number, $s );
3066 }
3067 }
3068
3069 if ( $wgTranslateNumerals ) {
3070 $s = $this->digitTransformTable();
3071 if ( $s ) {
3072 $number = strtr( $number, $s );
3073 }
3074 }
3075
3076 return $number;
3077 }
3078
3079 /**
3080 * Front-end for non-commafied formatNum
3081 *
3082 * @param mixed $number the string to be formatted, should be an integer
3083 * or a floating point number.
3084 * @since 1.21
3085 * @return string
3086 */
3087 public function formatNumNoSeparators( $number ) {
3088 return $this->formatNum( $number, true );
3089 }
3090
3091 /**
3092 * @param $number string
3093 * @return string
3094 */
3095 function parseFormattedNumber( $number ) {
3096 $s = $this->digitTransformTable();
3097 if ( $s ) {
3098 $number = strtr( $number, array_flip( $s ) );
3099 }
3100
3101 $s = $this->separatorTransformTable();
3102 if ( $s ) {
3103 $number = strtr( $number, array_flip( $s ) );
3104 }
3105
3106 $number = strtr( $number, array( ',' => '' ) );
3107 return $number;
3108 }
3109
3110 /**
3111 * Adds commas to a given number
3112 * @since 1.19
3113 * @param $number mixed
3114 * @return string
3115 */
3116 function commafy( $number ) {
3117 $digitGroupingPattern = $this->digitGroupingPattern();
3118 if ( $number === null ) {
3119 return '';
3120 }
3121
3122 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
3123 // default grouping is at thousands, use the same for ###,###,### pattern too.
3124 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
3125 } else {
3126 // Ref: http://cldr.unicode.org/translation/number-patterns
3127 $sign = "";
3128 if ( intval( $number ) < 0 ) {
3129 // For negative numbers apply the algorithm like positive number and add sign.
3130 $sign = "-";
3131 $number = substr( $number, 1 );
3132 }
3133 $integerPart = array();
3134 $decimalPart = array();
3135 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
3136 preg_match( "/\d+/", $number, $integerPart );
3137 preg_match( "/\.\d*/", $number, $decimalPart );
3138 $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
3139 if ( $groupedNumber === $number ) {
3140 // the string does not have any number part. Eg: .12345
3141 return $sign . $groupedNumber;
3142 }
3143 $start = $end = strlen( $integerPart[0] );
3144 while ( $start > 0 ) {
3145 $match = $matches[0][$numMatches - 1];
3146 $matchLen = strlen( $match );
3147 $start = $end - $matchLen;
3148 if ( $start < 0 ) {
3149 $start = 0;
3150 }
3151 $groupedNumber = substr( $number, $start, $end -$start ) . $groupedNumber;
3152 $end = $start;
3153 if ( $numMatches > 1 ) {
3154 // use the last pattern for the rest of the number
3155 $numMatches--;
3156 }
3157 if ( $start > 0 ) {
3158 $groupedNumber = "," . $groupedNumber;
3159 }
3160 }
3161 return $sign . $groupedNumber;
3162 }
3163 }
3164
3165 /**
3166 * @return String
3167 */
3168 function digitGroupingPattern() {
3169 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3170 }
3171
3172 /**
3173 * @return array
3174 */
3175 function digitTransformTable() {
3176 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3177 }
3178
3179 /**
3180 * @return array
3181 */
3182 function separatorTransformTable() {
3183 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3184 }
3185
3186 /**
3187 * Take a list of strings and build a locale-friendly comma-separated
3188 * list, using the local comma-separator message.
3189 * The last two strings are chained with an "and".
3190 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3191 *
3192 * @param $l Array
3193 * @return string
3194 */
3195 function listToText( array $l ) {
3196 $m = count( $l ) - 1;
3197 if ( $m < 0 ) {
3198 return '';
3199 }
3200 if ( $m > 0 ) {
3201 $and = $this->getMessageFromDB( 'and' );
3202 $space = $this->getMessageFromDB( 'word-separator' );
3203 if ( $m > 1 ) {
3204 $comma = $this->getMessageFromDB( 'comma-separator' );
3205 }
3206 }
3207 $s = $l[$m];
3208 for ( $i = $m - 1; $i >= 0; $i-- ) {
3209 if ( $i == $m - 1 ) {
3210 $s = $l[$i] . $and . $space . $s;
3211 } else {
3212 $s = $l[$i] . $comma . $s;
3213 }
3214 }
3215 return $s;
3216 }
3217
3218 /**
3219 * Take a list of strings and build a locale-friendly comma-separated
3220 * list, using the local comma-separator message.
3221 * @param $list array of strings to put in a comma list
3222 * @return string
3223 */
3224 function commaList( array $list ) {
3225 return implode(
3226 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3227 $list
3228 );
3229 }
3230
3231 /**
3232 * Take a list of strings and build a locale-friendly semicolon-separated
3233 * list, using the local semicolon-separator message.
3234 * @param $list array of strings to put in a semicolon list
3235 * @return string
3236 */
3237 function semicolonList( array $list ) {
3238 return implode(
3239 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3240 $list
3241 );
3242 }
3243
3244 /**
3245 * Same as commaList, but separate it with the pipe instead.
3246 * @param $list array of strings to put in a pipe list
3247 * @return string
3248 */
3249 function pipeList( array $list ) {
3250 return implode(
3251 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3252 $list
3253 );
3254 }
3255
3256 /**
3257 * Truncate a string to a specified length in bytes, appending an optional
3258 * string (e.g. for ellipses)
3259 *
3260 * The database offers limited byte lengths for some columns in the database;
3261 * multi-byte character sets mean we need to ensure that only whole characters
3262 * are included, otherwise broken characters can be passed to the user
3263 *
3264 * If $length is negative, the string will be truncated from the beginning
3265 *
3266 * @param $string String to truncate
3267 * @param $length Int: maximum length (including ellipses)
3268 * @param $ellipsis String to append to the truncated text
3269 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3270 * $adjustLength was introduced in 1.18, before that behaved as if false.
3271 * @return string
3272 */
3273 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3274 # Use the localized ellipsis character
3275 if ( $ellipsis == '...' ) {
3276 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3277 }
3278 # Check if there is no need to truncate
3279 if ( $length == 0 ) {
3280 return $ellipsis; // convention
3281 } elseif ( strlen( $string ) <= abs( $length ) ) {
3282 return $string; // no need to truncate
3283 }
3284 $stringOriginal = $string;
3285 # If ellipsis length is >= $length then we can't apply $adjustLength
3286 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3287 $string = $ellipsis; // this can be slightly unexpected
3288 # Otherwise, truncate and add ellipsis...
3289 } else {
3290 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3291 if ( $length > 0 ) {
3292 $length -= $eLength;
3293 $string = substr( $string, 0, $length ); // xyz...
3294 $string = $this->removeBadCharLast( $string );
3295 $string = $string . $ellipsis;
3296 } else {
3297 $length += $eLength;
3298 $string = substr( $string, $length ); // ...xyz
3299 $string = $this->removeBadCharFirst( $string );
3300 $string = $ellipsis . $string;
3301 }
3302 }
3303 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3304 # This check is *not* redundant if $adjustLength, due to the single case where
3305 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3306 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3307 return $string;
3308 } else {
3309 return $stringOriginal;
3310 }
3311 }
3312
3313 /**
3314 * Remove bytes that represent an incomplete Unicode character
3315 * at the end of string (e.g. bytes of the char are missing)
3316 *
3317 * @param $string String
3318 * @return string
3319 */
3320 protected function removeBadCharLast( $string ) {
3321 if ( $string != '' ) {
3322 $char = ord( $string[strlen( $string ) - 1] );
3323 $m = array();
3324 if ( $char >= 0xc0 ) {
3325 # We got the first byte only of a multibyte char; remove it.
3326 $string = substr( $string, 0, -1 );
3327 } elseif ( $char >= 0x80 &&
3328 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3329 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m )
3330 ) {
3331 # We chopped in the middle of a character; remove it
3332 $string = $m[1];
3333 }
3334 }
3335 return $string;
3336 }
3337
3338 /**
3339 * Remove bytes that represent an incomplete Unicode character
3340 * at the start of string (e.g. bytes of the char are missing)
3341 *
3342 * @param $string String
3343 * @return string
3344 */
3345 protected function removeBadCharFirst( $string ) {
3346 if ( $string != '' ) {
3347 $char = ord( $string[0] );
3348 if ( $char >= 0x80 && $char < 0xc0 ) {
3349 # We chopped in the middle of a character; remove the whole thing
3350 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3351 }
3352 }
3353 return $string;
3354 }
3355
3356 /**
3357 * Truncate a string of valid HTML to a specified length in bytes,
3358 * appending an optional string (e.g. for ellipses), and return valid HTML
3359 *
3360 * This is only intended for styled/linked text, such as HTML with
3361 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3362 * Also, this will not detect things like "display:none" CSS.
3363 *
3364 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3365 *
3366 * @param string $text HTML string to truncate
3367 * @param int $length (zero/positive) Maximum length (including ellipses)
3368 * @param string $ellipsis String to append to the truncated text
3369 * @return string
3370 */
3371 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3372 # Use the localized ellipsis character
3373 if ( $ellipsis == '...' ) {
3374 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3375 }
3376 # Check if there is clearly no need to truncate
3377 if ( $length <= 0 ) {
3378 return $ellipsis; // no text shown, nothing to format (convention)
3379 } elseif ( strlen( $text ) <= $length ) {
3380 return $text; // string short enough even *with* HTML (short-circuit)
3381 }
3382
3383 $dispLen = 0; // innerHTML legth so far
3384 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3385 $tagType = 0; // 0-open, 1-close
3386 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3387 $entityState = 0; // 0-not entity, 1-entity
3388 $tag = $ret = ''; // accumulated tag name, accumulated result string
3389 $openTags = array(); // open tag stack
3390 $maybeState = null; // possible truncation state
3391
3392 $textLen = strlen( $text );
3393 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3394 for ( $pos = 0; true; ++$pos ) {
3395 # Consider truncation once the display length has reached the maximim.
3396 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3397 # Check that we're not in the middle of a bracket/entity...
3398 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3399 if ( !$testingEllipsis ) {
3400 $testingEllipsis = true;
3401 # Save where we are; we will truncate here unless there turn out to
3402 # be so few remaining characters that truncation is not necessary.
3403 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3404 $maybeState = array( $ret, $openTags ); // save state
3405 }
3406 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3407 # String in fact does need truncation, the truncation point was OK.
3408 list( $ret, $openTags ) = $maybeState; // reload state
3409 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3410 $ret .= $ellipsis; // add ellipsis
3411 break;
3412 }
3413 }
3414 if ( $pos >= $textLen ) {
3415 break; // extra iteration just for above checks
3416 }
3417
3418 # Read the next char...
3419 $ch = $text[$pos];
3420 $lastCh = $pos ? $text[$pos - 1] : '';
3421 $ret .= $ch; // add to result string
3422 if ( $ch == '<' ) {
3423 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3424 $entityState = 0; // for bad HTML
3425 $bracketState = 1; // tag started (checking for backslash)
3426 } elseif ( $ch == '>' ) {
3427 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3428 $entityState = 0; // for bad HTML
3429 $bracketState = 0; // out of brackets
3430 } elseif ( $bracketState == 1 ) {
3431 if ( $ch == '/' ) {
3432 $tagType = 1; // close tag (e.g. "</span>")
3433 } else {
3434 $tagType = 0; // open tag (e.g. "<span>")
3435 $tag .= $ch;
3436 }
3437 $bracketState = 2; // building tag name
3438 } elseif ( $bracketState == 2 ) {
3439 if ( $ch != ' ' ) {
3440 $tag .= $ch;
3441 } else {
3442 // Name found (e.g. "<a href=..."), add on tag attributes...
3443 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3444 }
3445 } elseif ( $bracketState == 0 ) {
3446 if ( $entityState ) {
3447 if ( $ch == ';' ) {
3448 $entityState = 0;
3449 $dispLen++; // entity is one displayed char
3450 }
3451 } else {
3452 if ( $neLength == 0 && !$maybeState ) {
3453 // Save state without $ch. We want to *hit* the first
3454 // display char (to get tags) but not *use* it if truncating.
3455 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3456 }
3457 if ( $ch == '&' ) {
3458 $entityState = 1; // entity found, (e.g. "&#160;")
3459 } else {
3460 $dispLen++; // this char is displayed
3461 // Add the next $max display text chars after this in one swoop...
3462 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3463 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3464 $dispLen += $skipped;
3465 $pos += $skipped;
3466 }
3467 }
3468 }
3469 }
3470 // Close the last tag if left unclosed by bad HTML
3471 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3472 while ( count( $openTags ) > 0 ) {
3473 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3474 }
3475 return $ret;
3476 }
3477
3478 /**
3479 * truncateHtml() helper function
3480 * like strcspn() but adds the skipped chars to $ret
3481 *
3482 * @param $ret
3483 * @param $text
3484 * @param $search
3485 * @param $start
3486 * @param $len
3487 * @return int
3488 */
3489 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3490 if ( $len === null ) {
3491 $len = -1; // -1 means "no limit" for strcspn
3492 } elseif ( $len < 0 ) {
3493 $len = 0; // sanity
3494 }
3495 $skipCount = 0;
3496 if ( $start < strlen( $text ) ) {
3497 $skipCount = strcspn( $text, $search, $start, $len );
3498 $ret .= substr( $text, $start, $skipCount );
3499 }
3500 return $skipCount;
3501 }
3502
3503 /**
3504 * truncateHtml() helper function
3505 * (a) push or pop $tag from $openTags as needed
3506 * (b) clear $tag value
3507 * @param &$tag string Current HTML tag name we are looking at
3508 * @param $tagType int (0-open tag, 1-close tag)
3509 * @param $lastCh string Character before the '>' that ended this tag
3510 * @param &$openTags array Open tag stack (not accounting for $tag)
3511 */
3512 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3513 $tag = ltrim( $tag );
3514 if ( $tag != '' ) {
3515 if ( $tagType == 0 && $lastCh != '/' ) {
3516 $openTags[] = $tag; // tag opened (didn't close itself)
3517 } elseif ( $tagType == 1 ) {
3518 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3519 array_pop( $openTags ); // tag closed
3520 }
3521 }
3522 $tag = '';
3523 }
3524 }
3525
3526 /**
3527 * Grammatical transformations, needed for inflected languages
3528 * Invoked by putting {{grammar:case|word}} in a message
3529 *
3530 * @param $word string
3531 * @param $case string
3532 * @return string
3533 */
3534 function convertGrammar( $word, $case ) {
3535 global $wgGrammarForms;
3536 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3537 return $wgGrammarForms[$this->getCode()][$case][$word];
3538 }
3539 return $word;
3540 }
3541 /**
3542 * Get the grammar forms for the content language
3543 * @return array of grammar forms
3544 * @since 1.20
3545 */
3546 function getGrammarForms() {
3547 global $wgGrammarForms;
3548 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3549 return $wgGrammarForms[$this->getCode()];
3550 }
3551 return array();
3552 }
3553 /**
3554 * Provides an alternative text depending on specified gender.
3555 * Usage {{gender:username|masculine|feminine|neutral}}.
3556 * username is optional, in which case the gender of current user is used,
3557 * but only in (some) interface messages; otherwise default gender is used.
3558 *
3559 * If no forms are given, an empty string is returned. If only one form is
3560 * given, it will be returned unconditionally. These details are implied by
3561 * the caller and cannot be overridden in subclasses.
3562 *
3563 * If more than one form is given, the default is to use the neutral one
3564 * if it is specified, and to use the masculine one otherwise. These
3565 * details can be overridden in subclasses.
3566 *
3567 * @param $gender string
3568 * @param $forms array
3569 *
3570 * @return string
3571 */
3572 function gender( $gender, $forms ) {
3573 if ( !count( $forms ) ) {
3574 return '';
3575 }
3576 $forms = $this->preConvertPlural( $forms, 2 );
3577 if ( $gender === 'male' ) {
3578 return $forms[0];
3579 }
3580 if ( $gender === 'female' ) {
3581 return $forms[1];
3582 }
3583 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3584 }
3585
3586 /**
3587 * Plural form transformations, needed for some languages.
3588 * For example, there are 3 form of plural in Russian and Polish,
3589 * depending on "count mod 10". See [[w:Plural]]
3590 * For English it is pretty simple.
3591 *
3592 * Invoked by putting {{plural:count|wordform1|wordform2}}
3593 * or {{plural:count|wordform1|wordform2|wordform3}}
3594 *
3595 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3596 *
3597 * @param $count Integer: non-localized number
3598 * @param $forms Array: different plural forms
3599 * @return string Correct form of plural for $count in this language
3600 */
3601 function convertPlural( $count, $forms ) {
3602 if ( !count( $forms ) ) {
3603 return '';
3604 }
3605
3606 // Handle explicit n=pluralform cases
3607 foreach ( $forms as $index => $form ) {
3608 if ( preg_match( '/\d+=/i', $form ) ) {
3609 $pos = strpos( $form, '=' );
3610 if ( substr( $form, 0, $pos ) === (string) $count ) {
3611 return substr( $form, $pos + 1 );
3612 }
3613 unset( $forms[$index] );
3614 }
3615 }
3616 $forms = array_values( $forms );
3617
3618 $pluralForm = $this->getPluralRuleIndexNumber( $count );
3619 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3620 return $forms[$pluralForm];
3621 }
3622
3623 /**
3624 * Checks that convertPlural was given an array and pads it to requested
3625 * amount of forms by copying the last one.
3626 *
3627 * @param $count Integer: How many forms should there be at least
3628 * @param $forms Array of forms given to convertPlural
3629 * @return array Padded array of forms or an exception if not an array
3630 */
3631 protected function preConvertPlural( /* Array */ $forms, $count ) {
3632 while ( count( $forms ) < $count ) {
3633 $forms[] = $forms[count( $forms ) - 1];
3634 }
3635 return $forms;
3636 }
3637
3638 /**
3639 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3640 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3641 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3642 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3643 * match up with it.
3644 *
3645 * @param $str String: the validated block duration in English
3646 * @return string Somehow translated block duration
3647 * @see LanguageFi.php for example implementation
3648 */
3649 function translateBlockExpiry( $str ) {
3650 $duration = SpecialBlock::getSuggestedDurations( $this );
3651 foreach ( $duration as $show => $value ) {
3652 if ( strcmp( $str, $value ) == 0 ) {
3653 return htmlspecialchars( trim( $show ) );
3654 }
3655 }
3656
3657 // Since usually only infinite or indefinite is only on list, so try
3658 // equivalents if still here.
3659 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3660 if ( in_array( $str, $indefs ) ) {
3661 foreach ( $indefs as $val ) {
3662 $show = array_search( $val, $duration, true );
3663 if ( $show !== false ) {
3664 return htmlspecialchars( trim( $show ) );
3665 }
3666 }
3667 }
3668
3669 // If all else fails, return a standard duration or timestamp description.
3670 $time = strtotime( $str, 0 );
3671 if ( $time === false ) { // Unknown format. Return it as-is in case.
3672 return $str;
3673 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3674 // $time is relative to 0 so it's a duration length.
3675 return $this->formatDuration( $time );
3676 } else { // It's an absolute timestamp.
3677 if ( $time === 0 ) {
3678 // wfTimestamp() handles 0 as current time instead of epoch.
3679 return $this->timeanddate( '19700101000000' );
3680 } else {
3681 return $this->timeanddate( $time );
3682 }
3683 }
3684 }
3685
3686 /**
3687 * languages like Chinese need to be segmented in order for the diff
3688 * to be of any use
3689 *
3690 * @param $text String
3691 * @return String
3692 */
3693 public function segmentForDiff( $text ) {
3694 return $text;
3695 }
3696
3697 /**
3698 * and unsegment to show the result
3699 *
3700 * @param $text String
3701 * @return String
3702 */
3703 public function unsegmentForDiff( $text ) {
3704 return $text;
3705 }
3706
3707 /**
3708 * Return the LanguageConverter used in the Language
3709 *
3710 * @since 1.19
3711 * @return LanguageConverter
3712 */
3713 public function getConverter() {
3714 return $this->mConverter;
3715 }
3716
3717 /**
3718 * convert text to all supported variants
3719 *
3720 * @param $text string
3721 * @return array
3722 */
3723 public function autoConvertToAllVariants( $text ) {
3724 return $this->mConverter->autoConvertToAllVariants( $text );
3725 }
3726
3727 /**
3728 * convert text to different variants of a language.
3729 *
3730 * @param $text string
3731 * @return string
3732 */
3733 public function convert( $text ) {
3734 return $this->mConverter->convert( $text );
3735 }
3736
3737 /**
3738 * Convert a Title object to a string in the preferred variant
3739 *
3740 * @param $title Title
3741 * @return string
3742 */
3743 public function convertTitle( $title ) {
3744 return $this->mConverter->convertTitle( $title );
3745 }
3746
3747 /**
3748 * Convert a namespace index to a string in the preferred variant
3749 *
3750 * @param $ns int
3751 * @return string
3752 */
3753 public function convertNamespace( $ns ) {
3754 return $this->mConverter->convertNamespace( $ns );
3755 }
3756
3757 /**
3758 * Check if this is a language with variants
3759 *
3760 * @return bool
3761 */
3762 public function hasVariants() {
3763 return count( $this->getVariants() ) > 1;
3764 }
3765
3766 /**
3767 * Check if the language has the specific variant
3768 *
3769 * @since 1.19
3770 * @param $variant string
3771 * @return bool
3772 */
3773 public function hasVariant( $variant ) {
3774 return (bool)$this->mConverter->validateVariant( $variant );
3775 }
3776
3777 /**
3778 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3779 *
3780 * @param $text string
3781 * @return string
3782 */
3783 public function armourMath( $text ) {
3784 return $this->mConverter->armourMath( $text );
3785 }
3786
3787 /**
3788 * Perform output conversion on a string, and encode for safe HTML output.
3789 * @param $text String text to be converted
3790 * @param $isTitle Bool whether this conversion is for the article title
3791 * @return string
3792 * @todo this should get integrated somewhere sane
3793 */
3794 public function convertHtml( $text, $isTitle = false ) {
3795 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3796 }
3797
3798 /**
3799 * @param $key string
3800 * @return string
3801 */
3802 public function convertCategoryKey( $key ) {
3803 return $this->mConverter->convertCategoryKey( $key );
3804 }
3805
3806 /**
3807 * Get the list of variants supported by this language
3808 * see sample implementation in LanguageZh.php
3809 *
3810 * @return array an array of language codes
3811 */
3812 public function getVariants() {
3813 return $this->mConverter->getVariants();
3814 }
3815
3816 /**
3817 * @return string
3818 */
3819 public function getPreferredVariant() {
3820 return $this->mConverter->getPreferredVariant();
3821 }
3822
3823 /**
3824 * @return string
3825 */
3826 public function getDefaultVariant() {
3827 return $this->mConverter->getDefaultVariant();
3828 }
3829
3830 /**
3831 * @return string
3832 */
3833 public function getURLVariant() {
3834 return $this->mConverter->getURLVariant();
3835 }
3836
3837 /**
3838 * If a language supports multiple variants, it is
3839 * possible that non-existing link in one variant
3840 * actually exists in another variant. this function
3841 * tries to find it. See e.g. LanguageZh.php
3842 *
3843 * @param $link String: the name of the link
3844 * @param $nt Mixed: the title object of the link
3845 * @param $ignoreOtherCond Boolean: to disable other conditions when
3846 * we need to transclude a template or update a category's link
3847 * @return null the input parameters may be modified upon return
3848 */
3849 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3850 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3851 }
3852
3853 /**
3854 * If a language supports multiple variants, converts text
3855 * into an array of all possible variants of the text:
3856 * 'variant' => text in that variant
3857 *
3858 * @deprecated since 1.17 Use autoConvertToAllVariants()
3859 *
3860 * @param $text string
3861 *
3862 * @return string
3863 */
3864 public function convertLinkToAllVariants( $text ) {
3865 return $this->mConverter->convertLinkToAllVariants( $text );
3866 }
3867
3868 /**
3869 * returns language specific options used by User::getPageRenderHash()
3870 * for example, the preferred language variant
3871 *
3872 * @return string
3873 */
3874 function getExtraHashOptions() {
3875 return $this->mConverter->getExtraHashOptions();
3876 }
3877
3878 /**
3879 * For languages that support multiple variants, the title of an
3880 * article may be displayed differently in different variants. this
3881 * function returns the apporiate title defined in the body of the article.
3882 *
3883 * @return string
3884 */
3885 public function getParsedTitle() {
3886 return $this->mConverter->getParsedTitle();
3887 }
3888
3889 /**
3890 * Prepare external link text for conversion. When the text is
3891 * a URL, it shouldn't be converted, and it'll be wrapped in
3892 * the "raw" tag (-{R| }-) to prevent conversion.
3893 *
3894 * This function is called "markNoConversion" for historical
3895 * reasons.
3896 *
3897 * @param $text String: text to be used for external link
3898 * @param $noParse bool: wrap it without confirming it's a real URL first
3899 * @return string the tagged text
3900 */
3901 public function markNoConversion( $text, $noParse = false ) {
3902 // Excluding protocal-relative URLs may avoid many false positives.
3903 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3904 return $this->mConverter->markNoConversion( $text );
3905 } else {
3906 return $text;
3907 }
3908 }
3909
3910 /**
3911 * A regular expression to match legal word-trailing characters
3912 * which should be merged onto a link of the form [[foo]]bar.
3913 *
3914 * @return string
3915 */
3916 public function linkTrail() {
3917 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3918 }
3919
3920 /**
3921 * @return Language
3922 */
3923 function getLangObj() {
3924 return $this;
3925 }
3926
3927 /**
3928 * Get the RFC 3066 code for this language object
3929 *
3930 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3931 * htmlspecialchars() or similar
3932 *
3933 * @return string
3934 */
3935 public function getCode() {
3936 return $this->mCode;
3937 }
3938
3939 /**
3940 * Get the code in Bcp47 format which we can use
3941 * inside of html lang="" tags.
3942 *
3943 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3944 * htmlspecialchars() or similar.
3945 *
3946 * @since 1.19
3947 * @return string
3948 */
3949 public function getHtmlCode() {
3950 if ( is_null( $this->mHtmlCode ) ) {
3951 $this->mHtmlCode = wfBCP47( $this->getCode() );
3952 }
3953 return $this->mHtmlCode;
3954 }
3955
3956 /**
3957 * @param $code string
3958 */
3959 public function setCode( $code ) {
3960 $this->mCode = $code;
3961 // Ensure we don't leave an incorrect html code lying around
3962 $this->mHtmlCode = null;
3963 }
3964
3965 /**
3966 * Get the name of a file for a certain language code
3967 * @param $prefix string Prepend this to the filename
3968 * @param $code string Language code
3969 * @param $suffix string Append this to the filename
3970 * @throws MWException
3971 * @return string $prefix . $mangledCode . $suffix
3972 */
3973 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3974 // Protect against path traversal
3975 if ( !Language::isValidCode( $code )
3976 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3977 {
3978 throw new MWException( "Invalid language code \"$code\"" );
3979 }
3980
3981 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3982 }
3983
3984 /**
3985 * Get the language code from a file name. Inverse of getFileName()
3986 * @param $filename string $prefix . $languageCode . $suffix
3987 * @param $prefix string Prefix before the language code
3988 * @param $suffix string Suffix after the language code
3989 * @return string Language code, or false if $prefix or $suffix isn't found
3990 */
3991 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3992 $m = null;
3993 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3994 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3995 if ( !count( $m ) ) {
3996 return false;
3997 }
3998 return str_replace( '_', '-', strtolower( $m[1] ) );
3999 }
4000
4001 /**
4002 * @param $code string
4003 * @return string
4004 */
4005 public static function getMessagesFileName( $code ) {
4006 global $IP;
4007 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
4008 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
4009 return $file;
4010 }
4011
4012 /**
4013 * @param $code string
4014 * @return string
4015 */
4016 public static function getClassFileName( $code ) {
4017 global $IP;
4018 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
4019 }
4020
4021 /**
4022 * Get the first fallback for a given language.
4023 *
4024 * @param $code string
4025 *
4026 * @return bool|string
4027 */
4028 public static function getFallbackFor( $code ) {
4029 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4030 return false;
4031 } else {
4032 $fallbacks = self::getFallbacksFor( $code );
4033 $first = array_shift( $fallbacks );
4034 return $first;
4035 }
4036 }
4037
4038 /**
4039 * Get the ordered list of fallback languages.
4040 *
4041 * @since 1.19
4042 * @param $code string Language code
4043 * @return array
4044 */
4045 public static function getFallbacksFor( $code ) {
4046 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
4047 return array();
4048 } else {
4049 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
4050 $v = array_map( 'trim', explode( ',', $v ) );
4051 if ( $v[count( $v ) - 1] !== 'en' ) {
4052 $v[] = 'en';
4053 }
4054 return $v;
4055 }
4056 }
4057
4058 /**
4059 * Get all messages for a given language
4060 * WARNING: this may take a long time. If you just need all message *keys*
4061 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
4062 *
4063 * @param $code string
4064 *
4065 * @return array
4066 */
4067 public static function getMessagesFor( $code ) {
4068 return self::getLocalisationCache()->getItem( $code, 'messages' );
4069 }
4070
4071 /**
4072 * Get a message for a given language
4073 *
4074 * @param $key string
4075 * @param $code string
4076 *
4077 * @return string
4078 */
4079 public static function getMessageFor( $key, $code ) {
4080 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
4081 }
4082
4083 /**
4084 * Get all message keys for a given language. This is a faster alternative to
4085 * array_keys( Language::getMessagesFor( $code ) )
4086 *
4087 * @since 1.19
4088 * @param $code string Language code
4089 * @return array of message keys (strings)
4090 */
4091 public static function getMessageKeysFor( $code ) {
4092 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
4093 }
4094
4095 /**
4096 * @param $talk
4097 * @return mixed
4098 */
4099 function fixVariableInNamespace( $talk ) {
4100 if ( strpos( $talk, '$1' ) === false ) {
4101 return $talk;
4102 }
4103
4104 global $wgMetaNamespace;
4105 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
4106
4107 # Allow grammar transformations
4108 # Allowing full message-style parsing would make simple requests
4109 # such as action=raw much more expensive than they need to be.
4110 # This will hopefully cover most cases.
4111 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
4112 array( &$this, 'replaceGrammarInNamespace' ), $talk );
4113 return str_replace( ' ', '_', $talk );
4114 }
4115
4116 /**
4117 * @param $m string
4118 * @return string
4119 */
4120 function replaceGrammarInNamespace( $m ) {
4121 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
4122 }
4123
4124 /**
4125 * @throws MWException
4126 * @return array
4127 */
4128 static function getCaseMaps() {
4129 static $wikiUpperChars, $wikiLowerChars;
4130 if ( isset( $wikiUpperChars ) ) {
4131 return array( $wikiUpperChars, $wikiLowerChars );
4132 }
4133
4134 wfProfileIn( __METHOD__ );
4135 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
4136 if ( $arr === false ) {
4137 throw new MWException(
4138 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
4139 }
4140 $wikiUpperChars = $arr['wikiUpperChars'];
4141 $wikiLowerChars = $arr['wikiLowerChars'];
4142 wfProfileOut( __METHOD__ );
4143 return array( $wikiUpperChars, $wikiLowerChars );
4144 }
4145
4146 /**
4147 * Decode an expiry (block, protection, etc) which has come from the DB
4148 *
4149 * @todo FIXME: why are we returnings DBMS-dependent strings???
4150 *
4151 * @param $expiry String: Database expiry String
4152 * @param $format Bool|Int true to process using language functions, or TS_ constant
4153 * to return the expiry in a given timestamp
4154 * @return String
4155 * @since 1.18
4156 */
4157 public function formatExpiry( $expiry, $format = true ) {
4158 static $infinity;
4159 if ( $infinity === null ) {
4160 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
4161 }
4162
4163 if ( $expiry == '' || $expiry == $infinity ) {
4164 return $format === true
4165 ? $this->getMessageFromDB( 'infiniteblock' )
4166 : $infinity;
4167 } else {
4168 return $format === true
4169 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
4170 : wfTimestamp( $format, $expiry );
4171 }
4172 }
4173
4174 /**
4175 * @todo Document
4176 * @param $seconds int|float
4177 * @param $format Array Optional
4178 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4179 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4180 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4181 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4182 * @return string
4183 */
4184 function formatTimePeriod( $seconds, $format = array() ) {
4185 if ( !is_array( $format ) ) {
4186 $format = array( 'avoid' => $format ); // For backwards compatibility
4187 }
4188 if ( !isset( $format['avoid'] ) ) {
4189 $format['avoid'] = false;
4190 }
4191 if ( !isset( $format['noabbrevs' ] ) ) {
4192 $format['noabbrevs'] = false;
4193 }
4194 $secondsMsg = wfMessage(
4195 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4196 $minutesMsg = wfMessage(
4197 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4198 $hoursMsg = wfMessage(
4199 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4200 $daysMsg = wfMessage(
4201 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4202
4203 if ( round( $seconds * 10 ) < 100 ) {
4204 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4205 $s = $secondsMsg->params( $s )->text();
4206 } elseif ( round( $seconds ) < 60 ) {
4207 $s = $this->formatNum( round( $seconds ) );
4208 $s = $secondsMsg->params( $s )->text();
4209 } elseif ( round( $seconds ) < 3600 ) {
4210 $minutes = floor( $seconds / 60 );
4211 $secondsPart = round( fmod( $seconds, 60 ) );
4212 if ( $secondsPart == 60 ) {
4213 $secondsPart = 0;
4214 $minutes++;
4215 }
4216 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4217 $s .= ' ';
4218 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4219 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4220 $hours = floor( $seconds / 3600 );
4221 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4222 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4223 if ( $secondsPart == 60 ) {
4224 $secondsPart = 0;
4225 $minutes++;
4226 }
4227 if ( $minutes == 60 ) {
4228 $minutes = 0;
4229 $hours++;
4230 }
4231 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4232 $s .= ' ';
4233 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4234 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4235 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4236 }
4237 } else {
4238 $days = floor( $seconds / 86400 );
4239 if ( $format['avoid'] === 'avoidminutes' ) {
4240 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4241 if ( $hours == 24 ) {
4242 $hours = 0;
4243 $days++;
4244 }
4245 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4246 $s .= ' ';
4247 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4248 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4249 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4250 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4251 if ( $minutes == 60 ) {
4252 $minutes = 0;
4253 $hours++;
4254 }
4255 if ( $hours == 24 ) {
4256 $hours = 0;
4257 $days++;
4258 }
4259 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4260 $s .= ' ';
4261 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4262 $s .= ' ';
4263 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4264 } else {
4265 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4266 $s .= ' ';
4267 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4268 }
4269 }
4270 return $s;
4271 }
4272
4273 /**
4274 * Format a bitrate for output, using an appropriate
4275 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4276 *
4277 * This use base 1000. For base 1024 use formatSize(), for another base
4278 * see formatComputingNumbers()
4279 *
4280 * @param $bps int
4281 * @return string
4282 */
4283 function formatBitrate( $bps ) {
4284 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4285 }
4286
4287 /**
4288 * @param $size int Size of the unit
4289 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4290 * @param $messageKey string Message key to be uesd
4291 * @return string
4292 */
4293 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4294 if ( $size <= 0 ) {
4295 return str_replace( '$1', $this->formatNum( $size ),
4296 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4297 );
4298 }
4299 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4300 $index = 0;
4301
4302 $maxIndex = count( $sizes ) - 1;
4303 while ( $size >= $boundary && $index < $maxIndex ) {
4304 $index++;
4305 $size /= $boundary;
4306 }
4307
4308 // For small sizes no decimal places necessary
4309 $round = 0;
4310 if ( $index > 1 ) {
4311 // For MB and bigger two decimal places are smarter
4312 $round = 2;
4313 }
4314 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4315
4316 $size = round( $size, $round );
4317 $text = $this->getMessageFromDB( $msg );
4318 return str_replace( '$1', $this->formatNum( $size ), $text );
4319 }
4320
4321 /**
4322 * Format a size in bytes for output, using an appropriate
4323 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4324 *
4325 * This method use base 1024. For base 1000 use formatBitrate(), for
4326 * another base see formatComputingNumbers()
4327 *
4328 * @param $size int Size to format
4329 * @return string Plain text (not HTML)
4330 */
4331 function formatSize( $size ) {
4332 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4333 }
4334
4335 /**
4336 * Make a list item, used by various special pages
4337 *
4338 * @param $page String Page link
4339 * @param $details String Text between brackets
4340 * @param $oppositedm Boolean Add the direction mark opposite to your
4341 * language, to display text properly
4342 * @return String
4343 */
4344 function specialList( $page, $details, $oppositedm = true ) {
4345 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4346 $this->getDirMark();
4347 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4348 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4349 return $page . $details;
4350 }
4351
4352 /**
4353 * Generate (prev x| next x) (20|50|100...) type links for paging
4354 *
4355 * @param $title Title object to link
4356 * @param $offset Integer offset parameter
4357 * @param $limit Integer limit parameter
4358 * @param $query array|String optional URL query parameter string
4359 * @param $atend Bool optional param for specified if this is the last page
4360 * @return String
4361 */
4362 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4363 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4364
4365 # Make 'previous' link
4366 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4367 if ( $offset > 0 ) {
4368 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4369 $query, $prev, 'prevn-title', 'mw-prevlink' );
4370 } else {
4371 $plink = htmlspecialchars( $prev );
4372 }
4373
4374 # Make 'next' link
4375 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4376 if ( $atend ) {
4377 $nlink = htmlspecialchars( $next );
4378 } else {
4379 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4380 $query, $next, 'prevn-title', 'mw-nextlink' );
4381 }
4382
4383 # Make links to set number of items per page
4384 $numLinks = array();
4385 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4386 $numLinks[] = $this->numLink( $title, $offset, $num,
4387 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4388 }
4389
4390 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4391 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4392 }
4393
4394 /**
4395 * Helper function for viewPrevNext() that generates links
4396 *
4397 * @param $title Title object to link
4398 * @param $offset Integer offset parameter
4399 * @param $limit Integer limit parameter
4400 * @param $query Array extra query parameters
4401 * @param $link String text to use for the link; will be escaped
4402 * @param $tooltipMsg String name of the message to use as tooltip
4403 * @param $class String value of the "class" attribute of the link
4404 * @return String HTML fragment
4405 */
4406 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4407 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4408 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4409 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4410 'title' => $tooltip, 'class' => $class ), $link );
4411 }
4412
4413 /**
4414 * Get the conversion rule title, if any.
4415 *
4416 * @return string
4417 */
4418 public function getConvRuleTitle() {
4419 return $this->mConverter->getConvRuleTitle();
4420 }
4421
4422 /**
4423 * Get the compiled plural rules for the language
4424 * @since 1.20
4425 * @return array Associative array with plural form, and plural rule as key-value pairs
4426 */
4427 public function getCompiledPluralRules() {
4428 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4429 $fallbacks = Language::getFallbacksFor( $this->mCode );
4430 if ( !$pluralRules ) {
4431 foreach ( $fallbacks as $fallbackCode ) {
4432 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4433 if ( $pluralRules ) {
4434 break;
4435 }
4436 }
4437 }
4438 return $pluralRules;
4439 }
4440
4441 /**
4442 * Get the plural rules for the language
4443 * @since 1.20
4444 * @return array Associative array with plural form number and plural rule as key-value pairs
4445 */
4446 public function getPluralRules() {
4447 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4448 $fallbacks = Language::getFallbacksFor( $this->mCode );
4449 if ( !$pluralRules ) {
4450 foreach ( $fallbacks as $fallbackCode ) {
4451 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4452 if ( $pluralRules ) {
4453 break;
4454 }
4455 }
4456 }
4457 return $pluralRules;
4458 }
4459
4460 /**
4461 * Get the plural rule types for the language
4462 * @since 1.21
4463 * @return array Associative array with plural form number and plural rule type as key-value pairs
4464 */
4465 public function getPluralRuleTypes() {
4466 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
4467 $fallbacks = Language::getFallbacksFor( $this->mCode );
4468 if ( !$pluralRuleTypes ) {
4469 foreach ( $fallbacks as $fallbackCode ) {
4470 $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
4471 if ( $pluralRuleTypes ) {
4472 break;
4473 }
4474 }
4475 }
4476 return $pluralRuleTypes;
4477 }
4478
4479 /**
4480 * Find the index number of the plural rule appropriate for the given number
4481 * @return int The index number of the plural rule
4482 */
4483 public function getPluralRuleIndexNumber( $number ) {
4484 $pluralRules = $this->getCompiledPluralRules();
4485 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4486 return $form;
4487 }
4488
4489 /**
4490 * Find the plural rule type appropriate for the given number
4491 * For example, if the language is set to Arabic, getPluralType(5) should
4492 * return 'few'.
4493 * @since 1.21
4494 * @return string The name of the plural rule type, e.g. one, two, few, many
4495 */
4496 public function getPluralRuleType( $number ) {
4497 $index = $this->getPluralRuleIndexNumber( $number );
4498 $pluralRuleTypes = $this->getPluralRuleTypes();
4499 if ( isset( $pluralRuleTypes[$index] ) ) {
4500 return $pluralRuleTypes[$index];
4501 } else {
4502 return 'other';
4503 }
4504 }
4505 }