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