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