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