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