PageRenderTime 70ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/languages/Language.php

https://github.com/tav/confluence
PHP | 2735 lines | 1740 code | 292 blank | 703 comment | 374 complexity | 55b91445e76d2958a8fff9a17f33dabc MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * @defgroup Language Language
  4. *
  5. * @file
  6. * @ingroup Language
  7. */
  8. if( !defined( 'MEDIAWIKI' ) ) {
  9. echo "This file is part of MediaWiki, it is not a valid entry point.\n";
  10. exit( 1 );
  11. }
  12. # Read language names
  13. global $wgLanguageNames;
  14. require_once( dirname(__FILE__) . '/Names.php' ) ;
  15. global $wgInputEncoding, $wgOutputEncoding;
  16. /**
  17. * These are always UTF-8, they exist only for backwards compatibility
  18. */
  19. $wgInputEncoding = "UTF-8";
  20. $wgOutputEncoding = "UTF-8";
  21. if( function_exists( 'mb_strtoupper' ) ) {
  22. mb_internal_encoding('UTF-8');
  23. }
  24. /**
  25. * a fake language converter
  26. *
  27. * @ingroup Language
  28. */
  29. class FakeConverter {
  30. var $mLang;
  31. function FakeConverter($langobj) {$this->mLang = $langobj;}
  32. function convert($t, $i) {return $t;}
  33. function parserConvert($t, $p) {return $t;}
  34. function getVariants() { return array( $this->mLang->getCode() ); }
  35. function getPreferredVariant() {return $this->mLang->getCode(); }
  36. function findVariantLink(&$l, &$n, $ignoreOtherCond = false) {}
  37. function getExtraHashOptions() {return '';}
  38. function getParsedTitle() {return '';}
  39. function markNoConversion($text, $noParse=false) {return $text;}
  40. function convertCategoryKey( $key ) {return $key; }
  41. function convertLinkToAllVariants($text){ return array( $this->mLang->getCode() => $text); }
  42. function armourMath($text){ return $text; }
  43. }
  44. /**
  45. * Internationalisation code
  46. * @ingroup Language
  47. */
  48. class Language {
  49. var $mConverter, $mVariants, $mCode, $mLoaded = false;
  50. var $mMagicExtensions = array(), $mMagicHookDone = false;
  51. static public $mLocalisationKeys = array(
  52. 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
  53. 'magicWords', 'messages', 'rtl', 'digitTransformTable',
  54. 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
  55. 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
  56. 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
  57. 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
  58. 'imageFiles'
  59. );
  60. static public $mMergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
  61. 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles' );
  62. static public $mMergeableListKeys = array( 'extraUserToggles' );
  63. static public $mMergeableAliasListKeys = array( 'specialPageAliases' );
  64. static public $mLocalisationCache = array();
  65. static public $mLangObjCache = array();
  66. static public $mWeekdayMsgs = array(
  67. 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
  68. 'friday', 'saturday'
  69. );
  70. static public $mWeekdayAbbrevMsgs = array(
  71. 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
  72. );
  73. static public $mMonthMsgs = array(
  74. 'january', 'february', 'march', 'april', 'may_long', 'june',
  75. 'july', 'august', 'september', 'october', 'november',
  76. 'december'
  77. );
  78. static public $mMonthGenMsgs = array(
  79. 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
  80. 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
  81. 'december-gen'
  82. );
  83. static public $mMonthAbbrevMsgs = array(
  84. 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
  85. 'sep', 'oct', 'nov', 'dec'
  86. );
  87. static public $mIranianCalendarMonthMsgs = array(
  88. 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
  89. 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
  90. 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
  91. 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
  92. );
  93. static public $mHebrewCalendarMonthMsgs = array(
  94. 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
  95. 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
  96. 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
  97. 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
  98. 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
  99. );
  100. static public $mHebrewCalendarMonthGenMsgs = array(
  101. 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
  102. 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
  103. 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
  104. 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
  105. 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
  106. );
  107. static public $mHijriCalendarMonthMsgs = array(
  108. 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
  109. 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
  110. 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
  111. 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
  112. );
  113. /**
  114. * Get a cached language object for a given language code
  115. */
  116. static function factory( $code ) {
  117. if ( !isset( self::$mLangObjCache[$code] ) ) {
  118. if( count( self::$mLangObjCache ) > 10 ) {
  119. // Don't keep a billion objects around, that's stupid.
  120. self::$mLangObjCache = array();
  121. }
  122. self::$mLangObjCache[$code] = self::newFromCode( $code );
  123. }
  124. return self::$mLangObjCache[$code];
  125. }
  126. /**
  127. * Create a language object for a given language code
  128. */
  129. protected static function newFromCode( $code ) {
  130. global $IP;
  131. static $recursionLevel = 0;
  132. if ( $code == 'en' ) {
  133. $class = 'Language';
  134. } else {
  135. $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
  136. // Preload base classes to work around APC/PHP5 bug
  137. if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
  138. include_once("$IP/languages/classes/$class.deps.php");
  139. }
  140. if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
  141. include_once("$IP/languages/classes/$class.php");
  142. }
  143. }
  144. if ( $recursionLevel > 5 ) {
  145. throw new MWException( "Language fallback loop detected when creating class $class\n" );
  146. }
  147. if( ! class_exists( $class ) ) {
  148. $fallback = Language::getFallbackFor( $code );
  149. ++$recursionLevel;
  150. $lang = Language::newFromCode( $fallback );
  151. --$recursionLevel;
  152. $lang->setCode( $code );
  153. } else {
  154. $lang = new $class;
  155. }
  156. return $lang;
  157. }
  158. function __construct() {
  159. $this->mConverter = new FakeConverter($this);
  160. // Set the code to the name of the descendant
  161. if ( get_class( $this ) == 'Language' ) {
  162. $this->mCode = 'en';
  163. } else {
  164. $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
  165. }
  166. }
  167. /**
  168. * Reduce memory usage
  169. */
  170. function __destruct() {
  171. foreach ( $this as $name => $value ) {
  172. unset( $this->$name );
  173. }
  174. }
  175. /**
  176. * Hook which will be called if this is the content language.
  177. * Descendants can use this to register hook functions or modify globals
  178. */
  179. function initContLang() {}
  180. /**
  181. * @deprecated Use User::getDefaultOptions()
  182. * @return array
  183. */
  184. function getDefaultUserOptions() {
  185. wfDeprecated( __METHOD__ );
  186. return User::getDefaultOptions();
  187. }
  188. function getFallbackLanguageCode() {
  189. return self::getFallbackFor( $this->mCode );
  190. }
  191. /**
  192. * Exports $wgBookstoreListEn
  193. * @return array
  194. */
  195. function getBookstoreList() {
  196. $this->load();
  197. return $this->bookstoreList;
  198. }
  199. /**
  200. * @return array
  201. */
  202. function getNamespaces() {
  203. $this->load();
  204. return $this->namespaceNames;
  205. }
  206. /**
  207. * A convenience function that returns the same thing as
  208. * getNamespaces() except with the array values changed to ' '
  209. * where it found '_', useful for producing output to be displayed
  210. * e.g. in <select> forms.
  211. *
  212. * @return array
  213. */
  214. function getFormattedNamespaces() {
  215. $ns = $this->getNamespaces();
  216. foreach($ns as $k => $v) {
  217. $ns[$k] = strtr($v, '_', ' ');
  218. }
  219. return $ns;
  220. }
  221. /**
  222. * Get a namespace value by key
  223. * <code>
  224. * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
  225. * echo $mw_ns; // prints 'MediaWiki'
  226. * </code>
  227. *
  228. * @param $index Int: the array key of the namespace to return
  229. * @return mixed, string if the namespace value exists, otherwise false
  230. */
  231. function getNsText( $index ) {
  232. $ns = $this->getNamespaces();
  233. return isset( $ns[$index] ) ? $ns[$index] : false;
  234. }
  235. /**
  236. * A convenience function that returns the same thing as
  237. * getNsText() except with '_' changed to ' ', useful for
  238. * producing output.
  239. *
  240. * @return array
  241. */
  242. function getFormattedNsText( $index ) {
  243. $ns = $this->getNsText( $index );
  244. return strtr($ns, '_', ' ');
  245. }
  246. /**
  247. * Get a namespace key by value, case insensitive.
  248. * Only matches namespace names for the current language, not the
  249. * canonical ones defined in Namespace.php.
  250. *
  251. * @param $text String
  252. * @return mixed An integer if $text is a valid value otherwise false
  253. */
  254. function getLocalNsIndex( $text ) {
  255. $this->load();
  256. $lctext = $this->lc($text);
  257. return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
  258. }
  259. /**
  260. * Get a namespace key by value, case insensitive. Canonical namespace
  261. * names override custom ones defined for the current language.
  262. *
  263. * @param $text String
  264. * @return mixed An integer if $text is a valid value otherwise false
  265. */
  266. function getNsIndex( $text ) {
  267. $this->load();
  268. $lctext = $this->lc($text);
  269. if( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) return $ns;
  270. return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
  271. }
  272. /**
  273. * short names for language variants used for language conversion links.
  274. *
  275. * @param $code String
  276. * @return string
  277. */
  278. function getVariantname( $code ) {
  279. return $this->getMessageFromDB( "variantname-$code" );
  280. }
  281. function specialPage( $name ) {
  282. $aliases = $this->getSpecialPageAliases();
  283. if ( isset( $aliases[$name][0] ) ) {
  284. $name = $aliases[$name][0];
  285. }
  286. return $this->getNsText( NS_SPECIAL ) . ':' . $name;
  287. }
  288. function getQuickbarSettings() {
  289. return array(
  290. $this->getMessage( 'qbsettings-none' ),
  291. $this->getMessage( 'qbsettings-fixedleft' ),
  292. $this->getMessage( 'qbsettings-fixedright' ),
  293. $this->getMessage( 'qbsettings-floatingleft' ),
  294. $this->getMessage( 'qbsettings-floatingright' )
  295. );
  296. }
  297. function getMathNames() {
  298. $this->load();
  299. return $this->mathNames;
  300. }
  301. function getDatePreferences() {
  302. $this->load();
  303. return $this->datePreferences;
  304. }
  305. function getDateFormats() {
  306. $this->load();
  307. return $this->dateFormats;
  308. }
  309. function getDefaultDateFormat() {
  310. $this->load();
  311. return $this->defaultDateFormat;
  312. }
  313. function getDatePreferenceMigrationMap() {
  314. $this->load();
  315. return $this->datePreferenceMigrationMap;
  316. }
  317. function getImageFile( $image ) {
  318. $this->load();
  319. return $this->imageFiles[$image];
  320. }
  321. function getDefaultUserOptionOverrides() {
  322. $this->load();
  323. # XXX - apparently some languageas get empty arrays, didn't get to it yet -- midom
  324. if (is_array($this->defaultUserOptionOverrides)) {
  325. return $this->defaultUserOptionOverrides;
  326. } else {
  327. return array();
  328. }
  329. }
  330. function getExtraUserToggles() {
  331. $this->load();
  332. return $this->extraUserToggles;
  333. }
  334. function getUserToggle( $tog ) {
  335. return $this->getMessageFromDB( "tog-$tog" );
  336. }
  337. /**
  338. * Get language names, indexed by code.
  339. * If $customisedOnly is true, only returns codes with a messages file
  340. */
  341. public static function getLanguageNames( $customisedOnly = false ) {
  342. global $wgLanguageNames, $wgExtraLanguageNames;
  343. $allNames = $wgExtraLanguageNames + $wgLanguageNames;
  344. if ( !$customisedOnly ) {
  345. return $allNames;
  346. }
  347. global $IP;
  348. $names = array();
  349. $dir = opendir( "$IP/languages/messages" );
  350. while( false !== ( $file = readdir( $dir ) ) ) {
  351. $m = array();
  352. if( preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $file, $m ) ) {
  353. $code = str_replace( '_', '-', strtolower( $m[1] ) );
  354. if ( isset( $allNames[$code] ) ) {
  355. $names[$code] = $allNames[$code];
  356. }
  357. }
  358. }
  359. closedir( $dir );
  360. return $names;
  361. }
  362. /**
  363. * Get a message from the MediaWiki namespace.
  364. *
  365. * @param $msg String: message name
  366. * @return string
  367. */
  368. function getMessageFromDB( $msg ) {
  369. return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
  370. }
  371. function getLanguageName( $code ) {
  372. $names = self::getLanguageNames();
  373. if ( !array_key_exists( $code, $names ) ) {
  374. return '';
  375. }
  376. return $names[$code];
  377. }
  378. function getMonthName( $key ) {
  379. return $this->getMessageFromDB( self::$mMonthMsgs[$key-1] );
  380. }
  381. function getMonthNameGen( $key ) {
  382. return $this->getMessageFromDB( self::$mMonthGenMsgs[$key-1] );
  383. }
  384. function getMonthAbbreviation( $key ) {
  385. return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key-1] );
  386. }
  387. function getWeekdayName( $key ) {
  388. return $this->getMessageFromDB( self::$mWeekdayMsgs[$key-1] );
  389. }
  390. function getWeekdayAbbreviation( $key ) {
  391. return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key-1] );
  392. }
  393. function getIranianCalendarMonthName( $key ) {
  394. return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key-1] );
  395. }
  396. function getHebrewCalendarMonthName( $key ) {
  397. return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key-1] );
  398. }
  399. function getHebrewCalendarMonthNameGen( $key ) {
  400. return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key-1] );
  401. }
  402. function getHijriCalendarMonthName( $key ) {
  403. return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key-1] );
  404. }
  405. /**
  406. * Used by date() and time() to adjust the time output.
  407. *
  408. * @param $ts Int the time in date('YmdHis') format
  409. * @param $tz Mixed: adjust the time by this amount (default false, mean we
  410. * get user timecorrection setting)
  411. * @return int
  412. */
  413. function userAdjust( $ts, $tz = false ) {
  414. global $wgUser, $wgLocalTZoffset;
  415. if ( $tz === false ) {
  416. $tz = $wgUser->getOption( 'timecorrection' );
  417. }
  418. $data = explode( '|', $tz, 3 );
  419. if ( $data[0] == 'ZoneInfo' ) {
  420. if ( function_exists( 'timezone_open' ) && @timezone_open( $data[2] ) !== false ) {
  421. $date = date_create( $ts, timezone_open( 'UTC' ) );
  422. date_timezone_set( $date, timezone_open( $data[2] ) );
  423. $date = date_format( $date, 'YmdHis' );
  424. return $date;
  425. }
  426. # Unrecognized timezone, default to 'Offset' with the stored offset.
  427. $data[0] = 'Offset';
  428. }
  429. $minDiff = 0;
  430. if ( $data[0] == 'System' || $tz == '' ) {
  431. # Global offset in minutes.
  432. if( isset($wgLocalTZoffset) ) $minDiff = $wgLocalTZoffset;
  433. } else if ( $data[0] == 'Offset' ) {
  434. $minDiff = intval( $data[1] );
  435. } else {
  436. $data = explode( ':', $tz );
  437. if( count( $data ) == 2 ) {
  438. $data[0] = intval( $data[0] );
  439. $data[1] = intval( $data[1] );
  440. $minDiff = abs( $data[0] ) * 60 + $data[1];
  441. if ( $data[0] < 0 ) $minDiff = -$minDiff;
  442. } else {
  443. $minDiff = intval( $data[0] ) * 60;
  444. }
  445. }
  446. # No difference ? Return time unchanged
  447. if ( 0 == $minDiff ) return $ts;
  448. wfSuppressWarnings(); // E_STRICT system time bitching
  449. # Generate an adjusted date; take advantage of the fact that mktime
  450. # will normalize out-of-range values so we don't have to split $minDiff
  451. # into hours and minutes.
  452. $t = mktime( (
  453. (int)substr( $ts, 8, 2) ), # Hours
  454. (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
  455. (int)substr( $ts, 12, 2 ), # Seconds
  456. (int)substr( $ts, 4, 2 ), # Month
  457. (int)substr( $ts, 6, 2 ), # Day
  458. (int)substr( $ts, 0, 4 ) ); #Year
  459. $date = date( 'YmdHis', $t );
  460. wfRestoreWarnings();
  461. return $date;
  462. }
  463. /**
  464. * This is a workalike of PHP's date() function, but with better
  465. * internationalisation, a reduced set of format characters, and a better
  466. * escaping format.
  467. *
  468. * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
  469. * PHP manual for definitions. "o" format character is supported since
  470. * PHP 5.1.0, previous versions return literal o.
  471. * There are a number of extensions, which start with "x":
  472. *
  473. * xn Do not translate digits of the next numeric format character
  474. * xN Toggle raw digit (xn) flag, stays set until explicitly unset
  475. * xr Use roman numerals for the next numeric format character
  476. * xh Use hebrew numerals for the next numeric format character
  477. * xx Literal x
  478. * xg Genitive month name
  479. *
  480. * xij j (day number) in Iranian calendar
  481. * xiF F (month name) in Iranian calendar
  482. * xin n (month number) in Iranian calendar
  483. * xiY Y (full year) in Iranian calendar
  484. *
  485. * xjj j (day number) in Hebrew calendar
  486. * xjF F (month name) in Hebrew calendar
  487. * xjt t (days in month) in Hebrew calendar
  488. * xjx xg (genitive month name) in Hebrew calendar
  489. * xjn n (month number) in Hebrew calendar
  490. * xjY Y (full year) in Hebrew calendar
  491. *
  492. * xmj j (day number) in Hijri calendar
  493. * xmF F (month name) in Hijri calendar
  494. * xmn n (month number) in Hijri calendar
  495. * xmY Y (full year) in Hijri calendar
  496. *
  497. * xkY Y (full year) in Thai solar calendar. Months and days are
  498. * identical to the Gregorian calendar
  499. *
  500. * Characters enclosed in double quotes will be considered literal (with
  501. * the quotes themselves removed). Unmatched quotes will be considered
  502. * literal quotes. Example:
  503. *
  504. * "The month is" F => The month is January
  505. * i's" => 20'11"
  506. *
  507. * Backslash escaping is also supported.
  508. *
  509. * Input timestamp is assumed to be pre-normalized to the desired local
  510. * time zone, if any.
  511. *
  512. * @param $format String
  513. * @param $ts String: 14-character timestamp
  514. * YYYYMMDDHHMMSS
  515. * 01234567890123
  516. * @todo emulation of "o" format character for PHP pre 5.1.0
  517. * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
  518. */
  519. function sprintfDate( $format, $ts ) {
  520. $s = '';
  521. $raw = false;
  522. $roman = false;
  523. $hebrewNum = false;
  524. $unix = false;
  525. $rawToggle = false;
  526. $iranian = false;
  527. $hebrew = false;
  528. $hijri = false;
  529. $thai = false;
  530. for ( $p = 0; $p < strlen( $format ); $p++ ) {
  531. $num = false;
  532. $code = $format[$p];
  533. if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
  534. $code .= $format[++$p];
  535. }
  536. if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' ) && $p < strlen( $format ) - 1 ) {
  537. $code .= $format[++$p];
  538. }
  539. switch ( $code ) {
  540. case 'xx':
  541. $s .= 'x';
  542. break;
  543. case 'xn':
  544. $raw = true;
  545. break;
  546. case 'xN':
  547. $rawToggle = !$rawToggle;
  548. break;
  549. case 'xr':
  550. $roman = true;
  551. break;
  552. case 'xh':
  553. $hebrewNum = true;
  554. break;
  555. case 'xg':
  556. $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
  557. break;
  558. case 'xjx':
  559. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  560. $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
  561. break;
  562. case 'd':
  563. $num = substr( $ts, 6, 2 );
  564. break;
  565. case 'D':
  566. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  567. $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
  568. break;
  569. case 'j':
  570. $num = intval( substr( $ts, 6, 2 ) );
  571. break;
  572. case 'xij':
  573. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  574. $num = $iranian[2];
  575. break;
  576. case 'xmj':
  577. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  578. $num = $hijri[2];
  579. break;
  580. case 'xjj':
  581. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  582. $num = $hebrew[2];
  583. break;
  584. case 'l':
  585. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  586. $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
  587. break;
  588. case 'N':
  589. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  590. $w = gmdate( 'w', $unix );
  591. $num = $w ? $w : 7;
  592. break;
  593. case 'w':
  594. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  595. $num = gmdate( 'w', $unix );
  596. break;
  597. case 'z':
  598. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  599. $num = gmdate( 'z', $unix );
  600. break;
  601. case 'W':
  602. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  603. $num = gmdate( 'W', $unix );
  604. break;
  605. case 'F':
  606. $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
  607. break;
  608. case 'xiF':
  609. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  610. $s .= $this->getIranianCalendarMonthName( $iranian[1] );
  611. break;
  612. case 'xmF':
  613. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  614. $s .= $this->getHijriCalendarMonthName( $hijri[1] );
  615. break;
  616. case 'xjF':
  617. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  618. $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
  619. break;
  620. case 'm':
  621. $num = substr( $ts, 4, 2 );
  622. break;
  623. case 'M':
  624. $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
  625. break;
  626. case 'n':
  627. $num = intval( substr( $ts, 4, 2 ) );
  628. break;
  629. case 'xin':
  630. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  631. $num = $iranian[1];
  632. break;
  633. case 'xmn':
  634. if ( !$hijri ) $hijri = self::tsToHijri ( $ts );
  635. $num = $hijri[1];
  636. break;
  637. case 'xjn':
  638. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  639. $num = $hebrew[1];
  640. break;
  641. case 't':
  642. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  643. $num = gmdate( 't', $unix );
  644. break;
  645. case 'xjt':
  646. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  647. $num = $hebrew[3];
  648. break;
  649. case 'L':
  650. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  651. $num = gmdate( 'L', $unix );
  652. break;
  653. # 'o' is supported since PHP 5.1.0
  654. # return literal if not supported
  655. # TODO: emulation for pre 5.1.0 versions
  656. case 'o':
  657. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  658. if ( version_compare(PHP_VERSION, '5.1.0') === 1 )
  659. $num = date( 'o', $unix );
  660. else
  661. $s .= 'o';
  662. break;
  663. case 'Y':
  664. $num = substr( $ts, 0, 4 );
  665. break;
  666. case 'xiY':
  667. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  668. $num = $iranian[0];
  669. break;
  670. case 'xmY':
  671. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  672. $num = $hijri[0];
  673. break;
  674. case 'xjY':
  675. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  676. $num = $hebrew[0];
  677. break;
  678. case 'xkY':
  679. if ( !$thai ) $thai = self::tsToThai( $ts );
  680. $num = $thai[0];
  681. break;
  682. case 'y':
  683. $num = substr( $ts, 2, 2 );
  684. break;
  685. case 'a':
  686. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
  687. break;
  688. case 'A':
  689. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
  690. break;
  691. case 'g':
  692. $h = substr( $ts, 8, 2 );
  693. $num = $h % 12 ? $h % 12 : 12;
  694. break;
  695. case 'G':
  696. $num = intval( substr( $ts, 8, 2 ) );
  697. break;
  698. case 'h':
  699. $h = substr( $ts, 8, 2 );
  700. $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
  701. break;
  702. case 'H':
  703. $num = substr( $ts, 8, 2 );
  704. break;
  705. case 'i':
  706. $num = substr( $ts, 10, 2 );
  707. break;
  708. case 's':
  709. $num = substr( $ts, 12, 2 );
  710. break;
  711. case 'c':
  712. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  713. $s .= gmdate( 'c', $unix );
  714. break;
  715. case 'r':
  716. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  717. $s .= gmdate( 'r', $unix );
  718. break;
  719. case 'U':
  720. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  721. $num = $unix;
  722. break;
  723. case '\\':
  724. # Backslash escaping
  725. if ( $p < strlen( $format ) - 1 ) {
  726. $s .= $format[++$p];
  727. } else {
  728. $s .= '\\';
  729. }
  730. break;
  731. case '"':
  732. # Quoted literal
  733. if ( $p < strlen( $format ) - 1 ) {
  734. $endQuote = strpos( $format, '"', $p + 1 );
  735. if ( $endQuote === false ) {
  736. # No terminating quote, assume literal "
  737. $s .= '"';
  738. } else {
  739. $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
  740. $p = $endQuote;
  741. }
  742. } else {
  743. # Quote at end of string, assume literal "
  744. $s .= '"';
  745. }
  746. break;
  747. default:
  748. $s .= $format[$p];
  749. }
  750. if ( $num !== false ) {
  751. if ( $rawToggle || $raw ) {
  752. $s .= $num;
  753. $raw = false;
  754. } elseif ( $roman ) {
  755. $s .= self::romanNumeral( $num );
  756. $roman = false;
  757. } elseif( $hebrewNum ) {
  758. $s .= self::hebrewNumeral( $num );
  759. $hebrewNum = false;
  760. } else {
  761. $s .= $this->formatNum( $num, true );
  762. }
  763. $num = false;
  764. }
  765. }
  766. return $s;
  767. }
  768. private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  769. private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
  770. /**
  771. * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
  772. * Gregorian dates to Iranian dates. Originally written in C, it
  773. * is released under the terms of GNU Lesser General Public
  774. * License. Conversion to PHP was performed by Niklas Laxström.
  775. *
  776. * Link: http://www.farsiweb.info/jalali/jalali.c
  777. */
  778. private static function tsToIranian( $ts ) {
  779. $gy = substr( $ts, 0, 4 ) -1600;
  780. $gm = substr( $ts, 4, 2 ) -1;
  781. $gd = substr( $ts, 6, 2 ) -1;
  782. # Days passed from the beginning (including leap years)
  783. $gDayNo = 365*$gy
  784. + floor(($gy+3) / 4)
  785. - floor(($gy+99) / 100)
  786. + floor(($gy+399) / 400);
  787. // Add days of the past months of this year
  788. for( $i = 0; $i < $gm; $i++ ) {
  789. $gDayNo += self::$GREG_DAYS[$i];
  790. }
  791. // Leap years
  792. if ( $gm > 1 && (($gy%4===0 && $gy%100!==0 || ($gy%400==0)))) {
  793. $gDayNo++;
  794. }
  795. // Days passed in current month
  796. $gDayNo += $gd;
  797. $jDayNo = $gDayNo - 79;
  798. $jNp = floor($jDayNo / 12053);
  799. $jDayNo %= 12053;
  800. $jy = 979 + 33*$jNp + 4*floor($jDayNo/1461);
  801. $jDayNo %= 1461;
  802. if ( $jDayNo >= 366 ) {
  803. $jy += floor(($jDayNo-1)/365);
  804. $jDayNo = floor(($jDayNo-1)%365);
  805. }
  806. for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
  807. $jDayNo -= self::$IRANIAN_DAYS[$i];
  808. }
  809. $jm= $i+1;
  810. $jd= $jDayNo+1;
  811. return array($jy, $jm, $jd);
  812. }
  813. /**
  814. * Converting Gregorian dates to Hijri dates.
  815. *
  816. * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
  817. *
  818. * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
  819. */
  820. private static function tsToHijri ( $ts ) {
  821. $year = substr( $ts, 0, 4 );
  822. $month = substr( $ts, 4, 2 );
  823. $day = substr( $ts, 6, 2 );
  824. $zyr = $year;
  825. $zd=$day;
  826. $zm=$month;
  827. $zy=$zyr;
  828. if (($zy>1582)||(($zy==1582)&&($zm>10))||(($zy==1582)&&($zm==10)&&($zd>14)))
  829. {
  830. $zjd=(int)((1461*($zy + 4800 + (int)( ($zm-14) /12) ))/4) + (int)((367*($zm-2-12*((int)(($zm-14)/12))))/12)-(int)((3*(int)(( ($zy+4900+(int)(($zm-14)/12))/100)))/4)+$zd-32075;
  831. }
  832. else
  833. {
  834. $zjd = 367*$zy-(int)((7*($zy+5001+(int)(($zm-9)/7)))/4)+(int)((275*$zm)/9)+$zd+1729777;
  835. }
  836. $zl=$zjd-1948440+10632;
  837. $zn=(int)(($zl-1)/10631);
  838. $zl=$zl-10631*$zn+354;
  839. $zj=((int)((10985-$zl)/5316))*((int)((50*$zl)/17719))+((int)($zl/5670))*((int)((43*$zl)/15238));
  840. $zl=$zl-((int)((30-$zj)/15))*((int)((17719*$zj)/50))-((int)($zj/16))*((int)((15238*$zj)/43))+29;
  841. $zm=(int)((24*$zl)/709);
  842. $zd=$zl-(int)((709*$zm)/24);
  843. $zy=30*$zn+$zj-30;
  844. return array ($zy, $zm, $zd);
  845. }
  846. /**
  847. * Converting Gregorian dates to Hebrew dates.
  848. *
  849. * Based on a JavaScript code by Abu Mami and Yisrael Hersch
  850. * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
  851. * to translate the relevant functions into PHP and release them under
  852. * GNU GPL.
  853. *
  854. * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
  855. * and Adar II is 14. In a non-leap year, Adar is 6.
  856. */
  857. private static function tsToHebrew( $ts ) {
  858. # Parse date
  859. $year = substr( $ts, 0, 4 );
  860. $month = substr( $ts, 4, 2 );
  861. $day = substr( $ts, 6, 2 );
  862. # Calculate Hebrew year
  863. $hebrewYear = $year + 3760;
  864. # Month number when September = 1, August = 12
  865. $month += 4;
  866. if( $month > 12 ) {
  867. # Next year
  868. $month -= 12;
  869. $year++;
  870. $hebrewYear++;
  871. }
  872. # Calculate day of year from 1 September
  873. $dayOfYear = $day;
  874. for( $i = 1; $i < $month; $i++ ) {
  875. if( $i == 6 ) {
  876. # February
  877. $dayOfYear += 28;
  878. # Check if the year is leap
  879. if( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
  880. $dayOfYear++;
  881. }
  882. } elseif( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
  883. $dayOfYear += 30;
  884. } else {
  885. $dayOfYear += 31;
  886. }
  887. }
  888. # Calculate the start of the Hebrew year
  889. $start = self::hebrewYearStart( $hebrewYear );
  890. # Calculate next year's start
  891. if( $dayOfYear <= $start ) {
  892. # Day is before the start of the year - it is the previous year
  893. # Next year's start
  894. $nextStart = $start;
  895. # Previous year
  896. $year--;
  897. $hebrewYear--;
  898. # Add days since previous year's 1 September
  899. $dayOfYear += 365;
  900. if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  901. # Leap year
  902. $dayOfYear++;
  903. }
  904. # Start of the new (previous) year
  905. $start = self::hebrewYearStart( $hebrewYear );
  906. } else {
  907. # Next year's start
  908. $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
  909. }
  910. # Calculate Hebrew day of year
  911. $hebrewDayOfYear = $dayOfYear - $start;
  912. # Difference between year's days
  913. $diff = $nextStart - $start;
  914. # Add 12 (or 13 for leap years) days to ignore the difference between
  915. # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
  916. # difference is only about the year type
  917. if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  918. $diff += 13;
  919. } else {
  920. $diff += 12;
  921. }
  922. # Check the year pattern, and is leap year
  923. # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
  924. # This is mod 30, to work on both leap years (which add 30 days of Adar I)
  925. # and non-leap years
  926. $yearPattern = $diff % 30;
  927. # Check if leap year
  928. $isLeap = $diff >= 30;
  929. # Calculate day in the month from number of day in the Hebrew year
  930. # Don't check Adar - if the day is not in Adar, we will stop before;
  931. # if it is in Adar, we will use it to check if it is Adar I or Adar II
  932. $hebrewDay = $hebrewDayOfYear;
  933. $hebrewMonth = 1;
  934. $days = 0;
  935. while( $hebrewMonth <= 12 ) {
  936. # Calculate days in this month
  937. if( $isLeap && $hebrewMonth == 6 ) {
  938. # Adar in a leap year
  939. if( $isLeap ) {
  940. # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
  941. $days = 30;
  942. if( $hebrewDay <= $days ) {
  943. # Day in Adar I
  944. $hebrewMonth = 13;
  945. } else {
  946. # Subtract the days of Adar I
  947. $hebrewDay -= $days;
  948. # Try Adar II
  949. $days = 29;
  950. if( $hebrewDay <= $days ) {
  951. # Day in Adar II
  952. $hebrewMonth = 14;
  953. }
  954. }
  955. }
  956. } elseif( $hebrewMonth == 2 && $yearPattern == 2 ) {
  957. # Cheshvan in a complete year (otherwise as the rule below)
  958. $days = 30;
  959. } elseif( $hebrewMonth == 3 && $yearPattern == 0 ) {
  960. # Kislev in an incomplete year (otherwise as the rule below)
  961. $days = 29;
  962. } else {
  963. # Odd months have 30 days, even have 29
  964. $days = 30 - ( $hebrewMonth - 1 ) % 2;
  965. }
  966. if( $hebrewDay <= $days ) {
  967. # In the current month
  968. break;
  969. } else {
  970. # Subtract the days of the current month
  971. $hebrewDay -= $days;
  972. # Try in the next month
  973. $hebrewMonth++;
  974. }
  975. }
  976. return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
  977. }
  978. /**
  979. * This calculates the Hebrew year start, as days since 1 September.
  980. * Based on Carl Friedrich Gauss algorithm for finding Easter date.
  981. * Used for Hebrew date.
  982. */
  983. private static function hebrewYearStart( $year ) {
  984. $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
  985. $b = intval( ( $year - 1 ) % 4 );
  986. $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
  987. if( $m < 0 ) {
  988. $m--;
  989. }
  990. $Mar = intval( $m );
  991. if( $m < 0 ) {
  992. $m++;
  993. }
  994. $m -= $Mar;
  995. $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7);
  996. if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
  997. $Mar++;
  998. } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
  999. $Mar += 2;
  1000. } else if( $c == 2 || $c == 4 || $c == 6 ) {
  1001. $Mar++;
  1002. }
  1003. $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
  1004. return $Mar;
  1005. }
  1006. /**
  1007. * Algorithm to convert Gregorian dates to Thai solar dates.
  1008. *
  1009. * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
  1010. *
  1011. * @param $ts String: 14-character timestamp
  1012. * @return array converted year, month, day
  1013. */
  1014. private static function tsToThai( $ts ) {
  1015. $gy = substr( $ts, 0, 4 );
  1016. $gm = substr( $ts, 4, 2 );
  1017. $gd = substr( $ts, 6, 2 );
  1018. # Add 543 years to the Gregorian calendar
  1019. # Months and days are identical
  1020. $gy_thai = $gy + 543;
  1021. return array( $gy_thai, $gm, $gd );
  1022. }
  1023. /**
  1024. * Roman number formatting up to 3000
  1025. */
  1026. static function romanNumeral( $num ) {
  1027. static $table = array(
  1028. array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
  1029. array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
  1030. array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
  1031. array( '', 'M', 'MM', 'MMM' )
  1032. );
  1033. $num = intval( $num );
  1034. if ( $num > 3000 || $num <= 0 ) {
  1035. return $num;
  1036. }
  1037. $s = '';
  1038. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1039. if ( $num >= $pow10 ) {
  1040. $s .= $table[$i][floor($num / $pow10)];
  1041. }
  1042. $num = $num % $pow10;
  1043. }
  1044. return $s;
  1045. }
  1046. /**
  1047. * Hebrew Gematria number formatting up to 9999
  1048. */
  1049. static function hebrewNumeral( $num ) {
  1050. static $table = array(
  1051. array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
  1052. array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
  1053. array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
  1054. array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
  1055. );
  1056. $num = intval( $num );
  1057. if ( $num > 9999 || $num <= 0 ) {
  1058. return $num;
  1059. }
  1060. $s = '';
  1061. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1062. if ( $num >= $pow10 ) {
  1063. if ( $num == 15 || $num == 16 ) {
  1064. $s .= $table[0][9] . $table[0][$num - 9];
  1065. $num = 0;
  1066. } else {
  1067. $s .= $table[$i][intval( ( $num / $pow10 ) )];
  1068. if( $pow10 == 1000 ) {
  1069. $s .= "'";
  1070. }
  1071. }
  1072. }
  1073. $num = $num % $pow10;
  1074. }
  1075. if( strlen( $s ) == 2 ) {
  1076. $str = $s . "'";
  1077. } else {
  1078. $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
  1079. $str .= substr( $s, strlen( $s ) - 2, 2 );
  1080. }
  1081. $start = substr( $str, 0, strlen( $str ) - 2 );
  1082. $end = substr( $str, strlen( $str ) - 2 );
  1083. switch( $end ) {
  1084. case 'כ':
  1085. $str = $start . 'ך';
  1086. break;
  1087. case 'מ':
  1088. $str = $start . 'ם';
  1089. break;
  1090. case 'נ':
  1091. $str = $start . 'ן';
  1092. break;
  1093. case 'פ':
  1094. $str = $start . 'ף';
  1095. break;
  1096. case 'צ':
  1097. $str = $start . 'ץ';
  1098. break;
  1099. }
  1100. return $str;
  1101. }
  1102. /**
  1103. * This is meant to be used by time(), date(), and timeanddate() to get
  1104. * the date preference they're supposed to use, it should be used in
  1105. * all children.
  1106. *
  1107. *<code>
  1108. * function timeanddate([...], $format = true) {
  1109. * $datePreference = $this->dateFormat($format);
  1110. * [...]
  1111. * }
  1112. *</code>
  1113. *
  1114. * @param $usePrefs Mixed: if true, the user's preference is used
  1115. * if false, the site/language default is used
  1116. * if int/string, assumed to be a format.
  1117. * @return string
  1118. */
  1119. function dateFormat( $usePrefs = true ) {
  1120. global $wgUser;
  1121. if( is_bool( $usePrefs ) ) {
  1122. if( $usePrefs ) {
  1123. $datePreference = $wgUser->getDatePreference();
  1124. } else {
  1125. $options = User::getDefaultOptions();
  1126. $datePreference = (string)$options['date'];
  1127. }
  1128. } else {
  1129. $datePreference = (string)$usePrefs;
  1130. }
  1131. // return int
  1132. if( $datePreference == '' ) {
  1133. return 'default';
  1134. }
  1135. return $datePreference;
  1136. }
  1137. /**
  1138. * @param $ts Mixed: the time format which needs to be turned into a
  1139. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1140. * @param $adj Bool: whether to adjust the time output according to the
  1141. * user configured offset ($timecorrection)
  1142. * @param $format Mixed: true to use user's date format preference
  1143. * @param $timecorrection String: the time offset as returned by
  1144. * validateTimeZone() in Special:Preferences
  1145. * @return string
  1146. */
  1147. function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
  1148. $this->load();
  1149. if ( $adj ) {
  1150. $ts = $this->userAdjust( $ts, $timecorrection );
  1151. }
  1152. $pref = $this->dateFormat( $format );
  1153. if( $pref == 'default' || !isset( $this->dateFormats["$pref date"] ) ) {
  1154. $pref = $this->defaultDateFormat;
  1155. }
  1156. return $this->sprintfDate( $this->dateFormats["$pref date"], $ts );
  1157. }
  1158. /**
  1159. * @param $ts Mixed: the time format which needs to be turned into a
  1160. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1161. * @param $adj Bool: whether to adjust the time output according to the
  1162. * user configured offset ($timecorrection)
  1163. * @param $format Mixed: true to use user's date format preference
  1164. * @param $timecorrection String: the time offset as returned by
  1165. * validateTimeZone() in Special:Preferences
  1166. * @return string
  1167. */
  1168. function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
  1169. $this->load();
  1170. if ( $adj ) {
  1171. $ts = $this->userAdjust( $ts, $timecorrection );
  1172. }
  1173. $pref = $this->dateFormat( $format );
  1174. if( $pref == 'default' || !isset( $this->dateFormats["$pref time"] ) ) {
  1175. $pref = $this->defaultDateFormat;
  1176. }
  1177. return $this->sprintfDate( $this->dateFormats["$pref time"], $ts );
  1178. }
  1179. /**
  1180. * @param $ts Mixed: the time format which needs to be turned into a
  1181. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1182. * @param $adj Bool: whether to adjust the time output according to the
  1183. * user configured offset ($timecorrection)
  1184. * @param $format Mixed: what format to return, if it's false output the
  1185. * default one (default true)
  1186. * @param $timecorrection String: the time offset as returned by
  1187. * validateTimeZone() in Special:Preferences
  1188. * @return string
  1189. */
  1190. function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
  1191. $this->load();
  1192. $ts = wfTimestamp( TS_MW, $ts );
  1193. if ( $adj ) {
  1194. $ts = $this->userAdjust( $ts, $timecorrection );
  1195. }
  1196. $pref = $this->dateFormat( $format );
  1197. if( $pref == 'default' || !isset( $this->dateFormats["$pref both"] ) ) {
  1198. $pref = $this->defaultDateFormat;
  1199. }
  1200. return $this->sprintfDate( $this->dateFormats["$pref both"], $ts );
  1201. }
  1202. function getMessage( $key ) {
  1203. $this->load();
  1204. return isset( $this->messages[$key] ) ? $this->messages[$key] : null;
  1205. }
  1206. function getAllMessages() {
  1207. $this->load();
  1208. return $this->messages;
  1209. }
  1210. function iconv( $in, $out, $string ) {
  1211. # For most languages, this is a wrapper for iconv
  1212. return iconv( $in, $out . '//IGNORE', $string );
  1213. }
  1214. // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
  1215. function ucwordbreaksCallbackAscii($matches){
  1216. return $this->ucfirst($matches[1]);
  1217. }
  1218. function ucwordbreaksCallbackMB($matches){
  1219. return mb_strtoupper($matches[0]);
  1220. }
  1221. function ucCallback($matches){
  1222. list( $wikiUpperChars ) = self::getCaseMaps();
  1223. return strtr( $matches[1], $wikiUpperChars );
  1224. }
  1225. function lcCallback($matches){
  1226. list( , $wikiLowerChars ) = self::getCaseMaps();
  1227. return strtr( $matches[1], $wikiLowerChars );
  1228. }
  1229. function ucwordsCallbackMB($matches){
  1230. return mb_strtoupper($matches[0]);
  1231. }
  1232. function ucwordsCallbackWiki($matches){
  1233. list( $wikiUpperChars ) = self::getCaseMaps();
  1234. return strtr( $matches[0], $wikiUpperChars );
  1235. }
  1236. function ucfirst( $str ) {
  1237. if ( empty($str) ) return $str;
  1238. if ( ord($str[0]) < 128 ) return ucfirst($str);
  1239. else return self::uc($str,true); // fall back to more complex logic in case of multibyte strings
  1240. }
  1241. function uc( $str, $first = false ) {
  1242. if ( function_exists( 'mb_strtoupper' ) ) {
  1243. if ( $first ) {
  1244. if ( self::isMultibyte( $str ) ) {
  1245. return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  1246. } else {
  1247. return ucfirst( $str );
  1248. }
  1249. } else {
  1250. return self::isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
  1251. }
  1252. } else {
  1253. if ( self::isMultibyte( $str ) ) {
  1254. list( $wikiUpperChars ) = $this->getCaseMaps();
  1255. $x = $first ? '^' : '';
  1256. return preg_replace_callback(
  1257. "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
  1258. array($this,"ucCallback"),
  1259. $str
  1260. );
  1261. } else {
  1262. return $first ? ucfirst( $str ) : strtoupper( $str );
  1263. }
  1264. }
  1265. }
  1266. function lcfirst( $str ) {
  1267. if ( empty($str) ) return $str;
  1268. if ( is_string( $str ) && ord($str[0]) < 128 ) {
  1269. // editing string in place = cool
  1270. $str[0]=strtolower($str[0]);
  1271. return $str;
  1272. }
  1273. else return self::lc( $str, true );
  1274. }
  1275. function lc( $str, $first = false ) {
  1276. if ( function_exists( 'mb_strtolower' ) )
  1277. if ( $first )
  1278. if ( self::isMultibyte( $str ) )
  1279. return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  1280. else
  1281. return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
  1282. else
  1283. return self::isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
  1284. else
  1285. if ( self::isMultibyte( $str ) ) {
  1286. list( , $wikiLowerChars ) = self::getCaseMaps();
  1287. $x = $first ? '^' : '';
  1288. return preg_replace_callback(
  1289. "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
  1290. array($this,"lcCallback"),
  1291. $str
  1292. );
  1293. } else
  1294. return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
  1295. }
  1296. function isMultibyte( $str ) {
  1297. return (bool)preg_match( '/[\x80-\xff]/', $str );
  1298. }
  1299. function ucwords($str) {
  1300. if ( self::isMultibyte( $str ) ) {
  1301. $str = self::lc($str);
  1302. // regexp to find first letter in each word (i.e. after each space)
  1303. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  1304. // function to use to capitalize a single char
  1305. if ( function_exists( 'mb_strtoupper' ) )
  1306. return preg_replace_callback(
  1307. $replaceRegexp,
  1308. array($this,"ucwordsCallbackMB"),
  1309. $str
  1310. );
  1311. else
  1312. return preg_replace_callback(
  1313. $replaceRegexp,
  1314. array($this,"ucwordsCallbackWiki"),
  1315. $str
  1316. );
  1317. }
  1318. else
  1319. return ucwords( strtolower( $str ) );
  1320. }
  1321. # capitalize words at word breaks
  1322. function ucwordbreaks($str){
  1323. if (self::isMultibyte( $str ) ) {
  1324. $str = self::lc($str);
  1325. // since \b doesn't work for UTF-8, we explicitely define word break chars
  1326. $breaks= "[ \-\(\)\}\{\.,\?!]";
  1327. // find first letter after word break
  1328. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  1329. if ( function_exists( 'mb_strtoupper' ) )
  1330. return preg_replace_callback(
  1331. $replaceRegexp,
  1332. array($this,"ucwordbreaksCallbackMB"),
  1333. $str
  1334. );
  1335. else
  1336. return preg_replace_callback(
  1337. $replaceRegexp,
  1338. array($this,"ucwordsCallbackWiki"),
  1339. $str
  1340. );
  1341. }
  1342. else
  1343. return preg_replace_callback(
  1344. '/\b([\w\x80-\xff]+)\b/',
  1345. array($this,"ucwordbreaksCallbackAscii"),
  1346. $str );
  1347. }
  1348. /**
  1349. * Return a case-folded representation of $s
  1350. *
  1351. * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
  1352. * and $s2 are the same except for the case of their characters. It is not
  1353. * necessary for the value returned to make sense when displayed.
  1354. *
  1355. * Do *not* perform any other normalisation in this function. If a caller
  1356. * uses this function when it should be using a more general normalisation
  1357. * function, then fix the caller.
  1358. */
  1359. function caseFold( $s ) {
  1360. return $this->uc( $s );
  1361. }
  1362. function checkTitleEncoding( $s ) {
  1363. if( is_array( $s ) ) {
  1364. wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
  1365. }
  1366. # Check for non-UTF-8 URLs
  1367. $ishigh = preg_match( '/[\x80-\xff]/', $s);
  1368. if(!$ishigh) return $s;
  1369. $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
  1370. '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
  1371. if( $isutf8 ) return $s;
  1372. return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
  1373. }
  1374. function fallback8bitEncoding() {
  1375. $this->load();
  1376. return $this->fallback8bitEncoding;
  1377. }
  1378. /**
  1379. * Some languages have special punctuation to strip out
  1380. * or characters which need to be converted for MySQL's
  1381. * indexing to grok it correctly. Make such changes here.
  1382. *
  1383. * @param $string String
  1384. * @return String
  1385. */
  1386. function stripForSearch( $string ) {
  1387. global $wgDBtype;
  1388. if ( $wgDBtype != 'mysql' ) {
  1389. return $string;
  1390. }
  1391. wfProfileIn( __METHOD__ );
  1392. // MySQL fulltext index doesn't grok utf-8, so we
  1393. // need to fold cases and convert to hex
  1394. $out = preg_replace_callback(
  1395. "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
  1396. array( $this, 'stripForSearchCallback' ),
  1397. $this->lc( $string ) );
  1398. // And to add insult to injury, the default indexing
  1399. // ignores short words... Pad them so we can pass them
  1400. // through without reconfiguring the server...
  1401. $minLength = $this->minSearchLength();
  1402. if( $minLength > 1 ) {
  1403. $n = $minLength-1;
  1404. $out = preg_replace(
  1405. "/\b(\w{1,$n})\b/",
  1406. "$1u800",
  1407. $out );
  1408. }
  1409. // Periods within things like hostnames and IP addresses
  1410. // are also important -- we want a search for "example.com"
  1411. // or "192.168.1.1" to work sanely.
  1412. //
  1413. // MySQL's search seems to ignore them, so you'd match on
  1414. // "example.wikipedia.com" and "192.168.83.1" as well.
  1415. $out = preg_replace(
  1416. "/(\w)\.(\w|\*)/u",
  1417. "$1u82e$2",
  1418. $out );
  1419. wfProfileOut( __METHOD__ );
  1420. return $out;
  1421. }
  1422. /**
  1423. * Armor a case-folded UTF-8 string to get through MySQL's
  1424. * fulltext search without being mucked up by funny charset
  1425. * settings or anything else of the sort.
  1426. */
  1427. protected function stripForSearchCallback( $matches ) {
  1428. return 'u8' . bin2hex( $matches[1] );
  1429. }
  1430. /**
  1431. * Check MySQL server's ft_min_word_len setting so we know
  1432. * if we need to pad short words...
  1433. */
  1434. protected function minSearchLength() {
  1435. if( !isset( $this->minSearchLength ) ) {
  1436. $sql = "show global variables like 'ft\\_min\\_word\\_len'";
  1437. $dbr = wfGetDB( DB_SLAVE );
  1438. $result = $dbr->query( $sql );
  1439. $row = $result->fetchObject();
  1440. $result->free();
  1441. if( $row && $row->Variable_name == 'ft_min_word_len' ) {
  1442. $this->minSearchLength = intval( $row->Value );
  1443. } else {
  1444. $this->minSearchLength = 0;
  1445. }
  1446. }
  1447. return $this->minSearchLength;
  1448. }
  1449. function convertForSearchResult( $termsArray ) {
  1450. # some languages, e.g. Chinese, need to do a conversion
  1451. # in order for search results to be displayed correctly
  1452. return $termsArray;
  1453. }
  1454. /**
  1455. * Get the first character of a string.
  1456. *
  1457. * @param $s string
  1458. * @return string
  1459. */
  1460. function firstChar( $s ) {
  1461. $matches = array();
  1462. preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
  1463. '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
  1464. if ( isset( $matches[1] ) ) {
  1465. if ( strlen( $matches[1] ) != 3 ) {
  1466. return $matches[1];
  1467. }
  1468. // Break down Hangul syllables to grab the first jamo
  1469. $code = utf8ToCodepoint( $matches[1] );
  1470. if ( $code < 0xac00 || 0xd7a4 <= $code) {
  1471. return $matches[1];
  1472. } elseif ( $code < 0xb098 ) {
  1473. return "\xe3\x84\xb1";
  1474. } elseif ( $code < 0xb2e4 ) {
  1475. return "\xe3\x84\xb4";
  1476. } elseif ( $code < 0xb77c ) {
  1477. return "\xe3\x84\xb7";
  1478. } elseif ( $code < 0xb9c8 ) {
  1479. return "\xe3\x84\xb9";
  1480. } elseif ( $code < 0xbc14 ) {
  1481. return "\xe3\x85\x81";
  1482. } elseif ( $code < 0xc0ac ) {
  1483. return "\xe3\x85\x82";
  1484. } elseif ( $code < 0xc544 ) {
  1485. return "\xe3\x85\x85";
  1486. } elseif ( $code < 0xc790 ) {
  1487. return "\xe3\x85\x87";
  1488. } elseif ( $code < 0xcc28 ) {
  1489. return "\xe3\x85\x88";
  1490. } elseif ( $code < 0xce74 ) {
  1491. return "\xe3\x85\x8a";
  1492. } elseif ( $code < 0xd0c0 ) {
  1493. return "\xe3\x85\x8b";
  1494. } elseif ( $code < 0xd30c ) {
  1495. return "\xe3\x85\x8c";
  1496. } elseif ( $code < 0xd558 ) {
  1497. return "\xe3\x85\x8d";
  1498. } else {
  1499. return "\xe3\x85\x8e";
  1500. }
  1501. } else {
  1502. return "";
  1503. }
  1504. }
  1505. function initEncoding() {
  1506. # Some languages may have an alternate char encoding option
  1507. # (Esperanto X-coding, Japanese furigana conversion, etc)
  1508. # If this language is used as the primary content language,
  1509. # an override to the defaults can be set here on startup.
  1510. }
  1511. function recodeForEdit( $s ) {
  1512. # For some languages we'll want to explicitly specify
  1513. # which characters make it into the edit box raw
  1514. # or are converted in some way or another.
  1515. # Note that if wgOutputEncoding is different from
  1516. # wgInputEncoding, this text will be further converted
  1517. # to wgOutputEncoding.
  1518. global $wgEditEncoding;
  1519. if( $wgEditEncoding == '' or
  1520. $wgEditEncoding == 'UTF-8' ) {
  1521. return $s;
  1522. } else {
  1523. return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
  1524. }
  1525. }
  1526. function recodeInput( $s ) {
  1527. # Take the previous into account.
  1528. global $wgEditEncoding;
  1529. if($wgEditEncoding != "") {
  1530. $enc = $wgEditEncoding;
  1531. } else {
  1532. $enc = 'UTF-8';
  1533. }
  1534. if( $enc == 'UTF-8' ) {
  1535. return $s;
  1536. } else {
  1537. return $this->iconv( $enc, 'UTF-8', $s );
  1538. }
  1539. }
  1540. /**
  1541. * For right-to-left language support
  1542. *
  1543. * @return bool
  1544. */
  1545. function isRTL() {
  1546. $this->load();
  1547. return $this->rtl;
  1548. }
  1549. /**
  1550. * A hidden direction mark (LRM or RLM), depending on the language direction
  1551. *
  1552. * @return string
  1553. */
  1554. function getDirMark() {
  1555. return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
  1556. }
  1557. /**
  1558. * An arrow, depending on the language direction
  1559. *
  1560. * @return string
  1561. */
  1562. function getArrow() {
  1563. return $this->isRTL() ? '←' : '→';
  1564. }
  1565. /**
  1566. * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
  1567. *
  1568. * @return bool
  1569. */
  1570. function linkPrefixExtension() {
  1571. $this->load();
  1572. return $this->linkPrefixExtension;
  1573. }
  1574. function &getMagicWords() {
  1575. $this->load();
  1576. return $this->magicWords;
  1577. }
  1578. # Fill a MagicWord object with data from here
  1579. function getMagic( &$mw ) {
  1580. if ( !$this->mMagicHookDone ) {
  1581. $this->mMagicHookDone = true;
  1582. wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
  1583. }
  1584. if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
  1585. $rawEntry = $this->mMagicExtensions[$mw->mId];
  1586. } else {
  1587. $magicWords =& $this->getMagicWords();
  1588. if ( isset( $magicWords[$mw->mId] ) ) {
  1589. $rawEntry = $magicWords[$mw->mId];
  1590. } else {
  1591. # Fall back to English if local list is incomplete
  1592. $magicWords =& Language::getMagicWords();
  1593. if ( !isset($magicWords[$mw->mId]) ) {
  1594. throw new MWException("Ma…

Large files files are truncated, but you can click here to view the full file