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