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