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