Language.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736
  1. <?php
  2. /**
  3. * @defgroup Language Language
  4. *
  5. * @file
  6. * @ingroup Language
  7. */
  8. if( !defined( 'MEDIAWIKI' ) ) {
  9. echo "This file is part of MediaWiki, it is not a valid entry point.\n";
  10. exit( 1 );
  11. }
  12. # Read language names
  13. global $wgLanguageNames;
  14. require_once( dirname(__FILE__) . '/Names.php' ) ;
  15. global $wgInputEncoding, $wgOutputEncoding;
  16. /**
  17. * These are always UTF-8, they exist only for backwards compatibility
  18. */
  19. $wgInputEncoding = "UTF-8";
  20. $wgOutputEncoding = "UTF-8";
  21. if( function_exists( 'mb_strtoupper' ) ) {
  22. mb_internal_encoding('UTF-8');
  23. }
  24. /**
  25. * a fake language converter
  26. *
  27. * @ingroup Language
  28. */
  29. class FakeConverter {
  30. var $mLang;
  31. function FakeConverter($langobj) {$this->mLang = $langobj;}
  32. function convert($t, $i) {return $t;}
  33. function parserConvert($t, $p) {return $t;}
  34. function getVariants() { return array( $this->mLang->getCode() ); }
  35. function getPreferredVariant() {return $this->mLang->getCode(); }
  36. function findVariantLink(&$l, &$n, $ignoreOtherCond = false) {}
  37. function getExtraHashOptions() {return '';}
  38. function getParsedTitle() {return '';}
  39. function markNoConversion($text, $noParse=false) {return $text;}
  40. function convertCategoryKey( $key ) {return $key; }
  41. function convertLinkToAllVariants($text){ return array( $this->mLang->getCode() => $text); }
  42. function armourMath($text){ return $text; }
  43. }
  44. /**
  45. * Internationalisation code
  46. * @ingroup Language
  47. */
  48. class Language {
  49. var $mConverter, $mVariants, $mCode, $mLoaded = false;
  50. var $mMagicExtensions = array(), $mMagicHookDone = false;
  51. static public $mLocalisationKeys = array(
  52. 'fallback', 'namespaceNames', 'mathNames', 'bookstoreList',
  53. 'magicWords', 'messages', 'rtl', 'digitTransformTable',
  54. 'separatorTransformTable', 'fallback8bitEncoding', 'linkPrefixExtension',
  55. 'defaultUserOptionOverrides', 'linkTrail', 'namespaceAliases',
  56. 'dateFormats', 'datePreferences', 'datePreferenceMigrationMap',
  57. 'defaultDateFormat', 'extraUserToggles', 'specialPageAliases',
  58. 'imageFiles'
  59. );
  60. static public $mMergeableMapKeys = array( 'messages', 'namespaceNames', 'mathNames',
  61. 'dateFormats', 'defaultUserOptionOverrides', 'magicWords', 'imageFiles' );
  62. static public $mMergeableListKeys = array( 'extraUserToggles' );
  63. static public $mMergeableAliasListKeys = array( 'specialPageAliases' );
  64. static public $mLocalisationCache = array();
  65. static public $mLangObjCache = array();
  66. static public $mWeekdayMsgs = array(
  67. 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
  68. 'friday', 'saturday'
  69. );
  70. static public $mWeekdayAbbrevMsgs = array(
  71. 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
  72. );
  73. static public $mMonthMsgs = array(
  74. 'january', 'february', 'march', 'april', 'may_long', 'june',
  75. 'july', 'august', 'september', 'october', 'november',
  76. 'december'
  77. );
  78. static public $mMonthGenMsgs = array(
  79. 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
  80. 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
  81. 'december-gen'
  82. );
  83. static public $mMonthAbbrevMsgs = array(
  84. 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
  85. 'sep', 'oct', 'nov', 'dec'
  86. );
  87. static public $mIranianCalendarMonthMsgs = array(
  88. 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
  89. 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
  90. 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
  91. 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
  92. );
  93. static public $mHebrewCalendarMonthMsgs = array(
  94. 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
  95. 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
  96. 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
  97. 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
  98. 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
  99. );
  100. static public $mHebrewCalendarMonthGenMsgs = array(
  101. 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
  102. 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
  103. 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
  104. 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
  105. 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
  106. );
  107. static public $mHijriCalendarMonthMsgs = array(
  108. 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
  109. 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
  110. 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
  111. 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
  112. );
  113. /**
  114. * Get a cached language object for a given language code
  115. */
  116. static function factory( $code ) {
  117. if ( !isset( self::$mLangObjCache[$code] ) ) {
  118. if( count( self::$mLangObjCache ) > 10 ) {
  119. // Don't keep a billion objects around, that's stupid.
  120. self::$mLangObjCache = array();
  121. }
  122. self::$mLangObjCache[$code] = self::newFromCode( $code );
  123. }
  124. return self::$mLangObjCache[$code];
  125. }
  126. /**
  127. * Create a language object for a given language code
  128. */
  129. protected static function newFromCode( $code ) {
  130. global $IP;
  131. static $recursionLevel = 0;
  132. if ( $code == 'en' ) {
  133. $class = 'Language';
  134. } else {
  135. $class = 'Language' . str_replace( '-', '_', ucfirst( $code ) );
  136. // Preload base classes to work around APC/PHP5 bug
  137. if ( file_exists( "$IP/languages/classes/$class.deps.php" ) ) {
  138. include_once("$IP/languages/classes/$class.deps.php");
  139. }
  140. if ( file_exists( "$IP/languages/classes/$class.php" ) ) {
  141. include_once("$IP/languages/classes/$class.php");
  142. }
  143. }
  144. if ( $recursionLevel > 5 ) {
  145. throw new MWException( "Language fallback loop detected when creating class $class\n" );
  146. }
  147. if( ! class_exists( $class ) ) {
  148. $fallback = Language::getFallbackFor( $code );
  149. ++$recursionLevel;
  150. $lang = Language::newFromCode( $fallback );
  151. --$recursionLevel;
  152. $lang->setCode( $code );
  153. } else {
  154. $lang = new $class;
  155. }
  156. return $lang;
  157. }
  158. function __construct() {
  159. $this->mConverter = new FakeConverter($this);
  160. // Set the code to the name of the descendant
  161. if ( get_class( $this ) == 'Language' ) {
  162. $this->mCode = 'en';
  163. } else {
  164. $this->mCode = str_replace( '_', '-', strtolower( substr( get_class( $this ), 8 ) ) );
  165. }
  166. }
  167. /**
  168. * Reduce memory usage
  169. */
  170. function __destruct() {
  171. foreach ( $this as $name => $value ) {
  172. unset( $this->$name );
  173. }
  174. }
  175. /**
  176. * Hook which will be called if this is the content language.
  177. * Descendants can use this to register hook functions or modify globals
  178. */
  179. function initContLang() {}
  180. /**
  181. * @deprecated Use User::getDefaultOptions()
  182. * @return array
  183. */
  184. function getDefaultUserOptions() {
  185. wfDeprecated( __METHOD__ );
  186. return User::getDefaultOptions();
  187. }
  188. function getFallbackLanguageCode() {
  189. return self::getFallbackFor( $this->mCode );
  190. }
  191. /**
  192. * Exports $wgBookstoreListEn
  193. * @return array
  194. */
  195. function getBookstoreList() {
  196. $this->load();
  197. return $this->bookstoreList;
  198. }
  199. /**
  200. * @return array
  201. */
  202. function getNamespaces() {
  203. $this->load();
  204. return $this->namespaceNames;
  205. }
  206. /**
  207. * A convenience function that returns the same thing as
  208. * getNamespaces() except with the array values changed to ' '
  209. * where it found '_', useful for producing output to be displayed
  210. * e.g. in <select> forms.
  211. *
  212. * @return array
  213. */
  214. function getFormattedNamespaces() {
  215. $ns = $this->getNamespaces();
  216. foreach($ns as $k => $v) {
  217. $ns[$k] = strtr($v, '_', ' ');
  218. }
  219. return $ns;
  220. }
  221. /**
  222. * Get a namespace value by key
  223. * <code>
  224. * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
  225. * echo $mw_ns; // prints 'MediaWiki'
  226. * </code>
  227. *
  228. * @param $index Int: the array key of the namespace to return
  229. * @return mixed, string if the namespace value exists, otherwise false
  230. */
  231. function getNsText( $index ) {
  232. $ns = $this->getNamespaces();
  233. return isset( $ns[$index] ) ? $ns[$index] : false;
  234. }
  235. /**
  236. * A convenience function that returns the same thing as
  237. * getNsText() except with '_' changed to ' ', useful for
  238. * producing output.
  239. *
  240. * @return array
  241. */
  242. function getFormattedNsText( $index ) {
  243. $ns = $this->getNsText( $index );
  244. return strtr($ns, '_', ' ');
  245. }
  246. /**
  247. * Get a namespace key by value, case insensitive.
  248. * Only matches namespace names for the current language, not the
  249. * canonical ones defined in Namespace.php.
  250. *
  251. * @param $text String
  252. * @return mixed An integer if $text is a valid value otherwise false
  253. */
  254. function getLocalNsIndex( $text ) {
  255. $this->load();
  256. $lctext = $this->lc($text);
  257. return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
  258. }
  259. /**
  260. * Get a namespace key by value, case insensitive. Canonical namespace
  261. * names override custom ones defined for the current language.
  262. *
  263. * @param $text String
  264. * @return mixed An integer if $text is a valid value otherwise false
  265. */
  266. function getNsIndex( $text ) {
  267. $this->load();
  268. $lctext = $this->lc($text);
  269. if( ( $ns = MWNamespace::getCanonicalIndex( $lctext ) ) !== null ) return $ns;
  270. return isset( $this->mNamespaceIds[$lctext] ) ? $this->mNamespaceIds[$lctext] : false;
  271. }
  272. /**
  273. * short names for language variants used for language conversion links.
  274. *
  275. * @param $code String
  276. * @return string
  277. */
  278. function getVariantname( $code ) {
  279. return $this->getMessageFromDB( "variantname-$code" );
  280. }
  281. function specialPage( $name ) {
  282. $aliases = $this->getSpecialPageAliases();
  283. if ( isset( $aliases[$name][0] ) ) {
  284. $name = $aliases[$name][0];
  285. }
  286. return $this->getNsText( NS_SPECIAL ) . ':' . $name;
  287. }
  288. function getQuickbarSettings() {
  289. return array(
  290. $this->getMessage( 'qbsettings-none' ),
  291. $this->getMessage( 'qbsettings-fixedleft' ),
  292. $this->getMessage( 'qbsettings-fixedright' ),
  293. $this->getMessage( 'qbsettings-floatingleft' ),
  294. $this->getMessage( 'qbsettings-floatingright' )
  295. );
  296. }
  297. function getMathNames() {
  298. $this->load();
  299. return $this->mathNames;
  300. }
  301. function getDatePreferences() {
  302. $this->load();
  303. return $this->datePreferences;
  304. }
  305. function getDateFormats() {
  306. $this->load();
  307. return $this->dateFormats;
  308. }
  309. function getDefaultDateFormat() {
  310. $this->load();
  311. return $this->defaultDateFormat;
  312. }
  313. function getDatePreferenceMigrationMap() {
  314. $this->load();
  315. return $this->datePreferenceMigrationMap;
  316. }
  317. function getImageFile( $image ) {
  318. $this->load();
  319. return $this->imageFiles[$image];
  320. }
  321. function getDefaultUserOptionOverrides() {
  322. $this->load();
  323. # XXX - apparently some languageas get empty arrays, didn't get to it yet -- midom
  324. if (is_array($this->defaultUserOptionOverrides)) {
  325. return $this->defaultUserOptionOverrides;
  326. } else {
  327. return array();
  328. }
  329. }
  330. function getExtraUserToggles() {
  331. $this->load();
  332. return $this->extraUserToggles;
  333. }
  334. function getUserToggle( $tog ) {
  335. return $this->getMessageFromDB( "tog-$tog" );
  336. }
  337. /**
  338. * Get language names, indexed by code.
  339. * If $customisedOnly is true, only returns codes with a messages file
  340. */
  341. public static function getLanguageNames( $customisedOnly = false ) {
  342. global $wgLanguageNames, $wgExtraLanguageNames;
  343. $allNames = $wgExtraLanguageNames + $wgLanguageNames;
  344. if ( !$customisedOnly ) {
  345. return $allNames;
  346. }
  347. global $IP;
  348. $names = array();
  349. $dir = opendir( "$IP/languages/messages" );
  350. while( false !== ( $file = readdir( $dir ) ) ) {
  351. $m = array();
  352. if( preg_match( '/Messages([A-Z][a-z_]+)\.php$/', $file, $m ) ) {
  353. $code = str_replace( '_', '-', strtolower( $m[1] ) );
  354. if ( isset( $allNames[$code] ) ) {
  355. $names[$code] = $allNames[$code];
  356. }
  357. }
  358. }
  359. closedir( $dir );
  360. return $names;
  361. }
  362. /**
  363. * Get a message from the MediaWiki namespace.
  364. *
  365. * @param $msg String: message name
  366. * @return string
  367. */
  368. function getMessageFromDB( $msg ) {
  369. return wfMsgExt( $msg, array( 'parsemag', 'language' => $this ) );
  370. }
  371. function getLanguageName( $code ) {
  372. $names = self::getLanguageNames();
  373. if ( !array_key_exists( $code, $names ) ) {
  374. return '';
  375. }
  376. return $names[$code];
  377. }
  378. function getMonthName( $key ) {
  379. return $this->getMessageFromDB( self::$mMonthMsgs[$key-1] );
  380. }
  381. function getMonthNameGen( $key ) {
  382. return $this->getMessageFromDB( self::$mMonthGenMsgs[$key-1] );
  383. }
  384. function getMonthAbbreviation( $key ) {
  385. return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key-1] );
  386. }
  387. function getWeekdayName( $key ) {
  388. return $this->getMessageFromDB( self::$mWeekdayMsgs[$key-1] );
  389. }
  390. function getWeekdayAbbreviation( $key ) {
  391. return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key-1] );
  392. }
  393. function getIranianCalendarMonthName( $key ) {
  394. return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key-1] );
  395. }
  396. function getHebrewCalendarMonthName( $key ) {
  397. return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key-1] );
  398. }
  399. function getHebrewCalendarMonthNameGen( $key ) {
  400. return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key-1] );
  401. }
  402. function getHijriCalendarMonthName( $key ) {
  403. return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key-1] );
  404. }
  405. /**
  406. * Used by date() and time() to adjust the time output.
  407. *
  408. * @param $ts Int the time in date('YmdHis') format
  409. * @param $tz Mixed: adjust the time by this amount (default false, mean we
  410. * get user timecorrection setting)
  411. * @return int
  412. */
  413. function userAdjust( $ts, $tz = false ) {
  414. global $wgUser, $wgLocalTZoffset;
  415. if ( $tz === false ) {
  416. $tz = $wgUser->getOption( 'timecorrection' );
  417. }
  418. $data = explode( '|', $tz, 3 );
  419. if ( $data[0] == 'ZoneInfo' ) {
  420. if ( function_exists( 'timezone_open' ) && @timezone_open( $data[2] ) !== false ) {
  421. $date = date_create( $ts, timezone_open( 'UTC' ) );
  422. date_timezone_set( $date, timezone_open( $data[2] ) );
  423. $date = date_format( $date, 'YmdHis' );
  424. return $date;
  425. }
  426. # Unrecognized timezone, default to 'Offset' with the stored offset.
  427. $data[0] = 'Offset';
  428. }
  429. $minDiff = 0;
  430. if ( $data[0] == 'System' || $tz == '' ) {
  431. # Global offset in minutes.
  432. if( isset($wgLocalTZoffset) ) $minDiff = $wgLocalTZoffset;
  433. } else if ( $data[0] == 'Offset' ) {
  434. $minDiff = intval( $data[1] );
  435. } else {
  436. $data = explode( ':', $tz );
  437. if( count( $data ) == 2 ) {
  438. $data[0] = intval( $data[0] );
  439. $data[1] = intval( $data[1] );
  440. $minDiff = abs( $data[0] ) * 60 + $data[1];
  441. if ( $data[0] < 0 ) $minDiff = -$minDiff;
  442. } else {
  443. $minDiff = intval( $data[0] ) * 60;
  444. }
  445. }
  446. # No difference ? Return time unchanged
  447. if ( 0 == $minDiff ) return $ts;
  448. wfSuppressWarnings(); // E_STRICT system time bitching
  449. # Generate an adjusted date; take advantage of the fact that mktime
  450. # will normalize out-of-range values so we don't have to split $minDiff
  451. # into hours and minutes.
  452. $t = mktime( (
  453. (int)substr( $ts, 8, 2) ), # Hours
  454. (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
  455. (int)substr( $ts, 12, 2 ), # Seconds
  456. (int)substr( $ts, 4, 2 ), # Month
  457. (int)substr( $ts, 6, 2 ), # Day
  458. (int)substr( $ts, 0, 4 ) ); #Year
  459. $date = date( 'YmdHis', $t );
  460. wfRestoreWarnings();
  461. return $date;
  462. }
  463. /**
  464. * This is a workalike of PHP's date() function, but with better
  465. * internationalisation, a reduced set of format characters, and a better
  466. * escaping format.
  467. *
  468. * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrU. See the
  469. * PHP manual for definitions. "o" format character is supported since
  470. * PHP 5.1.0, previous versions return literal o.
  471. * There are a number of extensions, which start with "x":
  472. *
  473. * xn Do not translate digits of the next numeric format character
  474. * xN Toggle raw digit (xn) flag, stays set until explicitly unset
  475. * xr Use roman numerals for the next numeric format character
  476. * xh Use hebrew numerals for the next numeric format character
  477. * xx Literal x
  478. * xg Genitive month name
  479. *
  480. * xij j (day number) in Iranian calendar
  481. * xiF F (month name) in Iranian calendar
  482. * xin n (month number) in Iranian calendar
  483. * xiY Y (full year) in Iranian calendar
  484. *
  485. * xjj j (day number) in Hebrew calendar
  486. * xjF F (month name) in Hebrew calendar
  487. * xjt t (days in month) in Hebrew calendar
  488. * xjx xg (genitive month name) in Hebrew calendar
  489. * xjn n (month number) in Hebrew calendar
  490. * xjY Y (full year) in Hebrew calendar
  491. *
  492. * xmj j (day number) in Hijri calendar
  493. * xmF F (month name) in Hijri calendar
  494. * xmn n (month number) in Hijri calendar
  495. * xmY Y (full year) in Hijri calendar
  496. *
  497. * xkY Y (full year) in Thai solar calendar. Months and days are
  498. * identical to the Gregorian calendar
  499. *
  500. * Characters enclosed in double quotes will be considered literal (with
  501. * the quotes themselves removed). Unmatched quotes will be considered
  502. * literal quotes. Example:
  503. *
  504. * "The month is" F => The month is January
  505. * i's" => 20'11"
  506. *
  507. * Backslash escaping is also supported.
  508. *
  509. * Input timestamp is assumed to be pre-normalized to the desired local
  510. * time zone, if any.
  511. *
  512. * @param $format String
  513. * @param $ts String: 14-character timestamp
  514. * YYYYMMDDHHMMSS
  515. * 01234567890123
  516. * @todo emulation of "o" format character for PHP pre 5.1.0
  517. * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
  518. */
  519. function sprintfDate( $format, $ts ) {
  520. $s = '';
  521. $raw = false;
  522. $roman = false;
  523. $hebrewNum = false;
  524. $unix = false;
  525. $rawToggle = false;
  526. $iranian = false;
  527. $hebrew = false;
  528. $hijri = false;
  529. $thai = false;
  530. for ( $p = 0; $p < strlen( $format ); $p++ ) {
  531. $num = false;
  532. $code = $format[$p];
  533. if ( $code == 'x' && $p < strlen( $format ) - 1 ) {
  534. $code .= $format[++$p];
  535. }
  536. if ( ( $code === 'xi' || $code == 'xj' || $code == 'xk' || $code == 'xm' ) && $p < strlen( $format ) - 1 ) {
  537. $code .= $format[++$p];
  538. }
  539. switch ( $code ) {
  540. case 'xx':
  541. $s .= 'x';
  542. break;
  543. case 'xn':
  544. $raw = true;
  545. break;
  546. case 'xN':
  547. $rawToggle = !$rawToggle;
  548. break;
  549. case 'xr':
  550. $roman = true;
  551. break;
  552. case 'xh':
  553. $hebrewNum = true;
  554. break;
  555. case 'xg':
  556. $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
  557. break;
  558. case 'xjx':
  559. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  560. $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
  561. break;
  562. case 'd':
  563. $num = substr( $ts, 6, 2 );
  564. break;
  565. case 'D':
  566. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  567. $s .= $this->getWeekdayAbbreviation( gmdate( 'w', $unix ) + 1 );
  568. break;
  569. case 'j':
  570. $num = intval( substr( $ts, 6, 2 ) );
  571. break;
  572. case 'xij':
  573. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  574. $num = $iranian[2];
  575. break;
  576. case 'xmj':
  577. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  578. $num = $hijri[2];
  579. break;
  580. case 'xjj':
  581. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  582. $num = $hebrew[2];
  583. break;
  584. case 'l':
  585. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  586. $s .= $this->getWeekdayName( gmdate( 'w', $unix ) + 1 );
  587. break;
  588. case 'N':
  589. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  590. $w = gmdate( 'w', $unix );
  591. $num = $w ? $w : 7;
  592. break;
  593. case 'w':
  594. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  595. $num = gmdate( 'w', $unix );
  596. break;
  597. case 'z':
  598. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  599. $num = gmdate( 'z', $unix );
  600. break;
  601. case 'W':
  602. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  603. $num = gmdate( 'W', $unix );
  604. break;
  605. case 'F':
  606. $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
  607. break;
  608. case 'xiF':
  609. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  610. $s .= $this->getIranianCalendarMonthName( $iranian[1] );
  611. break;
  612. case 'xmF':
  613. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  614. $s .= $this->getHijriCalendarMonthName( $hijri[1] );
  615. break;
  616. case 'xjF':
  617. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  618. $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
  619. break;
  620. case 'm':
  621. $num = substr( $ts, 4, 2 );
  622. break;
  623. case 'M':
  624. $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
  625. break;
  626. case 'n':
  627. $num = intval( substr( $ts, 4, 2 ) );
  628. break;
  629. case 'xin':
  630. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  631. $num = $iranian[1];
  632. break;
  633. case 'xmn':
  634. if ( !$hijri ) $hijri = self::tsToHijri ( $ts );
  635. $num = $hijri[1];
  636. break;
  637. case 'xjn':
  638. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  639. $num = $hebrew[1];
  640. break;
  641. case 't':
  642. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  643. $num = gmdate( 't', $unix );
  644. break;
  645. case 'xjt':
  646. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  647. $num = $hebrew[3];
  648. break;
  649. case 'L':
  650. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  651. $num = gmdate( 'L', $unix );
  652. break;
  653. # 'o' is supported since PHP 5.1.0
  654. # return literal if not supported
  655. # TODO: emulation for pre 5.1.0 versions
  656. case 'o':
  657. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  658. if ( version_compare(PHP_VERSION, '5.1.0') === 1 )
  659. $num = date( 'o', $unix );
  660. else
  661. $s .= 'o';
  662. break;
  663. case 'Y':
  664. $num = substr( $ts, 0, 4 );
  665. break;
  666. case 'xiY':
  667. if ( !$iranian ) $iranian = self::tsToIranian( $ts );
  668. $num = $iranian[0];
  669. break;
  670. case 'xmY':
  671. if ( !$hijri ) $hijri = self::tsToHijri( $ts );
  672. $num = $hijri[0];
  673. break;
  674. case 'xjY':
  675. if ( !$hebrew ) $hebrew = self::tsToHebrew( $ts );
  676. $num = $hebrew[0];
  677. break;
  678. case 'xkY':
  679. if ( !$thai ) $thai = self::tsToThai( $ts );
  680. $num = $thai[0];
  681. break;
  682. case 'y':
  683. $num = substr( $ts, 2, 2 );
  684. break;
  685. case 'a':
  686. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
  687. break;
  688. case 'A':
  689. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
  690. break;
  691. case 'g':
  692. $h = substr( $ts, 8, 2 );
  693. $num = $h % 12 ? $h % 12 : 12;
  694. break;
  695. case 'G':
  696. $num = intval( substr( $ts, 8, 2 ) );
  697. break;
  698. case 'h':
  699. $h = substr( $ts, 8, 2 );
  700. $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
  701. break;
  702. case 'H':
  703. $num = substr( $ts, 8, 2 );
  704. break;
  705. case 'i':
  706. $num = substr( $ts, 10, 2 );
  707. break;
  708. case 's':
  709. $num = substr( $ts, 12, 2 );
  710. break;
  711. case 'c':
  712. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  713. $s .= gmdate( 'c', $unix );
  714. break;
  715. case 'r':
  716. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  717. $s .= gmdate( 'r', $unix );
  718. break;
  719. case 'U':
  720. if ( !$unix ) $unix = wfTimestamp( TS_UNIX, $ts );
  721. $num = $unix;
  722. break;
  723. case '\\':
  724. # Backslash escaping
  725. if ( $p < strlen( $format ) - 1 ) {
  726. $s .= $format[++$p];
  727. } else {
  728. $s .= '\\';
  729. }
  730. break;
  731. case '"':
  732. # Quoted literal
  733. if ( $p < strlen( $format ) - 1 ) {
  734. $endQuote = strpos( $format, '"', $p + 1 );
  735. if ( $endQuote === false ) {
  736. # No terminating quote, assume literal "
  737. $s .= '"';
  738. } else {
  739. $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
  740. $p = $endQuote;
  741. }
  742. } else {
  743. # Quote at end of string, assume literal "
  744. $s .= '"';
  745. }
  746. break;
  747. default:
  748. $s .= $format[$p];
  749. }
  750. if ( $num !== false ) {
  751. if ( $rawToggle || $raw ) {
  752. $s .= $num;
  753. $raw = false;
  754. } elseif ( $roman ) {
  755. $s .= self::romanNumeral( $num );
  756. $roman = false;
  757. } elseif( $hebrewNum ) {
  758. $s .= self::hebrewNumeral( $num );
  759. $hebrewNum = false;
  760. } else {
  761. $s .= $this->formatNum( $num, true );
  762. }
  763. $num = false;
  764. }
  765. }
  766. return $s;
  767. }
  768. private static $GREG_DAYS = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  769. private static $IRANIAN_DAYS = array( 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 );
  770. /**
  771. * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
  772. * Gregorian dates to Iranian dates. Originally written in C, it
  773. * is released under the terms of GNU Lesser General Public
  774. * License. Conversion to PHP was performed by Niklas Laxström.
  775. *
  776. * Link: http://www.farsiweb.info/jalali/jalali.c
  777. */
  778. private static function tsToIranian( $ts ) {
  779. $gy = substr( $ts, 0, 4 ) -1600;
  780. $gm = substr( $ts, 4, 2 ) -1;
  781. $gd = substr( $ts, 6, 2 ) -1;
  782. # Days passed from the beginning (including leap years)
  783. $gDayNo = 365*$gy
  784. + floor(($gy+3) / 4)
  785. - floor(($gy+99) / 100)
  786. + floor(($gy+399) / 400);
  787. // Add days of the past months of this year
  788. for( $i = 0; $i < $gm; $i++ ) {
  789. $gDayNo += self::$GREG_DAYS[$i];
  790. }
  791. // Leap years
  792. if ( $gm > 1 && (($gy%4===0 && $gy%100!==0 || ($gy%400==0)))) {
  793. $gDayNo++;
  794. }
  795. // Days passed in current month
  796. $gDayNo += $gd;
  797. $jDayNo = $gDayNo - 79;
  798. $jNp = floor($jDayNo / 12053);
  799. $jDayNo %= 12053;
  800. $jy = 979 + 33*$jNp + 4*floor($jDayNo/1461);
  801. $jDayNo %= 1461;
  802. if ( $jDayNo >= 366 ) {
  803. $jy += floor(($jDayNo-1)/365);
  804. $jDayNo = floor(($jDayNo-1)%365);
  805. }
  806. for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
  807. $jDayNo -= self::$IRANIAN_DAYS[$i];
  808. }
  809. $jm= $i+1;
  810. $jd= $jDayNo+1;
  811. return array($jy, $jm, $jd);
  812. }
  813. /**
  814. * Converting Gregorian dates to Hijri dates.
  815. *
  816. * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
  817. *
  818. * @link http://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
  819. */
  820. private static function tsToHijri ( $ts ) {
  821. $year = substr( $ts, 0, 4 );
  822. $month = substr( $ts, 4, 2 );
  823. $day = substr( $ts, 6, 2 );
  824. $zyr = $year;
  825. $zd=$day;
  826. $zm=$month;
  827. $zy=$zyr;
  828. if (($zy>1582)||(($zy==1582)&&($zm>10))||(($zy==1582)&&($zm==10)&&($zd>14)))
  829. {
  830. $zjd=(int)((1461*($zy + 4800 + (int)( ($zm-14) /12) ))/4) + (int)((367*($zm-2-12*((int)(($zm-14)/12))))/12)-(int)((3*(int)(( ($zy+4900+(int)(($zm-14)/12))/100)))/4)+$zd-32075;
  831. }
  832. else
  833. {
  834. $zjd = 367*$zy-(int)((7*($zy+5001+(int)(($zm-9)/7)))/4)+(int)((275*$zm)/9)+$zd+1729777;
  835. }
  836. $zl=$zjd-1948440+10632;
  837. $zn=(int)(($zl-1)/10631);
  838. $zl=$zl-10631*$zn+354;
  839. $zj=((int)((10985-$zl)/5316))*((int)((50*$zl)/17719))+((int)($zl/5670))*((int)((43*$zl)/15238));
  840. $zl=$zl-((int)((30-$zj)/15))*((int)((17719*$zj)/50))-((int)($zj/16))*((int)((15238*$zj)/43))+29;
  841. $zm=(int)((24*$zl)/709);
  842. $zd=$zl-(int)((709*$zm)/24);
  843. $zy=30*$zn+$zj-30;
  844. return array ($zy, $zm, $zd);
  845. }
  846. /**
  847. * Converting Gregorian dates to Hebrew dates.
  848. *
  849. * Based on a JavaScript code by Abu Mami and Yisrael Hersch
  850. * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
  851. * to translate the relevant functions into PHP and release them under
  852. * GNU GPL.
  853. *
  854. * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
  855. * and Adar II is 14. In a non-leap year, Adar is 6.
  856. */
  857. private static function tsToHebrew( $ts ) {
  858. # Parse date
  859. $year = substr( $ts, 0, 4 );
  860. $month = substr( $ts, 4, 2 );
  861. $day = substr( $ts, 6, 2 );
  862. # Calculate Hebrew year
  863. $hebrewYear = $year + 3760;
  864. # Month number when September = 1, August = 12
  865. $month += 4;
  866. if( $month > 12 ) {
  867. # Next year
  868. $month -= 12;
  869. $year++;
  870. $hebrewYear++;
  871. }
  872. # Calculate day of year from 1 September
  873. $dayOfYear = $day;
  874. for( $i = 1; $i < $month; $i++ ) {
  875. if( $i == 6 ) {
  876. # February
  877. $dayOfYear += 28;
  878. # Check if the year is leap
  879. if( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
  880. $dayOfYear++;
  881. }
  882. } elseif( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
  883. $dayOfYear += 30;
  884. } else {
  885. $dayOfYear += 31;
  886. }
  887. }
  888. # Calculate the start of the Hebrew year
  889. $start = self::hebrewYearStart( $hebrewYear );
  890. # Calculate next year's start
  891. if( $dayOfYear <= $start ) {
  892. # Day is before the start of the year - it is the previous year
  893. # Next year's start
  894. $nextStart = $start;
  895. # Previous year
  896. $year--;
  897. $hebrewYear--;
  898. # Add days since previous year's 1 September
  899. $dayOfYear += 365;
  900. if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  901. # Leap year
  902. $dayOfYear++;
  903. }
  904. # Start of the new (previous) year
  905. $start = self::hebrewYearStart( $hebrewYear );
  906. } else {
  907. # Next year's start
  908. $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
  909. }
  910. # Calculate Hebrew day of year
  911. $hebrewDayOfYear = $dayOfYear - $start;
  912. # Difference between year's days
  913. $diff = $nextStart - $start;
  914. # Add 12 (or 13 for leap years) days to ignore the difference between
  915. # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
  916. # difference is only about the year type
  917. if( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  918. $diff += 13;
  919. } else {
  920. $diff += 12;
  921. }
  922. # Check the year pattern, and is leap year
  923. # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
  924. # This is mod 30, to work on both leap years (which add 30 days of Adar I)
  925. # and non-leap years
  926. $yearPattern = $diff % 30;
  927. # Check if leap year
  928. $isLeap = $diff >= 30;
  929. # Calculate day in the month from number of day in the Hebrew year
  930. # Don't check Adar - if the day is not in Adar, we will stop before;
  931. # if it is in Adar, we will use it to check if it is Adar I or Adar II
  932. $hebrewDay = $hebrewDayOfYear;
  933. $hebrewMonth = 1;
  934. $days = 0;
  935. while( $hebrewMonth <= 12 ) {
  936. # Calculate days in this month
  937. if( $isLeap && $hebrewMonth == 6 ) {
  938. # Adar in a leap year
  939. if( $isLeap ) {
  940. # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
  941. $days = 30;
  942. if( $hebrewDay <= $days ) {
  943. # Day in Adar I
  944. $hebrewMonth = 13;
  945. } else {
  946. # Subtract the days of Adar I
  947. $hebrewDay -= $days;
  948. # Try Adar II
  949. $days = 29;
  950. if( $hebrewDay <= $days ) {
  951. # Day in Adar II
  952. $hebrewMonth = 14;
  953. }
  954. }
  955. }
  956. } elseif( $hebrewMonth == 2 && $yearPattern == 2 ) {
  957. # Cheshvan in a complete year (otherwise as the rule below)
  958. $days = 30;
  959. } elseif( $hebrewMonth == 3 && $yearPattern == 0 ) {
  960. # Kislev in an incomplete year (otherwise as the rule below)
  961. $days = 29;
  962. } else {
  963. # Odd months have 30 days, even have 29
  964. $days = 30 - ( $hebrewMonth - 1 ) % 2;
  965. }
  966. if( $hebrewDay <= $days ) {
  967. # In the current month
  968. break;
  969. } else {
  970. # Subtract the days of the current month
  971. $hebrewDay -= $days;
  972. # Try in the next month
  973. $hebrewMonth++;
  974. }
  975. }
  976. return array( $hebrewYear, $hebrewMonth, $hebrewDay, $days );
  977. }
  978. /**
  979. * This calculates the Hebrew year start, as days since 1 September.
  980. * Based on Carl Friedrich Gauss algorithm for finding Easter date.
  981. * Used for Hebrew date.
  982. */
  983. private static function hebrewYearStart( $year ) {
  984. $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
  985. $b = intval( ( $year - 1 ) % 4 );
  986. $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
  987. if( $m < 0 ) {
  988. $m--;
  989. }
  990. $Mar = intval( $m );
  991. if( $m < 0 ) {
  992. $m++;
  993. }
  994. $m -= $Mar;
  995. $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7);
  996. if( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
  997. $Mar++;
  998. } else if( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
  999. $Mar += 2;
  1000. } else if( $c == 2 || $c == 4 || $c == 6 ) {
  1001. $Mar++;
  1002. }
  1003. $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
  1004. return $Mar;
  1005. }
  1006. /**
  1007. * Algorithm to convert Gregorian dates to Thai solar dates.
  1008. *
  1009. * Link: http://en.wikipedia.org/wiki/Thai_solar_calendar
  1010. *
  1011. * @param $ts String: 14-character timestamp
  1012. * @return array converted year, month, day
  1013. */
  1014. private static function tsToThai( $ts ) {
  1015. $gy = substr( $ts, 0, 4 );
  1016. $gm = substr( $ts, 4, 2 );
  1017. $gd = substr( $ts, 6, 2 );
  1018. # Add 543 years to the Gregorian calendar
  1019. # Months and days are identical
  1020. $gy_thai = $gy + 543;
  1021. return array( $gy_thai, $gm, $gd );
  1022. }
  1023. /**
  1024. * Roman number formatting up to 3000
  1025. */
  1026. static function romanNumeral( $num ) {
  1027. static $table = array(
  1028. array( '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ),
  1029. array( '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ),
  1030. array( '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ),
  1031. array( '', 'M', 'MM', 'MMM' )
  1032. );
  1033. $num = intval( $num );
  1034. if ( $num > 3000 || $num <= 0 ) {
  1035. return $num;
  1036. }
  1037. $s = '';
  1038. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1039. if ( $num >= $pow10 ) {
  1040. $s .= $table[$i][floor($num / $pow10)];
  1041. }
  1042. $num = $num % $pow10;
  1043. }
  1044. return $s;
  1045. }
  1046. /**
  1047. * Hebrew Gematria number formatting up to 9999
  1048. */
  1049. static function hebrewNumeral( $num ) {
  1050. static $table = array(
  1051. array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ),
  1052. array( '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ),
  1053. array( '', 'ק', 'ר', 'ש', 'ת', 'תק', 'תר', 'תש', 'תת', 'תתק', 'תתר' ),
  1054. array( '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' )
  1055. );
  1056. $num = intval( $num );
  1057. if ( $num > 9999 || $num <= 0 ) {
  1058. return $num;
  1059. }
  1060. $s = '';
  1061. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1062. if ( $num >= $pow10 ) {
  1063. if ( $num == 15 || $num == 16 ) {
  1064. $s .= $table[0][9] . $table[0][$num - 9];
  1065. $num = 0;
  1066. } else {
  1067. $s .= $table[$i][intval( ( $num / $pow10 ) )];
  1068. if( $pow10 == 1000 ) {
  1069. $s .= "'";
  1070. }
  1071. }
  1072. }
  1073. $num = $num % $pow10;
  1074. }
  1075. if( strlen( $s ) == 2 ) {
  1076. $str = $s . "'";
  1077. } else {
  1078. $str = substr( $s, 0, strlen( $s ) - 2 ) . '"';
  1079. $str .= substr( $s, strlen( $s ) - 2, 2 );
  1080. }
  1081. $start = substr( $str, 0, strlen( $str ) - 2 );
  1082. $end = substr( $str, strlen( $str ) - 2 );
  1083. switch( $end ) {
  1084. case 'כ':
  1085. $str = $start . 'ך';
  1086. break;
  1087. case 'מ':
  1088. $str = $start . 'ם';
  1089. break;
  1090. case 'נ':
  1091. $str = $start . 'ן';
  1092. break;
  1093. case 'פ':
  1094. $str = $start . 'ף';
  1095. break;
  1096. case 'צ':
  1097. $str = $start . 'ץ';
  1098. break;
  1099. }
  1100. return $str;
  1101. }
  1102. /**
  1103. * This is meant to be used by time(), date(), and timeanddate() to get
  1104. * the date preference they're supposed to use, it should be used in
  1105. * all children.
  1106. *
  1107. *<code>
  1108. * function timeanddate([...], $format = true) {
  1109. * $datePreference = $this->dateFormat($format);
  1110. * [...]
  1111. * }
  1112. *</code>
  1113. *
  1114. * @param $usePrefs Mixed: if true, the user's preference is used
  1115. * if false, the site/language default is used
  1116. * if int/string, assumed to be a format.
  1117. * @return string
  1118. */
  1119. function dateFormat( $usePrefs = true ) {
  1120. global $wgUser;
  1121. if( is_bool( $usePrefs ) ) {
  1122. if( $usePrefs ) {
  1123. $datePreference = $wgUser->getDatePreference();
  1124. } else {
  1125. $options = User::getDefaultOptions();
  1126. $datePreference = (string)$options['date'];
  1127. }
  1128. } else {
  1129. $datePreference = (string)$usePrefs;
  1130. }
  1131. // return int
  1132. if( $datePreference == '' ) {
  1133. return 'default';
  1134. }
  1135. return $datePreference;
  1136. }
  1137. /**
  1138. * @param $ts Mixed: the time format which needs to be turned into a
  1139. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1140. * @param $adj Bool: whether to adjust the time output according to the
  1141. * user configured offset ($timecorrection)
  1142. * @param $format Mixed: true to use user's date format preference
  1143. * @param $timecorrection String: the time offset as returned by
  1144. * validateTimeZone() in Special:Preferences
  1145. * @return string
  1146. */
  1147. function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
  1148. $this->load();
  1149. if ( $adj ) {
  1150. $ts = $this->userAdjust( $ts, $timecorrection );
  1151. }
  1152. $pref = $this->dateFormat( $format );
  1153. if( $pref == 'default' || !isset( $this->dateFormats["$pref date"] ) ) {
  1154. $pref = $this->defaultDateFormat;
  1155. }
  1156. return $this->sprintfDate( $this->dateFormats["$pref date"], $ts );
  1157. }
  1158. /**
  1159. * @param $ts Mixed: the time format which needs to be turned into a
  1160. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1161. * @param $adj Bool: whether to adjust the time output according to the
  1162. * user configured offset ($timecorrection)
  1163. * @param $format Mixed: true to use user's date format preference
  1164. * @param $timecorrection String: the time offset as returned by
  1165. * validateTimeZone() in Special:Preferences
  1166. * @return string
  1167. */
  1168. function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
  1169. $this->load();
  1170. if ( $adj ) {
  1171. $ts = $this->userAdjust( $ts, $timecorrection );
  1172. }
  1173. $pref = $this->dateFormat( $format );
  1174. if( $pref == 'default' || !isset( $this->dateFormats["$pref time"] ) ) {
  1175. $pref = $this->defaultDateFormat;
  1176. }
  1177. return $this->sprintfDate( $this->dateFormats["$pref time"], $ts );
  1178. }
  1179. /**
  1180. * @param $ts Mixed: the time format which needs to be turned into a
  1181. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  1182. * @param $adj Bool: whether to adjust the time output according to the
  1183. * user configured offset ($timecorrection)
  1184. * @param $format Mixed: what format to return, if it's false output the
  1185. * default one (default true)
  1186. * @param $timecorrection String: the time offset as returned by
  1187. * validateTimeZone() in Special:Preferences
  1188. * @return string
  1189. */
  1190. function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false) {
  1191. $this->load();
  1192. $ts = wfTimestamp( TS_MW, $ts );
  1193. if ( $adj ) {
  1194. $ts = $this->userAdjust( $ts, $timecorrection );
  1195. }
  1196. $pref = $this->dateFormat( $format );
  1197. if( $pref == 'default' || !isset( $this->dateFormats["$pref both"] ) ) {
  1198. $pref = $this->defaultDateFormat;
  1199. }
  1200. return $this->sprintfDate( $this->dateFormats["$pref both"], $ts );
  1201. }
  1202. function getMessage( $key ) {
  1203. $this->load();
  1204. return isset( $this->messages[$key] ) ? $this->messages[$key] : null;
  1205. }
  1206. function getAllMessages() {
  1207. $this->load();
  1208. return $this->messages;
  1209. }
  1210. function iconv( $in, $out, $string ) {
  1211. # For most languages, this is a wrapper for iconv
  1212. return iconv( $in, $out . '//IGNORE', $string );
  1213. }
  1214. // callback functions for uc(), lc(), ucwords(), ucwordbreaks()
  1215. function ucwordbreaksCallbackAscii($matches){
  1216. return $this->ucfirst($matches[1]);
  1217. }
  1218. function ucwordbreaksCallbackMB($matches){
  1219. return mb_strtoupper($matches[0]);
  1220. }
  1221. function ucCallback($matches){
  1222. list( $wikiUpperChars ) = self::getCaseMaps();
  1223. return strtr( $matches[1], $wikiUpperChars );
  1224. }
  1225. function lcCallback($matches){
  1226. list( , $wikiLowerChars ) = self::getCaseMaps();
  1227. return strtr( $matches[1], $wikiLowerChars );
  1228. }
  1229. function ucwordsCallbackMB($matches){
  1230. return mb_strtoupper($matches[0]);
  1231. }
  1232. function ucwordsCallbackWiki($matches){
  1233. list( $wikiUpperChars ) = self::getCaseMaps();
  1234. return strtr( $matches[0], $wikiUpperChars );
  1235. }
  1236. function ucfirst( $str ) {
  1237. if ( empty($str) ) return $str;
  1238. if ( ord($str[0]) < 128 ) return ucfirst($str);
  1239. else return self::uc($str,true); // fall back to more complex logic in case of multibyte strings
  1240. }
  1241. function uc( $str, $first = false ) {
  1242. if ( function_exists( 'mb_strtoupper' ) ) {
  1243. if ( $first ) {
  1244. if ( self::isMultibyte( $str ) ) {
  1245. return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  1246. } else {
  1247. return ucfirst( $str );
  1248. }
  1249. } else {
  1250. return self::isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
  1251. }
  1252. } else {
  1253. if ( self::isMultibyte( $str ) ) {
  1254. list( $wikiUpperChars ) = $this->getCaseMaps();
  1255. $x = $first ? '^' : '';
  1256. return preg_replace_callback(
  1257. "/$x([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
  1258. array($this,"ucCallback"),
  1259. $str
  1260. );
  1261. } else {
  1262. return $first ? ucfirst( $str ) : strtoupper( $str );
  1263. }
  1264. }
  1265. }
  1266. function lcfirst( $str ) {
  1267. if ( empty($str) ) return $str;
  1268. if ( is_string( $str ) && ord($str[0]) < 128 ) {
  1269. // editing string in place = cool
  1270. $str[0]=strtolower($str[0]);
  1271. return $str;
  1272. }
  1273. else return self::lc( $str, true );
  1274. }
  1275. function lc( $str, $first = false ) {
  1276. if ( function_exists( 'mb_strtolower' ) )
  1277. if ( $first )
  1278. if ( self::isMultibyte( $str ) )
  1279. return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  1280. else
  1281. return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
  1282. else
  1283. return self::isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
  1284. else
  1285. if ( self::isMultibyte( $str ) ) {
  1286. list( , $wikiLowerChars ) = self::getCaseMaps();
  1287. $x = $first ? '^' : '';
  1288. return preg_replace_callback(
  1289. "/$x([A-Z]|[\\xc0-\\xff][\\x80-\\xbf]*)/",
  1290. array($this,"lcCallback"),
  1291. $str
  1292. );
  1293. } else
  1294. return $first ? strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 ) : strtolower( $str );
  1295. }
  1296. function isMultibyte( $str ) {
  1297. return (bool)preg_match( '/[\x80-\xff]/', $str );
  1298. }
  1299. function ucwords($str) {
  1300. if ( self::isMultibyte( $str ) ) {
  1301. $str = self::lc($str);
  1302. // regexp to find first letter in each word (i.e. after each space)
  1303. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  1304. // function to use to capitalize a single char
  1305. if ( function_exists( 'mb_strtoupper' ) )
  1306. return preg_replace_callback(
  1307. $replaceRegexp,
  1308. array($this,"ucwordsCallbackMB"),
  1309. $str
  1310. );
  1311. else
  1312. return preg_replace_callback(
  1313. $replaceRegexp,
  1314. array($this,"ucwordsCallbackWiki"),
  1315. $str
  1316. );
  1317. }
  1318. else
  1319. return ucwords( strtolower( $str ) );
  1320. }
  1321. # capitalize words at word breaks
  1322. function ucwordbreaks($str){
  1323. if (self::isMultibyte( $str ) ) {
  1324. $str = self::lc($str);
  1325. // since \b doesn't work for UTF-8, we explicitely define word break chars
  1326. $breaks= "[ \-\(\)\}\{\.,\?!]";
  1327. // find first letter after word break
  1328. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  1329. if ( function_exists( 'mb_strtoupper' ) )
  1330. return preg_replace_callback(
  1331. $replaceRegexp,
  1332. array($this,"ucwordbreaksCallbackMB"),
  1333. $str
  1334. );
  1335. else
  1336. return preg_replace_callback(
  1337. $replaceRegexp,
  1338. array($this,"ucwordsCallbackWiki"),
  1339. $str
  1340. );
  1341. }
  1342. else
  1343. return preg_replace_callback(
  1344. '/\b([\w\x80-\xff]+)\b/',
  1345. array($this,"ucwordbreaksCallbackAscii"),
  1346. $str );
  1347. }
  1348. /**
  1349. * Return a case-folded representation of $s
  1350. *
  1351. * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
  1352. * and $s2 are the same except for the case of their characters. It is not
  1353. * necessary for the value returned to make sense when displayed.
  1354. *
  1355. * Do *not* perform any other normalisation in this function. If a caller
  1356. * uses this function when it should be using a more general normalisation
  1357. * function, then fix the caller.
  1358. */
  1359. function caseFold( $s ) {
  1360. return $this->uc( $s );
  1361. }
  1362. function checkTitleEncoding( $s ) {
  1363. if( is_array( $s ) ) {
  1364. wfDebugDieBacktrace( 'Given array to checkTitleEncoding.' );
  1365. }
  1366. # Check for non-UTF-8 URLs
  1367. $ishigh = preg_match( '/[\x80-\xff]/', $s);
  1368. if(!$ishigh) return $s;
  1369. $isutf8 = preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
  1370. '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})+$/', $s );
  1371. if( $isutf8 ) return $s;
  1372. return $this->iconv( $this->fallback8bitEncoding(), "utf-8", $s );
  1373. }
  1374. function fallback8bitEncoding() {
  1375. $this->load();
  1376. return $this->fallback8bitEncoding;
  1377. }
  1378. /**
  1379. * Some languages have special punctuation to strip out
  1380. * or characters which need to be converted for MySQL's
  1381. * indexing to grok it correctly. Make such changes here.
  1382. *
  1383. * @param $string String
  1384. * @return String
  1385. */
  1386. function stripForSearch( $string ) {
  1387. global $wgDBtype;
  1388. if ( $wgDBtype != 'mysql' ) {
  1389. return $string;
  1390. }
  1391. wfProfileIn( __METHOD__ );
  1392. // MySQL fulltext index doesn't grok utf-8, so we
  1393. // need to fold cases and convert to hex
  1394. $out = preg_replace_callback(
  1395. "/([\\xc0-\\xff][\\x80-\\xbf]*)/",
  1396. array( $this, 'stripForSearchCallback' ),
  1397. $this->lc( $string ) );
  1398. // And to add insult to injury, the default indexing
  1399. // ignores short words... Pad them so we can pass them
  1400. // through without reconfiguring the server...
  1401. $minLength = $this->minSearchLength();
  1402. if( $minLength > 1 ) {
  1403. $n = $minLength-1;
  1404. $out = preg_replace(
  1405. "/\b(\w{1,$n})\b/",
  1406. "$1u800",
  1407. $out );
  1408. }
  1409. // Periods within things like hostnames and IP addresses
  1410. // are also important -- we want a search for "example.com"
  1411. // or "192.168.1.1" to work sanely.
  1412. //
  1413. // MySQL's search seems to ignore them, so you'd match on
  1414. // "example.wikipedia.com" and "192.168.83.1" as well.
  1415. $out = preg_replace(
  1416. "/(\w)\.(\w|\*)/u",
  1417. "$1u82e$2",
  1418. $out );
  1419. wfProfileOut( __METHOD__ );
  1420. return $out;
  1421. }
  1422. /**
  1423. * Armor a case-folded UTF-8 string to get through MySQL's
  1424. * fulltext search without being mucked up by funny charset
  1425. * settings or anything else of the sort.
  1426. */
  1427. protected function stripForSearchCallback( $matches ) {
  1428. return 'u8' . bin2hex( $matches[1] );
  1429. }
  1430. /**
  1431. * Check MySQL server's ft_min_word_len setting so we know
  1432. * if we need to pad short words...
  1433. */
  1434. protected function minSearchLength() {
  1435. if( !isset( $this->minSearchLength ) ) {
  1436. $sql = "show global variables like 'ft\\_min\\_word\\_len'";
  1437. $dbr = wfGetDB( DB_SLAVE );
  1438. $result = $dbr->query( $sql );
  1439. $row = $result->fetchObject();
  1440. $result->free();
  1441. if( $row && $row->Variable_name == 'ft_min_word_len' ) {
  1442. $this->minSearchLength = intval( $row->Value );
  1443. } else {
  1444. $this->minSearchLength = 0;
  1445. }
  1446. }
  1447. return $this->minSearchLength;
  1448. }
  1449. function convertForSearchResult( $termsArray ) {
  1450. # some languages, e.g. Chinese, need to do a conversion
  1451. # in order for search results to be displayed correctly
  1452. return $termsArray;
  1453. }
  1454. /**
  1455. * Get the first character of a string.
  1456. *
  1457. * @param $s string
  1458. * @return string
  1459. */
  1460. function firstChar( $s ) {
  1461. $matches = array();
  1462. preg_match( '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
  1463. '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/', $s, $matches);
  1464. if ( isset( $matches[1] ) ) {
  1465. if ( strlen( $matches[1] ) != 3 ) {
  1466. return $matches[1];
  1467. }
  1468. // Break down Hangul syllables to grab the first jamo
  1469. $code = utf8ToCodepoint( $matches[1] );
  1470. if ( $code < 0xac00 || 0xd7a4 <= $code) {
  1471. return $matches[1];
  1472. } elseif ( $code < 0xb098 ) {
  1473. return "\xe3\x84\xb1";
  1474. } elseif ( $code < 0xb2e4 ) {
  1475. return "\xe3\x84\xb4";
  1476. } elseif ( $code < 0xb77c ) {
  1477. return "\xe3\x84\xb7";
  1478. } elseif ( $code < 0xb9c8 ) {
  1479. return "\xe3\x84\xb9";
  1480. } elseif ( $code < 0xbc14 ) {
  1481. return "\xe3\x85\x81";
  1482. } elseif ( $code < 0xc0ac ) {
  1483. return "\xe3\x85\x82";
  1484. } elseif ( $code < 0xc544 ) {
  1485. return "\xe3\x85\x85";
  1486. } elseif ( $code < 0xc790 ) {
  1487. return "\xe3\x85\x87";
  1488. } elseif ( $code < 0xcc28 ) {
  1489. return "\xe3\x85\x88";
  1490. } elseif ( $code < 0xce74 ) {
  1491. return "\xe3\x85\x8a";
  1492. } elseif ( $code < 0xd0c0 ) {
  1493. return "\xe3\x85\x8b";
  1494. } elseif ( $code < 0xd30c ) {
  1495. return "\xe3\x85\x8c";
  1496. } elseif ( $code < 0xd558 ) {
  1497. return "\xe3\x85\x8d";
  1498. } else {
  1499. return "\xe3\x85\x8e";
  1500. }
  1501. } else {
  1502. return "";
  1503. }
  1504. }
  1505. function initEncoding() {
  1506. # Some languages may have an alternate char encoding option
  1507. # (Esperanto X-coding, Japanese furigana conversion, etc)
  1508. # If this language is used as the primary content language,
  1509. # an override to the defaults can be set here on startup.
  1510. }
  1511. function recodeForEdit( $s ) {
  1512. # For some languages we'll want to explicitly specify
  1513. # which characters make it into the edit box raw
  1514. # or are converted in some way or another.
  1515. # Note that if wgOutputEncoding is different from
  1516. # wgInputEncoding, this text will be further converted
  1517. # to wgOutputEncoding.
  1518. global $wgEditEncoding;
  1519. if( $wgEditEncoding == '' or
  1520. $wgEditEncoding == 'UTF-8' ) {
  1521. return $s;
  1522. } else {
  1523. return $this->iconv( 'UTF-8', $wgEditEncoding, $s );
  1524. }
  1525. }
  1526. function recodeInput( $s ) {
  1527. # Take the previous into account.
  1528. global $wgEditEncoding;
  1529. if($wgEditEncoding != "") {
  1530. $enc = $wgEditEncoding;
  1531. } else {
  1532. $enc = 'UTF-8';
  1533. }
  1534. if( $enc == 'UTF-8' ) {
  1535. return $s;
  1536. } else {
  1537. return $this->iconv( $enc, 'UTF-8', $s );
  1538. }
  1539. }
  1540. /**
  1541. * For right-to-left language support
  1542. *
  1543. * @return bool
  1544. */
  1545. function isRTL() {
  1546. $this->load();
  1547. return $this->rtl;
  1548. }
  1549. /**
  1550. * A hidden direction mark (LRM or RLM), depending on the language direction
  1551. *
  1552. * @return string
  1553. */
  1554. function getDirMark() {
  1555. return $this->isRTL() ? "\xE2\x80\x8F" : "\xE2\x80\x8E";
  1556. }
  1557. /**
  1558. * An arrow, depending on the language direction
  1559. *
  1560. * @return string
  1561. */
  1562. function getArrow() {
  1563. return $this->isRTL() ? '←' : '→';
  1564. }
  1565. /**
  1566. * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
  1567. *
  1568. * @return bool
  1569. */
  1570. function linkPrefixExtension() {
  1571. $this->load();
  1572. return $this->linkPrefixExtension;
  1573. }
  1574. function &getMagicWords() {
  1575. $this->load();
  1576. return $this->magicWords;
  1577. }
  1578. # Fill a MagicWord object with data from here
  1579. function getMagic( &$mw ) {
  1580. if ( !$this->mMagicHookDone ) {
  1581. $this->mMagicHookDone = true;
  1582. wfRunHooks( 'LanguageGetMagic', array( &$this->mMagicExtensions, $this->getCode() ) );
  1583. }
  1584. if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
  1585. $rawEntry = $this->mMagicExtensions[$mw->mId];
  1586. } else {
  1587. $magicWords =& $this->getMagicWords();
  1588. if ( isset( $magicWords[$mw->mId] ) ) {
  1589. $rawEntry = $magicWords[$mw->mId];
  1590. } else {
  1591. # Fall back to English if local list is incomplete
  1592. $magicWords =& Language::getMagicWords();
  1593. if ( !isset($magicWords[$mw->mId]) ) {
  1594. throw new MWException("Magic word '{$mw->mId}' not found" );
  1595. }
  1596. $rawEntry = $magicWords[$mw->mId];
  1597. }
  1598. }
  1599. if( !is_array( $rawEntry ) ) {
  1600. error_log( "\"$rawEntry\" is not a valid magic thingie for \"$mw->mId\"" );
  1601. } else {
  1602. $mw->mCaseSensitive = $rawEntry[0];
  1603. $mw->mSynonyms = array_slice( $rawEntry, 1 );
  1604. }
  1605. }
  1606. /**
  1607. * Add magic words to the extension array
  1608. */
  1609. function addMagicWordsByLang( $newWords ) {
  1610. $code = $this->getCode();
  1611. $fallbackChain = array();
  1612. while ( $code && !in_array( $code, $fallbackChain ) ) {
  1613. $fallbackChain[] = $code;
  1614. $code = self::getFallbackFor( $code );
  1615. }
  1616. if ( !in_array( 'en', $fallbackChain ) ) {
  1617. $fallbackChain[] = 'en';
  1618. }
  1619. $fallbackChain = array_reverse( $fallbackChain );
  1620. foreach ( $fallbackChain as $code ) {
  1621. if ( isset( $newWords[$code] ) ) {
  1622. $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
  1623. }
  1624. }
  1625. }
  1626. /**
  1627. * Get special page names, as an associative array
  1628. * case folded alias => real name
  1629. */
  1630. function getSpecialPageAliases() {
  1631. $this->load();
  1632. // Cache aliases because it may be slow to load them
  1633. if ( !isset( $this->mExtendedSpecialPageAliases ) ) {
  1634. // Initialise array
  1635. $this->mExtendedSpecialPageAliases = $this->specialPageAliases;
  1636. global $wgExtensionAliasesFiles;
  1637. foreach ( $wgExtensionAliasesFiles as $file ) {
  1638. // Fail fast
  1639. if ( !file_exists($file) )
  1640. throw new MWException( "Aliases file does not exist: $file" );
  1641. $aliases = array();
  1642. require($file);
  1643. // Check the availability of aliases
  1644. if ( !isset($aliases['en']) )
  1645. throw new MWException( "Malformed aliases file: $file" );
  1646. // Merge all aliases in fallback chain
  1647. $code = $this->getCode();
  1648. do {
  1649. if ( !isset($aliases[$code]) ) continue;
  1650. $aliases[$code] = $this->fixSpecialPageAliases( $aliases[$code] );
  1651. /* Merge the aliases, THIS will break if there is special page name
  1652. * which looks like a numerical key, thanks to PHP...
  1653. * See the array_merge_recursive manual entry */
  1654. $this->mExtendedSpecialPageAliases = array_merge_recursive(
  1655. $this->mExtendedSpecialPageAliases, $aliases[$code] );
  1656. } while ( $code = self::getFallbackFor( $code ) );
  1657. }
  1658. wfRunHooks( 'LanguageGetSpecialPageAliases',
  1659. array( &$this->mExtendedSpecialPageAliases, $this->getCode() ) );
  1660. }
  1661. return $this->mExtendedSpecialPageAliases;
  1662. }
  1663. /**
  1664. * Function to fix special page aliases. Will convert the first letter to
  1665. * upper case and spaces to underscores. Can be given a full aliases array,
  1666. * in which case it will recursively fix all aliases.
  1667. */
  1668. public function fixSpecialPageAliases( $mixed ) {
  1669. // Work recursively until in string level
  1670. if ( is_array($mixed) ) {
  1671. $callback = array( $this, 'fixSpecialPageAliases' );
  1672. return array_map( $callback, $mixed );
  1673. }
  1674. return str_replace( ' ', '_', $this->ucfirst( $mixed ) );
  1675. }
  1676. /**
  1677. * Italic is unsuitable for some languages
  1678. *
  1679. * @param $text String: the text to be emphasized.
  1680. * @return string
  1681. */
  1682. function emphasize( $text ) {
  1683. return "<em>$text</em>";
  1684. }
  1685. /**
  1686. * Normally we output all numbers in plain en_US style, that is
  1687. * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
  1688. * point twohundredthirtyfive. However this is not sutable for all
  1689. * languages, some such as Pakaran want ੨੯੩,੨੯੫.੨੩੫ and others such as
  1690. * Icelandic just want to use commas instead of dots, and dots instead
  1691. * of commas like "293.291,235".
  1692. *
  1693. * An example of this function being called:
  1694. * <code>
  1695. * wfMsg( 'message', $wgLang->formatNum( $num ) )
  1696. * </code>
  1697. *
  1698. * See LanguageGu.php for the Gujarati implementation and
  1699. * $separatorTransformTable on MessageIs.php for
  1700. * the , => . and . => , implementation.
  1701. *
  1702. * @todo check if it's viable to use localeconv() for the decimal
  1703. * separator thing.
  1704. * @param $number Mixed: the string to be formatted, should be an integer
  1705. * or a floating point number.
  1706. * @param $nocommafy Bool: set to true for special numbers like dates
  1707. * @return string
  1708. */
  1709. function formatNum( $number, $nocommafy = false ) {
  1710. global $wgTranslateNumerals;
  1711. if (!$nocommafy) {
  1712. $number = $this->commafy($number);
  1713. $s = $this->separatorTransformTable();
  1714. if ($s) { $number = strtr($number, $s); }
  1715. }
  1716. if ($wgTranslateNumerals) {
  1717. $s = $this->digitTransformTable();
  1718. if ($s) { $number = strtr($number, $s); }
  1719. }
  1720. return $number;
  1721. }
  1722. function parseFormattedNumber( $number ) {
  1723. $s = $this->digitTransformTable();
  1724. if ($s) { $number = strtr($number, array_flip($s)); }
  1725. $s = $this->separatorTransformTable();
  1726. if ($s) { $number = strtr($number, array_flip($s)); }
  1727. $number = strtr( $number, array (',' => '') );
  1728. return $number;
  1729. }
  1730. /**
  1731. * Adds commas to a given number
  1732. *
  1733. * @param $_ mixed
  1734. * @return string
  1735. */
  1736. function commafy($_) {
  1737. return strrev((string)preg_replace('/(\d{3})(?=\d)(?!\d*\.)/','$1,',strrev($_)));
  1738. }
  1739. function digitTransformTable() {
  1740. $this->load();
  1741. return $this->digitTransformTable;
  1742. }
  1743. function separatorTransformTable() {
  1744. $this->load();
  1745. return $this->separatorTransformTable;
  1746. }
  1747. /**
  1748. * Take a list of strings and build a locale-friendly comma-separated
  1749. * list, using the local comma-separator message.
  1750. * The last two strings are chained with an "and".
  1751. *
  1752. * @param $l Array
  1753. * @return string
  1754. */
  1755. function listToText( $l ) {
  1756. $s = '';
  1757. $m = count( $l ) - 1;
  1758. if( $m == 1 ) {
  1759. return $l[0] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $l[1];
  1760. }
  1761. else {
  1762. for ( $i = $m; $i >= 0; $i-- ) {
  1763. if ( $i == $m ) {
  1764. $s = $l[$i];
  1765. } else if( $i == $m - 1 ) {
  1766. $s = $l[$i] . $this->getMessageFromDB( 'and' ) . $this->getMessageFromDB( 'word-separator' ) . $s;
  1767. } else {
  1768. $s = $l[$i] . $this->getMessageFromDB( 'comma-separator' ) . $s;
  1769. }
  1770. }
  1771. return $s;
  1772. }
  1773. }
  1774. /**
  1775. * Take a list of strings and build a locale-friendly comma-separated
  1776. * list, using the local comma-separator message.
  1777. * @param $list array of strings to put in a comma list
  1778. * @return string
  1779. */
  1780. function commaList( $list ) {
  1781. return implode(
  1782. $list,
  1783. wfMsgExt( 'comma-separator', array( 'escapenoentities', 'language' => $this ) ) );
  1784. }
  1785. /**
  1786. * Take a list of strings and build a locale-friendly semicolon-separated
  1787. * list, using the local semicolon-separator message.
  1788. * @param $list array of strings to put in a semicolon list
  1789. * @return string
  1790. */
  1791. function semicolonList( $list ) {
  1792. return implode(
  1793. $list,
  1794. wfMsgExt( 'semicolon-separator', array( 'escapenoentities', 'language' => $this ) ) );
  1795. }
  1796. /**
  1797. * Same as commaList, but separate it with the pipe instead.
  1798. * @param $list array of strings to put in a pipe list
  1799. * @return string
  1800. */
  1801. function pipeList( $list ) {
  1802. return implode(
  1803. $list,
  1804. wfMsgExt( 'pipe-separator', array( 'escapenoentities', 'language' => $this ) ) );
  1805. }
  1806. /**
  1807. * Truncate a string to a specified length in bytes, appending an optional
  1808. * string (e.g. for ellipses)
  1809. *
  1810. * The database offers limited byte lengths for some columns in the database;
  1811. * multi-byte character sets mean we need to ensure that only whole characters
  1812. * are included, otherwise broken characters can be passed to the user
  1813. *
  1814. * If $length is negative, the string will be truncated from the beginning
  1815. *
  1816. * @param $string String to truncate
  1817. * @param $length Int: maximum length (excluding ellipses)
  1818. * @param $ellipsis String to append to the truncated text
  1819. * @return string
  1820. */
  1821. function truncate( $string, $length, $ellipsis = '...' ) {
  1822. # Use the localized ellipsis character
  1823. if( $ellipsis == '...' ) {
  1824. $ellipsis = wfMsgExt( 'ellipsis', array( 'escapenoentities', 'language' => $this ) );
  1825. }
  1826. if( $length == 0 ) {
  1827. return $ellipsis;
  1828. }
  1829. if ( strlen( $string ) <= abs( $length ) ) {
  1830. return $string;
  1831. }
  1832. if( $length > 0 ) {
  1833. $string = substr( $string, 0, $length );
  1834. $char = ord( $string[strlen( $string ) - 1] );
  1835. $m = array();
  1836. if ($char >= 0xc0) {
  1837. # We got the first byte only of a multibyte char; remove it.
  1838. $string = substr( $string, 0, -1 );
  1839. } elseif( $char >= 0x80 &&
  1840. preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
  1841. '[\xf0-\xf7][\x80-\xbf]{1,2})$/', $string, $m ) ) {
  1842. # We chopped in the middle of a character; remove it
  1843. $string = $m[1];
  1844. }
  1845. return $string . $ellipsis;
  1846. } else {
  1847. $string = substr( $string, $length );
  1848. $char = ord( $string[0] );
  1849. if( $char >= 0x80 && $char < 0xc0 ) {
  1850. # We chopped in the middle of a character; remove the whole thing
  1851. $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
  1852. }
  1853. return $ellipsis . $string;
  1854. }
  1855. }
  1856. /**
  1857. * Grammatical transformations, needed for inflected languages
  1858. * Invoked by putting {{grammar:case|word}} in a message
  1859. *
  1860. * @param $word string
  1861. * @param $case string
  1862. * @return string
  1863. */
  1864. function convertGrammar( $word, $case ) {
  1865. global $wgGrammarForms;
  1866. if ( isset($wgGrammarForms[$this->getCode()][$case][$word]) ) {
  1867. return $wgGrammarForms[$this->getCode()][$case][$word];
  1868. }
  1869. return $word;
  1870. }
  1871. /**
  1872. * Provides an alternative text depending on specified gender.
  1873. * Usage {{gender:username|masculine|feminine|neutral}}.
  1874. * username is optional, in which case the gender of current user is used,
  1875. * but only in (some) interface messages; otherwise default gender is used.
  1876. * If second or third parameter are not specified, masculine is used.
  1877. * These details may be overriden per language.
  1878. */
  1879. function gender( $gender, $forms ) {
  1880. if ( !count($forms) ) { return ''; }
  1881. $forms = $this->preConvertPlural( $forms, 2 );
  1882. if ( $gender === 'male' ) return $forms[0];
  1883. if ( $gender === 'female' ) return $forms[1];
  1884. return isset($forms[2]) ? $forms[2] : $forms[0];
  1885. }
  1886. /**
  1887. * Plural form transformations, needed for some languages.
  1888. * For example, there are 3 form of plural in Russian and Polish,
  1889. * depending on "count mod 10". See [[w:Plural]]
  1890. * For English it is pretty simple.
  1891. *
  1892. * Invoked by putting {{plural:count|wordform1|wordform2}}
  1893. * or {{plural:count|wordform1|wordform2|wordform3}}
  1894. *
  1895. * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
  1896. *
  1897. * @param $count Integer: non-localized number
  1898. * @param $forms Array: different plural forms
  1899. * @return string Correct form of plural for $count in this language
  1900. */
  1901. function convertPlural( $count, $forms ) {
  1902. if ( !count($forms) ) { return ''; }
  1903. $forms = $this->preConvertPlural( $forms, 2 );
  1904. return ( $count == 1 ) ? $forms[0] : $forms[1];
  1905. }
  1906. /**
  1907. * Checks that convertPlural was given an array and pads it to requested
  1908. * amound of forms by copying the last one.
  1909. *
  1910. * @param $count Integer: How many forms should there be at least
  1911. * @param $forms Array of forms given to convertPlural
  1912. * @return array Padded array of forms or an exception if not an array
  1913. */
  1914. protected function preConvertPlural( /* Array */ $forms, $count ) {
  1915. while ( count($forms) < $count ) {
  1916. $forms[] = $forms[count($forms)-1];
  1917. }
  1918. return $forms;
  1919. }
  1920. /**
  1921. * For translaing of expiry times
  1922. * @param $str String: the validated block time in English
  1923. * @return Somehow translated block time
  1924. * @see LanguageFi.php for example implementation
  1925. */
  1926. function translateBlockExpiry( $str ) {
  1927. $scBlockExpiryOptions = $this->getMessageFromDB( 'ipboptions' );
  1928. if ( $scBlockExpiryOptions == '-') {
  1929. return $str;
  1930. }
  1931. foreach (explode(',', $scBlockExpiryOptions) as $option) {
  1932. if ( strpos($option, ":") === false )
  1933. continue;
  1934. list($show, $value) = explode(":", $option);
  1935. if ( strcmp ( $str, $value) == 0 ) {
  1936. return htmlspecialchars( trim( $show ) );
  1937. }
  1938. }
  1939. return $str;
  1940. }
  1941. /**
  1942. * languages like Chinese need to be segmented in order for the diff
  1943. * to be of any use
  1944. *
  1945. * @param $text String
  1946. * @return String
  1947. */
  1948. function segmentForDiff( $text ) {
  1949. return $text;
  1950. }
  1951. /**
  1952. * and unsegment to show the result
  1953. *
  1954. * @param $text String
  1955. * @return String
  1956. */
  1957. function unsegmentForDiff( $text ) {
  1958. return $text;
  1959. }
  1960. # convert text to different variants of a language.
  1961. function convert( $text, $isTitle = false) {
  1962. return $this->mConverter->convert($text, $isTitle);
  1963. }
  1964. # Convert text from within Parser
  1965. function parserConvert( $text, &$parser ) {
  1966. return $this->mConverter->parserConvert( $text, $parser );
  1967. }
  1968. # Check if this is a language with variants
  1969. function hasVariants(){
  1970. return sizeof($this->getVariants())>1;
  1971. }
  1972. # Put custom tags (e.g. -{ }-) around math to prevent conversion
  1973. function armourMath($text){
  1974. return $this->mConverter->armourMath($text);
  1975. }
  1976. /**
  1977. * Perform output conversion on a string, and encode for safe HTML output.
  1978. * @param $text String
  1979. * @param $isTitle Bool -- wtf?
  1980. * @return string
  1981. * @todo this should get integrated somewhere sane
  1982. */
  1983. function convertHtml( $text, $isTitle = false ) {
  1984. return htmlspecialchars( $this->convert( $text, $isTitle ) );
  1985. }
  1986. function convertCategoryKey( $key ) {
  1987. return $this->mConverter->convertCategoryKey( $key );
  1988. }
  1989. /**
  1990. * get the list of variants supported by this langauge
  1991. * see sample implementation in LanguageZh.php
  1992. *
  1993. * @return array an array of language codes
  1994. */
  1995. function getVariants() {
  1996. return $this->mConverter->getVariants();
  1997. }
  1998. function getPreferredVariant( $fromUser = true ) {
  1999. return $this->mConverter->getPreferredVariant( $fromUser );
  2000. }
  2001. /**
  2002. * if a language supports multiple variants, it is
  2003. * possible that non-existing link in one variant
  2004. * actually exists in another variant. this function
  2005. * tries to find it. See e.g. LanguageZh.php
  2006. *
  2007. * @param $link String: the name of the link
  2008. * @param $nt Mixed: the title object of the link
  2009. * @param boolean $ignoreOtherCond: to disable other conditions when
  2010. * we need to transclude a template or update a category's link
  2011. * @return null the input parameters may be modified upon return
  2012. */
  2013. function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
  2014. $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
  2015. }
  2016. /**
  2017. * If a language supports multiple variants, converts text
  2018. * into an array of all possible variants of the text:
  2019. * 'variant' => text in that variant
  2020. */
  2021. function convertLinkToAllVariants($text){
  2022. return $this->mConverter->convertLinkToAllVariants($text);
  2023. }
  2024. /**
  2025. * returns language specific options used by User::getPageRenderHash()
  2026. * for example, the preferred language variant
  2027. *
  2028. * @return string
  2029. */
  2030. function getExtraHashOptions() {
  2031. return $this->mConverter->getExtraHashOptions();
  2032. }
  2033. /**
  2034. * for languages that support multiple variants, the title of an
  2035. * article may be displayed differently in different variants. this
  2036. * function returns the apporiate title defined in the body of the article.
  2037. *
  2038. * @return string
  2039. */
  2040. function getParsedTitle() {
  2041. return $this->mConverter->getParsedTitle();
  2042. }
  2043. /**
  2044. * Enclose a string with the "no conversion" tag. This is used by
  2045. * various functions in the Parser
  2046. *
  2047. * @param $text String: text to be tagged for no conversion
  2048. * @param $noParse
  2049. * @return string the tagged text
  2050. */
  2051. function markNoConversion( $text, $noParse=false ) {
  2052. return $this->mConverter->markNoConversion( $text, $noParse );
  2053. }
  2054. /**
  2055. * A regular expression to match legal word-trailing characters
  2056. * which should be merged onto a link of the form [[foo]]bar.
  2057. *
  2058. * @return string
  2059. */
  2060. function linkTrail() {
  2061. $this->load();
  2062. return $this->linkTrail;
  2063. }
  2064. function getLangObj() {
  2065. return $this;
  2066. }
  2067. /**
  2068. * Get the RFC 3066 code for this language object
  2069. */
  2070. function getCode() {
  2071. return $this->mCode;
  2072. }
  2073. function setCode( $code ) {
  2074. $this->mCode = $code;
  2075. }
  2076. static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
  2077. return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
  2078. }
  2079. static function getMessagesFileName( $code ) {
  2080. global $IP;
  2081. return self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
  2082. }
  2083. static function getClassFileName( $code ) {
  2084. global $IP;
  2085. return self::getFileName( "$IP/languages/classes/Language", $code, '.php' );
  2086. }
  2087. static function getLocalisationArray( $code, $disableCache = false ) {
  2088. self::loadLocalisation( $code, $disableCache );
  2089. return self::$mLocalisationCache[$code];
  2090. }
  2091. /**
  2092. * Load localisation data for a given code into the static cache
  2093. *
  2094. * @return array Dependencies, map of filenames to mtimes
  2095. */
  2096. static function loadLocalisation( $code, $disableCache = false ) {
  2097. static $recursionGuard = array();
  2098. global $wgMemc, $wgEnableSerializedMessages, $wgCheckSerialized;
  2099. if ( !$code ) {
  2100. throw new MWException( "Invalid language code requested" );
  2101. }
  2102. if ( !$disableCache ) {
  2103. # Try the per-process cache
  2104. if ( isset( self::$mLocalisationCache[$code] ) ) {
  2105. return self::$mLocalisationCache[$code]['deps'];
  2106. }
  2107. wfProfileIn( __METHOD__ );
  2108. # Try the serialized directory
  2109. if( $wgEnableSerializedMessages ) {
  2110. $cache = wfGetPrecompiledData( self::getFileName( "Messages", $code, '.ser' ) );
  2111. if ( $cache ) {
  2112. if ( $wgCheckSerialized && self::isLocalisationOutOfDate( $cache ) ) {
  2113. $cache = false;
  2114. wfDebug( "Language::loadLocalisation(): precompiled data file for $code is out of date\n" );
  2115. } else {
  2116. self::$mLocalisationCache[$code] = $cache;
  2117. wfDebug( "Language::loadLocalisation(): got localisation for $code from precompiled data file\n" );
  2118. wfProfileOut( __METHOD__ );
  2119. return self::$mLocalisationCache[$code]['deps'];
  2120. }
  2121. }
  2122. }
  2123. # Try the global cache
  2124. $memcKey = wfMemcKey('localisation', $code );
  2125. $fbMemcKey = wfMemcKey('fallback', $cache['fallback'] );
  2126. $cache = $wgMemc->get( $memcKey );
  2127. if ( $cache ) {
  2128. if ( self::isLocalisationOutOfDate( $cache ) ) {
  2129. $wgMemc->delete( $memcKey );
  2130. $wgMemc->delete( $fbMemcKey );
  2131. $cache = false;
  2132. wfDebug( "Language::loadLocalisation(): localisation cache for $code had expired\n" );
  2133. } else {
  2134. self::$mLocalisationCache[$code] = $cache;
  2135. wfDebug( "Language::loadLocalisation(): got localisation for $code from cache\n" );
  2136. wfProfileOut( __METHOD__ );
  2137. return $cache['deps'];
  2138. }
  2139. }
  2140. } else {
  2141. wfProfileIn( __METHOD__ );
  2142. }
  2143. # Default fallback, may be overridden when the messages file is included
  2144. if ( $code != 'en' ) {
  2145. $fallback = 'en';
  2146. } else {
  2147. $fallback = false;
  2148. }
  2149. # Load the primary localisation from the source file
  2150. $filename = self::getMessagesFileName( $code );
  2151. if ( !file_exists( $filename ) ) {
  2152. wfDebug( "Language::loadLocalisation(): no localisation file for $code, using implicit fallback to en\n" );
  2153. $cache = compact( self::$mLocalisationKeys ); // Set correct fallback
  2154. $deps = array();
  2155. } else {
  2156. $deps = array( $filename => filemtime( $filename ) );
  2157. require( $filename );
  2158. $cache = compact( self::$mLocalisationKeys );
  2159. wfDebug( "Language::loadLocalisation(): got localisation for $code from source\n" );
  2160. }
  2161. # Load magic word source file
  2162. global $IP;
  2163. $filename = "$IP/includes/MagicWord.php";
  2164. $newDeps = array( $filename => filemtime( $filename ) );
  2165. $deps = array_merge( $deps, $newDeps );
  2166. if ( !empty( $fallback ) ) {
  2167. # Load the fallback localisation, with a circular reference guard
  2168. if ( isset( $recursionGuard[$code] ) ) {
  2169. throw new MWException( "Error: Circular fallback reference in language code $code" );
  2170. }
  2171. $recursionGuard[$code] = true;
  2172. $newDeps = self::loadLocalisation( $fallback, $disableCache );
  2173. unset( $recursionGuard[$code] );
  2174. $secondary = self::$mLocalisationCache[$fallback];
  2175. $deps = array_merge( $deps, $newDeps );
  2176. # Merge the fallback localisation with the current localisation
  2177. foreach ( self::$mLocalisationKeys as $key ) {
  2178. if ( isset( $cache[$key] ) ) {
  2179. if ( isset( $secondary[$key] ) ) {
  2180. if ( in_array( $key, self::$mMergeableMapKeys ) ) {
  2181. $cache[$key] = $cache[$key] + $secondary[$key];
  2182. } elseif ( in_array( $key, self::$mMergeableListKeys ) ) {
  2183. $cache[$key] = array_merge( $secondary[$key], $cache[$key] );
  2184. } elseif ( in_array( $key, self::$mMergeableAliasListKeys ) ) {
  2185. $cache[$key] = array_merge_recursive( $cache[$key], $secondary[$key] );
  2186. }
  2187. }
  2188. } else {
  2189. $cache[$key] = $secondary[$key];
  2190. }
  2191. }
  2192. # Merge bookstore lists if requested
  2193. if ( !empty( $cache['bookstoreList']['inherit'] ) ) {
  2194. $cache['bookstoreList'] = array_merge( $cache['bookstoreList'], $secondary['bookstoreList'] );
  2195. }
  2196. if ( isset( $cache['bookstoreList']['inherit'] ) ) {
  2197. unset( $cache['bookstoreList']['inherit'] );
  2198. }
  2199. }
  2200. # Add dependencies to the cache entry
  2201. $cache['deps'] = $deps;
  2202. # Replace spaces with underscores in namespace names
  2203. $cache['namespaceNames'] = str_replace( ' ', '_', $cache['namespaceNames'] );
  2204. # And do the same for specialpage aliases. $page is an array.
  2205. foreach ( $cache['specialPageAliases'] as &$page ) {
  2206. $page = str_replace( ' ', '_', $page );
  2207. }
  2208. # Decouple the reference to prevent accidental damage
  2209. unset($page);
  2210. # Save to both caches
  2211. self::$mLocalisationCache[$code] = $cache;
  2212. if ( !$disableCache ) {
  2213. $wgMemc->set( $memcKey, $cache );
  2214. $wgMemc->set( $fbMemcKey, (string) $cache['fallback'] );
  2215. }
  2216. wfProfileOut( __METHOD__ );
  2217. return $deps;
  2218. }
  2219. /**
  2220. * Test if a given localisation cache is out of date with respect to the
  2221. * source Messages files. This is done automatically for the global cache
  2222. * in $wgMemc, but is only done on certain occasions for the serialized
  2223. * data file.
  2224. *
  2225. * @param $cache mixed Either a language code or a cache array
  2226. */
  2227. static function isLocalisationOutOfDate( $cache ) {
  2228. if ( !is_array( $cache ) ) {
  2229. self::loadLocalisation( $cache );
  2230. $cache = self::$mLocalisationCache[$cache];
  2231. }
  2232. // At least one language file and the MagicWord file needed
  2233. if( count($cache['deps']) < 2 ) {
  2234. return true;
  2235. }
  2236. $expired = false;
  2237. foreach ( $cache['deps'] as $file => $mtime ) {
  2238. if ( !file_exists( $file ) || filemtime( $file ) > $mtime ) {
  2239. $expired = true;
  2240. break;
  2241. }
  2242. }
  2243. return $expired;
  2244. }
  2245. /**
  2246. * Get the fallback for a given language
  2247. */
  2248. static function getFallbackFor( $code ) {
  2249. // Shortcut
  2250. if ( $code === 'en' ) return false;
  2251. // Local cache
  2252. static $cache = array();
  2253. // Quick return
  2254. if ( isset($cache[$code]) ) return $cache[$code];
  2255. // Try memcache
  2256. global $wgMemc;
  2257. $memcKey = wfMemcKey( 'fallback', $code );
  2258. $fbcode = $wgMemc->get( $memcKey );
  2259. if ( is_string($fbcode) ) {
  2260. // False is stored as a string to detect failures in memcache properly
  2261. if ( $fbcode === '' ) $fbcode = false;
  2262. // Update local cache and return
  2263. $cache[$code] = $fbcode;
  2264. return $fbcode;
  2265. }
  2266. // Nothing in caches, load and and update both caches
  2267. self::loadLocalisation( $code );
  2268. $fbcode = self::$mLocalisationCache[$code]['fallback'];
  2269. $cache[$code] = $fbcode;
  2270. $wgMemc->set( $memcKey, (string) $fbcode );
  2271. return $fbcode;
  2272. }
  2273. /**
  2274. * Get all messages for a given language
  2275. */
  2276. static function getMessagesFor( $code ) {
  2277. self::loadLocalisation( $code );
  2278. return self::$mLocalisationCache[$code]['messages'];
  2279. }
  2280. /**
  2281. * Get a message for a given language
  2282. */
  2283. static function getMessageFor( $key, $code ) {
  2284. self::loadLocalisation( $code );
  2285. return isset( self::$mLocalisationCache[$code]['messages'][$key] ) ? self::$mLocalisationCache[$code]['messages'][$key] : null;
  2286. }
  2287. /**
  2288. * Load localisation data for this object
  2289. */
  2290. function load() {
  2291. if ( !$this->mLoaded ) {
  2292. self::loadLocalisation( $this->getCode() );
  2293. $cache =& self::$mLocalisationCache[$this->getCode()];
  2294. foreach ( self::$mLocalisationKeys as $key ) {
  2295. $this->$key = $cache[$key];
  2296. }
  2297. $this->mLoaded = true;
  2298. $this->fixUpSettings();
  2299. }
  2300. }
  2301. /**
  2302. * Do any necessary post-cache-load settings adjustment
  2303. */
  2304. function fixUpSettings() {
  2305. global $wgExtraNamespaces, $wgMetaNamespace, $wgMetaNamespaceTalk,
  2306. $wgNamespaceAliases, $wgAmericanDates;
  2307. wfProfileIn( __METHOD__ );
  2308. if ( $wgExtraNamespaces ) {
  2309. $this->namespaceNames = $wgExtraNamespaces + $this->namespaceNames;
  2310. }
  2311. $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
  2312. if ( $wgMetaNamespaceTalk ) {
  2313. $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
  2314. } else {
  2315. $talk = $this->namespaceNames[NS_PROJECT_TALK];
  2316. $this->namespaceNames[NS_PROJECT_TALK] =
  2317. $this->fixVariableInNamespace( $talk );
  2318. }
  2319. # The above mixing may leave namespaces out of canonical order.
  2320. # Re-order by namespace ID number...
  2321. ksort( $this->namespaceNames );
  2322. # Put namespace names and aliases into a hashtable.
  2323. # If this is too slow, then we should arrange it so that it is done
  2324. # before caching. The catch is that at pre-cache time, the above
  2325. # class-specific fixup hasn't been done.
  2326. $this->mNamespaceIds = array();
  2327. foreach ( $this->namespaceNames as $index => $name ) {
  2328. $this->mNamespaceIds[$this->lc($name)] = $index;
  2329. }
  2330. if ( $this->namespaceAliases ) {
  2331. foreach ( $this->namespaceAliases as $name => $index ) {
  2332. if ( $index === NS_PROJECT_TALK ) {
  2333. unset( $this->namespaceAliases[$name] );
  2334. $name = $this->fixVariableInNamespace( $name );
  2335. $this->namespaceAliases[$name] = $index;
  2336. }
  2337. $this->mNamespaceIds[$this->lc($name)] = $index;
  2338. }
  2339. }
  2340. if ( $wgNamespaceAliases ) {
  2341. foreach ( $wgNamespaceAliases as $name => $index ) {
  2342. $this->mNamespaceIds[$this->lc($name)] = $index;
  2343. }
  2344. }
  2345. if ( $this->defaultDateFormat == 'dmy or mdy' ) {
  2346. $this->defaultDateFormat = $wgAmericanDates ? 'mdy' : 'dmy';
  2347. }
  2348. wfProfileOut( __METHOD__ );
  2349. }
  2350. function fixVariableInNamespace( $talk ) {
  2351. if ( strpos( $talk, '$1' ) === false ) return $talk;
  2352. global $wgMetaNamespace;
  2353. $talk = str_replace( '$1', $wgMetaNamespace, $talk );
  2354. # Allow grammar transformations
  2355. # Allowing full message-style parsing would make simple requests
  2356. # such as action=raw much more expensive than they need to be.
  2357. # This will hopefully cover most cases.
  2358. $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
  2359. array( &$this, 'replaceGrammarInNamespace' ), $talk );
  2360. return str_replace( ' ', '_', $talk );
  2361. }
  2362. function replaceGrammarInNamespace( $m ) {
  2363. return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
  2364. }
  2365. static function getCaseMaps() {
  2366. static $wikiUpperChars, $wikiLowerChars;
  2367. if ( isset( $wikiUpperChars ) ) {
  2368. return array( $wikiUpperChars, $wikiLowerChars );
  2369. }
  2370. wfProfileIn( __METHOD__ );
  2371. $arr = wfGetPrecompiledData( 'Utf8Case.ser' );
  2372. if ( $arr === false ) {
  2373. throw new MWException(
  2374. "Utf8Case.ser is missing, please run \"make\" in the serialized directory\n" );
  2375. }
  2376. extract( $arr );
  2377. wfProfileOut( __METHOD__ );
  2378. return array( $wikiUpperChars, $wikiLowerChars );
  2379. }
  2380. function formatTimePeriod( $seconds ) {
  2381. if ( $seconds < 10 ) {
  2382. return $this->formatNum( sprintf( "%.1f", $seconds ) ) . wfMsg( 'seconds-abbrev' );
  2383. } elseif ( $seconds < 60 ) {
  2384. return $this->formatNum( round( $seconds ) ) . wfMsg( 'seconds-abbrev' );
  2385. } elseif ( $seconds < 3600 ) {
  2386. return $this->formatNum( floor( $seconds / 60 ) ) . wfMsg( 'minutes-abbrev' ) .
  2387. $this->formatNum( round( fmod( $seconds, 60 ) ) ) . wfMsg( 'seconds-abbrev' );
  2388. } else {
  2389. $hours = floor( $seconds / 3600 );
  2390. $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
  2391. $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
  2392. return $this->formatNum( $hours ) . wfMsg( 'hours-abbrev' ) .
  2393. $this->formatNum( $minutes ) . wfMsg( 'minutes-abbrev' ) .
  2394. $this->formatNum( $secondsPart ) . wfMsg( 'seconds-abbrev' );
  2395. }
  2396. }
  2397. function formatBitrate( $bps ) {
  2398. $units = array( 'bps', 'kbps', 'Mbps', 'Gbps' );
  2399. if ( $bps <= 0 ) {
  2400. return $this->formatNum( $bps ) . $units[0];
  2401. }
  2402. $unitIndex = floor( log10( $bps ) / 3 );
  2403. $mantissa = $bps / pow( 1000, $unitIndex );
  2404. if ( $mantissa < 10 ) {
  2405. $mantissa = round( $mantissa, 1 );
  2406. } else {
  2407. $mantissa = round( $mantissa );
  2408. }
  2409. return $this->formatNum( $mantissa ) . $units[$unitIndex];
  2410. }
  2411. /**
  2412. * Format a size in bytes for output, using an appropriate
  2413. * unit (B, KB, MB or GB) according to the magnitude in question
  2414. *
  2415. * @param $size Size to format
  2416. * @return string Plain text (not HTML)
  2417. */
  2418. function formatSize( $size ) {
  2419. // For small sizes no decimal places necessary
  2420. $round = 0;
  2421. if( $size > 1024 ) {
  2422. $size = $size / 1024;
  2423. if( $size > 1024 ) {
  2424. $size = $size / 1024;
  2425. // For MB and bigger two decimal places are smarter
  2426. $round = 2;
  2427. if( $size > 1024 ) {
  2428. $size = $size / 1024;
  2429. $msg = 'size-gigabytes';
  2430. } else {
  2431. $msg = 'size-megabytes';
  2432. }
  2433. } else {
  2434. $msg = 'size-kilobytes';
  2435. }
  2436. } else {
  2437. $msg = 'size-bytes';
  2438. }
  2439. $size = round( $size, $round );
  2440. $text = $this->getMessageFromDB( $msg );
  2441. return str_replace( '$1', $this->formatNum( $size ), $text );
  2442. }
  2443. }