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