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