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