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