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