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