Localisation updates for core and extension messages from translatewiki.net (2011...
[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 # Note that if wgOutputEncoding is different from
2241 # wgInputEncoding, this text will be further converted
2242 # to wgOutputEncoding.
2243 global $wgEditEncoding;
2244 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
2245 return $s;
2246 } else {
2247 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
2248 }
2249 }
2250
2251 /**
2252 * @param $s string
2253 * @return string
2254 */
2255 function recodeInput( $s ) {
2256 # Take the previous into account.
2257 global $wgEditEncoding;
2258 if ( $wgEditEncoding != '' ) {
2259 $enc = $wgEditEncoding;
2260 } else {
2261 $enc = 'UTF-8';
2262 }
2263 if ( $enc == 'UTF-8' ) {
2264 return $s;
2265 } else {
2266 return $this->iconv( $enc, 'UTF-8', $s );
2267 }
2268 }
2269
2270 /**
2271 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
2272 * also cleans up certain backwards-compatible sequences, converting them
2273 * to the modern Unicode equivalent.
2274 *
2275 * This is language-specific for performance reasons only.
2276 *
2277 * @param $s string
2278 *
2279 * @return string
2280 */
2281 function normalize( $s ) {
2282 global $wgAllUnicodeFixes;
2283 $s = UtfNormal::cleanUp( $s );
2284 if ( $wgAllUnicodeFixes ) {
2285 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
2286 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
2287 }
2288
2289 return $s;
2290 }
2291
2292 /**
2293 * Transform a string using serialized data stored in the given file (which
2294 * must be in the serialized subdirectory of $IP). The file contains pairs
2295 * mapping source characters to destination characters.
2296 *
2297 * The data is cached in process memory. This will go faster if you have the
2298 * FastStringSearch extension.
2299 *
2300 * @param $file string
2301 * @param $string string
2302 *
2303 * @return string
2304 */
2305 function transformUsingPairFile( $file, $string ) {
2306 if ( !isset( $this->transformData[$file] ) ) {
2307 $data = wfGetPrecompiledData( $file );
2308 if ( $data === false ) {
2309 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
2310 }
2311 $this->transformData[$file] = new ReplacementArray( $data );
2312 }
2313 return $this->transformData[$file]->replace( $string );
2314 }
2315
2316 /**
2317 * For right-to-left language support
2318 *
2319 * @return bool
2320 */
2321 function isRTL() {
2322 return self::$dataCache->getItem( $this->mCode, 'rtl' );
2323 }
2324
2325 /**
2326 * Return the correct HTML 'dir' attribute value for this language.
2327 * @return String
2328 */
2329 function getDir() {
2330 return $this->isRTL() ? 'rtl' : 'ltr';
2331 }
2332
2333 /**
2334 * Return 'left' or 'right' as appropriate alignment for line-start
2335 * for this language's text direction.
2336 *
2337 * Should be equivalent to CSS3 'start' text-align value....
2338 *
2339 * @return String
2340 */
2341 function alignStart() {
2342 return $this->isRTL() ? 'right' : 'left';
2343 }
2344
2345 /**
2346 * Return 'right' or 'left' as appropriate alignment for line-end
2347 * for this language's text direction.
2348 *
2349 * Should be equivalent to CSS3 'end' text-align value....
2350 *
2351 * @return String
2352 */
2353 function alignEnd() {
2354 return $this->isRTL() ? 'left' : 'right';
2355 }
2356
2357 /**
2358 * A hidden direction mark (LRM or RLM), depending on the language direction
2359 *
2360 * @return string
2361 */
2362 function getDirMark() {
2363 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
2364 }
2365
2366 /**
2367 * @return array
2368 */
2369 function capitalizeAllNouns() {
2370 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2371 }
2372
2373 /**
2374 * An arrow, depending on the language direction
2375 *
2376 * @return string
2377 */
2378 function getArrow() {
2379 return $this->isRTL() ? '←' : '→';
2380 }
2381
2382 /**
2383 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2384 *
2385 * @return bool
2386 */
2387 function linkPrefixExtension() {
2388 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2389 }
2390
2391 /**
2392 * @return array
2393 */
2394 function getMagicWords() {
2395 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2396 }
2397
2398 protected function doMagicHook() {
2399 if ( $this->mMagicHookDone ) {
2400 return;
2401 }
2402 $this->mMagicHookDone = true;
2403 wfProfileIn( 'LanguageGetMagic' );
2404 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2405 wfProfileOut( 'LanguageGetMagic' );
2406 }
2407
2408 /**
2409 * Fill a MagicWord object with data from here
2410 *
2411 * @param $mw
2412 */
2413 function getMagic( $mw ) {
2414 $this->doMagicHook();
2415
2416 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2417 $rawEntry = $this->mMagicExtensions[$mw->mId];
2418 } else {
2419 $magicWords = $this->getMagicWords();
2420 if ( isset( $magicWords[$mw->mId] ) ) {
2421 $rawEntry = $magicWords[$mw->mId];
2422 } else {
2423 $rawEntry = false;
2424 }
2425 }
2426
2427 if ( !is_array( $rawEntry ) ) {
2428 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2429 } else {
2430 $mw->mCaseSensitive = $rawEntry[0];
2431 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2432 }
2433 }
2434
2435 /**
2436 * Add magic words to the extension array
2437 *
2438 * @param $newWords array
2439 */
2440 function addMagicWordsByLang( $newWords ) {
2441 $code = $this->getCode();
2442 $fallbackChain = array();
2443 while ( $code && !in_array( $code, $fallbackChain ) ) {
2444 $fallbackChain[] = $code;
2445 $code = self::getFallbackFor( $code );
2446 }
2447 if ( !in_array( 'en', $fallbackChain ) ) {
2448 $fallbackChain[] = 'en';
2449 }
2450 $fallbackChain = array_reverse( $fallbackChain );
2451 foreach ( $fallbackChain as $code ) {
2452 if ( isset( $newWords[$code] ) ) {
2453 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2454 }
2455 }
2456 }
2457
2458 /**
2459 * Get special page names, as an associative array
2460 * case folded alias => real name
2461 */
2462 function getSpecialPageAliases() {
2463 // Cache aliases because it may be slow to load them
2464 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2465 // Initialise array
2466 $this->mExtendedSpecialPageAliases =
2467 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2468 wfRunHooks( 'LanguageGetSpecialPageAliases',
2469 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2470 }
2471
2472 return $this->mExtendedSpecialPageAliases;
2473 }
2474
2475 /**
2476 * Italic is unsuitable for some languages
2477 *
2478 * @param $text String: the text to be emphasized.
2479 * @return string
2480 */
2481 function emphasize( $text ) {
2482 return "<em>$text</em>";
2483 }
2484
2485 /**
2486 * Normally we output all numbers in plain en_US style, that is
2487 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2488 * point twohundredthirtyfive. However this is not sutable for all
2489 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2490 * Icelandic just want to use commas instead of dots, and dots instead
2491 * of commas like "293.291,235".
2492 *
2493 * An example of this function being called:
2494 * <code>
2495 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2496 * </code>
2497 *
2498 * See LanguageGu.php for the Gujarati implementation and
2499 * $separatorTransformTable on MessageIs.php for
2500 * the , => . and . => , implementation.
2501 *
2502 * @todo check if it's viable to use localeconv() for the decimal
2503 * separator thing.
2504 * @param $number Mixed: the string to be formatted, should be an integer
2505 * or a floating point number.
2506 * @param $nocommafy Bool: set to true for special numbers like dates
2507 * @return string
2508 */
2509 function formatNum( $number, $nocommafy = false ) {
2510 global $wgTranslateNumerals;
2511 if ( !$nocommafy ) {
2512 $number = $this->commafy( $number );
2513 $s = $this->separatorTransformTable();
2514 if ( $s ) {
2515 $number = strtr( $number, $s );
2516 }
2517 }
2518
2519 if ( $wgTranslateNumerals ) {
2520 $s = $this->digitTransformTable();
2521 if ( $s ) {
2522 $number = strtr( $number, $s );
2523 }
2524 }
2525
2526 return $number;
2527 }
2528
2529 /**
2530 * @param $number string
2531 * @return string
2532 */
2533 function parseFormattedNumber( $number ) {
2534 $s = $this->digitTransformTable();
2535 if ( $s ) {
2536 $number = strtr( $number, array_flip( $s ) );
2537 }
2538
2539 $s = $this->separatorTransformTable();
2540 if ( $s ) {
2541 $number = strtr( $number, array_flip( $s ) );
2542 }
2543
2544 $number = strtr( $number, array( ',' => '' ) );
2545 return $number;
2546 }
2547
2548 /**
2549 * Adds commas to a given number
2550 *
2551 * @param $_ mixed
2552 * @return string
2553 */
2554 function commafy( $_ ) {
2555 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2556 }
2557
2558 /**
2559 * @return array
2560 */
2561 function digitTransformTable() {
2562 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2563 }
2564
2565 /**
2566 * @return array
2567 */
2568 function separatorTransformTable() {
2569 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2570 }
2571
2572 /**
2573 * Take a list of strings and build a locale-friendly comma-separated
2574 * list, using the local comma-separator message.
2575 * The last two strings are chained with an "and".
2576 *
2577 * @param $l Array
2578 * @return string
2579 */
2580 function listToText( $l ) {
2581 $s = '';
2582 $m = count( $l ) - 1;
2583 if ( $m == 1 ) {
2584 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2585 } else {
2586 for ( $i = $m; $i >= 0; $i-- ) {
2587 if ( $i == $m ) {
2588 $s = $l[$i];
2589 } else if ( $i == $m - 1 ) {
2590 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2591 } else {
2592 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2593 }
2594 }
2595 return $s;
2596 }
2597 }
2598
2599 /**
2600 * Take a list of strings and build a locale-friendly comma-separated
2601 * list, using the local comma-separator message.
2602 * @param $list array of strings to put in a comma list
2603 * @return string
2604 */
2605 function commaList( $list ) {
2606 return implode(
2607 $list,
2608 wfMsgExt(
2609 'comma-separator',
2610 array( 'parsemag', 'escapenoentities', 'language' => $this )
2611 )
2612 );
2613 }
2614
2615 /**
2616 * Take a list of strings and build a locale-friendly semicolon-separated
2617 * list, using the local semicolon-separator message.
2618 * @param $list array of strings to put in a semicolon list
2619 * @return string
2620 */
2621 function semicolonList( $list ) {
2622 return implode(
2623 $list,
2624 wfMsgExt(
2625 'semicolon-separator',
2626 array( 'parsemag', 'escapenoentities', 'language' => $this )
2627 )
2628 );
2629 }
2630
2631 /**
2632 * Same as commaList, but separate it with the pipe instead.
2633 * @param $list array of strings to put in a pipe list
2634 * @return string
2635 */
2636 function pipeList( $list ) {
2637 return implode(
2638 $list,
2639 wfMsgExt(
2640 'pipe-separator',
2641 array( 'escapenoentities', 'language' => $this )
2642 )
2643 );
2644 }
2645
2646 /**
2647 * Truncate a string to a specified length in bytes, appending an optional
2648 * string (e.g. for ellipses)
2649 *
2650 * The database offers limited byte lengths for some columns in the database;
2651 * multi-byte character sets mean we need to ensure that only whole characters
2652 * are included, otherwise broken characters can be passed to the user
2653 *
2654 * If $length is negative, the string will be truncated from the beginning
2655 *
2656 * @param $string String to truncate
2657 * @param $length Int: maximum length (including ellipses)
2658 * @param $ellipsis String to append to the truncated text
2659 * @param $adjustLength Boolean: Subtract length of ellipsis from $length.
2660 * $adjustLength was introduced in 1.18, before that behaved as if false.
2661 * @return string
2662 */
2663 function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
2664 # Use the localized ellipsis character
2665 if ( $ellipsis == '...' ) {
2666 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2667 }
2668 # Check if there is no need to truncate
2669 if ( $length == 0 ) {
2670 return $ellipsis; // convention
2671 } elseif ( strlen( $string ) <= abs( $length ) ) {
2672 return $string; // no need to truncate
2673 }
2674 $stringOriginal = $string;
2675 # If ellipsis length is >= $length then we can't apply $adjustLength
2676 if ( $adjustLength && strlen( $ellipsis ) >= abs( $length ) ) {
2677 $string = $ellipsis; // this can be slightly unexpected
2678 # Otherwise, truncate and add ellipsis...
2679 } else {
2680 $eLength = $adjustLength ? strlen( $ellipsis ) : 0;
2681 if ( $length > 0 ) {
2682 $length -= $eLength;
2683 $string = substr( $string, 0, $length ); // xyz...
2684 $string = $this->removeBadCharLast( $string );
2685 $string = $string . $ellipsis;
2686 } else {
2687 $length += $eLength;
2688 $string = substr( $string, $length ); // ...xyz
2689 $string = $this->removeBadCharFirst( $string );
2690 $string = $ellipsis . $string;
2691 }
2692 }
2693 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181).
2694 # This check is *not* redundant if $adjustLength, due to the single case where
2695 # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
2696 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2697 return $string;
2698 } else {
2699 return $stringOriginal;
2700 }
2701 }
2702
2703 /**
2704 * Remove bytes that represent an incomplete Unicode character
2705 * at the end of string (e.g. bytes of the char are missing)
2706 *
2707 * @param $string String
2708 * @return string
2709 */
2710 protected function removeBadCharLast( $string ) {
2711 if ( $string != '' ) {
2712 $char = ord( $string[strlen( $string ) - 1] );
2713 $m = array();
2714 if ( $char >= 0xc0 ) {
2715 # We got the first byte only of a multibyte char; remove it.
2716 $string = substr( $string, 0, -1 );
2717 } elseif ( $char >= 0x80 &&
2718 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2719 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2720 {
2721 # We chopped in the middle of a character; remove it
2722 $string = $m[1];
2723 }
2724 }
2725 return $string;
2726 }
2727
2728 /**
2729 * Remove bytes that represent an incomplete Unicode character
2730 * at the start of string (e.g. bytes of the char are missing)
2731 *
2732 * @param $string String
2733 * @return string
2734 */
2735 protected function removeBadCharFirst( $string ) {
2736 if ( $string != '' ) {
2737 $char = ord( $string[0] );
2738 if ( $char >= 0x80 && $char < 0xc0 ) {
2739 # We chopped in the middle of a character; remove the whole thing
2740 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2741 }
2742 }
2743 return $string;
2744 }
2745
2746 /**
2747 * Truncate a string of valid HTML to a specified length in bytes,
2748 * appending an optional string (e.g. for ellipses), and return valid HTML
2749 *
2750 * This is only intended for styled/linked text, such as HTML with
2751 * tags like <span> and <a>, were the tags are self-contained (valid HTML).
2752 * Also, this will not detect things like "display:none" CSS.
2753 *
2754 * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
2755 *
2756 * @param string $text HTML string to truncate
2757 * @param int $length (zero/positive) Maximum length (including ellipses)
2758 * @param string $ellipsis String to append to the truncated text
2759 * @return string
2760 */
2761 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2762 # Use the localized ellipsis character
2763 if ( $ellipsis == '...' ) {
2764 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2765 }
2766 # Check if there is clearly no need to truncate
2767 if ( $length <= 0 ) {
2768 return $ellipsis; // no text shown, nothing to format (convention)
2769 } elseif ( strlen( $text ) <= $length ) {
2770 return $text; // string short enough even *with* HTML (short-circuit)
2771 }
2772
2773 $displayLen = 0; // innerHTML legth so far
2774 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2775 $tagType = 0; // 0-open, 1-close
2776 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2777 $entityState = 0; // 0-not entity, 1-entity
2778 $tag = $ret = $pRet = ''; // accumulated tag name, accumulated result string
2779 $openTags = array(); // open tag stack
2780 $pOpenTags = array();
2781
2782 $textLen = strlen( $text );
2783 $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
2784 for ( $pos = 0; true; ++$pos ) {
2785 # Consider truncation once the display length has reached the maximim.
2786 # Check that we're not in the middle of a bracket/entity...
2787 if ( $displayLen >= $neLength && $bracketState == 0 && $entityState == 0 ) {
2788 if ( !$testingEllipsis ) {
2789 $testingEllipsis = true;
2790 # Save where we are; we will truncate here unless there turn out to
2791 # be so few remaining characters that truncation is not necessary.
2792 $pOpenTags = $openTags; // save state
2793 $pRet = $ret; // save state
2794 } elseif ( $displayLen > $length && $displayLen > strlen( $ellipsis ) ) {
2795 # String in fact does need truncation, the truncation point was OK.
2796 $openTags = $pOpenTags; // reload state
2797 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2798 $ret .= $ellipsis; // add ellipsis
2799 break;
2800 }
2801 }
2802 if ( $pos >= $textLen ) break; // extra iteration just for above checks
2803
2804 # Read the next char...
2805 $ch = $text[$pos];
2806 $lastCh = $pos ? $text[$pos - 1] : '';
2807 $ret .= $ch; // add to result string
2808 if ( $ch == '<' ) {
2809 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2810 $entityState = 0; // for bad HTML
2811 $bracketState = 1; // tag started (checking for backslash)
2812 } elseif ( $ch == '>' ) {
2813 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2814 $entityState = 0; // for bad HTML
2815 $bracketState = 0; // out of brackets
2816 } elseif ( $bracketState == 1 ) {
2817 if ( $ch == '/' ) {
2818 $tagType = 1; // close tag (e.g. "</span>")
2819 } else {
2820 $tagType = 0; // open tag (e.g. "<span>")
2821 $tag .= $ch;
2822 }
2823 $bracketState = 2; // building tag name
2824 } elseif ( $bracketState == 2 ) {
2825 if ( $ch != ' ' ) {
2826 $tag .= $ch;
2827 } else {
2828 // Name found (e.g. "<a href=..."), add on tag attributes...
2829 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2830 }
2831 } elseif ( $bracketState == 0 ) {
2832 if ( $entityState ) {
2833 if ( $ch == ';' ) {
2834 $entityState = 0;
2835 $displayLen++; // entity is one displayed char
2836 }
2837 } else {
2838 if ( $ch == '&' ) {
2839 $entityState = 1; // entity found, (e.g. "&#160;")
2840 } else {
2841 $displayLen++; // this char is displayed
2842 // Add the next $max display text chars after this in one swoop...
2843 $max = ( $testingEllipsis ? $length : $neLength ) - $displayLen;
2844 $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
2845 $displayLen += $skipped;
2846 $pos += $skipped;
2847 }
2848 }
2849 }
2850 }
2851 if ( $displayLen == 0 ) {
2852 return ''; // no text shown, nothing to format
2853 }
2854 // Close the last tag if left unclosed by bad HTML
2855 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2856 while ( count( $openTags ) > 0 ) {
2857 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2858 }
2859 return $ret;
2860 }
2861
2862 /**
2863 * truncateHtml() helper function
2864 * like strcspn() but adds the skipped chars to $ret
2865 *
2866 * @param $ret
2867 * @param $text
2868 * @param $search
2869 * @param $start
2870 * @param $len
2871 * @return int
2872 */
2873 private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
2874 if ( $len === null ) {
2875 $len = -1; // -1 means "no limit" for strcspn
2876 } elseif ( $len < 0 ) {
2877 $len = 0; // sanity
2878 }
2879 $skipCount = 0;
2880 if ( $start < strlen( $text ) ) {
2881 $skipCount = strcspn( $text, $search, $start, $len );
2882 $ret .= substr( $text, $start, $skipCount );
2883 }
2884 return $skipCount;
2885 }
2886
2887 /**
2888 * truncateHtml() helper function
2889 * (a) push or pop $tag from $openTags as needed
2890 * (b) clear $tag value
2891 * @param String &$tag Current HTML tag name we are looking at
2892 * @param int $tagType (0-open tag, 1-close tag)
2893 * @param char $lastCh Character before the '>' that ended this tag
2894 * @param array &$openTags Open tag stack (not accounting for $tag)
2895 */
2896 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2897 $tag = ltrim( $tag );
2898 if ( $tag != '' ) {
2899 if ( $tagType == 0 && $lastCh != '/' ) {
2900 $openTags[] = $tag; // tag opened (didn't close itself)
2901 } else if ( $tagType == 1 ) {
2902 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2903 array_pop( $openTags ); // tag closed
2904 }
2905 }
2906 $tag = '';
2907 }
2908 }
2909
2910 /**
2911 * Grammatical transformations, needed for inflected languages
2912 * Invoked by putting {{grammar:case|word}} in a message
2913 *
2914 * @param $word string
2915 * @param $case string
2916 * @return string
2917 */
2918 function convertGrammar( $word, $case ) {
2919 global $wgGrammarForms;
2920 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2921 return $wgGrammarForms[$this->getCode()][$case][$word];
2922 }
2923 return $word;
2924 }
2925
2926 /**
2927 * Provides an alternative text depending on specified gender.
2928 * Usage {{gender:username|masculine|feminine|neutral}}.
2929 * username is optional, in which case the gender of current user is used,
2930 * but only in (some) interface messages; otherwise default gender is used.
2931 * If second or third parameter are not specified, masculine is used.
2932 * These details may be overriden per language.
2933 *
2934 * @param $gender string
2935 * @param $forms array
2936 *
2937 * @return string
2938 */
2939 function gender( $gender, $forms ) {
2940 if ( !count( $forms ) ) {
2941 return '';
2942 }
2943 $forms = $this->preConvertPlural( $forms, 2 );
2944 if ( $gender === 'male' ) {
2945 return $forms[0];
2946 }
2947 if ( $gender === 'female' ) {
2948 return $forms[1];
2949 }
2950 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2951 }
2952
2953 /**
2954 * Plural form transformations, needed for some languages.
2955 * For example, there are 3 form of plural in Russian and Polish,
2956 * depending on "count mod 10". See [[w:Plural]]
2957 * For English it is pretty simple.
2958 *
2959 * Invoked by putting {{plural:count|wordform1|wordform2}}
2960 * or {{plural:count|wordform1|wordform2|wordform3}}
2961 *
2962 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2963 *
2964 * @param $count Integer: non-localized number
2965 * @param $forms Array: different plural forms
2966 * @return string Correct form of plural for $count in this language
2967 */
2968 function convertPlural( $count, $forms ) {
2969 if ( !count( $forms ) ) {
2970 return '';
2971 }
2972 $forms = $this->preConvertPlural( $forms, 2 );
2973
2974 return ( $count == 1 ) ? $forms[0] : $forms[1];
2975 }
2976
2977 /**
2978 * Checks that convertPlural was given an array and pads it to requested
2979 * amount of forms by copying the last one.
2980 *
2981 * @param $count Integer: How many forms should there be at least
2982 * @param $forms Array of forms given to convertPlural
2983 * @return array Padded array of forms or an exception if not an array
2984 */
2985 protected function preConvertPlural( /* Array */ $forms, $count ) {
2986 while ( count( $forms ) < $count ) {
2987 $forms[] = $forms[count( $forms ) - 1];
2988 }
2989 return $forms;
2990 }
2991
2992 /**
2993 * Maybe translate block durations. Note that this function is somewhat misnamed: it
2994 * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
2995 * (which is an absolute timestamp).
2996 * @param $str String: the validated block duration in English
2997 * @return Somehow translated block duration
2998 * @see LanguageFi.php for example implementation
2999 */
3000 function translateBlockExpiry( $str ) {
3001 $duration = SpecialBlock::getSuggestedDurations( $this );
3002 foreach( $duration as $show => $value ){
3003 if ( strcmp( $str, $value ) == 0 ) {
3004 return htmlspecialchars( trim( $show ) );
3005 }
3006 }
3007
3008 // Since usually only infinite or indefinite is only on list, so try
3009 // equivalents if still here.
3010 $indefs = array( 'infinite', 'infinity', 'indefinite' );
3011 if ( in_array( $str, $indefs ) ) {
3012 foreach( $indefs as $val ) {
3013 $show = array_search( $val, $duration, true );
3014 if ( $show !== false ) {
3015 return htmlspecialchars( trim( $show ) );
3016 }
3017 }
3018 }
3019 // If all else fails, return the original string.
3020 return $str;
3021 }
3022
3023 /**
3024 * languages like Chinese need to be segmented in order for the diff
3025 * to be of any use
3026 *
3027 * @param $text String
3028 * @return String
3029 */
3030 function segmentForDiff( $text ) {
3031 return $text;
3032 }
3033
3034 /**
3035 * and unsegment to show the result
3036 *
3037 * @param $text String
3038 * @return String
3039 */
3040 function unsegmentForDiff( $text ) {
3041 return $text;
3042 }
3043
3044 /**
3045 * convert text to all supported variants
3046 *
3047 * @param $text string
3048 * @return array
3049 */
3050 function autoConvertToAllVariants( $text ) {
3051 return $this->mConverter->autoConvertToAllVariants( $text );
3052 }
3053
3054 /**
3055 * convert text to different variants of a language.
3056 *
3057 * @param $text string
3058 * @return string
3059 */
3060 function convert( $text ) {
3061 return $this->mConverter->convert( $text );
3062 }
3063
3064
3065 /**
3066 * Convert a Title object to a string in the preferred variant
3067 *
3068 * @param $title Title
3069 * @return string
3070 */
3071 function convertTitle( $title ) {
3072 return $this->mConverter->convertTitle( $title );
3073 }
3074
3075 /**
3076 * Check if this is a language with variants
3077 *
3078 * @return bool
3079 */
3080 function hasVariants() {
3081 return sizeof( $this->getVariants() ) > 1;
3082 }
3083
3084 /**
3085 * Put custom tags (e.g. -{ }-) around math to prevent conversion
3086 *
3087 * @param $text string
3088 * @return string
3089 */
3090 function armourMath( $text ) {
3091 return $this->mConverter->armourMath( $text );
3092 }
3093
3094 /**
3095 * Perform output conversion on a string, and encode for safe HTML output.
3096 * @param $text String text to be converted
3097 * @param $isTitle Bool whether this conversion is for the article title
3098 * @return string
3099 * @todo this should get integrated somewhere sane
3100 */
3101 function convertHtml( $text, $isTitle = false ) {
3102 return htmlspecialchars( $this->convert( $text, $isTitle ) );
3103 }
3104
3105 /**
3106 * @param $key string
3107 * @return string
3108 */
3109 function convertCategoryKey( $key ) {
3110 return $this->mConverter->convertCategoryKey( $key );
3111 }
3112
3113 /**
3114 * Get the list of variants supported by this language
3115 * see sample implementation in LanguageZh.php
3116 *
3117 * @return array an array of language codes
3118 */
3119 function getVariants() {
3120 return $this->mConverter->getVariants();
3121 }
3122
3123 /**
3124 * @return string
3125 */
3126 function getPreferredVariant() {
3127 return $this->mConverter->getPreferredVariant();
3128 }
3129
3130 /**
3131 * @return string
3132 */
3133 function getDefaultVariant() {
3134 return $this->mConverter->getDefaultVariant();
3135 }
3136
3137 /**
3138 * @return string
3139 */
3140 function getURLVariant() {
3141 return $this->mConverter->getURLVariant();
3142 }
3143
3144 /**
3145 * If a language supports multiple variants, it is
3146 * possible that non-existing link in one variant
3147 * actually exists in another variant. this function
3148 * tries to find it. See e.g. LanguageZh.php
3149 *
3150 * @param $link String: the name of the link
3151 * @param $nt Mixed: the title object of the link
3152 * @param $ignoreOtherCond Boolean: to disable other conditions when
3153 * we need to transclude a template or update a category's link
3154 * @return null the input parameters may be modified upon return
3155 */
3156 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
3157 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
3158 }
3159
3160 /**
3161 * If a language supports multiple variants, converts text
3162 * into an array of all possible variants of the text:
3163 * 'variant' => text in that variant
3164 *
3165 * @deprecated since 1.17 Use autoConvertToAllVariants()
3166 *
3167 * @param $text string
3168 *
3169 * @return string
3170 */
3171 function convertLinkToAllVariants( $text ) {
3172 return $this->mConverter->convertLinkToAllVariants( $text );
3173 }
3174
3175 /**
3176 * returns language specific options used by User::getPageRenderHash()
3177 * for example, the preferred language variant
3178 *
3179 * @return string
3180 */
3181 function getExtraHashOptions() {
3182 return $this->mConverter->getExtraHashOptions();
3183 }
3184
3185 /**
3186 * For languages that support multiple variants, the title of an
3187 * article may be displayed differently in different variants. this
3188 * function returns the apporiate title defined in the body of the article.
3189 *
3190 * @return string
3191 */
3192 function getParsedTitle() {
3193 return $this->mConverter->getParsedTitle();
3194 }
3195
3196 /**
3197 * Enclose a string with the "no conversion" tag. This is used by
3198 * various functions in the Parser
3199 *
3200 * @param $text String: text to be tagged for no conversion
3201 * @param $noParse bool
3202 * @return string the tagged text
3203 */
3204 function markNoConversion( $text, $noParse = false ) {
3205 return $this->mConverter->markNoConversion( $text, $noParse );
3206 }
3207
3208 /**
3209 * A regular expression to match legal word-trailing characters
3210 * which should be merged onto a link of the form [[foo]]bar.
3211 *
3212 * @return string
3213 */
3214 function linkTrail() {
3215 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
3216 }
3217
3218 /**
3219 * @return Language
3220 */
3221 function getLangObj() {
3222 return $this;
3223 }
3224
3225 /**
3226 * Get the RFC 3066 code for this language object
3227 *
3228 * @return string
3229 */
3230 function getCode() {
3231 return $this->mCode;
3232 }
3233
3234 /**
3235 * @param $code string
3236 */
3237 function setCode( $code ) {
3238 $this->mCode = $code;
3239 }
3240
3241 /**
3242 * Get the name of a file for a certain language code
3243 * @param $prefix string Prepend this to the filename
3244 * @param $code string Language code
3245 * @param $suffix string Append this to the filename
3246 * @return string $prefix . $mangledCode . $suffix
3247 */
3248 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
3249 // Protect against path traversal
3250 if ( !Language::isValidCode( $code )
3251 || strcspn( $code, ":/\\\000" ) !== strlen( $code ) )
3252 {
3253 throw new MWException( "Invalid language code \"$code\"" );
3254 }
3255
3256 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
3257 }
3258
3259 /**
3260 * Get the language code from a file name. Inverse of getFileName()
3261 * @param $filename string $prefix . $languageCode . $suffix
3262 * @param $prefix string Prefix before the language code
3263 * @param $suffix string Suffix after the language code
3264 * @return string Language code, or false if $prefix or $suffix isn't found
3265 */
3266 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
3267 $m = null;
3268 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
3269 preg_quote( $suffix, '/' ) . '/', $filename, $m );
3270 if ( !count( $m ) ) {
3271 return false;
3272 }
3273 return str_replace( '_', '-', strtolower( $m[1] ) );
3274 }
3275
3276 /**
3277 * @param $code string
3278 * @return string
3279 */
3280 static function getMessagesFileName( $code ) {
3281 global $IP;
3282 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
3283 }
3284
3285 /**
3286 * @param $code string
3287 * @return string
3288 */
3289 static function getClassFileName( $code ) {
3290 global $IP;
3291 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
3292 }
3293
3294 /**
3295 * Get the fallback for a given language
3296 *
3297 * @param $code string
3298 *
3299 * @return false|string
3300 */
3301 static function getFallbackFor( $code ) {
3302 if ( $code === 'en' ) {
3303 // Shortcut
3304 return false;
3305 } else {
3306 return self::getLocalisationCache()->getItem( $code, 'fallback' );
3307 }
3308 }
3309
3310 /**
3311 * Get all messages for a given language
3312 * WARNING: this may take a long time
3313 *
3314 * @param $code string
3315 *
3316 * @return array
3317 */
3318 static function getMessagesFor( $code ) {
3319 return self::getLocalisationCache()->getItem( $code, 'messages' );
3320 }
3321
3322 /**
3323 * Get a message for a given language
3324 *
3325 * @param $key string
3326 * @param $code string
3327 *
3328 * @return string
3329 */
3330 static function getMessageFor( $key, $code ) {
3331 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
3332 }
3333
3334 /**
3335 * @param $talk
3336 * @return mixed
3337 */
3338 function fixVariableInNamespace( $talk ) {
3339 if ( strpos( $talk, '$1' ) === false ) {
3340 return $talk;
3341 }
3342
3343 global $wgMetaNamespace;
3344 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
3345
3346 # Allow grammar transformations
3347 # Allowing full message-style parsing would make simple requests
3348 # such as action=raw much more expensive than they need to be.
3349 # This will hopefully cover most cases.
3350 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
3351 array( &$this, 'replaceGrammarInNamespace' ), $talk );
3352 return str_replace( ' ', '_', $talk );
3353 }
3354
3355 /**
3356 * @param $m string
3357 * @return string
3358 */
3359 function replaceGrammarInNamespace( $m ) {
3360 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
3361 }
3362
3363 /**
3364 * @throws MWException
3365 * @return array
3366 */
3367 static function getCaseMaps() {
3368 static $wikiUpperChars, $wikiLowerChars;
3369 if ( isset( $wikiUpperChars ) ) {
3370 return array( $wikiUpperChars, $wikiLowerChars );
3371 }
3372
3373 wfProfileIn( __METHOD__ );
3374 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
3375 if ( $arr === false ) {
3376 throw new MWException(
3377 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
3378 }
3379 $wikiUpperChars = $arr['wikiUpperChars'];
3380 $wikiLowerChars = $arr['wikiLowerChars'];
3381 wfProfileOut( __METHOD__ );
3382 return array( $wikiUpperChars, $wikiLowerChars );
3383 }
3384
3385 /**
3386 * Decode an expiry (block, protection, etc) which has come from the DB
3387 *
3388 * @param $expiry String: Database expiry String
3389 * @param $format Bool|Int true to process using language functions, or TS_ constant
3390 * to return the expiry in a given timestamp
3391 * @return String
3392 */
3393 public function formatExpiry( $expiry, $format = true ) {
3394 static $infinity, $infinityMsg;
3395 if( $infinity === null ){
3396 $infinityMsg = wfMessage( 'infiniteblock' );
3397 $infinity = wfGetDB( DB_SLAVE )->getInfinity();
3398 }
3399
3400 if ( $expiry == '' || $expiry == $infinity ) {
3401 return $format === true
3402 ? $infinityMsg
3403 : $infinity;
3404 } else {
3405 return $format === true
3406 ? $this->timeanddate( $expiry )
3407 : wfTimestamp( $format, $expiry );
3408 }
3409 }
3410
3411 /**
3412 * @todo Document
3413 * @param $seconds String
3414 * @return string
3415 */
3416 function formatTimePeriod( $seconds ) {
3417 if ( round( $seconds * 10 ) < 100 ) {
3418 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3419 } elseif ( round( $seconds ) < 60 ) {
3420 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
3421 } elseif ( round( $seconds ) < 3600 ) {
3422 $minutes = floor( $seconds / 60 );
3423 $secondsPart = round( fmod( $seconds, 60 ) );
3424 if ( $secondsPart == 60 ) {
3425 $secondsPart = 0;
3426 $minutes++;
3427 }
3428 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3429 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3430 } else {
3431 $hours = floor( $seconds / 3600 );
3432 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
3433 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
3434 if ( $secondsPart == 60 ) {
3435 $secondsPart = 0;
3436 $minutes++;
3437 }
3438 if ( $minutes == 60 ) {
3439 $minutes = 0;
3440 $hours++;
3441 }
3442 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
3443 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
3444 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
3445 }
3446 }
3447
3448 /**
3449 * @param $bps int
3450 * @return string
3451 */
3452 function formatBitrate( $bps ) {
3453 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
3454 if ( $bps <= 0 ) {
3455 return $this->formatNum( $bps ) . $units[0];
3456 }
3457 $unitIndex = floor( log10( $bps ) / 3 );
3458 $mantissa = $bps / pow( 1000, $unitIndex );
3459 if ( $mantissa < 10 ) {
3460 $mantissa = round( $mantissa, 1 );
3461 } else {
3462 $mantissa = round( $mantissa );
3463 }
3464 return $this->formatNum( $mantissa ) . $units[$unitIndex];
3465 }
3466
3467 /**
3468 * Format a size in bytes for output, using an appropriate
3469 * unit (B, KB, MB or GB) according to the magnitude in question
3470 *
3471 * @param $size Size to format
3472 * @return string Plain text (not HTML)
3473 */
3474 function formatSize( $size ) {
3475 // For small sizes no decimal places necessary
3476 $round = 0;
3477 if ( $size > 1024 ) {
3478 $size = $size / 1024;
3479 if ( $size > 1024 ) {
3480 $size = $size / 1024;
3481 // For MB and bigger two decimal places are smarter
3482 $round = 2;
3483 if ( $size > 1024 ) {
3484 $size = $size / 1024;
3485 $msg = 'size-gigabytes';
3486 } else {
3487 $msg = 'size-megabytes';
3488 }
3489 } else {
3490 $msg = 'size-kilobytes';
3491 }
3492 } else {
3493 $msg = 'size-bytes';
3494 }
3495 $size = round( $size, $round );
3496 $text = $this->getMessageFromDB( $msg );
3497 return str_replace( '$1', $this->formatNum( $size ), $text );
3498 }
3499
3500 /**
3501 * Get the conversion rule title, if any.
3502 *
3503 * @return string
3504 */
3505 function getConvRuleTitle() {
3506 return $this->mConverter->getConvRuleTitle();
3507 }
3508 }