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