PageRenderTime 63ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/languages/Language.php

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