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