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