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