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