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