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