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