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