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