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