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