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