fixed typo
[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 }
981 }
982 return $s;
983 }
984
985 private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
986 private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
987 /**
988 * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
989 * Gregorian dates to Iranian dates. Originally written in C, it
990 * is released under the terms of GNU Lesser General Public
991 * License. Conversion to PHP was performed by Niklas Laxström.
992 *
993 * Link: http://www.farsiweb.info/jalali/jalali.c
994 */
995 private static function tsToIranian( $ts ) {
996 $gy = substr( $ts, 0, 4 ) -1600;
997 $gm = substr( $ts, 4, 2 ) -1;
998 $gd = substr( $ts, 6, 2 ) -1;
999
1000 # Days passed from the beginning (including leap years)
1001 $gDayNo = 365 * $gy
1002 + floor( ( $gy + 3 ) / 4 )
1003 - floor( ( $gy + 99 ) / 100 )
1004 + floor( ( $gy + 399 ) / 400 );
1005
1006
1007 // Add days of the past months of this year
1008 for ( $i = 0; $i < $gm; $i++ ) {
1009 $gDayNo += self::$GREG_DAYS[$i];
1010 }
1011
1012 // Leap years
1013 if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
1014 $gDayNo++;
1015 }
1016
1017 // Days passed in current month
1018 $gDayNo += $gd;
1019
1020 $jDayNo = $gDayNo - 79;
1021
1022 $jNp = floor( $jDayNo / 12053 );
1023 $jDayNo %= 12053;
1024
1025 $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
1026 $jDayNo %= 1461;
1027
1028 if ( $jDayNo >= 366 ) {
1029 $jy += floor( ( $jDayNo - 1 ) / 365 );
1030 $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
1031 }
1032
1033 for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
1034 $jDayNo -= self::$IRANIAN_DAYS[$i];
1035 }
1036
1037 $jm = $i + 1;
1038 $jd = $jDayNo + 1;
1039
1040 return array( $jy, $jm, $jd );
1041 }
1042
1043 /**
1044 * Converting Gregorian dates to Hijri dates.
1045 *
1046 * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
1047 *
1048 * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
1049 */
1050 private static function tsToHijri( $ts ) {
1051 $year = substr( $ts, 0, 4 );
1052 $month = substr( $ts, 4, 2 );
1053 $day = substr( $ts, 6, 2 );
1054
1055 $zyr = $year;
1056 $zd = $day;
1057 $zm = $month;
1058 $zy = $zyr;
1059
1060 if (
1061 ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
1062 ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
1063 )
1064 {
1065 $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
1066 (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
1067 (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
1068 $zd - 32075;
1069 } else {
1070 $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
1071 (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
1072 }
1073
1074 $zl = $zjd -1948440 + 10632;
1075 $zn = (int)( ( $zl - 1 ) / 10631 );
1076 $zl = $zl - 10631 * $zn + 354;
1077 $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) + ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
1078 $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) - ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
1079 $zm = (int)( ( 24 * $zl ) / 709 );
1080 $zd = $zl - (int)( ( 709 * $zm ) / 24 );
1081 $zy = 30 * $zn + $zj - 30;
1082
1083 return array( $zy, $zm, $zd );
1084 }
1085
1086 /**
1087 * Converting Gregorian dates to Hebrew dates.
1088 *
1089 * Based on a JavaScript code by Abu Mami and Yisrael Hersch
1090 * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
1091 * to translate the relevant functions into PHP and release them under
1092 * GNU GPL.
1093 *
1094 * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
1095 * and Adar II is 14. In a non-leap year, Adar is 6.
1096 */
1097 private static function tsToHebrew( $ts ) {
1098 # Parse date
1099 $year = substr( $ts, 0, 4 );
1100 $month = substr( $ts, 4, 2 );
1101 $day = substr( $ts, 6, 2 );
1102
1103 # Calculate Hebrew year
1104 $hebrewYear = $year + 3760;
1105
1106 # Month number when September = 1, August = 12
1107 $month += 4;
1108 if ( $month > 12 ) {
1109 # Next year
1110 $month -= 12;
1111 $year++;
1112 $hebrewYear++;
1113 }
1114
1115 # Calculate day of year from 1 September
1116 $dayOfYear = $day;
1117 for ( $i = 1; $i < $month; $i++ ) {
1118 if ( $i == 6 ) {
1119 # February
1120 $dayOfYear += 28;
1121 # Check if the year is leap
1122 if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
1123 $dayOfYear++;
1124 }
1125 } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
1126 $dayOfYear += 30;
1127 } else {
1128 $dayOfYear += 31;
1129 }
1130 }
1131
1132 # Calculate the start of the Hebrew year
1133 $start = self::hebrewYearStart( $hebrewYear );
1134
1135 # Calculate next year's start
1136 if ( $dayOfYear <= $start ) {
1137 # Day is before the start of the year - it is the previous year
1138 # Next year's start
1139 $nextStart = $start;
1140 # Previous year
1141 $year--;
1142 $hebrewYear--;
1143 # Add days since previous year's 1 September
1144 $dayOfYear += 365;
1145 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1146 # Leap year
1147 $dayOfYear++;
1148 }
1149 # Start of the new (previous) year
1150 $start = self::hebrewYearStart( $hebrewYear );
1151 } else {
1152 # Next year's start
1153 $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
1154 }
1155
1156 # Calculate Hebrew day of year
1157 $hebrewDayOfYear = $dayOfYear - $start;
1158
1159 # Difference between year's days
1160 $diff = $nextStart - $start;
1161 # Add 12 (or 13 for leap years) days to ignore the difference between
1162 # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
1163 # difference is only about the year type
1164 if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
1165 $diff += 13;
1166 } else {
1167 $diff += 12;
1168 }
1169
1170 # Check the year pattern, and is leap year
1171 # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
1172 # This is mod 30, to work on both leap years (which add 30 days of Adar I)
1173 # and non-leap years
1174 $yearPattern = $diff % 30;
1175 # Check if leap year
1176 $isLeap = $diff >= 30;
1177
1178 # Calculate day in the month from number of day in the Hebrew year
1179 # Don't check Adar - if the day is not in Adar, we will stop before;
1180 # if it is in Adar, we will use it to check if it is Adar I or Adar II
1181 $hebrewDay = $hebrewDayOfYear;
1182 $hebrewMonth = 1;
1183 $days = 0;
1184 while ( $hebrewMonth <= 12 ) {
1185 # Calculate days in this month
1186 if ( $isLeap && $hebrewMonth == 6 ) {
1187 # Adar in a leap year
1188 if ( $isLeap ) {
1189 # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
1190 $days = 30;
1191 if ( $hebrewDay <= $days ) {
1192 # Day in Adar I
1193 $hebrewMonth = 13;
1194 } else {
1195 # Subtract the days of Adar I
1196 $hebrewDay -= $days;
1197 # Try Adar II
1198 $days = 29;
1199 if ( $hebrewDay <= $days ) {
1200 # Day in Adar II
1201 $hebrewMonth = 14;
1202 }
1203 }
1204 }
1205 } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
1206 # Cheshvan in a complete year (otherwise as the rule below)
1207 $days = 30;
1208 } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
1209 # Kislev in an incomplete year (otherwise as the rule below)
1210 $days = 29;
1211 } else {
1212 # Odd months have 30 days, even have 29
1213 $days = 30 - ( $hebrewMonth - 1 ) % 2;
1214 }
1215 if ( $hebrewDay <= $days ) {
1216 # In the current month
1217 break;
1218 } else {
1219 # Subtract the days of the current month
1220 $hebrewDay -= $days;
1221 # Try in the next month
1222 $hebrewMonth++;
1223 }
1224 }
1225
1226 return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
1227 }
1228
1229 /**
1230 * This calculates the Hebrew year start, as days since 1 September.
1231 * Based on Carl Friedrich Gauss algorithm for finding Easter date.
1232 * Used for Hebrew date.
1233 */
1234 private static function hebrewYearStart( $year ) {
1235 $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
1236 $b = intval( ( $year - 1 ) % 4 );
1237 $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
1238 if ( $m < 0 ) {
1239 $m--;
1240 }
1241 $Mar = intval( $m );
1242 if ( $m < 0 ) {
1243 $m++;
1244 }
1245 $m -= $Mar;
1246
1247 $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
1248 if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
1249 $Mar++;
1250 } else if ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
1251 $Mar += 2;
1252 } else if ( $c == 2 || $c == 4 || $c == 6 ) {
1253 $Mar++;
1254 }
1255
1256 $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
1257 return $Mar;
1258 }
1259
1260 /**
1261 * Algorithm to convert Gregorian dates to Thai solar dates,
1262 * Minguo dates or Minguo dates.
1263 *
1264 * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
1265 * http://en.wikipedia.org/wiki/Minguo_calendar
1266 * http://en.wikipedia.org/wiki/Japanese_era_name
1267 *
1268 * @param $ts String: 14-character timestamp
1269 * @param $cName String: calender name
1270 * @return Array: converted year, month, day
1271 */
1272 private static function tsToYear( $ts, $cName ) {
1273 $gy = substr( $ts, 0, 4 );
1274 $gm = substr( $ts, 4, 2 );
1275 $gd = substr( $ts, 6, 2 );
1276
1277 if ( !strcmp( $cName, 'thai' ) ) {
1278 # Thai solar dates
1279 # Add 543 years to the Gregorian calendar
1280 # Months and days are identical
1281 $gy_offset = $gy + 543;
1282 } else if ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
1283 # Minguo dates
1284 # Deduct 1911 years from the Gregorian calendar
1285 # Months and days are identical
1286 $gy_offset = $gy - 1911;
1287 } else if ( !strcmp( $cName, 'tenno' ) ) {
1288 # Nengō dates up to Meiji period
1289 # Deduct years from the Gregorian calendar
1290 # depending on the nengo periods
1291 # Months and days are identical
1292 if ( ( $gy < 1912 ) || ( ( $gy == 1912 ) && ( $gm < 7 ) ) || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) ) ) {
1293 # Meiji period
1294 $gy_gannen = $gy - 1868 + 1;
1295 $gy_offset = $gy_gannen;
1296 if ( $gy_gannen == 1 ) {
1297 $gy_offset = '元';
1298 }
1299 $gy_offset = '明治' . $gy_offset;
1300 } else if (
1301 ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
1302 ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
1303 ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
1304 ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
1305 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
1306 )
1307 {
1308 # Taishō period
1309 $gy_gannen = $gy - 1912 + 1;
1310 $gy_offset = $gy_gannen;
1311 if ( $gy_gannen == 1 ) {
1312 $gy_offset = '元';
1313 }
1314 $gy_offset = '大正' . $gy_offset;
1315 } else if (
1316 ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
1317 ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
1318 ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
1319 )
1320 {
1321 # Shōwa period
1322 $gy_gannen = $gy - 1926 + 1;
1323 $gy_offset = $gy_gannen;
1324 if ( $gy_gannen == 1 ) {
1325 $gy_offset = '元';
1326 }
1327 $gy_offset = '昭和' . $gy_offset;
1328 } else {
1329 # Heisei period
1330 $gy_gannen = $gy - 1989 + 1;
1331 $gy_offset = $gy_gannen;
1332 if ( $gy_gannen == 1 ) {
1333 $gy_offset = '元';
1334 }
1335 $gy_offset = '平成' . $gy_offset;
1336 }
1337 } else {
1338 $gy_offset = $gy;
1339 }
1340
1341 return array( $gy_offset, $gm, $gd );
1342 }
1343
1344 /**
1345 * Roman number formatting up to 3000
1346 */
1347 static function romanNumeral( $num ) {
1348 static $table = array(
1349 array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
1350 array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
1351 array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
1352 array( '', 'M', 'MM', 'MMM' )
1353 );
1354
1355 $num = intval( $num );
1356 if ( $num > 3000 || $num <= 0 ) {
1357 return $num;
1358 }
1359
1360 $s = '';
1361 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1362 if ( $num >= $pow10 ) {
1363 $s .= $table[$i][floor( $num / $pow10 )];
1364 }
1365 $num = $num % $pow10;
1366 }
1367 return $s;
1368 }
1369
1370 /**
1371 * Hebrew Gematria number formatting up to 9999
1372 */
1373 static function hebrewNumeral( $num ) {
1374 static $table = array(
1375 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
1376 array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
1377 array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
1378 array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
1379 );
1380
1381 $num = intval( $num );
1382 if ( $num > 9999 || $num <= 0 ) {
1383 return $num;
1384 }
1385
1386 $s = '';
1387 for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
1388 if ( $num >= $pow10 ) {
1389 if ( $num == 15 || $num == 16 ) {
1390 $s .= $table[0][9] . $table[0][$num - 9];
1391 $num = 0;
1392 } else {
1393 $s .= $table[$i][intval( ( $num / $pow10 ) )];
1394 if ( $pow10 == 1000 ) {
1395 $s .= "'";
1396 }
1397 }
1398 }
1399 $num = $num % $pow10;
1400 }
1401 if ( strlen( $s ) == 2 ) {
1402 $str = $s . "'";
1403 } else {
1404 $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
1405 $str .= substr( $s, strlen( $s ) - 2, 2 );
1406 }
1407 $start = substr( $str, 0, strlen( $str ) - 2 );
1408 $end = substr( $str, strlen( $str ) - 2 );
1409 switch( $end ) {
1410 case 'כ':
1411 $str = $start . 'ך';
1412 break;
1413 case 'מ':
1414 $str = $start . 'ם';
1415 break;
1416 case 'נ':
1417 $str = $start . 'ן';
1418 break;
1419 case 'פ':
1420 $str = $start . 'ף';
1421 break;
1422 case 'צ':
1423 $str = $start . 'ץ';
1424 break;
1425 }
1426 return $str;
1427 }
1428
1429 /**
1430 * This is meant to be used by time(), date(), and timeanddate() to get
1431 * the date preference they're supposed to use, it should be used in
1432 * all children.
1433 *
1434 *<code>
1435 * function timeanddate([...], $format = true) {
1436 * $datePreference = $this->dateFormat($format);
1437 * [...]
1438 * }
1439 *</code>
1440 *
1441 * @param $usePrefs Mixed: if true, the user's preference is used
1442 * if false, the site/language default is used
1443 * if int/string, assumed to be a format.
1444 * @return string
1445 */
1446 function dateFormat( $usePrefs = true ) {
1447 global $wgUser;
1448
1449 if ( is_bool( $usePrefs ) ) {
1450 if ( $usePrefs ) {
1451 $datePreference = $wgUser->getDatePreference();
1452 } else {
1453 $datePreference = (string)User::getDefaultOption( 'date' );
1454 }
1455 } else {
1456 $datePreference = (string)$usePrefs;
1457 }
1458
1459 // return int
1460 if ( $datePreference == '' ) {
1461 return 'default';
1462 }
1463
1464 return $datePreference;
1465 }
1466
1467 /**
1468 * Get a format string for a given type and preference
1469 * @param $type May be date, time or both
1470 * @param $pref The format name as it appears in Messages*.php
1471 */
1472 function getDateFormatString( $type, $pref ) {
1473 if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
1474 if ( $pref == 'default' ) {
1475 $pref = $this->getDefaultDateFormat();
1476 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1477 } else {
1478 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1479 if ( is_null( $df ) ) {
1480 $pref = $this->getDefaultDateFormat();
1481 $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
1482 }
1483 }
1484 $this->dateFormatStrings[$type][$pref] = $df;
1485 }
1486 return $this->dateFormatStrings[$type][$pref];
1487 }
1488
1489 /**
1490 * @param $ts Mixed: the time format which needs to be turned into a
1491 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1492 * @param $adj Bool: whether to adjust the time output according to the
1493 * user configured offset ($timecorrection)
1494 * @param $format Mixed: true to use user's date format preference
1495 * @param $timecorrection String: the time offset as returned by
1496 * validateTimeZone() in Special:Preferences
1497 * @return string
1498 */
1499 function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
1500 $ts = wfTimestamp( TS_MW, $ts );
1501 if ( $adj ) {
1502 $ts = $this->userAdjust( $ts, $timecorrection );
1503 }
1504 $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
1505 return $this->sprintfDate( $df, $ts );
1506 }
1507
1508 /**
1509 * @param $ts Mixed: the time format which needs to be turned into a
1510 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1511 * @param $adj Bool: whether to adjust the time output according to the
1512 * user configured offset ($timecorrection)
1513 * @param $format Mixed: true to use user's date format preference
1514 * @param $timecorrection String: the time offset as returned by
1515 * validateTimeZone() in Special:Preferences
1516 * @return string
1517 */
1518 function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
1519 $ts = wfTimestamp( TS_MW, $ts );
1520 if ( $adj ) {
1521 $ts = $this->userAdjust( $ts, $timecorrection );
1522 }
1523 $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
1524 return $this->sprintfDate( $df, $ts );
1525 }
1526
1527 /**
1528 * @param $ts Mixed: the time format which needs to be turned into a
1529 * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
1530 * @param $adj Bool: whether to adjust the time output according to the
1531 * user configured offset ($timecorrection)
1532 * @param $format Mixed: what format to return, if it's false output the
1533 * default one (default true)
1534 * @param $timecorrection String: the time offset as returned by
1535 * validateTimeZone() in Special:Preferences
1536 * @return string
1537 */
1538 function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
1539 $ts = wfTimestamp( TS_MW, $ts );
1540 if ( $adj ) {
1541 $ts = $this->userAdjust( $ts, $timecorrection );
1542 }
1543 $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
1544 return $this->sprintfDate( $df, $ts );
1545 }
1546
1547 function getMessage( $key ) {
1548 return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
1549 }
1550
1551 function getAllMessages() {
1552 return self::$dataCache->getItem( $this->mCode, 'messages' );
1553 }
1554
1555 function iconv( $in, $out, $string ) {
1556 # This is a wrapper for iconv in all languages except esperanto,
1557 # which does some nasty x-conversions beforehand
1558
1559 # Even with //IGNORE iconv can whine about illegal characters in
1560 # *input* string. We just ignore those too.
1561 # REF: http://bugs.php.net/bug.php?id=37166
1562 # REF: https://bugzilla.wikimedia.org/show_bug.cgi?id=16885
1563 wfSuppressWarnings();
1564 $text = iconv( $in, $out . '//IGNORE', $string );
1565 wfRestoreWarnings();
1566 return $text;
1567 }
1568
1569 // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
1570 function ucwordbreaksCallbackAscii( $matches ) {
1571 return $this->ucfirst( $matches[1] );
1572 }
1573
1574 function ucwordbreaksCallbackMB( $matches ) {
1575 return mb_strtoupper( $matches[0] );
1576 }
1577
1578 function ucCallback( $matches ) {
1579 list( $wikiUpperChars ) = self::getCaseMaps();
1580 return strtr( $matches[1], $wikiUpperChars );
1581 }
1582
1583 function lcCallback( $matches ) {
1584 list( , $wikiLowerChars ) = self::getCaseMaps();
1585 return strtr( $matches[1], $wikiLowerChars );
1586 }
1587
1588 function ucwordsCallbackMB( $matches ) {
1589 return mb_strtoupper( $matches[0] );
1590 }
1591
1592 function ucwordsCallbackWiki( $matches ) {
1593 list( $wikiUpperChars ) = self::getCaseMaps();
1594 return strtr( $matches[0], $wikiUpperChars );
1595 }
1596
1597 /**
1598 * Make a string's first character uppercase
1599 */
1600 function ucfirst( $str ) {
1601 $o = ord( $str );
1602 if ( $o < 96 ) { // if already uppercase...
1603 return $str;
1604 } elseif ( $o < 128 ) {
1605 return ucfirst( $str ); // use PHP's ucfirst()
1606 } else {
1607 // fall back to more complex logic in case of multibyte strings
1608 return $this->uc( $str, true );
1609 }
1610 }
1611
1612 /**
1613 * Convert a string to uppercase
1614 */
1615 function uc( $str, $first = false ) {
1616 if ( function_exists( 'mb_strtoupper' ) ) {
1617 if ( $first ) {
1618 if ( $this->isMultibyte( $str ) ) {
1619 return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1620 } else {
1621 return ucfirst( $str );
1622 }
1623 } else {
1624 return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
1625 }
1626 } else {
1627 if ( $this->isMultibyte( $str ) ) {
1628 $x = $first ? '^' : '';
1629 return preg_replace_callback(
1630 "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1631 array( $this, 'ucCallback' ),
1632 $str
1633 );
1634 } else {
1635 return $first ? ucfirst( $str ) : strtoupper( $str );
1636 }
1637 }
1638 }
1639
1640 function lcfirst( $str ) {
1641 $o = ord( $str );
1642 if ( !$o ) {
1643 return strval( $str );
1644 } elseif ( $o >= 128 ) {
1645 return $this->lc( $str, true );
1646 } elseif ( $o > 96 ) {
1647 return $str;
1648 } else {
1649 $str[0] = strtolower( $str[0] );
1650 return $str;
1651 }
1652 }
1653
1654 function lc( $str, $first = false ) {
1655 if ( function_exists( 'mb_strtolower' ) ) {
1656 if ( $first ) {
1657 if ( $this->isMultibyte( $str ) ) {
1658 return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
1659 } else {
1660 return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
1661 }
1662 } else {
1663 return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
1664 }
1665 } else {
1666 if ( $this->isMultibyte( $str ) ) {
1667 $x = $first ? '^' : '';
1668 return preg_replace_callback(
1669 "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
1670 array( $this, 'lcCallback' ),
1671 $str
1672 );
1673 } else {
1674 return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
1675 }
1676 }
1677 }
1678
1679 function isMultibyte( $str ) {
1680 return (bool)preg_match( '/[\x80-\xff]/', $str );
1681 }
1682
1683 function ucwords( $str ) {
1684 if ( $this->isMultibyte( $str ) ) {
1685 $str = $this->lc( $str );
1686
1687 // regexp to find first letter in each word (i.e. after each space)
1688 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1689
1690 // function to use to capitalize a single char
1691 if ( function_exists( 'mb_strtoupper' ) ) {
1692 return preg_replace_callback(
1693 $replaceRegexp,
1694 array( $this, 'ucwordsCallbackMB' ),
1695 $str
1696 );
1697 } else {
1698 return preg_replace_callback(
1699 $replaceRegexp,
1700 array( $this, 'ucwordsCallbackWiki' ),
1701 $str
1702 );
1703 }
1704 } else {
1705 return ucwords( strtolower( $str ) );
1706 }
1707 }
1708
1709 # capitalize words at word breaks
1710 function ucwordbreaks( $str ) {
1711 if ( $this->isMultibyte( $str ) ) {
1712 $str = $this->lc( $str );
1713
1714 // since \b doesn't work for UTF-8, we explicitely define word break chars
1715 $breaks = "[ \-\(\)\}\{\.,\?!]";
1716
1717 // find first letter after word break
1718 $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
1719
1720 if ( function_exists( 'mb_strtoupper' ) ) {
1721 return preg_replace_callback(
1722 $replaceRegexp,
1723 array( $this, 'ucwordbreaksCallbackMB' ),
1724 $str
1725 );
1726 } else {
1727 return preg_replace_callback(
1728 $replaceRegexp,
1729 array( $this, 'ucwordsCallbackWiki' ),
1730 $str
1731 );
1732 }
1733 } else {
1734 return preg_replace_callback(
1735 '/\b([\w\x80-\xff]+)\b/',
1736 array( $this, 'ucwordbreaksCallbackAscii' ),
1737 $str
1738 );
1739 }
1740 }
1741
1742 /**
1743 * Return a case-folded representation of $s
1744 *
1745 * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
1746 * and $s2 are the same except for the case of their characters. It is not
1747 * necessary for the value returned to make sense when displayed.
1748 *
1749 * Do *not* perform any other normalisation in this function. If a caller
1750 * uses this function when it should be using a more general normalisation
1751 * function, then fix the caller.
1752 */
1753 function caseFold( $s ) {
1754 return $this->uc( $s );
1755 }
1756
1757 function checkTitleEncoding( $s ) {
1758 if ( is_array( $s ) ) {
1759 wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
1760 }
1761 # Check for non-UTF-8 URLs
1762 $ishigh = preg_match( '/[\x80-\xff]/', $s );
1763 if ( !$ishigh ) {
1764 return $s;
1765 }
1766
1767 $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1768 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
1769 if ( $isutf8 ) {
1770 return $s;
1771 }
1772
1773 return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
1774 }
1775
1776 function fallback8bitEncoding() {
1777 return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
1778 }
1779
1780 /**
1781 * Most writing systems use whitespace to break up words.
1782 * Some languages such as Chinese don't conventionally do this,
1783 * which requires special handling when breaking up words for
1784 * searching etc.
1785 */
1786 function hasWordBreaks() {
1787 return true;
1788 }
1789
1790 /**
1791 * Some languages such as Chinese require word segmentation,
1792 * Specify such segmentation when overridden in derived class.
1793 *
1794 * @param $string String
1795 * @return String
1796 */
1797 function segmentByWord( $string ) {
1798 return $string;
1799 }
1800
1801 /**
1802 * Some languages have special punctuation need to be normalized.
1803 * Make such changes here.
1804 *
1805 * @param $string String
1806 * @return String
1807 */
1808 function normalizeForSearch( $string ) {
1809 return self::convertDoubleWidth( $string );
1810 }
1811
1812 /**
1813 * convert double-width roman characters to single-width.
1814 * range: ff00-ff5f ~= 0020-007f
1815 */
1816 protected static function convertDoubleWidth( $string ) {
1817 static $full = null;
1818 static $half = null;
1819
1820 if ( $full === null ) {
1821 $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1822 $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1823 $full = str_split( $fullWidth, 3 );
1824 $half = str_split( $halfWidth );
1825 }
1826
1827 $string = str_replace( $full, $half, $string );
1828 return $string;
1829 }
1830
1831 protected static function insertSpace( $string, $pattern ) {
1832 $string = preg_replace( $pattern, " $1 ", $string );
1833 $string = preg_replace( '/ +/', ' ', $string );
1834 return $string;
1835 }
1836
1837 function convertForSearchResult( $termsArray ) {
1838 # some languages, e.g. Chinese, need to do a conversion
1839 # in order for search results to be displayed correctly
1840 return $termsArray;
1841 }
1842
1843 /**
1844 * Get the first character of a string.
1845 *
1846 * @param $s string
1847 * @return string
1848 */
1849 function firstChar( $s ) {
1850 $matches = array();
1851 preg_match(
1852 '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
1853 '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
1854 $s,
1855 $matches
1856 );
1857
1858 if ( isset( $matches[1] ) ) {
1859 if ( strlen( $matches[1] ) != 3 ) {
1860 return $matches[1];
1861 }
1862
1863 // Break down Hangul syllables to grab the first jamo
1864 $code = utf8ToCodepoint( $matches[1] );
1865 if ( $code < 0xac00 || 0xd7a4 <= $code ) {
1866 return $matches[1];
1867 } elseif ( $code < 0xb098 ) {
1868 return "\xe3\x84\xb1";
1869 } elseif ( $code < 0xb2e4 ) {
1870 return "\xe3\x84\xb4";
1871 } elseif ( $code < 0xb77c ) {
1872 return "\xe3\x84\xb7";
1873 } elseif ( $code < 0xb9c8 ) {
1874 return "\xe3\x84\xb9";
1875 } elseif ( $code < 0xbc14 ) {
1876 return "\xe3\x85\x81";
1877 } elseif ( $code < 0xc0ac ) {
1878 return "\xe3\x85\x82";
1879 } elseif ( $code < 0xc544 ) {
1880 return "\xe3\x85\x85";
1881 } elseif ( $code < 0xc790 ) {
1882 return "\xe3\x85\x87";
1883 } elseif ( $code < 0xcc28 ) {
1884 return "\xe3\x85\x88";
1885 } elseif ( $code < 0xce74 ) {
1886 return "\xe3\x85\x8a";
1887 } elseif ( $code < 0xd0c0 ) {
1888 return "\xe3\x85\x8b";
1889 } elseif ( $code < 0xd30c ) {
1890 return "\xe3\x85\x8c";
1891 } elseif ( $code < 0xd558 ) {
1892 return "\xe3\x85\x8d";
1893 } else {
1894 return "\xe3\x85\x8e";
1895 }
1896 } else {
1897 return '';
1898 }
1899 }
1900
1901 function initEncoding() {
1902 # Some languages may have an alternate char encoding option
1903 # (Esperanto X-coding, Japanese furigana conversion, etc)
1904 # If this language is used as the primary content language,
1905 # an override to the defaults can be set here on startup.
1906 }
1907
1908 function recodeForEdit( $s ) {
1909 # For some languages we'll want to explicitly specify
1910 # which characters make it into the edit box raw
1911 # or are converted in some way or another.
1912 # Note that if wgOutputEncoding is different from
1913 # wgInputEncoding, this text will be further converted
1914 # to wgOutputEncoding.
1915 global $wgEditEncoding;
1916 if ( $wgEditEncoding == '' || $wgEditEncoding == 'UTF-8' ) {
1917 return $s;
1918 } else {
1919 return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
1920 }
1921 }
1922
1923 function recodeInput( $s ) {
1924 # Take the previous into account.
1925 global $wgEditEncoding;
1926 if ( $wgEditEncoding != '' ) {
1927 $enc = $wgEditEncoding;
1928 } else {
1929 $enc = 'UTF-8';
1930 }
1931 if ( $enc == 'UTF-8' ) {
1932 return $s;
1933 } else {
1934 return $this->iconv( $enc, 'UTF-8', $s );
1935 }
1936 }
1937
1938 /**
1939 * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
1940 * also cleans up certain backwards-compatible sequences, converting them
1941 * to the modern Unicode equivalent.
1942 *
1943 * This is language-specific for performance reasons only.
1944 */
1945 function normalize( $s ) {
1946 global $wgAllUnicodeFixes;
1947 $s = UtfNormal::cleanUp( $s );
1948 if ( $wgAllUnicodeFixes ) {
1949 $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
1950 $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
1951 }
1952
1953 return $s;
1954 }
1955
1956 /**
1957 * Transform a string using serialized data stored in the given file (which
1958 * must be in the serialized subdirectory of $IP). The file contains pairs
1959 * mapping source characters to destination characters.
1960 *
1961 * The data is cached in process memory. This will go faster if you have the
1962 * FastStringSearch extension.
1963 */
1964 function transformUsingPairFile( $file, $string ) {
1965 if ( !isset( $this->transformData[$file] ) ) {
1966 $data = wfGetPrecompiledData( $file );
1967 if ( $data === false ) {
1968 throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
1969 }
1970 $this->transformData[$file] = new ReplacementArray( $data );
1971 }
1972 return $this->transformData[$file]->replace( $string );
1973 }
1974
1975 /**
1976 * For right-to-left language support
1977 *
1978 * @return bool
1979 */
1980 function isRTL() {
1981 return self::$dataCache->getItem( $this->mCode, 'rtl' );
1982 }
1983
1984 /**
1985 * Return the correct HTML 'dir' attribute value for this language.
1986 * @return String
1987 */
1988 function getDir() {
1989 return $this->isRTL() ? 'rtl' : 'ltr';
1990 }
1991
1992 /**
1993 * Return 'left' or 'right' as appropriate alignment for line-start
1994 * for this language's text direction.
1995 *
1996 * Should be equivalent to CSS3 'start' text-align value....
1997 *
1998 * @return String
1999 */
2000 function alignStart() {
2001 return $this->isRTL() ? 'right' : 'left';
2002 }
2003
2004 /**
2005 * Return 'right' or 'left' as appropriate alignment for line-end
2006 * for this language's text direction.
2007 *
2008 * Should be equivalent to CSS3 'end' text-align value....
2009 *
2010 * @return String
2011 */
2012 function alignEnd() {
2013 return $this->isRTL() ? 'left' : 'right';
2014 }
2015
2016 /**
2017 * A hidden direction mark (LRM or RLM), depending on the language direction
2018 *
2019 * @return string
2020 */
2021 function getDirMark() {
2022 return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
2023 }
2024
2025 function capitalizeAllNouns() {
2026 return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
2027 }
2028
2029 /**
2030 * An arrow, depending on the language direction
2031 *
2032 * @return string
2033 */
2034 function getArrow() {
2035 return $this->isRTL() ? '←' : '→';
2036 }
2037
2038 /**
2039 * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
2040 *
2041 * @return bool
2042 */
2043 function linkPrefixExtension() {
2044 return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
2045 }
2046
2047 function getMagicWords() {
2048 return self::$dataCache->getItem( $this->mCode, 'magicWords' );
2049 }
2050
2051 # Fill a MagicWord object with data from here
2052 function getMagic( $mw ) {
2053 if ( !$this->mMagicHookDone ) {
2054 $this->mMagicHookDone = true;
2055 wfProfileIn( 'LanguageGetMagic' );
2056 wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
2057 wfProfileOut( 'LanguageGetMagic' );
2058 }
2059 if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
2060 $rawEntry = $this->mMagicExtensions[$mw->mId];
2061 } else {
2062 $magicWords = $this->getMagicWords();
2063 if ( isset( $magicWords[$mw->mId] ) ) {
2064 $rawEntry = $magicWords[$mw->mId];
2065 } else {
2066 $rawEntry = false;
2067 }
2068 }
2069
2070 if ( !is_array( $rawEntry ) ) {
2071 error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
2072 } else {
2073 $mw->mCaseSensitive = $rawEntry[0];
2074 $mw->mSynonyms = array_slice( $rawEntry, 1 );
2075 }
2076 }
2077
2078 /**
2079 * Add magic words to the extension array
2080 */
2081 function addMagicWordsByLang( $newWords ) {
2082 $code = $this->getCode();
2083 $fallbackChain = array();
2084 while ( $code && !in_array( $code, $fallbackChain ) ) {
2085 $fallbackChain[] = $code;
2086 $code = self::getFallbackFor( $code );
2087 }
2088 if ( !in_array( 'en', $fallbackChain ) ) {
2089 $fallbackChain[] = 'en';
2090 }
2091 $fallbackChain = array_reverse( $fallbackChain );
2092 foreach ( $fallbackChain as $code ) {
2093 if ( isset( $newWords[$code] ) ) {
2094 $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
2095 }
2096 }
2097 }
2098
2099 /**
2100 * Get special page names, as an associative array
2101 * case folded alias => real name
2102 */
2103 function getSpecialPageAliases() {
2104 // Cache aliases because it may be slow to load them
2105 if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
2106 // Initialise array
2107 $this->mExtendedSpecialPageAliases =
2108 self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
2109 wfRunHooks( 'LanguageGetSpecialPageAliases',
2110 array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
2111 }
2112
2113 return $this->mExtendedSpecialPageAliases;
2114 }
2115
2116 /**
2117 * Italic is unsuitable for some languages
2118 *
2119 * @param $text String: the text to be emphasized.
2120 * @return string
2121 */
2122 function emphasize( $text ) {
2123 return "<em>$text</em>";
2124 }
2125
2126 /**
2127 * Normally we output all numbers in plain en_US style, that is
2128 * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
2129 * point twohundredthirtyfive. However this is not sutable for all
2130 * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
2131 * Icelandic just want to use commas instead of dots, and dots instead
2132 * of commas like "293.291,235".
2133 *
2134 * An example of this function being called:
2135 * <code>
2136 * wfMsg( 'message', $wgLang->formatNum( $num ) )
2137 * </code>
2138 *
2139 * See LanguageGu.php for the Gujarati implementation and
2140 * $separatorTransformTable on MessageIs.php for
2141 * the , => . and . => , implementation.
2142 *
2143 * @todo check if it's viable to use localeconv() for the decimal
2144 * separator thing.
2145 * @param $number Mixed: the string to be formatted, should be an integer
2146 * or a floating point number.
2147 * @param $nocommafy Bool: set to true for special numbers like dates
2148 * @return string
2149 */
2150 function formatNum( $number, $nocommafy = false ) {
2151 global $wgTranslateNumerals;
2152 if ( !$nocommafy ) {
2153 $number = $this->commafy( $number );
2154 $s = $this->separatorTransformTable();
2155 if ( $s ) {
2156 $number = strtr( $number, $s );
2157 }
2158 }
2159
2160 if ( $wgTranslateNumerals ) {
2161 $s = $this->digitTransformTable();
2162 if ( $s ) {
2163 $number = strtr( $number, $s );
2164 }
2165 }
2166
2167 return $number;
2168 }
2169
2170 function parseFormattedNumber( $number ) {
2171 $s = $this->digitTransformTable();
2172 if ( $s ) {
2173 $number = strtr( $number, array_flip( $s ) );
2174 }
2175
2176 $s = $this->separatorTransformTable();
2177 if ( $s ) {
2178 $number = strtr( $number, array_flip( $s ) );
2179 }
2180
2181 $number = strtr( $number, array( ',' => '' ) );
2182 return $number;
2183 }
2184
2185 /**
2186 * Adds commas to a given number
2187 *
2188 * @param $_ mixed
2189 * @return string
2190 */
2191 function commafy( $_ ) {
2192 return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $_ ) ) );
2193 }
2194
2195 function digitTransformTable() {
2196 return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
2197 }
2198
2199 function separatorTransformTable() {
2200 return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
2201 }
2202
2203 /**
2204 * Take a list of strings and build a locale-friendly comma-separated
2205 * list, using the local comma-separator message.
2206 * The last two strings are chained with an "and".
2207 *
2208 * @param $l Array
2209 * @return string
2210 */
2211 function listToText( $l ) {
2212 $s = '';
2213 $m = count( $l ) - 1;
2214 if ( $m == 1 ) {
2215 return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
2216 } else {
2217 for ( $i = $m; $i >= 0; $i-- ) {
2218 if ( $i == $m ) {
2219 $s = $l[$i];
2220 } else if ( $i == $m - 1 ) {
2221 $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
2222 } else {
2223 $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
2224 }
2225 }
2226 return $s;
2227 }
2228 }
2229
2230 /**
2231 * Take a list of strings and build a locale-friendly comma-separated
2232 * list, using the local comma-separator message.
2233 * @param $list array of strings to put in a comma list
2234 * @return string
2235 */
2236 function commaList( $list ) {
2237 return implode(
2238 $list,
2239 wfMsgExt(
2240 'comma-separator',
2241 array( 'parsemag', 'escapenoentities', 'language' => $this )
2242 )
2243 );
2244 }
2245
2246 /**
2247 * Take a list of strings and build a locale-friendly semicolon-separated
2248 * list, using the local semicolon-separator message.
2249 * @param $list array of strings to put in a semicolon list
2250 * @return string
2251 */
2252 function semicolonList( $list ) {
2253 return implode(
2254 $list,
2255 wfMsgExt(
2256 'semicolon-separator',
2257 array( 'parsemag', 'escapenoentities', 'language' => $this )
2258 )
2259 );
2260 }
2261
2262 /**
2263 * Same as commaList, but separate it with the pipe instead.
2264 * @param $list array of strings to put in a pipe list
2265 * @return string
2266 */
2267 function pipeList( $list ) {
2268 return implode(
2269 $list,
2270 wfMsgExt(
2271 'pipe-separator',
2272 array( 'escapenoentities', 'language' => $this )
2273 )
2274 );
2275 }
2276
2277 /**
2278 * Truncate a string to a specified length in bytes, appending an optional
2279 * string (e.g. for ellipses)
2280 *
2281 * The database offers limited byte lengths for some columns in the database;
2282 * multi-byte character sets mean we need to ensure that only whole characters
2283 * are included, otherwise broken characters can be passed to the user
2284 *
2285 * If $length is negative, the string will be truncated from the beginning
2286 *
2287 * @param $string String to truncate
2288 * @param $length Int: maximum length (excluding ellipses)
2289 * @param $ellipsis String to append to the truncated text
2290 * @return string
2291 */
2292 function truncate( $string, $length, $ellipsis = '...' ) {
2293 # Use the localized ellipsis character
2294 if ( $ellipsis == '...' ) {
2295 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2296 }
2297 # Check if there is no need to truncate
2298 if ( $length == 0 ) {
2299 return $ellipsis;
2300 } elseif ( strlen( $string ) <= abs( $length ) ) {
2301 return $string;
2302 }
2303 $stringOriginal = $string;
2304 if ( $length > 0 ) {
2305 $string = substr( $string, 0, $length ); // xyz...
2306 $string = $this->removeBadCharLast( $string );
2307 $string = $string . $ellipsis;
2308 } else {
2309 $string = substr( $string, $length ); // ...xyz
2310 $string = $this->removeBadCharFirst( $string );
2311 $string = $ellipsis . $string;
2312 }
2313 # Do not truncate if the ellipsis makes the string longer/equal (bug 22181)
2314 if ( strlen( $string ) < strlen( $stringOriginal ) ) {
2315 return $string;
2316 } else {
2317 return $stringOriginal;
2318 }
2319 }
2320
2321 /**
2322 * Remove bytes that represent an incomplete Unicode character
2323 * at the end of string (e.g. bytes of the char are missing)
2324 *
2325 * @param $string String
2326 * @return string
2327 */
2328 protected function removeBadCharLast( $string ) {
2329 $char = ord( $string[strlen( $string ) - 1] );
2330 $m = array();
2331 if ( $char >= 0xc0 ) {
2332 # We got the first byte only of a multibyte char; remove it.
2333 $string = substr( $string, 0, -1 );
2334 } elseif ( $char >= 0x80 &&
2335 preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
2336 '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) )
2337 {
2338 # We chopped in the middle of a character; remove it
2339 $string = $m[1];
2340 }
2341 return $string;
2342 }
2343
2344 /**
2345 * Remove bytes that represent an incomplete Unicode character
2346 * at the start of string (e.g. bytes of the char are missing)
2347 *
2348 * @param $string String
2349 * @return string
2350 */
2351 protected function removeBadCharFirst( $string ) {
2352 $char = ord( $string[0] );
2353 if ( $char >= 0x80 && $char < 0xc0 ) {
2354 # We chopped in the middle of a character; remove the whole thing
2355 $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
2356 }
2357 return $string;
2358 }
2359
2360 /*
2361 * Truncate a string of valid HTML to a specified length in bytes,
2362 * appending an optional string (e.g. for ellipses), and return valid HTML
2363 *
2364 * This is only intended for styled/linked text, such as HTML with
2365 * tags like <span> and <a>, were the tags are self-contained (valid HTML)
2366 *
2367 * Note: tries to fix broken HTML with MWTidy
2368 *
2369 * @param string $text HTML string to truncate
2370 * @param int $length (zero/positive) Maximum length (excluding ellipses)
2371 * @param string $ellipsis String to append to the truncated text
2372 * @returns string
2373 */
2374 function truncateHtml( $text, $length, $ellipsis = '...' ) {
2375 # Use the localized ellipsis character
2376 if ( $ellipsis == '...' ) {
2377 $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
2378 }
2379 # Check if there is no need to truncate
2380 if ( $length <= 0 ) {
2381 return $ellipsis; // no text shown, nothing to format
2382 } elseif ( strlen( $text ) <= $length ) {
2383 return $text; // string short enough even *with* HTML
2384 }
2385 $text = MWTidy::tidy( $text ); // fix tags
2386 $displayLen = 0; // innerHTML legth so far
2387 $testingEllipsis = false; // checking if ellipses will make string longer/equal?
2388 $tagType = 0; // 0-open, 1-close
2389 $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
2390 $entityState = 0; // 0-not entity, 1-entity
2391 $tag = $ret = '';
2392 $openTags = array(); // open tag stack
2393 $textLen = strlen( $text );
2394 for ( $pos = 0; $pos < $textLen; ++$pos ) {
2395 $ch = $text[$pos];
2396 $lastCh = $pos ? $text[$pos - 1] : '';
2397 $ret .= $ch; // add to result string
2398 if ( $ch == '<' ) {
2399 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
2400 $entityState = 0; // for bad HTML
2401 $bracketState = 1; // tag started (checking for backslash)
2402 } elseif ( $ch == '>' ) {
2403 $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
2404 $entityState = 0; // for bad HTML
2405 $bracketState = 0; // out of brackets
2406 } elseif ( $bracketState == 1 ) {
2407 if ( $ch == '/' ) {
2408 $tagType = 1; // close tag (e.g. "</span>")
2409 } else {
2410 $tagType = 0; // open tag (e.g. "<span>")
2411 $tag .= $ch;
2412 }
2413 $bracketState = 2; // building tag name
2414 } elseif ( $bracketState == 2 ) {
2415 if ( $ch != ' ' ) {
2416 $tag .= $ch;
2417 } else {
2418 // Name found (e.g. "<a href=..."), add on tag attributes...
2419 $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
2420 }
2421 } elseif ( $bracketState == 0 ) {
2422 if ( $entityState ) {
2423 if ( $ch == ';' ) {
2424 $entityState = 0;
2425 $displayLen++; // entity is one displayed char
2426 }
2427 } else {
2428 if ( $ch == '&' ) {
2429 $entityState = 1; // entity found, (e.g. "&#160;")
2430 } else {
2431 $displayLen++; // this char is displayed
2432 // Add on the other display text after this...
2433 $skipped = $this->truncate_skip(
2434 $ret, $text, "<>&", $pos + 1, $length - $displayLen );
2435 $displayLen += $skipped;
2436 $pos += $skipped;
2437 }
2438 }
2439 }
2440 # Consider truncation once the display length has reached the maximim.
2441 # Double-check that we're not in the middle of a bracket/entity...
2442 if ( $displayLen >= $length && $bracketState == 0 && $entityState == 0 ) {
2443 if ( !$testingEllipsis ) {
2444 $testingEllipsis = true;
2445 # Save where we are; we will truncate here unless
2446 # the ellipsis actually makes the string longer.
2447 $pOpenTags = $openTags; // save state
2448 $pRet = $ret; // save state
2449 } elseif ( $displayLen > ( $length + strlen( $ellipsis ) ) ) {
2450 # Ellipsis won't make string longer/equal, the truncation point was OK.
2451 $openTags = $pOpenTags; // reload state
2452 $ret = $this->removeBadCharLast( $pRet ); // reload state, multi-byte char fix
2453 $ret .= $ellipsis; // add ellipsis
2454 break;
2455 }
2456 }
2457 }
2458 if ( $displayLen == 0 ) {
2459 return ''; // no text shown, nothing to format
2460 }
2461 // Close the last tag if left unclosed by bad HTML
2462 $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
2463 while ( count( $openTags ) > 0 ) {
2464 $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
2465 }
2466 return $ret;
2467 }
2468
2469 // truncateHtml() helper function
2470 // like strcspn() but adds the skipped chars to $ret
2471 private function truncate_skip( &$ret, $text, $search, $start, $len = -1 ) {
2472 $skipCount = 0;
2473 if ( $start < strlen( $text ) ) {
2474 $skipCount = strcspn( $text, $search, $start, $len );
2475 $ret .= substr( $text, $start, $skipCount );
2476 }
2477 return $skipCount;
2478 }
2479
2480 /*
2481 * truncateHtml() helper function
2482 * (a) push or pop $tag from $openTags as needed
2483 * (b) clear $tag value
2484 * @param String &$tag Current HTML tag name we are looking at
2485 * @param int $tagType (0-open tag, 1-close tag)
2486 * @param char $lastCh Character before the '>' that ended this tag
2487 * @param array &$openTags Open tag stack (not accounting for $tag)
2488 */
2489 private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
2490 $tag = ltrim( $tag );
2491 if ( $tag != '' ) {
2492 if ( $tagType == 0 && $lastCh != '/' ) {
2493 $openTags[] = $tag; // tag opened (didn't close itself)
2494 } else if ( $tagType == 1 ) {
2495 if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
2496 array_pop( $openTags ); // tag closed
2497 }
2498 }
2499 $tag = '';
2500 }
2501 }
2502
2503 /**
2504 * Grammatical transformations, needed for inflected languages
2505 * Invoked by putting {{grammar:case|word}} in a message
2506 *
2507 * @param $word string
2508 * @param $case string
2509 * @return string
2510 */
2511 function convertGrammar( $word, $case ) {
2512 global $wgGrammarForms;
2513 if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
2514 return $wgGrammarForms[$this->getCode()][$case][$word];
2515 }
2516 return $word;
2517 }
2518
2519 /**
2520 * Provides an alternative text depending on specified gender.
2521 * Usage {{gender:username|masculine|feminine|neutral}}.
2522 * username is optional, in which case the gender of current user is used,
2523 * but only in (some) interface messages; otherwise default gender is used.
2524 * If second or third parameter are not specified, masculine is used.
2525 * These details may be overriden per language.
2526 */
2527 function gender( $gender, $forms ) {
2528 if ( !count( $forms ) ) {
2529 return '';
2530 }
2531 $forms = $this->preConvertPlural( $forms, 2 );
2532 if ( $gender === 'male' ) {
2533 return $forms[0];
2534 }
2535 if ( $gender === 'female' ) {
2536 return $forms[1];
2537 }
2538 return isset( $forms[2] ) ? $forms[2] : $forms[0];
2539 }
2540
2541 /**
2542 * Plural form transformations, needed for some languages.
2543 * For example, there are 3 form of plural in Russian and Polish,
2544 * depending on "count mod 10". See [[w:Plural]]
2545 * For English it is pretty simple.
2546 *
2547 * Invoked by putting {{plural:count|wordform1|wordform2}}
2548 * or {{plural:count|wordform1|wordform2|wordform3}}
2549 *
2550 * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
2551 *
2552 * @param $count Integer: non-localized number
2553 * @param $forms Array: different plural forms
2554 * @return string Correct form of plural for $count in this language
2555 */
2556 function convertPlural( $count, $forms ) {
2557 if ( !count( $forms ) ) {
2558 return '';
2559 }
2560 $forms = $this->preConvertPlural( $forms, 2 );
2561
2562 return ( $count == 1 ) ? $forms[0] : $forms[1];
2563 }
2564
2565 /**
2566 * Checks that convertPlural was given an array and pads it to requested
2567 * amound of forms by copying the last one.
2568 *
2569 * @param $count Integer: How many forms should there be at least
2570 * @param $forms Array of forms given to convertPlural
2571 * @return array Padded array of forms or an exception if not an array
2572 */
2573 protected function preConvertPlural( /* Array */ $forms, $count ) {
2574 while ( count( $forms ) < $count ) {
2575 $forms[] = $forms[count( $forms ) - 1];
2576 }
2577 return $forms;
2578 }
2579
2580 /**
2581 * For translating of expiry times
2582 * @param $str String: the validated block time in English
2583 * @return Somehow translated block time
2584 * @see LanguageFi.php for example implementation
2585 */
2586 function translateBlockExpiry( $str ) {
2587 $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
2588
2589 if ( $scBlockExpiryOptions == '-' ) {
2590 return $str;
2591 }
2592
2593 foreach ( explode( ',', $scBlockExpiryOptions ) as $option ) {
2594 if ( strpos( $option, ':' ) === false ) {
2595 continue;
2596 }
2597 list( $show, $value ) = explode( ':', $option );
2598 if ( strcmp( $str, $value ) == 0 ) {
2599 return htmlspecialchars( trim( $show ) );
2600 }
2601 }
2602
2603 return $str;
2604 }
2605
2606 /**
2607 * languages like Chinese need to be segmented in order for the diff
2608 * to be of any use
2609 *
2610 * @param $text String
2611 * @return String
2612 */
2613 function segmentForDiff( $text ) {
2614 return $text;
2615 }
2616
2617 /**
2618 * and unsegment to show the result
2619 *
2620 * @param $text String
2621 * @return String
2622 */
2623 function unsegmentForDiff( $text ) {
2624 return $text;
2625 }
2626
2627 # convert text to all supported variants
2628 function autoConvertToAllVariants( $text ) {
2629 return $this->mConverter->autoConvertToAllVariants( $text );
2630 }
2631
2632 # convert text to different variants of a language.
2633 function convert( $text ) {
2634 return $this->mConverter->convert( $text );
2635 }
2636
2637 # Convert a Title object to a string in the preferred variant
2638 function convertTitle( $title ) {
2639 return $this->mConverter->convertTitle( $title );
2640 }
2641
2642 # Check if this is a language with variants
2643 function hasVariants() {
2644 return sizeof( $this->getVariants() ) > 1;
2645 }
2646
2647 # Put custom tags (e.g. -{ }-) around math to prevent conversion
2648 function armourMath( $text ) {
2649 return $this->mConverter->armourMath( $text );
2650 }
2651
2652 /**
2653 * Perform output conversion on a string, and encode for safe HTML output.
2654 * @param $text String text to be converted
2655 * @param $isTitle Bool whether this conversion is for the article title
2656 * @return string
2657 * @todo this should get integrated somewhere sane
2658 */
2659 function convertHtml( $text, $isTitle = false ) {
2660 return htmlspecialchars( $this->convert( $text, $isTitle ) );
2661 }
2662
2663 function convertCategoryKey( $key ) {
2664 return $this->mConverter->convertCategoryKey( $key );
2665 }
2666
2667 /**
2668 * Get the list of variants supported by this langauge
2669 * see sample implementation in LanguageZh.php
2670 *
2671 * @return array an array of language codes
2672 */
2673 function getVariants() {
2674 return $this->mConverter->getVariants();
2675 }
2676
2677 function getPreferredVariant() {
2678 return $this->mConverter->getPreferredVariant();
2679 }
2680
2681 function getDefaultVariant() {
2682 return $this->mConverter->getDefaultVariant();
2683 }
2684
2685 function getURLVariant() {
2686 return $this->mConverter->getURLVariant();
2687 }
2688
2689 /**
2690 * If a language supports multiple variants, it is
2691 * possible that non-existing link in one variant
2692 * actually exists in another variant. this function
2693 * tries to find it. See e.g. LanguageZh.php
2694 *
2695 * @param $link String: the name of the link
2696 * @param $nt Mixed: the title object of the link
2697 * @param $ignoreOtherCond Boolean: to disable other conditions when
2698 * we need to transclude a template or update a category's link
2699 * @return null the input parameters may be modified upon return
2700 */
2701 function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
2702 $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
2703 }
2704
2705 /**
2706 * If a language supports multiple variants, converts text
2707 * into an array of all possible variants of the text:
2708 * 'variant' => text in that variant
2709 */
2710 function convertLinkToAllVariants( $text ) {
2711 return $this->mConverter->convertLinkToAllVariants( $text );
2712 }
2713
2714 /**
2715 * returns language specific options used by User::getPageRenderHash()
2716 * for example, the preferred language variant
2717 *
2718 * @return string
2719 */
2720 function getExtraHashOptions() {
2721 return $this->mConverter->getExtraHashOptions();
2722 }
2723
2724 /**
2725 * For languages that support multiple variants, the title of an
2726 * article may be displayed differently in different variants. this
2727 * function returns the apporiate title defined in the body of the article.
2728 *
2729 * @return string
2730 */
2731 function getParsedTitle() {
2732 return $this->mConverter->getParsedTitle();
2733 }
2734
2735 /**
2736 * Enclose a string with the "no conversion" tag. This is used by
2737 * various functions in the Parser
2738 *
2739 * @param $text String: text to be tagged for no conversion
2740 * @param $noParse
2741 * @return string the tagged text
2742 */
2743 function markNoConversion( $text, $noParse = false ) {
2744 return $this->mConverter->markNoConversion( $text, $noParse );
2745 }
2746
2747 /**
2748 * A regular expression to match legal word-trailing characters
2749 * which should be merged onto a link of the form [[foo]]bar.
2750 *
2751 * @return string
2752 */
2753 function linkTrail() {
2754 return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
2755 }
2756
2757 function getLangObj() {
2758 return $this;
2759 }
2760
2761 /**
2762 * Get the RFC 3066 code for this language object
2763 */
2764 function getCode() {
2765 return $this->mCode;
2766 }
2767
2768 function setCode( $code ) {
2769 $this->mCode = $code;
2770 }
2771
2772 /**
2773 * Get the name of a file for a certain language code
2774 * @param $prefix string Prepend this to the filename
2775 * @param $code string Language code
2776 * @param $suffix string Append this to the filename
2777 * @return string $prefix . $mangledCode . $suffix
2778 */
2779 static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
2780 return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
2781 }
2782
2783 /**
2784 * Get the language code from a file name. Inverse of getFileName()
2785 * @param $filename string $prefix . $languageCode . $suffix
2786 * @param $prefix string Prefix before the language code
2787 * @param $suffix string Suffix after the language code
2788 * @return Language code, or false if $prefix or $suffix isn't found
2789 */
2790 static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
2791 $m = null;
2792 preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
2793 preg_quote( $suffix, '/' ) . '/', $filename, $m );
2794 if ( !count( $m ) ) {
2795 return false;
2796 }
2797 return str_replace( '_', '-', strtolower( $m[1] ) );
2798 }
2799
2800 static function getMessagesFileName( $code ) {
2801 global $IP;
2802 return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
2803 }
2804
2805 static function getClassFileName( $code ) {
2806 global $IP;
2807 return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
2808 }
2809
2810 /**
2811 * Get the fallback for a given language
2812 */
2813 static function getFallbackFor( $code ) {
2814 if ( $code === 'en' ) {
2815 // Shortcut
2816 return false;
2817 } else {
2818 return self::getLocalisationCache()->getItem( $code, 'fallback' );
2819 }
2820 }
2821
2822 /**
2823 * Get all messages for a given language
2824 * WARNING: this may take a long time
2825 */
2826 static function getMessagesFor( $code ) {
2827 return self::getLocalisationCache()->getItem( $code, 'messages' );
2828 }
2829
2830 /**
2831 * Get a message for a given language
2832 */
2833 static function getMessageFor( $key, $code ) {
2834 return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
2835 }
2836
2837 function fixVariableInNamespace( $talk ) {
2838 if ( strpos( $talk, '$1' ) === false ) {
2839 return $talk;
2840 }
2841
2842 global $wgMetaNamespace;
2843 $talk = str_replace( '$1', $wgMetaNamespace, $talk );
2844
2845 # Allow grammar transformations
2846 # Allowing full message-style parsing would make simple requests
2847 # such as action=raw much more expensive than they need to be.
2848 # This will hopefully cover most cases.
2849 $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
2850 array( &$this, 'replaceGrammarInNamespace' ), $talk );
2851 return str_replace( ' ', '_', $talk );
2852 }
2853
2854 function replaceGrammarInNamespace( $m ) {
2855 return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
2856 }
2857
2858 static function getCaseMaps() {
2859 static $wikiUpperChars, $wikiLowerChars;
2860 if ( isset( $wikiUpperChars ) ) {
2861 return array( $wikiUpperChars, $wikiLowerChars );
2862 }
2863
2864 wfProfileIn( __METHOD__ );
2865 $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
2866 if ( $arr === false ) {
2867 throw new MWException(
2868 "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
2869 }
2870 extract( $arr );
2871 wfProfileOut( __METHOD__ );
2872 return array( $wikiUpperChars, $wikiLowerChars );
2873 }
2874
2875 function formatTimePeriod( $seconds ) {
2876 if ( round( $seconds * 10 ) < 100 ) {
2877 return $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2878 } elseif ( round( $seconds ) < 60 ) {
2879 return $this->formatNum( round( $seconds ) ) . $this->getMessageFromDB( 'seconds-abbrev' );
2880 } elseif ( round( $seconds ) < 3600 ) {
2881 $minutes = floor( $seconds / 60 );
2882 $secondsPart = round( fmod( $seconds, 60 ) );
2883 if ( $secondsPart == 60 ) {
2884 $secondsPart = 0;
2885 $minutes++;
2886 }
2887 return $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2888 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2889 } else {
2890 $hours = floor( $seconds / 3600 );
2891 $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
2892 $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
2893 if ( $secondsPart == 60 ) {
2894 $secondsPart = 0;
2895 $minutes++;
2896 }
2897 if ( $minutes == 60 ) {
2898 $minutes = 0;
2899 $hours++;
2900 }
2901 return $this->formatNum( $hours ) . $this->getMessageFromDB( 'hours-abbrev' ) . ' ' .
2902 $this->formatNum( $minutes ) . $this->getMessageFromDB( 'minutes-abbrev' ) . ' ' .
2903 $this->formatNum( $secondsPart ) . $this->getMessageFromDB( 'seconds-abbrev' );
2904 }
2905 }
2906
2907 function formatBitrate( $bps ) {
2908 $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
2909 if ( $bps <= 0 ) {
2910 return $this->formatNum( $bps ) . $units[0];
2911 }
2912 $unitIndex = floor( log10( $bps ) / 3 );
2913 $mantissa = $bps / pow( 1000, $unitIndex );
2914 if ( $mantissa < 10 ) {
2915 $mantissa = round( $mantissa, 1 );
2916 } else {
2917 $mantissa = round( $mantissa );
2918 }
2919 return $this->formatNum( $mantissa ) . $units[$unitIndex];
2920 }
2921
2922 /**
2923 * Format a size in bytes for output, using an appropriate
2924 * unit (B, KB, MB or GB) according to the magnitude in question
2925 *
2926 * @param $size Size to format
2927 * @return string Plain text (not HTML)
2928 */
2929 function formatSize( $size ) {
2930 // For small sizes no decimal places necessary
2931 $round = 0;
2932 if ( $size > 1024 ) {
2933 $size = $size / 1024;
2934 if ( $size > 1024 ) {
2935 $size = $size / 1024;
2936 // For MB and bigger two decimal places are smarter
2937 $round = 2;
2938 if ( $size > 1024 ) {
2939 $size = $size / 1024;
2940 $msg = 'size-gigabytes';
2941 } else {
2942 $msg = 'size-megabytes';
2943 }
2944 } else {
2945 $msg = 'size-kilobytes';
2946 }
2947 } else {
2948 $msg = 'size-bytes';
2949 }
2950 $size = round( $size, $round );
2951 $text = $this->getMessageFromDB( $msg );
2952 return str_replace( '$1', $this->formatNum( $size ), $text );
2953 }
2954
2955 /**
2956 * Get the conversion rule title, if any.
2957 */
2958 function getConvRuleTitle() {
2959 return $this->mConverter->getConvRuleTitle();
2960 }
2961
2962 /**
2963 * Given a string, convert it to a (hopefully short) key that can be used
2964 * for efficient sorting. A binary sort according to the sortkeys
2965 * corresponds to a logical sort of the corresponding strings. Current
2966 * code expects that a null character should sort before all others, but
2967 * has no other particular expectations (and that one can be changed if
2968 * necessary).
2969 *
2970 * @param string $string UTF-8 string
2971 * @return string Binary sortkey
2972 */
2973 public function convertToSortkey( $string ) {
2974 # Fake function for now
2975 return strtoupper( $string );
2976 }
2977
2978 /**
2979 * Given a string, return the logical "first letter" to be used for
2980 * grouping on category pages and so on. This has to be coordinated
2981 * carefully with convertToSortkey(), or else the sorted list might jump
2982 * back and forth between the same "initial letters" or other pathological
2983 * behavior. For instance, if you just return the first character, but "a"
2984 * sorts the same as "A" based on convertToSortkey(), then you might get a
2985 * list like
2986 *
2987 * == A ==
2988 * * [[Aardvark]]
2989 *
2990 * == a ==
2991 * * [[antelope]]
2992 *
2993 * == A ==
2994 * * [[Ape]]
2995 *
2996 * etc., assuming for the sake of argument that $wgCapitalLinks is false.
2997 *
2998 * @param string $string UTF-8 string
2999 * @return string UTF-8 string corresponding to the first letter of input
3000 */
3001 public function firstLetterForLists( $string ) {
3002 if ( $string[0] == "\0" ) {
3003 $string = substr( $string, 1 );
3004 }
3005 return strtoupper( $this->firstChar( $string ) );
3006 }
3007 }