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