Language.php 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015
  1. <?php
  2. /**
  3. * Internationalisation code.
  4. * See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more information.
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License along
  17. * with this program; if not, write to the Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. * http://www.gnu.org/copyleft/gpl.html
  20. *
  21. * @file
  22. * @ingroup Language
  23. */
  24. /**
  25. * @defgroup Language Language
  26. */
  27. use CLDRPluralRuleParser\Evaluator;
  28. /**
  29. * Internationalisation code
  30. * @ingroup Language
  31. */
  32. class Language {
  33. /**
  34. * @var LanguageConverter
  35. */
  36. public $mConverter;
  37. public $mVariants, $mCode, $mLoaded = false;
  38. public $mMagicExtensions = [], $mMagicHookDone = false;
  39. private $mHtmlCode = null, $mParentLanguage = false;
  40. public $dateFormatStrings = [];
  41. public $mExtendedSpecialPageAliases;
  42. /** @var array|null */
  43. protected $namespaceNames;
  44. protected $mNamespaceIds, $namespaceAliases;
  45. /**
  46. * ReplacementArray object caches
  47. */
  48. public $transformData = [];
  49. /**
  50. * @var LocalisationCache
  51. */
  52. static public $dataCache;
  53. static public $mLangObjCache = [];
  54. static public $mWeekdayMsgs = [
  55. 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday',
  56. 'friday', 'saturday'
  57. ];
  58. static public $mWeekdayAbbrevMsgs = [
  59. 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
  60. ];
  61. static public $mMonthMsgs = [
  62. 'january', 'february', 'march', 'april', 'may_long', 'june',
  63. 'july', 'august', 'september', 'october', 'november',
  64. 'december'
  65. ];
  66. static public $mMonthGenMsgs = [
  67. 'january-gen', 'february-gen', 'march-gen', 'april-gen', 'may-gen', 'june-gen',
  68. 'july-gen', 'august-gen', 'september-gen', 'october-gen', 'november-gen',
  69. 'december-gen'
  70. ];
  71. static public $mMonthAbbrevMsgs = [
  72. 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
  73. 'sep', 'oct', 'nov', 'dec'
  74. ];
  75. static public $mIranianCalendarMonthMsgs = [
  76. 'iranian-calendar-m1', 'iranian-calendar-m2', 'iranian-calendar-m3',
  77. 'iranian-calendar-m4', 'iranian-calendar-m5', 'iranian-calendar-m6',
  78. 'iranian-calendar-m7', 'iranian-calendar-m8', 'iranian-calendar-m9',
  79. 'iranian-calendar-m10', 'iranian-calendar-m11', 'iranian-calendar-m12'
  80. ];
  81. static public $mHebrewCalendarMonthMsgs = [
  82. 'hebrew-calendar-m1', 'hebrew-calendar-m2', 'hebrew-calendar-m3',
  83. 'hebrew-calendar-m4', 'hebrew-calendar-m5', 'hebrew-calendar-m6',
  84. 'hebrew-calendar-m7', 'hebrew-calendar-m8', 'hebrew-calendar-m9',
  85. 'hebrew-calendar-m10', 'hebrew-calendar-m11', 'hebrew-calendar-m12',
  86. 'hebrew-calendar-m6a', 'hebrew-calendar-m6b'
  87. ];
  88. static public $mHebrewCalendarMonthGenMsgs = [
  89. 'hebrew-calendar-m1-gen', 'hebrew-calendar-m2-gen', 'hebrew-calendar-m3-gen',
  90. 'hebrew-calendar-m4-gen', 'hebrew-calendar-m5-gen', 'hebrew-calendar-m6-gen',
  91. 'hebrew-calendar-m7-gen', 'hebrew-calendar-m8-gen', 'hebrew-calendar-m9-gen',
  92. 'hebrew-calendar-m10-gen', 'hebrew-calendar-m11-gen', 'hebrew-calendar-m12-gen',
  93. 'hebrew-calendar-m6a-gen', 'hebrew-calendar-m6b-gen'
  94. ];
  95. static public $mHijriCalendarMonthMsgs = [
  96. 'hijri-calendar-m1', 'hijri-calendar-m2', 'hijri-calendar-m3',
  97. 'hijri-calendar-m4', 'hijri-calendar-m5', 'hijri-calendar-m6',
  98. 'hijri-calendar-m7', 'hijri-calendar-m8', 'hijri-calendar-m9',
  99. 'hijri-calendar-m10', 'hijri-calendar-m11', 'hijri-calendar-m12'
  100. ];
  101. /**
  102. * @since 1.20
  103. * @var array
  104. */
  105. static public $durationIntervals = [
  106. 'millennia' => 31556952000,
  107. 'centuries' => 3155695200,
  108. 'decades' => 315569520,
  109. 'years' => 31556952, // 86400 * ( 365 + ( 24 * 3 + 25 ) / 400 )
  110. 'weeks' => 604800,
  111. 'days' => 86400,
  112. 'hours' => 3600,
  113. 'minutes' => 60,
  114. 'seconds' => 1,
  115. ];
  116. /**
  117. * Cache for language fallbacks.
  118. * @see Language::getFallbacksIncludingSiteLanguage
  119. * @since 1.21
  120. * @var array
  121. */
  122. static private $fallbackLanguageCache = [];
  123. /**
  124. * Cache for grammar rules data
  125. * @var MapCacheLRU|null
  126. */
  127. static private $grammarTransformations;
  128. /**
  129. * Cache for language names
  130. * @var HashBagOStuff|null
  131. */
  132. static private $languageNameCache;
  133. /**
  134. * Unicode directional formatting characters, for embedBidi()
  135. */
  136. static private $lre = "\xE2\x80\xAA"; // U+202A LEFT-TO-RIGHT EMBEDDING
  137. static private $rle = "\xE2\x80\xAB"; // U+202B RIGHT-TO-LEFT EMBEDDING
  138. static private $pdf = "\xE2\x80\xAC"; // U+202C POP DIRECTIONAL FORMATTING
  139. /**
  140. * Directionality test regex for embedBidi(). Matches the first strong directionality codepoint:
  141. * - in group 1 if it is LTR
  142. * - in group 2 if it is RTL
  143. * Does not match if there is no strong directionality codepoint.
  144. *
  145. * The form is '/(?:([strong ltr codepoint])|([strong rtl codepoint]))/u' .
  146. *
  147. * Generated by UnicodeJS (see tools/strongDir) from the UCD; see
  148. * https://phabricator.wikimedia.org/diffusion/GUJS/ .
  149. */
  150. // @codeCoverageIgnoreStart
  151. // phpcs:ignore Generic.Files.LineLength
  152. static private $strongDirRegex = '/(?:([\x{41}-\x{5a}\x{61}-\x{7a}\x{aa}\x{b5}\x{ba}\x{c0}-\x{d6}\x{d8}-\x{f6}\x{f8}-\x{2b8}\x{2bb}-\x{2c1}\x{2d0}\x{2d1}\x{2e0}-\x{2e4}\x{2ee}\x{370}-\x{373}\x{376}\x{377}\x{37a}-\x{37d}\x{37f}\x{386}\x{388}-\x{38a}\x{38c}\x{38e}-\x{3a1}\x{3a3}-\x{3f5}\x{3f7}-\x{482}\x{48a}-\x{52f}\x{531}-\x{556}\x{559}-\x{55f}\x{561}-\x{587}\x{589}\x{903}-\x{939}\x{93b}\x{93d}-\x{940}\x{949}-\x{94c}\x{94e}-\x{950}\x{958}-\x{961}\x{964}-\x{980}\x{982}\x{983}\x{985}-\x{98c}\x{98f}\x{990}\x{993}-\x{9a8}\x{9aa}-\x{9b0}\x{9b2}\x{9b6}-\x{9b9}\x{9bd}-\x{9c0}\x{9c7}\x{9c8}\x{9cb}\x{9cc}\x{9ce}\x{9d7}\x{9dc}\x{9dd}\x{9df}-\x{9e1}\x{9e6}-\x{9f1}\x{9f4}-\x{9fa}\x{a03}\x{a05}-\x{a0a}\x{a0f}\x{a10}\x{a13}-\x{a28}\x{a2a}-\x{a30}\x{a32}\x{a33}\x{a35}\x{a36}\x{a38}\x{a39}\x{a3e}-\x{a40}\x{a59}-\x{a5c}\x{a5e}\x{a66}-\x{a6f}\x{a72}-\x{a74}\x{a83}\x{a85}-\x{a8d}\x{a8f}-\x{a91}\x{a93}-\x{aa8}\x{aaa}-\x{ab0}\x{ab2}\x{ab3}\x{ab5}-\x{ab9}\x{abd}-\x{ac0}\x{ac9}\x{acb}\x{acc}\x{ad0}\x{ae0}\x{ae1}\x{ae6}-\x{af0}\x{af9}\x{b02}\x{b03}\x{b05}-\x{b0c}\x{b0f}\x{b10}\x{b13}-\x{b28}\x{b2a}-\x{b30}\x{b32}\x{b33}\x{b35}-\x{b39}\x{b3d}\x{b3e}\x{b40}\x{b47}\x{b48}\x{b4b}\x{b4c}\x{b57}\x{b5c}\x{b5d}\x{b5f}-\x{b61}\x{b66}-\x{b77}\x{b83}\x{b85}-\x{b8a}\x{b8e}-\x{b90}\x{b92}-\x{b95}\x{b99}\x{b9a}\x{b9c}\x{b9e}\x{b9f}\x{ba3}\x{ba4}\x{ba8}-\x{baa}\x{bae}-\x{bb9}\x{bbe}\x{bbf}\x{bc1}\x{bc2}\x{bc6}-\x{bc8}\x{bca}-\x{bcc}\x{bd0}\x{bd7}\x{be6}-\x{bf2}\x{c01}-\x{c03}\x{c05}-\x{c0c}\x{c0e}-\x{c10}\x{c12}-\x{c28}\x{c2a}-\x{c39}\x{c3d}\x{c41}-\x{c44}\x{c58}-\x{c5a}\x{c60}\x{c61}\x{c66}-\x{c6f}\x{c7f}\x{c82}\x{c83}\x{c85}-\x{c8c}\x{c8e}-\x{c90}\x{c92}-\x{ca8}\x{caa}-\x{cb3}\x{cb5}-\x{cb9}\x{cbd}-\x{cc4}\x{cc6}-\x{cc8}\x{cca}\x{ccb}\x{cd5}\x{cd6}\x{cde}\x{ce0}\x{ce1}\x{ce6}-\x{cef}\x{cf1}\x{cf2}\x{d02}\x{d03}\x{d05}-\x{d0c}\x{d0e}-\x{d10}\x{d12}-\x{d3a}\x{d3d}-\x{d40}\x{d46}-\x{d48}\x{d4a}-\x{d4c}\x{d4e}\x{d57}\x{d5f}-\x{d61}\x{d66}-\x{d75}\x{d79}-\x{d7f}\x{d82}\x{d83}\x{d85}-\x{d96}\x{d9a}-\x{db1}\x{db3}-\x{dbb}\x{dbd}\x{dc0}-\x{dc6}\x{dcf}-\x{dd1}\x{dd8}-\x{ddf}\x{de6}-\x{def}\x{df2}-\x{df4}\x{e01}-\x{e30}\x{e32}\x{e33}\x{e40}-\x{e46}\x{e4f}-\x{e5b}\x{e81}\x{e82}\x{e84}\x{e87}\x{e88}\x{e8a}\x{e8d}\x{e94}-\x{e97}\x{e99}-\x{e9f}\x{ea1}-\x{ea3}\x{ea5}\x{ea7}\x{eaa}\x{eab}\x{ead}-\x{eb0}\x{eb2}\x{eb3}\x{ebd}\x{ec0}-\x{ec4}\x{ec6}\x{ed0}-\x{ed9}\x{edc}-\x{edf}\x{f00}-\x{f17}\x{f1a}-\x{f34}\x{f36}\x{f38}\x{f3e}-\x{f47}\x{f49}-\x{f6c}\x{f7f}\x{f85}\x{f88}-\x{f8c}\x{fbe}-\x{fc5}\x{fc7}-\x{fcc}\x{fce}-\x{fda}\x{1000}-\x{102c}\x{1031}\x{1038}\x{103b}\x{103c}\x{103f}-\x{1057}\x{105a}-\x{105d}\x{1061}-\x{1070}\x{1075}-\x{1081}\x{1083}\x{1084}\x{1087}-\x{108c}\x{108e}-\x{109c}\x{109e}-\x{10c5}\x{10c7}\x{10cd}\x{10d0}-\x{1248}\x{124a}-\x{124d}\x{1250}-\x{1256}\x{1258}\x{125a}-\x{125d}\x{1260}-\x{1288}\x{128a}-\x{128d}\x{1290}-\x{12b0}\x{12b2}-\x{12b5}\x{12b8}-\x{12be}\x{12c0}\x{12c2}-\x{12c5}\x{12c8}-\x{12d6}\x{12d8}-\x{1310}\x{1312}-\x{1315}\x{1318}-\x{135a}\x{1360}-\x{137c}\x{1380}-\x{138f}\x{13a0}-\x{13f5}\x{13f8}-\x{13fd}\x{1401}-\x{167f}\x{1681}-\x{169a}\x{16a0}-\x{16f8}\x{1700}-\x{170c}\x{170e}-\x{1711}\x{1720}-\x{1731}\x{1735}\x{1736}\x{1740}-\x{1751}\x{1760}-\x{176c}\x{176e}-\x{1770}\x{1780}-\x{17b3}\x{17b6}\x{17be}-\x{17c5}\x{17c7}\x{17c8}\x{17d4}-\x{17da}\x{17dc}\x{17e0}-\x{17e9}\x{1810}-\x{1819}\x{1820}-\x{1877}\x{1880}-\x{18a8}\x{18aa}\x{18b0}-\x{18f5}\x{1900}-\x{191e}\x{1923}-\x{1926}\x{1929}-\x{192b}\x{1930}\x{1931}\x{1933}-\x{1938}\x{1946}-\x{196d}\x{1970}-\x{1974}\x{1980}-\x{19ab}\x{19b0}-\x{19c9}\x{19d0}-\x{19da}\x{1a00}-\x{1a16}\x{1a19}\x{1a1a}\x{1a1e}-\x{1a55}\x{1a57}\x{1a61}\x{1a63}\x{1a64}\x{1a6d}-\x{1a72}\x{1a80}-\x{1a89}\x{1a90}-\x{1a99}\x{1aa0}-\x{1aad}\x{1b04}-\x{1b33}\x{1b35}\x{1b3b}\x{1b3d}-\x{1b41}\x{1b43}-\x{1b4b}\x{1b50}-\x{1b6a}\x{1b74}-\x{1b7c}\x{1b82}-\x{1ba1}\x{1ba6}\x{1ba7}\x{1baa}\x{1bae}-\x{1be5}\x{1be7}\x{1bea}-\x{1bec}\x{1bee}\x{1bf2}\x{1bf3}\x{1bfc}-\x{1c2b}\x{1c34}\x{1c35}\x{1c3b}-\x{1c49}\x{1c4d}-\x{1c7f}\x{1cc0}-\x{1cc7}\x{1cd3}\x{1ce1}\x{1ce9}-\x{1cec}\x{1cee}-\x{1cf3}\x{1cf5}\x{1cf6}\x{1d00}-\x{1dbf}\x{1e00}-\x{1f15}\x{1f18}-\x{1f1d}\x{1f20}-\x{1f45}\x{1f48}-\x{1f4d}\x{1f50}-\x{1f57}\x{1f59}\x{1f5b}\x{1f5d}\x{1f5f}-\x{1f7d}\x{1f80}-\x{1fb4}\x{1fb6}-\x{1fbc}\x{1fbe}\x{1fc2}-\x{1fc4}\x{1fc6}-\x{1fcc}\x{1fd0}-\x{1fd3}\x{1fd6}-\x{1fdb}\x{1fe0}-\x{1fec}\x{1ff2}-\x{1ff4}\x{1ff6}-\x{1ffc}\x{200e}\x{2071}\x{207f}\x{2090}-\x{209c}\x{2102}\x{2107}\x{210a}-\x{2113}\x{2115}\x{2119}-\x{211d}\x{2124}\x{2126}\x{2128}\x{212a}-\x{212d}\x{212f}-\x{2139}\x{213c}-\x{213f}\x{2145}-\x{2149}\x{214e}\x{214f}\x{2160}-\x{2188}\x{2336}-\x{237a}\x{2395}\x{249c}-\x{24e9}\x{26ac}\x{2800}-\x{28ff}\x{2c00}-\x{2c2e}\x{2c30}-\x{2c5e}\x{2c60}-\x{2ce4}\x{2ceb}-\x{2cee}\x{2cf2}\x{2cf3}\x{2d00}-\x{2d25}\x{2d27}\x{2d2d}\x{2d30}-\x{2d67}\x{2d6f}\x{2d70}\x{2d80}-\x{2d96}\x{2da0}-\x{2da6}\x{2da8}-\x{2dae}\x{2db0}-\x{2db6}\x{2db8}-\x{2dbe}\x{2dc0}-\x{2dc6}\x{2dc8}-\x{2dce}\x{2dd0}-\x{2dd6}\x{2dd8}-\x{2dde}\x{3005}-\x{3007}\x{3021}-\x{3029}\x{302e}\x{302f}\x{3031}-\x{3035}\x{3038}-\x{303c}\x{3041}-\x{3096}\x{309d}-\x{309f}\x{30a1}-\x{30fa}\x{30fc}-\x{30ff}\x{3105}-\x{312d}\x{3131}-\x{318e}\x{3190}-\x{31ba}\x{31f0}-\x{321c}\x{3220}-\x{324f}\x{3260}-\x{327b}\x{327f}-\x{32b0}\x{32c0}-\x{32cb}\x{32d0}-\x{32fe}\x{3300}-\x{3376}\x{337b}-\x{33dd}\x{33e0}-\x{33fe}\x{3400}-\x{4db5}\x{4e00}-\x{9fd5}\x{a000}-\x{a48c}\x{a4d0}-\x{a60c}\x{a610}-\x{a62b}\x{a640}-\x{a66e}\x{a680}-\x{a69d}\x{a6a0}-\x{a6ef}\x{a6f2}-\x{a6f7}\x{a722}-\x{a787}\x{a789}-\x{a7ad}\x{a7b0}-\x{a7b7}\x{a7f7}-\x{a801}\x{a803}-\x{a805}\x{a807}-\x{a80a}\x{a80c}-\x{a824}\x{a827}\x{a830}-\x{a837}\x{a840}-\x{a873}\x{a880}-\x{a8c3}\x{a8ce}-\x{a8d9}\x{a8f2}-\x{a8fd}\x{a900}-\x{a925}\x{a92e}-\x{a946}\x{a952}\x{a953}\x{a95f}-\x{a97c}\x{a983}-\x{a9b2}\x{a9b4}\x{a9b5}\x{a9ba}\x{a9bb}\x{a9bd}-\x{a9cd}\x{a9cf}-\x{a9d9}\x{a9de}-\x{a9e4}\x{a9e6}-\x{a9fe}\x{aa00}-\x{aa28}\x{aa2f}\x{aa30}\x{aa33}\x{aa34}\x{aa40}-\x{aa42}\x{aa44}-\x{aa4b}\x{aa4d}\x{aa50}-\x{aa59}\x{aa5c}-\x{aa7b}\x{aa7d}-\x{aaaf}\x{aab1}\x{aab5}\x{aab6}\x{aab9}-\x{aabd}\x{aac0}\x{aac2}\x{aadb}-\x{aaeb}\x{aaee}-\x{aaf5}\x{ab01}-\x{ab06}\x{ab09}-\x{ab0e}\x{ab11}-\x{ab16}\x{ab20}-\x{ab26}\x{ab28}-\x{ab2e}\x{ab30}-\x{ab65}\x{ab70}-\x{abe4}\x{abe6}\x{abe7}\x{abe9}-\x{abec}\x{abf0}-\x{abf9}\x{ac00}-\x{d7a3}\x{d7b0}-\x{d7c6}\x{d7cb}-\x{d7fb}\x{e000}-\x{fa6d}\x{fa70}-\x{fad9}\x{fb00}-\x{fb06}\x{fb13}-\x{fb17}\x{ff21}-\x{ff3a}\x{ff41}-\x{ff5a}\x{ff66}-\x{ffbe}\x{ffc2}-\x{ffc7}\x{ffca}-\x{ffcf}\x{ffd2}-\x{ffd7}\x{ffda}-\x{ffdc}\x{10000}-\x{1000b}\x{1000d}-\x{10026}\x{10028}-\x{1003a}\x{1003c}\x{1003d}\x{1003f}-\x{1004d}\x{10050}-\x{1005d}\x{10080}-\x{100fa}\x{10100}\x{10102}\x{10107}-\x{10133}\x{10137}-\x{1013f}\x{101d0}-\x{101fc}\x{10280}-\x{1029c}\x{102a0}-\x{102d0}\x{10300}-\x{10323}\x{10330}-\x{1034a}\x{10350}-\x{10375}\x{10380}-\x{1039d}\x{1039f}-\x{103c3}\x{103c8}-\x{103d5}\x{10400}-\x{1049d}\x{104a0}-\x{104a9}\x{10500}-\x{10527}\x{10530}-\x{10563}\x{1056f}\x{10600}-\x{10736}\x{10740}-\x{10755}\x{10760}-\x{10767}\x{11000}\x{11002}-\x{11037}\x{11047}-\x{1104d}\x{11066}-\x{1106f}\x{11082}-\x{110b2}\x{110b7}\x{110b8}\x{110bb}-\x{110c1}\x{110d0}-\x{110e8}\x{110f0}-\x{110f9}\x{11103}-\x{11126}\x{1112c}\x{11136}-\x{11143}\x{11150}-\x{11172}\x{11174}-\x{11176}\x{11182}-\x{111b5}\x{111bf}-\x{111c9}\x{111cd}\x{111d0}-\x{111df}\x{111e1}-\x{111f4}\x{11200}-\x{11211}\x{11213}-\x{1122e}\x{11232}\x{11233}\x{11235}\x{11238}-\x{1123d}\x{11280}-\x{11286}\x{11288}\x{1128a}-\x{1128d}\x{1128f}-\x{1129d}\x{1129f}-\x{112a9}\x{112b0}-\x{112de}\x{112e0}-\x{112e2}\x{112f0}-\x{112f9}\x{11302}\x{11303}\x{11305}-\x{1130c}\x{1130f}\x{11310}\x{11313}-\x{11328}\x{1132a}-\x{11330}\x{11332}\x{11333}\x{11335}-\x{11339}\x{1133d}-\x{1133f}\x{11341}-\x{11344}\x{11347}\x{11348}\x{1134b}-\x{1134d}\x{11350}\x{11357}\x{1135d}-\x{11363}\x{11480}-\x{114b2}\x{114b9}\x{114bb}-\x{114be}\x{114c1}\x{114c4}-\x{114c7}\x{114d0}-\x{114d9}\x{11580}-\x{115b1}\x{115b8}-\x{115bb}\x{115be}\x{115c1}-\x{115db}\x{11600}-\x{11632}\x{1163b}\x{1163c}\x{1163e}\x{11641}-\x{11644}\x{11650}-\x{11659}\x{11680}-\x{116aa}\x{116ac}\x{116ae}\x{116af}\x{116b6}\x{116c0}-\x{116c9}\x{11700}-\x{11719}\x{11720}\x{11721}\x{11726}\x{11730}-\x{1173f}\x{118a0}-\x{118f2}\x{118ff}\x{11ac0}-\x{11af8}\x{12000}-\x{12399}\x{12400}-\x{1246e}\x{12470}-\x{12474}\x{12480}-\x{12543}\x{13000}-\x{1342e}\x{14400}-\x{14646}\x{16800}-\x{16a38}\x{16a40}-\x{16a5e}\x{16a60}-\x{16a69}\x{16a6e}\x{16a6f}\x{16ad0}-\x{16aed}\x{16af5}\x{16b00}-\x{16b2f}\x{16b37}-\x{16b45}\x{16b50}-\x{16b59}\x{16b5b}-\x{16b61}\x{16b63}-\x{16b77}\x{16b7d}-\x{16b8f}\x{16f00}-\x{16f44}\x{16f50}-\x{16f7e}\x{16f93}-\x{16f9f}\x{1b000}\x{1b001}\x{1bc00}-\x{1bc6a}\x{1bc70}-\x{1bc7c}\x{1bc80}-\x{1bc88}\x{1bc90}-\x{1bc99}\x{1bc9c}\x{1bc9f}\x{1d000}-\x{1d0f5}\x{1d100}-\x{1d126}\x{1d129}-\x{1d166}\x{1d16a}-\x{1d172}\x{1d183}\x{1d184}\x{1d18c}-\x{1d1a9}\x{1d1ae}-\x{1d1e8}\x{1d360}-\x{1d371}\x{1d400}-\x{1d454}\x{1d456}-\x{1d49c}\x{1d49e}\x{1d49f}\x{1d4a2}\x{1d4a5}\x{1d4a6}\x{1d4a9}-\x{1d4ac}\x{1d4ae}-\x{1d4b9}\x{1d4bb}\x{1d4bd}-\x{1d4c3}\x{1d4c5}-\x{1d505}\x{1d507}-\x{1d50a}\x{1d50d}-\x{1d514}\x{1d516}-\x{1d51c}\x{1d51e}-\x{1d539}\x{1d53b}-\x{1d53e}\x{1d540}-\x{1d544}\x{1d546}\x{1d54a}-\x{1d550}\x{1d552}-\x{1d6a5}\x{1d6a8}-\x{1d6da}\x{1d6dc}-\x{1d714}\x{1d716}-\x{1d74e}\x{1d750}-\x{1d788}\x{1d78a}-\x{1d7c2}\x{1d7c4}-\x{1d7cb}\x{1d800}-\x{1d9ff}\x{1da37}-\x{1da3a}\x{1da6d}-\x{1da74}\x{1da76}-\x{1da83}\x{1da85}-\x{1da8b}\x{1f110}-\x{1f12e}\x{1f130}-\x{1f169}\x{1f170}-\x{1f19a}\x{1f1e6}-\x{1f202}\x{1f210}-\x{1f23a}\x{1f240}-\x{1f248}\x{1f250}\x{1f251}\x{20000}-\x{2a6d6}\x{2a700}-\x{2b734}\x{2b740}-\x{2b81d}\x{2b820}-\x{2cea1}\x{2f800}-\x{2fa1d}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}])|([\x{590}\x{5be}\x{5c0}\x{5c3}\x{5c6}\x{5c8}-\x{5ff}\x{7c0}-\x{7ea}\x{7f4}\x{7f5}\x{7fa}-\x{815}\x{81a}\x{824}\x{828}\x{82e}-\x{858}\x{85c}-\x{89f}\x{200f}\x{fb1d}\x{fb1f}-\x{fb28}\x{fb2a}-\x{fb4f}\x{10800}-\x{1091e}\x{10920}-\x{10a00}\x{10a04}\x{10a07}-\x{10a0b}\x{10a10}-\x{10a37}\x{10a3b}-\x{10a3e}\x{10a40}-\x{10ae4}\x{10ae7}-\x{10b38}\x{10b40}-\x{10e5f}\x{10e7f}-\x{10fff}\x{1e800}-\x{1e8cf}\x{1e8d7}-\x{1edff}\x{1ef00}-\x{1efff}\x{608}\x{60b}\x{60d}\x{61b}-\x{64a}\x{66d}-\x{66f}\x{671}-\x{6d5}\x{6e5}\x{6e6}\x{6ee}\x{6ef}\x{6fa}-\x{710}\x{712}-\x{72f}\x{74b}-\x{7a5}\x{7b1}-\x{7bf}\x{8a0}-\x{8e2}\x{fb50}-\x{fd3d}\x{fd40}-\x{fdcf}\x{fdf0}-\x{fdfc}\x{fdfe}\x{fdff}\x{fe70}-\x{fefe}\x{1ee00}-\x{1eeef}\x{1eef2}-\x{1eeff}]))/u';
  153. // @codeCoverageIgnoreEnd
  154. /**
  155. * Get a cached or new language object for a given language code
  156. * @param string $code
  157. * @throws MWException
  158. * @return Language
  159. */
  160. static function factory( $code ) {
  161. global $wgDummyLanguageCodes, $wgLangObjCacheSize;
  162. if ( isset( $wgDummyLanguageCodes[$code] ) ) {
  163. $code = $wgDummyLanguageCodes[$code];
  164. }
  165. // get the language object to process
  166. $langObj = isset( self::$mLangObjCache[$code] )
  167. ? self::$mLangObjCache[$code]
  168. : self::newFromCode( $code );
  169. // merge the language object in to get it up front in the cache
  170. self::$mLangObjCache = array_merge( [ $code => $langObj ], self::$mLangObjCache );
  171. // get rid of the oldest ones in case we have an overflow
  172. self::$mLangObjCache = array_slice( self::$mLangObjCache, 0, $wgLangObjCacheSize, true );
  173. return $langObj;
  174. }
  175. /**
  176. * Create a language object for a given language code
  177. * @param string $code
  178. * @param bool $fallback Whether we're going through language fallback chain
  179. * @throws MWException
  180. * @return Language
  181. */
  182. protected static function newFromCode( $code, $fallback = false ) {
  183. if ( !self::isValidCode( $code ) ) {
  184. throw new MWException( "Invalid language code \"$code\"" );
  185. }
  186. if ( !self::isValidBuiltInCode( $code ) ) {
  187. // It's not possible to customise this code with class files, so
  188. // just return a Language object. This is to support uselang= hacks.
  189. $lang = new Language;
  190. $lang->setCode( $code );
  191. return $lang;
  192. }
  193. // Check if there is a language class for the code
  194. $class = self::classFromCode( $code, $fallback );
  195. if ( class_exists( $class ) ) {
  196. $lang = new $class;
  197. return $lang;
  198. }
  199. // Keep trying the fallback list until we find an existing class
  200. $fallbacks = self::getFallbacksFor( $code );
  201. foreach ( $fallbacks as $fallbackCode ) {
  202. if ( !self::isValidBuiltInCode( $fallbackCode ) ) {
  203. throw new MWException( "Invalid fallback '$fallbackCode' in fallback sequence for '$code'" );
  204. }
  205. $class = self::classFromCode( $fallbackCode );
  206. if ( class_exists( $class ) ) {
  207. $lang = new $class;
  208. $lang->setCode( $code );
  209. return $lang;
  210. }
  211. }
  212. throw new MWException( "Invalid fallback sequence for language '$code'" );
  213. }
  214. /**
  215. * Checks whether any localisation is available for that language tag
  216. * in MediaWiki (MessagesXx.php exists).
  217. *
  218. * @param string $code Language tag (in lower case)
  219. * @return bool Whether language is supported
  220. * @since 1.21
  221. */
  222. public static function isSupportedLanguage( $code ) {
  223. if ( !self::isValidBuiltInCode( $code ) ) {
  224. return false;
  225. }
  226. if ( $code === 'qqq' ) {
  227. return false;
  228. }
  229. return is_readable( self::getMessagesFileName( $code ) ) ||
  230. is_readable( self::getJsonMessagesFileName( $code ) );
  231. }
  232. /**
  233. * Returns true if a language code string is a well-formed language tag
  234. * according to RFC 5646.
  235. * This function only checks well-formedness; it doesn't check that
  236. * language, script or variant codes actually exist in the repositories.
  237. *
  238. * Based on regexes by Mark Davis of the Unicode Consortium:
  239. * http://unicode.org/repos/cldr/trunk/tools/java/org/unicode/cldr/util/data/langtagRegex.txt
  240. *
  241. * @param string $code
  242. * @param bool $lenient Whether to allow '_' as separator. The default is only '-'.
  243. *
  244. * @return bool
  245. * @since 1.21
  246. */
  247. public static function isWellFormedLanguageTag( $code, $lenient = false ) {
  248. $alpha = '[a-z]';
  249. $digit = '[0-9]';
  250. $alphanum = '[a-z0-9]';
  251. $x = 'x'; # private use singleton
  252. $singleton = '[a-wy-z]'; # other singleton
  253. $s = $lenient ? '[-_]' : '-';
  254. $language = "$alpha{2,8}|$alpha{2,3}$s$alpha{3}";
  255. $script = "$alpha{4}"; # ISO 15924
  256. $region = "(?:$alpha{2}|$digit{3})"; # ISO 3166-1 alpha-2 or UN M.49
  257. $variant = "(?:$alphanum{5,8}|$digit$alphanum{3})";
  258. $extension = "$singleton(?:$s$alphanum{2,8})+";
  259. $privateUse = "$x(?:$s$alphanum{1,8})+";
  260. # Define certain grandfathered codes, since otherwise the regex is pretty useless.
  261. # Since these are limited, this is safe even later changes to the registry --
  262. # the only oddity is that it might change the type of the tag, and thus
  263. # the results from the capturing groups.
  264. # https://www.iana.org/assignments/language-subtag-registry
  265. $grandfathered = "en{$s}GB{$s}oed"
  266. . "|i{$s}(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)"
  267. . "|no{$s}(?:bok|nyn)"
  268. . "|sgn{$s}(?:BE{$s}(?:fr|nl)|CH{$s}de)"
  269. . "|zh{$s}min{$s}nan";
  270. $variantList = "$variant(?:$s$variant)*";
  271. $extensionList = "$extension(?:$s$extension)*";
  272. $langtag = "(?:($language)"
  273. . "(?:$s$script)?"
  274. . "(?:$s$region)?"
  275. . "(?:$s$variantList)?"
  276. . "(?:$s$extensionList)?"
  277. . "(?:$s$privateUse)?)";
  278. # The final breakdown, with capturing groups for each of these components
  279. # The variants, extensions, grandfathered, and private-use may have interior '-'
  280. $root = "^(?:$langtag|$privateUse|$grandfathered)$";
  281. return (bool)preg_match( "/$root/", strtolower( $code ) );
  282. }
  283. /**
  284. * Returns true if a language code string is of a valid form, whether or
  285. * not it exists. This includes codes which are used solely for
  286. * customisation via the MediaWiki namespace.
  287. *
  288. * @param string $code
  289. *
  290. * @return bool
  291. */
  292. public static function isValidCode( $code ) {
  293. static $cache = [];
  294. if ( !isset( $cache[$code] ) ) {
  295. // People think language codes are html safe, so enforce it.
  296. // Ideally we should only allow a-zA-Z0-9-
  297. // but, .+ and other chars are often used for {{int:}} hacks
  298. // see bugs T39564, T39587, T38938
  299. $cache[$code] =
  300. // Protect against path traversal
  301. strcspn( $code, ":/\\\000&<>'\"" ) === strlen( $code )
  302. && !preg_match( MediaWikiTitleCodec::getTitleInvalidRegex(), $code );
  303. }
  304. return $cache[$code];
  305. }
  306. /**
  307. * Returns true if a language code is of a valid form for the purposes of
  308. * internal customisation of MediaWiki, via Messages*.php or *.json.
  309. *
  310. * @param string $code
  311. *
  312. * @throws MWException
  313. * @since 1.18
  314. * @return bool
  315. */
  316. public static function isValidBuiltInCode( $code ) {
  317. if ( !is_string( $code ) ) {
  318. if ( is_object( $code ) ) {
  319. $addmsg = " of class " . get_class( $code );
  320. } else {
  321. $addmsg = '';
  322. }
  323. $type = gettype( $code );
  324. throw new MWException( __METHOD__ . " must be passed a string, $type given$addmsg" );
  325. }
  326. return (bool)preg_match( '/^[a-z0-9-]{2,}$/', $code );
  327. }
  328. /**
  329. * Returns true if a language code is an IETF tag known to MediaWiki.
  330. *
  331. * @param string $tag
  332. *
  333. * @since 1.21
  334. * @return bool
  335. */
  336. public static function isKnownLanguageTag( $tag ) {
  337. // Quick escape for invalid input to avoid exceptions down the line
  338. // when code tries to process tags which are not valid at all.
  339. if ( !self::isValidBuiltInCode( $tag ) ) {
  340. return false;
  341. }
  342. if ( isset( MediaWiki\Languages\Data\Names::$names[$tag] )
  343. || self::fetchLanguageName( $tag, $tag ) !== ''
  344. ) {
  345. return true;
  346. }
  347. return false;
  348. }
  349. /**
  350. * Get the LocalisationCache instance
  351. *
  352. * @return LocalisationCache
  353. */
  354. public static function getLocalisationCache() {
  355. if ( is_null( self::$dataCache ) ) {
  356. global $wgLocalisationCacheConf;
  357. $class = $wgLocalisationCacheConf['class'];
  358. self::$dataCache = new $class( $wgLocalisationCacheConf );
  359. }
  360. return self::$dataCache;
  361. }
  362. function __construct() {
  363. $this->mConverter = new FakeConverter( $this );
  364. // Set the code to the name of the descendant
  365. if ( static::class === 'Language' ) {
  366. $this->mCode = 'en';
  367. } else {
  368. $this->mCode = str_replace( '_', '-', strtolower( substr( static::class, 8 ) ) );
  369. }
  370. self::getLocalisationCache();
  371. }
  372. /**
  373. * Reduce memory usage
  374. */
  375. function __destruct() {
  376. foreach ( $this as $name => $value ) {
  377. unset( $this->$name );
  378. }
  379. }
  380. /**
  381. * Hook which will be called if this is the content language.
  382. * Descendants can use this to register hook functions or modify globals
  383. */
  384. function initContLang() {
  385. }
  386. /**
  387. * @return array
  388. * @since 1.19
  389. */
  390. public function getFallbackLanguages() {
  391. return self::getFallbacksFor( $this->mCode );
  392. }
  393. /**
  394. * Exports $wgBookstoreListEn
  395. * @return array
  396. */
  397. public function getBookstoreList() {
  398. return self::$dataCache->getItem( $this->mCode, 'bookstoreList' );
  399. }
  400. /**
  401. * Returns an array of localised namespaces indexed by their numbers. If the namespace is not
  402. * available in localised form, it will be included in English.
  403. *
  404. * @return array
  405. */
  406. public function getNamespaces() {
  407. if ( is_null( $this->namespaceNames ) ) {
  408. global $wgMetaNamespace, $wgMetaNamespaceTalk, $wgExtraNamespaces;
  409. $validNamespaces = MWNamespace::getCanonicalNamespaces();
  410. $this->namespaceNames = $wgExtraNamespaces +
  411. self::$dataCache->getItem( $this->mCode, 'namespaceNames' );
  412. $this->namespaceNames += $validNamespaces;
  413. $this->namespaceNames[NS_PROJECT] = $wgMetaNamespace;
  414. if ( $wgMetaNamespaceTalk ) {
  415. $this->namespaceNames[NS_PROJECT_TALK] = $wgMetaNamespaceTalk;
  416. } else {
  417. $talk = $this->namespaceNames[NS_PROJECT_TALK];
  418. $this->namespaceNames[NS_PROJECT_TALK] =
  419. $this->fixVariableInNamespace( $talk );
  420. }
  421. # Sometimes a language will be localised but not actually exist on this wiki.
  422. foreach ( $this->namespaceNames as $key => $text ) {
  423. if ( !isset( $validNamespaces[$key] ) ) {
  424. unset( $this->namespaceNames[$key] );
  425. }
  426. }
  427. # The above mixing may leave namespaces out of canonical order.
  428. # Re-order by namespace ID number...
  429. ksort( $this->namespaceNames );
  430. Hooks::run( 'LanguageGetNamespaces', [ &$this->namespaceNames ] );
  431. }
  432. return $this->namespaceNames;
  433. }
  434. /**
  435. * Arbitrarily set all of the namespace names at once. Mainly used for testing
  436. * @param array $namespaces Array of namespaces (id => name)
  437. */
  438. public function setNamespaces( array $namespaces ) {
  439. $this->namespaceNames = $namespaces;
  440. $this->mNamespaceIds = null;
  441. }
  442. /**
  443. * Resets all of the namespace caches. Mainly used for testing
  444. */
  445. public function resetNamespaces() {
  446. $this->namespaceNames = null;
  447. $this->mNamespaceIds = null;
  448. $this->namespaceAliases = null;
  449. }
  450. /**
  451. * A convenience function that returns getNamespaces() with spaces instead of underscores
  452. * in values. Useful for producing output to be displayed e.g. in `<select>` forms.
  453. *
  454. * @return array
  455. */
  456. public function getFormattedNamespaces() {
  457. $ns = $this->getNamespaces();
  458. foreach ( $ns as $k => $v ) {
  459. $ns[$k] = strtr( $v, '_', ' ' );
  460. }
  461. return $ns;
  462. }
  463. /**
  464. * Get a namespace value by key
  465. *
  466. * <code>
  467. * $mw_ns = $wgContLang->getNsText( NS_MEDIAWIKI );
  468. * echo $mw_ns; // prints 'MediaWiki'
  469. * </code>
  470. *
  471. * @param int $index The array key of the namespace to return
  472. * @return string|bool String if the namespace value exists, otherwise false
  473. */
  474. public function getNsText( $index ) {
  475. $ns = $this->getNamespaces();
  476. return isset( $ns[$index] ) ? $ns[$index] : false;
  477. }
  478. /**
  479. * A convenience function that returns the same thing as
  480. * getNsText() except with '_' changed to ' ', useful for
  481. * producing output.
  482. *
  483. * <code>
  484. * $mw_ns = $wgContLang->getFormattedNsText( NS_MEDIAWIKI_TALK );
  485. * echo $mw_ns; // prints 'MediaWiki talk'
  486. * </code>
  487. *
  488. * @param int $index The array key of the namespace to return
  489. * @return string Namespace name without underscores (empty string if namespace does not exist)
  490. */
  491. public function getFormattedNsText( $index ) {
  492. $ns = $this->getNsText( $index );
  493. return strtr( $ns, '_', ' ' );
  494. }
  495. /**
  496. * Returns gender-dependent namespace alias if available.
  497. * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
  498. * @param int $index Namespace index
  499. * @param string $gender Gender key (male, female... )
  500. * @return string
  501. * @since 1.18
  502. */
  503. public function getGenderNsText( $index, $gender ) {
  504. global $wgExtraGenderNamespaces;
  505. $ns = $wgExtraGenderNamespaces +
  506. (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
  507. return isset( $ns[$index][$gender] ) ? $ns[$index][$gender] : $this->getNsText( $index );
  508. }
  509. /**
  510. * Whether this language uses gender-dependent namespace aliases.
  511. * See https://www.mediawiki.org/wiki/Manual:$wgExtraGenderNamespaces
  512. * @return bool
  513. * @since 1.18
  514. */
  515. public function needsGenderDistinction() {
  516. global $wgExtraGenderNamespaces, $wgExtraNamespaces;
  517. if ( count( $wgExtraGenderNamespaces ) > 0 ) {
  518. // $wgExtraGenderNamespaces overrides everything
  519. return true;
  520. } elseif ( isset( $wgExtraNamespaces[NS_USER] ) && isset( $wgExtraNamespaces[NS_USER_TALK] ) ) {
  521. /// @todo There may be other gender namespace than NS_USER & NS_USER_TALK in the future
  522. // $wgExtraNamespaces overrides any gender aliases specified in i18n files
  523. return false;
  524. } else {
  525. // Check what is in i18n files
  526. $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
  527. return count( $aliases ) > 0;
  528. }
  529. }
  530. /**
  531. * Get a namespace key by value, case insensitive.
  532. * Only matches namespace names for the current language, not the
  533. * canonical ones defined in Namespace.php.
  534. *
  535. * @param string $text
  536. * @return int|bool An integer if $text is a valid value otherwise false
  537. */
  538. function getLocalNsIndex( $text ) {
  539. $lctext = $this->lc( $text );
  540. $ids = $this->getNamespaceIds();
  541. return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
  542. }
  543. /**
  544. * @return array
  545. */
  546. public function getNamespaceAliases() {
  547. if ( is_null( $this->namespaceAliases ) ) {
  548. $aliases = self::$dataCache->getItem( $this->mCode, 'namespaceAliases' );
  549. if ( !$aliases ) {
  550. $aliases = [];
  551. } else {
  552. foreach ( $aliases as $name => $index ) {
  553. if ( $index === NS_PROJECT_TALK ) {
  554. unset( $aliases[$name] );
  555. $name = $this->fixVariableInNamespace( $name );
  556. $aliases[$name] = $index;
  557. }
  558. }
  559. }
  560. global $wgExtraGenderNamespaces;
  561. $genders = $wgExtraGenderNamespaces +
  562. (array)self::$dataCache->getItem( $this->mCode, 'namespaceGenderAliases' );
  563. foreach ( $genders as $index => $forms ) {
  564. foreach ( $forms as $alias ) {
  565. $aliases[$alias] = $index;
  566. }
  567. }
  568. # Also add converted namespace names as aliases, to avoid confusion.
  569. $convertedNames = [];
  570. foreach ( $this->getVariants() as $variant ) {
  571. if ( $variant === $this->mCode ) {
  572. continue;
  573. }
  574. foreach ( $this->getNamespaces() as $ns => $_ ) {
  575. $convertedNames[$this->getConverter()->convertNamespace( $ns, $variant )] = $ns;
  576. }
  577. }
  578. $this->namespaceAliases = $aliases + $convertedNames;
  579. }
  580. return $this->namespaceAliases;
  581. }
  582. /**
  583. * @return array
  584. */
  585. public function getNamespaceIds() {
  586. if ( is_null( $this->mNamespaceIds ) ) {
  587. global $wgNamespaceAliases;
  588. # Put namespace names and aliases into a hashtable.
  589. # If this is too slow, then we should arrange it so that it is done
  590. # before caching. The catch is that at pre-cache time, the above
  591. # class-specific fixup hasn't been done.
  592. $this->mNamespaceIds = [];
  593. foreach ( $this->getNamespaces() as $index => $name ) {
  594. $this->mNamespaceIds[$this->lc( $name )] = $index;
  595. }
  596. foreach ( $this->getNamespaceAliases() as $name => $index ) {
  597. $this->mNamespaceIds[$this->lc( $name )] = $index;
  598. }
  599. if ( $wgNamespaceAliases ) {
  600. foreach ( $wgNamespaceAliases as $name => $index ) {
  601. $this->mNamespaceIds[$this->lc( $name )] = $index;
  602. }
  603. }
  604. }
  605. return $this->mNamespaceIds;
  606. }
  607. /**
  608. * Get a namespace key by value, case insensitive. Canonical namespace
  609. * names override custom ones defined for the current language.
  610. *
  611. * @param string $text
  612. * @return int|bool An integer if $text is a valid value otherwise false
  613. */
  614. public function getNsIndex( $text ) {
  615. $lctext = $this->lc( $text );
  616. $ns = MWNamespace::getCanonicalIndex( $lctext );
  617. if ( $ns !== null ) {
  618. return $ns;
  619. }
  620. $ids = $this->getNamespaceIds();
  621. return isset( $ids[$lctext] ) ? $ids[$lctext] : false;
  622. }
  623. /**
  624. * short names for language variants used for language conversion links.
  625. *
  626. * @param string $code
  627. * @param bool $usemsg Use the "variantname-xyz" message if it exists
  628. * @return string
  629. */
  630. public function getVariantname( $code, $usemsg = true ) {
  631. $msg = "variantname-$code";
  632. if ( $usemsg && wfMessage( $msg )->exists() ) {
  633. return $this->getMessageFromDB( $msg );
  634. }
  635. $name = self::fetchLanguageName( $code );
  636. if ( $name ) {
  637. return $name; # if it's defined as a language name, show that
  638. } else {
  639. # otherwise, output the language code
  640. return $code;
  641. }
  642. }
  643. /**
  644. * @return string[]|bool List of date format preference keys, or false if disabled.
  645. */
  646. public function getDatePreferences() {
  647. return self::$dataCache->getItem( $this->mCode, 'datePreferences' );
  648. }
  649. /**
  650. * @return array
  651. */
  652. function getDateFormats() {
  653. return self::$dataCache->getItem( $this->mCode, 'dateFormats' );
  654. }
  655. /**
  656. * @return array|string
  657. */
  658. public function getDefaultDateFormat() {
  659. $df = self::$dataCache->getItem( $this->mCode, 'defaultDateFormat' );
  660. if ( $df === 'dmy or mdy' ) {
  661. global $wgAmericanDates;
  662. return $wgAmericanDates ? 'mdy' : 'dmy';
  663. } else {
  664. return $df;
  665. }
  666. }
  667. /**
  668. * @return array
  669. */
  670. public function getDatePreferenceMigrationMap() {
  671. return self::$dataCache->getItem( $this->mCode, 'datePreferenceMigrationMap' );
  672. }
  673. /**
  674. * @param string $image
  675. * @return array|null
  676. */
  677. function getImageFile( $image ) {
  678. return self::$dataCache->getSubitem( $this->mCode, 'imageFiles', $image );
  679. }
  680. /**
  681. * @return array
  682. * @since 1.24
  683. */
  684. public function getImageFiles() {
  685. return self::$dataCache->getItem( $this->mCode, 'imageFiles' );
  686. }
  687. /**
  688. * @return array
  689. */
  690. public function getExtraUserToggles() {
  691. return (array)self::$dataCache->getItem( $this->mCode, 'extraUserToggles' );
  692. }
  693. /**
  694. * @param string $tog
  695. * @return string
  696. */
  697. function getUserToggle( $tog ) {
  698. return $this->getMessageFromDB( "tog-$tog" );
  699. }
  700. /**
  701. * Get an array of language names, indexed by code.
  702. * @param null|string $inLanguage Code of language in which to return the names
  703. * Use null for autonyms (native names)
  704. * @param string $include One of:
  705. * 'all' all available languages
  706. * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
  707. * 'mwfile' only if the language is in 'mw' *and* has a message file
  708. * @return array Language code => language name
  709. * @since 1.20
  710. */
  711. public static function fetchLanguageNames( $inLanguage = null, $include = 'mw' ) {
  712. $cacheKey = $inLanguage === null ? 'null' : $inLanguage;
  713. $cacheKey .= ":$include";
  714. if ( self::$languageNameCache === null ) {
  715. self::$languageNameCache = new HashBagOStuff( [ 'maxKeys' => 20 ] );
  716. }
  717. $ret = self::$languageNameCache->get( $cacheKey );
  718. if ( !$ret ) {
  719. $ret = self::fetchLanguageNamesUncached( $inLanguage, $include );
  720. self::$languageNameCache->set( $cacheKey, $ret );
  721. }
  722. return $ret;
  723. }
  724. /**
  725. * Uncached helper for fetchLanguageNames
  726. * @param null|string $inLanguage Code of language in which to return the names
  727. * Use null for autonyms (native names)
  728. * @param string $include One of:
  729. * 'all' all available languages
  730. * 'mw' only if the language is defined in MediaWiki or wgExtraLanguageNames (default)
  731. * 'mwfile' only if the language is in 'mw' *and* has a message file
  732. * @return array Language code => language name
  733. */
  734. private static function fetchLanguageNamesUncached( $inLanguage = null, $include = 'mw' ) {
  735. global $wgExtraLanguageNames, $wgUsePigLatinVariant;
  736. // If passed an invalid language code to use, fallback to en
  737. if ( $inLanguage !== null && !self::isValidCode( $inLanguage ) ) {
  738. $inLanguage = 'en';
  739. }
  740. $names = [];
  741. if ( $inLanguage ) {
  742. # TODO: also include when $inLanguage is null, when this code is more efficient
  743. Hooks::run( 'LanguageGetTranslatedLanguageNames', [ &$names, $inLanguage ] );
  744. }
  745. $mwNames = $wgExtraLanguageNames + MediaWiki\Languages\Data\Names::$names;
  746. if ( $wgUsePigLatinVariant ) {
  747. // Pig Latin (for variant development)
  748. $mwNames['en-x-piglatin'] = 'Igpay Atinlay';
  749. }
  750. foreach ( $mwNames as $mwCode => $mwName ) {
  751. # - Prefer own MediaWiki native name when not using the hook
  752. # - For other names just add if not added through the hook
  753. if ( $mwCode === $inLanguage || !isset( $names[$mwCode] ) ) {
  754. $names[$mwCode] = $mwName;
  755. }
  756. }
  757. if ( $include === 'all' ) {
  758. ksort( $names );
  759. return $names;
  760. }
  761. $returnMw = [];
  762. $coreCodes = array_keys( $mwNames );
  763. foreach ( $coreCodes as $coreCode ) {
  764. $returnMw[$coreCode] = $names[$coreCode];
  765. }
  766. if ( $include === 'mwfile' ) {
  767. $namesMwFile = [];
  768. # We do this using a foreach over the codes instead of a directory
  769. # loop so that messages files in extensions will work correctly.
  770. foreach ( $returnMw as $code => $value ) {
  771. if ( is_readable( self::getMessagesFileName( $code ) )
  772. || is_readable( self::getJsonMessagesFileName( $code ) )
  773. ) {
  774. $namesMwFile[$code] = $names[$code];
  775. }
  776. }
  777. ksort( $namesMwFile );
  778. return $namesMwFile;
  779. }
  780. ksort( $returnMw );
  781. # 'mw' option; default if it's not one of the other two options (all/mwfile)
  782. return $returnMw;
  783. }
  784. /**
  785. * @param string $code The code of the language for which to get the name
  786. * @param null|string $inLanguage Code of language in which to return the name (null for autonyms)
  787. * @param string $include 'all', 'mw' or 'mwfile'; see fetchLanguageNames()
  788. * @return string Language name or empty
  789. * @since 1.20
  790. */
  791. public static function fetchLanguageName( $code, $inLanguage = null, $include = 'all' ) {
  792. $code = strtolower( $code );
  793. $array = self::fetchLanguageNames( $inLanguage, $include );
  794. return !array_key_exists( $code, $array ) ? '' : $array[$code];
  795. }
  796. /**
  797. * Get a message from the MediaWiki namespace.
  798. *
  799. * @param string $msg Message name
  800. * @return string
  801. */
  802. public function getMessageFromDB( $msg ) {
  803. return $this->msg( $msg )->text();
  804. }
  805. /**
  806. * Get message object in this language. Only for use inside this class.
  807. *
  808. * @param string $msg Message name
  809. * @return Message
  810. */
  811. protected function msg( $msg ) {
  812. return wfMessage( $msg )->inLanguage( $this );
  813. }
  814. /**
  815. * @param string $key
  816. * @return string
  817. */
  818. public function getMonthName( $key ) {
  819. return $this->getMessageFromDB( self::$mMonthMsgs[$key - 1] );
  820. }
  821. /**
  822. * @return array
  823. */
  824. public function getMonthNamesArray() {
  825. $monthNames = [ '' ];
  826. for ( $i = 1; $i < 13; $i++ ) {
  827. $monthNames[] = $this->getMonthName( $i );
  828. }
  829. return $monthNames;
  830. }
  831. /**
  832. * @param string $key
  833. * @return string
  834. */
  835. public function getMonthNameGen( $key ) {
  836. return $this->getMessageFromDB( self::$mMonthGenMsgs[$key - 1] );
  837. }
  838. /**
  839. * @param string $key
  840. * @return string
  841. */
  842. public function getMonthAbbreviation( $key ) {
  843. return $this->getMessageFromDB( self::$mMonthAbbrevMsgs[$key - 1] );
  844. }
  845. /**
  846. * @return array
  847. */
  848. public function getMonthAbbreviationsArray() {
  849. $monthNames = [ '' ];
  850. for ( $i = 1; $i < 13; $i++ ) {
  851. $monthNames[] = $this->getMonthAbbreviation( $i );
  852. }
  853. return $monthNames;
  854. }
  855. /**
  856. * @param string $key
  857. * @return string
  858. */
  859. public function getWeekdayName( $key ) {
  860. return $this->getMessageFromDB( self::$mWeekdayMsgs[$key - 1] );
  861. }
  862. /**
  863. * @param string $key
  864. * @return string
  865. */
  866. function getWeekdayAbbreviation( $key ) {
  867. return $this->getMessageFromDB( self::$mWeekdayAbbrevMsgs[$key - 1] );
  868. }
  869. /**
  870. * @param string $key
  871. * @return string
  872. */
  873. function getIranianCalendarMonthName( $key ) {
  874. return $this->getMessageFromDB( self::$mIranianCalendarMonthMsgs[$key - 1] );
  875. }
  876. /**
  877. * @param string $key
  878. * @return string
  879. */
  880. function getHebrewCalendarMonthName( $key ) {
  881. return $this->getMessageFromDB( self::$mHebrewCalendarMonthMsgs[$key - 1] );
  882. }
  883. /**
  884. * @param string $key
  885. * @return string
  886. */
  887. function getHebrewCalendarMonthNameGen( $key ) {
  888. return $this->getMessageFromDB( self::$mHebrewCalendarMonthGenMsgs[$key - 1] );
  889. }
  890. /**
  891. * @param string $key
  892. * @return string
  893. */
  894. function getHijriCalendarMonthName( $key ) {
  895. return $this->getMessageFromDB( self::$mHijriCalendarMonthMsgs[$key - 1] );
  896. }
  897. /**
  898. * Pass through result from $dateTimeObj->format()
  899. * @param DateTime|bool|null &$dateTimeObj
  900. * @param string $ts
  901. * @param DateTimeZone|bool|null $zone
  902. * @param string $code
  903. * @return string
  904. */
  905. private static function dateTimeObjFormat( &$dateTimeObj, $ts, $zone, $code ) {
  906. if ( !$dateTimeObj ) {
  907. $dateTimeObj = DateTime::createFromFormat(
  908. 'YmdHis', $ts, $zone ?: new DateTimeZone( 'UTC' )
  909. );
  910. }
  911. return $dateTimeObj->format( $code );
  912. }
  913. /**
  914. * This is a workalike of PHP's date() function, but with better
  915. * internationalisation, a reduced set of format characters, and a better
  916. * escaping format.
  917. *
  918. * Supported format characters are dDjlNwzWFmMntLoYyaAgGhHiscrUeIOPTZ. See
  919. * the PHP manual for definitions. There are a number of extensions, which
  920. * start with "x":
  921. *
  922. * xn Do not translate digits of the next numeric format character
  923. * xN Toggle raw digit (xn) flag, stays set until explicitly unset
  924. * xr Use roman numerals for the next numeric format character
  925. * xh Use hebrew numerals for the next numeric format character
  926. * xx Literal x
  927. * xg Genitive month name
  928. *
  929. * xij j (day number) in Iranian calendar
  930. * xiF F (month name) in Iranian calendar
  931. * xin n (month number) in Iranian calendar
  932. * xiy y (two digit year) in Iranian calendar
  933. * xiY Y (full year) in Iranian calendar
  934. * xit t (days in month) in Iranian calendar
  935. * xiz z (day of the year) in Iranian calendar
  936. *
  937. * xjj j (day number) in Hebrew calendar
  938. * xjF F (month name) in Hebrew calendar
  939. * xjt t (days in month) in Hebrew calendar
  940. * xjx xg (genitive month name) in Hebrew calendar
  941. * xjn n (month number) in Hebrew calendar
  942. * xjY Y (full year) in Hebrew calendar
  943. *
  944. * xmj j (day number) in Hijri calendar
  945. * xmF F (month name) in Hijri calendar
  946. * xmn n (month number) in Hijri calendar
  947. * xmY Y (full year) in Hijri calendar
  948. *
  949. * xkY Y (full year) in Thai solar calendar. Months and days are
  950. * identical to the Gregorian calendar
  951. * xoY Y (full year) in Minguo calendar or Juche year.
  952. * Months and days are identical to the
  953. * Gregorian calendar
  954. * xtY Y (full year) in Japanese nengo. Months and days are
  955. * identical to the Gregorian calendar
  956. *
  957. * Characters enclosed in double quotes will be considered literal (with
  958. * the quotes themselves removed). Unmatched quotes will be considered
  959. * literal quotes. Example:
  960. *
  961. * "The month is" F => The month is January
  962. * i's" => 20'11"
  963. *
  964. * Backslash escaping is also supported.
  965. *
  966. * Input timestamp is assumed to be pre-normalized to the desired local
  967. * time zone, if any. Note that the format characters crUeIOPTZ will assume
  968. * $ts is UTC if $zone is not given.
  969. *
  970. * @param string $format
  971. * @param string $ts 14-character timestamp
  972. * YYYYMMDDHHMMSS
  973. * 01234567890123
  974. * @param DateTimeZone $zone Timezone of $ts
  975. * @param int &$ttl The amount of time (in seconds) the output may be cached for.
  976. * Only makes sense if $ts is the current time.
  977. * @todo handling of "o" format character for Iranian, Hebrew, Hijri & Thai?
  978. *
  979. * @throws MWException
  980. * @return string
  981. */
  982. public function sprintfDate( $format, $ts, DateTimeZone $zone = null, &$ttl = 'unused' ) {
  983. $s = '';
  984. $raw = false;
  985. $roman = false;
  986. $hebrewNum = false;
  987. $dateTimeObj = false;
  988. $rawToggle = false;
  989. $iranian = false;
  990. $hebrew = false;
  991. $hijri = false;
  992. $thai = false;
  993. $minguo = false;
  994. $tenno = false;
  995. $usedSecond = false;
  996. $usedMinute = false;
  997. $usedHour = false;
  998. $usedAMPM = false;
  999. $usedDay = false;
  1000. $usedWeek = false;
  1001. $usedMonth = false;
  1002. $usedYear = false;
  1003. $usedISOYear = false;
  1004. $usedIsLeapYear = false;
  1005. $usedHebrewMonth = false;
  1006. $usedIranianMonth = false;
  1007. $usedHijriMonth = false;
  1008. $usedHebrewYear = false;
  1009. $usedIranianYear = false;
  1010. $usedHijriYear = false;
  1011. $usedTennoYear = false;
  1012. if ( strlen( $ts ) !== 14 ) {
  1013. throw new MWException( __METHOD__ . ": The timestamp $ts should have 14 characters" );
  1014. }
  1015. if ( !ctype_digit( $ts ) ) {
  1016. throw new MWException( __METHOD__ . ": The timestamp $ts should be a number" );
  1017. }
  1018. $formatLength = strlen( $format );
  1019. for ( $p = 0; $p < $formatLength; $p++ ) {
  1020. $num = false;
  1021. $code = $format[$p];
  1022. if ( $code == 'x' && $p < $formatLength - 1 ) {
  1023. $code .= $format[++$p];
  1024. }
  1025. if ( ( $code === 'xi'
  1026. || $code === 'xj'
  1027. || $code === 'xk'
  1028. || $code === 'xm'
  1029. || $code === 'xo'
  1030. || $code === 'xt' )
  1031. && $p < $formatLength - 1 ) {
  1032. $code .= $format[++$p];
  1033. }
  1034. switch ( $code ) {
  1035. case 'xx':
  1036. $s .= 'x';
  1037. break;
  1038. case 'xn':
  1039. $raw = true;
  1040. break;
  1041. case 'xN':
  1042. $rawToggle = !$rawToggle;
  1043. break;
  1044. case 'xr':
  1045. $roman = true;
  1046. break;
  1047. case 'xh':
  1048. $hebrewNum = true;
  1049. break;
  1050. case 'xg':
  1051. $usedMonth = true;
  1052. $s .= $this->getMonthNameGen( substr( $ts, 4, 2 ) );
  1053. break;
  1054. case 'xjx':
  1055. $usedHebrewMonth = true;
  1056. if ( !$hebrew ) {
  1057. $hebrew = self::tsToHebrew( $ts );
  1058. }
  1059. $s .= $this->getHebrewCalendarMonthNameGen( $hebrew[1] );
  1060. break;
  1061. case 'd':
  1062. $usedDay = true;
  1063. $num = substr( $ts, 6, 2 );
  1064. break;
  1065. case 'D':
  1066. $usedDay = true;
  1067. $s .= $this->getWeekdayAbbreviation(
  1068. self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
  1069. );
  1070. break;
  1071. case 'j':
  1072. $usedDay = true;
  1073. $num = intval( substr( $ts, 6, 2 ) );
  1074. break;
  1075. case 'xij':
  1076. $usedDay = true;
  1077. if ( !$iranian ) {
  1078. $iranian = self::tsToIranian( $ts );
  1079. }
  1080. $num = $iranian[2];
  1081. break;
  1082. case 'xmj':
  1083. $usedDay = true;
  1084. if ( !$hijri ) {
  1085. $hijri = self::tsToHijri( $ts );
  1086. }
  1087. $num = $hijri[2];
  1088. break;
  1089. case 'xjj':
  1090. $usedDay = true;
  1091. if ( !$hebrew ) {
  1092. $hebrew = self::tsToHebrew( $ts );
  1093. }
  1094. $num = $hebrew[2];
  1095. break;
  1096. case 'l':
  1097. $usedDay = true;
  1098. $s .= $this->getWeekdayName(
  1099. self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'w' ) + 1
  1100. );
  1101. break;
  1102. case 'F':
  1103. $usedMonth = true;
  1104. $s .= $this->getMonthName( substr( $ts, 4, 2 ) );
  1105. break;
  1106. case 'xiF':
  1107. $usedIranianMonth = true;
  1108. if ( !$iranian ) {
  1109. $iranian = self::tsToIranian( $ts );
  1110. }
  1111. $s .= $this->getIranianCalendarMonthName( $iranian[1] );
  1112. break;
  1113. case 'xmF':
  1114. $usedHijriMonth = true;
  1115. if ( !$hijri ) {
  1116. $hijri = self::tsToHijri( $ts );
  1117. }
  1118. $s .= $this->getHijriCalendarMonthName( $hijri[1] );
  1119. break;
  1120. case 'xjF':
  1121. $usedHebrewMonth = true;
  1122. if ( !$hebrew ) {
  1123. $hebrew = self::tsToHebrew( $ts );
  1124. }
  1125. $s .= $this->getHebrewCalendarMonthName( $hebrew[1] );
  1126. break;
  1127. case 'm':
  1128. $usedMonth = true;
  1129. $num = substr( $ts, 4, 2 );
  1130. break;
  1131. case 'M':
  1132. $usedMonth = true;
  1133. $s .= $this->getMonthAbbreviation( substr( $ts, 4, 2 ) );
  1134. break;
  1135. case 'n':
  1136. $usedMonth = true;
  1137. $num = intval( substr( $ts, 4, 2 ) );
  1138. break;
  1139. case 'xin':
  1140. $usedIranianMonth = true;
  1141. if ( !$iranian ) {
  1142. $iranian = self::tsToIranian( $ts );
  1143. }
  1144. $num = $iranian[1];
  1145. break;
  1146. case 'xmn':
  1147. $usedHijriMonth = true;
  1148. if ( !$hijri ) {
  1149. $hijri = self::tsToHijri( $ts );
  1150. }
  1151. $num = $hijri[1];
  1152. break;
  1153. case 'xjn':
  1154. $usedHebrewMonth = true;
  1155. if ( !$hebrew ) {
  1156. $hebrew = self::tsToHebrew( $ts );
  1157. }
  1158. $num = $hebrew[1];
  1159. break;
  1160. case 'xjt':
  1161. $usedHebrewMonth = true;
  1162. if ( !$hebrew ) {
  1163. $hebrew = self::tsToHebrew( $ts );
  1164. }
  1165. $num = $hebrew[3];
  1166. break;
  1167. case 'Y':
  1168. $usedYear = true;
  1169. $num = substr( $ts, 0, 4 );
  1170. break;
  1171. case 'xiY':
  1172. $usedIranianYear = true;
  1173. if ( !$iranian ) {
  1174. $iranian = self::tsToIranian( $ts );
  1175. }
  1176. $num = $iranian[0];
  1177. break;
  1178. case 'xmY':
  1179. $usedHijriYear = true;
  1180. if ( !$hijri ) {
  1181. $hijri = self::tsToHijri( $ts );
  1182. }
  1183. $num = $hijri[0];
  1184. break;
  1185. case 'xjY':
  1186. $usedHebrewYear = true;
  1187. if ( !$hebrew ) {
  1188. $hebrew = self::tsToHebrew( $ts );
  1189. }
  1190. $num = $hebrew[0];
  1191. break;
  1192. case 'xkY':
  1193. $usedYear = true;
  1194. if ( !$thai ) {
  1195. $thai = self::tsToYear( $ts, 'thai' );
  1196. }
  1197. $num = $thai[0];
  1198. break;
  1199. case 'xoY':
  1200. $usedYear = true;
  1201. if ( !$minguo ) {
  1202. $minguo = self::tsToYear( $ts, 'minguo' );
  1203. }
  1204. $num = $minguo[0];
  1205. break;
  1206. case 'xtY':
  1207. $usedTennoYear = true;
  1208. if ( !$tenno ) {
  1209. $tenno = self::tsToYear( $ts, 'tenno' );
  1210. }
  1211. $num = $tenno[0];
  1212. break;
  1213. case 'y':
  1214. $usedYear = true;
  1215. $num = substr( $ts, 2, 2 );
  1216. break;
  1217. case 'xiy':
  1218. $usedIranianYear = true;
  1219. if ( !$iranian ) {
  1220. $iranian = self::tsToIranian( $ts );
  1221. }
  1222. $num = substr( $iranian[0], -2 );
  1223. break;
  1224. case 'xit':
  1225. $usedIranianYear = true;
  1226. if ( !$iranian ) {
  1227. $iranian = self::tsToIranian( $ts );
  1228. }
  1229. $num = self::$IRANIAN_DAYS[$iranian[1] - 1];
  1230. break;
  1231. case 'xiz':
  1232. $usedIranianYear = true;
  1233. if ( !$iranian ) {
  1234. $iranian = self::tsToIranian( $ts );
  1235. }
  1236. $num = $iranian[3];
  1237. break;
  1238. case 'a':
  1239. $usedAMPM = true;
  1240. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'am' : 'pm';
  1241. break;
  1242. case 'A':
  1243. $usedAMPM = true;
  1244. $s .= intval( substr( $ts, 8, 2 ) ) < 12 ? 'AM' : 'PM';
  1245. break;
  1246. case 'g':
  1247. $usedHour = true;
  1248. $h = substr( $ts, 8, 2 );
  1249. $num = $h % 12 ? $h % 12 : 12;
  1250. break;
  1251. case 'G':
  1252. $usedHour = true;
  1253. $num = intval( substr( $ts, 8, 2 ) );
  1254. break;
  1255. case 'h':
  1256. $usedHour = true;
  1257. $h = substr( $ts, 8, 2 );
  1258. $num = sprintf( '%02d', $h % 12 ? $h % 12 : 12 );
  1259. break;
  1260. case 'H':
  1261. $usedHour = true;
  1262. $num = substr( $ts, 8, 2 );
  1263. break;
  1264. case 'i':
  1265. $usedMinute = true;
  1266. $num = substr( $ts, 10, 2 );
  1267. break;
  1268. case 's':
  1269. $usedSecond = true;
  1270. $num = substr( $ts, 12, 2 );
  1271. break;
  1272. case 'c':
  1273. case 'r':
  1274. $usedSecond = true;
  1275. // fall through
  1276. case 'e':
  1277. case 'O':
  1278. case 'P':
  1279. case 'T':
  1280. $s .= self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1281. break;
  1282. case 'w':
  1283. case 'N':
  1284. case 'z':
  1285. $usedDay = true;
  1286. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1287. break;
  1288. case 'W':
  1289. $usedWeek = true;
  1290. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1291. break;
  1292. case 't':
  1293. $usedMonth = true;
  1294. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1295. break;
  1296. case 'L':
  1297. $usedIsLeapYear = true;
  1298. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1299. break;
  1300. case 'o':
  1301. $usedISOYear = true;
  1302. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1303. break;
  1304. case 'U':
  1305. $usedSecond = true;
  1306. // fall through
  1307. case 'I':
  1308. case 'Z':
  1309. $num = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, $code );
  1310. break;
  1311. case '\\':
  1312. # Backslash escaping
  1313. if ( $p < $formatLength - 1 ) {
  1314. $s .= $format[++$p];
  1315. } else {
  1316. $s .= '\\';
  1317. }
  1318. break;
  1319. case '"':
  1320. # Quoted literal
  1321. if ( $p < $formatLength - 1 ) {
  1322. $endQuote = strpos( $format, '"', $p + 1 );
  1323. if ( $endQuote === false ) {
  1324. # No terminating quote, assume literal "
  1325. $s .= '"';
  1326. } else {
  1327. $s .= substr( $format, $p + 1, $endQuote - $p - 1 );
  1328. $p = $endQuote;
  1329. }
  1330. } else {
  1331. # Quote at end of string, assume literal "
  1332. $s .= '"';
  1333. }
  1334. break;
  1335. default:
  1336. $s .= $format[$p];
  1337. }
  1338. if ( $num !== false ) {
  1339. if ( $rawToggle || $raw ) {
  1340. $s .= $num;
  1341. $raw = false;
  1342. } elseif ( $roman ) {
  1343. $s .= self::romanNumeral( $num );
  1344. $roman = false;
  1345. } elseif ( $hebrewNum ) {
  1346. $s .= self::hebrewNumeral( $num );
  1347. $hebrewNum = false;
  1348. } else {
  1349. $s .= $this->formatNum( $num, true );
  1350. }
  1351. }
  1352. }
  1353. if ( $ttl === 'unused' ) {
  1354. // No need to calculate the TTL, the caller wont use it anyway.
  1355. } elseif ( $usedSecond ) {
  1356. $ttl = 1;
  1357. } elseif ( $usedMinute ) {
  1358. $ttl = 60 - substr( $ts, 12, 2 );
  1359. } elseif ( $usedHour ) {
  1360. $ttl = 3600 - substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
  1361. } elseif ( $usedAMPM ) {
  1362. $ttl = 43200 - ( substr( $ts, 8, 2 ) % 12 ) * 3600 -
  1363. substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
  1364. } elseif (
  1365. $usedDay ||
  1366. $usedHebrewMonth ||
  1367. $usedIranianMonth ||
  1368. $usedHijriMonth ||
  1369. $usedHebrewYear ||
  1370. $usedIranianYear ||
  1371. $usedHijriYear ||
  1372. $usedTennoYear
  1373. ) {
  1374. // @todo Someone who understands the non-Gregorian calendars
  1375. // should write proper logic for them so that they don't need purged every day.
  1376. $ttl = 86400 - substr( $ts, 8, 2 ) * 3600 -
  1377. substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
  1378. } else {
  1379. $possibleTtls = [];
  1380. $timeRemainingInDay = 86400 - substr( $ts, 8, 2 ) * 3600 -
  1381. substr( $ts, 10, 2 ) * 60 - substr( $ts, 12, 2 );
  1382. if ( $usedWeek ) {
  1383. $possibleTtls[] =
  1384. ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400 +
  1385. $timeRemainingInDay;
  1386. } elseif ( $usedISOYear ) {
  1387. // December 28th falls on the last ISO week of the year, every year.
  1388. // The last ISO week of a year can be 52 or 53.
  1389. $lastWeekOfISOYear = DateTime::createFromFormat(
  1390. 'Ymd',
  1391. substr( $ts, 0, 4 ) . '1228',
  1392. $zone ?: new DateTimeZone( 'UTC' )
  1393. )->format( 'W' );
  1394. $currentISOWeek = self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'W' );
  1395. $weeksRemaining = $lastWeekOfISOYear - $currentISOWeek;
  1396. $timeRemainingInWeek =
  1397. ( 7 - self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'N' ) ) * 86400
  1398. + $timeRemainingInDay;
  1399. $possibleTtls[] = $weeksRemaining * 604800 + $timeRemainingInWeek;
  1400. }
  1401. if ( $usedMonth ) {
  1402. $possibleTtls[] =
  1403. ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 't' ) -
  1404. substr( $ts, 6, 2 ) ) * 86400
  1405. + $timeRemainingInDay;
  1406. } elseif ( $usedYear ) {
  1407. $possibleTtls[] =
  1408. ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
  1409. self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
  1410. + $timeRemainingInDay;
  1411. } elseif ( $usedIsLeapYear ) {
  1412. $year = substr( $ts, 0, 4 );
  1413. $timeRemainingInYear =
  1414. ( self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'L' ) + 364 -
  1415. self::dateTimeObjFormat( $dateTimeObj, $ts, $zone, 'z' ) ) * 86400
  1416. + $timeRemainingInDay;
  1417. $mod = $year % 4;
  1418. if ( $mod || ( !( $year % 100 ) && $year % 400 ) ) {
  1419. // this isn't a leap year. see when the next one starts
  1420. $nextCandidate = $year - $mod + 4;
  1421. if ( $nextCandidate % 100 || !( $nextCandidate % 400 ) ) {
  1422. $possibleTtls[] = ( $nextCandidate - $year - 1 ) * 365 * 86400 +
  1423. $timeRemainingInYear;
  1424. } else {
  1425. $possibleTtls[] = ( $nextCandidate - $year + 3 ) * 365 * 86400 +
  1426. $timeRemainingInYear;
  1427. }
  1428. } else {
  1429. // this is a leap year, so the next year isn't
  1430. $possibleTtls[] = $timeRemainingInYear;
  1431. }
  1432. }
  1433. if ( $possibleTtls ) {
  1434. $ttl = min( $possibleTtls );
  1435. }
  1436. }
  1437. return $s;
  1438. }
  1439. private static $GREG_DAYS = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
  1440. private static $IRANIAN_DAYS = [ 31, 31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 29 ];
  1441. /**
  1442. * Algorithm by Roozbeh Pournader and Mohammad Toossi to convert
  1443. * Gregorian dates to Iranian dates. Originally written in C, it
  1444. * is released under the terms of GNU Lesser General Public
  1445. * License. Conversion to PHP was performed by Niklas Laxström.
  1446. *
  1447. * Link: http://www.farsiweb.info/jalali/jalali.c
  1448. *
  1449. * @param string $ts
  1450. *
  1451. * @return int[]
  1452. */
  1453. private static function tsToIranian( $ts ) {
  1454. $gy = substr( $ts, 0, 4 ) - 1600;
  1455. $gm = substr( $ts, 4, 2 ) - 1;
  1456. $gd = substr( $ts, 6, 2 ) - 1;
  1457. # Days passed from the beginning (including leap years)
  1458. $gDayNo = 365 * $gy
  1459. + floor( ( $gy + 3 ) / 4 )
  1460. - floor( ( $gy + 99 ) / 100 )
  1461. + floor( ( $gy + 399 ) / 400 );
  1462. // Add days of the past months of this year
  1463. for ( $i = 0; $i < $gm; $i++ ) {
  1464. $gDayNo += self::$GREG_DAYS[$i];
  1465. }
  1466. // Leap years
  1467. if ( $gm > 1 && ( ( $gy % 4 === 0 && $gy % 100 !== 0 || ( $gy % 400 == 0 ) ) ) ) {
  1468. $gDayNo++;
  1469. }
  1470. // Days passed in current month
  1471. $gDayNo += (int)$gd;
  1472. $jDayNo = $gDayNo - 79;
  1473. $jNp = floor( $jDayNo / 12053 );
  1474. $jDayNo %= 12053;
  1475. $jy = 979 + 33 * $jNp + 4 * floor( $jDayNo / 1461 );
  1476. $jDayNo %= 1461;
  1477. if ( $jDayNo >= 366 ) {
  1478. $jy += floor( ( $jDayNo - 1 ) / 365 );
  1479. $jDayNo = floor( ( $jDayNo - 1 ) % 365 );
  1480. }
  1481. $jz = $jDayNo;
  1482. for ( $i = 0; $i < 11 && $jDayNo >= self::$IRANIAN_DAYS[$i]; $i++ ) {
  1483. $jDayNo -= self::$IRANIAN_DAYS[$i];
  1484. }
  1485. $jm = $i + 1;
  1486. $jd = $jDayNo + 1;
  1487. return [ $jy, $jm, $jd, $jz ];
  1488. }
  1489. /**
  1490. * Converting Gregorian dates to Hijri dates.
  1491. *
  1492. * Based on a PHP-Nuke block by Sharjeel which is released under GNU/GPL license
  1493. *
  1494. * @see https://phpnuke.org/modules.php?name=News&file=article&sid=8234&mode=thread&order=0&thold=0
  1495. *
  1496. * @param string $ts
  1497. *
  1498. * @return int[]
  1499. */
  1500. private static function tsToHijri( $ts ) {
  1501. $year = substr( $ts, 0, 4 );
  1502. $month = substr( $ts, 4, 2 );
  1503. $day = substr( $ts, 6, 2 );
  1504. $zyr = $year;
  1505. $zd = $day;
  1506. $zm = $month;
  1507. $zy = $zyr;
  1508. if (
  1509. ( $zy > 1582 ) || ( ( $zy == 1582 ) && ( $zm > 10 ) ) ||
  1510. ( ( $zy == 1582 ) && ( $zm == 10 ) && ( $zd > 14 ) )
  1511. ) {
  1512. $zjd = (int)( ( 1461 * ( $zy + 4800 + (int)( ( $zm - 14 ) / 12 ) ) ) / 4 ) +
  1513. (int)( ( 367 * ( $zm - 2 - 12 * ( (int)( ( $zm - 14 ) / 12 ) ) ) ) / 12 ) -
  1514. (int)( ( 3 * (int)( ( ( $zy + 4900 + (int)( ( $zm - 14 ) / 12 ) ) / 100 ) ) ) / 4 ) +
  1515. $zd - 32075;
  1516. } else {
  1517. $zjd = 367 * $zy - (int)( ( 7 * ( $zy + 5001 + (int)( ( $zm - 9 ) / 7 ) ) ) / 4 ) +
  1518. (int)( ( 275 * $zm ) / 9 ) + $zd + 1729777;
  1519. }
  1520. $zl = $zjd - 1948440 + 10632;
  1521. $zn = (int)( ( $zl - 1 ) / 10631 );
  1522. $zl = $zl - 10631 * $zn + 354;
  1523. $zj = ( (int)( ( 10985 - $zl ) / 5316 ) ) * ( (int)( ( 50 * $zl ) / 17719 ) ) +
  1524. ( (int)( $zl / 5670 ) ) * ( (int)( ( 43 * $zl ) / 15238 ) );
  1525. $zl = $zl - ( (int)( ( 30 - $zj ) / 15 ) ) * ( (int)( ( 17719 * $zj ) / 50 ) ) -
  1526. ( (int)( $zj / 16 ) ) * ( (int)( ( 15238 * $zj ) / 43 ) ) + 29;
  1527. $zm = (int)( ( 24 * $zl ) / 709 );
  1528. $zd = $zl - (int)( ( 709 * $zm ) / 24 );
  1529. $zy = 30 * $zn + $zj - 30;
  1530. return [ $zy, $zm, $zd ];
  1531. }
  1532. /**
  1533. * Converting Gregorian dates to Hebrew dates.
  1534. *
  1535. * Based on a JavaScript code by Abu Mami and Yisrael Hersch
  1536. * (abu-mami@kaluach.net, http://www.kaluach.net), who permitted
  1537. * to translate the relevant functions into PHP and release them under
  1538. * GNU GPL.
  1539. *
  1540. * The months are counted from Tishrei = 1. In a leap year, Adar I is 13
  1541. * and Adar II is 14. In a non-leap year, Adar is 6.
  1542. *
  1543. * @param string $ts
  1544. *
  1545. * @return int[]
  1546. */
  1547. private static function tsToHebrew( $ts ) {
  1548. # Parse date
  1549. $year = substr( $ts, 0, 4 );
  1550. $month = substr( $ts, 4, 2 );
  1551. $day = substr( $ts, 6, 2 );
  1552. # Calculate Hebrew year
  1553. $hebrewYear = $year + 3760;
  1554. # Month number when September = 1, August = 12
  1555. $month += 4;
  1556. if ( $month > 12 ) {
  1557. # Next year
  1558. $month -= 12;
  1559. $year++;
  1560. $hebrewYear++;
  1561. }
  1562. # Calculate day of year from 1 September
  1563. $dayOfYear = $day;
  1564. for ( $i = 1; $i < $month; $i++ ) {
  1565. if ( $i == 6 ) {
  1566. # February
  1567. $dayOfYear += 28;
  1568. # Check if the year is leap
  1569. if ( $year % 400 == 0 || ( $year % 4 == 0 && $year % 100 > 0 ) ) {
  1570. $dayOfYear++;
  1571. }
  1572. } elseif ( $i == 8 || $i == 10 || $i == 1 || $i == 3 ) {
  1573. $dayOfYear += 30;
  1574. } else {
  1575. $dayOfYear += 31;
  1576. }
  1577. }
  1578. # Calculate the start of the Hebrew year
  1579. $start = self::hebrewYearStart( $hebrewYear );
  1580. # Calculate next year's start
  1581. if ( $dayOfYear <= $start ) {
  1582. # Day is before the start of the year - it is the previous year
  1583. # Next year's start
  1584. $nextStart = $start;
  1585. # Previous year
  1586. $year--;
  1587. $hebrewYear--;
  1588. # Add days since previous year's 1 September
  1589. $dayOfYear += 365;
  1590. if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  1591. # Leap year
  1592. $dayOfYear++;
  1593. }
  1594. # Start of the new (previous) year
  1595. $start = self::hebrewYearStart( $hebrewYear );
  1596. } else {
  1597. # Next year's start
  1598. $nextStart = self::hebrewYearStart( $hebrewYear + 1 );
  1599. }
  1600. # Calculate Hebrew day of year
  1601. $hebrewDayOfYear = $dayOfYear - $start;
  1602. # Difference between year's days
  1603. $diff = $nextStart - $start;
  1604. # Add 12 (or 13 for leap years) days to ignore the difference between
  1605. # Hebrew and Gregorian year (353 at least vs. 365/6) - now the
  1606. # difference is only about the year type
  1607. if ( ( $year % 400 == 0 ) || ( $year % 100 != 0 && $year % 4 == 0 ) ) {
  1608. $diff += 13;
  1609. } else {
  1610. $diff += 12;
  1611. }
  1612. # Check the year pattern, and is leap year
  1613. # 0 means an incomplete year, 1 means a regular year, 2 means a complete year
  1614. # This is mod 30, to work on both leap years (which add 30 days of Adar I)
  1615. # and non-leap years
  1616. $yearPattern = $diff % 30;
  1617. # Check if leap year
  1618. $isLeap = $diff >= 30;
  1619. # Calculate day in the month from number of day in the Hebrew year
  1620. # Don't check Adar - if the day is not in Adar, we will stop before;
  1621. # if it is in Adar, we will use it to check if it is Adar I or Adar II
  1622. $hebrewDay = $hebrewDayOfYear;
  1623. $hebrewMonth = 1;
  1624. $days = 0;
  1625. while ( $hebrewMonth <= 12 ) {
  1626. # Calculate days in this month
  1627. if ( $isLeap && $hebrewMonth == 6 ) {
  1628. # Adar in a leap year
  1629. if ( $isLeap ) {
  1630. # Leap year - has Adar I, with 30 days, and Adar II, with 29 days
  1631. $days = 30;
  1632. if ( $hebrewDay <= $days ) {
  1633. # Day in Adar I
  1634. $hebrewMonth = 13;
  1635. } else {
  1636. # Subtract the days of Adar I
  1637. $hebrewDay -= $days;
  1638. # Try Adar II
  1639. $days = 29;
  1640. if ( $hebrewDay <= $days ) {
  1641. # Day in Adar II
  1642. $hebrewMonth = 14;
  1643. }
  1644. }
  1645. }
  1646. } elseif ( $hebrewMonth == 2 && $yearPattern == 2 ) {
  1647. # Cheshvan in a complete year (otherwise as the rule below)
  1648. $days = 30;
  1649. } elseif ( $hebrewMonth == 3 && $yearPattern == 0 ) {
  1650. # Kislev in an incomplete year (otherwise as the rule below)
  1651. $days = 29;
  1652. } else {
  1653. # Odd months have 30 days, even have 29
  1654. $days = 30 - ( $hebrewMonth - 1 ) % 2;
  1655. }
  1656. if ( $hebrewDay <= $days ) {
  1657. # In the current month
  1658. break;
  1659. } else {
  1660. # Subtract the days of the current month
  1661. $hebrewDay -= $days;
  1662. # Try in the next month
  1663. $hebrewMonth++;
  1664. }
  1665. }
  1666. return [ $hebrewYear, $hebrewMonth, $hebrewDay, $days ];
  1667. }
  1668. /**
  1669. * This calculates the Hebrew year start, as days since 1 September.
  1670. * Based on Carl Friedrich Gauss algorithm for finding Easter date.
  1671. * Used for Hebrew date.
  1672. *
  1673. * @param int $year
  1674. *
  1675. * @return string
  1676. */
  1677. private static function hebrewYearStart( $year ) {
  1678. $a = intval( ( 12 * ( $year - 1 ) + 17 ) % 19 );
  1679. $b = intval( ( $year - 1 ) % 4 );
  1680. $m = 32.044093161144 + 1.5542417966212 * $a + $b / 4.0 - 0.0031777940220923 * ( $year - 1 );
  1681. if ( $m < 0 ) {
  1682. $m--;
  1683. }
  1684. $Mar = intval( $m );
  1685. if ( $m < 0 ) {
  1686. $m++;
  1687. }
  1688. $m -= $Mar;
  1689. $c = intval( ( $Mar + 3 * ( $year - 1 ) + 5 * $b + 5 ) % 7 );
  1690. if ( $c == 0 && $a > 11 && $m >= 0.89772376543210 ) {
  1691. $Mar++;
  1692. } elseif ( $c == 1 && $a > 6 && $m >= 0.63287037037037 ) {
  1693. $Mar += 2;
  1694. } elseif ( $c == 2 || $c == 4 || $c == 6 ) {
  1695. $Mar++;
  1696. }
  1697. $Mar += intval( ( $year - 3761 ) / 100 ) - intval( ( $year - 3761 ) / 400 ) - 24;
  1698. return $Mar;
  1699. }
  1700. /**
  1701. * Algorithm to convert Gregorian dates to Thai solar dates,
  1702. * Minguo dates or Minguo dates.
  1703. *
  1704. * Link: https://en.wikipedia.org/wiki/Thai_solar_calendar
  1705. * https://en.wikipedia.org/wiki/Minguo_calendar
  1706. * https://en.wikipedia.org/wiki/Japanese_era_name
  1707. *
  1708. * @param string $ts 14-character timestamp
  1709. * @param string $cName Calender name
  1710. * @return array Converted year, month, day
  1711. */
  1712. private static function tsToYear( $ts, $cName ) {
  1713. $gy = substr( $ts, 0, 4 );
  1714. $gm = substr( $ts, 4, 2 );
  1715. $gd = substr( $ts, 6, 2 );
  1716. if ( !strcmp( $cName, 'thai' ) ) {
  1717. # Thai solar dates
  1718. # Add 543 years to the Gregorian calendar
  1719. # Months and days are identical
  1720. $gy_offset = $gy + 543;
  1721. } elseif ( ( !strcmp( $cName, 'minguo' ) ) || !strcmp( $cName, 'juche' ) ) {
  1722. # Minguo dates
  1723. # Deduct 1911 years from the Gregorian calendar
  1724. # Months and days are identical
  1725. $gy_offset = $gy - 1911;
  1726. } elseif ( !strcmp( $cName, 'tenno' ) ) {
  1727. # Nengō dates up to Meiji period
  1728. # Deduct years from the Gregorian calendar
  1729. # depending on the nengo periods
  1730. # Months and days are identical
  1731. if ( ( $gy < 1912 )
  1732. || ( ( $gy == 1912 ) && ( $gm < 7 ) )
  1733. || ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd < 31 ) )
  1734. ) {
  1735. # Meiji period
  1736. $gy_gannen = $gy - 1868 + 1;
  1737. $gy_offset = $gy_gannen;
  1738. if ( $gy_gannen == 1 ) {
  1739. $gy_offset = '元';
  1740. }
  1741. $gy_offset = '明治' . $gy_offset;
  1742. } elseif (
  1743. ( ( $gy == 1912 ) && ( $gm == 7 ) && ( $gd == 31 ) ) ||
  1744. ( ( $gy == 1912 ) && ( $gm >= 8 ) ) ||
  1745. ( ( $gy > 1912 ) && ( $gy < 1926 ) ) ||
  1746. ( ( $gy == 1926 ) && ( $gm < 12 ) ) ||
  1747. ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd < 26 ) )
  1748. ) {
  1749. # Taishō period
  1750. $gy_gannen = $gy - 1912 + 1;
  1751. $gy_offset = $gy_gannen;
  1752. if ( $gy_gannen == 1 ) {
  1753. $gy_offset = '元';
  1754. }
  1755. $gy_offset = '大正' . $gy_offset;
  1756. } elseif (
  1757. ( ( $gy == 1926 ) && ( $gm == 12 ) && ( $gd >= 26 ) ) ||
  1758. ( ( $gy > 1926 ) && ( $gy < 1989 ) ) ||
  1759. ( ( $gy == 1989 ) && ( $gm == 1 ) && ( $gd < 8 ) )
  1760. ) {
  1761. # Shōwa period
  1762. $gy_gannen = $gy - 1926 + 1;
  1763. $gy_offset = $gy_gannen;
  1764. if ( $gy_gannen == 1 ) {
  1765. $gy_offset = '元';
  1766. }
  1767. $gy_offset = '昭和' . $gy_offset;
  1768. } else {
  1769. # Heisei period
  1770. $gy_gannen = $gy - 1989 + 1;
  1771. $gy_offset = $gy_gannen;
  1772. if ( $gy_gannen == 1 ) {
  1773. $gy_offset = '元';
  1774. }
  1775. $gy_offset = '平成' . $gy_offset;
  1776. }
  1777. } else {
  1778. $gy_offset = $gy;
  1779. }
  1780. return [ $gy_offset, $gm, $gd ];
  1781. }
  1782. /**
  1783. * Gets directionality of the first strongly directional codepoint, for embedBidi()
  1784. *
  1785. * This is the rule the BIDI algorithm uses to determine the directionality of
  1786. * paragraphs ( http://unicode.org/reports/tr9/#The_Paragraph_Level ) and
  1787. * FSI isolates ( http://unicode.org/reports/tr9/#Explicit_Directional_Isolates ).
  1788. *
  1789. * TODO: Does not handle BIDI control characters inside the text.
  1790. * TODO: Does not handle unallocated characters.
  1791. *
  1792. * @param string $text Text to test
  1793. * @return null|string Directionality ('ltr' or 'rtl') or null
  1794. */
  1795. private static function strongDirFromContent( $text = '' ) {
  1796. if ( !preg_match( self::$strongDirRegex, $text, $matches ) ) {
  1797. return null;
  1798. }
  1799. if ( $matches[1] === '' ) {
  1800. return 'rtl';
  1801. }
  1802. return 'ltr';
  1803. }
  1804. /**
  1805. * Roman number formatting up to 10000
  1806. *
  1807. * @param int $num
  1808. *
  1809. * @return string
  1810. */
  1811. static function romanNumeral( $num ) {
  1812. static $table = [
  1813. [ '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X' ],
  1814. [ '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', 'C' ],
  1815. [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', 'M' ],
  1816. [ '', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM',
  1817. 'MMMMMMMM', 'MMMMMMMMM', 'MMMMMMMMMM' ]
  1818. ];
  1819. $num = intval( $num );
  1820. if ( $num > 10000 || $num <= 0 ) {
  1821. return $num;
  1822. }
  1823. $s = '';
  1824. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1825. if ( $num >= $pow10 ) {
  1826. $s .= $table[$i][(int)floor( $num / $pow10 )];
  1827. }
  1828. $num = $num % $pow10;
  1829. }
  1830. return $s;
  1831. }
  1832. /**
  1833. * Hebrew Gematria number formatting up to 9999
  1834. *
  1835. * @param int $num
  1836. *
  1837. * @return string
  1838. */
  1839. static function hebrewNumeral( $num ) {
  1840. static $table = [
  1841. [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ],
  1842. [ '', 'י', 'כ', 'ל', 'מ', 'נ', 'ס', 'ע', 'פ', 'צ', 'ק' ],
  1843. [ '',
  1844. [ 'ק' ],
  1845. [ 'ר' ],
  1846. [ 'ש' ],
  1847. [ 'ת' ],
  1848. [ 'ת', 'ק' ],
  1849. [ 'ת', 'ר' ],
  1850. [ 'ת', 'ש' ],
  1851. [ 'ת', 'ת' ],
  1852. [ 'ת', 'ת', 'ק' ],
  1853. [ 'ת', 'ת', 'ר' ],
  1854. ],
  1855. [ '', 'א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ז', 'ח', 'ט', 'י' ]
  1856. ];
  1857. $num = intval( $num );
  1858. if ( $num > 9999 || $num <= 0 ) {
  1859. return $num;
  1860. }
  1861. // Round thousands have special notations
  1862. if ( $num === 1000 ) {
  1863. return "א' אלף";
  1864. } elseif ( $num % 1000 === 0 ) {
  1865. return $table[0][$num / 1000] . "' אלפים";
  1866. }
  1867. $letters = [];
  1868. for ( $pow10 = 1000, $i = 3; $i >= 0; $pow10 /= 10, $i-- ) {
  1869. if ( $num >= $pow10 ) {
  1870. if ( $num === 15 || $num === 16 ) {
  1871. $letters[] = $table[0][9];
  1872. $letters[] = $table[0][$num - 9];
  1873. $num = 0;
  1874. } else {
  1875. $letters = array_merge(
  1876. $letters,
  1877. (array)$table[$i][intval( $num / $pow10 )]
  1878. );
  1879. if ( $pow10 === 1000 ) {
  1880. $letters[] = "'";
  1881. }
  1882. }
  1883. }
  1884. $num = $num % $pow10;
  1885. }
  1886. $preTransformLength = count( $letters );
  1887. if ( $preTransformLength === 1 ) {
  1888. // Add geresh (single quote) to one-letter numbers
  1889. $letters[] = "'";
  1890. } else {
  1891. $lastIndex = $preTransformLength - 1;
  1892. $letters[$lastIndex] = str_replace(
  1893. [ 'כ', 'מ', 'נ', 'פ', 'צ' ],
  1894. [ 'ך', 'ם', 'ן', 'ף', 'ץ' ],
  1895. $letters[$lastIndex]
  1896. );
  1897. // Add gershayim (double quote) to multiple-letter numbers,
  1898. // but exclude numbers with only one letter after the thousands
  1899. // (1001-1009, 1020, 1030, 2001-2009, etc.)
  1900. if ( $letters[1] === "'" && $preTransformLength === 3 ) {
  1901. $letters[] = "'";
  1902. } else {
  1903. array_splice( $letters, -1, 0, '"' );
  1904. }
  1905. }
  1906. return implode( $letters );
  1907. }
  1908. /**
  1909. * Used by date() and time() to adjust the time output.
  1910. *
  1911. * @param string $ts The time in date('YmdHis') format
  1912. * @param mixed $tz Adjust the time by this amount (default false, mean we
  1913. * get user timecorrection setting)
  1914. * @return int
  1915. */
  1916. public function userAdjust( $ts, $tz = false ) {
  1917. global $wgUser, $wgLocalTZoffset;
  1918. if ( $tz === false ) {
  1919. $tz = $wgUser->getOption( 'timecorrection' );
  1920. }
  1921. $data = explode( '|', $tz, 3 );
  1922. if ( $data[0] == 'ZoneInfo' ) {
  1923. try {
  1924. $userTZ = new DateTimeZone( $data[2] );
  1925. $date = new DateTime( $ts, new DateTimeZone( 'UTC' ) );
  1926. $date->setTimezone( $userTZ );
  1927. return $date->format( 'YmdHis' );
  1928. } catch ( Exception $e ) {
  1929. // Unrecognized timezone, default to 'Offset' with the stored offset.
  1930. $data[0] = 'Offset';
  1931. }
  1932. }
  1933. if ( $data[0] == 'System' || $tz == '' ) {
  1934. # Global offset in minutes.
  1935. $minDiff = $wgLocalTZoffset;
  1936. } elseif ( $data[0] == 'Offset' ) {
  1937. $minDiff = intval( $data[1] );
  1938. } else {
  1939. $data = explode( ':', $tz );
  1940. if ( count( $data ) == 2 ) {
  1941. $data[0] = intval( $data[0] );
  1942. $data[1] = intval( $data[1] );
  1943. $minDiff = abs( $data[0] ) * 60 + $data[1];
  1944. if ( $data[0] < 0 ) {
  1945. $minDiff = -$minDiff;
  1946. }
  1947. } else {
  1948. $minDiff = intval( $data[0] ) * 60;
  1949. }
  1950. }
  1951. # No difference ? Return time unchanged
  1952. if ( 0 == $minDiff ) {
  1953. return $ts;
  1954. }
  1955. Wikimedia\suppressWarnings(); // E_STRICT system time bitching
  1956. # Generate an adjusted date; take advantage of the fact that mktime
  1957. # will normalize out-of-range values so we don't have to split $minDiff
  1958. # into hours and minutes.
  1959. $t = mktime( (
  1960. (int)substr( $ts, 8, 2 ) ), # Hours
  1961. (int)substr( $ts, 10, 2 ) + $minDiff, # Minutes
  1962. (int)substr( $ts, 12, 2 ), # Seconds
  1963. (int)substr( $ts, 4, 2 ), # Month
  1964. (int)substr( $ts, 6, 2 ), # Day
  1965. (int)substr( $ts, 0, 4 ) ); # Year
  1966. $date = date( 'YmdHis', $t );
  1967. Wikimedia\restoreWarnings();
  1968. return $date;
  1969. }
  1970. /**
  1971. * This is meant to be used by time(), date(), and timeanddate() to get
  1972. * the date preference they're supposed to use, it should be used in
  1973. * all children.
  1974. *
  1975. * function timeanddate([...], $format = true) {
  1976. * $datePreference = $this->dateFormat($format);
  1977. * [...]
  1978. * }
  1979. *
  1980. * @param int|string|bool $usePrefs If true, the user's preference is used
  1981. * if false, the site/language default is used
  1982. * if int/string, assumed to be a format.
  1983. * @return string
  1984. */
  1985. function dateFormat( $usePrefs = true ) {
  1986. global $wgUser;
  1987. if ( is_bool( $usePrefs ) ) {
  1988. if ( $usePrefs ) {
  1989. $datePreference = $wgUser->getDatePreference();
  1990. } else {
  1991. $datePreference = (string)User::getDefaultOption( 'date' );
  1992. }
  1993. } else {
  1994. $datePreference = (string)$usePrefs;
  1995. }
  1996. // return int
  1997. if ( $datePreference == '' ) {
  1998. return 'default';
  1999. }
  2000. return $datePreference;
  2001. }
  2002. /**
  2003. * Get a format string for a given type and preference
  2004. * @param string $type May be 'date', 'time', 'both', or 'pretty'.
  2005. * @param string $pref The format name as it appears in Messages*.php under
  2006. * $datePreferences.
  2007. *
  2008. * @since 1.22 New type 'pretty' that provides a more readable timestamp format
  2009. *
  2010. * @return string
  2011. */
  2012. function getDateFormatString( $type, $pref ) {
  2013. $wasDefault = false;
  2014. if ( $pref == 'default' ) {
  2015. $wasDefault = true;
  2016. $pref = $this->getDefaultDateFormat();
  2017. }
  2018. if ( !isset( $this->dateFormatStrings[$type][$pref] ) ) {
  2019. $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
  2020. if ( $type === 'pretty' && $df === null ) {
  2021. $df = $this->getDateFormatString( 'date', $pref );
  2022. }
  2023. if ( !$wasDefault && $df === null ) {
  2024. $pref = $this->getDefaultDateFormat();
  2025. $df = self::$dataCache->getSubitem( $this->mCode, 'dateFormats', "$pref $type" );
  2026. }
  2027. $this->dateFormatStrings[$type][$pref] = $df;
  2028. }
  2029. return $this->dateFormatStrings[$type][$pref];
  2030. }
  2031. /**
  2032. * @param string $ts The time format which needs to be turned into a
  2033. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2034. * @param bool $adj Whether to adjust the time output according to the
  2035. * user configured offset ($timecorrection)
  2036. * @param mixed $format True to use user's date format preference
  2037. * @param string|bool $timecorrection The time offset as returned by
  2038. * validateTimeZone() in Special:Preferences
  2039. * @return string
  2040. */
  2041. public function date( $ts, $adj = false, $format = true, $timecorrection = false ) {
  2042. $ts = wfTimestamp( TS_MW, $ts );
  2043. if ( $adj ) {
  2044. $ts = $this->userAdjust( $ts, $timecorrection );
  2045. }
  2046. $df = $this->getDateFormatString( 'date', $this->dateFormat( $format ) );
  2047. return $this->sprintfDate( $df, $ts );
  2048. }
  2049. /**
  2050. * @param string $ts The time format which needs to be turned into a
  2051. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2052. * @param bool $adj Whether to adjust the time output according to the
  2053. * user configured offset ($timecorrection)
  2054. * @param mixed $format True to use user's date format preference
  2055. * @param string|bool $timecorrection The time offset as returned by
  2056. * validateTimeZone() in Special:Preferences
  2057. * @return string
  2058. */
  2059. public function time( $ts, $adj = false, $format = true, $timecorrection = false ) {
  2060. $ts = wfTimestamp( TS_MW, $ts );
  2061. if ( $adj ) {
  2062. $ts = $this->userAdjust( $ts, $timecorrection );
  2063. }
  2064. $df = $this->getDateFormatString( 'time', $this->dateFormat( $format ) );
  2065. return $this->sprintfDate( $df, $ts );
  2066. }
  2067. /**
  2068. * @param string $ts The time format which needs to be turned into a
  2069. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2070. * @param bool $adj Whether to adjust the time output according to the
  2071. * user configured offset ($timecorrection)
  2072. * @param mixed $format What format to return, if it's false output the
  2073. * default one (default true)
  2074. * @param string|bool $timecorrection The time offset as returned by
  2075. * validateTimeZone() in Special:Preferences
  2076. * @return string
  2077. */
  2078. public function timeanddate( $ts, $adj = false, $format = true, $timecorrection = false ) {
  2079. $ts = wfTimestamp( TS_MW, $ts );
  2080. if ( $adj ) {
  2081. $ts = $this->userAdjust( $ts, $timecorrection );
  2082. }
  2083. $df = $this->getDateFormatString( 'both', $this->dateFormat( $format ) );
  2084. return $this->sprintfDate( $df, $ts );
  2085. }
  2086. /**
  2087. * Takes a number of seconds and turns it into a text using values such as hours and minutes.
  2088. *
  2089. * @since 1.20
  2090. *
  2091. * @param int $seconds The amount of seconds.
  2092. * @param array $chosenIntervals The intervals to enable.
  2093. *
  2094. * @return string
  2095. */
  2096. public function formatDuration( $seconds, array $chosenIntervals = [] ) {
  2097. $intervals = $this->getDurationIntervals( $seconds, $chosenIntervals );
  2098. $segments = [];
  2099. foreach ( $intervals as $intervalName => $intervalValue ) {
  2100. // Messages: duration-seconds, duration-minutes, duration-hours, duration-days, duration-weeks,
  2101. // duration-years, duration-decades, duration-centuries, duration-millennia
  2102. $message = wfMessage( 'duration-' . $intervalName )->numParams( $intervalValue );
  2103. $segments[] = $message->inLanguage( $this )->escaped();
  2104. }
  2105. return $this->listToText( $segments );
  2106. }
  2107. /**
  2108. * Takes a number of seconds and returns an array with a set of corresponding intervals.
  2109. * For example 65 will be turned into [ minutes => 1, seconds => 5 ].
  2110. *
  2111. * @since 1.20
  2112. *
  2113. * @param int $seconds The amount of seconds.
  2114. * @param array $chosenIntervals The intervals to enable.
  2115. *
  2116. * @return array
  2117. */
  2118. public function getDurationIntervals( $seconds, array $chosenIntervals = [] ) {
  2119. if ( empty( $chosenIntervals ) ) {
  2120. $chosenIntervals = [
  2121. 'millennia',
  2122. 'centuries',
  2123. 'decades',
  2124. 'years',
  2125. 'days',
  2126. 'hours',
  2127. 'minutes',
  2128. 'seconds'
  2129. ];
  2130. }
  2131. $intervals = array_intersect_key( self::$durationIntervals, array_flip( $chosenIntervals ) );
  2132. $sortedNames = array_keys( $intervals );
  2133. $smallestInterval = array_pop( $sortedNames );
  2134. $segments = [];
  2135. foreach ( $intervals as $name => $length ) {
  2136. $value = floor( $seconds / $length );
  2137. if ( $value > 0 || ( $name == $smallestInterval && empty( $segments ) ) ) {
  2138. $seconds -= $value * $length;
  2139. $segments[$name] = $value;
  2140. }
  2141. }
  2142. return $segments;
  2143. }
  2144. /**
  2145. * Internal helper function for userDate(), userTime() and userTimeAndDate()
  2146. *
  2147. * @param string $type Can be 'date', 'time' or 'both'
  2148. * @param string $ts The time format which needs to be turned into a
  2149. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2150. * @param User $user User object used to get preferences for timezone and format
  2151. * @param array $options Array, can contain the following keys:
  2152. * - 'timecorrection': time correction, can have the following values:
  2153. * - true: use user's preference
  2154. * - false: don't use time correction
  2155. * - int: value of time correction in minutes
  2156. * - 'format': format to use, can have the following values:
  2157. * - true: use user's preference
  2158. * - false: use default preference
  2159. * - string: format to use
  2160. * @since 1.19
  2161. * @return string
  2162. */
  2163. private function internalUserTimeAndDate( $type, $ts, User $user, array $options ) {
  2164. $ts = wfTimestamp( TS_MW, $ts );
  2165. $options += [ 'timecorrection' => true, 'format' => true ];
  2166. if ( $options['timecorrection'] !== false ) {
  2167. if ( $options['timecorrection'] === true ) {
  2168. $offset = $user->getOption( 'timecorrection' );
  2169. } else {
  2170. $offset = $options['timecorrection'];
  2171. }
  2172. $ts = $this->userAdjust( $ts, $offset );
  2173. }
  2174. if ( $options['format'] === true ) {
  2175. $format = $user->getDatePreference();
  2176. } else {
  2177. $format = $options['format'];
  2178. }
  2179. $df = $this->getDateFormatString( $type, $this->dateFormat( $format ) );
  2180. return $this->sprintfDate( $df, $ts );
  2181. }
  2182. /**
  2183. * Get the formatted date for the given timestamp and formatted for
  2184. * the given user.
  2185. *
  2186. * @param mixed $ts Mixed: the time format which needs to be turned into a
  2187. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2188. * @param User $user User object used to get preferences for timezone and format
  2189. * @param array $options Array, can contain the following keys:
  2190. * - 'timecorrection': time correction, can have the following values:
  2191. * - true: use user's preference
  2192. * - false: don't use time correction
  2193. * - int: value of time correction in minutes
  2194. * - 'format': format to use, can have the following values:
  2195. * - true: use user's preference
  2196. * - false: use default preference
  2197. * - string: format to use
  2198. * @since 1.19
  2199. * @return string
  2200. */
  2201. public function userDate( $ts, User $user, array $options = [] ) {
  2202. return $this->internalUserTimeAndDate( 'date', $ts, $user, $options );
  2203. }
  2204. /**
  2205. * Get the formatted time for the given timestamp and formatted for
  2206. * the given user.
  2207. *
  2208. * @param mixed $ts The time format which needs to be turned into a
  2209. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2210. * @param User $user User object used to get preferences for timezone and format
  2211. * @param array $options Array, can contain the following keys:
  2212. * - 'timecorrection': time correction, can have the following values:
  2213. * - true: use user's preference
  2214. * - false: don't use time correction
  2215. * - int: value of time correction in minutes
  2216. * - 'format': format to use, can have the following values:
  2217. * - true: use user's preference
  2218. * - false: use default preference
  2219. * - string: format to use
  2220. * @since 1.19
  2221. * @return string
  2222. */
  2223. public function userTime( $ts, User $user, array $options = [] ) {
  2224. return $this->internalUserTimeAndDate( 'time', $ts, $user, $options );
  2225. }
  2226. /**
  2227. * Get the formatted date and time for the given timestamp and formatted for
  2228. * the given user.
  2229. *
  2230. * @param mixed $ts The time format which needs to be turned into a
  2231. * date('YmdHis') format with wfTimestamp(TS_MW,$ts)
  2232. * @param User $user User object used to get preferences for timezone and format
  2233. * @param array $options Array, can contain the following keys:
  2234. * - 'timecorrection': time correction, can have the following values:
  2235. * - true: use user's preference
  2236. * - false: don't use time correction
  2237. * - int: value of time correction in minutes
  2238. * - 'format': format to use, can have the following values:
  2239. * - true: use user's preference
  2240. * - false: use default preference
  2241. * - string: format to use
  2242. * @since 1.19
  2243. * @return string
  2244. */
  2245. public function userTimeAndDate( $ts, User $user, array $options = [] ) {
  2246. return $this->internalUserTimeAndDate( 'both', $ts, $user, $options );
  2247. }
  2248. /**
  2249. * Get the timestamp in a human-friendly relative format, e.g., "3 days ago".
  2250. *
  2251. * Determine the difference between the timestamp and the current time, and
  2252. * generate a readable timestamp by returning "<N> <units> ago", where the
  2253. * largest possible unit is used.
  2254. *
  2255. * @since 1.26 (Prior to 1.26 method existed but was not meant to be used directly)
  2256. *
  2257. * @param MWTimestamp $time
  2258. * @param MWTimestamp|null $relativeTo The base timestamp to compare to (defaults to now)
  2259. * @param User|null $user User the timestamp is being generated for
  2260. * (or null to use main context's user)
  2261. * @return string Formatted timestamp
  2262. */
  2263. public function getHumanTimestamp(
  2264. MWTimestamp $time, MWTimestamp $relativeTo = null, User $user = null
  2265. ) {
  2266. if ( $relativeTo === null ) {
  2267. $relativeTo = new MWTimestamp();
  2268. }
  2269. if ( $user === null ) {
  2270. $user = RequestContext::getMain()->getUser();
  2271. }
  2272. // Adjust for the user's timezone.
  2273. $offsetThis = $time->offsetForUser( $user );
  2274. $offsetRel = $relativeTo->offsetForUser( $user );
  2275. $ts = '';
  2276. if ( Hooks::run( 'GetHumanTimestamp', [ &$ts, $time, $relativeTo, $user, $this ] ) ) {
  2277. $ts = $this->getHumanTimestampInternal( $time, $relativeTo, $user );
  2278. }
  2279. // Reset the timezone on the objects.
  2280. $time->timestamp->sub( $offsetThis );
  2281. $relativeTo->timestamp->sub( $offsetRel );
  2282. return $ts;
  2283. }
  2284. /**
  2285. * Convert an MWTimestamp into a pretty human-readable timestamp using
  2286. * the given user preferences and relative base time.
  2287. *
  2288. * @see Language::getHumanTimestamp
  2289. * @param MWTimestamp $ts Timestamp to prettify
  2290. * @param MWTimestamp $relativeTo Base timestamp
  2291. * @param User $user User preferences to use
  2292. * @return string Human timestamp
  2293. * @since 1.26
  2294. */
  2295. private function getHumanTimestampInternal(
  2296. MWTimestamp $ts, MWTimestamp $relativeTo, User $user
  2297. ) {
  2298. $diff = $ts->diff( $relativeTo );
  2299. $diffDay = (bool)( (int)$ts->timestamp->format( 'w' ) -
  2300. (int)$relativeTo->timestamp->format( 'w' ) );
  2301. $days = $diff->days ?: (int)$diffDay;
  2302. if ( $diff->invert || $days > 5
  2303. && $ts->timestamp->format( 'Y' ) !== $relativeTo->timestamp->format( 'Y' )
  2304. ) {
  2305. // Timestamps are in different years: use full timestamp
  2306. // Also do full timestamp for future dates
  2307. /**
  2308. * @todo FIXME: Add better handling of future timestamps.
  2309. */
  2310. $format = $this->getDateFormatString( 'both', $user->getDatePreference() ?: 'default' );
  2311. $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
  2312. } elseif ( $days > 5 ) {
  2313. // Timestamps are in same year, but more than 5 days ago: show day and month only.
  2314. $format = $this->getDateFormatString( 'pretty', $user->getDatePreference() ?: 'default' );
  2315. $ts = $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) );
  2316. } elseif ( $days > 1 ) {
  2317. // Timestamp within the past week: show the day of the week and time
  2318. $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
  2319. $weekday = self::$mWeekdayMsgs[$ts->timestamp->format( 'w' )];
  2320. // Messages:
  2321. // sunday-at, monday-at, tuesday-at, wednesday-at, thursday-at, friday-at, saturday-at
  2322. $ts = wfMessage( "$weekday-at" )
  2323. ->inLanguage( $this )
  2324. ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
  2325. ->text();
  2326. } elseif ( $days == 1 ) {
  2327. // Timestamp was yesterday: say 'yesterday' and the time.
  2328. $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
  2329. $ts = wfMessage( 'yesterday-at' )
  2330. ->inLanguage( $this )
  2331. ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
  2332. ->text();
  2333. } elseif ( $diff->h > 1 || $diff->h == 1 && $diff->i > 30 ) {
  2334. // Timestamp was today, but more than 90 minutes ago: say 'today' and the time.
  2335. $format = $this->getDateFormatString( 'time', $user->getDatePreference() ?: 'default' );
  2336. $ts = wfMessage( 'today-at' )
  2337. ->inLanguage( $this )
  2338. ->params( $this->sprintfDate( $format, $ts->getTimestamp( TS_MW ) ) )
  2339. ->text();
  2340. // From here on in, the timestamp was soon enough ago so that we can simply say
  2341. // XX units ago, e.g., "2 hours ago" or "5 minutes ago"
  2342. } elseif ( $diff->h == 1 ) {
  2343. // Less than 90 minutes, but more than an hour ago.
  2344. $ts = wfMessage( 'hours-ago' )->inLanguage( $this )->numParams( 1 )->text();
  2345. } elseif ( $diff->i >= 1 ) {
  2346. // A few minutes ago.
  2347. $ts = wfMessage( 'minutes-ago' )->inLanguage( $this )->numParams( $diff->i )->text();
  2348. } elseif ( $diff->s >= 30 ) {
  2349. // Less than a minute, but more than 30 sec ago.
  2350. $ts = wfMessage( 'seconds-ago' )->inLanguage( $this )->numParams( $diff->s )->text();
  2351. } else {
  2352. // Less than 30 seconds ago.
  2353. $ts = wfMessage( 'just-now' )->text();
  2354. }
  2355. return $ts;
  2356. }
  2357. /**
  2358. * @param string $key
  2359. * @return string|null
  2360. */
  2361. public function getMessage( $key ) {
  2362. return self::$dataCache->getSubitem( $this->mCode, 'messages', $key );
  2363. }
  2364. /**
  2365. * @return array
  2366. */
  2367. function getAllMessages() {
  2368. return self::$dataCache->getItem( $this->mCode, 'messages' );
  2369. }
  2370. /**
  2371. * @param string $in
  2372. * @param string $out
  2373. * @param string $string
  2374. * @return string
  2375. */
  2376. public function iconv( $in, $out, $string ) {
  2377. # Even with //IGNORE iconv can whine about illegal characters in
  2378. # *input* string. We just ignore those too.
  2379. # REF: https://bugs.php.net/bug.php?id=37166
  2380. # REF: https://phabricator.wikimedia.org/T18885
  2381. Wikimedia\suppressWarnings();
  2382. $text = iconv( $in, $out . '//IGNORE', $string );
  2383. Wikimedia\restoreWarnings();
  2384. return $text;
  2385. }
  2386. // callback functions for ucwords(), ucwordbreaks()
  2387. /**
  2388. * @param array $matches
  2389. * @return mixed|string
  2390. */
  2391. function ucwordbreaksCallbackAscii( $matches ) {
  2392. return $this->ucfirst( $matches[1] );
  2393. }
  2394. /**
  2395. * @param array $matches
  2396. * @return string
  2397. */
  2398. function ucwordbreaksCallbackMB( $matches ) {
  2399. return mb_strtoupper( $matches[0] );
  2400. }
  2401. /**
  2402. * @param array $matches
  2403. * @return string
  2404. */
  2405. function ucwordsCallbackMB( $matches ) {
  2406. return mb_strtoupper( $matches[0] );
  2407. }
  2408. /**
  2409. * Make a string's first character uppercase
  2410. *
  2411. * @param string $str
  2412. *
  2413. * @return string
  2414. */
  2415. public function ucfirst( $str ) {
  2416. $o = ord( $str );
  2417. if ( $o < 96 ) { // if already uppercase...
  2418. return $str;
  2419. } elseif ( $o < 128 ) {
  2420. return ucfirst( $str ); // use PHP's ucfirst()
  2421. } else {
  2422. // fall back to more complex logic in case of multibyte strings
  2423. return $this->uc( $str, true );
  2424. }
  2425. }
  2426. /**
  2427. * Convert a string to uppercase
  2428. *
  2429. * @param string $str
  2430. * @param bool $first
  2431. *
  2432. * @return string
  2433. */
  2434. public function uc( $str, $first = false ) {
  2435. if ( $first ) {
  2436. if ( $this->isMultibyte( $str ) ) {
  2437. return mb_strtoupper( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  2438. } else {
  2439. return ucfirst( $str );
  2440. }
  2441. } else {
  2442. return $this->isMultibyte( $str ) ? mb_strtoupper( $str ) : strtoupper( $str );
  2443. }
  2444. }
  2445. /**
  2446. * @param string $str
  2447. * @return mixed|string
  2448. */
  2449. function lcfirst( $str ) {
  2450. $o = ord( $str );
  2451. if ( !$o ) {
  2452. return strval( $str );
  2453. } elseif ( $o >= 128 ) {
  2454. return $this->lc( $str, true );
  2455. } elseif ( $o > 96 ) {
  2456. return $str;
  2457. } else {
  2458. $str[0] = strtolower( $str[0] );
  2459. return $str;
  2460. }
  2461. }
  2462. /**
  2463. * @param string $str
  2464. * @param bool $first
  2465. * @return mixed|string
  2466. */
  2467. function lc( $str, $first = false ) {
  2468. if ( $first ) {
  2469. if ( $this->isMultibyte( $str ) ) {
  2470. return mb_strtolower( mb_substr( $str, 0, 1 ) ) . mb_substr( $str, 1 );
  2471. } else {
  2472. return strtolower( substr( $str, 0, 1 ) ) . substr( $str, 1 );
  2473. }
  2474. } else {
  2475. return $this->isMultibyte( $str ) ? mb_strtolower( $str ) : strtolower( $str );
  2476. }
  2477. }
  2478. /**
  2479. * @param string $str
  2480. * @return bool
  2481. */
  2482. function isMultibyte( $str ) {
  2483. return strlen( $str ) !== mb_strlen( $str );
  2484. }
  2485. /**
  2486. * @param string $str
  2487. * @return mixed|string
  2488. */
  2489. function ucwords( $str ) {
  2490. if ( $this->isMultibyte( $str ) ) {
  2491. $str = $this->lc( $str );
  2492. // regexp to find first letter in each word (i.e. after each space)
  2493. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)| ([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  2494. // function to use to capitalize a single char
  2495. return preg_replace_callback(
  2496. $replaceRegexp,
  2497. [ $this, 'ucwordsCallbackMB' ],
  2498. $str
  2499. );
  2500. } else {
  2501. return ucwords( strtolower( $str ) );
  2502. }
  2503. }
  2504. /**
  2505. * capitalize words at word breaks
  2506. *
  2507. * @param string $str
  2508. * @return mixed
  2509. */
  2510. function ucwordbreaks( $str ) {
  2511. if ( $this->isMultibyte( $str ) ) {
  2512. $str = $this->lc( $str );
  2513. // since \b doesn't work for UTF-8, we explicitely define word break chars
  2514. $breaks = "[ \-\(\)\}\{\.,\?!]";
  2515. // find first letter after word break
  2516. $replaceRegexp = "/^([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)|" .
  2517. "$breaks([a-z]|[\\xc0-\\xff][\\x80-\\xbf]*)/";
  2518. return preg_replace_callback(
  2519. $replaceRegexp,
  2520. [ $this, 'ucwordbreaksCallbackMB' ],
  2521. $str
  2522. );
  2523. } else {
  2524. return preg_replace_callback(
  2525. '/\b([\w\x80-\xff]+)\b/',
  2526. [ $this, 'ucwordbreaksCallbackAscii' ],
  2527. $str
  2528. );
  2529. }
  2530. }
  2531. /**
  2532. * Return a case-folded representation of $s
  2533. *
  2534. * This is a representation such that caseFold($s1)==caseFold($s2) if $s1
  2535. * and $s2 are the same except for the case of their characters. It is not
  2536. * necessary for the value returned to make sense when displayed.
  2537. *
  2538. * Do *not* perform any other normalisation in this function. If a caller
  2539. * uses this function when it should be using a more general normalisation
  2540. * function, then fix the caller.
  2541. *
  2542. * @param string $s
  2543. *
  2544. * @return string
  2545. */
  2546. function caseFold( $s ) {
  2547. return $this->uc( $s );
  2548. }
  2549. /**
  2550. * @param string $s
  2551. * @return string
  2552. * @throws MWException
  2553. */
  2554. function checkTitleEncoding( $s ) {
  2555. if ( is_array( $s ) ) {
  2556. throw new MWException( 'Given array to checkTitleEncoding.' );
  2557. }
  2558. if ( StringUtils::isUtf8( $s ) ) {
  2559. return $s;
  2560. }
  2561. return $this->iconv( $this->fallback8bitEncoding(), 'utf-8', $s );
  2562. }
  2563. /**
  2564. * @return array
  2565. */
  2566. function fallback8bitEncoding() {
  2567. return self::$dataCache->getItem( $this->mCode, 'fallback8bitEncoding' );
  2568. }
  2569. /**
  2570. * Most writing systems use whitespace to break up words.
  2571. * Some languages such as Chinese don't conventionally do this,
  2572. * which requires special handling when breaking up words for
  2573. * searching etc.
  2574. *
  2575. * @return bool
  2576. */
  2577. function hasWordBreaks() {
  2578. return true;
  2579. }
  2580. /**
  2581. * Some languages such as Chinese require word segmentation,
  2582. * Specify such segmentation when overridden in derived class.
  2583. *
  2584. * @param string $string
  2585. * @return string
  2586. */
  2587. function segmentByWord( $string ) {
  2588. return $string;
  2589. }
  2590. /**
  2591. * Some languages have special punctuation need to be normalized.
  2592. * Make such changes here.
  2593. *
  2594. * @param string $string
  2595. * @return string
  2596. */
  2597. function normalizeForSearch( $string ) {
  2598. return self::convertDoubleWidth( $string );
  2599. }
  2600. /**
  2601. * convert double-width roman characters to single-width.
  2602. * range: ff00-ff5f ~= 0020-007f
  2603. *
  2604. * @param string $string
  2605. *
  2606. * @return string
  2607. */
  2608. protected static function convertDoubleWidth( $string ) {
  2609. static $full = null;
  2610. static $half = null;
  2611. if ( $full === null ) {
  2612. $fullWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2613. $halfWidth = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2614. $full = str_split( $fullWidth, 3 );
  2615. $half = str_split( $halfWidth );
  2616. }
  2617. $string = str_replace( $full, $half, $string );
  2618. return $string;
  2619. }
  2620. /**
  2621. * @param string $string
  2622. * @param string $pattern
  2623. * @return string
  2624. */
  2625. protected static function insertSpace( $string, $pattern ) {
  2626. $string = preg_replace( $pattern, " $1 ", $string );
  2627. $string = preg_replace( '/ +/', ' ', $string );
  2628. return $string;
  2629. }
  2630. /**
  2631. * @param array $termsArray
  2632. * @return array
  2633. */
  2634. function convertForSearchResult( $termsArray ) {
  2635. # some languages, e.g. Chinese, need to do a conversion
  2636. # in order for search results to be displayed correctly
  2637. return $termsArray;
  2638. }
  2639. /**
  2640. * Get the first character of a string.
  2641. *
  2642. * @param string $s
  2643. * @return string
  2644. */
  2645. function firstChar( $s ) {
  2646. $matches = [];
  2647. preg_match(
  2648. '/^([\x00-\x7f]|[\xc0-\xdf][\x80-\xbf]|' .
  2649. '[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xf7][\x80-\xbf]{3})/',
  2650. $s,
  2651. $matches
  2652. );
  2653. if ( isset( $matches[1] ) ) {
  2654. if ( strlen( $matches[1] ) != 3 ) {
  2655. return $matches[1];
  2656. }
  2657. // Break down Hangul syllables to grab the first jamo
  2658. $code = UtfNormal\Utils::utf8ToCodepoint( $matches[1] );
  2659. if ( $code < 0xac00 || 0xd7a4 <= $code ) {
  2660. return $matches[1];
  2661. } elseif ( $code < 0xb098 ) {
  2662. return "\xe3\x84\xb1";
  2663. } elseif ( $code < 0xb2e4 ) {
  2664. return "\xe3\x84\xb4";
  2665. } elseif ( $code < 0xb77c ) {
  2666. return "\xe3\x84\xb7";
  2667. } elseif ( $code < 0xb9c8 ) {
  2668. return "\xe3\x84\xb9";
  2669. } elseif ( $code < 0xbc14 ) {
  2670. return "\xe3\x85\x81";
  2671. } elseif ( $code < 0xc0ac ) {
  2672. return "\xe3\x85\x82";
  2673. } elseif ( $code < 0xc544 ) {
  2674. return "\xe3\x85\x85";
  2675. } elseif ( $code < 0xc790 ) {
  2676. return "\xe3\x85\x87";
  2677. } elseif ( $code < 0xcc28 ) {
  2678. return "\xe3\x85\x88";
  2679. } elseif ( $code < 0xce74 ) {
  2680. return "\xe3\x85\x8a";
  2681. } elseif ( $code < 0xd0c0 ) {
  2682. return "\xe3\x85\x8b";
  2683. } elseif ( $code < 0xd30c ) {
  2684. return "\xe3\x85\x8c";
  2685. } elseif ( $code < 0xd558 ) {
  2686. return "\xe3\x85\x8d";
  2687. } else {
  2688. return "\xe3\x85\x8e";
  2689. }
  2690. } else {
  2691. return '';
  2692. }
  2693. }
  2694. /**
  2695. * @deprecated No-op since 1.28
  2696. */
  2697. function initEncoding() {
  2698. // No-op.
  2699. }
  2700. /**
  2701. * @param string $s
  2702. * @return string
  2703. * @deprecated No-op since 1.28
  2704. */
  2705. function recodeForEdit( $s ) {
  2706. return $s;
  2707. }
  2708. /**
  2709. * @param string $s
  2710. * @return string
  2711. * @deprecated No-op since 1.28
  2712. */
  2713. function recodeInput( $s ) {
  2714. return $s;
  2715. }
  2716. /**
  2717. * Convert a UTF-8 string to normal form C. In Malayalam and Arabic, this
  2718. * also cleans up certain backwards-compatible sequences, converting them
  2719. * to the modern Unicode equivalent.
  2720. *
  2721. * This is language-specific for performance reasons only.
  2722. *
  2723. * @param string $s
  2724. *
  2725. * @return string
  2726. */
  2727. function normalize( $s ) {
  2728. global $wgAllUnicodeFixes;
  2729. $s = UtfNormal\Validator::cleanUp( $s );
  2730. if ( $wgAllUnicodeFixes ) {
  2731. $s = $this->transformUsingPairFile( 'normalize-ar.ser', $s );
  2732. $s = $this->transformUsingPairFile( 'normalize-ml.ser', $s );
  2733. }
  2734. return $s;
  2735. }
  2736. /**
  2737. * Transform a string using serialized data stored in the given file (which
  2738. * must be in the serialized subdirectory of $IP). The file contains pairs
  2739. * mapping source characters to destination characters.
  2740. *
  2741. * The data is cached in process memory. This will go faster if you have the
  2742. * FastStringSearch extension.
  2743. *
  2744. * @param string $file
  2745. * @param string $string
  2746. *
  2747. * @throws MWException
  2748. * @return string
  2749. */
  2750. function transformUsingPairFile( $file, $string ) {
  2751. if ( !isset( $this->transformData[$file] ) ) {
  2752. $data = wfGetPrecompiledData( $file );
  2753. if ( $data === false ) {
  2754. throw new MWException( __METHOD__ . ": The transformation file $file is missing" );
  2755. }
  2756. $this->transformData[$file] = new ReplacementArray( $data );
  2757. }
  2758. return $this->transformData[$file]->replace( $string );
  2759. }
  2760. /**
  2761. * For right-to-left language support
  2762. *
  2763. * @return bool
  2764. */
  2765. function isRTL() {
  2766. return self::$dataCache->getItem( $this->mCode, 'rtl' );
  2767. }
  2768. /**
  2769. * Return the correct HTML 'dir' attribute value for this language.
  2770. * @return string
  2771. */
  2772. function getDir() {
  2773. return $this->isRTL() ? 'rtl' : 'ltr';
  2774. }
  2775. /**
  2776. * Return 'left' or 'right' as appropriate alignment for line-start
  2777. * for this language's text direction.
  2778. *
  2779. * Should be equivalent to CSS3 'start' text-align value....
  2780. *
  2781. * @return string
  2782. */
  2783. function alignStart() {
  2784. return $this->isRTL() ? 'right' : 'left';
  2785. }
  2786. /**
  2787. * Return 'right' or 'left' as appropriate alignment for line-end
  2788. * for this language's text direction.
  2789. *
  2790. * Should be equivalent to CSS3 'end' text-align value....
  2791. *
  2792. * @return string
  2793. */
  2794. function alignEnd() {
  2795. return $this->isRTL() ? 'left' : 'right';
  2796. }
  2797. /**
  2798. * A hidden direction mark (LRM or RLM), depending on the language direction.
  2799. * Unlike getDirMark(), this function returns the character as an HTML entity.
  2800. * This function should be used when the output is guaranteed to be HTML,
  2801. * because it makes the output HTML source code more readable. When
  2802. * the output is plain text or can be escaped, getDirMark() should be used.
  2803. *
  2804. * @param bool $opposite Get the direction mark opposite to your language
  2805. * @return string
  2806. * @since 1.20
  2807. */
  2808. function getDirMarkEntity( $opposite = false ) {
  2809. if ( $opposite ) {
  2810. return $this->isRTL() ? '&lrm;' : '&rlm;';
  2811. }
  2812. return $this->isRTL() ? '&rlm;' : '&lrm;';
  2813. }
  2814. /**
  2815. * A hidden direction mark (LRM or RLM), depending on the language direction.
  2816. * This function produces them as invisible Unicode characters and
  2817. * the output may be hard to read and debug, so it should only be used
  2818. * when the output is plain text or can be escaped. When the output is
  2819. * HTML, use getDirMarkEntity() instead.
  2820. *
  2821. * @param bool $opposite Get the direction mark opposite to your language
  2822. * @return string
  2823. */
  2824. function getDirMark( $opposite = false ) {
  2825. $lrm = "\xE2\x80\x8E"; # LEFT-TO-RIGHT MARK, commonly abbreviated LRM
  2826. $rlm = "\xE2\x80\x8F"; # RIGHT-TO-LEFT MARK, commonly abbreviated RLM
  2827. if ( $opposite ) {
  2828. return $this->isRTL() ? $lrm : $rlm;
  2829. }
  2830. return $this->isRTL() ? $rlm : $lrm;
  2831. }
  2832. /**
  2833. * @return array
  2834. */
  2835. function capitalizeAllNouns() {
  2836. return self::$dataCache->getItem( $this->mCode, 'capitalizeAllNouns' );
  2837. }
  2838. /**
  2839. * An arrow, depending on the language direction.
  2840. *
  2841. * @param string $direction The direction of the arrow: forwards (default),
  2842. * backwards, left, right, up, down.
  2843. * @return string
  2844. */
  2845. function getArrow( $direction = 'forwards' ) {
  2846. switch ( $direction ) {
  2847. case 'forwards':
  2848. return $this->isRTL() ? '←' : '→';
  2849. case 'backwards':
  2850. return $this->isRTL() ? '→' : '←';
  2851. case 'left':
  2852. return '←';
  2853. case 'right':
  2854. return '→';
  2855. case 'up':
  2856. return '↑';
  2857. case 'down':
  2858. return '↓';
  2859. }
  2860. }
  2861. /**
  2862. * To allow "foo[[bar]]" to extend the link over the whole word "foobar"
  2863. *
  2864. * @return bool
  2865. */
  2866. function linkPrefixExtension() {
  2867. return self::$dataCache->getItem( $this->mCode, 'linkPrefixExtension' );
  2868. }
  2869. /**
  2870. * Get all magic words from cache.
  2871. * @return array
  2872. */
  2873. function getMagicWords() {
  2874. return self::$dataCache->getItem( $this->mCode, 'magicWords' );
  2875. }
  2876. /**
  2877. * Run the LanguageGetMagic hook once.
  2878. */
  2879. protected function doMagicHook() {
  2880. if ( $this->mMagicHookDone ) {
  2881. return;
  2882. }
  2883. $this->mMagicHookDone = true;
  2884. Hooks::run( 'LanguageGetMagic', [ &$this->mMagicExtensions, $this->getCode() ] );
  2885. }
  2886. /**
  2887. * Fill a MagicWord object with data from here
  2888. *
  2889. * @param MagicWord $mw
  2890. */
  2891. function getMagic( $mw ) {
  2892. // Saves a function call
  2893. if ( !$this->mMagicHookDone ) {
  2894. $this->doMagicHook();
  2895. }
  2896. if ( isset( $this->mMagicExtensions[$mw->mId] ) ) {
  2897. $rawEntry = $this->mMagicExtensions[$mw->mId];
  2898. } else {
  2899. $rawEntry = self::$dataCache->getSubitem(
  2900. $this->mCode, 'magicWords', $mw->mId );
  2901. }
  2902. if ( !is_array( $rawEntry ) ) {
  2903. wfWarn( "\"$rawEntry\" is not a valid magic word for \"$mw->mId\"" );
  2904. } else {
  2905. $mw->mCaseSensitive = $rawEntry[0];
  2906. $mw->mSynonyms = array_slice( $rawEntry, 1 );
  2907. }
  2908. }
  2909. /**
  2910. * Add magic words to the extension array
  2911. *
  2912. * @param array $newWords
  2913. */
  2914. function addMagicWordsByLang( $newWords ) {
  2915. $fallbackChain = $this->getFallbackLanguages();
  2916. $fallbackChain = array_reverse( $fallbackChain );
  2917. foreach ( $fallbackChain as $code ) {
  2918. if ( isset( $newWords[$code] ) ) {
  2919. $this->mMagicExtensions = $newWords[$code] + $this->mMagicExtensions;
  2920. }
  2921. }
  2922. }
  2923. /**
  2924. * Get special page names, as an associative array
  2925. * canonical name => array of valid names, including aliases
  2926. * @return array
  2927. */
  2928. function getSpecialPageAliases() {
  2929. // Cache aliases because it may be slow to load them
  2930. if ( is_null( $this->mExtendedSpecialPageAliases ) ) {
  2931. // Initialise array
  2932. $this->mExtendedSpecialPageAliases =
  2933. self::$dataCache->getItem( $this->mCode, 'specialPageAliases' );
  2934. Hooks::run( 'LanguageGetSpecialPageAliases',
  2935. [ &$this->mExtendedSpecialPageAliases, $this->getCode() ] );
  2936. }
  2937. return $this->mExtendedSpecialPageAliases;
  2938. }
  2939. /**
  2940. * Italic is unsuitable for some languages
  2941. *
  2942. * @param string $text The text to be emphasized.
  2943. * @return string
  2944. */
  2945. function emphasize( $text ) {
  2946. return "<em>$text</em>";
  2947. }
  2948. /**
  2949. * Normally we output all numbers in plain en_US style, that is
  2950. * 293,291.235 for twohundredninetythreethousand-twohundredninetyone
  2951. * point twohundredthirtyfive. However this is not suitable for all
  2952. * languages, some such as Bengali (bn) want ২,৯৩,২৯১.২৩৫ and others such as
  2953. * Icelandic just want to use commas instead of dots, and dots instead
  2954. * of commas like "293.291,235".
  2955. *
  2956. * An example of this function being called:
  2957. * <code>
  2958. * wfMessage( 'message' )->numParams( $num )->text()
  2959. * </code>
  2960. *
  2961. * See $separatorTransformTable on MessageIs.php for
  2962. * the , => . and . => , implementation.
  2963. *
  2964. * @todo check if it's viable to use localeconv() for the decimal separator thing.
  2965. * @param int|float $number The string to be formatted, should be an integer
  2966. * or a floating point number.
  2967. * @param bool $nocommafy Set to true for special numbers like dates
  2968. * @return string
  2969. */
  2970. public function formatNum( $number, $nocommafy = false ) {
  2971. global $wgTranslateNumerals;
  2972. if ( !$nocommafy ) {
  2973. $number = $this->commafy( $number );
  2974. $s = $this->separatorTransformTable();
  2975. if ( $s ) {
  2976. $number = strtr( $number, $s );
  2977. }
  2978. }
  2979. if ( $wgTranslateNumerals ) {
  2980. $s = $this->digitTransformTable();
  2981. if ( $s ) {
  2982. $number = strtr( $number, $s );
  2983. }
  2984. }
  2985. return (string)$number;
  2986. }
  2987. /**
  2988. * Front-end for non-commafied formatNum
  2989. *
  2990. * @param int|float $number The string to be formatted, should be an integer
  2991. * or a floating point number.
  2992. * @since 1.21
  2993. * @return string
  2994. */
  2995. public function formatNumNoSeparators( $number ) {
  2996. return $this->formatNum( $number, true );
  2997. }
  2998. /**
  2999. * @param string $number
  3000. * @return string
  3001. */
  3002. public function parseFormattedNumber( $number ) {
  3003. $s = $this->digitTransformTable();
  3004. if ( $s ) {
  3005. // eliminate empty array values such as ''. (T66347)
  3006. $s = array_filter( $s );
  3007. $number = strtr( $number, array_flip( $s ) );
  3008. }
  3009. $s = $this->separatorTransformTable();
  3010. if ( $s ) {
  3011. // eliminate empty array values such as ''. (T66347)
  3012. $s = array_filter( $s );
  3013. $number = strtr( $number, array_flip( $s ) );
  3014. }
  3015. $number = strtr( $number, [ ',' => '' ] );
  3016. return $number;
  3017. }
  3018. /**
  3019. * Adds commas to a given number
  3020. * @since 1.19
  3021. * @param mixed $number
  3022. * @return string
  3023. */
  3024. function commafy( $number ) {
  3025. $digitGroupingPattern = $this->digitGroupingPattern();
  3026. $minimumGroupingDigits = $this->minimumGroupingDigits();
  3027. if ( $number === null ) {
  3028. return '';
  3029. }
  3030. if ( !$digitGroupingPattern || $digitGroupingPattern === "###,###,###" ) {
  3031. // Default grouping is at thousands, use the same for ###,###,### pattern too.
  3032. // In some languages it's conventional not to insert a thousands separator
  3033. // in numbers that are four digits long (1000-9999).
  3034. if ( $minimumGroupingDigits ) {
  3035. // Number of '#' characters after last comma in the grouping pattern.
  3036. // The pattern is hardcoded here, but this would vary for different patterns.
  3037. $primaryGroupingSize = 3;
  3038. // Maximum length of a number to suppress digit grouping for.
  3039. $maximumLength = $minimumGroupingDigits + $primaryGroupingSize - 1;
  3040. if ( preg_match( '/^\-?\d{1,' . $maximumLength . '}(\.\d+)?$/', $number ) ) {
  3041. return $number;
  3042. }
  3043. }
  3044. return strrev( (string)preg_replace( '/(\d{3})(?=\d)(?!\d*\.)/', '$1,', strrev( $number ) ) );
  3045. } else {
  3046. // Ref: http://cldr.unicode.org/translation/number-patterns
  3047. $sign = "";
  3048. if ( intval( $number ) < 0 ) {
  3049. // For negative numbers apply the algorithm like positive number and add sign.
  3050. $sign = "-";
  3051. $number = substr( $number, 1 );
  3052. }
  3053. $integerPart = [];
  3054. $decimalPart = [];
  3055. $numMatches = preg_match_all( "/(#+)/", $digitGroupingPattern, $matches );
  3056. preg_match( "/\d+/", $number, $integerPart );
  3057. preg_match( "/\.\d*/", $number, $decimalPart );
  3058. $groupedNumber = ( count( $decimalPart ) > 0 ) ? $decimalPart[0] : "";
  3059. if ( $groupedNumber === $number ) {
  3060. // the string does not have any number part. Eg: .12345
  3061. return $sign . $groupedNumber;
  3062. }
  3063. $start = $end = ( $integerPart ) ? strlen( $integerPart[0] ) : 0;
  3064. while ( $start > 0 ) {
  3065. $match = $matches[0][$numMatches - 1];
  3066. $matchLen = strlen( $match );
  3067. $start = $end - $matchLen;
  3068. if ( $start < 0 ) {
  3069. $start = 0;
  3070. }
  3071. $groupedNumber = substr( $number, $start, $end - $start ) . $groupedNumber;
  3072. $end = $start;
  3073. if ( $numMatches > 1 ) {
  3074. // use the last pattern for the rest of the number
  3075. $numMatches--;
  3076. }
  3077. if ( $start > 0 ) {
  3078. $groupedNumber = "," . $groupedNumber;
  3079. }
  3080. }
  3081. return $sign . $groupedNumber;
  3082. }
  3083. }
  3084. /**
  3085. * @return string
  3086. */
  3087. function digitGroupingPattern() {
  3088. return self::$dataCache->getItem( $this->mCode, 'digitGroupingPattern' );
  3089. }
  3090. /**
  3091. * @return array
  3092. */
  3093. function digitTransformTable() {
  3094. return self::$dataCache->getItem( $this->mCode, 'digitTransformTable' );
  3095. }
  3096. /**
  3097. * @return array
  3098. */
  3099. function separatorTransformTable() {
  3100. return self::$dataCache->getItem( $this->mCode, 'separatorTransformTable' );
  3101. }
  3102. /**
  3103. * @return int|null
  3104. */
  3105. function minimumGroupingDigits() {
  3106. return self::$dataCache->getItem( $this->mCode, 'minimumGroupingDigits' );
  3107. }
  3108. /**
  3109. * Take a list of strings and build a locale-friendly comma-separated
  3110. * list, using the local comma-separator message.
  3111. * The last two strings are chained with an "and".
  3112. * NOTE: This function will only work with standard numeric array keys (0, 1, 2…)
  3113. *
  3114. * @param string[] $l
  3115. * @return string
  3116. */
  3117. function listToText( array $l ) {
  3118. $m = count( $l ) - 1;
  3119. if ( $m < 0 ) {
  3120. return '';
  3121. }
  3122. if ( $m > 0 ) {
  3123. $and = $this->msg( 'and' )->escaped();
  3124. $space = $this->msg( 'word-separator' )->escaped();
  3125. if ( $m > 1 ) {
  3126. $comma = $this->msg( 'comma-separator' )->escaped();
  3127. }
  3128. }
  3129. $s = $l[$m];
  3130. for ( $i = $m - 1; $i >= 0; $i-- ) {
  3131. if ( $i == $m - 1 ) {
  3132. $s = $l[$i] . $and . $space . $s;
  3133. } else {
  3134. $s = $l[$i] . $comma . $s;
  3135. }
  3136. }
  3137. return $s;
  3138. }
  3139. /**
  3140. * Take a list of strings and build a locale-friendly comma-separated
  3141. * list, using the local comma-separator message.
  3142. * @param string[] $list Array of strings to put in a comma list
  3143. * @return string
  3144. */
  3145. function commaList( array $list ) {
  3146. return implode(
  3147. wfMessage( 'comma-separator' )->inLanguage( $this )->escaped(),
  3148. $list
  3149. );
  3150. }
  3151. /**
  3152. * Take a list of strings and build a locale-friendly semicolon-separated
  3153. * list, using the local semicolon-separator message.
  3154. * @param string[] $list Array of strings to put in a semicolon list
  3155. * @return string
  3156. */
  3157. function semicolonList( array $list ) {
  3158. return implode(
  3159. wfMessage( 'semicolon-separator' )->inLanguage( $this )->escaped(),
  3160. $list
  3161. );
  3162. }
  3163. /**
  3164. * Same as commaList, but separate it with the pipe instead.
  3165. * @param string[] $list Array of strings to put in a pipe list
  3166. * @return string
  3167. */
  3168. function pipeList( array $list ) {
  3169. return implode(
  3170. wfMessage( 'pipe-separator' )->inLanguage( $this )->escaped(),
  3171. $list
  3172. );
  3173. }
  3174. /**
  3175. * This method is deprecated since 1.31 and kept as alias for truncateForDatabase, which
  3176. * has replaced it. This method provides truncation suitable for DB.
  3177. *
  3178. * The database offers limited byte lengths for some columns in the database;
  3179. * multi-byte character sets mean we need to ensure that only whole characters
  3180. * are included, otherwise broken characters can be passed to the user.
  3181. *
  3182. * @deprecated since 1.31, use truncateForDatabase or truncateForVisual as appropriate.
  3183. *
  3184. * @param string $string String to truncate
  3185. * @param int $length Maximum length (including ellipsis)
  3186. * @param string $ellipsis String to append to the truncated text
  3187. * @param bool $adjustLength Subtract length of ellipsis from $length.
  3188. * $adjustLength was introduced in 1.18, before that behaved as if false.
  3189. * @return string
  3190. */
  3191. function truncate( $string, $length, $ellipsis = '...', $adjustLength = true ) {
  3192. return $this->truncateForDatabase( $string, $length, $ellipsis, $adjustLength );
  3193. }
  3194. /**
  3195. * Truncate a string to a specified length in bytes, appending an optional
  3196. * string (e.g. for ellipsis)
  3197. *
  3198. * If $length is negative, the string will be truncated from the beginning
  3199. *
  3200. * @since 1.31
  3201. *
  3202. * @param string $string String to truncate
  3203. * @param int $length Maximum length in bytes
  3204. * @param string $ellipsis String to append to the end of truncated text
  3205. * @param bool $adjustLength Subtract length of ellipsis from $length
  3206. *
  3207. * @return string
  3208. */
  3209. function truncateForDatabase( $string, $length, $ellipsis = '...', $adjustLength = true ) {
  3210. return $this->truncateInternal(
  3211. $string, $length, $ellipsis, $adjustLength, 'strlen', 'substr'
  3212. );
  3213. }
  3214. /**
  3215. * Truncate a string to a specified number of characters, appending an optional
  3216. * string (e.g. for ellipsis).
  3217. *
  3218. * This provides multibyte version of truncate() method of this class, suitable for truncation
  3219. * based on number of characters, instead of number of bytes.
  3220. *
  3221. * If $length is negative, the string will be truncated from the beginning.
  3222. *
  3223. * @since 1.31
  3224. *
  3225. * @param string $string String to truncate
  3226. * @param int $length Maximum number of characters
  3227. * @param string $ellipsis String to append to the end of truncated text
  3228. * @param bool $adjustLength Subtract length of ellipsis from $length
  3229. *
  3230. * @return string
  3231. */
  3232. function truncateForVisual( $string, $length, $ellipsis = '...', $adjustLength = true ) {
  3233. // Passing encoding to mb_strlen and mb_substr is optional.
  3234. // Encoding defaults to mb_internal_encoding(), which is set to UTF-8 in Setup.php, so
  3235. // explicit specification of encoding is skipped.
  3236. // Note: Both multibyte methods are callables invoked in truncateInternal.
  3237. return $this->truncateInternal(
  3238. $string, $length, $ellipsis, $adjustLength, 'mb_strlen', 'mb_substr'
  3239. );
  3240. }
  3241. /**
  3242. * Internal method used for truncation. This method abstracts text truncation into
  3243. * one common method, allowing users to provide length measurement function and
  3244. * function for finding substring.
  3245. *
  3246. * For usages, see truncateForDatabase and truncateForVisual.
  3247. *
  3248. * @param string $string String to truncate
  3249. * @param int $length Maximum length of final text
  3250. * @param string $ellipsis String to append to the end of truncated text
  3251. * @param bool $adjustLength Subtract length of ellipsis from $length
  3252. * @param callable $measureLength Callable function used for determining the length of text
  3253. * @param callable $getSubstring Callable function used for getting the substrings
  3254. *
  3255. * @return string
  3256. */
  3257. private function truncateInternal(
  3258. $string, $length, $ellipsis = '...', $adjustLength = true, $measureLength, $getSubstring
  3259. ) {
  3260. if ( !is_callable( $measureLength ) || !is_callable( $getSubstring ) ) {
  3261. throw new InvalidArgumentException( 'Invalid callback provided' );
  3262. }
  3263. # Check if there is no need to truncate
  3264. if ( $measureLength( $string ) <= abs( $length ) ) {
  3265. return $string; // no need to truncate
  3266. }
  3267. # Use the localized ellipsis character
  3268. if ( $ellipsis == '...' ) {
  3269. $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
  3270. }
  3271. if ( $length == 0 ) {
  3272. return $ellipsis; // convention
  3273. }
  3274. $stringOriginal = $string;
  3275. # If ellipsis length is >= $length then we can't apply $adjustLength
  3276. if ( $adjustLength && $measureLength( $ellipsis ) >= abs( $length ) ) {
  3277. $string = $ellipsis; // this can be slightly unexpected
  3278. # Otherwise, truncate and add ellipsis...
  3279. } else {
  3280. $ellipsisLength = $adjustLength ? $measureLength( $ellipsis ) : 0;
  3281. if ( $length > 0 ) {
  3282. $length -= $ellipsisLength;
  3283. $string = $getSubstring( $string, 0, $length ); // xyz...
  3284. $string = $this->removeBadCharLast( $string );
  3285. $string = rtrim( $string );
  3286. $string = $string . $ellipsis;
  3287. } else {
  3288. $length += $ellipsisLength;
  3289. $string = $getSubstring( $string, $length ); // ...xyz
  3290. $string = $this->removeBadCharFirst( $string );
  3291. $string = ltrim( $string );
  3292. $string = $ellipsis . $string;
  3293. }
  3294. }
  3295. # Do not truncate if the ellipsis makes the string longer/equal (T24181).
  3296. # This check is *not* redundant if $adjustLength, due to the single case where
  3297. # LEN($ellipsis) > ABS($limit arg); $stringOriginal could be shorter than $string.
  3298. if ( $measureLength( $string ) < $measureLength( $stringOriginal ) ) {
  3299. return $string;
  3300. } else {
  3301. return $stringOriginal;
  3302. }
  3303. }
  3304. /**
  3305. * Remove bytes that represent an incomplete Unicode character
  3306. * at the end of string (e.g. bytes of the char are missing)
  3307. *
  3308. * @param string $string
  3309. * @return string
  3310. */
  3311. protected function removeBadCharLast( $string ) {
  3312. if ( $string != '' ) {
  3313. $char = ord( $string[strlen( $string ) - 1] );
  3314. $m = [];
  3315. if ( $char >= 0xc0 ) {
  3316. # We got the first byte only of a multibyte char; remove it.
  3317. $string = substr( $string, 0, -1 );
  3318. } elseif ( $char >= 0x80 &&
  3319. // Use the /s modifier (PCRE_DOTALL) so (.*) also matches newlines
  3320. preg_match( '/^(.*)(?:[\xe0-\xef][\x80-\xbf]|' .
  3321. '[\xf0-\xf7][\x80-\xbf]{1,2})$/s', $string, $m )
  3322. ) {
  3323. # We chopped in the middle of a character; remove it
  3324. $string = $m[1];
  3325. }
  3326. }
  3327. return $string;
  3328. }
  3329. /**
  3330. * Remove bytes that represent an incomplete Unicode character
  3331. * at the start of string (e.g. bytes of the char are missing)
  3332. *
  3333. * @param string $string
  3334. * @return string
  3335. */
  3336. protected function removeBadCharFirst( $string ) {
  3337. if ( $string != '' ) {
  3338. $char = ord( $string[0] );
  3339. if ( $char >= 0x80 && $char < 0xc0 ) {
  3340. # We chopped in the middle of a character; remove the whole thing
  3341. $string = preg_replace( '/^[\x80-\xbf]+/', '', $string );
  3342. }
  3343. }
  3344. return $string;
  3345. }
  3346. /**
  3347. * Truncate a string of valid HTML to a specified length in bytes,
  3348. * appending an optional string (e.g. for ellipses), and return valid HTML
  3349. *
  3350. * This is only intended for styled/linked text, such as HTML with
  3351. * tags like <span> and <a>, were the tags are self-contained (valid HTML).
  3352. * Also, this will not detect things like "display:none" CSS.
  3353. *
  3354. * Note: since 1.18 you do not need to leave extra room in $length for ellipses.
  3355. *
  3356. * @param string $text HTML string to truncate
  3357. * @param int $length (zero/positive) Maximum length (including ellipses)
  3358. * @param string $ellipsis String to append to the truncated text
  3359. * @return string
  3360. */
  3361. function truncateHtml( $text, $length, $ellipsis = '...' ) {
  3362. # Use the localized ellipsis character
  3363. if ( $ellipsis == '...' ) {
  3364. $ellipsis = wfMessage( 'ellipsis' )->inLanguage( $this )->escaped();
  3365. }
  3366. # Check if there is clearly no need to truncate
  3367. if ( $length <= 0 ) {
  3368. return $ellipsis; // no text shown, nothing to format (convention)
  3369. } elseif ( strlen( $text ) <= $length ) {
  3370. return $text; // string short enough even *with* HTML (short-circuit)
  3371. }
  3372. $dispLen = 0; // innerHTML legth so far
  3373. $testingEllipsis = false; // checking if ellipses will make string longer/equal?
  3374. $tagType = 0; // 0-open, 1-close
  3375. $bracketState = 0; // 1-tag start, 2-tag name, 0-neither
  3376. $entityState = 0; // 0-not entity, 1-entity
  3377. $tag = $ret = ''; // accumulated tag name, accumulated result string
  3378. $openTags = []; // open tag stack
  3379. $maybeState = null; // possible truncation state
  3380. $textLen = strlen( $text );
  3381. $neLength = max( 0, $length - strlen( $ellipsis ) ); // non-ellipsis len if truncated
  3382. for ( $pos = 0; true; ++$pos ) {
  3383. # Consider truncation once the display length has reached the maximim.
  3384. # We check if $dispLen > 0 to grab tags for the $neLength = 0 case.
  3385. # Check that we're not in the middle of a bracket/entity...
  3386. if ( $dispLen && $dispLen >= $neLength && $bracketState == 0 && !$entityState ) {
  3387. if ( !$testingEllipsis ) {
  3388. $testingEllipsis = true;
  3389. # Save where we are; we will truncate here unless there turn out to
  3390. # be so few remaining characters that truncation is not necessary.
  3391. if ( !$maybeState ) { // already saved? ($neLength = 0 case)
  3392. $maybeState = [ $ret, $openTags ]; // save state
  3393. }
  3394. } elseif ( $dispLen > $length && $dispLen > strlen( $ellipsis ) ) {
  3395. # String in fact does need truncation, the truncation point was OK.
  3396. list( $ret, $openTags ) = $maybeState; // reload state
  3397. $ret = $this->removeBadCharLast( $ret ); // multi-byte char fix
  3398. $ret .= $ellipsis; // add ellipsis
  3399. break;
  3400. }
  3401. }
  3402. if ( $pos >= $textLen ) {
  3403. break; // extra iteration just for above checks
  3404. }
  3405. # Read the next char...
  3406. $ch = $text[$pos];
  3407. $lastCh = $pos ? $text[$pos - 1] : '';
  3408. $ret .= $ch; // add to result string
  3409. if ( $ch == '<' ) {
  3410. $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags ); // for bad HTML
  3411. $entityState = 0; // for bad HTML
  3412. $bracketState = 1; // tag started (checking for backslash)
  3413. } elseif ( $ch == '>' ) {
  3414. $this->truncate_endBracket( $tag, $tagType, $lastCh, $openTags );
  3415. $entityState = 0; // for bad HTML
  3416. $bracketState = 0; // out of brackets
  3417. } elseif ( $bracketState == 1 ) {
  3418. if ( $ch == '/' ) {
  3419. $tagType = 1; // close tag (e.g. "</span>")
  3420. } else {
  3421. $tagType = 0; // open tag (e.g. "<span>")
  3422. $tag .= $ch;
  3423. }
  3424. $bracketState = 2; // building tag name
  3425. } elseif ( $bracketState == 2 ) {
  3426. if ( $ch != ' ' ) {
  3427. $tag .= $ch;
  3428. } else {
  3429. // Name found (e.g. "<a href=..."), add on tag attributes...
  3430. $pos += $this->truncate_skip( $ret, $text, "<>", $pos + 1 );
  3431. }
  3432. } elseif ( $bracketState == 0 ) {
  3433. if ( $entityState ) {
  3434. if ( $ch == ';' ) {
  3435. $entityState = 0;
  3436. $dispLen++; // entity is one displayed char
  3437. }
  3438. } else {
  3439. if ( $neLength == 0 && !$maybeState ) {
  3440. // Save state without $ch. We want to *hit* the first
  3441. // display char (to get tags) but not *use* it if truncating.
  3442. $maybeState = [ substr( $ret, 0, -1 ), $openTags ];
  3443. }
  3444. if ( $ch == '&' ) {
  3445. $entityState = 1; // entity found, (e.g. "&#160;")
  3446. } else {
  3447. $dispLen++; // this char is displayed
  3448. // Add the next $max display text chars after this in one swoop...
  3449. $max = ( $testingEllipsis ? $length : $neLength ) - $dispLen;
  3450. $skipped = $this->truncate_skip( $ret, $text, "<>&", $pos + 1, $max );
  3451. $dispLen += $skipped;
  3452. $pos += $skipped;
  3453. }
  3454. }
  3455. }
  3456. }
  3457. // Close the last tag if left unclosed by bad HTML
  3458. $this->truncate_endBracket( $tag, $text[$textLen - 1], $tagType, $openTags );
  3459. while ( count( $openTags ) > 0 ) {
  3460. $ret .= '</' . array_pop( $openTags ) . '>'; // close open tags
  3461. }
  3462. return $ret;
  3463. }
  3464. /**
  3465. * truncateHtml() helper function
  3466. * like strcspn() but adds the skipped chars to $ret
  3467. *
  3468. * @param string $ret
  3469. * @param string $text
  3470. * @param string $search
  3471. * @param int $start
  3472. * @param null|int $len
  3473. * @return int
  3474. */
  3475. private function truncate_skip( &$ret, $text, $search, $start, $len = null ) {
  3476. if ( $len === null ) {
  3477. $len = -1; // -1 means "no limit" for strcspn
  3478. } elseif ( $len < 0 ) {
  3479. $len = 0; // sanity
  3480. }
  3481. $skipCount = 0;
  3482. if ( $start < strlen( $text ) ) {
  3483. $skipCount = strcspn( $text, $search, $start, $len );
  3484. $ret .= substr( $text, $start, $skipCount );
  3485. }
  3486. return $skipCount;
  3487. }
  3488. /**
  3489. * truncateHtml() helper function
  3490. * (a) push or pop $tag from $openTags as needed
  3491. * (b) clear $tag value
  3492. * @param string &$tag Current HTML tag name we are looking at
  3493. * @param int $tagType (0-open tag, 1-close tag)
  3494. * @param string $lastCh Character before the '>' that ended this tag
  3495. * @param array &$openTags Open tag stack (not accounting for $tag)
  3496. */
  3497. private function truncate_endBracket( &$tag, $tagType, $lastCh, &$openTags ) {
  3498. $tag = ltrim( $tag );
  3499. if ( $tag != '' ) {
  3500. if ( $tagType == 0 && $lastCh != '/' ) {
  3501. $openTags[] = $tag; // tag opened (didn't close itself)
  3502. } elseif ( $tagType == 1 ) {
  3503. if ( $openTags && $tag == $openTags[count( $openTags ) - 1] ) {
  3504. array_pop( $openTags ); // tag closed
  3505. }
  3506. }
  3507. $tag = '';
  3508. }
  3509. }
  3510. /**
  3511. * Grammatical transformations, needed for inflected languages
  3512. * Invoked by putting {{grammar:case|word}} in a message
  3513. *
  3514. * @param string $word
  3515. * @param string $case
  3516. * @return string
  3517. */
  3518. function convertGrammar( $word, $case ) {
  3519. global $wgGrammarForms;
  3520. if ( isset( $wgGrammarForms[$this->getCode()][$case][$word] ) ) {
  3521. return $wgGrammarForms[$this->getCode()][$case][$word];
  3522. }
  3523. $grammarTransformations = $this->getGrammarTransformations();
  3524. if ( isset( $grammarTransformations[$case] ) ) {
  3525. $forms = $grammarTransformations[$case];
  3526. // Some names of grammar rules are aliases for other rules.
  3527. // In such cases the value is a string rather than object,
  3528. // so load the actual rules.
  3529. if ( is_string( $forms ) ) {
  3530. $forms = $grammarTransformations[$forms];
  3531. }
  3532. foreach ( array_values( $forms ) as $rule ) {
  3533. $form = $rule[0];
  3534. if ( $form === '@metadata' ) {
  3535. continue;
  3536. }
  3537. $replacement = $rule[1];
  3538. $regex = '/' . addcslashes( $form, '/' ) . '/u';
  3539. $patternMatches = preg_match( $regex, $word );
  3540. if ( $patternMatches === false ) {
  3541. wfLogWarning(
  3542. 'An error occurred while processing grammar. ' .
  3543. "Word: '$word'. Regex: /$form/."
  3544. );
  3545. } elseif ( $patternMatches === 1 ) {
  3546. $word = preg_replace( $regex, $replacement, $word );
  3547. break;
  3548. }
  3549. }
  3550. }
  3551. return $word;
  3552. }
  3553. /**
  3554. * Get the grammar forms for the content language
  3555. * @return array Array of grammar forms
  3556. * @since 1.20
  3557. */
  3558. function getGrammarForms() {
  3559. global $wgGrammarForms;
  3560. if ( isset( $wgGrammarForms[$this->getCode()] )
  3561. && is_array( $wgGrammarForms[$this->getCode()] )
  3562. ) {
  3563. return $wgGrammarForms[$this->getCode()];
  3564. }
  3565. return [];
  3566. }
  3567. /**
  3568. * Get the grammar transformations data for the language.
  3569. * Used like grammar forms, with {{GRAMMAR}} and cases,
  3570. * but uses pairs of regexes and replacements instead of code.
  3571. *
  3572. * @return array[] Array of grammar transformations.
  3573. * @throws MWException
  3574. * @since 1.28
  3575. */
  3576. public function getGrammarTransformations() {
  3577. $languageCode = $this->getCode();
  3578. if ( self::$grammarTransformations === null ) {
  3579. self::$grammarTransformations = new MapCacheLRU( 10 );
  3580. }
  3581. if ( self::$grammarTransformations->has( $languageCode ) ) {
  3582. return self::$grammarTransformations->get( $languageCode );
  3583. }
  3584. $data = [];
  3585. $grammarDataFile = __DIR__ . "/data/grammarTransformations/$languageCode.json";
  3586. if ( is_readable( $grammarDataFile ) ) {
  3587. $data = FormatJson::decode(
  3588. file_get_contents( $grammarDataFile ),
  3589. true
  3590. );
  3591. if ( $data === null ) {
  3592. throw new MWException( "Invalid grammar data for \"$languageCode\"." );
  3593. }
  3594. self::$grammarTransformations->set( $languageCode, $data );
  3595. }
  3596. return $data;
  3597. }
  3598. /**
  3599. * Provides an alternative text depending on specified gender.
  3600. * Usage {{gender:username|masculine|feminine|unknown}}.
  3601. * username is optional, in which case the gender of current user is used,
  3602. * but only in (some) interface messages; otherwise default gender is used.
  3603. *
  3604. * If no forms are given, an empty string is returned. If only one form is
  3605. * given, it will be returned unconditionally. These details are implied by
  3606. * the caller and cannot be overridden in subclasses.
  3607. *
  3608. * If three forms are given, the default is to use the third (unknown) form.
  3609. * If fewer than three forms are given, the default is to use the first (masculine) form.
  3610. * These details can be overridden in subclasses.
  3611. *
  3612. * @param string $gender
  3613. * @param array $forms
  3614. *
  3615. * @return string
  3616. */
  3617. function gender( $gender, $forms ) {
  3618. if ( !count( $forms ) ) {
  3619. return '';
  3620. }
  3621. $forms = $this->preConvertPlural( $forms, 2 );
  3622. if ( $gender === 'male' ) {
  3623. return $forms[0];
  3624. }
  3625. if ( $gender === 'female' ) {
  3626. return $forms[1];
  3627. }
  3628. return isset( $forms[2] ) ? $forms[2] : $forms[0];
  3629. }
  3630. /**
  3631. * Plural form transformations, needed for some languages.
  3632. * For example, there are 3 form of plural in Russian and Polish,
  3633. * depending on "count mod 10". See [[w:Plural]]
  3634. * For English it is pretty simple.
  3635. *
  3636. * Invoked by putting {{plural:count|wordform1|wordform2}}
  3637. * or {{plural:count|wordform1|wordform2|wordform3}}
  3638. *
  3639. * Example: {{plural:{{NUMBEROFARTICLES}}|article|articles}}
  3640. *
  3641. * @param int $count Non-localized number
  3642. * @param array $forms Different plural forms
  3643. * @return string Correct form of plural for $count in this language
  3644. */
  3645. function convertPlural( $count, $forms ) {
  3646. // Handle explicit n=pluralform cases
  3647. $forms = $this->handleExplicitPluralForms( $count, $forms );
  3648. if ( is_string( $forms ) ) {
  3649. return $forms;
  3650. }
  3651. if ( !count( $forms ) ) {
  3652. return '';
  3653. }
  3654. $pluralForm = $this->getPluralRuleIndexNumber( $count );
  3655. $pluralForm = min( $pluralForm, count( $forms ) - 1 );
  3656. return $forms[$pluralForm];
  3657. }
  3658. /**
  3659. * Handles explicit plural forms for Language::convertPlural()
  3660. *
  3661. * In {{PLURAL:$1|0=nothing|one|many}}, 0=nothing will be returned if $1 equals zero.
  3662. * If an explicitly defined plural form matches the $count, then
  3663. * string value returned, otherwise array returned for further consideration
  3664. * by CLDR rules or overridden convertPlural().
  3665. *
  3666. * @since 1.23
  3667. *
  3668. * @param int $count Non-localized number
  3669. * @param array $forms Different plural forms
  3670. *
  3671. * @return array|string
  3672. */
  3673. protected function handleExplicitPluralForms( $count, array $forms ) {
  3674. foreach ( $forms as $index => $form ) {
  3675. if ( preg_match( '/\d+=/i', $form ) ) {
  3676. $pos = strpos( $form, '=' );
  3677. if ( substr( $form, 0, $pos ) === (string)$count ) {
  3678. return substr( $form, $pos + 1 );
  3679. }
  3680. unset( $forms[$index] );
  3681. }
  3682. }
  3683. return array_values( $forms );
  3684. }
  3685. /**
  3686. * Checks that convertPlural was given an array and pads it to requested
  3687. * amount of forms by copying the last one.
  3688. *
  3689. * @param array $forms Array of forms given to convertPlural
  3690. * @param int $count How many forms should there be at least
  3691. * @return array Padded array of forms or an exception if not an array
  3692. */
  3693. protected function preConvertPlural( /* Array */ $forms, $count ) {
  3694. while ( count( $forms ) < $count ) {
  3695. $forms[] = $forms[count( $forms ) - 1];
  3696. }
  3697. return $forms;
  3698. }
  3699. /**
  3700. * Wraps argument with unicode control characters for directionality safety
  3701. *
  3702. * This solves the problem where directionality-neutral characters at the edge of
  3703. * the argument string get interpreted with the wrong directionality from the
  3704. * enclosing context, giving renderings that look corrupted like "(Ben_(WMF".
  3705. *
  3706. * The wrapping is LRE...PDF or RLE...PDF, depending on the detected
  3707. * directionality of the argument string, using the BIDI algorithm's own "First
  3708. * strong directional codepoint" rule. Essentially, this works round the fact that
  3709. * there is no embedding equivalent of U+2068 FSI (isolation with heuristic
  3710. * direction inference). The latter is cleaner but still not widely supported.
  3711. *
  3712. * @param string $text Text to wrap
  3713. * @return string Text, wrapped in LRE...PDF or RLE...PDF or nothing
  3714. */
  3715. public function embedBidi( $text = '' ) {
  3716. $dir = self::strongDirFromContent( $text );
  3717. if ( $dir === 'ltr' ) {
  3718. // Wrap in LEFT-TO-RIGHT EMBEDDING ... POP DIRECTIONAL FORMATTING
  3719. return self::$lre . $text . self::$pdf;
  3720. }
  3721. if ( $dir === 'rtl' ) {
  3722. // Wrap in RIGHT-TO-LEFT EMBEDDING ... POP DIRECTIONAL FORMATTING
  3723. return self::$rle . $text . self::$pdf;
  3724. }
  3725. // No strong directionality: do not wrap
  3726. return $text;
  3727. }
  3728. /**
  3729. * @todo Maybe translate block durations. Note that this function is somewhat misnamed: it
  3730. * deals with translating the *duration* ("1 week", "4 days", etc), not the expiry time
  3731. * (which is an absolute timestamp). Please note: do NOT add this blindly, as it is used
  3732. * on old expiry lengths recorded in log entries. You'd need to provide the start date to
  3733. * match up with it.
  3734. *
  3735. * @param string $str The validated block duration in English
  3736. * @param User $user User object to use timezone from or null for $wgUser
  3737. * @param int $now Current timestamp, for formatting relative block durations
  3738. * @return string Somehow translated block duration
  3739. * @see LanguageFi.php for example implementation
  3740. */
  3741. function translateBlockExpiry( $str, User $user = null, $now = 0 ) {
  3742. $duration = SpecialBlock::getSuggestedDurations( $this );
  3743. foreach ( $duration as $show => $value ) {
  3744. if ( strcmp( $str, $value ) == 0 ) {
  3745. return htmlspecialchars( trim( $show ) );
  3746. }
  3747. }
  3748. if ( wfIsInfinity( $str ) ) {
  3749. foreach ( $duration as $show => $value ) {
  3750. if ( wfIsInfinity( $value ) ) {
  3751. return htmlspecialchars( trim( $show ) );
  3752. }
  3753. }
  3754. }
  3755. // If all else fails, return a standard duration or timestamp description.
  3756. $time = strtotime( $str, $now );
  3757. if ( $time === false ) { // Unknown format. Return it as-is in case.
  3758. return $str;
  3759. } elseif ( $time !== strtotime( $str, $now + 1 ) ) { // It's a relative timestamp.
  3760. // The result differs based on current time, so the difference
  3761. // is a fixed duration length.
  3762. return $this->formatDuration( $time - $now );
  3763. } else { // It's an absolute timestamp.
  3764. if ( $time === 0 ) {
  3765. // wfTimestamp() handles 0 as current time instead of epoch.
  3766. $time = '19700101000000';
  3767. }
  3768. if ( $user ) {
  3769. return $this->userTimeAndDate( $time, $user );
  3770. }
  3771. return $this->timeanddate( $time );
  3772. }
  3773. }
  3774. /**
  3775. * languages like Chinese need to be segmented in order for the diff
  3776. * to be of any use
  3777. *
  3778. * @param string $text
  3779. * @return string
  3780. */
  3781. public function segmentForDiff( $text ) {
  3782. return $text;
  3783. }
  3784. /**
  3785. * and unsegment to show the result
  3786. *
  3787. * @param string $text
  3788. * @return string
  3789. */
  3790. public function unsegmentForDiff( $text ) {
  3791. return $text;
  3792. }
  3793. /**
  3794. * Return the LanguageConverter used in the Language
  3795. *
  3796. * @since 1.19
  3797. * @return LanguageConverter
  3798. */
  3799. public function getConverter() {
  3800. return $this->mConverter;
  3801. }
  3802. /**
  3803. * convert text to a variant
  3804. *
  3805. * @param string $text text to convert
  3806. * @param string|bool $variant variant to convert to, or false to use the user's preferred
  3807. * variant (if logged in), or the project default variant
  3808. * @return string the converted string
  3809. */
  3810. public function autoConvert( $text, $variant = false ) {
  3811. return $this->mConverter->autoConvert( $text, $variant );
  3812. }
  3813. /**
  3814. * convert text to all supported variants
  3815. *
  3816. * @param string $text
  3817. * @return array
  3818. */
  3819. public function autoConvertToAllVariants( $text ) {
  3820. return $this->mConverter->autoConvertToAllVariants( $text );
  3821. }
  3822. /**
  3823. * convert text to different variants of a language.
  3824. *
  3825. * @param string $text
  3826. * @return string
  3827. */
  3828. public function convert( $text ) {
  3829. return $this->mConverter->convert( $text );
  3830. }
  3831. /**
  3832. * Convert a Title object to a string in the preferred variant
  3833. *
  3834. * @param Title $title
  3835. * @return string
  3836. */
  3837. public function convertTitle( $title ) {
  3838. return $this->mConverter->convertTitle( $title );
  3839. }
  3840. /**
  3841. * Convert a namespace index to a string in the preferred variant
  3842. *
  3843. * @param int $ns namespace index (https://www.mediawiki.org/wiki/Manual:Namespace)
  3844. * @param string|null $variant variant to convert to, or null to use the user's preferred
  3845. * variant (if logged in), or the project default variant
  3846. * @return string a string representation of the namespace
  3847. */
  3848. public function convertNamespace( $ns, $variant = null ) {
  3849. return $this->mConverter->convertNamespace( $ns, $variant );
  3850. }
  3851. /**
  3852. * Check if this is a language with variants
  3853. *
  3854. * @return bool
  3855. */
  3856. public function hasVariants() {
  3857. return count( $this->getVariants() ) > 1;
  3858. }
  3859. /**
  3860. * Check if the language has the specific variant
  3861. *
  3862. * @since 1.19
  3863. * @param string $variant
  3864. * @return bool
  3865. */
  3866. public function hasVariant( $variant ) {
  3867. return (bool)$this->mConverter->validateVariant( $variant );
  3868. }
  3869. /**
  3870. * Perform output conversion on a string, and encode for safe HTML output.
  3871. * @param string $text Text to be converted
  3872. * @param bool $isTitle Whether this conversion is for the article title
  3873. * @return string
  3874. * @todo this should get integrated somewhere sane
  3875. */
  3876. public function convertHtml( $text, $isTitle = false ) {
  3877. return htmlspecialchars( $this->convert( $text, $isTitle ) );
  3878. }
  3879. /**
  3880. * @param string $key
  3881. * @return string
  3882. */
  3883. public function convertCategoryKey( $key ) {
  3884. return $this->mConverter->convertCategoryKey( $key );
  3885. }
  3886. /**
  3887. * Get the list of variants supported by this language
  3888. * see sample implementation in LanguageZh.php
  3889. *
  3890. * @return string[] An array of language codes
  3891. */
  3892. public function getVariants() {
  3893. return $this->mConverter->getVariants();
  3894. }
  3895. /**
  3896. * @return string
  3897. */
  3898. public function getPreferredVariant() {
  3899. return $this->mConverter->getPreferredVariant();
  3900. }
  3901. /**
  3902. * @return string
  3903. */
  3904. public function getDefaultVariant() {
  3905. return $this->mConverter->getDefaultVariant();
  3906. }
  3907. /**
  3908. * @return string
  3909. */
  3910. public function getURLVariant() {
  3911. return $this->mConverter->getURLVariant();
  3912. }
  3913. /**
  3914. * If a language supports multiple variants, it is
  3915. * possible that non-existing link in one variant
  3916. * actually exists in another variant. this function
  3917. * tries to find it. See e.g. LanguageZh.php
  3918. * The input parameters may be modified upon return
  3919. *
  3920. * @param string &$link The name of the link
  3921. * @param Title &$nt The title object of the link
  3922. * @param bool $ignoreOtherCond To disable other conditions when
  3923. * we need to transclude a template or update a category's link
  3924. */
  3925. public function findVariantLink( &$link, &$nt, $ignoreOtherCond = false ) {
  3926. $this->mConverter->findVariantLink( $link, $nt, $ignoreOtherCond );
  3927. }
  3928. /**
  3929. * returns language specific options used by User::getPageRenderHash()
  3930. * for example, the preferred language variant
  3931. *
  3932. * @return string
  3933. */
  3934. function getExtraHashOptions() {
  3935. return $this->mConverter->getExtraHashOptions();
  3936. }
  3937. /**
  3938. * For languages that support multiple variants, the title of an
  3939. * article may be displayed differently in different variants. this
  3940. * function returns the apporiate title defined in the body of the article.
  3941. *
  3942. * @return string
  3943. */
  3944. public function getParsedTitle() {
  3945. return $this->mConverter->getParsedTitle();
  3946. }
  3947. /**
  3948. * Refresh the cache of conversion tables when
  3949. * MediaWiki:Conversiontable* is updated.
  3950. *
  3951. * @param Title $title The Title of the page being updated
  3952. */
  3953. public function updateConversionTable( Title $title ) {
  3954. $this->mConverter->updateConversionTable( $title );
  3955. }
  3956. /**
  3957. * Prepare external link text for conversion. When the text is
  3958. * a URL, it shouldn't be converted, and it'll be wrapped in
  3959. * the "raw" tag (-{R| }-) to prevent conversion.
  3960. *
  3961. * This function is called "markNoConversion" for historical
  3962. * reasons.
  3963. *
  3964. * @param string $text Text to be used for external link
  3965. * @param bool $noParse Wrap it without confirming it's a real URL first
  3966. * @return string The tagged text
  3967. */
  3968. public function markNoConversion( $text, $noParse = false ) {
  3969. // Excluding protocal-relative URLs may avoid many false positives.
  3970. if ( $noParse || preg_match( '/^(?:' . wfUrlProtocolsWithoutProtRel() . ')/', $text ) ) {
  3971. return $this->mConverter->markNoConversion( $text );
  3972. } else {
  3973. return $text;
  3974. }
  3975. }
  3976. /**
  3977. * A regular expression to match legal word-trailing characters
  3978. * which should be merged onto a link of the form [[foo]]bar.
  3979. *
  3980. * @return string
  3981. */
  3982. public function linkTrail() {
  3983. return self::$dataCache->getItem( $this->mCode, 'linkTrail' );
  3984. }
  3985. /**
  3986. * A regular expression character set to match legal word-prefixing
  3987. * characters which should be merged onto a link of the form foo[[bar]].
  3988. *
  3989. * @return string
  3990. */
  3991. public function linkPrefixCharset() {
  3992. return self::$dataCache->getItem( $this->mCode, 'linkPrefixCharset' );
  3993. }
  3994. /**
  3995. * Get the "parent" language which has a converter to convert a "compatible" language
  3996. * (in another variant) to this language (eg. zh for zh-cn, but not en for en-gb).
  3997. *
  3998. * @return Language|null
  3999. * @since 1.22
  4000. */
  4001. public function getParentLanguage() {
  4002. if ( $this->mParentLanguage !== false ) {
  4003. return $this->mParentLanguage;
  4004. }
  4005. $code = explode( '-', $this->getCode() )[0];
  4006. if ( !in_array( $code, LanguageConverter::$languagesWithVariants ) ) {
  4007. $this->mParentLanguage = null;
  4008. return null;
  4009. }
  4010. $lang = self::factory( $code );
  4011. if ( !$lang->hasVariant( $this->getCode() ) ) {
  4012. $this->mParentLanguage = null;
  4013. return null;
  4014. }
  4015. $this->mParentLanguage = $lang;
  4016. return $lang;
  4017. }
  4018. /**
  4019. * Compare with an other language object
  4020. *
  4021. * @since 1.28
  4022. * @param Language $lang
  4023. * @return bool
  4024. */
  4025. public function equals( Language $lang ) {
  4026. return $lang->getCode() === $this->mCode;
  4027. }
  4028. /**
  4029. * Get the internal language code for this language object
  4030. *
  4031. * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
  4032. * htmlspecialchars() or similar
  4033. *
  4034. * @return string
  4035. */
  4036. public function getCode() {
  4037. return $this->mCode;
  4038. }
  4039. /**
  4040. * Get the code in BCP 47 format which we can use
  4041. * inside of html lang="" tags.
  4042. *
  4043. * NOTE: The return value of this function is NOT HTML-safe and must be escaped with
  4044. * htmlspecialchars() or similar.
  4045. *
  4046. * @since 1.19
  4047. * @return string
  4048. */
  4049. public function getHtmlCode() {
  4050. if ( is_null( $this->mHtmlCode ) ) {
  4051. $this->mHtmlCode = LanguageCode::bcp47( $this->getCode() );
  4052. }
  4053. return $this->mHtmlCode;
  4054. }
  4055. /**
  4056. * @param string $code
  4057. */
  4058. public function setCode( $code ) {
  4059. $this->mCode = $code;
  4060. // Ensure we don't leave incorrect cached data lying around
  4061. $this->mHtmlCode = null;
  4062. $this->mParentLanguage = false;
  4063. }
  4064. /**
  4065. * Get the language code from a file name. Inverse of getFileName()
  4066. * @param string $filename $prefix . $languageCode . $suffix
  4067. * @param string $prefix Prefix before the language code
  4068. * @param string $suffix Suffix after the language code
  4069. * @return string Language code, or false if $prefix or $suffix isn't found
  4070. */
  4071. public static function getCodeFromFileName( $filename, $prefix = 'Language', $suffix = '.php' ) {
  4072. $m = null;
  4073. preg_match( '/' . preg_quote( $prefix, '/' ) . '([A-Z][a-z_]+)' .
  4074. preg_quote( $suffix, '/' ) . '/', $filename, $m );
  4075. if ( !count( $m ) ) {
  4076. return false;
  4077. }
  4078. return str_replace( '_', '-', strtolower( $m[1] ) );
  4079. }
  4080. /**
  4081. * @param string $code
  4082. * @param bool $fallback Whether we're going through language fallback chain
  4083. * @return string Name of the language class
  4084. */
  4085. public static function classFromCode( $code, $fallback = true ) {
  4086. if ( $fallback && $code == 'en' ) {
  4087. return 'Language';
  4088. } else {
  4089. return 'Language' . str_replace( '-', '_', ucfirst( $code ) );
  4090. }
  4091. }
  4092. /**
  4093. * Get the name of a file for a certain language code
  4094. * @param string $prefix Prepend this to the filename
  4095. * @param string $code Language code
  4096. * @param string $suffix Append this to the filename
  4097. * @throws MWException
  4098. * @return string $prefix . $mangledCode . $suffix
  4099. */
  4100. public static function getFileName( $prefix = 'Language', $code, $suffix = '.php' ) {
  4101. if ( !self::isValidBuiltInCode( $code ) ) {
  4102. throw new MWException( "Invalid language code \"$code\"" );
  4103. }
  4104. return $prefix . str_replace( '-', '_', ucfirst( $code ) ) . $suffix;
  4105. }
  4106. /**
  4107. * @param string $code
  4108. * @return string
  4109. */
  4110. public static function getMessagesFileName( $code ) {
  4111. global $IP;
  4112. $file = self::getFileName( "$IP/languages/messages/Messages", $code, '.php' );
  4113. Hooks::run( 'Language::getMessagesFileName', [ $code, &$file ] );
  4114. return $file;
  4115. }
  4116. /**
  4117. * @param string $code
  4118. * @return string
  4119. * @throws MWException
  4120. * @since 1.23
  4121. */
  4122. public static function getJsonMessagesFileName( $code ) {
  4123. global $IP;
  4124. if ( !self::isValidBuiltInCode( $code ) ) {
  4125. throw new MWException( "Invalid language code \"$code\"" );
  4126. }
  4127. return "$IP/languages/i18n/$code.json";
  4128. }
  4129. /**
  4130. * Get the first fallback for a given language.
  4131. *
  4132. * @param string $code
  4133. *
  4134. * @return bool|string
  4135. */
  4136. public static function getFallbackFor( $code ) {
  4137. $fallbacks = self::getFallbacksFor( $code );
  4138. if ( $fallbacks ) {
  4139. return $fallbacks[0];
  4140. }
  4141. return false;
  4142. }
  4143. /**
  4144. * Get the ordered list of fallback languages.
  4145. *
  4146. * @since 1.19
  4147. * @param string $code Language code
  4148. * @return array Non-empty array, ending in "en"
  4149. */
  4150. public static function getFallbacksFor( $code ) {
  4151. if ( $code === 'en' || !self::isValidBuiltInCode( $code ) ) {
  4152. return [];
  4153. }
  4154. // For unknown languages, fallbackSequence returns an empty array,
  4155. // hardcode fallback to 'en' in that case.
  4156. return self::getLocalisationCache()->getItem( $code, 'fallbackSequence' ) ?: [ 'en' ];
  4157. }
  4158. /**
  4159. * Get the ordered list of fallback languages, ending with the fallback
  4160. * language chain for the site language.
  4161. *
  4162. * @since 1.22
  4163. * @param string $code Language code
  4164. * @return array Array( fallbacks, site fallbacks )
  4165. */
  4166. public static function getFallbacksIncludingSiteLanguage( $code ) {
  4167. global $wgLanguageCode;
  4168. // Usually, we will only store a tiny number of fallback chains, so we
  4169. // keep them in static memory.
  4170. $cacheKey = "{$code}-{$wgLanguageCode}";
  4171. if ( !array_key_exists( $cacheKey, self::$fallbackLanguageCache ) ) {
  4172. $fallbacks = self::getFallbacksFor( $code );
  4173. // Append the site's fallback chain, including the site language itself
  4174. $siteFallbacks = self::getFallbacksFor( $wgLanguageCode );
  4175. array_unshift( $siteFallbacks, $wgLanguageCode );
  4176. // Eliminate any languages already included in the chain
  4177. $siteFallbacks = array_diff( $siteFallbacks, $fallbacks );
  4178. self::$fallbackLanguageCache[$cacheKey] = [ $fallbacks, $siteFallbacks ];
  4179. }
  4180. return self::$fallbackLanguageCache[$cacheKey];
  4181. }
  4182. /**
  4183. * Get all messages for a given language
  4184. * WARNING: this may take a long time. If you just need all message *keys*
  4185. * but need the *contents* of only a few messages, consider using getMessageKeysFor().
  4186. *
  4187. * @param string $code
  4188. *
  4189. * @return array
  4190. */
  4191. public static function getMessagesFor( $code ) {
  4192. return self::getLocalisationCache()->getItem( $code, 'messages' );
  4193. }
  4194. /**
  4195. * Get a message for a given language
  4196. *
  4197. * @param string $key
  4198. * @param string $code
  4199. *
  4200. * @return string
  4201. */
  4202. public static function getMessageFor( $key, $code ) {
  4203. return self::getLocalisationCache()->getSubitem( $code, 'messages', $key );
  4204. }
  4205. /**
  4206. * Get all message keys for a given language. This is a faster alternative to
  4207. * array_keys( Language::getMessagesFor( $code ) )
  4208. *
  4209. * @since 1.19
  4210. * @param string $code Language code
  4211. * @return array Array of message keys (strings)
  4212. */
  4213. public static function getMessageKeysFor( $code ) {
  4214. return self::getLocalisationCache()->getSubitemList( $code, 'messages' );
  4215. }
  4216. /**
  4217. * @param string $talk
  4218. * @return mixed
  4219. */
  4220. function fixVariableInNamespace( $talk ) {
  4221. if ( strpos( $talk, '$1' ) === false ) {
  4222. return $talk;
  4223. }
  4224. global $wgMetaNamespace;
  4225. $talk = str_replace( '$1', $wgMetaNamespace, $talk );
  4226. # Allow grammar transformations
  4227. # Allowing full message-style parsing would make simple requests
  4228. # such as action=raw much more expensive than they need to be.
  4229. # This will hopefully cover most cases.
  4230. $talk = preg_replace_callback( '/{{grammar:(.*?)\|(.*?)}}/i',
  4231. [ $this, 'replaceGrammarInNamespace' ], $talk );
  4232. return str_replace( ' ', '_', $talk );
  4233. }
  4234. /**
  4235. * @param string $m
  4236. * @return string
  4237. */
  4238. function replaceGrammarInNamespace( $m ) {
  4239. return $this->convertGrammar( trim( $m[2] ), trim( $m[1] ) );
  4240. }
  4241. /**
  4242. * Decode an expiry (block, protection, etc) which has come from the DB
  4243. *
  4244. * @param string $expiry Database expiry String
  4245. * @param bool|int $format True to process using language functions, or TS_ constant
  4246. * to return the expiry in a given timestamp
  4247. * @param string $infinity If $format is not true, use this string for infinite expiry
  4248. * @return string
  4249. * @since 1.18
  4250. */
  4251. public function formatExpiry( $expiry, $format = true, $infinity = 'infinity' ) {
  4252. static $dbInfinity;
  4253. if ( $dbInfinity === null ) {
  4254. $dbInfinity = wfGetDB( DB_REPLICA )->getInfinity();
  4255. }
  4256. if ( $expiry == '' || $expiry === 'infinity' || $expiry == $dbInfinity ) {
  4257. return $format === true
  4258. ? $this->getMessageFromDB( 'infiniteblock' )
  4259. : $infinity;
  4260. } else {
  4261. return $format === true
  4262. ? $this->timeanddate( $expiry, /* User preference timezone */ true )
  4263. : wfTimestamp( $format, $expiry );
  4264. }
  4265. }
  4266. /**
  4267. * Formats a time given in seconds into a string representation of that time.
  4268. *
  4269. * @param int|float $seconds
  4270. * @param array $format An optional argument that formats the returned string in different ways:
  4271. * If $format['avoid'] === 'avoidseconds': don't show seconds if $seconds >= 1 hour,
  4272. * If $format['avoid'] === 'avoidminutes': don't show seconds/minutes if $seconds > 48 hours,
  4273. * If $format['noabbrevs'] is true: use 'seconds' and friends instead of 'seconds-abbrev'
  4274. * and friends.
  4275. * @note For backwards compatibility, $format may also be one of the strings 'avoidseconds'
  4276. * or 'avoidminutes'.
  4277. * @return string
  4278. */
  4279. function formatTimePeriod( $seconds, $format = [] ) {
  4280. if ( !is_array( $format ) ) {
  4281. $format = [ 'avoid' => $format ]; // For backwards compatibility
  4282. }
  4283. if ( !isset( $format['avoid'] ) ) {
  4284. $format['avoid'] = false;
  4285. }
  4286. if ( !isset( $format['noabbrevs'] ) ) {
  4287. $format['noabbrevs'] = false;
  4288. }
  4289. $secondsMsg = wfMessage(
  4290. $format['noabbrevs'] ? 'seconds' : 'seconds-abbrev' )->inLanguage( $this );
  4291. $minutesMsg = wfMessage(
  4292. $format['noabbrevs'] ? 'minutes' : 'minutes-abbrev' )->inLanguage( $this );
  4293. $hoursMsg = wfMessage(
  4294. $format['noabbrevs'] ? 'hours' : 'hours-abbrev' )->inLanguage( $this );
  4295. $daysMsg = wfMessage(
  4296. $format['noabbrevs'] ? 'days' : 'days-abbrev' )->inLanguage( $this );
  4297. if ( round( $seconds * 10 ) < 100 ) {
  4298. $s = $this->formatNum( sprintf( "%.1f", round( $seconds * 10 ) / 10 ) );
  4299. $s = $secondsMsg->params( $s )->text();
  4300. } elseif ( round( $seconds ) < 60 ) {
  4301. $s = $this->formatNum( round( $seconds ) );
  4302. $s = $secondsMsg->params( $s )->text();
  4303. } elseif ( round( $seconds ) < 3600 ) {
  4304. $minutes = floor( $seconds / 60 );
  4305. $secondsPart = round( fmod( $seconds, 60 ) );
  4306. if ( $secondsPart == 60 ) {
  4307. $secondsPart = 0;
  4308. $minutes++;
  4309. }
  4310. $s = $minutesMsg->params( $this->formatNum( $minutes ) )->text();
  4311. $s .= ' ';
  4312. $s .= $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
  4313. } elseif ( round( $seconds ) <= 2 * 86400 ) {
  4314. $hours = floor( $seconds / 3600 );
  4315. $minutes = floor( ( $seconds - $hours * 3600 ) / 60 );
  4316. $secondsPart = round( $seconds - $hours * 3600 - $minutes * 60 );
  4317. if ( $secondsPart == 60 ) {
  4318. $secondsPart = 0;
  4319. $minutes++;
  4320. }
  4321. if ( $minutes == 60 ) {
  4322. $minutes = 0;
  4323. $hours++;
  4324. }
  4325. $s = $hoursMsg->params( $this->formatNum( $hours ) )->text();
  4326. $s .= ' ';
  4327. $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
  4328. if ( !in_array( $format['avoid'], [ 'avoidseconds', 'avoidminutes' ] ) ) {
  4329. $s .= ' ' . $secondsMsg->params( $this->formatNum( $secondsPart ) )->text();
  4330. }
  4331. } else {
  4332. $days = floor( $seconds / 86400 );
  4333. if ( $format['avoid'] === 'avoidminutes' ) {
  4334. $hours = round( ( $seconds - $days * 86400 ) / 3600 );
  4335. if ( $hours == 24 ) {
  4336. $hours = 0;
  4337. $days++;
  4338. }
  4339. $s = $daysMsg->params( $this->formatNum( $days ) )->text();
  4340. $s .= ' ';
  4341. $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
  4342. } elseif ( $format['avoid'] === 'avoidseconds' ) {
  4343. $hours = floor( ( $seconds - $days * 86400 ) / 3600 );
  4344. $minutes = round( ( $seconds - $days * 86400 - $hours * 3600 ) / 60 );
  4345. if ( $minutes == 60 ) {
  4346. $minutes = 0;
  4347. $hours++;
  4348. }
  4349. if ( $hours == 24 ) {
  4350. $hours = 0;
  4351. $days++;
  4352. }
  4353. $s = $daysMsg->params( $this->formatNum( $days ) )->text();
  4354. $s .= ' ';
  4355. $s .= $hoursMsg->params( $this->formatNum( $hours ) )->text();
  4356. $s .= ' ';
  4357. $s .= $minutesMsg->params( $this->formatNum( $minutes ) )->text();
  4358. } else {
  4359. $s = $daysMsg->params( $this->formatNum( $days ) )->text();
  4360. $s .= ' ';
  4361. $s .= $this->formatTimePeriod( $seconds - $days * 86400, $format );
  4362. }
  4363. }
  4364. return $s;
  4365. }
  4366. /**
  4367. * Format a bitrate for output, using an appropriate
  4368. * unit (bps, kbps, Mbps, Gbps, Tbps, Pbps, Ebps, Zbps or Ybps) according to
  4369. * the magnitude in question.
  4370. *
  4371. * This use base 1000. For base 1024 use formatSize(), for another base
  4372. * see formatComputingNumbers().
  4373. *
  4374. * @param int $bps
  4375. * @return string
  4376. */
  4377. function formatBitrate( $bps ) {
  4378. return $this->formatComputingNumbers( $bps, 1000, "bitrate-$1bits" );
  4379. }
  4380. /**
  4381. * @param int $size Size of the unit
  4382. * @param int $boundary Size boundary (1000, or 1024 in most cases)
  4383. * @param string $messageKey Message key to be uesd
  4384. * @return string
  4385. */
  4386. function formatComputingNumbers( $size, $boundary, $messageKey ) {
  4387. if ( $size <= 0 ) {
  4388. return str_replace( '$1', $this->formatNum( $size ),
  4389. $this->getMessageFromDB( str_replace( '$1', '', $messageKey ) )
  4390. );
  4391. }
  4392. $sizes = [ '', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa', 'zeta', 'yotta' ];
  4393. $index = 0;
  4394. $maxIndex = count( $sizes ) - 1;
  4395. while ( $size >= $boundary && $index < $maxIndex ) {
  4396. $index++;
  4397. $size /= $boundary;
  4398. }
  4399. // For small sizes no decimal places necessary
  4400. $round = 0;
  4401. if ( $index > 1 ) {
  4402. // For MB and bigger two decimal places are smarter
  4403. $round = 2;
  4404. }
  4405. $msg = str_replace( '$1', $sizes[$index], $messageKey );
  4406. $size = round( $size, $round );
  4407. $text = $this->getMessageFromDB( $msg );
  4408. return str_replace( '$1', $this->formatNum( $size ), $text );
  4409. }
  4410. /**
  4411. * Format a size in bytes for output, using an appropriate
  4412. * unit (B, KB, MB, GB, TB, PB, EB, ZB or YB) according to the magnitude in question
  4413. *
  4414. * This method use base 1024. For base 1000 use formatBitrate(), for
  4415. * another base see formatComputingNumbers()
  4416. *
  4417. * @param int $size Size to format
  4418. * @return string Plain text (not HTML)
  4419. */
  4420. function formatSize( $size ) {
  4421. return $this->formatComputingNumbers( $size, 1024, "size-$1bytes" );
  4422. }
  4423. /**
  4424. * Make a list item, used by various special pages
  4425. *
  4426. * @param string $page Page link
  4427. * @param string $details HTML safe text between brackets
  4428. * @param bool $oppositedm Add the direction mark opposite to your
  4429. * language, to display text properly
  4430. * @return string HTML escaped
  4431. */
  4432. function specialList( $page, $details, $oppositedm = true ) {
  4433. if ( !$details ) {
  4434. return $page;
  4435. }
  4436. $dirmark = ( $oppositedm ? $this->getDirMark( true ) : '' ) . $this->getDirMark();
  4437. return $page .
  4438. $dirmark .
  4439. $this->msg( 'word-separator' )->escaped() .
  4440. $this->msg( 'parentheses' )->rawParams( $details )->escaped();
  4441. }
  4442. /**
  4443. * Generate (prev x| next x) (20|50|100...) type links for paging
  4444. *
  4445. * @param Title $title Title object to link
  4446. * @param int $offset
  4447. * @param int $limit
  4448. * @param array $query Optional URL query parameter string
  4449. * @param bool $atend Optional param for specified if this is the last page
  4450. * @return string
  4451. */
  4452. public function viewPrevNext( Title $title, $offset, $limit,
  4453. array $query = [], $atend = false
  4454. ) {
  4455. // @todo FIXME: Why on earth this needs one message for the text and another one for tooltip?
  4456. # Make 'previous' link
  4457. $prev = wfMessage( 'prevn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
  4458. if ( $offset > 0 ) {
  4459. $plink = $this->numLink( $title, max( $offset - $limit, 0 ), $limit,
  4460. $query, $prev, 'prevn-title', 'mw-prevlink' );
  4461. } else {
  4462. $plink = htmlspecialchars( $prev );
  4463. }
  4464. # Make 'next' link
  4465. $next = wfMessage( 'nextn' )->inLanguage( $this )->title( $title )->numParams( $limit )->text();
  4466. if ( $atend ) {
  4467. $nlink = htmlspecialchars( $next );
  4468. } else {
  4469. $nlink = $this->numLink( $title, $offset + $limit, $limit,
  4470. $query, $next, 'nextn-title', 'mw-nextlink' );
  4471. }
  4472. # Make links to set number of items per page
  4473. $numLinks = [];
  4474. foreach ( [ 20, 50, 100, 250, 500 ] as $num ) {
  4475. $numLinks[] = $this->numLink( $title, $offset, $num,
  4476. $query, $this->formatNum( $num ), 'shown-title', 'mw-numlink' );
  4477. }
  4478. return wfMessage( 'viewprevnext' )->inLanguage( $this )->title( $title
  4479. )->rawParams( $plink, $nlink, $this->pipeList( $numLinks ) )->escaped();
  4480. }
  4481. /**
  4482. * Helper function for viewPrevNext() that generates links
  4483. *
  4484. * @param Title $title Title object to link
  4485. * @param int $offset
  4486. * @param int $limit
  4487. * @param array $query Extra query parameters
  4488. * @param string $link Text to use for the link; will be escaped
  4489. * @param string $tooltipMsg Name of the message to use as tooltip
  4490. * @param string $class Value of the "class" attribute of the link
  4491. * @return string HTML fragment
  4492. */
  4493. private function numLink( Title $title, $offset, $limit, array $query, $link,
  4494. $tooltipMsg, $class
  4495. ) {
  4496. $query = [ 'limit' => $limit, 'offset' => $offset ] + $query;
  4497. $tooltip = wfMessage( $tooltipMsg )->inLanguage( $this )->title( $title )
  4498. ->numParams( $limit )->text();
  4499. return Html::element( 'a', [ 'href' => $title->getLocalURL( $query ),
  4500. 'title' => $tooltip, 'class' => $class ], $link );
  4501. }
  4502. /**
  4503. * Get the conversion rule title, if any.
  4504. *
  4505. * @return string
  4506. */
  4507. public function getConvRuleTitle() {
  4508. return $this->mConverter->getConvRuleTitle();
  4509. }
  4510. /**
  4511. * Get the compiled plural rules for the language
  4512. * @since 1.20
  4513. * @return array Associative array with plural form, and plural rule as key-value pairs
  4514. */
  4515. public function getCompiledPluralRules() {
  4516. $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'compiledPluralRules' );
  4517. $fallbacks = self::getFallbacksFor( $this->mCode );
  4518. if ( !$pluralRules ) {
  4519. foreach ( $fallbacks as $fallbackCode ) {
  4520. $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'compiledPluralRules' );
  4521. if ( $pluralRules ) {
  4522. break;
  4523. }
  4524. }
  4525. }
  4526. return $pluralRules;
  4527. }
  4528. /**
  4529. * Get the plural rules for the language
  4530. * @since 1.20
  4531. * @return array Associative array with plural form number and plural rule as key-value pairs
  4532. */
  4533. public function getPluralRules() {
  4534. $pluralRules = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRules' );
  4535. $fallbacks = self::getFallbacksFor( $this->mCode );
  4536. if ( !$pluralRules ) {
  4537. foreach ( $fallbacks as $fallbackCode ) {
  4538. $pluralRules = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRules' );
  4539. if ( $pluralRules ) {
  4540. break;
  4541. }
  4542. }
  4543. }
  4544. return $pluralRules;
  4545. }
  4546. /**
  4547. * Get the plural rule types for the language
  4548. * @since 1.22
  4549. * @return array Associative array with plural form number and plural rule type as key-value pairs
  4550. */
  4551. public function getPluralRuleTypes() {
  4552. $pluralRuleTypes = self::$dataCache->getItem( strtolower( $this->mCode ), 'pluralRuleTypes' );
  4553. $fallbacks = self::getFallbacksFor( $this->mCode );
  4554. if ( !$pluralRuleTypes ) {
  4555. foreach ( $fallbacks as $fallbackCode ) {
  4556. $pluralRuleTypes = self::$dataCache->getItem( strtolower( $fallbackCode ), 'pluralRuleTypes' );
  4557. if ( $pluralRuleTypes ) {
  4558. break;
  4559. }
  4560. }
  4561. }
  4562. return $pluralRuleTypes;
  4563. }
  4564. /**
  4565. * Find the index number of the plural rule appropriate for the given number
  4566. * @param int $number
  4567. * @return int The index number of the plural rule
  4568. */
  4569. public function getPluralRuleIndexNumber( $number ) {
  4570. $pluralRules = $this->getCompiledPluralRules();
  4571. $form = Evaluator::evaluateCompiled( $number, $pluralRules );
  4572. return $form;
  4573. }
  4574. /**
  4575. * Find the plural rule type appropriate for the given number
  4576. * For example, if the language is set to Arabic, getPluralType(5) should
  4577. * return 'few'.
  4578. * @since 1.22
  4579. * @param int $number
  4580. * @return string The name of the plural rule type, e.g. one, two, few, many
  4581. */
  4582. public function getPluralRuleType( $number ) {
  4583. $index = $this->getPluralRuleIndexNumber( $number );
  4584. $pluralRuleTypes = $this->getPluralRuleTypes();
  4585. if ( isset( $pluralRuleTypes[$index] ) ) {
  4586. return $pluralRuleTypes[$index];
  4587. } else {
  4588. return 'other';
  4589. }
  4590. }
  4591. }