* (bug 27398) Add $wgExtraGenderNamespaces for configured gendered namespaces
[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
1263 // Add days of the past months of this year
1264 for ( $i = 0; $i < $gm; $i++ ) {
1265 $gDayNo += self::$GREG_DAYS[$i];
1266 }
1267
1268 // Leap years
1269 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1270 $gDayNo++;
1271 }
1272
1273 // Days passed in current month
1274 $gDayNo += $gd;
1275
1276 $jDayNo = $gDayNo - 79;
1277
1278 $jNp = floor( $jDayNo / 12053 );
1279 $jDayNo %= 12053;
1280
1281 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1282 $jDayNo %= 1461;
1283
1284 if ( $jDayNo >= 366 ) {
1285 $jy += floor( ( $jDayNo - 1 ) / 365 );
1286 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1287 }
1288
1289 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1290 $jDayNo -= self::$IRANIAN_DAYS[$i];
1291 }
1292
1293 $jm = $i + 1;
1294 $jd = $jDayNo + 1;
1295
1296 return array( $jy, $jm, $jd );
1297 }
1298
1299 /**
1300 * Converting Gregorian dates to Hijri dates.
1301 *
1302 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1303 *
1304 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1305 *
1306 * @param $ts string
1307 *
1308 * @return string
1309 */
1310 private static function tsToHijri( $ts ) {
1311 $year = substr( $ts, 0, 4 );
1312 $month = substr( $ts, 4, 2 );
1313 $day = substr( $ts, 6, 2 );
1314
1315 $zyr = $year;
1316 $zd = $day;
1317 $zm = $month;
1318 $zy = $zyr;
1319
1320 if (
1321 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1322 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1323 )
1324 {
1325 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1326 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1327 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1328 $zd - 32075;
1329 } else {
1330 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1331 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1332 }
1333
1334 $zl = $zjd -1948440 + 10632;
1335 $zn = (int)( ( $zl - 1 ) / 10631 );
1336 $zl = $zl - 10631 * $zn + 354;
1337 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1338 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1339 $zm = (int)( ( 24 * $zl ) / 709 );
1340 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1341 $zy = 30 * $zn + $zj - 30;
1342
1343 return array( $zy, $zm, $zd );
1344 }
1345
1346 /**
1347 * Converting Gregorian dates to Hebrew dates.
1348 *
1349 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1350 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1351 * to translate the relevant functions into PHP and release them under
1352 * GNU GPL.
1353 *
1354 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1355 * and Adar II is 14. In a non-leap year, Adar is 6.
1356 *
1357 * @param $ts string
1358 *
1359 * @return string
1360 */
1361 private static function tsToHebrew( $ts ) {
1362 # Parse date
1363 $year = substr( $ts, 0, 4 );
1364 $month = substr( $ts, 4, 2 );
1365 $day = substr( $ts, 6, 2 );
1366
1367 # Calculate Hebrew year
1368 $hebrewYear = $year + 3760;
1369
1370 # Month number when September = 1, August = 12
1371 $month += 4;
1372 if ( $month > 12 ) {
1373 # Next year
1374 $month -= 12;
1375 $year++;
1376 $hebrewYear++;
1377 }
1378
1379 # Calculate day of year from 1 September
1380 $dayOfYear = $day;
1381 for ( $i = 1; $i < $month; $i++ ) {
1382 if ( $i == 6 ) {
1383 # February
1384 $dayOfYear += 28;
1385 # Check if the year is leap
1386 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1387 $dayOfYear++;
1388 }
1389 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1390 $dayOfYear += 30;
1391 } else {
1392 $dayOfYear += 31;
1393 }
1394 }
1395
1396 # Calculate the start of the Hebrew year
1397 $start = self::hebrewYearStart( $hebrewYear );
1398
1399 # Calculate next year's start
1400 if ( $dayOfYear <= $start ) {
1401 # Day is before the start of the year - it is the previous year
1402 # Next year's start
1403 $nextStart = $start;
1404 # Previous year
1405 $year--;
1406 $hebrewYear--;
1407 # Add days since previous year's 1 September
1408 $dayOfYear += 365;
1409 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1410 # Leap year
1411 $dayOfYear++;
1412 }
1413 # Start of the new (previous) year
1414 $start = self::hebrewYearStart( $hebrewYear );
1415 } else {
1416 # Next year's start
1417 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1418 }
1419
1420 # Calculate Hebrew day of year
1421 $hebrewDayOfYear = $dayOfYear - $start;
1422
1423 # Difference between year's days
1424 $diff = $nextStart - $start;
1425 # Add 12 (or 13 for leap years) days to ignore the difference between
1426 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1427 # difference is only about the year type
1428 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1429 $diff += 13;
1430 } else {
1431 $diff += 12;
1432 }
1433
1434 # Check the year pattern, and is leap year
1435 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1436 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1437 # and non-leap years
1438 $yearPattern = $diff % 30;
1439 # Check if leap year
1440 $isLeap = $diff >= 30;
1441
1442 # Calculate day in the month from number of day in the Hebrew year
1443 # Don't check Adar - if the day is not in Adar, we will stop before;
1444 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1445 $hebrewDay = $hebrewDayOfYear;
1446 $hebrewMonth = 1;
1447 $days = 0;
1448 while ( $hebrewMonth <= 12 ) {
1449 # Calculate days in this month
1450 if ( $isLeap && $hebrewMonth == 6 ) {
1451 # Adar in a leap year
1452 if ( $isLeap ) {
1453 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1454 $days = 30;
1455 if ( $hebrewDay <= $days ) {
1456 # Day in Adar I
1457 $hebrewMonth = 13;
1458 } else {
1459 # Subtract the days of Adar I
1460 $hebrewDay -= $days;
1461 # Try Adar II
1462 $days = 29;
1463 if ( $hebrewDay <= $days ) {
1464 # Day in Adar II
1465 $hebrewMonth = 14;
1466 }
1467 }
1468 }
1469 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1470 # Cheshvan in a complete year (otherwise as the rule below)
1471 $days = 30;
1472 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1473 # Kislev in an incomplete year (otherwise as the rule below)
1474 $days = 29;
1475 } else {
1476 # Odd months have 30 days, even have 29
1477 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1478 }
1479 if ( $hebrewDay <= $days ) {
1480 # In the current month
1481 break;
1482 } else {
1483 # Subtract the days of the current month
1484 $hebrewDay -= $days;
1485 # Try in the next month
1486 $hebrewMonth++;
1487 }
1488 }
1489
1490 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1491 }
1492
1493 /**
1494 * This calculates the Hebrew year start, as days since 1 September.
1495 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1496 * Used for Hebrew date.
1497 *
1498 * @param $year int
1499 *
1500 * @return string
1501 */
1502 private static function hebrewYearStart( $year ) {
1503 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1504 $b = intval( ( $year - 1 ) % 4 );
1505 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1506 if ( $m < 0 ) {
1507 $m--;
1508 }
1509 $Mar = intval( $m );
1510 if ( $m < 0 ) {
1511 $m++;
1512 }
1513 $m -= $Mar;
1514
1515 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1516 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1517 $Mar++;
1518 } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1519 $Mar += 2;
1520 } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
1521 $Mar++;
1522 }
1523
1524 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1525 return $Mar;
1526 }
1527
1528 /**
1529 * Algorithm to convert Gregorian dates to Thai solar dates,
1530 * Minguo dates or Minguo dates.
1531 *
1532 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1533 * http://en.wikipedia.org/wiki/Minguo_calendar
1534 * http://en.wikipedia.org/wiki/Japanese_era_name
1535 *
1536 * @param $ts String: 14-character timestamp
1537 * @param $cName String: calender name
1538 * @return Array: converted year, month, day
1539 */
1540 private static function tsToYear( $ts, $cName ) {
1541 $gy = substr( $ts, 0, 4 );
1542 $gm = substr( $ts, 4, 2 );
1543 $gd = substr( $ts, 6, 2 );
1544
1545 if ( !strcmp( $cName, 'thai' ) ) {
1546 # Thai solar dates
1547 # Add 543 years to the Gregorian calendar
1548 # Months and days are identical
1549 $gy_offset = $gy + 543;
1550 } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1551 # Minguo dates
1552 # Deduct 1911 years from the Gregorian calendar
1553 # Months and days are identical
1554 $gy_offset = $gy - 1911;
1555 } elseif ( !strcmp( $cName, 'tenno' ) ) {
1556 # Nengō dates up to Meiji period
1557 # Deduct years from the Gregorian calendar
1558 # depending on the nengo periods
1559 # Months and days are identical
1560 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1561 # Meiji period
1562 $gy_gannen = $gy - 1868 + 1;
1563 $gy_offset = $gy_gannen;
1564 if ( $gy_gannen == 1 ) {
1565 $gy_offset = '元';
1566 }
1567 $gy_offset = '明治' . $gy_offset;
1568 } elseif (
1569 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1570 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1571 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1572 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1573 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1574 )
1575 {
1576 # Taishō period
1577 $gy_gannen = $gy - 1912 + 1;
1578 $gy_offset = $gy_gannen;
1579 if ( $gy_gannen == 1 ) {
1580 $gy_offset = '元';
1581 }
1582 $gy_offset = '大正' . $gy_offset;
1583 } elseif (
1584 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1585 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1586 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1587 )
1588 {
1589 # Shōwa period
1590 $gy_gannen = $gy - 1926 + 1;
1591 $gy_offset = $gy_gannen;
1592 if ( $gy_gannen == 1 ) {
1593 $gy_offset = '元';
1594 }
1595 $gy_offset = '昭和' . $gy_offset;
1596 } else {
1597 # Heisei period
1598 $gy_gannen = $gy - 1989 + 1;
1599 $gy_offset = $gy_gannen;
1600 if ( $gy_gannen == 1 ) {
1601 $gy_offset = '元';
1602 }
1603 $gy_offset = '平成' . $gy_offset;
1604 }
1605 } else {
1606 $gy_offset = $gy;
1607 }
1608
1609 return array( $gy_offset, $gm, $gd );
1610 }
1611
1612 /**
1613 * Roman number formatting up to 3000
1614 *
1615 * @param $num int
1616 *
1617 * @return string
1618 */
1619 static function romanNumeral( $num ) {
1620 static $table = array(
1621 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1622 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1623 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1624 array( '', 'M', 'MM', 'MMM' )
1625 );
1626
1627 $num = intval( $num );
1628 if ( $num > 3000 || $num <= 0 ) {
1629 return $num;
1630 }
1631
1632 $s = '';
1633 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1634 if ( $num >= $pow10 ) {
1635 $s .= $table[$i][floor( $num / $pow10 )];
1636 }
1637 $num = $num % $pow10;
1638 }
1639 return $s;
1640 }
1641
1642 /**
1643 * Hebrew Gematria number formatting up to 9999
1644 *
1645 * @param $num int
1646 *
1647 * @return string
1648 */
1649 static function hebrewNumeral( $num ) {
1650 static $table = array(
1651 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1652 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1653 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1654 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1655 );
1656
1657 $num = intval( $num );
1658 if ( $num > 9999 || $num <= 0 ) {
1659 return $num;
1660 }
1661
1662 $s = '';
1663 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1664 if ( $num >= $pow10 ) {
1665 if ( $num == 15 || $num == 16 ) {
1666 $s .= $table[0][9] . $table[0][$num - 9];
1667 $num = 0;
1668 } else {
1669 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1670 if ( $pow10 == 1000 ) {
1671 $s .= "'";
1672 }
1673 }
1674 }
1675 $num = $num % $pow10;
1676 }
1677 if ( strlen( $s ) == 2 ) {
1678 $str = $s . "'";
1679 } else {
1680 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1681 $str .= substr( $s, strlen( $s ) - 2, 2 );
1682 }
1683 $start = substr( $str, 0, strlen( $str ) - 2 );
1684 $end = substr( $str, strlen( $str ) - 2 );
1685 switch( $end ) {
1686 case 'כ':
1687 $str = $start . 'ך';
1688 break;
1689 case 'מ':
1690 $str = $start . 'ם';
1691 break;
1692 case 'נ':
1693 $str = $start . 'ן';
1694 break;
1695 case 'פ':
1696 $str = $start . 'ף';
1697 break;
1698 case 'צ':
1699 $str = $start . 'ץ';
1700 break;
1701 }
1702 return $str;
1703 }
1704
1705 /**
1706 * This is meant to be used by time(), date(), and timeanddate() to get
1707 * the date preference they're supposed to use, it should be used in
1708 * all children.
1709 *
1710 *<code>
1711 * function timeanddate([...], $format = true) {
1712 * $datePreference = $this->dateFormat($format);
1713 * [...]
1714 * }
1715 *</code>
1716 *
1717 * @param $usePrefs Mixed: if true, the user's preference is used
1718 * if false, the site/language default is used
1719 * if int/string, assumed to be a format.
1720 * @return string
1721 */
1722 function dateFormat( $usePrefs = true ) {
1723 global $wgUser;
1724
1725 if ( is_bool( $usePrefs ) ) {
1726 if ( $usePrefs ) {
1727 $datePreference = $wgUser->getDatePreference();
1728 } else {
1729 $datePreference = (string)User::getDefaultOption( 'date' );
1730 }
1731 } else {
1732 $datePreference = (string)$usePrefs;
1733 }
1734
1735 // return int
1736 if ( $datePreference == '' ) {
1737 return 'default';
1738 }
1739
1740 return $datePreference;
1741 }
1742
1743 /**
1744 * Get a format string for a given type and preference
1745 * @param $type string May be date, time or both
1746 * @param $pref string The format name as it appears in Messages*.php
1747 *
1748 * @return string
1749 */
1750 function getDateFormatString( $type, $pref ) {
1751 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1752 if ( $pref == 'default' ) {
1753 $pref = $this->getDefaultDateFormat();
1754 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1755 } else {
1756 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1757 if ( is_null( $df ) ) {
1758 $pref = $this->getDefaultDateFormat();
1759 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1760 }
1761 }
1762 $this->dateFormatStrings[$type][$pref] = $df;
1763 }
1764 return $this->dateFormatStrings[$type][$pref];
1765 }
1766
1767 /**
1768 * @param $ts Mixed: the time format which needs to be turned into a
1769 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1770 * @param $adj Bool: whether to adjust the time output according to the
1771 * user configured offset ($timecorrection)
1772 * @param $format Mixed: true to use user's date format preference
1773 * @param $timecorrection String|bool the time offset as returned by
1774 * validateTimeZone() in Special:Preferences
1775 * @return string
1776 */
1777 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1778 $ts = wfTimestamp( TS_MW, $ts );
1779 if ( $adj ) {
1780 $ts = $this->userAdjust( $ts, $timecorrection );
1781 }
1782 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1783 return $this->sprintfDate( $df, $ts );
1784 }
1785
1786 /**
1787 * @param $ts Mixed: the time format which needs to be turned into a
1788 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1789 * @param $adj Bool: whether to adjust the time output according to the
1790 * user configured offset ($timecorrection)
1791 * @param $format Mixed: true to use user's date format preference
1792 * @param $timecorrection String|bool the time offset as returned by
1793 * validateTimeZone() in Special:Preferences
1794 * @return string
1795 */
1796 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1797 $ts = wfTimestamp( TS_MW, $ts );
1798 if ( $adj ) {
1799 $ts = $this->userAdjust( $ts, $timecorrection );
1800 }
1801 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1802 return $this->sprintfDate( $df, $ts );
1803 }
1804
1805 /**
1806 * @param $ts Mixed: the time format which needs to be turned into a
1807 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1808 * @param $adj Bool: whether to adjust the time output according to the
1809 * user configured offset ($timecorrection)
1810 * @param $format Mixed: what format to return, if it's false output the
1811 * default one (default true)
1812 * @param $timecorrection String|bool the time offset as returned by
1813 * validateTimeZone() in Special:Preferences
1814 * @return string
1815 */
1816 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1817 $ts = wfTimestamp( TS_MW, $ts );
1818 if ( $adj ) {
1819 $ts = $this->userAdjust( $ts, $timecorrection );
1820 }
1821 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1822 return $this->sprintfDate( $df, $ts );
1823 }
1824
1825 /**
1826 * @param $key string
1827 * @return array|null
1828 */
1829 function getMessage( $key ) {
1830 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
1831 }
1832
1833 /**
1834 * @return array
1835 */
1836 function getAllMessages() {
1837 return self::$dataCache->getItem( $this->mCode, 'messages' );
1838 }
1839
1840 /**
1841 * @param $in
1842 * @param $out
1843 * @param $string
1844 * @return string
1845 */
1846 function iconv( $in, $out, $string ) {
1847 # This is a wrapper for iconv in all languages except esperanto,
1848 # which does some nasty x-conversions beforehand
1849
1850 # Even with //IGNORE iconv can whine about illegal characters in
1851 # *input* string. We just ignore those too.
1852 # REF: http://bugs.php.net/bug.php?id=37166
1853 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1854 wfSuppressWarnings();
1855 $text = iconv( $in, $out . '//IGNORE', $string );
1856 wfRestoreWarnings();
1857 return $text;
1858 }
1859
1860 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1861
1862 /**
1863 * @param $matches array
1864 * @return mixed|string
1865 */
1866 function ucwordbreaksCallbackAscii( $matches ) {
1867 return $this->ucfirst( $matches[1] );
1868 }
1869
1870 /**
1871 * @param $matches array
1872 * @return string
1873 */
1874 function ucwordbreaksCallbackMB( $matches ) {
1875 return mb_strtoupper( $matches[0] );
1876 }
1877
1878 /**
1879 * @param $matches array
1880 * @return string
1881 */
1882 function ucCallback( $matches ) {
1883 list( $wikiUpperChars ) = self::getCaseMaps();
1884 return strtr( $matches[1], $wikiUpperChars );
1885 }
1886
1887 /**
1888 * @param $matches array
1889 * @return string
1890 */
1891 function lcCallback( $matches ) {
1892 list( , $wikiLowerChars ) = self::getCaseMaps();
1893 return strtr( $matches[1], $wikiLowerChars );
1894 }
1895
1896 /**
1897 * @param $matches array
1898 * @return string
1899 */
1900 function ucwordsCallbackMB( $matches ) {
1901 return mb_strtoupper( $matches[0] );
1902 }
1903
1904 /**
1905 * @param $matches array
1906 * @return string
1907 */
1908 function ucwordsCallbackWiki( $matches ) {
1909 list( $wikiUpperChars ) = self::getCaseMaps();
1910 return strtr( $matches[0], $wikiUpperChars );
1911 }
1912
1913 /**
1914 * Make a string's first character uppercase
1915 *
1916 * @param $str string
1917 *
1918 * @return string
1919 */
1920 function ucfirst( $str ) {
1921 $o = ord( $str );
1922 if ( $o < 96 ) { // if already uppercase...
1923 return $str;
1924 } elseif ( $o < 128 ) {
1925 return ucfirst( $str ); // use PHP's ucfirst()
1926 } else {
1927 // fall back to more complex logic in case of multibyte strings
1928 return $this->uc( $str, true );
1929 }
1930 }
1931
1932 /**
1933 * Convert a string to uppercase
1934 *
1935 * @param $str string
1936 * @param $first bool
1937 *
1938 * @return string
1939 */
1940 function uc( $str, $first = false ) {
1941 if ( function_exists( 'mb_strtoupper' ) ) {
1942 if ( $first ) {
1943 if ( $this->isMultibyte( $str ) ) {
1944 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1945 } else {
1946 return ucfirst( $str );
1947 }
1948 } else {
1949 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1950 }
1951 } else {
1952 if ( $this->isMultibyte( $str ) ) {
1953 $x = $first ? '^' : '';
1954 return preg_replace_callback(
1955 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1956 array( $this, 'ucCallback' ),
1957 $str
1958 );
1959 } else {
1960 return $first ? ucfirst( $str ) : strtoupper( $str );
1961 }
1962 }
1963 }
1964
1965 /**
1966 * @param $str string
1967 * @return mixed|string
1968 */
1969 function lcfirst( $str ) {
1970 $o = ord( $str );
1971 if ( !$o ) {
1972 return strval( $str );
1973 } elseif ( $o >= 128 ) {
1974 return $this->lc( $str, true );
1975 } elseif ( $o > 96 ) {
1976 return $str;
1977 } else {
1978 $str[0] = strtolower( $str[0] );
1979 return $str;
1980 }
1981 }
1982
1983 /**
1984 * @param $str string
1985 * @param $first bool
1986 * @return mixed|string
1987 */
1988 function lc( $str, $first = false ) {
1989 if ( function_exists( 'mb_strtolower' ) ) {
1990 if ( $first ) {
1991 if ( $this->isMultibyte( $str ) ) {
1992 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1993 } else {
1994 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1995 }
1996 } else {
1997 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1998 }
1999 } else {
2000 if ( $this->isMultibyte( $str ) ) {
2001 $x = $first ? '^' : '';
2002 return preg_replace_callback(
2003 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
2004 array( $this, 'lcCallback' ),
2005 $str
2006 );
2007 } else {
2008 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
2009 }
2010 }
2011 }
2012
2013 /**
2014 * @param $str string
2015 * @return bool
2016 */
2017 function isMultibyte( $str ) {
2018 return (bool)preg_match( '/[\x80-\xff]/', $str );
2019 }
2020
2021 /**
2022 * @param $str string
2023 * @return mixed|string
2024 */
2025 function ucwords( $str ) {
2026 if ( $this->isMultibyte( $str ) ) {
2027 $str = $this->lc( $str );
2028
2029 // regexp to find first letter in each word (i.e. after each space)
2030 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2031
2032 // function to use to capitalize a single char
2033 if ( function_exists( 'mb_strtoupper' ) ) {
2034 return preg_replace_callback(
2035 $replaceRegexp,
2036 array( $this, 'ucwordsCallbackMB' ),
2037 $str
2038 );
2039 } else {
2040 return preg_replace_callback(
2041 $replaceRegexp,
2042 array( $this, 'ucwordsCallbackWiki' ),
2043 $str
2044 );
2045 }
2046 } else {
2047 return ucwords( strtolower( $str ) );
2048 }
2049 }
2050
2051 /**
2052 * capitalize words at word breaks
2053 *
2054 * @param $str string
2055 * @return mixed
2056 */
2057 function ucwordbreaks( $str ) {
2058 if ( $this->isMultibyte( $str ) ) {
2059 $str = $this->lc( $str );
2060
2061 // since \b doesn't work for UTF-8, we explicitely define word break chars
2062 $breaks = "[ \-\(\)\}\{\.,\?!]";
2063
2064 // find first letter after word break
2065 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
2066
2067 if ( function_exists( 'mb_strtoupper' ) ) {
2068 return preg_replace_callback(
2069 $replaceRegexp,
2070 array( $this, 'ucwordbreaksCallbackMB' ),
2071 $str
2072 );
2073 } else {
2074 return preg_replace_callback(
2075 $replaceRegexp,
2076 array( $this, 'ucwordsCallbackWiki' ),
2077 $str
2078 );
2079 }
2080 } else {
2081 return preg_replace_callback(
2082 '/\b([\w\x80-\xff]+)\b/',
2083 array( $this, 'ucwordbreaksCallbackAscii' ),
2084 $str
2085 );
2086 }
2087 }
2088
2089 /**
2090 * Return a case-folded representation of $s
2091 *
2092 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
2093 * and $s2 are the same except for the case of their characters. It is not
2094 * necessary for the value returned to make sense when displayed.
2095 *
2096 * Do *not* perform any other normalisation in this function. If a caller
2097 * uses this function when it should be using a more general normalisation
2098 * function, then fix the caller.
2099 *
2100 * @param $s string
2101 *
2102 * @return string
2103 */
2104 function caseFold( $s ) {
2105 return $this->uc( $s );
2106 }
2107
2108 /**
2109 * @param $s string
2110 * @return string
2111 */
2112 function checkTitleEncoding( $s ) {
2113 if ( is_array( $s ) ) {
2114 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
2115 }
2116 # Check for non-UTF-8 URLs
2117 $ishigh = preg_match( '/[\x80-\xff]/', $s );
2118 if ( !$ishigh ) {
2119 return $s;
2120 }
2121
2122 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2123 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
2124 if ( $isutf8 ) {
2125 return $s;
2126 }
2127
2128 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
2129 }
2130
2131 /**
2132 * @return array
2133 */
2134 function fallback8bitEncoding() {
2135 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
2136 }
2137
2138 /**
2139 * Most writing systems use whitespace to break up words.
2140 * Some languages such as Chinese don't conventionally do this,
2141 * which requires special handling when breaking up words for
2142 * searching etc.
2143 *
2144 * @return bool
2145 */
2146 function hasWordBreaks() {
2147 return true;
2148 }
2149
2150 /**
2151 * Some languages such as Chinese require word segmentation,
2152 * Specify such segmentation when overridden in derived class.
2153 *
2154 * @param $string String
2155 * @return String
2156 */
2157 function segmentByWord( $string ) {
2158 return $string;
2159 }
2160
2161 /**
2162 * Some languages have special punctuation need to be normalized.
2163 * Make such changes here.
2164 *
2165 * @param $string String
2166 * @return String
2167 */
2168 function normalizeForSearch( $string ) {
2169 return self::convertDoubleWidth( $string );
2170 }
2171
2172 /**
2173 * convert double-width roman characters to single-width.
2174 * range: ff00-ff5f ~= 0020-007f
2175 *
2176 * @param $string string
2177 *
2178 * @return string
2179 */
2180 protected static function convertDoubleWidth( $string ) {
2181 static $full = null;
2182 static $half = null;
2183
2184 if ( $full === null ) {
2185 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2186 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
2187 $full = str_split( $fullWidth, 3 );
2188 $half = str_split( $halfWidth );
2189 }
2190
2191 $string = str_replace( $full, $half, $string );
2192 return $string;
2193 }
2194
2195 /**
2196 * @param $string string
2197 * @param $pattern string
2198 * @return string
2199 */
2200 protected static function insertSpace( $string, $pattern ) {
2201 $string = preg_replace( $pattern, " $1 ", $string );
2202 $string = preg_replace( '/ +/', ' ', $string );
2203 return $string;
2204 }
2205
2206 /**
2207 * @param $termsArray array
2208 * @return array
2209 */
2210 function convertForSearchResult( $termsArray ) {
2211 # some languages, e.g. Chinese, need to do a conversion
2212 # in order for search results to be displayed correctly
2213 return $termsArray;
2214 }
2215
2216 /**
2217 * Get the first character of a string.
2218 *
2219 * @param $s string
2220 * @return string
2221 */
2222 function firstChar( $s ) {
2223 $matches = array();
2224 preg_match(
2225 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
2226 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
2227 $s,
2228 $matches
2229 );
2230
2231 if ( isset( $matches[1] ) ) {
2232 if ( strlen( $matches[1] ) != 3 ) {
2233 return $matches[1];
2234 }
2235
2236 // Break down Hangul syllables to grab the first jamo
2237 $code = utf8ToCodepoint( $matches[1] );
2238 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
2239 return $matches[1];
2240 } elseif ( $code < 0xb098 ) {
2241 return "\xe3\x84\xb1";
2242 } elseif ( $code < 0xb2e4 ) {
2243 return "\xe3\x84\xb4";
2244 } elseif ( $code < 0xb77c ) {
2245 return "\xe3\x84\xb7";
2246 } elseif ( $code < 0xb9c8 ) {
2247 return "\xe3\x84\xb9";
2248 } elseif ( $code < 0xbc14 ) {
2249 return "\xe3\x85\x81";
2250 } elseif ( $code < 0xc0ac ) {
2251 return "\xe3\x85\x82";
2252 } elseif ( $code < 0xc544 ) {
2253 return "\xe3\x85\x85";
2254 } elseif ( $code < 0xc790 ) {
2255 return "\xe3\x85\x87";
2256 } elseif ( $code < 0xcc28 ) {
2257 return "\xe3\x85\x88";
2258 } elseif ( $code < 0xce74 ) {
2259 return "\xe3\x85\x8a";
2260 } elseif ( $code < 0xd0c0 ) {
2261 return "\xe3\x85\x8b";
2262 } elseif ( $code < 0xd30c ) {
2263 return "\xe3\x85\x8c";
2264 } elseif ( $code < 0xd558 ) {
2265 return "\xe3\x85\x8d";
2266 } else {
2267 return "\xe3\x85\x8e";
2268 }
2269 } else {
2270 return '';
2271 }
2272 }
2273
2274 function initEncoding() {
2275 # Some languages may have an alternate char encoding option
2276 # (Esperanto X-coding, Japanese furigana conversion, etc)
2277 # If this language is used as the primary content language,
2278 # an override to the defaults can be set here on startup.
2279 }
2280
2281 /**
2282 * @param $s string
2283 * @return string
2284 */
2285 function recodeForEdit( $s ) {
2286 # For some languages we'll want to explicitly specify
2287 # which characters make it into the edit box raw
2288 # or are converted in some way or another.
2289 global $wgEditEncoding;
2290 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2291 return $s;
2292 } else {
2293 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2294 }
2295 }
2296
2297 /**
2298 * @param $s string
2299 * @return string
2300 */
2301 function recodeInput( $s ) {
2302 # Take the previous into account.
2303 global $wgEditEncoding;
2304 if ( $wgEditEncoding != '' ) {
2305 $enc = $wgEditEncoding;
2306 } else {
2307 $enc = 'UTF-8';
2308 }
2309 if ( $enc == 'UTF-8' ) {
2310 return $s;
2311 } else {
2312 return $this->iconv( $enc, 'UTF-8', $s );
2313 }
2314 }
2315
2316 /**
2317 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2318 * also cleans up certain backwards-compatible sequences, converting them
2319 * to the modern Unicode equivalent.
2320 *
2321 * This is language-specific for performance reasons only.
2322 *
2323 * @param $s string
2324 *
2325 * @return string
2326 */
2327 function normalize( $s ) {
2328 global $wgAllUnicodeFixes;
2329 $s = UtfNormal::cleanUp( $s );
2330 if ( $wgAllUnicodeFixes ) {
2331 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2332 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2333 }
2334
2335 return $s;
2336 }
2337
2338 /**
2339 * Transform a string using serialized data stored in the given file (which
2340 * must be in the serialized subdirectory of $IP). The file contains pairs
2341 * mapping source characters to destination characters.
2342 *
2343 * The data is cached in process memory. This will go faster if you have the
2344 * FastStringSearch extension.
2345 *
2346 * @param $file string
2347 * @param $string string
2348 *
2349 * @return string
2350 */
2351 function transformUsingPairFile( $file, $string ) {
2352 if ( !isset( $this->transformData[$file] ) ) {
2353 $data = wfGetPrecompiledData( $file );
2354 if ( $data === false ) {
2355 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2356 }
2357 $this->transformData[$file] = new ReplacementArray( $data );
2358 }
2359 return $this->transformData[$file]->replace( $string );
2360 }
2361
2362 /**
2363 * For right-to-left language support
2364 *
2365 * @return bool
2366 */
2367 function isRTL() {
2368 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2369 }
2370
2371 /**
2372 * Return the correct HTML 'dir' attribute value for this language.
2373 * @return String
2374 */
2375 function getDir() {
2376 return $this->isRTL() ? 'rtl' : 'ltr';
2377 }
2378
2379 /**
2380 * Return 'left' or 'right' as appropriate alignment for line-start
2381 * for this language's text direction.
2382 *
2383 * Should be equivalent to CSS3 'start' text-align value....
2384 *
2385 * @return String
2386 */
2387 function alignStart() {
2388 return $this->isRTL() ? 'right' : 'left';
2389 }
2390
2391 /**
2392 * Return 'right' or 'left' as appropriate alignment for line-end
2393 * for this language's text direction.
2394 *
2395 * Should be equivalent to CSS3 'end' text-align value....
2396 *
2397 * @return String
2398 */
2399 function alignEnd() {
2400 return $this->isRTL() ? 'left' : 'right';
2401 }
2402
2403 /**
2404 * A hidden direction mark (LRM or RLM), depending on the language direction
2405 *
2406 * @param $opposite Boolean Get the direction mark opposite to your language
2407 * @return string
2408 */
2409 function getDirMark( $opposite = false ) {
2410 $rtl = "\xE2\x80\x8F";
2411 $ltr = "\xE2\x80\x8E";
2412 if( $opposite ) { return $this->isRTL() ? $ltr : $rtl; }
2413 return $this->isRTL() ? $rtl : $ltr;
2414 }
2415
2416 /**
2417 * @return array
2418 */
2419 function capitalizeAllNouns() {
2420 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2421 }
2422
2423 /**
2424 * An arrow, depending on the language direction
2425 *
2426 * @return string
2427 */
2428 function getArrow() {
2429 return $this->isRTL() ? '←' : '→';
2430 }
2431
2432 /**
2433 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2434 *
2435 * @return bool
2436 */
2437 function linkPrefixExtension() {
2438 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2439 }
2440
2441 /**
2442 * @return array
2443 */
2444 function getMagicWords() {
2445 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2446 }
2447
2448 protected function doMagicHook() {
2449 if ( $this->mMagicHookDone ) {
2450 return;
2451 }
2452 $this->mMagicHookDone = true;
2453 wfProfileIn( 'LanguageGetMagic' );
2454 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2455 wfProfileOut( 'LanguageGetMagic' );
2456 }
2457
2458 /**
2459 * Fill a MagicWord object with data from here
2460 *
2461 * @param $mw
2462 */
2463 function getMagic( $mw ) {
2464 $this->doMagicHook();
2465
2466 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2467 $rawEntry = $this->mMagicExtensions[$mw->mId];
2468 } else {
2469 $magicWords = $this->getMagicWords();
2470 if ( isset( $magicWords[$mw->mId] ) ) {
2471 $rawEntry = $magicWords[$mw->mId];
2472 } else {
2473 $rawEntry = false;
2474 }
2475 }
2476
2477 if ( !is_array( $rawEntry ) ) {
2478 error_log( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
2479 } else {
2480 $mw->mCaseSensitive = $rawEntry[0];
2481 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2482 }
2483 }
2484
2485 /**
2486 * Add magic words to the extension array
2487 *
2488 * @param $newWords array
2489 */
2490 function addMagicWordsByLang( $newWords ) {
2491 $fallbackChain = $this->getFallbackLanguages();
2492 $fallbackChain = array_reverse( $fallbackChain );
2493 foreach ( $fallbackChain as $code ) {
2494 if ( isset( $newWords[$code] ) ) {
2495 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2496 }
2497 }
2498 }
2499
2500 /**
2501 * Get special page names, as an associative array
2502 * case folded alias => real name
2503 */
2504 function getSpecialPageAliases() {
2505 // Cache aliases because it may be slow to load them
2506 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2507 // Initialise array
2508 $this->mExtendedSpecialPageAliases =
2509 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2510 wfRunHooks( 'LanguageGetSpecialPageAliases',
2511 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2512 }
2513
2514 return $this->mExtendedSpecialPageAliases;
2515 }
2516
2517 /**
2518 * Italic is unsuitable for some languages
2519 *
2520 * @param $text String: the text to be emphasized.
2521 * @return string
2522 */
2523 function emphasize( $text ) {
2524 return "<em>$text</em>";
2525 }
2526
2527 /**
2528 * Normally we output all numbers in plain en_US style, that is
2529 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2530 * point twohundredthirtyfive. However this is not suitable for all
2531 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2532 * Icelandic just want to use commas instead of dots, and dots instead
2533 * of commas like "293.291,235".
2534 *
2535 * An example of this function being called:
2536 * <code>
2537 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2538 * </code>
2539 *
2540 * See LanguageGu.php for the Gujarati implementation and
2541 * $separatorTransformTable on MessageIs.php for
2542 * the , => . and . => , implementation.
2543 *
2544 * @todo check if it's viable to use localeconv() for the decimal
2545 * separator thing.
2546 * @param $number Mixed: the string to be formatted, should be an integer
2547 * or a floating point number.
2548 * @param $nocommafy Bool: set to true for special numbers like dates
2549 * @return string
2550 */
2551 function formatNum( $number, $nocommafy = false ) {
2552 global $wgTranslateNumerals;
2553 if ( !$nocommafy ) {
2554 $number = $this->commafy( $number );
2555 $s = $this->separatorTransformTable();
2556 if ( $s ) {
2557 $number = strtr( $number, $s );
2558 }
2559 }
2560
2561 if ( $wgTranslateNumerals ) {
2562 $s = $this->digitTransformTable();
2563 if ( $s ) {
2564 $number = strtr( $number, $s );
2565 }
2566 }
2567
2568 return $number;
2569 }
2570
2571 /**
2572 * @param $number string
2573 * @return string
2574 */
2575 function parseFormattedNumber( $number ) {
2576 $s = $this->digitTransformTable();
2577 if ( $s ) {
2578 $number = strtr( $number, array_flip( $s ) );
2579 }
2580
2581 $s = $this->separatorTransformTable();
2582 if ( $s ) {
2583 $number = strtr( $number, array_flip( $s ) );
2584 }
2585
2586 $number = strtr( $number, array( ',' => '' ) );
2587 return $number;
2588 }
2589
2590 /**
2591 * Adds commas to a given number
2592 *
2593 * @param $_ mixed
2594 * @return string
2595 */
2596 function commafy( $_ ) {
2597 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2598 }
2599
2600 /**
2601 * @return array
2602 */
2603 function digitTransformTable() {
2604 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2605 }
2606
2607 /**
2608 * @return array
2609 */
2610 function separatorTransformTable() {
2611 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2612 }
2613
2614 /**
2615 * Take a list of strings and build a locale-friendly comma-separated
2616 * list, using the local comma-separator message.
2617 * The last two strings are chained with an "and".
2618 *
2619 * @param $l Array
2620 * @return string
2621 */
2622 function listToText( $l ) {
2623 $s = '';
2624 $m = count( $l ) - 1;
2625 if ( $m == 1 ) {
2626 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2627 } else {
2628 for ( $i = $m; $i >= 0; $i-- ) {
2629 if ( $i == $m ) {
2630 $s = $l[$i];
2631 } elseif ( $i == $m - 1 ) {
2632 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2633 } else {
2634 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2635 }
2636 }
2637 return $s;
2638 }
2639 }
2640
2641 /**
2642 * Take a list of strings and build a locale-friendly comma-separated
2643 * list, using the local comma-separator message.
2644 * @param $list array of strings to put in a comma list
2645 * @return string
2646 */
2647 function commaList( $list ) {
2648 return implode(
2649 $list,
2650 wfMsgExt(
2651 'comma-separator',
2652 array( 'parsemag', 'escapenoentities', 'language' => $this )
2653 )
2654 );
2655 }
2656
2657 /**
2658 * Take a list of strings and build a locale-friendly semicolon-separated
2659 * list, using the local semicolon-separator message.
2660 * @param $list array of strings to put in a semicolon list
2661 * @return string
2662 */
2663 function semicolonList( $list ) {
2664 return implode(
2665 $list,
2666 wfMsgExt(
2667 'semicolon-separator',
2668 array( 'parsemag', 'escapenoentities', 'language' => $this )
2669 )
2670 );
2671 }
2672
2673 /**
2674 * Same as commaList, but separate it with the pipe instead.
2675 * @param $list array of strings to put in a pipe list
2676 * @return string
2677 */
2678 function pipeList( $list ) {
2679 return implode(
2680 $list,
2681 wfMsgExt(
2682 'pipe-separator',
2683 array( 'escapenoentities', 'language' => $this )
2684 )
2685 );
2686 }
2687
2688 /**
2689 * Truncate a string to a specified length in bytes, appending an optional
2690 * string (e.g. for ellipses)
2691 *
2692 * The database offers limited byte lengths for some columns in the database;
2693 * multi-byte character sets mean we need to ensure that only whole characters
2694 * are included, otherwise broken characters can be passed to the user
2695 *
2696 * If $length is negative, the string will be truncated from the beginning
2697 *
2698 * @param $string String to truncate
2699 * @param $length Int: maximum length (including ellipses)
2700 * @param $ellipsis String to append to the truncated text
2701 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2702 * $adjustLength was introduced in 1.18, before that behaved as if false.
2703 * @return string
2704 */
2705 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2706 # Use the localized ellipsis character
2707 if ( $ellipsis == '...' ) {
2708 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2709 }
2710 # Check if there is no need to truncate
2711 if ( $length == 0 ) {
2712 return $ellipsis; // convention
2713 } elseif ( strlen( $string ) <= abs( $length ) ) {
2714 return $string; // no need to truncate
2715 }
2716 $stringOriginal = $string;
2717 # If ellipsis length is >= $length then we can't apply $adjustLength
2718 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2719 $string = $ellipsis; // this can be slightly unexpected
2720 # Otherwise, truncate and add ellipsis...
2721 } else {
2722 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
2723 if ( $length > 0 ) {
2724 $length -= $eLength;
2725 $string = substr( $string, 0, $length ); // xyz...
2726 $string = $this->removeBadCharLast( $string );
2727 $string = $string . $ellipsis;
2728 } else {
2729 $length += $eLength;
2730 $string = substr( $string, $length ); // ...xyz
2731 $string = $this->removeBadCharFirst( $string );
2732 $string = $ellipsis . $string;
2733 }
2734 }
2735 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2736 # This check is *not* redundant if $adjustLength, due to the single case where
2737 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2738 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2739 return $string;
2740 } else {
2741 return $stringOriginal;
2742 }
2743 }
2744
2745 /**
2746 * Remove bytes that represent an incomplete Unicode character
2747 * at the end of string (e.g. bytes of the char are missing)
2748 *
2749 * @param $string String
2750 * @return string
2751 */
2752 protected function removeBadCharLast( $string ) {
2753 if ( $string != '' ) {
2754 $char = ord( $string[strlen( $string ) - 1] );
2755 $m = array();
2756 if ( $char >= 0xc0 ) {
2757 # We got the first byte only of a multibyte char; remove it.
2758 $string = substr( $string, 0, -1 );
2759 } elseif ( $char >= 0x80 &&
2760 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2761 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2762 {
2763 # We chopped in the middle of a character; remove it
2764 $string = $m[1];
2765 }
2766 }
2767 return $string;
2768 }
2769
2770 /**
2771 * Remove bytes that represent an incomplete Unicode character
2772 * at the start of string (e.g. bytes of the char are missing)
2773 *
2774 * @param $string String
2775 * @return string
2776 */
2777 protected function removeBadCharFirst( $string ) {
2778 if ( $string != '' ) {
2779 $char = ord( $string[0] );
2780 if ( $char >= 0x80 && $char < 0xc0 ) {
2781 # We chopped in the middle of a character; remove the whole thing
2782 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2783 }
2784 }
2785 return $string;
2786 }
2787
2788 /**
2789 * Truncate a string of valid HTML to a specified length in bytes,
2790 * appending an optional string (e.g. for ellipses), and return valid HTML
2791 *
2792 * This is only intended for styled/linked text, such as HTML with
2793 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2794 * Also, this will not detect things like "display:none" CSS.
2795 *
2796 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2797 *
2798 * @param string $text HTML string to truncate
2799 * @param int $length (zero/positive) Maximum length (including ellipses)
2800 * @param string $ellipsis String to append to the truncated text
2801 * @return string
2802 */
2803 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2804 # Use the localized ellipsis character
2805 if ( $ellipsis == '...' ) {
2806 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2807 }
2808 # Check if there is clearly no need to truncate
2809 if ( $length <= 0 ) {
2810 return $ellipsis; // no text shown, nothing to format (convention)
2811 } elseif ( strlen( $text ) <= $length ) {
2812 return $text; // string short enough even *with* HTML (short-circuit)
2813 }
2814
2815 $dispLen = 0; // innerHTML legth so far
2816 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2817 $tagType = 0; // 0-open, 1-close
2818 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2819 $entityState = 0; // 0-not entity, 1-entity
2820 $tag = $ret = ''; // accumulated tag name, accumulated result string
2821 $openTags = array(); // open tag stack
2822 $maybeState = null; // possible truncation state
2823
2824 $textLen = strlen( $text );
2825 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2826 for ( $pos = 0; true; ++$pos ) {
2827 # Consider truncation once the display length has reached the maximim.
2828 # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
2829 # Check that we're not in the middle of a bracket/entity...
2830 if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
2831 if ( !$testingEllipsis ) {
2832 $testingEllipsis = true;
2833 # Save where we are; we will truncate here unless there turn out to
2834 # be so few remaining characters that truncation is not necessary.
2835 if ( !$maybeState ) { // already saved? ($neLength = 0 case)
2836 $maybeState = array( $ret, $openTags ); // save state
2837 }
2838 } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
2839 # String in fact does need truncation, the truncation point was OK.
2840 list( $ret, $openTags ) = $maybeState; // reload state
2841 $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
2842 $ret .= $ellipsis; // add ellipsis
2843 break;
2844 }
2845 }
2846 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2847
2848 # Read the next char...
2849 $ch = $text[$pos];
2850 $lastCh = $pos ? $text[$pos - 1] : '';
2851 $ret .= $ch; // add to result string
2852 if ( $ch == '<' ) {
2853 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2854 $entityState = 0; // for bad HTML
2855 $bracketState = 1; // tag started (checking for backslash)
2856 } elseif ( $ch == '>' ) {
2857 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2858 $entityState = 0; // for bad HTML
2859 $bracketState = 0; // out of brackets
2860 } elseif ( $bracketState == 1 ) {
2861 if ( $ch == '/' ) {
2862 $tagType = 1; // close tag (e.g. "</span>")
2863 } else {
2864 $tagType = 0; // open tag (e.g. "<span>")
2865 $tag .= $ch;
2866 }
2867 $bracketState = 2; // building tag name
2868 } elseif ( $bracketState == 2 ) {
2869 if ( $ch != ' ' ) {
2870 $tag .= $ch;
2871 } else {
2872 // Name found (e.g. "<a href=..."), add on tag attributes...
2873 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2874 }
2875 } elseif ( $bracketState == 0 ) {
2876 if ( $entityState ) {
2877 if ( $ch == ';' ) {
2878 $entityState = 0;
2879 $dispLen++; // entity is one displayed char
2880 }
2881 } else {
2882 if ( $neLength == 0 && !$maybeState ) {
2883 // Save state without $ch. We want to *hit* the first
2884 // display char (to get tags) but not *use* it if truncating.
2885 $maybeState = array( substr( $ret, 0, -1 ), $openTags );
2886 }
2887 if ( $ch == '&' ) {
2888 $entityState = 1; // entity found, (e.g. "&#160;")
2889 } else {
2890 $dispLen++; // this char is displayed
2891 // Add the next $max display text chars after this in one swoop...
2892 $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
2893 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
2894 $dispLen += $skipped;
2895 $pos += $skipped;
2896 }
2897 }
2898 }
2899 }
2900 // Close the last tag if left unclosed by bad HTML
2901 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2902 while ( count( $openTags ) > 0 ) {
2903 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2904 }
2905 return $ret;
2906 }
2907
2908 /**
2909 * truncateHtml() helper function
2910 * like strcspn() but adds the skipped chars to $ret
2911 *
2912 * @param $ret
2913 * @param $text
2914 * @param $search
2915 * @param $start
2916 * @param $len
2917 * @return int
2918 */
2919 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2920 if ( $len === null ) {
2921 $len = -1; // -1 means "no limit" for strcspn
2922 } elseif ( $len < 0 ) {
2923 $len = 0; // sanity
2924 }
2925 $skipCount = 0;
2926 if ( $start < strlen( $text ) ) {
2927 $skipCount = strcspn( $text, $search, $start, $len );
2928 $ret .= substr( $text, $start, $skipCount );
2929 }
2930 return $skipCount;
2931 }
2932
2933 /**
2934 * truncateHtml() helper function
2935 * (a) push or pop $tag from $openTags as needed
2936 * (b) clear $tag value
2937 * @param String &$tag Current HTML tag name we are looking at
2938 * @param int $tagType (0-open tag, 1-close tag)
2939 * @param char $lastCh Character before the '>' that ended this tag
2940 * @param array &$openTags Open tag stack (not accounting for $tag)
2941 */
2942 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2943 $tag = ltrim( $tag );
2944 if ( $tag != '' ) {
2945 if ( $tagType == 0 && $lastCh != '/' ) {
2946 $openTags[] = $tag; // tag opened (didn't close itself)
2947 } elseif ( $tagType == 1 ) {
2948 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2949 array_pop( $openTags ); // tag closed
2950 }
2951 }
2952 $tag = '';
2953 }
2954 }
2955
2956 /**
2957 * Grammatical transformations, needed for inflected languages
2958 * Invoked by putting {{grammar:case|word}} in a message
2959 *
2960 * @param $word string
2961 * @param $case string
2962 * @return string
2963 */
2964 function convertGrammar( $word, $case ) {
2965 global $wgGrammarForms;
2966 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2967 return $wgGrammarForms[$this->getCode()][$case][$word];
2968 }
2969 return $word;
2970 }
2971
2972 /**
2973 * Provides an alternative text depending on specified gender.
2974 * Usage {{gender:username|masculine|feminine|neutral}}.
2975 * username is optional, in which case the gender of current user is used,
2976 * but only in (some) interface messages; otherwise default gender is used.
2977 * If second or third parameter are not specified, masculine is used.
2978 * These details may be overriden per language.
2979 *
2980 * @param $gender string
2981 * @param $forms array
2982 *
2983 * @return string
2984 */
2985 function gender( $gender, $forms ) {
2986 if ( !count( $forms ) ) {
2987 return '';
2988 }
2989 $forms = $this->preConvertPlural( $forms, 2 );
2990 if ( $gender === 'male' ) {
2991 return $forms[0];
2992 }
2993 if ( $gender === 'female' ) {
2994 return $forms[1];
2995 }
2996 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2997 }
2998
2999 /**
3000 * Plural form transformations, needed for some languages.
3001 * For example, there are 3 form of plural in Russian and Polish,
3002 * depending on "count mod 10". See [[w:Plural]]
3003 * For English it is pretty simple.
3004 *
3005 * Invoked by putting {{plural:count|wordform1|wordform2}}
3006 * or {{plural:count|wordform1|wordform2|wordform3}}
3007 *
3008 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
3009 *
3010 * @param $count Integer: non-localized number
3011 * @param $forms Array: different plural forms
3012 * @return string Correct form of plural for $count in this language
3013 */
3014 function convertPlural( $count, $forms ) {
3015 if ( !count( $forms ) ) {
3016 return '';
3017 }
3018 $forms = $this->preConvertPlural( $forms, 2 );
3019
3020 return ( $count == 1 ) ? $forms[0] : $forms[1];
3021 }
3022
3023 /**
3024 * Checks that convertPlural was given an array and pads it to requested
3025 * amount of forms by copying the last one.
3026 *
3027 * @param $count Integer: How many forms should there be at least
3028 * @param $forms Array of forms given to convertPlural
3029 * @return array Padded array of forms or an exception if not an array
3030 */
3031 protected function preConvertPlural( /* Array */ $forms, $count ) {
3032 while ( count( $forms ) < $count ) {
3033 $forms[] = $forms[count( $forms ) - 1];
3034 }
3035 return $forms;
3036 }
3037
3038 /**
3039 * This translates the duration ("1 week", "4 days", etc)
3040 * as well as the expiry time (which is an absolute timestamp).
3041 * @param $str String: the validated block duration in English
3042 * @return Somehow translated block duration
3043 * @see LanguageFi.php for example implementation
3044 */
3045 function translateBlockExpiry( $str ) {
3046 $duration = SpecialBlock::getSuggestedDurations( $this );
3047 foreach( $duration as $show => $value ){
3048 if ( strcmp( $str, $value ) == 0 ) {
3049 return htmlspecialchars( trim( $show ) );
3050 }
3051 }
3052
3053 // Since usually only infinite or indefinite is only on list, so try
3054 // equivalents if still here.
3055 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3056 if ( in_array( $str, $indefs ) ) {
3057 foreach( $indefs as $val ) {
3058 $show = array_search( $val, $duration, true );
3059 if ( $show !== false ) {
3060 return htmlspecialchars( trim( $show ) );
3061 }
3062 }
3063 }
3064 // If no duration is given, but a timestamp, display that
3065 return ( strtotime( $str ) ? $this->timeanddate( strtotime( $str ) ) : $str );
3066 }
3067
3068 /**
3069 * languages like Chinese need to be segmented in order for the diff
3070 * to be of any use
3071 *
3072 * @param $text String
3073 * @return String
3074 */
3075 function segmentForDiff( $text ) {
3076 return $text;
3077 }
3078
3079 /**
3080 * and unsegment to show the result
3081 *
3082 * @param $text String
3083 * @return String
3084 */
3085 function unsegmentForDiff( $text ) {
3086 return $text;
3087 }
3088
3089 /**
3090 * convert text to all supported variants
3091 *
3092 * @param $text string
3093 * @return array
3094 */
3095 function autoConvertToAllVariants( $text ) {
3096 return $this->mConverter->autoConvertToAllVariants( $text );
3097 }
3098
3099 /**
3100 * convert text to different variants of a language.
3101 *
3102 * @param $text string
3103 * @return string
3104 */
3105 function convert( $text ) {
3106 return $this->mConverter->convert( $text );
3107 }
3108
3109
3110 /**
3111 * Convert a Title object to a string in the preferred variant
3112 *
3113 * @param $title Title
3114 * @return string
3115 */
3116 function convertTitle( $title ) {
3117 return $this->mConverter->convertTitle( $title );
3118 }
3119
3120 /**
3121 * Check if this is a language with variants
3122 *
3123 * @return bool
3124 */
3125 function hasVariants() {
3126 return sizeof( $this->getVariants() ) > 1;
3127 }
3128
3129 /**
3130 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3131 *
3132 * @param $text string
3133 * @return string
3134 */
3135 function armourMath( $text ) {
3136 return $this->mConverter->armourMath( $text );
3137 }
3138
3139 /**
3140 * Perform output conversion on a string, and encode for safe HTML output.
3141 * @param $text String text to be converted
3142 * @param $isTitle Bool whether this conversion is for the article title
3143 * @return string
3144 * @todo this should get integrated somewhere sane
3145 */
3146 function convertHtml( $text, $isTitle = false ) {
3147 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3148 }
3149
3150 /**
3151 * @param $key string
3152 * @return string
3153 */
3154 function convertCategoryKey( $key ) {
3155 return $this->mConverter->convertCategoryKey( $key );
3156 }
3157
3158 /**
3159 * Get the list of variants supported by this language
3160 * see sample implementation in LanguageZh.php
3161 *
3162 * @return array an array of language codes
3163 */
3164 function getVariants() {
3165 return $this->mConverter->getVariants();
3166 }
3167
3168 /**
3169 * @return string
3170 */
3171 function getPreferredVariant() {
3172 return $this->mConverter->getPreferredVariant();
3173 }
3174
3175 /**
3176 * @return string
3177 */
3178 function getDefaultVariant() {
3179 return $this->mConverter->getDefaultVariant();
3180 }
3181
3182 /**
3183 * @return string
3184 */
3185 function getURLVariant() {
3186 return $this->mConverter->getURLVariant();
3187 }
3188
3189 /**
3190 * If a language supports multiple variants, it is
3191 * possible that non-existing link in one variant
3192 * actually exists in another variant. this function
3193 * tries to find it. See e.g. LanguageZh.php
3194 *
3195 * @param $link String: the name of the link
3196 * @param $nt Mixed: the title object of the link
3197 * @param $ignoreOtherCond Boolean: to disable other conditions when
3198 * we need to transclude a template or update a category's link
3199 * @return null the input parameters may be modified upon return
3200 */
3201 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3202 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3203 }
3204
3205 /**
3206 * If a language supports multiple variants, converts text
3207 * into an array of all possible variants of the text:
3208 * 'variant' => text in that variant
3209 *
3210 * @deprecated since 1.17 Use autoConvertToAllVariants()
3211 *
3212 * @param $text string
3213 *
3214 * @return string
3215 */
3216 function convertLinkToAllVariants( $text ) {
3217 return $this->mConverter->convertLinkToAllVariants( $text );
3218 }
3219
3220 /**
3221 * returns language specific options used by User::getPageRenderHash()
3222 * for example, the preferred language variant
3223 *
3224 * @return string
3225 */
3226 function getExtraHashOptions() {
3227 return $this->mConverter->getExtraHashOptions();
3228 }
3229
3230 /**
3231 * For languages that support multiple variants, the title of an
3232 * article may be displayed differently in different variants. this
3233 * function returns the apporiate title defined in the body of the article.
3234 *
3235 * @return string
3236 */
3237 function getParsedTitle() {
3238 return $this->mConverter->getParsedTitle();
3239 }
3240
3241 /**
3242 * Enclose a string with the "no conversion" tag. This is used by
3243 * various functions in the Parser
3244 *
3245 * @param $text String: text to be tagged for no conversion
3246 * @param $noParse bool
3247 * @return string the tagged text
3248 */
3249 function markNoConversion( $text, $noParse = false ) {
3250 return $this->mConverter->markNoConversion( $text, $noParse );
3251 }
3252
3253 /**
3254 * A regular expression to match legal word-trailing characters
3255 * which should be merged onto a link of the form [[foo]]bar.
3256 *
3257 * @return string
3258 */
3259 function linkTrail() {
3260 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3261 }
3262
3263 /**
3264 * @return Language
3265 */
3266 function getLangObj() {
3267 return $this;
3268 }
3269
3270 /**
3271 * Get the RFC 3066 code for this language object
3272 *
3273 * @return string
3274 */
3275 function getCode() {
3276 return $this->mCode;
3277 }
3278
3279 /**
3280 * @param $code string
3281 */
3282 function setCode( $code ) {
3283 $this->mCode = $code;
3284 }
3285
3286 /**
3287 * Get the name of a file for a certain language code
3288 * @param $prefix string Prepend this to the filename
3289 * @param $code string Language code
3290 * @param $suffix string Append this to the filename
3291 * @return string $prefix . $mangledCode . $suffix
3292 */
3293 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3294 // Protect against path traversal
3295 if ( !Language::isValidCode( $code )
3296 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3297 {
3298 throw new MWException( "Invalid language code \"$code\"" );
3299 }
3300
3301 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3302 }
3303
3304 /**
3305 * Get the language code from a file name. Inverse of getFileName()
3306 * @param $filename string $prefix . $languageCode . $suffix
3307 * @param $prefix string Prefix before the language code
3308 * @param $suffix string Suffix after the language code
3309 * @return string Language code, or false if $prefix or $suffix isn't found
3310 */
3311 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3312 $m = null;
3313 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3314 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3315 if ( !count( $m ) ) {
3316 return false;
3317 }
3318 return str_replace( '_', '-', strtolower( $m[1] ) );
3319 }
3320
3321 /**
3322 * @param $code string
3323 * @return string
3324 */
3325 static function getMessagesFileName( $code ) {
3326 global $IP;
3327 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3328 }
3329
3330 /**
3331 * @param $code string
3332 * @return string
3333 */
3334 static function getClassFileName( $code ) {
3335 global $IP;
3336 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3337 }
3338
3339 /**
3340 * Get the first fallback for a given language.
3341 *
3342 * @param $code string
3343 *
3344 * @return false|string
3345 */
3346 static function getFallbackFor( $code ) {
3347 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3348 return false;
3349 } else {
3350 $fallbacks = self::getFallbacksFor( $code );
3351 $first = array_shift( $fallbacks );
3352 return $first;
3353 }
3354 }
3355
3356 /**
3357 * Get the ordered list of fallback languages.
3358 *
3359 * @since 1.19
3360 * @param $code string Language code
3361 * @return array
3362 */
3363 static function getFallbacksFor( $code ) {
3364 if ( $code === 'en' || !Language::isValidBuiltInCode( $code ) ) {
3365 return array();
3366 } else {
3367 $v = self::getLocalisationCache()->getItem( $code, 'fallback' );
3368 $v = array_map( 'trim', explode( ',', $v ) );
3369 if ( $v[count( $v ) - 1] !== 'en' ) {
3370 $v[] = 'en';
3371 }
3372 return $v;
3373 }
3374 }
3375
3376 /**
3377 * Get all messages for a given language
3378 * WARNING: this may take a long time. If you just need all message *keys*
3379 * but need the *contents* of only a few messages, consider using getMessageKeysFor().
3380 *
3381 * @param $code string
3382 *
3383 * @return array
3384 */
3385 static function getMessagesFor( $code ) {
3386 return self::getLocalisationCache()->getItem( $code, 'messages' );
3387 }
3388
3389 /**
3390 * Get a message for a given language
3391 *
3392 * @param $key string
3393 * @param $code string
3394 *
3395 * @return string
3396 */
3397 static function getMessageFor( $key, $code ) {
3398 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3399 }
3400
3401 /**
3402 * Get all message keys for a given language. This is a faster alternative to
3403 * array_keys( Language::getMessagesFor( $code ) )
3404 * @param $code string Language code
3405 * @return array of message keys (strings)
3406 */
3407 static function getMessageKeysFor( $code ) {
3408 return self::getLocalisationCache()->getSubItemList( $code, 'messages' );
3409 }
3410
3411 /**
3412 * @param $talk
3413 * @return mixed
3414 */
3415 function fixVariableInNamespace( $talk ) {
3416 if ( strpos( $talk, '$1' ) === false ) {
3417 return $talk;
3418 }
3419
3420 global $wgMetaNamespace;
3421 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3422
3423 # Allow grammar transformations
3424 # Allowing full message-style parsing would make simple requests
3425 # such as action=raw much more expensive than they need to be.
3426 # This will hopefully cover most cases.
3427 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3428 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3429 return str_replace( ' ', '_', $talk );
3430 }
3431
3432 /**
3433 * @param $m string
3434 * @return string
3435 */
3436 function replaceGrammarInNamespace( $m ) {
3437 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3438 }
3439
3440 /**
3441 * @throws MWException
3442 * @return array
3443 */
3444 static function getCaseMaps() {
3445 static $wikiUpperChars, $wikiLowerChars;
3446 if ( isset( $wikiUpperChars ) ) {
3447 return array( $wikiUpperChars, $wikiLowerChars );
3448 }
3449
3450 wfProfileIn( __METHOD__ );
3451 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3452 if ( $arr === false ) {
3453 throw new MWException(
3454 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3455 }
3456 $wikiUpperChars = $arr['wikiUpperChars'];
3457 $wikiLowerChars = $arr['wikiLowerChars'];
3458 wfProfileOut( __METHOD__ );
3459 return array( $wikiUpperChars, $wikiLowerChars );
3460 }
3461
3462 /**
3463 * Decode an expiry (block, protection, etc) which has come from the DB
3464 *
3465 * @param $expiry String: Database expiry String
3466 * @param $format Bool|Int true to process using language functions, or TS_ constant
3467 * to return the expiry in a given timestamp
3468 * @return String
3469 */
3470 public function formatExpiry( $expiry, $format = true ) {
3471 static $infinity, $infinityMsg;
3472 if( $infinity === null ){
3473 $infinityMsg = wfMessage( 'infiniteblock' );
3474 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3475 }
3476
3477 if ( $expiry == '' || $expiry == $infinity ) {
3478 return $format === true
3479 ? $infinityMsg
3480 : $infinity;
3481 } else {
3482 return $format === true
3483 ? $this->timeanddate( $expiry )
3484 : wfTimestamp( $format, $expiry );
3485 }
3486 }
3487
3488 /**
3489 * @todo Document
3490 * @param $seconds int|float
3491 * @param $format String Optional, one of ("avoidseconds","avoidminutes"):
3492 * "avoidseconds" - don't mention seconds if $seconds >= 1 hour
3493 * "avoidminutes" - don't mention seconds/minutes if $seconds > 48 hours
3494 * @return string
3495 */
3496 function formatTimePeriod( $seconds, $format = false ) {
3497 if ( round( $seconds * 10 ) < 100 ) {
3498 $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
3499 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3500 } elseif ( round( $seconds ) < 60 ) {
3501 $s = $this->formatNum( round( $seconds ) );
3502 $s .= $this->getMessageFromDB( 'seconds-abbrev' );
3503 } elseif ( round( $seconds ) < 3600 ) {
3504 $minutes = floor( $seconds / 60 );
3505 $secondsPart = round( fmod( $seconds, 60 ) );
3506 if ( $secondsPart == 60 ) {
3507 $secondsPart = 0;
3508 $minutes++;
3509 }
3510 $s = $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3511 $s .= ' ';
3512 $s .= $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3513 } elseif ( round( $seconds ) <= 2*86400 ) {
3514 $hours = floor( $seconds / 3600 );
3515 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3516 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3517 if ( $secondsPart == 60 ) {
3518 $secondsPart = 0;
3519 $minutes++;
3520 }
3521 if ( $minutes == 60 ) {
3522 $minutes = 0;
3523 $hours++;
3524 }
3525 $s = $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3526 $s .= ' ';
3527 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3528 if ( !in_array( $format, array( 'avoidseconds', 'avoidminutes' ) ) ) {
3529 $s .= ' ' . $this->formatNum( $secondsPart ) .
3530 $this->getMessageFromDB( 'seconds-abbrev' );
3531 }
3532 } else {
3533 $days = floor( $seconds / 86400 );
3534 if ( $format === 'avoidminutes' ) {
3535 $hours = round( ( $seconds - $days * 86400 ) / 3600 );
3536 if ( $hours == 24 ) {
3537 $hours = 0;
3538 $days++;
3539 }
3540 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3541 $s .= ' ';
3542 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3543 } elseif ( $format === 'avoidseconds' ) {
3544 $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
3545 $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
3546 if ( $minutes == 60 ) {
3547 $minutes = 0;
3548 $hours++;
3549 }
3550 if ( $hours == 24 ) {
3551 $hours = 0;
3552 $days++;
3553 }
3554 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3555 $s .= ' ';
3556 $s .= $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' );
3557 $s .= ' ';
3558 $s .= $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' );
3559 } else {
3560 $s = $this->formatNum( $days ) . $this->getMessageFromDB( 'days-abbrev' );
3561 $s .= ' ';
3562 $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
3563 }
3564 }
3565 return $s;
3566 }
3567
3568 /**
3569 * @param $bps int
3570 * @return string
3571 */
3572 function formatBitrate( $bps ) {
3573 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3574 if ( $bps <= 0 ) {
3575 return $this->formatNum( $bps ) . $units[0];
3576 }
3577 $unitIndex = floor( log10( $bps ) / 3 );
3578 $mantissa = $bps / pow( 1000, $unitIndex );
3579 if ( $mantissa < 10 ) {
3580 $mantissa = round( $mantissa, 1 );
3581 } else {
3582 $mantissa = round( $mantissa );
3583 }
3584 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3585 }
3586
3587 /**
3588 * Format a size in bytes for output, using an appropriate
3589 * unit (B, KB, MB or GB) according to the magnitude in question
3590 *
3591 * @param $size int Size to format
3592 * @return string Plain text (not HTML)
3593 */
3594 function formatSize( $size ) {
3595 // For small sizes no decimal places necessary
3596 $round = 0;
3597 if ( $size > 1024 ) {
3598 $size = $size / 1024;
3599 if ( $size > 1024 ) {
3600 $size = $size / 1024;
3601 // For MB and bigger two decimal places are smarter
3602 $round = 2;
3603 if ( $size > 1024 ) {
3604 $size = $size / 1024;
3605 $msg = 'size-gigabytes';
3606 } else {
3607 $msg = 'size-megabytes';
3608 }
3609 } else {
3610 $msg = 'size-kilobytes';
3611 }
3612 } else {
3613 $msg = 'size-bytes';
3614 }
3615 $size = round( $size, $round );
3616 $text = $this->getMessageFromDB( $msg );
3617 return str_replace( '$1', $this->formatNum( $size ), $text );
3618 }
3619
3620 /**
3621 * Get the conversion rule title, if any.
3622 *
3623 * @return string
3624 */
3625 function getConvRuleTitle() {
3626 return $this->mConverter->getConvRuleTitle();
3627 }
3628 }