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