Merge "[JobQueue] Pushed stats down to job queue subclasses."
[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 = new Message( 'duration-' . $intervalName, array( $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 # Check for non-UTF-8 URLs
2429 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2430 if ( !$ishigh ) {
2431 return $s;
2432 }
2433
2434 if ( function_exists( 'mb_check_encoding' ) ) {
2435 $isutf8 = mb_check_encoding( $s, 'UTF-8' );
2436 } else {
2437 $isutf8 = preg_match( '/^(?>[\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2438 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2439 }
2440 if ( $isutf8 ) {
2441 return $s;
2442 }
2443
2444 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2445 }
2446
2447 /**
2448 * @return array
2449 */
2450 function fallback8bitEncoding() {
2451 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2452 }
2453
2454 /**
2455 * Most writing systems use whitespace to break up words.
2456 * Some languages such as Chinese don't conventionally do this,
2457 * which requires special handling when breaking up words for
2458 * searching etc.
2459 *
2460 * @return bool
2461 */
2462 function hasWordBreaks() {
2463 return true;
2464 }
2465
2466 /**
2467 * Some languages such as Chinese require word segmentation,
2468 * Specify such segmentation when overridden in derived class.
2469 *
2470 * @param $string String
2471 * @return String
2472 */
2473 function segmentByWord( $string ) {
2474 return $string;
2475 }
2476
2477 /**
2478 * Some languages have special punctuation need to be normalized.
2479 * Make such changes here.
2480 *
2481 * @param $string String
2482 * @return String
2483 */
2484 function normalizeForSearch( $string ) {
2485 return self::convertDoubleWidth( $string );
2486 }
2487
2488 /**
2489 * convert double-width roman characters to single-width.
2490 * range: ff00-ff5f ~= 0020-007f
2491 *
2492 * @param $string string
2493 *
2494 * @return string
2495 */
2496 protected static function convertDoubleWidth( $string ) {
2497 static $full = null;
2498 static $half = null;
2499
2500 if ( $full === null ) {
2501 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2502 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2503 $full = str_split( $fullWidth, 3 );
2504 $half = str_split( $halfWidth );
2505 }
2506
2507 $string = str_replace( $full, $half, $string );
2508 return $string;
2509 }
2510
2511 /**
2512 * @param $string string
2513 * @param $pattern string
2514 * @return string
2515 */
2516 protected static function insertSpace( $string, $pattern ) {
2517 $string = preg_replace( $pattern, " $1 ", $string );
2518 $string = preg_replace( '/ +/', ' ', $string );
2519 return $string;
2520 }
2521
2522 /**
2523 * @param $termsArray array
2524 * @return array
2525 */
2526 function convertForSearchResult( $termsArray ) {
2527 # some languages, e.g. Chinese, need to do a conversion
2528 # in order for search results to be displayed correctly
2529 return $termsArray;
2530 }
2531
2532 /**
2533 * Get the first character of a string.
2534 *
2535 * @param $s string
2536 * @return string
2537 */
2538 function firstChar( $s ) {
2539 $matches = array();
2540 preg_match(
2541 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2542 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2543 $s,
2544 $matches
2545 );
2546
2547 if ( isset( $matches[1] ) ) {
2548 if ( strlen( $matches[1] ) != 3 ) {
2549 return $matches[1];
2550 }
2551
2552 // Break down Hangul syllables to grab the first jamo
2553 $code = utf8ToCodepoint( $matches[1] );
2554 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2555 return $matches[1];
2556 } elseif ( $code < 0xb098 ) {
2557 return "\xe3\x84\xb1";
2558 } elseif ( $code < 0xb2e4 ) {
2559 return "\xe3\x84\xb4";
2560 } elseif ( $code < 0xb77c ) {
2561 return "\xe3\x84\xb7";
2562 } elseif ( $code < 0xb9c8 ) {
2563 return "\xe3\x84\xb9";
2564 } elseif ( $code < 0xbc14 ) {
2565 return "\xe3\x85\x81";
2566 } elseif ( $code < 0xc0ac ) {
2567 return "\xe3\x85\x82";
2568 } elseif ( $code < 0xc544 ) {
2569 return "\xe3\x85\x85";
2570 } elseif ( $code < 0xc790 ) {
2571 return "\xe3\x85\x87";
2572 } elseif ( $code < 0xcc28 ) {
2573 return "\xe3\x85\x88";
2574 } elseif ( $code < 0xce74 ) {
2575 return "\xe3\x85\x8a";
2576 } elseif ( $code < 0xd0c0 ) {
2577 return "\xe3\x85\x8b";
2578 } elseif ( $code < 0xd30c ) {
2579 return "\xe3\x85\x8c";
2580 } elseif ( $code < 0xd558 ) {
2581 return "\xe3\x85\x8d";
2582 } else {
2583 return "\xe3\x85\x8e";
2584 }
2585 } else {
2586 return '';
2587 }
2588 }
2589
2590 function initEncoding() {
2591 # Some languages may have an alternate char encoding option
2592 # (Esperanto X-coding, Japanese furigana conversion, etc)
2593 # If this language is used as the primary content language,
2594 # an override to the defaults can be set here on startup.
2595 }
2596
2597 /**
2598 * @param $s string
2599 * @return string
2600 */
2601 function recodeForEdit( $s ) {
2602 # For some languages we'll want to explicitly specify
2603 # which characters make it into the edit box raw
2604 # or are converted in some way or another.
2605 global $wgEditEncoding;
2606 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2607 return $s;
2608 } else {
2609 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2610 }
2611 }
2612
2613 /**
2614 * @param $s string
2615 * @return string
2616 */
2617 function recodeInput( $s ) {
2618 # Take the previous into account.
2619 global $wgEditEncoding;
2620 if ( $wgEditEncoding != '' ) {
2621 $enc = $wgEditEncoding;
2622 } else {
2623 $enc = 'UTF-8';
2624 }
2625 if ( $enc == 'UTF-8' ) {
2626 return $s;
2627 } else {
2628 return $this->iconv( $enc, 'UTF-8', $s );
2629 }
2630 }
2631
2632 /**
2633 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2634 * also cleans up certain backwards-compatible sequences, converting them
2635 * to the modern Unicode equivalent.
2636 *
2637 * This is language-specific for performance reasons only.
2638 *
2639 * @param $s string
2640 *
2641 * @return string
2642 */
2643 function normalize( $s ) {
2644 global $wgAllUnicodeFixes;
2645 $s = UtfNormal::cleanUp( $s );
2646 if ( $wgAllUnicodeFixes ) {
2647 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2648 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2649 }
2650
2651 return $s;
2652 }
2653
2654 /**
2655 * Transform a string using serialized data stored in the given file (which
2656 * must be in the serialized subdirectory of $IP). The file contains pairs
2657 * mapping source characters to destination characters.
2658 *
2659 * The data is cached in process memory. This will go faster if you have the
2660 * FastStringSearch extension.
2661 *
2662 * @param $file string
2663 * @param $string string
2664 *
2665 * @throws MWException
2666 * @return string
2667 */
2668 function transformUsingPairFile( $file, $string ) {
2669 if ( !isset( $this->transformData[$file] ) ) {
2670 $data = wfGetPrecompiledData( $file );
2671 if ( $data === false ) {
2672 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2673 }
2674 $this->transformData[$file] = new ReplacementArray( $data );
2675 }
2676 return $this->transformData[$file]->replace( $string );
2677 }
2678
2679 /**
2680 * For right-to-left language support
2681 *
2682 * @return bool
2683 */
2684 function isRTL() {
2685 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2686 }
2687
2688 /**
2689 * Return the correct HTML 'dir' attribute value for this language.
2690 * @return String
2691 */
2692 function getDir() {
2693 return $this->isRTL() ? 'rtl' : 'ltr';
2694 }
2695
2696 /**
2697 * Return 'left' or 'right' as appropriate alignment for line-start
2698 * for this language's text direction.
2699 *
2700 * Should be equivalent to CSS3 'start' text-align value....
2701 *
2702 * @return String
2703 */
2704 function alignStart() {
2705 return $this->isRTL() ? 'right' : 'left';
2706 }
2707
2708 /**
2709 * Return 'right' or 'left' as appropriate alignment for line-end
2710 * for this language's text direction.
2711 *
2712 * Should be equivalent to CSS3 'end' text-align value....
2713 *
2714 * @return String
2715 */
2716 function alignEnd() {
2717 return $this->isRTL() ? 'left' : 'right';
2718 }
2719
2720 /**
2721 * A hidden direction mark (LRM or RLM), depending on the language direction.
2722 * Unlike getDirMark(), this function returns the character as an HTML entity.
2723 * This function should be used when the output is guaranteed to be HTML,
2724 * because it makes the output HTML source code more readable. When
2725 * the output is plain text or can be escaped, getDirMark() should be used.
2726 *
2727 * @param $opposite Boolean Get the direction mark opposite to your language
2728 * @return string
2729 * @since 1.20
2730 */
2731 function getDirMarkEntity( $opposite = false ) {
2732 if ( $opposite ) { return $this->isRTL() ? '&lrm;' : '&rlm;'; }
2733 return $this->isRTL() ? '&rlm;' : '&lrm;';
2734 }
2735
2736 /**
2737 * A hidden direction mark (LRM or RLM), depending on the language direction.
2738 * This function produces them as invisible Unicode characters and
2739 * the output may be hard to read and debug, so it should only be used
2740 * when the output is plain text or can be escaped. When the output is
2741 * HTML, use getDirMarkEntity() instead.
2742 *
2743 * @param $opposite Boolean Get the direction mark opposite to your language
2744 * @return string
2745 */
2746 function getDirMark( $opposite = false ) {
2747 $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
2748 $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
2749 if ( $opposite ) { return $this->isRTL() ? $lrm : $rlm; }
2750 return $this->isRTL() ? $rlm : $lrm;
2751 }
2752
2753 /**
2754 * @return array
2755 */
2756 function capitalizeAllNouns() {
2757 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2758 }
2759
2760 /**
2761 * An arrow, depending on the language direction.
2762 *
2763 * @param $direction String: the direction of the arrow: forwards (default), backwards, left, right, up, down.
2764 * @return string
2765 */
2766 function getArrow( $direction = 'forwards' ) {
2767 switch ( $direction ) {
2768 case 'forwards':
2769 return $this->isRTL() ? '←' : '→';
2770 case 'backwards':
2771 return $this->isRTL() ? '→' : '←';
2772 case 'left':
2773 return '←';
2774 case 'right':
2775 return '→';
2776 case 'up':
2777 return '↑';
2778 case 'down':
2779 return '↓';
2780 }
2781 }
2782
2783 /**
2784 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2785 *
2786 * @return bool
2787 */
2788 function linkPrefixExtension() {
2789 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2790 }
2791
2792 /**
2793 * @return array
2794 */
2795 function getMagicWords() {
2796 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2797 }
2798
2799 protected function doMagicHook() {
2800 if ( $this->mMagicHookDone ) {
2801 return;
2802 }
2803 $this->mMagicHookDone = true;
2804 wfProfileIn( 'LanguageGetMagic' );
2805 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2806 wfProfileOut( 'LanguageGetMagic' );
2807 }
2808
2809 /**
2810 * Fill a MagicWord object with data from here
2811 *
2812 * @param $mw
2813 */
2814 function getMagic( $mw ) {
2815 $this->doMagicHook();
2816
2817 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2818 $rawEntry = $this->mMagicExtensions[$mw->mId];
2819 } else {
2820 $magicWords = $this->getMagicWords();
2821 if ( isset( $magicWords[$mw->mId] ) ) {
2822 $rawEntry = $magicWords[$mw->mId];
2823 } else {
2824 $rawEntry = false;
2825 }
2826 }
2827
2828 if ( !is_array( $rawEntry ) ) {
2829 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2830 } else {
2831 $mw->mCaseSensitive = $rawEntry[0];
2832 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2833 }
2834 }
2835
2836 /**
2837 * Add magic words to the extension array
2838 *
2839 * @param $newWords array
2840 */
2841 function addMagicWordsByLang( $newWords ) {
2842 $fallbackChain = $this->getFallbackLanguages();
2843 $fallbackChain = array_reverse( $fallbackChain );
2844 foreach ( $fallbackChain as $code ) {
2845 if ( isset( $newWords[$code] ) ) {
2846 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2847 }
2848 }
2849 }
2850
2851 /**
2852 * Get special page names, as an associative array
2853 * case folded alias => real name
2854 */
2855 function getSpecialPageAliases() {
2856 // Cache aliases because it may be slow to load them
2857 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2858 // Initialise array
2859 $this->mExtendedSpecialPageAliases =
2860 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2861 wfRunHooks( 'LanguageGetSpecialPageAliases',
2862 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2863 }
2864
2865 return $this->mExtendedSpecialPageAliases;
2866 }
2867
2868 /**
2869 * Italic is unsuitable for some languages
2870 *
2871 * @param $text String: the text to be emphasized.
2872 * @return string
2873 */
2874 function emphasize( $text ) {
2875 return "<em>$text</em>";
2876 }
2877
2878 /**
2879 * Normally we output all numbers in plain en_US style, that is
2880 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2881 * point twohundredthirtyfive. However this is not suitable for all
2882 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2883 * Icelandic just want to use commas instead of dots, and dots instead
2884 * of commas like "293.291,235".
2885 *
2886 * An example of this function being called:
2887 * <code>
2888 * wfMessage( 'message' )->numParams( $num )->text()
2889 * </code>
2890 *
2891 * See LanguageGu.php for the Gujarati implementation and
2892 * $separatorTransformTable on MessageIs.php for
2893 * the , => . and . => , implementation.
2894 *
2895 * @todo check if it's viable to use localeconv() for the decimal
2896 * separator thing.
2897 * @param $number Mixed: the string to be formatted, should be an integer
2898 * or a floating point number.
2899 * @param $nocommafy Bool: set to true for special numbers like dates
2900 * @return string
2901 */
2902 public function formatNum( $number, $nocommafy = false ) {
2903 global $wgTranslateNumerals;
2904 if ( !$nocommafy ) {
2905 $number = $this->commafy( $number );
2906 $s = $this->separatorTransformTable();
2907 if ( $s ) {
2908 $number = strtr( $number, $s );
2909 }
2910 }
2911
2912 if ( $wgTranslateNumerals ) {
2913 $s = $this->digitTransformTable();
2914 if ( $s ) {
2915 $number = strtr( $number, $s );
2916 }
2917 }
2918
2919 return $number;
2920 }
2921
2922 /**
2923 * @param $number string
2924 * @return string
2925 */
2926 function parseFormattedNumber( $number ) {
2927 $s = $this->digitTransformTable();
2928 if ( $s ) {
2929 $number = strtr( $number, array_flip( $s ) );
2930 }
2931
2932 $s = $this->separatorTransformTable();
2933 if ( $s ) {
2934 $number = strtr( $number, array_flip( $s ) );
2935 }
2936
2937 $number = strtr( $number, array( ',' => '' ) );
2938 return $number;
2939 }
2940
2941 /**
2942 * Adds commas to a given number
2943 * @since 1.19
2944 * @param $_ mixed
2945 * @return string
2946 */
2947 function commafy( $_ ) {
2948 $digitGroupingPattern = $this->digitGroupingPattern();
2949 if ( $_ === null ) {
2950 return '';
2951 }
2952
2953 if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
2954 // default grouping is at thousands, use the same for ###,###,### pattern too.
2955 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2956 } else {
2957 // Ref: http://cldr.unicode.org/translation/number-patterns
2958 $sign = "";
2959 if ( intval( $_ ) < 0 ) {
2960 // For negative numbers apply the algorithm like positive number and add sign.
2961 $sign = "-";
2962 $_ = substr( $_, 1 );
2963 }
2964 $numberpart = array();
2965 $decimalpart = array();
2966 $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
2967 preg_match( "/\d+/", $_, $numberpart );
2968 preg_match( "/\.\d*/", $_, $decimalpart );
2969 $groupedNumber = ( count( $decimalpart ) > 0 ) ? $decimalpart[0]:"";
2970 if ( $groupedNumber === $_ ) {
2971 // the string does not have any number part. Eg: .12345
2972 return $sign . $groupedNumber;
2973 }
2974 $start = $end = strlen( $numberpart[0] );
2975 while ( $start > 0 ) {
2976 $match = $matches[0][$numMatches -1] ;
2977 $matchLen = strlen( $match );
2978 $start = $end - $matchLen;
2979 if ( $start < 0 ) {
2980 $start = 0;
2981 }
2982 $groupedNumber = substr( $_ , $start, $end -$start ) . $groupedNumber ;
2983 $end = $start;
2984 if ( $numMatches > 1 ) {
2985 // use the last pattern for the rest of the number
2986 $numMatches--;
2987 }
2988 if ( $start > 0 ) {
2989 $groupedNumber = "," . $groupedNumber;
2990 }
2991 }
2992 return $sign . $groupedNumber;
2993 }
2994 }
2995 /**
2996 * @return String
2997 */
2998 function digitGroupingPattern() {
2999 return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
3000 }
3001
3002 /**
3003 * @return array
3004 */
3005 function digitTransformTable() {
3006 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
3007 }
3008
3009 /**
3010 * @return array
3011 */
3012 function separatorTransformTable() {
3013 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
3014 }
3015
3016 /**
3017 * Take a list of strings and build a locale-friendly comma-separated
3018 * list, using the local comma-separator message.
3019 * The last two strings are chained with an "and".
3020 * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
3021 *
3022 * @param $l Array
3023 * @return string
3024 */
3025 function listToText( array $l ) {
3026 $s = '';
3027 $m = count( $l ) - 1;
3028
3029 if ( $m === 0 ) {
3030 return $l[0];
3031 } elseif ( $m === 1 ) {
3032 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
3033 } else {
3034 for ( $i = $m; $i >= 0; $i-- ) {
3035 if ( $i == $m ) {
3036 $s = $l[$i];
3037 } elseif ( $i == $m - 1 ) {
3038 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
3039 } else {
3040 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
3041 }
3042 }
3043 return $s;
3044 }
3045 }
3046
3047 /**
3048 * Take a list of strings and build a locale-friendly comma-separated
3049 * list, using the local comma-separator message.
3050 * @param $list array of strings to put in a comma list
3051 * @return string
3052 */
3053 function commaList( array $list ) {
3054 return implode(
3055 wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
3056 $list
3057 );
3058 }
3059
3060 /**
3061 * Take a list of strings and build a locale-friendly semicolon-separated
3062 * list, using the local semicolon-separator message.
3063 * @param $list array of strings to put in a semicolon list
3064 * @return string
3065 */
3066 function semicolonList( array $list ) {
3067 return implode(
3068 wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
3069 $list
3070 );
3071 }
3072
3073 /**
3074 * Same as commaList, but separate it with the pipe instead.
3075 * @param $list array of strings to put in a pipe list
3076 * @return string
3077 */
3078 function pipeList( array $list ) {
3079 return implode(
3080 wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
3081 $list
3082 );
3083 }
3084
3085 /**
3086 * Truncate a string to a specified length in bytes, appending an optional
3087 * string (e.g. for ellipses)
3088 *
3089 * The database offers limited byte lengths for some columns in the database;
3090 * multi-byte character sets mean we need to ensure that only whole characters
3091 * are included, otherwise broken characters can be passed to the user
3092 *
3093 * If $length is negative, the string will be truncated from the beginning
3094 *
3095 * @param $string String to truncate
3096 * @param $length Int: maximum length (including ellipses)
3097 * @param $ellipsis String to append to the truncated text
3098 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
3099 * $adjustLength was introduced in 1.18, before that behaved as if false.
3100 * @return string
3101 */
3102 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
3103 # Use the localized ellipsis character
3104 if ( $ellipsis == '...' ) {
3105 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3106 }
3107 # Check if there is no need to truncate
3108 if ( $length == 0 ) {
3109 return $ellipsis; // convention
3110 } elseif ( strlen( $string ) <= abs( $length ) ) {
3111 return $string; // no need to truncate
3112 }
3113 $stringOriginal = $string;
3114 # If ellipsis length is >= $length then we can't apply $adjustLength
3115 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
3116 $string = $ellipsis; // this can be slightly unexpected
3117 # Otherwise, truncate and add ellipsis...
3118 } else {
3119 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
3120 if ( $length > 0 ) {
3121 $length -= $eLength;
3122 $string = substr( $string, 0, $length ); // xyz...
3123 $string = $this->removeBadCharLast( $string );
3124 $string = $string . $ellipsis;
3125 } else {
3126 $length += $eLength;
3127 $string = substr( $string, $length ); // ...xyz
3128 $string = $this->removeBadCharFirst( $string );
3129 $string = $ellipsis . $string;
3130 }
3131 }
3132 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
3133 # This check is *not* redundant if $adjustLength, due to the single case where
3134 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
3135 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
3136 return $string;
3137 } else {
3138 return $stringOriginal;
3139 }
3140 }
3141
3142 /**
3143 * Remove bytes that represent an incomplete Unicode character
3144 * at the end of string (e.g. bytes of the char are missing)
3145 *
3146 * @param $string String
3147 * @return string
3148 */
3149 protected function removeBadCharLast( $string ) {
3150 if ( $string != '' ) {
3151 $char = ord( $string[strlen( $string ) - 1] );
3152 $m = array();
3153 if ( $char >= 0xc0 ) {
3154 # We got the first byte only of a multibyte char; remove it.
3155 $string = substr( $string, 0, -1 );
3156 } elseif ( $char >= 0x80 &&
3157 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
3158 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
3159 {
3160 # We chopped in the middle of a character; remove it
3161 $string = $m[1];
3162 }
3163 }
3164 return $string;
3165 }
3166
3167 /**
3168 * Remove bytes that represent an incomplete Unicode character
3169 * at the start of string (e.g. bytes of the char are missing)
3170 *
3171 * @param $string String
3172 * @return string
3173 */
3174 protected function removeBadCharFirst( $string ) {
3175 if ( $string != '' ) {
3176 $char = ord( $string[0] );
3177 if ( $char >= 0x80 && $char < 0xc0 ) {
3178 # We chopped in the middle of a character; remove the whole thing
3179 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
3180 }
3181 }
3182 return $string;
3183 }
3184
3185 /**
3186 * Truncate a string of valid HTML to a specified length in bytes,
3187 * appending an optional string (e.g. for ellipses), and return valid HTML
3188 *
3189 * This is only intended for styled/linked text, such as HTML with
3190 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
3191 * Also, this will not detect things like "display:none" CSS.
3192 *
3193 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
3194 *
3195 * @param string $text HTML string to truncate
3196 * @param int $length (zero/positive) Maximum length (including ellipses)
3197 * @param string $ellipsis String to append to the truncated text
3198 * @return string
3199 */
3200 function truncateHtml( $text, $length, $ellipsis = '...' ) {
3201 # Use the localized ellipsis character
3202 if ( $ellipsis == '...' ) {
3203 $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
3204 }
3205 # Check if there is clearly no need to truncate
3206 if ( $length <= 0 ) {
3207 return $ellipsis; // no text shown, nothing to format (convention)
3208 } elseif ( strlen( $text ) <= $length ) {
3209 return $text; // string short enough even *with* HTML (short-circuit)
3210 }
3211
3212 $dispLen = 0; // innerHTML legth so far
3213 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
3214 $tagType = 0; // 0-open, 1-close
3215 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
3216 $entityState = 0; // 0-not entity, 1-entity
3217 $tag = $ret = ''; // accumulated tag name, accumulated result string
3218 $openTags = array(); // open tag stack
3219 $maybeState = null; // possible truncation state
3220
3221 $textLen = strlen( $text );
3222 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
3223 for ( $pos = 0; true; ++$pos ) {
3224 # Consider truncation once the display length has reached the maximim.
3225 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
3226 # Check that we're not in the middle of a bracket/entity...
3227 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
3228 if ( !$testingEllipsis ) {
3229 $testingEllipsis = true;
3230 # Save where we are; we will truncate here unless there turn out to
3231 # be so few remaining characters that truncation is not necessary.
3232 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
3233 $maybeState = array( $ret, $openTags ); // save state
3234 }
3235 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
3236 # String in fact does need truncation, the truncation point was OK.
3237 list( $ret, $openTags ) = $maybeState; // reload state
3238 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
3239 $ret .= $ellipsis; // add ellipsis
3240 break;
3241 }
3242 }
3243 if ( $pos >= $textLen ) break; // extra iteration just for above checks
3244
3245 # Read the next char...
3246 $ch = $text[$pos];
3247 $lastCh = $pos ? $text[$pos - 1] : '';
3248 $ret .= $ch; // add to result string
3249 if ( $ch == '<' ) {
3250 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
3251 $entityState = 0; // for bad HTML
3252 $bracketState = 1; // tag started (checking for backslash)
3253 } elseif ( $ch == '>' ) {
3254 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
3255 $entityState = 0; // for bad HTML
3256 $bracketState = 0; // out of brackets
3257 } elseif ( $bracketState == 1 ) {
3258 if ( $ch == '/' ) {
3259 $tagType = 1; // close tag (e.g. "</span>")
3260 } else {
3261 $tagType = 0; // open tag (e.g. "<span>")
3262 $tag .= $ch;
3263 }
3264 $bracketState = 2; // building tag name
3265 } elseif ( $bracketState == 2 ) {
3266 if ( $ch != ' ' ) {
3267 $tag .= $ch;
3268 } else {
3269 // Name found (e.g. "<a href=..."), add on tag attributes...
3270 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
3271 }
3272 } elseif ( $bracketState == 0 ) {
3273 if ( $entityState ) {
3274 if ( $ch == ';' ) {
3275 $entityState = 0;
3276 $dispLen++; // entity is one displayed char
3277 }
3278 } else {
3279 if ( $neLength == 0 && !$maybeState ) {
3280 // Save state without $ch. We want to *hit* the first
3281 // display char (to get tags) but not *use* it if truncating.
3282 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
3283 }
3284 if ( $ch == '&' ) {
3285 $entityState = 1; // entity found, (e.g. "&#160;")
3286 } else {
3287 $dispLen++; // this char is displayed
3288 // Add the next $max display text chars after this in one swoop...
3289 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
3290 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
3291 $dispLen += $skipped;
3292 $pos += $skipped;
3293 }
3294 }
3295 }
3296 }
3297 // Close the last tag if left unclosed by bad HTML
3298 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
3299 while ( count( $openTags ) > 0 ) {
3300 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
3301 }
3302 return $ret;
3303 }
3304
3305 /**
3306 * truncateHtml() helper function
3307 * like strcspn() but adds the skipped chars to $ret
3308 *
3309 * @param $ret
3310 * @param $text
3311 * @param $search
3312 * @param $start
3313 * @param $len
3314 * @return int
3315 */
3316 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
3317 if ( $len === null ) {
3318 $len = -1; // -1 means "no limit" for strcspn
3319 } elseif ( $len < 0 ) {
3320 $len = 0; // sanity
3321 }
3322 $skipCount = 0;
3323 if ( $start < strlen( $text ) ) {
3324 $skipCount = strcspn( $text, $search, $start, $len );
3325 $ret .= substr( $text, $start, $skipCount );
3326 }
3327 return $skipCount;
3328 }
3329
3330 /**
3331 * truncateHtml() helper function
3332 * (a) push or pop $tag from $openTags as needed
3333 * (b) clear $tag value
3334 * @param &$tag string Current HTML tag name we are looking at
3335 * @param $tagType int (0-open tag, 1-close tag)
3336 * @param $lastCh string Character before the '>' that ended this tag
3337 * @param &$openTags array Open tag stack (not accounting for $tag)
3338 */
3339 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
3340 $tag = ltrim( $tag );
3341 if ( $tag != '' ) {
3342 if ( $tagType == 0 && $lastCh != '/' ) {
3343 $openTags[] = $tag; // tag opened (didn't close itself)
3344 } elseif ( $tagType == 1 ) {
3345 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
3346 array_pop( $openTags ); // tag closed
3347 }
3348 }
3349 $tag = '';
3350 }
3351 }
3352
3353 /**
3354 * Grammatical transformations, needed for inflected languages
3355 * Invoked by putting {{grammar:case|word}} in a message
3356 *
3357 * @param $word string
3358 * @param $case string
3359 * @return string
3360 */
3361 function convertGrammar( $word, $case ) {
3362 global $wgGrammarForms;
3363 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
3364 return $wgGrammarForms[$this->getCode()][$case][$word];
3365 }
3366 return $word;
3367 }
3368 /**
3369 * Get the grammar forms for the content language
3370 * @return array of grammar forms
3371 * @since 1.20
3372 */
3373 function getGrammarForms() {
3374 global $wgGrammarForms;
3375 if ( isset( $wgGrammarForms[$this->getCode()] ) && is_array( $wgGrammarForms[$this->getCode()] ) ) {
3376 return $wgGrammarForms[$this->getCode()];
3377 }
3378 return array();
3379 }
3380 /**
3381 * Provides an alternative text depending on specified gender.
3382 * Usage {{gender:username|masculine|feminine|neutral}}.
3383 * username is optional, in which case the gender of current user is used,
3384 * but only in (some) interface messages; otherwise default gender is used.
3385 *
3386 * If no forms are given, an empty string is returned. If only one form is
3387 * given, it will be returned unconditionally. These details are implied by
3388 * the caller and cannot be overridden in subclasses.
3389 *
3390 * If more than one form is given, the default is to use the neutral one
3391 * if it is specified, and to use the masculine one otherwise. These
3392 * details can be overridden in subclasses.
3393 *
3394 * @param $gender string
3395 * @param $forms array
3396 *
3397 * @return string
3398 */
3399 function gender( $gender, $forms ) {
3400 if ( !count( $forms ) ) {
3401 return '';
3402 }
3403 $forms = $this->preConvertPlural( $forms, 2 );
3404 if ( $gender === 'male' ) {
3405 return $forms[0];
3406 }
3407 if ( $gender === 'female' ) {
3408 return $forms[1];
3409 }
3410 return isset( $forms[2] ) ? $forms[2] : $forms[0];
3411 }
3412
3413 /**
3414 * Plural form transformations, needed for some languages.
3415 * For example, there are 3 form of plural in Russian and Polish,
3416 * depending on "count mod 10". See [[w:Plural]]
3417 * For English it is pretty simple.
3418 *
3419 * Invoked by putting {{plural:count|wordform1|wordform2}}
3420 * or {{plural:count|wordform1|wordform2|wordform3}}
3421 *
3422 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3423 *
3424 * @param $count Integer: non-localized number
3425 * @param $forms Array: different plural forms
3426 * @return string Correct form of plural for $count in this language
3427 */
3428 function convertPlural( $count, $forms ) {
3429 if ( !count( $forms ) ) {
3430 return '';
3431 }
3432
3433 // Handle explicit 0= and 1= forms
3434 foreach ( $forms as $index => $form ) {
3435 if ( isset( $form[1] ) && $form[1] === '=' ) {
3436 if ( $form[0] === (string) $count ) {
3437 return substr( $form, 2 );
3438 }
3439 unset( $forms[$index] );
3440 }
3441 }
3442 $forms = array_values( $forms );
3443
3444 $pluralForm = $this->getPluralForm( $count );
3445 $pluralForm = min( $pluralForm, count( $forms ) - 1 );
3446 return $forms[$pluralForm];
3447 }
3448
3449 /**
3450 * Checks that convertPlural was given an array and pads it to requested
3451 * amount of forms by copying the last one.
3452 *
3453 * @param $count Integer: How many forms should there be at least
3454 * @param $forms Array of forms given to convertPlural
3455 * @return array Padded array of forms or an exception if not an array
3456 */
3457 protected function preConvertPlural( /* Array */ $forms, $count ) {
3458 while ( count( $forms ) < $count ) {
3459 $forms[] = $forms[count( $forms ) - 1];
3460 }
3461 return $forms;
3462 }
3463
3464 /**
3465 * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
3466 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
3467 * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
3468 * on old expiry lengths recorded in log entries. You'd need to provide the start date to
3469 * match up with it.
3470 *
3471 * @param $str String: the validated block duration in English
3472 * @return string Somehow translated block duration
3473 * @see LanguageFi.php for example implementation
3474 */
3475 function translateBlockExpiry( $str ) {
3476 $duration = SpecialBlock::getSuggestedDurations( $this );
3477 foreach ( $duration as $show => $value ) {
3478 if ( strcmp( $str, $value ) == 0 ) {
3479 return htmlspecialchars( trim( $show ) );
3480 }
3481 }
3482
3483 // Since usually only infinite or indefinite is only on list, so try
3484 // equivalents if still here.
3485 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3486 if ( in_array( $str, $indefs ) ) {
3487 foreach ( $indefs as $val ) {
3488 $show = array_search( $val, $duration, true );
3489 if ( $show !== false ) {
3490 return htmlspecialchars( trim( $show ) );
3491 }
3492 }
3493 }
3494
3495 // If all else fails, return a standard duration or timestamp description.
3496 $time = strtotime( $str, 0 );
3497 if ( $time === false ) { // Unknown format. Return it as-is in case.
3498 return $str;
3499 } elseif ( $time !== strtotime( $str, 1 ) ) { // It's a relative timestamp.
3500 // $time is relative to 0 so it's a duration length.
3501 return $this->formatDuration( $time );
3502 } else { // It's an absolute timestamp.
3503 if ( $time === 0 ) {
3504 // wfTimestamp() handles 0 as current time instead of epoch.
3505 return $this->timeanddate( '19700101000000' );
3506 } else {
3507 return $this->timeanddate( $time );
3508 }
3509 }
3510 }
3511
3512 /**
3513 * languages like Chinese need to be segmented in order for the diff
3514 * to be of any use
3515 *
3516 * @param $text String
3517 * @return String
3518 */
3519 public function segmentForDiff( $text ) {
3520 return $text;
3521 }
3522
3523 /**
3524 * and unsegment to show the result
3525 *
3526 * @param $text String
3527 * @return String
3528 */
3529 public function unsegmentForDiff( $text ) {
3530 return $text;
3531 }
3532
3533 /**
3534 * Return the LanguageConverter used in the Language
3535 *
3536 * @since 1.19
3537 * @return LanguageConverter
3538 */
3539 public function getConverter() {
3540 return $this->mConverter;
3541 }
3542
3543 /**
3544 * convert text to all supported variants
3545 *
3546 * @param $text string
3547 * @return array
3548 */
3549 public function autoConvertToAllVariants( $text ) {
3550 return $this->mConverter->autoConvertToAllVariants( $text );
3551 }
3552
3553 /**
3554 * convert text to different variants of a language.
3555 *
3556 * @param $text string
3557 * @return string
3558 */
3559 public function convert( $text ) {
3560 return $this->mConverter->convert( $text );
3561 }
3562
3563 /**
3564 * Convert a Title object to a string in the preferred variant
3565 *
3566 * @param $title Title
3567 * @return string
3568 */
3569 public function convertTitle( $title ) {
3570 return $this->mConverter->convertTitle( $title );
3571 }
3572
3573 /**
3574 * Convert a namespace index to a string in the preferred variant
3575 *
3576 * @param $ns int
3577 * @return string
3578 */
3579 public function convertNamespace( $ns ) {
3580 return $this->mConverter->convertNamespace( $ns );
3581 }
3582
3583 /**
3584 * Check if this is a language with variants
3585 *
3586 * @return bool
3587 */
3588 public function hasVariants() {
3589 return sizeof( $this->getVariants() ) > 1;
3590 }
3591
3592 /**
3593 * Check if the language has the specific variant
3594 *
3595 * @since 1.19
3596 * @param $variant string
3597 * @return bool
3598 */
3599 public function hasVariant( $variant ) {
3600 return (bool)$this->mConverter->validateVariant( $variant );
3601 }
3602
3603 /**
3604 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3605 *
3606 * @param $text string
3607 * @return string
3608 */
3609 public function armourMath( $text ) {
3610 return $this->mConverter->armourMath( $text );
3611 }
3612
3613 /**
3614 * Perform output conversion on a string, and encode for safe HTML output.
3615 * @param $text String text to be converted
3616 * @param $isTitle Bool whether this conversion is for the article title
3617 * @return string
3618 * @todo this should get integrated somewhere sane
3619 */
3620 public function convertHtml( $text, $isTitle = false ) {
3621 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3622 }
3623
3624 /**
3625 * @param $key string
3626 * @return string
3627 */
3628 public function convertCategoryKey( $key ) {
3629 return $this->mConverter->convertCategoryKey( $key );
3630 }
3631
3632 /**
3633 * Get the list of variants supported by this language
3634 * see sample implementation in LanguageZh.php
3635 *
3636 * @return array an array of language codes
3637 */
3638 public function getVariants() {
3639 return $this->mConverter->getVariants();
3640 }
3641
3642 /**
3643 * @return string
3644 */
3645 public function getPreferredVariant() {
3646 return $this->mConverter->getPreferredVariant();
3647 }
3648
3649 /**
3650 * @return string
3651 */
3652 public function getDefaultVariant() {
3653 return $this->mConverter->getDefaultVariant();
3654 }
3655
3656 /**
3657 * @return string
3658 */
3659 public function getURLVariant() {
3660 return $this->mConverter->getURLVariant();
3661 }
3662
3663 /**
3664 * If a language supports multiple variants, it is
3665 * possible that non-existing link in one variant
3666 * actually exists in another variant. this function
3667 * tries to find it. See e.g. LanguageZh.php
3668 *
3669 * @param $link String: the name of the link
3670 * @param $nt Mixed: the title object of the link
3671 * @param $ignoreOtherCond Boolean: to disable other conditions when
3672 * we need to transclude a template or update a category's link
3673 * @return null the input parameters may be modified upon return
3674 */
3675 public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3676 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3677 }
3678
3679 /**
3680 * If a language supports multiple variants, converts text
3681 * into an array of all possible variants of the text:
3682 * 'variant' => text in that variant
3683 *
3684 * @deprecated since 1.17 Use autoConvertToAllVariants()
3685 *
3686 * @param $text string
3687 *
3688 * @return string
3689 */
3690 public function convertLinkToAllVariants( $text ) {
3691 return $this->mConverter->convertLinkToAllVariants( $text );
3692 }
3693
3694 /**
3695 * returns language specific options used by User::getPageRenderHash()
3696 * for example, the preferred language variant
3697 *
3698 * @return string
3699 */
3700 function getExtraHashOptions() {
3701 return $this->mConverter->getExtraHashOptions();
3702 }
3703
3704 /**
3705 * For languages that support multiple variants, the title of an
3706 * article may be displayed differently in different variants. this
3707 * function returns the apporiate title defined in the body of the article.
3708 *
3709 * @return string
3710 */
3711 public function getParsedTitle() {
3712 return $this->mConverter->getParsedTitle();
3713 }
3714
3715 /**
3716 * Prepare external link text for conversion. When the text is
3717 * a URL, it shouldn't be converted, and it'll be wrapped in
3718 * the "raw" tag (-{R| }-) to prevent conversion.
3719 *
3720 * This function is called "markNoConversion" for historical
3721 * reasons.
3722 *
3723 * @param $text String: text to be used for external link
3724 * @param $noParse bool: wrap it without confirming it's a real URL first
3725 * @return string the tagged text
3726 */
3727 public function markNoConversion( $text, $noParse = false ) {
3728 // Excluding protocal-relative URLs may avoid many false positives.
3729 if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
3730 return $this->mConverter->markNoConversion( $text );
3731 } else {
3732 return $text;
3733 }
3734 }
3735
3736 /**
3737 * A regular expression to match legal word-trailing characters
3738 * which should be merged onto a link of the form [[foo]]bar.
3739 *
3740 * @return string
3741 */
3742 public function linkTrail() {
3743 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3744 }
3745
3746 /**
3747 * @return Language
3748 */
3749 function getLangObj() {
3750 return $this;
3751 }
3752
3753 /**
3754 * Get the RFC 3066 code for this language object
3755 *
3756 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3757 * htmlspecialchars() or similar
3758 *
3759 * @return string
3760 */
3761 public function getCode() {
3762 return $this->mCode;
3763 }
3764
3765 /**
3766 * Get the code in Bcp47 format which we can use
3767 * inside of html lang="" tags.
3768 *
3769 * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
3770 * htmlspecialchars() or similar.
3771 *
3772 * @since 1.19
3773 * @return string
3774 */
3775 public function getHtmlCode() {
3776 if ( is_null( $this->mHtmlCode ) ) {
3777 $this->mHtmlCode = wfBCP47( $this->getCode() );
3778 }
3779 return $this->mHtmlCode;
3780 }
3781
3782 /**
3783 * @param $code string
3784 */
3785 public function setCode( $code ) {
3786 $this->mCode = $code;
3787 // Ensure we don't leave an incorrect html code lying around
3788 $this->mHtmlCode = null;
3789 }
3790
3791 /**
3792 * Get the name of a file for a certain language code
3793 * @param $prefix string Prepend this to the filename
3794 * @param $code string Language code
3795 * @param $suffix string Append this to the filename
3796 * @throws MWException
3797 * @return string $prefix . $mangledCode . $suffix
3798 */
3799 public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3800 // Protect against path traversal
3801 if ( !Language::isValidCode( $code )
3802 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3803 {
3804 throw new MWException( "Invalid language code \"$code\"" );
3805 }
3806
3807 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3808 }
3809
3810 /**
3811 * Get the language code from a file name. Inverse of getFileName()
3812 * @param $filename string $prefix . $languageCode . $suffix
3813 * @param $prefix string Prefix before the language code
3814 * @param $suffix string Suffix after the language code
3815 * @return string Language code, or false if $prefix or $suffix isn't found
3816 */
3817 public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3818 $m = null;
3819 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3820 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3821 if ( !count( $m ) ) {
3822 return false;
3823 }
3824 return str_replace( '_', '-', strtolower( $m[1] ) );
3825 }
3826
3827 /**
3828 * @param $code string
3829 * @return string
3830 */
3831 public static function getMessagesFileName( $code ) {
3832 global $IP;
3833 $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3834 wfRunHooks( 'Language::getMessagesFileName', array( $code, &$file ) );
3835 return $file;
3836 }
3837
3838 /**
3839 * @param $code string
3840 * @return string
3841 */
3842 public static function getClassFileName( $code ) {
3843 global $IP;
3844 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3845 }
3846
3847 /**
3848 * Get the first fallback for a given language.
3849 *
3850 * @param $code string
3851 *
3852 * @return bool|string
3853 */
3854 public static function getFallbackFor( $code ) {
3855 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3856 return false;
3857 } else {
3858 $fallbacks = self::getFallbacksFor( $code );
3859 $first = array_shift( $fallbacks );
3860 return $first;
3861 }
3862 }
3863
3864 /**
3865 * Get the ordered list of fallback languages.
3866 *
3867 * @since 1.19
3868 * @param $code string Language code
3869 * @return array
3870 */
3871 public static function getFallbacksFor( $code ) {
3872 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3873 return array();
3874 } else {
3875 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3876 $v = array_map( 'trim', explode( ',', $v ) );
3877 if ( $v[count( $v ) - 1] !== 'en' ) {
3878 $v[] = 'en';
3879 }
3880 return $v;
3881 }
3882 }
3883
3884 /**
3885 * Get all messages for a given language
3886 * WARNING: this may take a long time. If you just need all message *keys*
3887 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3888 *
3889 * @param $code string
3890 *
3891 * @return array
3892 */
3893 public static function getMessagesFor( $code ) {
3894 return self::getLocalisationCache()->getItem( $code, 'messages' );
3895 }
3896
3897 /**
3898 * Get a message for a given language
3899 *
3900 * @param $key string
3901 * @param $code string
3902 *
3903 * @return string
3904 */
3905 public static function getMessageFor( $key, $code ) {
3906 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3907 }
3908
3909 /**
3910 * Get all message keys for a given language. This is a faster alternative to
3911 * array_keys( Language::getMessagesFor( $code ) )
3912 *
3913 * @since 1.19
3914 * @param $code string Language code
3915 * @return array of message keys (strings)
3916 */
3917 public static function getMessageKeysFor( $code ) {
3918 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3919 }
3920
3921 /**
3922 * @param $talk
3923 * @return mixed
3924 */
3925 function fixVariableInNamespace( $talk ) {
3926 if ( strpos( $talk, '$1' ) === false ) {
3927 return $talk;
3928 }
3929
3930 global $wgMetaNamespace;
3931 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3932
3933 # Allow grammar transformations
3934 # Allowing full message-style parsing would make simple requests
3935 # such as action=raw much more expensive than they need to be.
3936 # This will hopefully cover most cases.
3937 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3938 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3939 return str_replace( ' ', '_', $talk );
3940 }
3941
3942 /**
3943 * @param $m string
3944 * @return string
3945 */
3946 function replaceGrammarInNamespace( $m ) {
3947 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3948 }
3949
3950 /**
3951 * @throws MWException
3952 * @return array
3953 */
3954 static function getCaseMaps() {
3955 static $wikiUpperChars, $wikiLowerChars;
3956 if ( isset( $wikiUpperChars ) ) {
3957 return array( $wikiUpperChars, $wikiLowerChars );
3958 }
3959
3960 wfProfileIn( __METHOD__ );
3961 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3962 if ( $arr === false ) {
3963 throw new MWException(
3964 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3965 }
3966 $wikiUpperChars = $arr['wikiUpperChars'];
3967 $wikiLowerChars = $arr['wikiLowerChars'];
3968 wfProfileOut( __METHOD__ );
3969 return array( $wikiUpperChars, $wikiLowerChars );
3970 }
3971
3972 /**
3973 * Decode an expiry (block, protection, etc) which has come from the DB
3974 *
3975 * @todo FIXME: why are we returnings DBMS-dependent strings???
3976 *
3977 * @param $expiry String: Database expiry String
3978 * @param $format Bool|Int true to process using language functions, or TS_ constant
3979 * to return the expiry in a given timestamp
3980 * @return String
3981 * @since 1.18
3982 */
3983 public function formatExpiry( $expiry, $format = true ) {
3984 static $infinity, $infinityMsg;
3985 if ( $infinity === null ) {
3986 $infinityMsg = wfMessage( 'infiniteblock' );
3987 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3988 }
3989
3990 if ( $expiry == '' || $expiry == $infinity ) {
3991 return $format === true
3992 ? $infinityMsg
3993 : $infinity;
3994 } else {
3995 return $format === true
3996 ? $this->timeanddate( $expiry, /* User preference timezone */ true )
3997 : wfTimestamp( $format, $expiry );
3998 }
3999 }
4000
4001 /**
4002 * @todo Document
4003 * @param $seconds int|float
4004 * @param $format Array Optional
4005 * If $format['avoid'] == 'avoidseconds' - don't mention seconds if $seconds >= 1 hour
4006 * If $format['avoid'] == 'avoidminutes' - don't mention seconds/minutes if $seconds > 48 hours
4007 * If $format['noabbrevs'] is true - use 'seconds' and friends instead of 'seconds-abbrev' and friends
4008 * For backwards compatibility, $format may also be one of the strings 'avoidseconds' or 'avoidminutes'
4009 * @return string
4010 */
4011 function formatTimePeriod( $seconds, $format = array() ) {
4012 if ( !is_array( $format ) ) {
4013 $format = array( 'avoid' => $format ); // For backwards compatibility
4014 }
4015 if ( !isset( $format['avoid'] ) ) {
4016 $format['avoid'] = false;
4017 }
4018 if ( !isset( $format['noabbrevs' ] ) ) {
4019 $format['noabbrevs'] = false;
4020 }
4021 $secondsMsg = wfMessage(
4022 $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
4023 $minutesMsg = wfMessage(
4024 $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
4025 $hoursMsg = wfMessage(
4026 $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
4027 $daysMsg = wfMessage(
4028 $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
4029
4030 if ( round( $seconds * 10 ) < 100 ) {
4031 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
4032 $s = $secondsMsg->params( $s )->text();
4033 } elseif ( round( $seconds ) < 60 ) {
4034 $s = $this->formatNum( round( $seconds ) );
4035 $s = $secondsMsg->params( $s )->text();
4036 } elseif ( round( $seconds ) < 3600 ) {
4037 $minutes = floor( $seconds / 60 );
4038 $secondsPart = round( fmod( $seconds, 60 ) );
4039 if ( $secondsPart == 60 ) {
4040 $secondsPart = 0;
4041 $minutes++;
4042 }
4043 $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4044 $s .= ' ';
4045 $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4046 } elseif ( round( $seconds ) <= 2 * 86400 ) {
4047 $hours = floor( $seconds / 3600 );
4048 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
4049 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
4050 if ( $secondsPart == 60 ) {
4051 $secondsPart = 0;
4052 $minutes++;
4053 }
4054 if ( $minutes == 60 ) {
4055 $minutes = 0;
4056 $hours++;
4057 }
4058 $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
4059 $s .= ' ';
4060 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4061 if ( !in_array( $format['avoid'], array( 'avoidseconds', 'avoidminutes' ) ) ) {
4062 $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
4063 }
4064 } else {
4065 $days = floor( $seconds / 86400 );
4066 if ( $format['avoid'] === 'avoidminutes' ) {
4067 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
4068 if ( $hours == 24 ) {
4069 $hours = 0;
4070 $days++;
4071 }
4072 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4073 $s .= ' ';
4074 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4075 } elseif ( $format['avoid'] === 'avoidseconds' ) {
4076 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
4077 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
4078 if ( $minutes == 60 ) {
4079 $minutes = 0;
4080 $hours++;
4081 }
4082 if ( $hours == 24 ) {
4083 $hours = 0;
4084 $days++;
4085 }
4086 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4087 $s .= ' ';
4088 $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
4089 $s .= ' ';
4090 $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
4091 } else {
4092 $s = $daysMsg->params( $this->formatNum( $days ) )->text();
4093 $s .= ' ';
4094 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
4095 }
4096 }
4097 return $s;
4098 }
4099
4100 /**
4101 * Format a bitrate for output, using an appropriate
4102 * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to the magnitude in question
4103 *
4104 * This use base 1000. For base 1024 use formatSize(), for another base
4105 * see formatComputingNumbers()
4106 *
4107 * @param $bps int
4108 * @return string
4109 */
4110 function formatBitrate( $bps ) {
4111 return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
4112 }
4113
4114 /**
4115 * @param $size int Size of the unit
4116 * @param $boundary int Size boundary (1000, or 1024 in most cases)
4117 * @param $messageKey string Message key to be uesd
4118 * @return string
4119 */
4120 function formatComputingNumbers( $size, $boundary, $messageKey ) {
4121 if ( $size <= 0 ) {
4122 return str_replace( '$1', $this->formatNum( $size ),
4123 $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
4124 );
4125 }
4126 $sizes = array( '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' );
4127 $index = 0;
4128
4129 $maxIndex = count( $sizes ) - 1;
4130 while ( $size >= $boundary && $index < $maxIndex ) {
4131 $index++;
4132 $size /= $boundary;
4133 }
4134
4135 // For small sizes no decimal places necessary
4136 $round = 0;
4137 if ( $index > 1 ) {
4138 // For MB and bigger two decimal places are smarter
4139 $round = 2;
4140 }
4141 $msg = str_replace( '$1', $sizes[$index], $messageKey );
4142
4143 $size = round( $size, $round );
4144 $text = $this->getMessageFromDB( $msg );
4145 return str_replace( '$1', $this->formatNum( $size ), $text );
4146 }
4147
4148 /**
4149 * Format a size in bytes for output, using an appropriate
4150 * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
4151 *
4152 * This method use base 1024. For base 1000 use formatBitrate(), for
4153 * another base see formatComputingNumbers()
4154 *
4155 * @param $size int Size to format
4156 * @return string Plain text (not HTML)
4157 */
4158 function formatSize( $size ) {
4159 return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
4160 }
4161
4162 /**
4163 * Make a list item, used by various special pages
4164 *
4165 * @param $page String Page link
4166 * @param $details String Text between brackets
4167 * @param $oppositedm Boolean Add the direction mark opposite to your
4168 * language, to display text properly
4169 * @return String
4170 */
4171 function specialList( $page, $details, $oppositedm = true ) {
4172 $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) .
4173 $this->getDirMark();
4174 $details = $details ? $dirmark . $this->getMessageFromDB( 'word-separator' ) .
4175 wfMessage( 'parentheses' )->rawParams( $details )->inLanguage( $this )->escaped() : '';
4176 return $page . $details;
4177 }
4178
4179 /**
4180 * Generate (prev x| next x) (20|50|100...) type links for paging
4181 *
4182 * @param $title Title object to link
4183 * @param $offset Integer offset parameter
4184 * @param $limit Integer limit parameter
4185 * @param $query array|String optional URL query parameter string
4186 * @param $atend Bool optional param for specified if this is the last page
4187 * @return String
4188 */
4189 public function viewPrevNext( Title $title, $offset, $limit, array $query = array(), $atend = false ) {
4190 // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
4191
4192 # Make 'previous' link
4193 $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4194 if ( $offset > 0 ) {
4195 $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
4196 $query, $prev, 'prevn-title', 'mw-prevlink' );
4197 } else {
4198 $plink = htmlspecialchars( $prev );
4199 }
4200
4201 # Make 'next' link
4202 $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4203 if ( $atend ) {
4204 $nlink = htmlspecialchars( $next );
4205 } else {
4206 $nlink = $this->numLink( $title, $offset + $limit, $limit,
4207 $query, $next, 'prevn-title', 'mw-nextlink' );
4208 }
4209
4210 # Make links to set number of items per page
4211 $numLinks = array();
4212 foreach ( array( 20, 50, 100, 250, 500 ) as $num ) {
4213 $numLinks[] = $this->numLink( $title, $offset, $num,
4214 $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
4215 }
4216
4217 return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
4218 )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
4219 }
4220
4221 /**
4222 * Helper function for viewPrevNext() that generates links
4223 *
4224 * @param $title Title object to link
4225 * @param $offset Integer offset parameter
4226 * @param $limit Integer limit parameter
4227 * @param $query Array extra query parameters
4228 * @param $link String text to use for the link; will be escaped
4229 * @param $tooltipMsg String name of the message to use as tooltip
4230 * @param $class String value of the "class" attribute of the link
4231 * @return String HTML fragment
4232 */
4233 private function numLink( Title $title, $offset, $limit, array $query, $link, $tooltipMsg, $class ) {
4234 $query = array( 'limit' => $limit, 'offset' => $offset ) + $query;
4235 $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
4236 return Html::element( 'a', array( 'href' => $title->getLocalURL( $query ),
4237 'title' => $tooltip, 'class' => $class ), $link );
4238 }
4239
4240 /**
4241 * Get the conversion rule title, if any.
4242 *
4243 * @return string
4244 */
4245 public function getConvRuleTitle() {
4246 return $this->mConverter->getConvRuleTitle();
4247 }
4248
4249 /**
4250 * Get the compiled plural rules for the language
4251 * @since 1.20
4252 * @return array Associative array with plural form, and plural rule as key-value pairs
4253 */
4254 public function getCompiledPluralRules() {
4255 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
4256 $fallbacks = Language::getFallbacksFor( $this->mCode );
4257 if ( !$pluralRules ) {
4258 foreach ( $fallbacks as $fallbackCode ) {
4259 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
4260 if ( $pluralRules ) {
4261 break;
4262 }
4263 }
4264 }
4265 return $pluralRules;
4266 }
4267
4268 /**
4269 * Get the plural rules for the language
4270 * @since 1.20
4271 * @return array Associative array with plural form, and plural rule as key-value pairs
4272 */
4273 public function getPluralRules() {
4274 $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
4275 $fallbacks = Language::getFallbacksFor( $this->mCode );
4276 if ( !$pluralRules ) {
4277 foreach ( $fallbacks as $fallbackCode ) {
4278 $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
4279 if ( $pluralRules ) {
4280 break;
4281 }
4282 }
4283 }
4284 return $pluralRules;
4285 }
4286
4287 /**
4288 * Find the plural form matching to the given number
4289 * It return the form index.
4290 * @return int The index of the plural form
4291 */
4292 private function getPluralForm( $number ) {
4293 $pluralRules = $this->getCompiledPluralRules();
4294 $form = CLDRPluralRuleEvaluator::evaluateCompiled( $number, $pluralRules );
4295 return $form;
4296 }
4297
4298 }