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