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