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