functions.php 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320
  1. <?php
  2. /**
  3. * Main WordPress API
  4. *
  5. * @package WordPress
  6. */
  7. require( ABSPATH . WPINC . '/option.php' );
  8. /**
  9. * Convert given MySQL date string into a different format.
  10. *
  11. * `$format` should be a PHP date format string.
  12. * 'U' and 'G' formats will return a sum of timestamp with timezone offset.
  13. * `$date` is expected to be local time in MySQL format (`Y-m-d H:i:s`).
  14. *
  15. * Historically UTC time could be passed to the function to produce Unix timestamp.
  16. *
  17. * If `$translate` is true then the given date and format string will
  18. * be passed to `wp_date()` for translation.
  19. *
  20. * @since 0.71
  21. *
  22. * @param string $format Format of the date to return.
  23. * @param string $date Date string to convert.
  24. * @param bool $translate Whether the return date should be translated. Default true.
  25. * @return string|int|false Formatted date string or sum of Unix timestamp and timezone offset.
  26. * False on failure.
  27. */
  28. function mysql2date( $format, $date, $translate = true ) {
  29. if ( empty( $date ) ) {
  30. return false;
  31. }
  32. $datetime = date_create( $date, wp_timezone() );
  33. if ( false === $datetime ) {
  34. return false;
  35. }
  36. // Returns a sum of timestamp with timezone offset. Ideally should never be used.
  37. if ( 'G' === $format || 'U' === $format ) {
  38. return $datetime->getTimestamp() + $datetime->getOffset();
  39. }
  40. if ( $translate ) {
  41. return wp_date( $format, $datetime->getTimestamp() );
  42. }
  43. return $datetime->format( $format );
  44. }
  45. /**
  46. * Retrieves the current time based on specified type.
  47. *
  48. * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  49. * The 'timestamp' type will return the current timestamp or a sum of timestamp
  50. * and timezone offset, depending on `$gmt`.
  51. * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  52. *
  53. * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  54. * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  55. *
  56. * @since 1.0.0
  57. *
  58. * @param string $type Type of time to retrieve. Accepts 'mysql', 'timestamp',
  59. * or PHP date format string (e.g. 'Y-m-d').
  60. * @param int|bool $gmt Optional. Whether to use GMT timezone. Default false.
  61. * @return int|string Integer if $type is 'timestamp', string otherwise.
  62. */
  63. function current_time( $type, $gmt = 0 ) {
  64. // Don't use non-GMT timestamp, unless you know the difference and really need to.
  65. if ( 'timestamp' === $type || 'U' === $type ) {
  66. return $gmt ? time() : time() + (int) ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  67. }
  68. if ( 'mysql' === $type ) {
  69. $type = 'Y-m-d H:i:s';
  70. }
  71. $timezone = $gmt ? new DateTimeZone( 'UTC' ) : wp_timezone();
  72. $datetime = new DateTime( 'now', $timezone );
  73. return $datetime->format( $type );
  74. }
  75. /**
  76. * Retrieves the current time as an object with the timezone from settings.
  77. *
  78. * @since 5.3.0
  79. *
  80. * @return DateTimeImmutable Date and time object.
  81. */
  82. function current_datetime() {
  83. return new DateTimeImmutable( 'now', wp_timezone() );
  84. }
  85. /**
  86. * Retrieves the timezone from site settings as a string.
  87. *
  88. * Uses the `timezone_string` option to get a proper timezone if available,
  89. * otherwise falls back to an offset.
  90. *
  91. * @since 5.3.0
  92. *
  93. * @return string PHP timezone string or a ±HH:MM offset.
  94. */
  95. function wp_timezone_string() {
  96. $timezone_string = get_option( 'timezone_string' );
  97. if ( $timezone_string ) {
  98. return $timezone_string;
  99. }
  100. $offset = (float) get_option( 'gmt_offset' );
  101. $hours = (int) $offset;
  102. $minutes = ( $offset - $hours );
  103. $sign = ( $offset < 0 ) ? '-' : '+';
  104. $abs_hour = abs( $hours );
  105. $abs_mins = abs( $minutes * 60 );
  106. $tz_offset = sprintf( '%s%02d:%02d', $sign, $abs_hour, $abs_mins );
  107. return $tz_offset;
  108. }
  109. /**
  110. * Retrieves the timezone from site settings as a `DateTimeZone` object.
  111. *
  112. * Timezone can be based on a PHP timezone string or a ±HH:MM offset.
  113. *
  114. * @since 5.3.0
  115. *
  116. * @return DateTimeZone Timezone object.
  117. */
  118. function wp_timezone() {
  119. return new DateTimeZone( wp_timezone_string() );
  120. }
  121. /**
  122. * Retrieves the date in localized format, based on a sum of Unix timestamp and
  123. * timezone offset in seconds.
  124. *
  125. * If the locale specifies the locale month and weekday, then the locale will
  126. * take over the format for the date. If it isn't, then the date format string
  127. * will be used instead.
  128. *
  129. * Note that due to the way WP typically generates a sum of timestamp and offset
  130. * with `strtotime()`, it implies offset added at a _current_ time, not at the time
  131. * the timestamp represents. Storing such timestamps or calculating them differently
  132. * will lead to invalid output.
  133. *
  134. * @since 0.71
  135. * @since 5.3.0 Converted into a wrapper for wp_date().
  136. *
  137. * @global WP_Locale $wp_locale WordPress date and time locale object.
  138. *
  139. * @param string $format Format to display the date.
  140. * @param int|bool $timestamp_with_offset Optional. A sum of Unix timestamp and timezone offset
  141. * in seconds. Default false.
  142. * @param bool $gmt Optional. Whether to use GMT timezone. Only applies
  143. * if timestamp is not provided. Default false.
  144. * @return string The date, translated if locale specifies it.
  145. */
  146. function date_i18n( $format, $timestamp_with_offset = false, $gmt = false ) {
  147. $timestamp = $timestamp_with_offset;
  148. // If timestamp is omitted it should be current time (summed with offset, unless `$gmt` is true).
  149. if ( ! is_numeric( $timestamp ) ) {
  150. $timestamp = current_time( 'timestamp', $gmt );
  151. }
  152. /*
  153. * This is a legacy implementation quirk that the returned timestamp is also with offset.
  154. * Ideally this function should never be used to produce a timestamp.
  155. */
  156. if ( 'U' === $format ) {
  157. $date = $timestamp;
  158. } elseif ( $gmt && false === $timestamp_with_offset ) { // Current time in UTC.
  159. $date = wp_date( $format, null, new DateTimeZone( 'UTC' ) );
  160. } elseif ( false === $timestamp_with_offset ) { // Current time in site's timezone.
  161. $date = wp_date( $format );
  162. } else {
  163. /*
  164. * Timestamp with offset is typically produced by a UTC `strtotime()` call on an input without timezone.
  165. * This is the best attempt to reverse that operation into a local time to use.
  166. */
  167. $local_time = gmdate( 'Y-m-d H:i:s', $timestamp );
  168. $timezone = wp_timezone();
  169. $datetime = date_create( $local_time, $timezone );
  170. $date = wp_date( $format, $datetime->getTimestamp(), $timezone );
  171. }
  172. /**
  173. * Filters the date formatted based on the locale.
  174. *
  175. * @since 2.8.0
  176. *
  177. * @param string $date Formatted date string.
  178. * @param string $format Format to display the date.
  179. * @param int $timestamp A sum of Unix timestamp and timezone offset in seconds.
  180. * Might be without offset if input omitted timestamp but requested GMT.
  181. * @param bool $gmt Whether to use GMT timezone. Only applies if timestamp was not provided.
  182. * Default false.
  183. */
  184. $date = apply_filters( 'date_i18n', $date, $format, $timestamp, $gmt );
  185. return $date;
  186. }
  187. /**
  188. * Retrieves the date, in localized format.
  189. *
  190. * This is a newer function, intended to replace `date_i18n()` without legacy quirks in it.
  191. *
  192. * Note that, unlike `date_i18n()`, this function accepts a true Unix timestamp, not summed
  193. * with timezone offset.
  194. *
  195. * @since 5.3.0
  196. *
  197. * @param string $format PHP date format.
  198. * @param int $timestamp Optional. Unix timestamp. Defaults to current time.
  199. * @param DateTimeZone $timezone Optional. Timezone to output result in. Defaults to timezone
  200. * from site settings.
  201. * @return string|false The date, translated if locale specifies it. False on invalid timestamp input.
  202. */
  203. function wp_date( $format, $timestamp = null, $timezone = null ) {
  204. global $wp_locale;
  205. if ( null === $timestamp ) {
  206. $timestamp = time();
  207. } elseif ( ! is_numeric( $timestamp ) ) {
  208. return false;
  209. }
  210. if ( ! $timezone ) {
  211. $timezone = wp_timezone();
  212. }
  213. $datetime = date_create( '@' . $timestamp );
  214. $datetime->setTimezone( $timezone );
  215. if ( empty( $wp_locale->month ) || empty( $wp_locale->weekday ) ) {
  216. $date = $datetime->format( $format );
  217. } else {
  218. // We need to unpack shorthand `r` format because it has parts that might be localized.
  219. $format = preg_replace( '/(?<!\\\\)r/', DATE_RFC2822, $format );
  220. $new_format = '';
  221. $format_length = strlen( $format );
  222. $month = $wp_locale->get_month( $datetime->format( 'm' ) );
  223. $weekday = $wp_locale->get_weekday( $datetime->format( 'w' ) );
  224. for ( $i = 0; $i < $format_length; $i ++ ) {
  225. switch ( $format[ $i ] ) {
  226. case 'D':
  227. $new_format .= addcslashes( $wp_locale->get_weekday_abbrev( $weekday ), '\\A..Za..z' );
  228. break;
  229. case 'F':
  230. $new_format .= addcslashes( $month, '\\A..Za..z' );
  231. break;
  232. case 'l':
  233. $new_format .= addcslashes( $weekday, '\\A..Za..z' );
  234. break;
  235. case 'M':
  236. $new_format .= addcslashes( $wp_locale->get_month_abbrev( $month ), '\\A..Za..z' );
  237. break;
  238. case 'a':
  239. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'a' ) ), '\\A..Za..z' );
  240. break;
  241. case 'A':
  242. $new_format .= addcslashes( $wp_locale->get_meridiem( $datetime->format( 'A' ) ), '\\A..Za..z' );
  243. break;
  244. case '\\':
  245. $new_format .= $format[ $i ];
  246. // If character follows a slash, we add it without translating.
  247. if ( $i < $format_length ) {
  248. $new_format .= $format[ ++$i ];
  249. }
  250. break;
  251. default:
  252. $new_format .= $format[ $i ];
  253. break;
  254. }
  255. }
  256. $date = $datetime->format( $new_format );
  257. $date = wp_maybe_decline_date( $date );
  258. }
  259. /**
  260. * Filters the date formatted based on the locale.
  261. *
  262. * @since 5.3.0
  263. *
  264. * @param string $date Formatted date string.
  265. * @param string $format Format to display the date.
  266. * @param int $timestamp Unix timestamp.
  267. * @param DateTimeZone $timezone Timezone.
  268. *
  269. */
  270. $date = apply_filters( 'wp_date', $date, $format, $timestamp, $timezone );
  271. return $date;
  272. }
  273. /**
  274. * Determines if the date should be declined.
  275. *
  276. * If the locale specifies that month names require a genitive case in certain
  277. * formats (like 'j F Y'), the month name will be replaced with a correct form.
  278. *
  279. * @since 4.4.0
  280. *
  281. * @global WP_Locale $wp_locale WordPress date and time locale object.
  282. *
  283. * @param string $date Formatted date string.
  284. * @return string The date, declined if locale specifies it.
  285. */
  286. function wp_maybe_decline_date( $date ) {
  287. global $wp_locale;
  288. // i18n functions are not available in SHORTINIT mode
  289. if ( ! function_exists( '_x' ) ) {
  290. return $date;
  291. }
  292. /*
  293. * translators: If months in your language require a genitive case,
  294. * translate this to 'on'. Do not translate into your own language.
  295. */
  296. if ( 'on' === _x( 'off', 'decline months names: on or off' ) ) {
  297. $months = $wp_locale->month;
  298. $months_genitive = $wp_locale->month_genitive;
  299. // Match a format like 'j F Y' or 'j. F'
  300. if ( preg_match( '#^\d{1,2}\.? [^\d ]+#u', $date ) ) {
  301. foreach ( $months as $key => $month ) {
  302. $months[ $key ] = '# ' . $month . '( |$)#u';
  303. }
  304. foreach ( $months_genitive as $key => $month ) {
  305. $months_genitive[ $key ] = ' ' . $month . '$1';
  306. }
  307. $date = preg_replace( $months, $months_genitive, $date );
  308. }
  309. // Match a format like 'F jS' or 'F j' and change it to 'j F'
  310. if ( preg_match( '#^[^\d ]+ \d{1,2}(st|nd|rd|th)? #u', trim( $date ) ) ) {
  311. foreach ( $months as $key => $month ) {
  312. $months[ $key ] = '#' . $month . ' (\d{1,2})(st|nd|rd|th)?#u';
  313. }
  314. foreach ( $months_genitive as $key => $month ) {
  315. $months_genitive[ $key ] = '$1 ' . $month;
  316. }
  317. $date = preg_replace( $months, $months_genitive, $date );
  318. }
  319. }
  320. // Used for locale-specific rules
  321. $locale = get_locale();
  322. if ( 'ca' === $locale ) {
  323. // " de abril| de agost| de octubre..." -> " d'abril| d'agost| d'octubre..."
  324. $date = preg_replace( '# de ([ao])#i', " d'\\1", $date );
  325. }
  326. return $date;
  327. }
  328. /**
  329. * Convert float number to format based on the locale.
  330. *
  331. * @since 2.3.0
  332. *
  333. * @global WP_Locale $wp_locale WordPress date and time locale object.
  334. *
  335. * @param float $number The number to convert based on locale.
  336. * @param int $decimals Optional. Precision of the number of decimal places. Default 0.
  337. * @return string Converted number in string format.
  338. */
  339. function number_format_i18n( $number, $decimals = 0 ) {
  340. global $wp_locale;
  341. if ( isset( $wp_locale ) ) {
  342. $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  343. } else {
  344. $formatted = number_format( $number, absint( $decimals ) );
  345. }
  346. /**
  347. * Filters the number formatted based on the locale.
  348. *
  349. * @since 2.8.0
  350. * @since 4.9.0 The `$number` and `$decimals` parameters were added.
  351. *
  352. * @param string $formatted Converted number in string format.
  353. * @param float $number The number to convert based on locale.
  354. * @param int $decimals Precision of the number of decimal places.
  355. */
  356. return apply_filters( 'number_format_i18n', $formatted, $number, $decimals );
  357. }
  358. /**
  359. * Convert number of bytes largest unit bytes will fit into.
  360. *
  361. * It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts
  362. * number of bytes to human readable number by taking the number of that unit
  363. * that the bytes will go into it. Supports TB value.
  364. *
  365. * Please note that integers in PHP are limited to 32 bits, unless they are on
  366. * 64 bit architecture, then they have 64 bit size. If you need to place the
  367. * larger size then what PHP integer type will hold, then use a string. It will
  368. * be converted to a double, which should always have 64 bit length.
  369. *
  370. * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  371. *
  372. * @since 2.3.0
  373. *
  374. * @param int|string $bytes Number of bytes. Note max integer size for integers.
  375. * @param int $decimals Optional. Precision of number of decimal places. Default 0.
  376. * @return string|false False on failure. Number string on success.
  377. */
  378. function size_format( $bytes, $decimals = 0 ) {
  379. $quant = array(
  380. 'TB' => TB_IN_BYTES,
  381. 'GB' => GB_IN_BYTES,
  382. 'MB' => MB_IN_BYTES,
  383. 'KB' => KB_IN_BYTES,
  384. 'B' => 1,
  385. );
  386. if ( 0 === $bytes ) {
  387. return number_format_i18n( 0, $decimals ) . ' B';
  388. }
  389. foreach ( $quant as $unit => $mag ) {
  390. if ( doubleval( $bytes ) >= $mag ) {
  391. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  392. }
  393. }
  394. return false;
  395. }
  396. /**
  397. * Convert a duration to human readable format.
  398. *
  399. * @since 5.1.0
  400. *
  401. * @param string $duration Duration will be in string format (HH:ii:ss) OR (ii:ss),
  402. * with a possible prepended negative sign (-).
  403. * @return string|false A human readable duration string, false on failure.
  404. */
  405. function human_readable_duration( $duration = '' ) {
  406. if ( ( empty( $duration ) || ! is_string( $duration ) ) ) {
  407. return false;
  408. }
  409. $duration = trim( $duration );
  410. // Remove prepended negative sign.
  411. if ( '-' === substr( $duration, 0, 1 ) ) {
  412. $duration = substr( $duration, 1 );
  413. }
  414. // Extract duration parts.
  415. $duration_parts = array_reverse( explode( ':', $duration ) );
  416. $duration_count = count( $duration_parts );
  417. $hour = null;
  418. $minute = null;
  419. $second = null;
  420. if ( 3 === $duration_count ) {
  421. // Validate HH:ii:ss duration format.
  422. if ( ! ( (bool) preg_match( '/^([0-9]+):([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  423. return false;
  424. }
  425. // Three parts: hours, minutes & seconds.
  426. list( $second, $minute, $hour ) = $duration_parts;
  427. } elseif ( 2 === $duration_count ) {
  428. // Validate ii:ss duration format.
  429. if ( ! ( (bool) preg_match( '/^([0-5]?[0-9]):([0-5]?[0-9])$/', $duration ) ) ) {
  430. return false;
  431. }
  432. // Two parts: minutes & seconds.
  433. list( $second, $minute ) = $duration_parts;
  434. } else {
  435. return false;
  436. }
  437. $human_readable_duration = array();
  438. // Add the hour part to the string.
  439. if ( is_numeric( $hour ) ) {
  440. /* translators: %s: Time duration in hour or hours. */
  441. $human_readable_duration[] = sprintf( _n( '%s hour', '%s hours', $hour ), (int) $hour );
  442. }
  443. // Add the minute part to the string.
  444. if ( is_numeric( $minute ) ) {
  445. /* translators: %s: Time duration in minute or minutes. */
  446. $human_readable_duration[] = sprintf( _n( '%s minute', '%s minutes', $minute ), (int) $minute );
  447. }
  448. // Add the second part to the string.
  449. if ( is_numeric( $second ) ) {
  450. /* translators: %s: Time duration in second or seconds. */
  451. $human_readable_duration[] = sprintf( _n( '%s second', '%s seconds', $second ), (int) $second );
  452. }
  453. return implode( ', ', $human_readable_duration );
  454. }
  455. /**
  456. * Get the week start and end from the datetime or date string from MySQL.
  457. *
  458. * @since 0.71
  459. *
  460. * @param string $mysqlstring Date or datetime field type from MySQL.
  461. * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
  462. * @return array Keys are 'start' and 'end'.
  463. */
  464. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  465. // MySQL string year.
  466. $my = substr( $mysqlstring, 0, 4 );
  467. // MySQL string month.
  468. $mm = substr( $mysqlstring, 8, 2 );
  469. // MySQL string day.
  470. $md = substr( $mysqlstring, 5, 2 );
  471. // The timestamp for MySQL string day.
  472. $day = mktime( 0, 0, 0, $md, $mm, $my );
  473. // The day of the week from the timestamp.
  474. $weekday = gmdate( 'w', $day );
  475. if ( ! is_numeric( $start_of_week ) ) {
  476. $start_of_week = get_option( 'start_of_week' );
  477. }
  478. if ( $weekday < $start_of_week ) {
  479. $weekday += 7;
  480. }
  481. // The most recent week start day on or before $day.
  482. $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
  483. // $start + 1 week - 1 second.
  484. $end = $start + WEEK_IN_SECONDS - 1;
  485. return compact( 'start', 'end' );
  486. }
  487. /**
  488. * Unserialize value only if it was serialized.
  489. *
  490. * @since 2.0.0
  491. *
  492. * @param string $original Maybe unserialized original, if is needed.
  493. * @return mixed Unserialized data can be any type.
  494. */
  495. function maybe_unserialize( $original ) {
  496. if ( is_serialized( $original ) ) { // don't attempt to unserialize data that wasn't serialized going in
  497. return @unserialize( $original );
  498. }
  499. return $original;
  500. }
  501. /**
  502. * Check value to find if it was serialized.
  503. *
  504. * If $data is not an string, then returned value will always be false.
  505. * Serialized data is always a string.
  506. *
  507. * @since 2.0.5
  508. *
  509. * @param string $data Value to check to see if was serialized.
  510. * @param bool $strict Optional. Whether to be strict about the end of the string. Default true.
  511. * @return bool False if not serialized and true if it was.
  512. */
  513. function is_serialized( $data, $strict = true ) {
  514. // if it isn't a string, it isn't serialized.
  515. if ( ! is_string( $data ) ) {
  516. return false;
  517. }
  518. $data = trim( $data );
  519. if ( 'N;' == $data ) {
  520. return true;
  521. }
  522. if ( strlen( $data ) < 4 ) {
  523. return false;
  524. }
  525. if ( ':' !== $data[1] ) {
  526. return false;
  527. }
  528. if ( $strict ) {
  529. $lastc = substr( $data, -1 );
  530. if ( ';' !== $lastc && '}' !== $lastc ) {
  531. return false;
  532. }
  533. } else {
  534. $semicolon = strpos( $data, ';' );
  535. $brace = strpos( $data, '}' );
  536. // Either ; or } must exist.
  537. if ( false === $semicolon && false === $brace ) {
  538. return false;
  539. }
  540. // But neither must be in the first X characters.
  541. if ( false !== $semicolon && $semicolon < 3 ) {
  542. return false;
  543. }
  544. if ( false !== $brace && $brace < 4 ) {
  545. return false;
  546. }
  547. }
  548. $token = $data[0];
  549. switch ( $token ) {
  550. case 's':
  551. if ( $strict ) {
  552. if ( '"' !== substr( $data, -2, 1 ) ) {
  553. return false;
  554. }
  555. } elseif ( false === strpos( $data, '"' ) ) {
  556. return false;
  557. }
  558. // or else fall through
  559. case 'a':
  560. case 'O':
  561. return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  562. case 'b':
  563. case 'i':
  564. case 'd':
  565. $end = $strict ? '$' : '';
  566. return (bool) preg_match( "/^{$token}:[0-9.E+-]+;$end/", $data );
  567. }
  568. return false;
  569. }
  570. /**
  571. * Check whether serialized data is of string type.
  572. *
  573. * @since 2.0.5
  574. *
  575. * @param string $data Serialized data.
  576. * @return bool False if not a serialized string, true if it is.
  577. */
  578. function is_serialized_string( $data ) {
  579. // if it isn't a string, it isn't a serialized string.
  580. if ( ! is_string( $data ) ) {
  581. return false;
  582. }
  583. $data = trim( $data );
  584. if ( strlen( $data ) < 4 ) {
  585. return false;
  586. } elseif ( ':' !== $data[1] ) {
  587. return false;
  588. } elseif ( ';' !== substr( $data, -1 ) ) {
  589. return false;
  590. } elseif ( $data[0] !== 's' ) {
  591. return false;
  592. } elseif ( '"' !== substr( $data, -2, 1 ) ) {
  593. return false;
  594. } else {
  595. return true;
  596. }
  597. }
  598. /**
  599. * Serialize data, if needed.
  600. *
  601. * @since 2.0.5
  602. *
  603. * @param string|array|object $data Data that might be serialized.
  604. * @return mixed A scalar data
  605. */
  606. function maybe_serialize( $data ) {
  607. if ( is_array( $data ) || is_object( $data ) ) {
  608. return serialize( $data );
  609. }
  610. // Double serialization is required for backward compatibility.
  611. // See https://core.trac.wordpress.org/ticket/12930
  612. // Also the world will end. See WP 3.6.1.
  613. if ( is_serialized( $data, false ) ) {
  614. return serialize( $data );
  615. }
  616. return $data;
  617. }
  618. /**
  619. * Retrieve post title from XMLRPC XML.
  620. *
  621. * If the title element is not part of the XML, then the default post title from
  622. * the $post_default_title will be used instead.
  623. *
  624. * @since 0.71
  625. *
  626. * @global string $post_default_title Default XML-RPC post title.
  627. *
  628. * @param string $content XMLRPC XML Request content
  629. * @return string Post title
  630. */
  631. function xmlrpc_getposttitle( $content ) {
  632. global $post_default_title;
  633. if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  634. $post_title = $matchtitle[1];
  635. } else {
  636. $post_title = $post_default_title;
  637. }
  638. return $post_title;
  639. }
  640. /**
  641. * Retrieve the post category or categories from XMLRPC XML.
  642. *
  643. * If the category element is not found, then the default post category will be
  644. * used. The return type then would be what $post_default_category. If the
  645. * category is found, then it will always be an array.
  646. *
  647. * @since 0.71
  648. *
  649. * @global string $post_default_category Default XML-RPC post category.
  650. *
  651. * @param string $content XMLRPC XML Request content
  652. * @return string|array List of categories or category name.
  653. */
  654. function xmlrpc_getpostcategory( $content ) {
  655. global $post_default_category;
  656. if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  657. $post_category = trim( $matchcat[1], ',' );
  658. $post_category = explode( ',', $post_category );
  659. } else {
  660. $post_category = $post_default_category;
  661. }
  662. return $post_category;
  663. }
  664. /**
  665. * XMLRPC XML content without title and category elements.
  666. *
  667. * @since 0.71
  668. *
  669. * @param string $content XML-RPC XML Request content.
  670. * @return string XMLRPC XML Request content without title and category elements.
  671. */
  672. function xmlrpc_removepostdata( $content ) {
  673. $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  674. $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  675. $content = trim( $content );
  676. return $content;
  677. }
  678. /**
  679. * Use RegEx to extract URLs from arbitrary content.
  680. *
  681. * @since 3.7.0
  682. *
  683. * @param string $content Content to extract URLs from.
  684. * @return array URLs found in passed string.
  685. */
  686. function wp_extract_urls( $content ) {
  687. preg_match_all(
  688. "#([\"']?)("
  689. . '(?:([\w-]+:)?//?)'
  690. . '[^\s()<>]+'
  691. . '[.]'
  692. . '(?:'
  693. . '\([\w\d]+\)|'
  694. . '(?:'
  695. . "[^`!()\[\]{};:'\".,<>«»“”‘’\s]|"
  696. . '(?:[:]\d+)?/?'
  697. . ')+'
  698. . ')'
  699. . ")\\1#",
  700. $content,
  701. $post_links
  702. );
  703. $post_links = array_unique( array_map( 'html_entity_decode', $post_links[2] ) );
  704. return array_values( $post_links );
  705. }
  706. /**
  707. * Check content for video and audio links to add as enclosures.
  708. *
  709. * Will not add enclosures that have already been added and will
  710. * remove enclosures that are no longer in the post. This is called as
  711. * pingbacks and trackbacks.
  712. *
  713. * @since 1.5.0
  714. * @since 5.3.0 The `$content` parameter was made optional, and the `$post` parameter was
  715. * updated to accept a post ID or a WP_Post object.
  716. *
  717. * @global wpdb $wpdb WordPress database abstraction object.
  718. *
  719. * @param string $content Post content. If `null`, the `post_content` field from `$post` is used.
  720. * @param int|WP_Post $post Post ID or post object.
  721. * @return null|bool Returns false if post is not found.
  722. */
  723. function do_enclose( $content = null, $post ) {
  724. global $wpdb;
  725. // @todo Tidy this code and make the debug code optional.
  726. include_once( ABSPATH . WPINC . '/class-IXR.php' );
  727. $post = get_post( $post );
  728. if ( ! $post ) {
  729. return false;
  730. }
  731. if ( null === $content ) {
  732. $content = $post->post_content;
  733. }
  734. $post_links = array();
  735. $pung = get_enclosed( $post->ID );
  736. $post_links_temp = wp_extract_urls( $content );
  737. foreach ( $pung as $link_test ) {
  738. // Link is no longer in post.
  739. if ( ! in_array( $link_test, $post_links_temp, true ) ) {
  740. $mids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post->ID, $wpdb->esc_like( $link_test ) . '%' ) );
  741. foreach ( $mids as $mid ) {
  742. delete_metadata_by_mid( 'post', $mid );
  743. }
  744. }
  745. }
  746. foreach ( (array) $post_links_temp as $link_test ) {
  747. // If we haven't pung it already.
  748. if ( ! in_array( $link_test, $pung, true ) ) {
  749. $test = @parse_url( $link_test );
  750. if ( false === $test ) {
  751. continue;
  752. }
  753. if ( isset( $test['query'] ) ) {
  754. $post_links[] = $link_test;
  755. } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
  756. $post_links[] = $link_test;
  757. }
  758. }
  759. }
  760. /**
  761. * Filters the list of enclosure links before querying the database.
  762. *
  763. * Allows for the addition and/or removal of potential enclosures to save
  764. * to postmeta before checking the database for existing enclosures.
  765. *
  766. * @since 4.4.0
  767. *
  768. * @param array $post_links An array of enclosure links.
  769. * @param int $post_ID Post ID.
  770. */
  771. $post_links = apply_filters( 'enclosure_links', $post_links, $post->ID );
  772. foreach ( (array) $post_links as $url ) {
  773. if ( '' !== $url && ! $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post->ID, $wpdb->esc_like( $url ) . '%' ) ) ) {
  774. $headers = wp_get_http_headers( $url );
  775. if ( $headers ) {
  776. $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  777. $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  778. $allowed_types = array( 'video', 'audio' );
  779. // Check to see if we can figure out the mime type from
  780. // the extension
  781. $url_parts = @parse_url( $url );
  782. if ( false !== $url_parts ) {
  783. $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  784. if ( ! empty( $extension ) ) {
  785. foreach ( wp_get_mime_types() as $exts => $mime ) {
  786. if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  787. $type = $mime;
  788. break;
  789. }
  790. }
  791. }
  792. }
  793. if ( in_array( substr( $type, 0, strpos( $type, '/' ) ), $allowed_types, true ) ) {
  794. add_post_meta( $post->ID, 'enclosure', "$url\n$len\n$mime\n" );
  795. }
  796. }
  797. }
  798. }
  799. }
  800. /**
  801. * Retrieve HTTP Headers from URL.
  802. *
  803. * @since 1.5.1
  804. *
  805. * @param string $url URL to retrieve HTTP headers from.
  806. * @param bool $deprecated Not Used.
  807. * @return bool|string False on failure, headers on success.
  808. */
  809. function wp_get_http_headers( $url, $deprecated = false ) {
  810. if ( ! empty( $deprecated ) ) {
  811. _deprecated_argument( __FUNCTION__, '2.7.0' );
  812. }
  813. $response = wp_safe_remote_head( $url );
  814. if ( is_wp_error( $response ) ) {
  815. return false;
  816. }
  817. return wp_remote_retrieve_headers( $response );
  818. }
  819. /**
  820. * Determines whether the publish date of the current post in the loop is different
  821. * from the publish date of the previous post in the loop.
  822. *
  823. * For more information on this and similar theme functions, check out
  824. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  825. * Conditional Tags} article in the Theme Developer Handbook.
  826. *
  827. * @since 0.71
  828. *
  829. * @global string $currentday The day of the current post in the loop.
  830. * @global string $previousday The day of the previous post in the loop.
  831. *
  832. * @return int 1 when new day, 0 if not a new day.
  833. */
  834. function is_new_day() {
  835. global $currentday, $previousday;
  836. if ( $currentday !== $previousday ) {
  837. return 1;
  838. } else {
  839. return 0;
  840. }
  841. }
  842. /**
  843. * Build URL query based on an associative and, or indexed array.
  844. *
  845. * This is a convenient function for easily building url queries. It sets the
  846. * separator to '&' and uses _http_build_query() function.
  847. *
  848. * @since 2.3.0
  849. *
  850. * @see _http_build_query() Used to build the query
  851. * @link https://secure.php.net/manual/en/function.http-build-query.php for more on what
  852. * http_build_query() does.
  853. *
  854. * @param array $data URL-encode key/value pairs.
  855. * @return string URL-encoded string.
  856. */
  857. function build_query( $data ) {
  858. return _http_build_query( $data, null, '&', '', false );
  859. }
  860. /**
  861. * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
  862. *
  863. * @since 3.2.0
  864. * @access private
  865. *
  866. * @see https://secure.php.net/manual/en/function.http-build-query.php
  867. *
  868. * @param array|object $data An array or object of data. Converted to array.
  869. * @param string $prefix Optional. Numeric index. If set, start parameter numbering with it.
  870. * Default null.
  871. * @param string $sep Optional. Argument separator; defaults to 'arg_separator.output'.
  872. * Default null.
  873. * @param string $key Optional. Used to prefix key name. Default empty.
  874. * @param bool $urlencode Optional. Whether to use urlencode() in the result. Default true.
  875. *
  876. * @return string The query string.
  877. */
  878. function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
  879. $ret = array();
  880. foreach ( (array) $data as $k => $v ) {
  881. if ( $urlencode ) {
  882. $k = urlencode( $k );
  883. }
  884. if ( is_int( $k ) && $prefix != null ) {
  885. $k = $prefix . $k;
  886. }
  887. if ( ! empty( $key ) ) {
  888. $k = $key . '%5B' . $k . '%5D';
  889. }
  890. if ( $v === null ) {
  891. continue;
  892. } elseif ( $v === false ) {
  893. $v = '0';
  894. }
  895. if ( is_array( $v ) || is_object( $v ) ) {
  896. array_push( $ret, _http_build_query( $v, '', $sep, $k, $urlencode ) );
  897. } elseif ( $urlencode ) {
  898. array_push( $ret, $k . '=' . urlencode( $v ) );
  899. } else {
  900. array_push( $ret, $k . '=' . $v );
  901. }
  902. }
  903. if ( null === $sep ) {
  904. $sep = ini_get( 'arg_separator.output' );
  905. }
  906. return implode( $sep, $ret );
  907. }
  908. /**
  909. * Retrieves a modified URL query string.
  910. *
  911. * You can rebuild the URL and append query variables to the URL query by using this function.
  912. * There are two ways to use this function; either a single key and value, or an associative array.
  913. *
  914. * Using a single key and value:
  915. *
  916. * add_query_arg( 'key', 'value', 'http://example.com' );
  917. *
  918. * Using an associative array:
  919. *
  920. * add_query_arg( array(
  921. * 'key1' => 'value1',
  922. * 'key2' => 'value2',
  923. * ), 'http://example.com' );
  924. *
  925. * Omitting the URL from either use results in the current URL being used
  926. * (the value of `$_SERVER['REQUEST_URI']`).
  927. *
  928. * Values are expected to be encoded appropriately with urlencode() or rawurlencode().
  929. *
  930. * Setting any query variable's value to boolean false removes the key (see remove_query_arg()).
  931. *
  932. * Important: The return value of add_query_arg() is not escaped by default. Output should be
  933. * late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting
  934. * (XSS) attacks.
  935. *
  936. * @since 1.5.0
  937. * @since 5.3.0 Formalized the existing and already documented parameters
  938. * by adding `...$args` to the function signature.
  939. *
  940. * @param string|array $key Either a query variable key, or an associative array of query variables.
  941. * @param string $value Optional. Either a query variable value, or a URL to act upon.
  942. * @param string $url Optional. A URL to act upon.
  943. * @return string New URL query string (unescaped).
  944. */
  945. function add_query_arg( ...$args ) {
  946. if ( is_array( $args[0] ) ) {
  947. if ( count( $args ) < 2 || false === $args[1] ) {
  948. $uri = $_SERVER['REQUEST_URI'];
  949. } else {
  950. $uri = $args[1];
  951. }
  952. } else {
  953. if ( count( $args ) < 3 || false === $args[2] ) {
  954. $uri = $_SERVER['REQUEST_URI'];
  955. } else {
  956. $uri = $args[2];
  957. }
  958. }
  959. $frag = strstr( $uri, '#' );
  960. if ( $frag ) {
  961. $uri = substr( $uri, 0, -strlen( $frag ) );
  962. } else {
  963. $frag = '';
  964. }
  965. if ( 0 === stripos( $uri, 'http://' ) ) {
  966. $protocol = 'http://';
  967. $uri = substr( $uri, 7 );
  968. } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  969. $protocol = 'https://';
  970. $uri = substr( $uri, 8 );
  971. } else {
  972. $protocol = '';
  973. }
  974. if ( strpos( $uri, '?' ) !== false ) {
  975. list( $base, $query ) = explode( '?', $uri, 2 );
  976. $base .= '?';
  977. } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  978. $base = $uri . '?';
  979. $query = '';
  980. } else {
  981. $base = '';
  982. $query = $uri;
  983. }
  984. wp_parse_str( $query, $qs );
  985. $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  986. if ( is_array( $args[0] ) ) {
  987. foreach ( $args[0] as $k => $v ) {
  988. $qs[ $k ] = $v;
  989. }
  990. } else {
  991. $qs[ $args[0] ] = $args[1];
  992. }
  993. foreach ( $qs as $k => $v ) {
  994. if ( $v === false ) {
  995. unset( $qs[ $k ] );
  996. }
  997. }
  998. $ret = build_query( $qs );
  999. $ret = trim( $ret, '?' );
  1000. $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  1001. $ret = $protocol . $base . $ret . $frag;
  1002. $ret = rtrim( $ret, '?' );
  1003. return $ret;
  1004. }
  1005. /**
  1006. * Removes an item or items from a query string.
  1007. *
  1008. * @since 1.5.0
  1009. *
  1010. * @param string|array $key Query key or keys to remove.
  1011. * @param bool|string $query Optional. When false uses the current URL. Default false.
  1012. * @return string New URL query string.
  1013. */
  1014. function remove_query_arg( $key, $query = false ) {
  1015. if ( is_array( $key ) ) { // removing multiple keys
  1016. foreach ( $key as $k ) {
  1017. $query = add_query_arg( $k, false, $query );
  1018. }
  1019. return $query;
  1020. }
  1021. return add_query_arg( $key, false, $query );
  1022. }
  1023. /**
  1024. * Returns an array of single-use query variable names that can be removed from a URL.
  1025. *
  1026. * @since 4.4.0
  1027. *
  1028. * @return array An array of parameters to remove from the URL.
  1029. */
  1030. function wp_removable_query_args() {
  1031. $removable_query_args = array(
  1032. 'activate',
  1033. 'activated',
  1034. 'approved',
  1035. 'deactivate',
  1036. 'deleted',
  1037. 'disabled',
  1038. 'enabled',
  1039. 'error',
  1040. 'hotkeys_highlight_first',
  1041. 'hotkeys_highlight_last',
  1042. 'locked',
  1043. 'message',
  1044. 'same',
  1045. 'saved',
  1046. 'settings-updated',
  1047. 'skipped',
  1048. 'spammed',
  1049. 'trashed',
  1050. 'unspammed',
  1051. 'untrashed',
  1052. 'update',
  1053. 'updated',
  1054. 'wp-post-new-reload',
  1055. );
  1056. /**
  1057. * Filters the list of query variables to remove.
  1058. *
  1059. * @since 4.2.0
  1060. *
  1061. * @param array $removable_query_args An array of query variables to remove from a URL.
  1062. */
  1063. return apply_filters( 'removable_query_args', $removable_query_args );
  1064. }
  1065. /**
  1066. * Walks the array while sanitizing the contents.
  1067. *
  1068. * @since 0.71
  1069. *
  1070. * @param array $array Array to walk while sanitizing contents.
  1071. * @return array Sanitized $array.
  1072. */
  1073. function add_magic_quotes( $array ) {
  1074. foreach ( (array) $array as $k => $v ) {
  1075. if ( is_array( $v ) ) {
  1076. $array[ $k ] = add_magic_quotes( $v );
  1077. } else {
  1078. $array[ $k ] = addslashes( $v );
  1079. }
  1080. }
  1081. return $array;
  1082. }
  1083. /**
  1084. * HTTP request for URI to retrieve content.
  1085. *
  1086. * @since 1.5.1
  1087. *
  1088. * @see wp_safe_remote_get()
  1089. *
  1090. * @param string $uri URI/URL of web page to retrieve.
  1091. * @return false|string HTTP content. False on failure.
  1092. */
  1093. function wp_remote_fopen( $uri ) {
  1094. $parsed_url = @parse_url( $uri );
  1095. if ( ! $parsed_url || ! is_array( $parsed_url ) ) {
  1096. return false;
  1097. }
  1098. $options = array();
  1099. $options['timeout'] = 10;
  1100. $response = wp_safe_remote_get( $uri, $options );
  1101. if ( is_wp_error( $response ) ) {
  1102. return false;
  1103. }
  1104. return wp_remote_retrieve_body( $response );
  1105. }
  1106. /**
  1107. * Set up the WordPress query.
  1108. *
  1109. * @since 2.0.0
  1110. *
  1111. * @global WP $wp Current WordPress environment instance.
  1112. * @global WP_Query $wp_query WordPress Query object.
  1113. * @global WP_Query $wp_the_query Copy of the WordPress Query object.
  1114. *
  1115. * @param string|array $query_vars Default WP_Query arguments.
  1116. */
  1117. function wp( $query_vars = '' ) {
  1118. global $wp, $wp_query, $wp_the_query;
  1119. $wp->main( $query_vars );
  1120. if ( ! isset( $wp_the_query ) ) {
  1121. $wp_the_query = $wp_query;
  1122. }
  1123. }
  1124. /**
  1125. * Retrieve the description for the HTTP status.
  1126. *
  1127. * @since 2.3.0
  1128. * @since 3.9.0 Added status codes 418, 428, 429, 431, and 511.
  1129. * @since 4.5.0 Added status codes 308, 421, and 451.
  1130. * @since 5.1.0 Added status code 103.
  1131. *
  1132. * @global array $wp_header_to_desc
  1133. *
  1134. * @param int $code HTTP status code.
  1135. * @return string Status description if found, an empty string otherwise.
  1136. */
  1137. function get_status_header_desc( $code ) {
  1138. global $wp_header_to_desc;
  1139. $code = absint( $code );
  1140. if ( ! isset( $wp_header_to_desc ) ) {
  1141. $wp_header_to_desc = array(
  1142. 100 => 'Continue',
  1143. 101 => 'Switching Protocols',
  1144. 102 => 'Processing',
  1145. 103 => 'Early Hints',
  1146. 200 => 'OK',
  1147. 201 => 'Created',
  1148. 202 => 'Accepted',
  1149. 203 => 'Non-Authoritative Information',
  1150. 204 => 'No Content',
  1151. 205 => 'Reset Content',
  1152. 206 => 'Partial Content',
  1153. 207 => 'Multi-Status',
  1154. 226 => 'IM Used',
  1155. 300 => 'Multiple Choices',
  1156. 301 => 'Moved Permanently',
  1157. 302 => 'Found',
  1158. 303 => 'See Other',
  1159. 304 => 'Not Modified',
  1160. 305 => 'Use Proxy',
  1161. 306 => 'Reserved',
  1162. 307 => 'Temporary Redirect',
  1163. 308 => 'Permanent Redirect',
  1164. 400 => 'Bad Request',
  1165. 401 => 'Unauthorized',
  1166. 402 => 'Payment Required',
  1167. 403 => 'Forbidden',
  1168. 404 => 'Not Found',
  1169. 405 => 'Method Not Allowed',
  1170. 406 => 'Not Acceptable',
  1171. 407 => 'Proxy Authentication Required',
  1172. 408 => 'Request Timeout',
  1173. 409 => 'Conflict',
  1174. 410 => 'Gone',
  1175. 411 => 'Length Required',
  1176. 412 => 'Precondition Failed',
  1177. 413 => 'Request Entity Too Large',
  1178. 414 => 'Request-URI Too Long',
  1179. 415 => 'Unsupported Media Type',
  1180. 416 => 'Requested Range Not Satisfiable',
  1181. 417 => 'Expectation Failed',
  1182. 418 => 'I\'m a teapot',
  1183. 421 => 'Misdirected Request',
  1184. 422 => 'Unprocessable Entity',
  1185. 423 => 'Locked',
  1186. 424 => 'Failed Dependency',
  1187. 426 => 'Upgrade Required',
  1188. 428 => 'Precondition Required',
  1189. 429 => 'Too Many Requests',
  1190. 431 => 'Request Header Fields Too Large',
  1191. 451 => 'Unavailable For Legal Reasons',
  1192. 500 => 'Internal Server Error',
  1193. 501 => 'Not Implemented',
  1194. 502 => 'Bad Gateway',
  1195. 503 => 'Service Unavailable',
  1196. 504 => 'Gateway Timeout',
  1197. 505 => 'HTTP Version Not Supported',
  1198. 506 => 'Variant Also Negotiates',
  1199. 507 => 'Insufficient Storage',
  1200. 510 => 'Not Extended',
  1201. 511 => 'Network Authentication Required',
  1202. );
  1203. }
  1204. if ( isset( $wp_header_to_desc[ $code ] ) ) {
  1205. return $wp_header_to_desc[ $code ];
  1206. } else {
  1207. return '';
  1208. }
  1209. }
  1210. /**
  1211. * Set HTTP status header.
  1212. *
  1213. * @since 2.0.0
  1214. * @since 4.4.0 Added the `$description` parameter.
  1215. *
  1216. * @see get_status_header_desc()
  1217. *
  1218. * @param int $code HTTP status code.
  1219. * @param string $description Optional. A custom description for the HTTP status.
  1220. */
  1221. function status_header( $code, $description = '' ) {
  1222. if ( ! $description ) {
  1223. $description = get_status_header_desc( $code );
  1224. }
  1225. if ( empty( $description ) ) {
  1226. return;
  1227. }
  1228. $protocol = wp_get_server_protocol();
  1229. $status_header = "$protocol $code $description";
  1230. if ( function_exists( 'apply_filters' ) ) {
  1231. /**
  1232. * Filters an HTTP status header.
  1233. *
  1234. * @since 2.2.0
  1235. *
  1236. * @param string $status_header HTTP status header.
  1237. * @param int $code HTTP status code.
  1238. * @param string $description Description for the status code.
  1239. * @param string $protocol Server protocol.
  1240. */
  1241. $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
  1242. }
  1243. if ( ! headers_sent() ) {
  1244. header( $status_header, true, $code );
  1245. }
  1246. }
  1247. /**
  1248. * Get the header information to prevent caching.
  1249. *
  1250. * The several different headers cover the different ways cache prevention
  1251. * is handled by different browsers
  1252. *
  1253. * @since 2.8.0
  1254. *
  1255. * @return array The associative array of header names and field values.
  1256. */
  1257. function wp_get_nocache_headers() {
  1258. $headers = array(
  1259. 'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1260. 'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1261. );
  1262. if ( function_exists( 'apply_filters' ) ) {
  1263. /**
  1264. * Filters the cache-controlling headers.
  1265. *
  1266. * @since 2.8.0
  1267. *
  1268. * @see wp_get_nocache_headers()
  1269. *
  1270. * @param array $headers {
  1271. * Header names and field values.
  1272. *
  1273. * @type string $Expires Expires header.
  1274. * @type string $Cache-Control Cache-Control header.
  1275. * }
  1276. */
  1277. $headers = (array) apply_filters( 'nocache_headers', $headers );
  1278. }
  1279. $headers['Last-Modified'] = false;
  1280. return $headers;
  1281. }
  1282. /**
  1283. * Set the headers to prevent caching for the different browsers.
  1284. *
  1285. * Different browsers support different nocache headers, so several
  1286. * headers must be sent so that all of them get the point that no
  1287. * caching should occur.
  1288. *
  1289. * @since 2.0.0
  1290. *
  1291. * @see wp_get_nocache_headers()
  1292. */
  1293. function nocache_headers() {
  1294. if ( headers_sent() ) {
  1295. return;
  1296. }
  1297. $headers = wp_get_nocache_headers();
  1298. unset( $headers['Last-Modified'] );
  1299. header_remove( 'Last-Modified' );
  1300. foreach ( $headers as $name => $field_value ) {
  1301. header( "{$name}: {$field_value}" );
  1302. }
  1303. }
  1304. /**
  1305. * Set the headers for caching for 10 days with JavaScript content type.
  1306. *
  1307. * @since 2.1.0
  1308. */
  1309. function cache_javascript_headers() {
  1310. $expiresOffset = 10 * DAY_IN_SECONDS;
  1311. header( 'Content-Type: text/javascript; charset=' . get_bloginfo( 'charset' ) );
  1312. header( 'Vary: Accept-Encoding' ); // Handle proxies
  1313. header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $expiresOffset ) . ' GMT' );
  1314. }
  1315. /**
  1316. * Retrieve the number of database queries during the WordPress execution.
  1317. *
  1318. * @since 2.0.0
  1319. *
  1320. * @global wpdb $wpdb WordPress database abstraction object.
  1321. *
  1322. * @return int Number of database queries.
  1323. */
  1324. function get_num_queries() {
  1325. global $wpdb;
  1326. return $wpdb->num_queries;
  1327. }
  1328. /**
  1329. * Whether input is yes or no.
  1330. *
  1331. * Must be 'y' to be true.
  1332. *
  1333. * @since 1.0.0
  1334. *
  1335. * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
  1336. * @return bool True if yes, false on anything else.
  1337. */
  1338. function bool_from_yn( $yn ) {
  1339. return ( strtolower( $yn ) == 'y' );
  1340. }
  1341. /**
  1342. * Load the feed template from the use of an action hook.
  1343. *
  1344. * If the feed action does not have a hook, then the function will die with a
  1345. * message telling the visitor that the feed is not valid.
  1346. *
  1347. * It is better to only have one hook for each feed.
  1348. *
  1349. * @since 2.1.0
  1350. *
  1351. * @global WP_Query $wp_query WordPress Query object.
  1352. */
  1353. function do_feed() {
  1354. global $wp_query;
  1355. $feed = get_query_var( 'feed' );
  1356. // Remove the pad, if present.
  1357. $feed = preg_replace( '/^_+/', '', $feed );
  1358. if ( $feed == '' || $feed == 'feed' ) {
  1359. $feed = get_default_feed();
  1360. }
  1361. if ( ! has_action( "do_feed_{$feed}" ) ) {
  1362. wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  1363. }
  1364. /**
  1365. * Fires once the given feed is loaded.
  1366. *
  1367. * The dynamic portion of the hook name, `$feed`, refers to the feed template name.
  1368. * Possible values include: 'rdf', 'rss', 'rss2', and 'atom'.
  1369. *
  1370. * @since 2.1.0
  1371. * @since 4.4.0 The `$feed` parameter was added.
  1372. *
  1373. * @param bool $is_comment_feed Whether the feed is a comment feed.
  1374. * @param string $feed The feed name.
  1375. */
  1376. do_action( "do_feed_{$feed}", $wp_query->is_comment_feed, $feed );
  1377. }
  1378. /**
  1379. * Load the RDF RSS 0.91 Feed template.
  1380. *
  1381. * @since 2.1.0
  1382. *
  1383. * @see load_template()
  1384. */
  1385. function do_feed_rdf() {
  1386. load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1387. }
  1388. /**
  1389. * Load the RSS 1.0 Feed Template.
  1390. *
  1391. * @since 2.1.0
  1392. *
  1393. * @see load_template()
  1394. */
  1395. function do_feed_rss() {
  1396. load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1397. }
  1398. /**
  1399. * Load either the RSS2 comment feed or the RSS2 posts feed.
  1400. *
  1401. * @since 2.1.0
  1402. *
  1403. * @see load_template()
  1404. *
  1405. * @param bool $for_comments True for the comment feed, false for normal feed.
  1406. */
  1407. function do_feed_rss2( $for_comments ) {
  1408. if ( $for_comments ) {
  1409. load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1410. } else {
  1411. load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1412. }
  1413. }
  1414. /**
  1415. * Load either Atom comment feed or Atom posts feed.
  1416. *
  1417. * @since 2.1.0
  1418. *
  1419. * @see load_template()
  1420. *
  1421. * @param bool $for_comments True for the comment feed, false for normal feed.
  1422. */
  1423. function do_feed_atom( $for_comments ) {
  1424. if ( $for_comments ) {
  1425. load_template( ABSPATH . WPINC . '/feed-atom-comments.php' );
  1426. } else {
  1427. load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1428. }
  1429. }
  1430. /**
  1431. * Displays the default robots.txt file content.
  1432. *
  1433. * @since 2.1.0
  1434. * @since 5.3.0 Remove the "Disallow: /" output if search engine visiblity is
  1435. * discouraged in favor of robots meta HTML tag in wp_no_robots().
  1436. */
  1437. function do_robots() {
  1438. header( 'Content-Type: text/plain; charset=utf-8' );
  1439. /**
  1440. * Fires when displaying the robots.txt file.
  1441. *
  1442. * @since 2.1.0
  1443. */
  1444. do_action( 'do_robotstxt' );
  1445. $output = "User-agent: *\n";
  1446. $public = get_option( 'blog_public' );
  1447. $site_url = parse_url( site_url() );
  1448. $path = ( ! empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  1449. $output .= "Disallow: $path/wp-admin/\n";
  1450. $output .= "Allow: $path/wp-admin/admin-ajax.php\n";
  1451. /**
  1452. * Filters the robots.txt output.
  1453. *
  1454. * @since 3.0.0
  1455. *
  1456. * @param string $output The robots.txt output.
  1457. * @param bool $public Whether the site is considered "public".
  1458. */
  1459. echo apply_filters( 'robots_txt', $output, $public );
  1460. }
  1461. /**
  1462. * Determines whether WordPress is already installed.
  1463. *
  1464. * The cache will be checked first. If you have a cache plugin, which saves
  1465. * the cache values, then this will work. If you use the default WordPress
  1466. * cache, and the database goes away, then you might have problems.
  1467. *
  1468. * Checks for the 'siteurl' option for whether WordPress is installed.
  1469. *
  1470. * For more information on this and similar theme functions, check out
  1471. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1472. * Conditional Tags} article in the Theme Developer Handbook.
  1473. *
  1474. * @since 2.1.0
  1475. *
  1476. * @global wpdb $wpdb WordPress database abstraction object.
  1477. *
  1478. * @return bool Whether the site is already installed.
  1479. */
  1480. function is_blog_installed() {
  1481. global $wpdb;
  1482. /*
  1483. * Check cache first. If options table goes away and we have true
  1484. * cached, oh well.
  1485. */
  1486. if ( wp_cache_get( 'is_blog_installed' ) ) {
  1487. return true;
  1488. }
  1489. $suppress = $wpdb->suppress_errors();
  1490. if ( ! wp_installing() ) {
  1491. $alloptions = wp_load_alloptions();
  1492. }
  1493. // If siteurl is not set to autoload, check it specifically
  1494. if ( ! isset( $alloptions['siteurl'] ) ) {
  1495. $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1496. } else {
  1497. $installed = $alloptions['siteurl'];
  1498. }
  1499. $wpdb->suppress_errors( $suppress );
  1500. $installed = ! empty( $installed );
  1501. wp_cache_set( 'is_blog_installed', $installed );
  1502. if ( $installed ) {
  1503. return true;
  1504. }
  1505. // If visiting repair.php, return true and let it take over.
  1506. if ( defined( 'WP_REPAIRING' ) ) {
  1507. return true;
  1508. }
  1509. $suppress = $wpdb->suppress_errors();
  1510. /*
  1511. * Loop over the WP tables. If none exist, then scratch installation is allowed.
  1512. * If one or more exist, suggest table repair since we got here because the
  1513. * options table could not be accessed.
  1514. */
  1515. $wp_tables = $wpdb->tables();
  1516. foreach ( $wp_tables as $table ) {
  1517. // The existence of custom user tables shouldn't suggest an insane state or prevent a clean installation.
  1518. if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table ) {
  1519. continue;
  1520. }
  1521. if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table ) {
  1522. continue;
  1523. }
  1524. if ( ! $wpdb->get_results( "DESCRIBE $table;" ) ) {
  1525. continue;
  1526. }
  1527. // One or more tables exist. We are insane.
  1528. wp_load_translations_early();
  1529. // Die with a DB error.
  1530. $wpdb->error = sprintf(
  1531. /* translators: %s: Database repair URL. */
  1532. __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ),
  1533. 'maint/repair.php?referrer=is_blog_installed'
  1534. );
  1535. dead_db();
  1536. }
  1537. $wpdb->suppress_errors( $suppress );
  1538. wp_cache_set( 'is_blog_installed', false );
  1539. return false;
  1540. }
  1541. /**
  1542. * Retrieve URL with nonce added to URL query.
  1543. *
  1544. * @since 2.0.4
  1545. *
  1546. * @param string $actionurl URL to add nonce action.
  1547. * @param int|string $action Optional. Nonce action name. Default -1.
  1548. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1549. * @return string Escaped URL with nonce action added.
  1550. */
  1551. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1552. $actionurl = str_replace( '&amp;', '&', $actionurl );
  1553. return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1554. }
  1555. /**
  1556. * Retrieve or display nonce hidden field for forms.
  1557. *
  1558. * The nonce field is used to validate that the contents of the form came from
  1559. * the location on the current site and not somewhere else. The nonce does not
  1560. * offer absolute protection, but should protect against most cases. It is very
  1561. * important to use nonce field in forms.
  1562. *
  1563. * The $action and $name are optional, but if you want to have better security,
  1564. * it is strongly suggested to set those two parameters. It is easier to just
  1565. * call the function without any parameters, because validation of the nonce
  1566. * doesn't require any parameters, but since crackers know what the default is
  1567. * it won't be difficult for them to find a way around your nonce and cause
  1568. * damage.
  1569. *
  1570. * The input name will be whatever $name value you gave. The input value will be
  1571. * the nonce creation value.
  1572. *
  1573. * @since 2.0.4
  1574. *
  1575. * @param int|string $action Optional. Action name. Default -1.
  1576. * @param string $name Optional. Nonce name. Default '_wpnonce'.
  1577. * @param bool $referer Optional. Whether to set the referer field for validation. Default true.
  1578. * @param bool $echo Optional. Whether to display or return hidden form field. Default true.
  1579. * @return string Nonce field HTML markup.
  1580. */
  1581. function wp_nonce_field( $action = -1, $name = '_wpnonce', $referer = true, $echo = true ) {
  1582. $name = esc_attr( $name );
  1583. $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1584. if ( $referer ) {
  1585. $nonce_field .= wp_referer_field( false );
  1586. }
  1587. if ( $echo ) {
  1588. echo $nonce_field;
  1589. }
  1590. return $nonce_field;
  1591. }
  1592. /**
  1593. * Retrieve or display referer hidden field for forms.
  1594. *
  1595. * The referer link is the current Request URI from the server super global. The
  1596. * input name is '_wp_http_referer', in case you wanted to check manually.
  1597. *
  1598. * @since 2.0.4
  1599. *
  1600. * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
  1601. * @return string Referer field HTML markup.
  1602. */
  1603. function wp_referer_field( $echo = true ) {
  1604. $referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1605. if ( $echo ) {
  1606. echo $referer_field;
  1607. }
  1608. return $referer_field;
  1609. }
  1610. /**
  1611. * Retrieve or display original referer hidden field for forms.
  1612. *
  1613. * The input name is '_wp_original_http_referer' and will be either the same
  1614. * value of wp_referer_field(), if that was posted already or it will be the
  1615. * current page, if it doesn't exist.
  1616. *
  1617. * @since 2.0.4
  1618. *
  1619. * @param bool $echo Optional. Whether to echo the original http referer. Default true.
  1620. * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
  1621. * Default 'current'.
  1622. * @return string Original referer field.
  1623. */
  1624. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1625. $ref = wp_get_original_referer();
  1626. if ( ! $ref ) {
  1627. $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1628. }
  1629. $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1630. if ( $echo ) {
  1631. echo $orig_referer_field;
  1632. }
  1633. return $orig_referer_field;
  1634. }
  1635. /**
  1636. * Retrieve referer from '_wp_http_referer' or HTTP referer.
  1637. *
  1638. * If it's the same as the current request URL, will return false.
  1639. *
  1640. * @since 2.0.4
  1641. *
  1642. * @return false|string False on failure. Referer URL on success.
  1643. */
  1644. function wp_get_referer() {
  1645. if ( ! function_exists( 'wp_validate_redirect' ) ) {
  1646. return false;
  1647. }
  1648. $ref = wp_get_raw_referer();
  1649. if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) && $ref !== home_url() . wp_unslash( $_SERVER['REQUEST_URI'] ) ) {
  1650. return wp_validate_redirect( $ref, false );
  1651. }
  1652. return false;
  1653. }
  1654. /**
  1655. * Retrieves unvalidated referer from '_wp_http_referer' or HTTP referer.
  1656. *
  1657. * Do not use for redirects, use wp_get_referer() instead.
  1658. *
  1659. * @since 4.5.0
  1660. *
  1661. * @return string|false Referer URL on success, false on failure.
  1662. */
  1663. function wp_get_raw_referer() {
  1664. if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) {
  1665. return wp_unslash( $_REQUEST['_wp_http_referer'] );
  1666. } elseif ( ! empty( $_SERVER['HTTP_REFERER'] ) ) {
  1667. return wp_unslash( $_SERVER['HTTP_REFERER'] );
  1668. }
  1669. return false;
  1670. }
  1671. /**
  1672. * Retrieve original referer that was posted, if it exists.
  1673. *
  1674. * @since 2.0.4
  1675. *
  1676. * @return string|false False if no original referer or original referer if set.
  1677. */
  1678. function wp_get_original_referer() {
  1679. if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) ) {
  1680. return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1681. }
  1682. return false;
  1683. }
  1684. /**
  1685. * Recursive directory creation based on full path.
  1686. *
  1687. * Will attempt to set permissions on folders.
  1688. *
  1689. * @since 2.0.1
  1690. *
  1691. * @param string $target Full path to attempt to create.
  1692. * @return bool Whether the path was created. True if path already exists.
  1693. */
  1694. function wp_mkdir_p( $target ) {
  1695. $wrapper = null;
  1696. // Strip the protocol.
  1697. if ( wp_is_stream( $target ) ) {
  1698. list( $wrapper, $target ) = explode( '://', $target, 2 );
  1699. }
  1700. // From php.net/mkdir user contributed notes.
  1701. $target = str_replace( '//', '/', $target );
  1702. // Put the wrapper back on the target.
  1703. if ( $wrapper !== null ) {
  1704. $target = $wrapper . '://' . $target;
  1705. }
  1706. /*
  1707. * Safe mode fails with a trailing slash under certain PHP versions.
  1708. * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1709. */
  1710. $target = rtrim( $target, '/' );
  1711. if ( empty( $target ) ) {
  1712. $target = '/';
  1713. }
  1714. if ( file_exists( $target ) ) {
  1715. return @is_dir( $target );
  1716. }
  1717. // Do not allow path traversals.
  1718. if ( false !== strpos( $target, '../' ) || false !== strpos( $target, '..' . DIRECTORY_SEPARATOR ) ) {
  1719. return false;
  1720. }
  1721. // We need to find the permissions of the parent folder that exists and inherit that.
  1722. $target_parent = dirname( $target );
  1723. while ( '.' != $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) {
  1724. $target_parent = dirname( $target_parent );
  1725. }
  1726. // Get the permission bits.
  1727. $stat = @stat( $target_parent );
  1728. if ( $stat ) {
  1729. $dir_perms = $stat['mode'] & 0007777;
  1730. } else {
  1731. $dir_perms = 0777;
  1732. }
  1733. if ( @mkdir( $target, $dir_perms, true ) ) {
  1734. /*
  1735. * If a umask is set that modifies $dir_perms, we'll have to re-set
  1736. * the $dir_perms correctly with chmod()
  1737. */
  1738. if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
  1739. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1740. for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
  1741. chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1742. }
  1743. }
  1744. return true;
  1745. }
  1746. return false;
  1747. }
  1748. /**
  1749. * Test if a given filesystem path is absolute.
  1750. *
  1751. * For example, '/foo/bar', or 'c:\windows'.
  1752. *
  1753. * @since 2.5.0
  1754. *
  1755. * @param string $path File path.
  1756. * @return bool True if path is absolute, false is not absolute.
  1757. */
  1758. function path_is_absolute( $path ) {
  1759. /*
  1760. * Check to see if the path is a stream and check to see if its an actual
  1761. * path or file as realpath() does not support stream wrappers.
  1762. */
  1763. if ( wp_is_stream( $path ) && ( is_dir( $path ) || is_file( $path ) ) ) {
  1764. return true;
  1765. }
  1766. /*
  1767. * This is definitive if true but fails if $path does not exist or contains
  1768. * a symbolic link.
  1769. */
  1770. if ( realpath( $path ) == $path ) {
  1771. return true;
  1772. }
  1773. if ( strlen( $path ) == 0 || $path[0] == '.' ) {
  1774. return false;
  1775. }
  1776. // Windows allows absolute paths like this.
  1777. if ( preg_match( '#^[a-zA-Z]:\\\\#', $path ) ) {
  1778. return true;
  1779. }
  1780. // A path starting with / or \ is absolute; anything else is relative.
  1781. return ( $path[0] == '/' || $path[0] == '\\' );
  1782. }
  1783. /**
  1784. * Join two filesystem paths together.
  1785. *
  1786. * For example, 'give me $path relative to $base'. If the $path is absolute,
  1787. * then it the full path is returned.
  1788. *
  1789. * @since 2.5.0
  1790. *
  1791. * @param string $base Base path.
  1792. * @param string $path Path relative to $base.
  1793. * @return string The path with the base or absolute path.
  1794. */
  1795. function path_join( $base, $path ) {
  1796. if ( path_is_absolute( $path ) ) {
  1797. return $path;
  1798. }
  1799. return rtrim( $base, '/' ) . '/' . ltrim( $path, '/' );
  1800. }
  1801. /**
  1802. * Normalize a filesystem path.
  1803. *
  1804. * On windows systems, replaces backslashes with forward slashes
  1805. * and forces upper-case drive letters.
  1806. * Allows for two leading slashes for Windows network shares, but
  1807. * ensures that all other duplicate slashes are reduced to a single.
  1808. *
  1809. * @since 3.9.0
  1810. * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
  1811. * @since 4.5.0 Allows for Windows network shares.
  1812. * @since 4.9.7 Allows for PHP file wrappers.
  1813. *
  1814. * @param string $path Path to normalize.
  1815. * @return string Normalized path.
  1816. */
  1817. function wp_normalize_path( $path ) {
  1818. $wrapper = '';
  1819. if ( wp_is_stream( $path ) ) {
  1820. list( $wrapper, $path ) = explode( '://', $path, 2 );
  1821. $wrapper .= '://';
  1822. }
  1823. // Standardise all paths to use /
  1824. $path = str_replace( '\\', '/', $path );
  1825. // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
  1826. $path = preg_replace( '|(?<=.)/+|', '/', $path );
  1827. // Windows paths should uppercase the drive letter
  1828. if ( ':' === substr( $path, 1, 1 ) ) {
  1829. $path = ucfirst( $path );
  1830. }
  1831. return $wrapper . $path;
  1832. }
  1833. /**
  1834. * Determine a writable directory for temporary files.
  1835. *
  1836. * Function's preference is the return value of sys_get_temp_dir(),
  1837. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1838. * before finally defaulting to /tmp/
  1839. *
  1840. * In the event that this function does not find a writable location,
  1841. * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
  1842. *
  1843. * @since 2.5.0
  1844. *
  1845. * @staticvar string $temp
  1846. *
  1847. * @return string Writable temporary directory.
  1848. */
  1849. function get_temp_dir() {
  1850. static $temp = '';
  1851. if ( defined( 'WP_TEMP_DIR' ) ) {
  1852. return trailingslashit( WP_TEMP_DIR );
  1853. }
  1854. if ( $temp ) {
  1855. return trailingslashit( $temp );
  1856. }
  1857. if ( function_exists( 'sys_get_temp_dir' ) ) {
  1858. $temp = sys_get_temp_dir();
  1859. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1860. return trailingslashit( $temp );
  1861. }
  1862. }
  1863. $temp = ini_get( 'upload_tmp_dir' );
  1864. if ( @is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1865. return trailingslashit( $temp );
  1866. }
  1867. $temp = WP_CONTENT_DIR . '/';
  1868. if ( is_dir( $temp ) && wp_is_writable( $temp ) ) {
  1869. return $temp;
  1870. }
  1871. return '/tmp/';
  1872. }
  1873. /**
  1874. * Determine if a directory is writable.
  1875. *
  1876. * This function is used to work around certain ACL issues in PHP primarily
  1877. * affecting Windows Servers.
  1878. *
  1879. * @since 3.6.0
  1880. *
  1881. * @see win_is_writable()
  1882. *
  1883. * @param string $path Path to check for write-ability.
  1884. * @return bool Whether the path is writable.
  1885. */
  1886. function wp_is_writable( $path ) {
  1887. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) ) {
  1888. return win_is_writable( $path );
  1889. } else {
  1890. return @is_writable( $path );
  1891. }
  1892. }
  1893. /**
  1894. * Workaround for Windows bug in is_writable() function
  1895. *
  1896. * PHP has issues with Windows ACL's for determine if a
  1897. * directory is writable or not, this works around them by
  1898. * checking the ability to open files rather than relying
  1899. * upon PHP to interprate the OS ACL.
  1900. *
  1901. * @since 2.8.0
  1902. *
  1903. * @see https://bugs.php.net/bug.php?id=27609
  1904. * @see https://bugs.php.net/bug.php?id=30931
  1905. *
  1906. * @param string $path Windows path to check for write-ability.
  1907. * @return bool Whether the path is writable.
  1908. */
  1909. function win_is_writable( $path ) {
  1910. if ( $path[ strlen( $path ) - 1 ] == '/' ) { // if it looks like a directory, check a random file within the directory
  1911. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp' );
  1912. } elseif ( is_dir( $path ) ) { // If it's a directory (and not a file) check a random file within the directory
  1913. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1914. }
  1915. // check tmp file for read/write capabilities
  1916. $should_delete_tmp_file = ! file_exists( $path );
  1917. $f = @fopen( $path, 'a' );
  1918. if ( $f === false ) {
  1919. return false;
  1920. }
  1921. fclose( $f );
  1922. if ( $should_delete_tmp_file ) {
  1923. unlink( $path );
  1924. }
  1925. return true;
  1926. }
  1927. /**
  1928. * Retrieves uploads directory information.
  1929. *
  1930. * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
  1931. * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
  1932. * when not uploading files.
  1933. *
  1934. * @since 4.5.0
  1935. *
  1936. * @see wp_upload_dir()
  1937. *
  1938. * @return array See wp_upload_dir() for description.
  1939. */
  1940. function wp_get_upload_dir() {
  1941. return wp_upload_dir( null, false );
  1942. }
  1943. /**
  1944. * Returns an array containing the current upload directory's path and URL.
  1945. *
  1946. * Checks the 'upload_path' option, which should be from the web root folder,
  1947. * and if it isn't empty it will be used. If it is empty, then the path will be
  1948. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1949. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1950. *
  1951. * The upload URL path is set either by the 'upload_url_path' option or by using
  1952. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1953. *
  1954. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1955. * the administration settings panel), then the time will be used. The format
  1956. * will be year first and then month.
  1957. *
  1958. * If the path couldn't be created, then an error will be returned with the key
  1959. * 'error' containing the error message. The error suggests that the parent
  1960. * directory is not writable by the server.
  1961. *
  1962. * @since 2.0.0
  1963. * @uses _wp_upload_dir()
  1964. *
  1965. * @staticvar array $cache
  1966. * @staticvar array $tested_paths
  1967. *
  1968. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1969. * @param bool $create_dir Optional. Whether to check and create the uploads directory.
  1970. * Default true for backward compatibility.
  1971. * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false.
  1972. * @return array {
  1973. * Array of information about the upload directory.
  1974. *
  1975. * @type string $path Base directory and subdirectory or full path to upload directory.
  1976. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  1977. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  1978. * @type string $basedir Path without subdir.
  1979. * @type string $baseurl URL path without subdir.
  1980. * @type string|false $error False or error message.
  1981. * }
  1982. */
  1983. function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
  1984. static $cache = array(), $tested_paths = array();
  1985. $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
  1986. if ( $refresh_cache || empty( $cache[ $key ] ) ) {
  1987. $cache[ $key ] = _wp_upload_dir( $time );
  1988. }
  1989. /**
  1990. * Filters the uploads directory data.
  1991. *
  1992. * @since 2.0.0
  1993. *
  1994. * @param array $uploads {
  1995. * Array of information about the upload directory.
  1996. *
  1997. * @type string $path Base directory and subdirectory or full path to upload directory.
  1998. * @type string $url Base URL and subdirectory or absolute URL to upload directory.
  1999. * @type string $subdir Subdirectory if uploads use year/month folders option is on.
  2000. * @type string $basedir Path without subdir.
  2001. * @type string $baseurl URL path without subdir.
  2002. * @type string|false $error False or error message.
  2003. * }
  2004. */
  2005. $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
  2006. if ( $create_dir ) {
  2007. $path = $uploads['path'];
  2008. if ( array_key_exists( $path, $tested_paths ) ) {
  2009. $uploads['error'] = $tested_paths[ $path ];
  2010. } else {
  2011. if ( ! wp_mkdir_p( $path ) ) {
  2012. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
  2013. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  2014. } else {
  2015. $error_path = wp_basename( $uploads['basedir'] ) . $uploads['subdir'];
  2016. }
  2017. $uploads['error'] = sprintf(
  2018. /* translators: %s: Directory path. */
  2019. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2020. esc_html( $error_path )
  2021. );
  2022. }
  2023. $tested_paths[ $path ] = $uploads['error'];
  2024. }
  2025. }
  2026. return $uploads;
  2027. }
  2028. /**
  2029. * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
  2030. *
  2031. * @since 4.5.0
  2032. * @access private
  2033. *
  2034. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2035. * @return array See wp_upload_dir()
  2036. */
  2037. function _wp_upload_dir( $time = null ) {
  2038. $siteurl = get_option( 'siteurl' );
  2039. $upload_path = trim( get_option( 'upload_path' ) );
  2040. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  2041. $dir = WP_CONTENT_DIR . '/uploads';
  2042. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  2043. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  2044. $dir = path_join( ABSPATH, $upload_path );
  2045. } else {
  2046. $dir = $upload_path;
  2047. }
  2048. $url = get_option( 'upload_url_path' );
  2049. if ( ! $url ) {
  2050. if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) ) {
  2051. $url = WP_CONTENT_URL . '/uploads';
  2052. } else {
  2053. $url = trailingslashit( $siteurl ) . $upload_path;
  2054. }
  2055. }
  2056. /*
  2057. * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  2058. * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  2059. */
  2060. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  2061. $dir = ABSPATH . UPLOADS;
  2062. $url = trailingslashit( $siteurl ) . UPLOADS;
  2063. }
  2064. // If multisite (and if not the main site in a post-MU network)
  2065. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  2066. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  2067. /*
  2068. * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  2069. * straightforward: Append sites/%d if we're not on the main site (for post-MU
  2070. * networks). (The extra directory prevents a four-digit ID from conflicting with
  2071. * a year-based directory for the main site. But if a MU-era network has disabled
  2072. * ms-files rewriting manually, they don't need the extra directory, as they never
  2073. * had wp-content/uploads for the main site.)
  2074. */
  2075. if ( defined( 'MULTISITE' ) ) {
  2076. $ms_dir = '/sites/' . get_current_blog_id();
  2077. } else {
  2078. $ms_dir = '/' . get_current_blog_id();
  2079. }
  2080. $dir .= $ms_dir;
  2081. $url .= $ms_dir;
  2082. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  2083. /*
  2084. * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  2085. * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  2086. * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  2087. * there, and
  2088. * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  2089. * the original blog ID.
  2090. *
  2091. * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  2092. * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  2093. * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  2094. * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  2095. */
  2096. if ( defined( 'BLOGUPLOADDIR' ) ) {
  2097. $dir = untrailingslashit( BLOGUPLOADDIR );
  2098. } else {
  2099. $dir = ABSPATH . UPLOADS;
  2100. }
  2101. $url = trailingslashit( $siteurl ) . 'files';
  2102. }
  2103. }
  2104. $basedir = $dir;
  2105. $baseurl = $url;
  2106. $subdir = '';
  2107. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  2108. // Generate the yearly and monthly dirs
  2109. if ( ! $time ) {
  2110. $time = current_time( 'mysql' );
  2111. }
  2112. $y = substr( $time, 0, 4 );
  2113. $m = substr( $time, 5, 2 );
  2114. $subdir = "/$y/$m";
  2115. }
  2116. $dir .= $subdir;
  2117. $url .= $subdir;
  2118. return array(
  2119. 'path' => $dir,
  2120. 'url' => $url,
  2121. 'subdir' => $subdir,
  2122. 'basedir' => $basedir,
  2123. 'baseurl' => $baseurl,
  2124. 'error' => false,
  2125. );
  2126. }
  2127. /**
  2128. * Get a filename that is sanitized and unique for the given directory.
  2129. *
  2130. * If the filename is not unique, then a number will be added to the filename
  2131. * before the extension, and will continue adding numbers until the filename is
  2132. * unique.
  2133. *
  2134. * The callback is passed three parameters, the first one is the directory, the
  2135. * second is the filename, and the third is the extension.
  2136. *
  2137. * @since 2.5.0
  2138. *
  2139. * @param string $dir Directory.
  2140. * @param string $filename File name.
  2141. * @param callable $unique_filename_callback Callback. Default null.
  2142. * @return string New filename, if given wasn't unique.
  2143. */
  2144. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  2145. // Sanitize the file name before we begin processing.
  2146. $filename = sanitize_file_name( $filename );
  2147. // Separate the filename into a name and extension.
  2148. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  2149. $name = pathinfo( $filename, PATHINFO_BASENAME );
  2150. if ( $ext ) {
  2151. $ext = '.' . $ext;
  2152. }
  2153. // Edge case: if file is named '.ext', treat as an empty name.
  2154. if ( $name === $ext ) {
  2155. $name = '';
  2156. }
  2157. /*
  2158. * Increment the file number until we have a unique file to save in $dir.
  2159. * Use callback if supplied.
  2160. */
  2161. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  2162. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  2163. } else {
  2164. $number = '';
  2165. // Change '.ext' to lower case.
  2166. if ( $ext && strtolower( $ext ) != $ext ) {
  2167. $ext2 = strtolower( $ext );
  2168. $filename2 = preg_replace( '|' . preg_quote( $ext ) . '$|', $ext2, $filename );
  2169. // Check for both lower and upper case extension or image sub-sizes may be overwritten.
  2170. while ( file_exists( $dir . "/$filename" ) || file_exists( $dir . "/$filename2" ) ) {
  2171. $new_number = (int) $number + 1;
  2172. $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-$new_number$ext", $filename );
  2173. $filename2 = str_replace( array( "-$number$ext2", "$number$ext2" ), "-$new_number$ext2", $filename2 );
  2174. $number = $new_number;
  2175. }
  2176. /**
  2177. * Filters the result when generating a unique file name.
  2178. *
  2179. * @since 4.5.0
  2180. *
  2181. * @param string $filename Unique file name.
  2182. * @param string $ext File extension, eg. ".png".
  2183. * @param string $dir Directory path.
  2184. * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
  2185. */
  2186. return apply_filters( 'wp_unique_filename', $filename2, $ext, $dir, $unique_filename_callback );
  2187. }
  2188. while ( file_exists( $dir . "/$filename" ) ) {
  2189. $new_number = (int) $number + 1;
  2190. if ( '' == "$number$ext" ) {
  2191. $filename = "$filename-" . $new_number;
  2192. } else {
  2193. $filename = str_replace( array( "-$number$ext", "$number$ext" ), '-' . $new_number . $ext, $filename );
  2194. }
  2195. $number = $new_number;
  2196. }
  2197. }
  2198. /** This filter is documented in wp-includes/functions.php */
  2199. return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
  2200. }
  2201. /**
  2202. * Create a file in the upload folder with given content.
  2203. *
  2204. * If there is an error, then the key 'error' will exist with the error message.
  2205. * If success, then the key 'file' will have the unique file path, the 'url' key
  2206. * will have the link to the new file. and the 'error' key will be set to false.
  2207. *
  2208. * This function will not move an uploaded file to the upload folder. It will
  2209. * create a new file with the content in $bits parameter. If you move the upload
  2210. * file, read the content of the uploaded file, and then you can give the
  2211. * filename and content to this function, which will add it to the upload
  2212. * folder.
  2213. *
  2214. * The permissions will be set on the new file automatically by this function.
  2215. *
  2216. * @since 2.0.0
  2217. *
  2218. * @param string $name Filename.
  2219. * @param null|string $deprecated Never used. Set to null.
  2220. * @param mixed $bits File content
  2221. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  2222. * @return array
  2223. */
  2224. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  2225. if ( ! empty( $deprecated ) ) {
  2226. _deprecated_argument( __FUNCTION__, '2.0.0' );
  2227. }
  2228. if ( empty( $name ) ) {
  2229. return array( 'error' => __( 'Empty filename' ) );
  2230. }
  2231. $wp_filetype = wp_check_filetype( $name );
  2232. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
  2233. return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.' ) );
  2234. }
  2235. $upload = wp_upload_dir( $time );
  2236. if ( $upload['error'] !== false ) {
  2237. return $upload;
  2238. }
  2239. /**
  2240. * Filters whether to treat the upload bits as an error.
  2241. *
  2242. * Passing a non-array to the filter will effectively short-circuit preparing
  2243. * the upload bits, returning that value instead.
  2244. *
  2245. * @since 3.0.0
  2246. *
  2247. * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
  2248. */
  2249. $upload_bits_error = apply_filters(
  2250. 'wp_upload_bits',
  2251. array(
  2252. 'name' => $name,
  2253. 'bits' => $bits,
  2254. 'time' => $time,
  2255. )
  2256. );
  2257. if ( ! is_array( $upload_bits_error ) ) {
  2258. $upload['error'] = $upload_bits_error;
  2259. return $upload;
  2260. }
  2261. $filename = wp_unique_filename( $upload['path'], $name );
  2262. $new_file = $upload['path'] . "/$filename";
  2263. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  2264. if ( 0 === strpos( $upload['basedir'], ABSPATH ) ) {
  2265. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  2266. } else {
  2267. $error_path = wp_basename( $upload['basedir'] ) . $upload['subdir'];
  2268. }
  2269. $message = sprintf(
  2270. /* translators: %s: Directory path. */
  2271. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  2272. $error_path
  2273. );
  2274. return array( 'error' => $message );
  2275. }
  2276. $ifp = @fopen( $new_file, 'wb' );
  2277. if ( ! $ifp ) {
  2278. return array(
  2279. /* translators: %s: File name. */
  2280. 'error' => sprintf( __( 'Could not write file %s' ), $new_file ),
  2281. );
  2282. }
  2283. fwrite( $ifp, $bits );
  2284. fclose( $ifp );
  2285. clearstatcache();
  2286. // Set correct file permissions
  2287. $stat = @ stat( dirname( $new_file ) );
  2288. $perms = $stat['mode'] & 0007777;
  2289. $perms = $perms & 0000666;
  2290. chmod( $new_file, $perms );
  2291. clearstatcache();
  2292. // Compute the URL
  2293. $url = $upload['url'] . "/$filename";
  2294. /** This filter is documented in wp-admin/includes/file.php */
  2295. return apply_filters(
  2296. 'wp_handle_upload',
  2297. array(
  2298. 'file' => $new_file,
  2299. 'url' => $url,
  2300. 'type' => $wp_filetype['type'],
  2301. 'error' => false,
  2302. ),
  2303. 'sideload'
  2304. );
  2305. }
  2306. /**
  2307. * Retrieve the file type based on the extension name.
  2308. *
  2309. * @since 2.5.0
  2310. *
  2311. * @param string $ext The extension to search.
  2312. * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
  2313. */
  2314. function wp_ext2type( $ext ) {
  2315. $ext = strtolower( $ext );
  2316. $ext2type = wp_get_ext_types();
  2317. foreach ( $ext2type as $type => $exts ) {
  2318. if ( in_array( $ext, $exts ) ) {
  2319. return $type;
  2320. }
  2321. }
  2322. }
  2323. /**
  2324. * Retrieve the file type from the file name.
  2325. *
  2326. * You can optionally define the mime array, if needed.
  2327. *
  2328. * @since 2.0.4
  2329. *
  2330. * @param string $filename File name or path.
  2331. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  2332. * @return array Values with extension first and mime type.
  2333. */
  2334. function wp_check_filetype( $filename, $mimes = null ) {
  2335. if ( empty( $mimes ) ) {
  2336. $mimes = get_allowed_mime_types();
  2337. }
  2338. $type = false;
  2339. $ext = false;
  2340. foreach ( $mimes as $ext_preg => $mime_match ) {
  2341. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2342. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2343. $type = $mime_match;
  2344. $ext = $ext_matches[1];
  2345. break;
  2346. }
  2347. }
  2348. return compact( 'ext', 'type' );
  2349. }
  2350. /**
  2351. * Attempt to determine the real file type of a file.
  2352. *
  2353. * If unable to, the file name extension will be used to determine type.
  2354. *
  2355. * If it's determined that the extension does not match the file's real type,
  2356. * then the "proper_filename" value will be set with a proper filename and extension.
  2357. *
  2358. * Currently this function only supports renaming images validated via wp_get_image_mime().
  2359. *
  2360. * @since 3.0.0
  2361. *
  2362. * @param string $file Full path to the file.
  2363. * @param string $filename The name of the file (may differ from $file due to $file being
  2364. * in a tmp directory).
  2365. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  2366. * @return array Values for the extension, MIME, and either a corrected filename or false
  2367. * if original $filename is valid.
  2368. */
  2369. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2370. $proper_filename = false;
  2371. // Do basic extension validation and MIME mapping
  2372. $wp_filetype = wp_check_filetype( $filename, $mimes );
  2373. $ext = $wp_filetype['ext'];
  2374. $type = $wp_filetype['type'];
  2375. // We can't do any further validation without a file to work with
  2376. if ( ! file_exists( $file ) ) {
  2377. return compact( 'ext', 'type', 'proper_filename' );
  2378. }
  2379. $real_mime = false;
  2380. // Validate image types.
  2381. if ( $type && 0 === strpos( $type, 'image/' ) ) {
  2382. // Attempt to figure out what type of image it actually is
  2383. $real_mime = wp_get_image_mime( $file );
  2384. if ( $real_mime && $real_mime != $type ) {
  2385. /**
  2386. * Filters the list mapping image mime types to their respective extensions.
  2387. *
  2388. * @since 3.0.0
  2389. *
  2390. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  2391. */
  2392. $mime_to_ext = apply_filters(
  2393. 'getimagesize_mimes_to_exts',
  2394. array(
  2395. 'image/jpeg' => 'jpg',
  2396. 'image/png' => 'png',
  2397. 'image/gif' => 'gif',
  2398. 'image/bmp' => 'bmp',
  2399. 'image/tiff' => 'tif',
  2400. )
  2401. );
  2402. // Replace whatever is after the last period in the filename with the correct extension
  2403. if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
  2404. $filename_parts = explode( '.', $filename );
  2405. array_pop( $filename_parts );
  2406. $filename_parts[] = $mime_to_ext[ $real_mime ];
  2407. $new_filename = implode( '.', $filename_parts );
  2408. if ( $new_filename != $filename ) {
  2409. $proper_filename = $new_filename; // Mark that it changed
  2410. }
  2411. // Redefine the extension / MIME
  2412. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2413. $ext = $wp_filetype['ext'];
  2414. $type = $wp_filetype['type'];
  2415. } else {
  2416. // Reset $real_mime and try validating again.
  2417. $real_mime = false;
  2418. }
  2419. }
  2420. }
  2421. // Validate files that didn't get validated during previous checks.
  2422. if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) {
  2423. $finfo = finfo_open( FILEINFO_MIME_TYPE );
  2424. $real_mime = finfo_file( $finfo, $file );
  2425. finfo_close( $finfo );
  2426. // fileinfo often misidentifies obscure files as one of these types
  2427. $nonspecific_types = array(
  2428. 'application/octet-stream',
  2429. 'application/encrypted',
  2430. 'application/CDFV2-encrypted',
  2431. 'application/zip',
  2432. );
  2433. /*
  2434. * If $real_mime doesn't match the content type we're expecting from the file's extension,
  2435. * we need to do some additional vetting. Media types and those listed in $nonspecific_types are
  2436. * allowed some leeway, but anything else must exactly match the real content type.
  2437. */
  2438. if ( in_array( $real_mime, $nonspecific_types, true ) ) {
  2439. // File is a non-specific binary type. That's ok if it's a type that generally tends to be binary.
  2440. if ( ! in_array( substr( $type, 0, strcspn( $type, '/' ) ), array( 'application', 'video', 'audio' ) ) ) {
  2441. $type = false;
  2442. $ext = false;
  2443. }
  2444. } elseif ( 0 === strpos( $real_mime, 'video/' ) || 0 === strpos( $real_mime, 'audio/' ) ) {
  2445. /*
  2446. * For these types, only the major type must match the real value.
  2447. * This means that common mismatches are forgiven: application/vnd.apple.numbers is often misidentified as application/zip,
  2448. * and some media files are commonly named with the wrong extension (.mov instead of .mp4)
  2449. */
  2450. if ( substr( $real_mime, 0, strcspn( $real_mime, '/' ) ) !== substr( $type, 0, strcspn( $type, '/' ) ) ) {
  2451. $type = false;
  2452. $ext = false;
  2453. }
  2454. } elseif ( 'text/plain' === $real_mime ) {
  2455. // A few common file types are occasionally detected as text/plain; allow those.
  2456. if ( ! in_array(
  2457. $type,
  2458. array(
  2459. 'text/plain',
  2460. 'text/csv',
  2461. 'text/richtext',
  2462. 'text/tsv',
  2463. 'text/vtt',
  2464. )
  2465. )
  2466. ) {
  2467. $type = false;
  2468. $ext = false;
  2469. }
  2470. } elseif ( 'text/rtf' === $real_mime ) {
  2471. // Special casing for RTF files.
  2472. if ( ! in_array(
  2473. $type,
  2474. array(
  2475. 'text/rtf',
  2476. 'text/plain',
  2477. 'application/rtf',
  2478. )
  2479. )
  2480. ) {
  2481. $type = false;
  2482. $ext = false;
  2483. }
  2484. } else {
  2485. if ( $type !== $real_mime ) {
  2486. /*
  2487. * Everything else including image/* and application/*:
  2488. * If the real content type doesn't match the file extension, assume it's dangerous.
  2489. */
  2490. $type = false;
  2491. $ext = false;
  2492. }
  2493. }
  2494. }
  2495. // The mime type must be allowed
  2496. if ( $type ) {
  2497. $allowed = get_allowed_mime_types();
  2498. if ( ! in_array( $type, $allowed ) ) {
  2499. $type = false;
  2500. $ext = false;
  2501. }
  2502. }
  2503. /**
  2504. * Filters the "real" file type of the given file.
  2505. *
  2506. * @since 3.0.0
  2507. * @since 5.1.0 The $real_mime parameter was added.
  2508. *
  2509. * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
  2510. * 'proper_filename' keys.
  2511. * @param string $file Full path to the file.
  2512. * @param string $filename The name of the file (may differ from $file due to
  2513. * $file being in a tmp directory).
  2514. * @param array $mimes Key is the file extension with value as the mime type.
  2515. * @param string|bool $real_mime The actual mime type or false if the type cannot be determined.
  2516. */
  2517. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes, $real_mime );
  2518. }
  2519. /**
  2520. * Returns the real mime type of an image file.
  2521. *
  2522. * This depends on exif_imagetype() or getimagesize() to determine real mime types.
  2523. *
  2524. * @since 4.7.1
  2525. *
  2526. * @param string $file Full path to the file.
  2527. * @return string|false The actual mime type or false if the type cannot be determined.
  2528. */
  2529. function wp_get_image_mime( $file ) {
  2530. /*
  2531. * Use exif_imagetype() to check the mimetype if available or fall back to
  2532. * getimagesize() if exif isn't avaialbe. If either function throws an Exception
  2533. * we assume the file could not be validated.
  2534. */
  2535. try {
  2536. if ( is_callable( 'exif_imagetype' ) ) {
  2537. $imagetype = exif_imagetype( $file );
  2538. $mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
  2539. } elseif ( function_exists( 'getimagesize' ) ) {
  2540. $imagesize = @getimagesize( $file );
  2541. $mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
  2542. } else {
  2543. $mime = false;
  2544. }
  2545. } catch ( Exception $e ) {
  2546. $mime = false;
  2547. }
  2548. return $mime;
  2549. }
  2550. /**
  2551. * Retrieve list of mime types and file extensions.
  2552. *
  2553. * @since 3.5.0
  2554. * @since 4.2.0 Support was added for GIMP (xcf) files.
  2555. *
  2556. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  2557. */
  2558. function wp_get_mime_types() {
  2559. /**
  2560. * Filters the list of mime types and file extensions.
  2561. *
  2562. * This filter should be used to add, not remove, mime types. To remove
  2563. * mime types, use the {@see 'upload_mimes'} filter.
  2564. *
  2565. * @since 3.5.0
  2566. *
  2567. * @param array $wp_get_mime_types Mime types keyed by the file extension regex
  2568. * corresponding to those types.
  2569. */
  2570. return apply_filters(
  2571. 'mime_types',
  2572. array(
  2573. // Image formats.
  2574. 'jpg|jpeg|jpe' => 'image/jpeg',
  2575. 'gif' => 'image/gif',
  2576. 'png' => 'image/png',
  2577. 'bmp' => 'image/bmp',
  2578. 'tiff|tif' => 'image/tiff',
  2579. 'ico' => 'image/x-icon',
  2580. // Video formats.
  2581. 'asf|asx' => 'video/x-ms-asf',
  2582. 'wmv' => 'video/x-ms-wmv',
  2583. 'wmx' => 'video/x-ms-wmx',
  2584. 'wm' => 'video/x-ms-wm',
  2585. 'avi' => 'video/avi',
  2586. 'divx' => 'video/divx',
  2587. 'flv' => 'video/x-flv',
  2588. 'mov|qt' => 'video/quicktime',
  2589. 'mpeg|mpg|mpe' => 'video/mpeg',
  2590. 'mp4|m4v' => 'video/mp4',
  2591. 'ogv' => 'video/ogg',
  2592. 'webm' => 'video/webm',
  2593. 'mkv' => 'video/x-matroska',
  2594. '3gp|3gpp' => 'video/3gpp', // Can also be audio
  2595. '3g2|3gp2' => 'video/3gpp2', // Can also be audio
  2596. // Text formats.
  2597. 'txt|asc|c|cc|h|srt' => 'text/plain',
  2598. 'csv' => 'text/csv',
  2599. 'tsv' => 'text/tab-separated-values',
  2600. 'ics' => 'text/calendar',
  2601. 'rtx' => 'text/richtext',
  2602. 'css' => 'text/css',
  2603. 'htm|html' => 'text/html',
  2604. 'vtt' => 'text/vtt',
  2605. 'dfxp' => 'application/ttaf+xml',
  2606. // Audio formats.
  2607. 'mp3|m4a|m4b' => 'audio/mpeg',
  2608. 'aac' => 'audio/aac',
  2609. 'ra|ram' => 'audio/x-realaudio',
  2610. 'wav' => 'audio/wav',
  2611. 'ogg|oga' => 'audio/ogg',
  2612. 'flac' => 'audio/flac',
  2613. 'mid|midi' => 'audio/midi',
  2614. 'wma' => 'audio/x-ms-wma',
  2615. 'wax' => 'audio/x-ms-wax',
  2616. 'mka' => 'audio/x-matroska',
  2617. // Misc application formats.
  2618. 'rtf' => 'application/rtf',
  2619. 'js' => 'application/javascript',
  2620. 'pdf' => 'application/pdf',
  2621. 'swf' => 'application/x-shockwave-flash',
  2622. 'class' => 'application/java',
  2623. 'tar' => 'application/x-tar',
  2624. 'zip' => 'application/zip',
  2625. 'gz|gzip' => 'application/x-gzip',
  2626. 'rar' => 'application/rar',
  2627. '7z' => 'application/x-7z-compressed',
  2628. 'exe' => 'application/x-msdownload',
  2629. 'psd' => 'application/octet-stream',
  2630. 'xcf' => 'application/octet-stream',
  2631. // MS Office formats.
  2632. 'doc' => 'application/msword',
  2633. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  2634. 'wri' => 'application/vnd.ms-write',
  2635. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  2636. 'mdb' => 'application/vnd.ms-access',
  2637. 'mpp' => 'application/vnd.ms-project',
  2638. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  2639. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  2640. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  2641. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  2642. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  2643. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  2644. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2645. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2646. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  2647. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2648. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2649. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  2650. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2651. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  2652. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2653. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  2654. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  2655. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2656. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  2657. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2658. 'oxps' => 'application/oxps',
  2659. 'xps' => 'application/vnd.ms-xpsdocument',
  2660. // OpenOffice formats.
  2661. 'odt' => 'application/vnd.oasis.opendocument.text',
  2662. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2663. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2664. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2665. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2666. 'odb' => 'application/vnd.oasis.opendocument.database',
  2667. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2668. // WordPerfect formats.
  2669. 'wp|wpd' => 'application/wordperfect',
  2670. // iWork formats.
  2671. 'key' => 'application/vnd.apple.keynote',
  2672. 'numbers' => 'application/vnd.apple.numbers',
  2673. 'pages' => 'application/vnd.apple.pages',
  2674. )
  2675. );
  2676. }
  2677. /**
  2678. * Retrieves the list of common file extensions and their types.
  2679. *
  2680. * @since 4.6.0
  2681. *
  2682. * @return array Array of file extensions types keyed by the type of file.
  2683. */
  2684. function wp_get_ext_types() {
  2685. /**
  2686. * Filters file type based on the extension name.
  2687. *
  2688. * @since 2.5.0
  2689. *
  2690. * @see wp_ext2type()
  2691. *
  2692. * @param array $ext2type Multi-dimensional array with extensions for a default set
  2693. * of file types.
  2694. */
  2695. return apply_filters(
  2696. 'ext2type',
  2697. array(
  2698. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
  2699. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  2700. 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  2701. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
  2702. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  2703. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  2704. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  2705. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  2706. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  2707. )
  2708. );
  2709. }
  2710. /**
  2711. * Retrieve list of allowed mime types and file extensions.
  2712. *
  2713. * @since 2.8.6
  2714. *
  2715. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  2716. * @return array Array of mime types keyed by the file extension regex corresponding
  2717. * to those types.
  2718. */
  2719. function get_allowed_mime_types( $user = null ) {
  2720. $t = wp_get_mime_types();
  2721. unset( $t['swf'], $t['exe'] );
  2722. if ( function_exists( 'current_user_can' ) ) {
  2723. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  2724. }
  2725. if ( empty( $unfiltered ) ) {
  2726. unset( $t['htm|html'], $t['js'] );
  2727. }
  2728. /**
  2729. * Filters list of allowed mime types and file extensions.
  2730. *
  2731. * @since 2.0.0
  2732. *
  2733. * @param array $t Mime types keyed by the file extension regex corresponding to
  2734. * those types. 'swf' and 'exe' removed from full list. 'htm|html' also
  2735. * removed depending on '$user' capabilities.
  2736. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  2737. */
  2738. return apply_filters( 'upload_mimes', $t, $user );
  2739. }
  2740. /**
  2741. * Display "Are You Sure" message to confirm the action being taken.
  2742. *
  2743. * If the action has the nonce explain message, then it will be displayed
  2744. * along with the "Are you sure?" message.
  2745. *
  2746. * @since 2.0.4
  2747. *
  2748. * @param string $action The nonce action.
  2749. */
  2750. function wp_nonce_ays( $action ) {
  2751. if ( 'log-out' == $action ) {
  2752. $html = sprintf(
  2753. /* translators: %s: Site title. */
  2754. __( 'You are attempting to log out of %s' ),
  2755. get_bloginfo( 'name' )
  2756. );
  2757. $html .= '</p><p>';
  2758. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  2759. $html .= sprintf(
  2760. /* translators: %s: Logout URL. */
  2761. __( 'Do you really want to <a href="%s">log out</a>?' ),
  2762. wp_logout_url( $redirect_to )
  2763. );
  2764. } else {
  2765. $html = __( 'The link you followed has expired.' );
  2766. if ( wp_get_referer() ) {
  2767. $html .= '</p><p>';
  2768. $html .= sprintf(
  2769. '<a href="%s">%s</a>',
  2770. esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
  2771. __( 'Please try again.' )
  2772. );
  2773. }
  2774. }
  2775. wp_die( $html, __( 'Something went wrong.' ), 403 );
  2776. }
  2777. /**
  2778. * Kills WordPress execution and displays HTML page with an error message.
  2779. *
  2780. * This function complements the `die()` PHP function. The difference is that
  2781. * HTML will be displayed to the user. It is recommended to use this function
  2782. * only when the execution should not continue any further. It is not recommended
  2783. * to call this function very often, and try to handle as many errors as possible
  2784. * silently or more gracefully.
  2785. *
  2786. * As a shorthand, the desired HTTP response code may be passed as an integer to
  2787. * the `$title` parameter (the default title would apply) or the `$args` parameter.
  2788. *
  2789. * @since 2.0.4
  2790. * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
  2791. * an integer to be used as the response code.
  2792. * @since 5.1.0 The `$link_url`, `$link_text`, and `$exit` arguments were added.
  2793. * @since 5.3.0 The `$charset` argument was added.
  2794. *
  2795. * @global WP_Query $wp_query WordPress Query object.
  2796. *
  2797. * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,
  2798. * and not an Ajax or XML-RPC request, the error's messages are used.
  2799. * Default empty.
  2800. * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
  2801. * error data with the key 'title' may be used to specify the title.
  2802. * If `$title` is an integer, then it is treated as the response
  2803. * code. Default empty.
  2804. * @param string|array|int $args {
  2805. * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
  2806. * as the response code. Default empty array.
  2807. *
  2808. * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
  2809. * @type string $link_url A URL to include a link to. Only works in combination with $link_text.
  2810. * Default empty string.
  2811. * @type string $link_text A label for the link to include. Only works in combination with $link_url.
  2812. * Default empty string.
  2813. * @type bool $back_link Whether to include a link to go back. Default false.
  2814. * @type string $text_direction The text direction. This is only useful internally, when WordPress
  2815. * is still loading and the site's locale is not set up yet. Accepts 'rtl'.
  2816. * Default is the value of is_rtl().
  2817. * @type string $charset Character set of the HTML output. Default 'utf-8'.
  2818. * @type string $code Error code to use. Default is 'wp_die', or the main error code if $message
  2819. * is a WP_Error.
  2820. * @type bool $exit Whether to exit the process after completion. Default true.
  2821. * }
  2822. */
  2823. function wp_die( $message = '', $title = '', $args = array() ) {
  2824. global $wp_query;
  2825. if ( is_int( $args ) ) {
  2826. $args = array( 'response' => $args );
  2827. } elseif ( is_int( $title ) ) {
  2828. $args = array( 'response' => $title );
  2829. $title = '';
  2830. }
  2831. if ( wp_doing_ajax() ) {
  2832. /**
  2833. * Filters the callback for killing WordPress execution for Ajax requests.
  2834. *
  2835. * @since 3.4.0
  2836. *
  2837. * @param callable $function Callback function name.
  2838. */
  2839. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2840. } elseif ( wp_is_json_request() ) {
  2841. /**
  2842. * Filters the callback for killing WordPress execution for JSON requests.
  2843. *
  2844. * @since 5.1.0
  2845. *
  2846. * @param callable $function Callback function name.
  2847. */
  2848. $function = apply_filters( 'wp_die_json_handler', '_json_wp_die_handler' );
  2849. } elseif ( wp_is_jsonp_request() ) {
  2850. /**
  2851. * Filters the callback for killing WordPress execution for JSONP requests.
  2852. *
  2853. * @since 5.2.0
  2854. *
  2855. * @param callable $function Callback function name.
  2856. */
  2857. $function = apply_filters( 'wp_die_jsonp_handler', '_jsonp_wp_die_handler' );
  2858. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2859. /**
  2860. * Filters the callback for killing WordPress execution for XML-RPC requests.
  2861. *
  2862. * @since 3.4.0
  2863. *
  2864. * @param callable $function Callback function name.
  2865. */
  2866. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2867. } elseif ( wp_is_xml_request()
  2868. || isset( $wp_query ) &&
  2869. ( function_exists( 'is_feed' ) && is_feed()
  2870. || function_exists( 'is_comment_feed' ) && is_comment_feed()
  2871. || function_exists( 'is_trackback' ) && is_trackback() ) ) {
  2872. /**
  2873. * Filters the callback for killing WordPress execution for XML requests.
  2874. *
  2875. * @since 5.2.0
  2876. *
  2877. * @param callable $function Callback function name.
  2878. */
  2879. $function = apply_filters( 'wp_die_xml_handler', '_xml_wp_die_handler' );
  2880. } else {
  2881. /**
  2882. * Filters the callback for killing WordPress execution for all non-Ajax, non-JSON, non-XML requests.
  2883. *
  2884. * @since 3.0.0
  2885. *
  2886. * @param callable $function Callback function name.
  2887. */
  2888. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  2889. }
  2890. call_user_func( $function, $message, $title, $args );
  2891. }
  2892. /**
  2893. * Kills WordPress execution and displays HTML page with an error message.
  2894. *
  2895. * This is the default handler for wp_die(). If you want a custom one,
  2896. * you can override this using the {@see 'wp_die_handler'} filter in wp_die().
  2897. *
  2898. * @since 3.0.0
  2899. * @access private
  2900. *
  2901. * @param string|WP_Error $message Error message or WP_Error object.
  2902. * @param string $title Optional. Error title. Default empty.
  2903. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2904. */
  2905. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2906. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  2907. if ( is_string( $message ) ) {
  2908. if ( ! empty( $parsed_args['additional_errors'] ) ) {
  2909. $message = array_merge(
  2910. array( $message ),
  2911. wp_list_pluck( $parsed_args['additional_errors'], 'message' )
  2912. );
  2913. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $message ) . "</li>\n\t</ul>";
  2914. }
  2915. $message = sprintf(
  2916. '<div class="wp-die-message">%s</div>',
  2917. $message
  2918. );
  2919. }
  2920. $have_gettext = function_exists( '__' );
  2921. if ( ! empty( $parsed_args['link_url'] ) && ! empty( $parsed_args['link_text'] ) ) {
  2922. $link_url = $parsed_args['link_url'];
  2923. if ( function_exists( 'esc_url' ) ) {
  2924. $link_url = esc_url( $link_url );
  2925. }
  2926. $link_text = $parsed_args['link_text'];
  2927. $message .= "\n<p><a href='{$link_url}'>{$link_text}</a></p>";
  2928. }
  2929. if ( isset( $parsed_args['back_link'] ) && $parsed_args['back_link'] ) {
  2930. $back_text = $have_gettext ? __( '&laquo; Back' ) : '&laquo; Back';
  2931. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  2932. }
  2933. if ( ! did_action( 'admin_head' ) ) :
  2934. if ( ! headers_sent() ) {
  2935. header( "Content-Type: text/html; charset={$parsed_args['charset']}" );
  2936. status_header( $parsed_args['response'] );
  2937. nocache_headers();
  2938. }
  2939. $text_direction = $parsed_args['text_direction'];
  2940. if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) {
  2941. $dir_attr = get_language_attributes();
  2942. } else {
  2943. $dir_attr = "dir='$text_direction'";
  2944. }
  2945. ?>
  2946. <!DOCTYPE html>
  2947. <html xmlns="http://www.w3.org/1999/xhtml" <?php echo $dir_attr; ?>>
  2948. <head>
  2949. <meta http-equiv="Content-Type" content="text/html; charset=<?php echo $parsed_args['charset']; ?>" />
  2950. <meta name="viewport" content="width=device-width">
  2951. <?php
  2952. if ( function_exists( 'wp_no_robots' ) ) {
  2953. wp_no_robots();
  2954. }
  2955. ?>
  2956. <title><?php echo $title; ?></title>
  2957. <style type="text/css">
  2958. html {
  2959. background: #f1f1f1;
  2960. }
  2961. body {
  2962. background: #fff;
  2963. color: #444;
  2964. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  2965. margin: 2em auto;
  2966. padding: 1em 2em;
  2967. max-width: 700px;
  2968. -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
  2969. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.13);
  2970. }
  2971. h1 {
  2972. border-bottom: 1px solid #dadada;
  2973. clear: both;
  2974. color: #666;
  2975. font-size: 24px;
  2976. margin: 30px 0 0 0;
  2977. padding: 0;
  2978. padding-bottom: 7px;
  2979. }
  2980. #error-page {
  2981. margin-top: 50px;
  2982. }
  2983. #error-page p,
  2984. #error-page .wp-die-message {
  2985. font-size: 14px;
  2986. line-height: 1.5;
  2987. margin: 25px 0 20px;
  2988. }
  2989. #error-page code {
  2990. font-family: Consolas, Monaco, monospace;
  2991. }
  2992. ul li {
  2993. margin-bottom: 10px;
  2994. font-size: 14px ;
  2995. }
  2996. a {
  2997. color: #0073aa;
  2998. }
  2999. a:hover,
  3000. a:active {
  3001. color: #00a0d2;
  3002. }
  3003. a:focus {
  3004. color: #124964;
  3005. -webkit-box-shadow:
  3006. 0 0 0 1px #5b9dd9,
  3007. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3008. box-shadow:
  3009. 0 0 0 1px #5b9dd9,
  3010. 0 0 2px 1px rgba(30, 140, 190, 0.8);
  3011. outline: none;
  3012. }
  3013. .button {
  3014. background: #f7f7f7;
  3015. border: 1px solid #ccc;
  3016. color: #555;
  3017. display: inline-block;
  3018. text-decoration: none;
  3019. font-size: 13px;
  3020. line-height: 2;
  3021. height: 28px;
  3022. margin: 0;
  3023. padding: 0 10px 1px;
  3024. cursor: pointer;
  3025. -webkit-border-radius: 3px;
  3026. -webkit-appearance: none;
  3027. border-radius: 3px;
  3028. white-space: nowrap;
  3029. -webkit-box-sizing: border-box;
  3030. -moz-box-sizing: border-box;
  3031. box-sizing: border-box;
  3032. -webkit-box-shadow: 0 1px 0 #ccc;
  3033. box-shadow: 0 1px 0 #ccc;
  3034. vertical-align: top;
  3035. }
  3036. .button.button-large {
  3037. height: 30px;
  3038. line-height: 2.15384615;
  3039. padding: 0 12px 2px;
  3040. }
  3041. .button:hover,
  3042. .button:focus {
  3043. background: #fafafa;
  3044. border-color: #999;
  3045. color: #23282d;
  3046. }
  3047. .button:focus {
  3048. border-color: #5b9dd9;
  3049. -webkit-box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
  3050. box-shadow: 0 0 3px rgba(0, 115, 170, 0.8);
  3051. outline: none;
  3052. }
  3053. .button:active {
  3054. background: #eee;
  3055. border-color: #999;
  3056. -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
  3057. box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
  3058. }
  3059. <?php
  3060. if ( 'rtl' == $text_direction ) {
  3061. echo 'body { font-family: Tahoma, Arial; }';
  3062. }
  3063. ?>
  3064. </style>
  3065. </head>
  3066. <body id="error-page">
  3067. <?php endif; // ! did_action( 'admin_head' ) ?>
  3068. <?php echo $message; ?>
  3069. </body>
  3070. </html>
  3071. <?php
  3072. if ( $parsed_args['exit'] ) {
  3073. die();
  3074. }
  3075. }
  3076. /**
  3077. * Kills WordPress execution and displays Ajax response with an error message.
  3078. *
  3079. * This is the handler for wp_die() when processing Ajax requests.
  3080. *
  3081. * @since 3.4.0
  3082. * @access private
  3083. *
  3084. * @param string $message Error message.
  3085. * @param string $title Optional. Error title (unused). Default empty.
  3086. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3087. */
  3088. function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
  3089. // Set default 'response' to 200 for AJAX requests.
  3090. $args = wp_parse_args(
  3091. $args,
  3092. array( 'response' => 200 )
  3093. );
  3094. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3095. if ( ! headers_sent() ) {
  3096. // This is intentional. For backward-compatibility, support passing null here.
  3097. if ( null !== $args['response'] ) {
  3098. status_header( $parsed_args['response'] );
  3099. }
  3100. nocache_headers();
  3101. }
  3102. if ( is_scalar( $message ) ) {
  3103. $message = (string) $message;
  3104. } else {
  3105. $message = '0';
  3106. }
  3107. if ( $parsed_args['exit'] ) {
  3108. die( $message );
  3109. }
  3110. echo $message;
  3111. }
  3112. /**
  3113. * Kills WordPress execution and displays JSON response with an error message.
  3114. *
  3115. * This is the handler for wp_die() when processing JSON requests.
  3116. *
  3117. * @since 5.1.0
  3118. * @access private
  3119. *
  3120. * @param string $message Error message.
  3121. * @param string $title Optional. Error title. Default empty.
  3122. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3123. */
  3124. function _json_wp_die_handler( $message, $title = '', $args = array() ) {
  3125. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3126. $data = array(
  3127. 'code' => $parsed_args['code'],
  3128. 'message' => $message,
  3129. 'data' => array(
  3130. 'status' => $parsed_args['response'],
  3131. ),
  3132. 'additional_errors' => $parsed_args['additional_errors'],
  3133. );
  3134. if ( ! headers_sent() ) {
  3135. header( "Content-Type: application/json; charset={$parsed_args['charset']}" );
  3136. if ( null !== $parsed_args['response'] ) {
  3137. status_header( $parsed_args['response'] );
  3138. }
  3139. nocache_headers();
  3140. }
  3141. echo wp_json_encode( $data );
  3142. if ( $parsed_args['exit'] ) {
  3143. die();
  3144. }
  3145. }
  3146. /**
  3147. * Kills WordPress execution and displays JSONP response with an error message.
  3148. *
  3149. * This is the handler for wp_die() when processing JSONP requests.
  3150. *
  3151. * @since 5.2.0
  3152. * @access private
  3153. *
  3154. * @param string $message Error message.
  3155. * @param string $title Optional. Error title. Default empty.
  3156. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3157. */
  3158. function _jsonp_wp_die_handler( $message, $title = '', $args = array() ) {
  3159. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3160. $data = array(
  3161. 'code' => $parsed_args['code'],
  3162. 'message' => $message,
  3163. 'data' => array(
  3164. 'status' => $parsed_args['response'],
  3165. ),
  3166. 'additional_errors' => $parsed_args['additional_errors'],
  3167. );
  3168. if ( ! headers_sent() ) {
  3169. header( "Content-Type: application/javascript; charset={$parsed_args['charset']}" );
  3170. header( 'X-Content-Type-Options: nosniff' );
  3171. header( 'X-Robots-Tag: noindex' );
  3172. if ( null !== $parsed_args['response'] ) {
  3173. status_header( $parsed_args['response'] );
  3174. }
  3175. nocache_headers();
  3176. }
  3177. $result = wp_json_encode( $data );
  3178. $jsonp_callback = $_GET['_jsonp'];
  3179. echo '/**/' . $jsonp_callback . '(' . $result . ')';
  3180. if ( $parsed_args['exit'] ) {
  3181. die();
  3182. }
  3183. }
  3184. /**
  3185. * Kills WordPress execution and displays XML response with an error message.
  3186. *
  3187. * This is the handler for wp_die() when processing XMLRPC requests.
  3188. *
  3189. * @since 3.2.0
  3190. * @access private
  3191. *
  3192. * @global wp_xmlrpc_server $wp_xmlrpc_server
  3193. *
  3194. * @param string $message Error message.
  3195. * @param string $title Optional. Error title. Default empty.
  3196. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3197. */
  3198. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  3199. global $wp_xmlrpc_server;
  3200. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3201. if ( ! headers_sent() ) {
  3202. nocache_headers();
  3203. }
  3204. if ( $wp_xmlrpc_server ) {
  3205. $error = new IXR_Error( $parsed_args['response'], $message );
  3206. $wp_xmlrpc_server->output( $error->getXml() );
  3207. }
  3208. if ( $parsed_args['exit'] ) {
  3209. die();
  3210. }
  3211. }
  3212. /**
  3213. * Kills WordPress execution and displays XML response with an error message.
  3214. *
  3215. * This is the handler for wp_die() when processing XML requests.
  3216. *
  3217. * @since 5.2.0
  3218. * @access private
  3219. *
  3220. * @param string $message Error message.
  3221. * @param string $title Optional. Error title. Default empty.
  3222. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3223. */
  3224. function _xml_wp_die_handler( $message, $title = '', $args = array() ) {
  3225. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3226. $message = htmlspecialchars( $message );
  3227. $title = htmlspecialchars( $title );
  3228. $xml = <<<EOD
  3229. <error>
  3230. <code>{$parsed_args['code']}</code>
  3231. <title><![CDATA[{$title}]]></title>
  3232. <message><![CDATA[{$message}]]></message>
  3233. <data>
  3234. <status>{$parsed_args['response']}</status>
  3235. </data>
  3236. </error>
  3237. EOD;
  3238. if ( ! headers_sent() ) {
  3239. header( "Content-Type: text/xml; charset={$parsed_args['charset']}" );
  3240. if ( null !== $parsed_args['response'] ) {
  3241. status_header( $parsed_args['response'] );
  3242. }
  3243. nocache_headers();
  3244. }
  3245. echo $xml;
  3246. if ( $parsed_args['exit'] ) {
  3247. die();
  3248. }
  3249. }
  3250. /**
  3251. * Kills WordPress execution and displays an error message.
  3252. *
  3253. * This is the handler for wp_die() when processing APP requests.
  3254. *
  3255. * @since 3.4.0
  3256. * @since 5.1.0 Added the $title and $args parameters.
  3257. * @access private
  3258. *
  3259. * @param string $message Optional. Response to print. Default empty.
  3260. * @param string $title Optional. Error title (unused). Default empty.
  3261. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3262. */
  3263. function _scalar_wp_die_handler( $message = '', $title = '', $args = array() ) {
  3264. list( $message, $title, $parsed_args ) = _wp_die_process_input( $message, $title, $args );
  3265. if ( $parsed_args['exit'] ) {
  3266. if ( is_scalar( $message ) ) {
  3267. die( (string) $message );
  3268. }
  3269. die();
  3270. }
  3271. if ( is_scalar( $message ) ) {
  3272. echo (string) $message;
  3273. }
  3274. }
  3275. /**
  3276. * Processes arguments passed to wp_die() consistently for its handlers.
  3277. *
  3278. * @since 5.1.0
  3279. * @access private
  3280. *
  3281. * @param string|WP_Error $message Error message or WP_Error object.
  3282. * @param string $title Optional. Error title. Default empty.
  3283. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  3284. * @return array {
  3285. * Processed arguments.
  3286. *
  3287. * @type string $0 Error message.
  3288. * @type string $1 Error title.
  3289. * @type array $2 Arguments to control behavior.
  3290. * }
  3291. */
  3292. function _wp_die_process_input( $message, $title = '', $args = array() ) {
  3293. $defaults = array(
  3294. 'response' => 0,
  3295. 'code' => '',
  3296. 'exit' => true,
  3297. 'back_link' => false,
  3298. 'link_url' => '',
  3299. 'link_text' => '',
  3300. 'text_direction' => '',
  3301. 'charset' => 'utf-8',
  3302. 'additional_errors' => array(),
  3303. );
  3304. $args = wp_parse_args( $args, $defaults );
  3305. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  3306. if ( ! empty( $message->errors ) ) {
  3307. $errors = array();
  3308. foreach ( (array) $message->errors as $error_code => $error_messages ) {
  3309. foreach ( (array) $error_messages as $error_message ) {
  3310. $errors[] = array(
  3311. 'code' => $error_code,
  3312. 'message' => $error_message,
  3313. 'data' => $message->get_error_data( $error_code ),
  3314. );
  3315. }
  3316. }
  3317. $message = $errors[0]['message'];
  3318. if ( empty( $args['code'] ) ) {
  3319. $args['code'] = $errors[0]['code'];
  3320. }
  3321. if ( empty( $args['response'] ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['status'] ) ) {
  3322. $args['response'] = $errors[0]['data']['status'];
  3323. }
  3324. if ( empty( $title ) && is_array( $errors[0]['data'] ) && ! empty( $errors[0]['data']['title'] ) ) {
  3325. $title = $errors[0]['data']['title'];
  3326. }
  3327. unset( $errors[0] );
  3328. $args['additional_errors'] = array_values( $errors );
  3329. } else {
  3330. $message = '';
  3331. }
  3332. }
  3333. $have_gettext = function_exists( '__' );
  3334. // The $title and these specific $args must always have a non-empty value.
  3335. if ( empty( $args['code'] ) ) {
  3336. $args['code'] = 'wp_die';
  3337. }
  3338. if ( empty( $args['response'] ) ) {
  3339. $args['response'] = 500;
  3340. }
  3341. if ( empty( $title ) ) {
  3342. $title = $have_gettext ? __( 'WordPress &rsaquo; Error' ) : 'WordPress &rsaquo; Error';
  3343. }
  3344. if ( empty( $args['text_direction'] ) || ! in_array( $args['text_direction'], array( 'ltr', 'rtl' ), true ) ) {
  3345. $args['text_direction'] = 'ltr';
  3346. if ( function_exists( 'is_rtl' ) && is_rtl() ) {
  3347. $args['text_direction'] = 'rtl';
  3348. }
  3349. }
  3350. if ( ! empty( $args['charset'] ) ) {
  3351. $args['charset'] = _canonical_charset( $args['charset'] );
  3352. }
  3353. return array( $message, $title, $args );
  3354. }
  3355. /**
  3356. * Encode a variable into JSON, with some sanity checks.
  3357. *
  3358. * @since 4.1.0
  3359. * @since 5.3.0 No longer handles support for PHP < 5.6.
  3360. *
  3361. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3362. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  3363. * @param int $depth Optional. Maximum depth to walk through $data. Must be
  3364. * greater than 0. Default 512.
  3365. * @return string|false The JSON encoded string, or false if it cannot be encoded.
  3366. */
  3367. function wp_json_encode( $data, $options = 0, $depth = 512 ) {
  3368. $json = json_encode( $data, $options, $depth );
  3369. // If json_encode() was successful, no need to do more sanity checking.
  3370. if ( false !== $json ) {
  3371. return $json;
  3372. }
  3373. try {
  3374. $data = _wp_json_sanity_check( $data, $depth );
  3375. } catch ( Exception $e ) {
  3376. return false;
  3377. }
  3378. return json_encode( $data, $options, $depth );
  3379. }
  3380. /**
  3381. * Perform sanity checks on data that shall be encoded to JSON.
  3382. *
  3383. * @ignore
  3384. * @since 4.1.0
  3385. * @access private
  3386. *
  3387. * @see wp_json_encode()
  3388. *
  3389. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  3390. * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
  3391. * @return mixed The sanitized data that shall be encoded to JSON.
  3392. */
  3393. function _wp_json_sanity_check( $data, $depth ) {
  3394. if ( $depth < 0 ) {
  3395. throw new Exception( 'Reached depth limit' );
  3396. }
  3397. if ( is_array( $data ) ) {
  3398. $output = array();
  3399. foreach ( $data as $id => $el ) {
  3400. // Don't forget to sanitize the ID!
  3401. if ( is_string( $id ) ) {
  3402. $clean_id = _wp_json_convert_string( $id );
  3403. } else {
  3404. $clean_id = $id;
  3405. }
  3406. // Check the element type, so that we're only recursing if we really have to.
  3407. if ( is_array( $el ) || is_object( $el ) ) {
  3408. $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
  3409. } elseif ( is_string( $el ) ) {
  3410. $output[ $clean_id ] = _wp_json_convert_string( $el );
  3411. } else {
  3412. $output[ $clean_id ] = $el;
  3413. }
  3414. }
  3415. } elseif ( is_object( $data ) ) {
  3416. $output = new stdClass;
  3417. foreach ( $data as $id => $el ) {
  3418. if ( is_string( $id ) ) {
  3419. $clean_id = _wp_json_convert_string( $id );
  3420. } else {
  3421. $clean_id = $id;
  3422. }
  3423. if ( is_array( $el ) || is_object( $el ) ) {
  3424. $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
  3425. } elseif ( is_string( $el ) ) {
  3426. $output->$clean_id = _wp_json_convert_string( $el );
  3427. } else {
  3428. $output->$clean_id = $el;
  3429. }
  3430. }
  3431. } elseif ( is_string( $data ) ) {
  3432. return _wp_json_convert_string( $data );
  3433. } else {
  3434. return $data;
  3435. }
  3436. return $output;
  3437. }
  3438. /**
  3439. * Convert a string to UTF-8, so that it can be safely encoded to JSON.
  3440. *
  3441. * @ignore
  3442. * @since 4.1.0
  3443. * @access private
  3444. *
  3445. * @see _wp_json_sanity_check()
  3446. *
  3447. * @staticvar bool $use_mb
  3448. *
  3449. * @param string $string The string which is to be converted.
  3450. * @return string The checked string.
  3451. */
  3452. function _wp_json_convert_string( $string ) {
  3453. static $use_mb = null;
  3454. if ( is_null( $use_mb ) ) {
  3455. $use_mb = function_exists( 'mb_convert_encoding' );
  3456. }
  3457. if ( $use_mb ) {
  3458. $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
  3459. if ( $encoding ) {
  3460. return mb_convert_encoding( $string, 'UTF-8', $encoding );
  3461. } else {
  3462. return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
  3463. }
  3464. } else {
  3465. return wp_check_invalid_utf8( $string, true );
  3466. }
  3467. }
  3468. /**
  3469. * Prepares response data to be serialized to JSON.
  3470. *
  3471. * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
  3472. *
  3473. * @ignore
  3474. * @since 4.4.0
  3475. * @deprecated 5.3.0 This function is no longer needed as support for PHP 5.2-5.3
  3476. * has been dropped.
  3477. * @access private
  3478. *
  3479. * @param mixed $data Native representation.
  3480. * @return bool|int|float|null|string|array Data ready for `json_encode()`.
  3481. */
  3482. function _wp_json_prepare_data( $data ) {
  3483. _deprecated_function( __FUNCTION__, '5.3.0' );
  3484. return $data;
  3485. }
  3486. /**
  3487. * Send a JSON response back to an Ajax request.
  3488. *
  3489. * @since 3.5.0
  3490. * @since 4.7.0 The `$status_code` parameter was added.
  3491. *
  3492. * @param mixed $response Variable (usually an array or object) to encode as JSON,
  3493. * then print and die.
  3494. * @param int $status_code The HTTP status code to output.
  3495. */
  3496. function wp_send_json( $response, $status_code = null ) {
  3497. if ( ! headers_sent() ) {
  3498. header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  3499. if ( null !== $status_code ) {
  3500. status_header( $status_code );
  3501. }
  3502. }
  3503. echo wp_json_encode( $response );
  3504. if ( wp_doing_ajax() ) {
  3505. wp_die(
  3506. '',
  3507. '',
  3508. array(
  3509. 'response' => null,
  3510. )
  3511. );
  3512. } else {
  3513. die;
  3514. }
  3515. }
  3516. /**
  3517. * Send a JSON response back to an Ajax request, indicating success.
  3518. *
  3519. * @since 3.5.0
  3520. * @since 4.7.0 The `$status_code` parameter was added.
  3521. *
  3522. * @param mixed $data Data to encode as JSON, then print and die.
  3523. * @param int $status_code The HTTP status code to output.
  3524. */
  3525. function wp_send_json_success( $data = null, $status_code = null ) {
  3526. $response = array( 'success' => true );
  3527. if ( isset( $data ) ) {
  3528. $response['data'] = $data;
  3529. }
  3530. wp_send_json( $response, $status_code );
  3531. }
  3532. /**
  3533. * Send a JSON response back to an Ajax request, indicating failure.
  3534. *
  3535. * If the `$data` parameter is a WP_Error object, the errors
  3536. * within the object are processed and output as an array of error
  3537. * codes and corresponding messages. All other types are output
  3538. * without further processing.
  3539. *
  3540. * @since 3.5.0
  3541. * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
  3542. * @since 4.7.0 The `$status_code` parameter was added.
  3543. *
  3544. * @param mixed $data Data to encode as JSON, then print and die.
  3545. * @param int $status_code The HTTP status code to output.
  3546. */
  3547. function wp_send_json_error( $data = null, $status_code = null ) {
  3548. $response = array( 'success' => false );
  3549. if ( isset( $data ) ) {
  3550. if ( is_wp_error( $data ) ) {
  3551. $result = array();
  3552. foreach ( $data->errors as $code => $messages ) {
  3553. foreach ( $messages as $message ) {
  3554. $result[] = array(
  3555. 'code' => $code,
  3556. 'message' => $message,
  3557. );
  3558. }
  3559. }
  3560. $response['data'] = $result;
  3561. } else {
  3562. $response['data'] = $data;
  3563. }
  3564. }
  3565. wp_send_json( $response, $status_code );
  3566. }
  3567. /**
  3568. * Checks that a JSONP callback is a valid JavaScript callback.
  3569. *
  3570. * Only allows alphanumeric characters and the dot character in callback
  3571. * function names. This helps to mitigate XSS attacks caused by directly
  3572. * outputting user input.
  3573. *
  3574. * @since 4.6.0
  3575. *
  3576. * @param string $callback Supplied JSONP callback function.
  3577. * @return bool True if valid callback, otherwise false.
  3578. */
  3579. function wp_check_jsonp_callback( $callback ) {
  3580. if ( ! is_string( $callback ) ) {
  3581. return false;
  3582. }
  3583. preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
  3584. return 0 === $illegal_char_count;
  3585. }
  3586. /**
  3587. * Retrieve the WordPress home page URL.
  3588. *
  3589. * If the constant named 'WP_HOME' exists, then it will be used and returned
  3590. * by the function. This can be used to counter the redirection on your local
  3591. * development environment.
  3592. *
  3593. * @since 2.2.0
  3594. * @access private
  3595. *
  3596. * @see WP_HOME
  3597. *
  3598. * @param string $url URL for the home location.
  3599. * @return string Homepage location.
  3600. */
  3601. function _config_wp_home( $url = '' ) {
  3602. if ( defined( 'WP_HOME' ) ) {
  3603. return untrailingslashit( WP_HOME );
  3604. }
  3605. return $url;
  3606. }
  3607. /**
  3608. * Retrieve the WordPress site URL.
  3609. *
  3610. * If the constant named 'WP_SITEURL' is defined, then the value in that
  3611. * constant will always be returned. This can be used for debugging a site
  3612. * on your localhost while not having to change the database to your URL.
  3613. *
  3614. * @since 2.2.0
  3615. * @access private
  3616. *
  3617. * @see WP_SITEURL
  3618. *
  3619. * @param string $url URL to set the WordPress site location.
  3620. * @return string The WordPress Site URL.
  3621. */
  3622. function _config_wp_siteurl( $url = '' ) {
  3623. if ( defined( 'WP_SITEURL' ) ) {
  3624. return untrailingslashit( WP_SITEURL );
  3625. }
  3626. return $url;
  3627. }
  3628. /**
  3629. * Delete the fresh site option.
  3630. *
  3631. * @since 4.7.0
  3632. * @access private
  3633. */
  3634. function _delete_option_fresh_site() {
  3635. update_option( 'fresh_site', '0' );
  3636. }
  3637. /**
  3638. * Set the localized direction for MCE plugin.
  3639. *
  3640. * Will only set the direction to 'rtl', if the WordPress locale has
  3641. * the text direction set to 'rtl'.
  3642. *
  3643. * Fills in the 'directionality' setting, enables the 'directionality'
  3644. * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  3645. * 'theme_advanced_buttons1' array keys. These keys are then returned
  3646. * in the $mce_init (TinyMCE settings) array.
  3647. *
  3648. * @since 2.1.0
  3649. * @access private
  3650. *
  3651. * @param array $mce_init MCE settings array.
  3652. * @return array Direction set for 'rtl', if needed by locale.
  3653. */
  3654. function _mce_set_direction( $mce_init ) {
  3655. if ( is_rtl() ) {
  3656. $mce_init['directionality'] = 'rtl';
  3657. $mce_init['rtl_ui'] = true;
  3658. if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
  3659. $mce_init['plugins'] .= ',directionality';
  3660. }
  3661. if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
  3662. $mce_init['toolbar1'] .= ',ltr';
  3663. }
  3664. }
  3665. return $mce_init;
  3666. }
  3667. /**
  3668. * Convert smiley code to the icon graphic file equivalent.
  3669. *
  3670. * You can turn off smilies, by going to the write setting screen and unchecking
  3671. * the box, or by setting 'use_smilies' option to false or removing the option.
  3672. *
  3673. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  3674. * to an array, with the key the code the blogger types in and the value the
  3675. * image file.
  3676. *
  3677. * The $wp_smiliessearch global is for the regular expression and is set each
  3678. * time the function is called.
  3679. *
  3680. * The full list of smilies can be found in the function and won't be listed in
  3681. * the description. Probably should create a Codex page for it, so that it is
  3682. * available.
  3683. *
  3684. * @global array $wpsmiliestrans
  3685. * @global array $wp_smiliessearch
  3686. *
  3687. * @since 2.2.0
  3688. */
  3689. function smilies_init() {
  3690. global $wpsmiliestrans, $wp_smiliessearch;
  3691. // don't bother setting up smilies if they are disabled
  3692. if ( ! get_option( 'use_smilies' ) ) {
  3693. return;
  3694. }
  3695. if ( ! isset( $wpsmiliestrans ) ) {
  3696. $wpsmiliestrans = array(
  3697. ':mrgreen:' => 'mrgreen.png',
  3698. ':neutral:' => "\xf0\x9f\x98\x90",
  3699. ':twisted:' => "\xf0\x9f\x98\x88",
  3700. ':arrow:' => "\xe2\x9e\xa1",
  3701. ':shock:' => "\xf0\x9f\x98\xaf",
  3702. ':smile:' => "\xf0\x9f\x99\x82",
  3703. ':???:' => "\xf0\x9f\x98\x95",
  3704. ':cool:' => "\xf0\x9f\x98\x8e",
  3705. ':evil:' => "\xf0\x9f\x91\xbf",
  3706. ':grin:' => "\xf0\x9f\x98\x80",
  3707. ':idea:' => "\xf0\x9f\x92\xa1",
  3708. ':oops:' => "\xf0\x9f\x98\xb3",
  3709. ':razz:' => "\xf0\x9f\x98\x9b",
  3710. ':roll:' => "\xf0\x9f\x99\x84",
  3711. ':wink:' => "\xf0\x9f\x98\x89",
  3712. ':cry:' => "\xf0\x9f\x98\xa5",
  3713. ':eek:' => "\xf0\x9f\x98\xae",
  3714. ':lol:' => "\xf0\x9f\x98\x86",
  3715. ':mad:' => "\xf0\x9f\x98\xa1",
  3716. ':sad:' => "\xf0\x9f\x99\x81",
  3717. '8-)' => "\xf0\x9f\x98\x8e",
  3718. '8-O' => "\xf0\x9f\x98\xaf",
  3719. ':-(' => "\xf0\x9f\x99\x81",
  3720. ':-)' => "\xf0\x9f\x99\x82",
  3721. ':-?' => "\xf0\x9f\x98\x95",
  3722. ':-D' => "\xf0\x9f\x98\x80",
  3723. ':-P' => "\xf0\x9f\x98\x9b",
  3724. ':-o' => "\xf0\x9f\x98\xae",
  3725. ':-x' => "\xf0\x9f\x98\xa1",
  3726. ':-|' => "\xf0\x9f\x98\x90",
  3727. ';-)' => "\xf0\x9f\x98\x89",
  3728. // This one transformation breaks regular text with frequency.
  3729. // '8)' => "\xf0\x9f\x98\x8e",
  3730. '8O' => "\xf0\x9f\x98\xaf",
  3731. ':(' => "\xf0\x9f\x99\x81",
  3732. ':)' => "\xf0\x9f\x99\x82",
  3733. ':?' => "\xf0\x9f\x98\x95",
  3734. ':D' => "\xf0\x9f\x98\x80",
  3735. ':P' => "\xf0\x9f\x98\x9b",
  3736. ':o' => "\xf0\x9f\x98\xae",
  3737. ':x' => "\xf0\x9f\x98\xa1",
  3738. ':|' => "\xf0\x9f\x98\x90",
  3739. ';)' => "\xf0\x9f\x98\x89",
  3740. ':!:' => "\xe2\x9d\x97",
  3741. ':?:' => "\xe2\x9d\x93",
  3742. );
  3743. }
  3744. /**
  3745. * Filters all the smilies.
  3746. *
  3747. * This filter must be added before `smilies_init` is run, as
  3748. * it is normally only run once to setup the smilies regex.
  3749. *
  3750. * @since 4.7.0
  3751. *
  3752. * @param array $wpsmiliestrans List of the smilies.
  3753. */
  3754. $wpsmiliestrans = apply_filters( 'smilies', $wpsmiliestrans );
  3755. if ( count( $wpsmiliestrans ) == 0 ) {
  3756. return;
  3757. }
  3758. /*
  3759. * NOTE: we sort the smilies in reverse key order. This is to make sure
  3760. * we match the longest possible smilie (:???: vs :?) as the regular
  3761. * expression used below is first-match
  3762. */
  3763. krsort( $wpsmiliestrans );
  3764. $spaces = wp_spaces_regexp();
  3765. // Begin first "subpattern"
  3766. $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  3767. $subchar = '';
  3768. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  3769. $firstchar = substr( $smiley, 0, 1 );
  3770. $rest = substr( $smiley, 1 );
  3771. // new subpattern?
  3772. if ( $firstchar != $subchar ) {
  3773. if ( $subchar != '' ) {
  3774. $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern"
  3775. $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
  3776. }
  3777. $subchar = $firstchar;
  3778. $wp_smiliessearch .= preg_quote( $firstchar, '/' ) . '(?:';
  3779. } else {
  3780. $wp_smiliessearch .= '|';
  3781. }
  3782. $wp_smiliessearch .= preg_quote( $rest, '/' );
  3783. }
  3784. $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  3785. }
  3786. /**
  3787. * Merge user defined arguments into defaults array.
  3788. *
  3789. * This function is used throughout WordPress to allow for both string or array
  3790. * to be merged into another array.
  3791. *
  3792. * @since 2.2.0
  3793. * @since 2.3.0 `$args` can now also be an object.
  3794. *
  3795. * @param string|array|object $args Value to merge with $defaults.
  3796. * @param array $defaults Optional. Array that serves as the defaults. Default empty.
  3797. * @return array Merged user defined values with defaults.
  3798. */
  3799. function wp_parse_args( $args, $defaults = '' ) {
  3800. if ( is_object( $args ) ) {
  3801. $parsed_args = get_object_vars( $args );
  3802. } elseif ( is_array( $args ) ) {
  3803. $parsed_args =& $args;
  3804. } else {
  3805. wp_parse_str( $args, $parsed_args );
  3806. }
  3807. if ( is_array( $defaults ) ) {
  3808. return array_merge( $defaults, $parsed_args );
  3809. }
  3810. return $parsed_args;
  3811. }
  3812. /**
  3813. * Cleans up an array, comma- or space-separated list of scalar values.
  3814. *
  3815. * @since 5.1.0
  3816. *
  3817. * @param array|string $list List of values.
  3818. * @return array Sanitized array of values.
  3819. */
  3820. function wp_parse_list( $list ) {
  3821. if ( ! is_array( $list ) ) {
  3822. return preg_split( '/[\s,]+/', $list, -1, PREG_SPLIT_NO_EMPTY );
  3823. }
  3824. return $list;
  3825. }
  3826. /**
  3827. * Clean up an array, comma- or space-separated list of IDs.
  3828. *
  3829. * @since 3.0.0
  3830. *
  3831. * @param array|string $list List of ids.
  3832. * @return array Sanitized array of IDs.
  3833. */
  3834. function wp_parse_id_list( $list ) {
  3835. $list = wp_parse_list( $list );
  3836. return array_unique( array_map( 'absint', $list ) );
  3837. }
  3838. /**
  3839. * Clean up an array, comma- or space-separated list of slugs.
  3840. *
  3841. * @since 4.7.0
  3842. *
  3843. * @param array|string $list List of slugs.
  3844. * @return array Sanitized array of slugs.
  3845. */
  3846. function wp_parse_slug_list( $list ) {
  3847. $list = wp_parse_list( $list );
  3848. return array_unique( array_map( 'sanitize_title', $list ) );
  3849. }
  3850. /**
  3851. * Extract a slice of an array, given a list of keys.
  3852. *
  3853. * @since 3.1.0
  3854. *
  3855. * @param array $array The original array.
  3856. * @param array $keys The list of keys.
  3857. * @return array The array slice.
  3858. */
  3859. function wp_array_slice_assoc( $array, $keys ) {
  3860. $slice = array();
  3861. foreach ( $keys as $key ) {
  3862. if ( isset( $array[ $key ] ) ) {
  3863. $slice[ $key ] = $array[ $key ];
  3864. }
  3865. }
  3866. return $slice;
  3867. }
  3868. /**
  3869. * Determines if the variable is a numeric-indexed array.
  3870. *
  3871. * @since 4.4.0
  3872. *
  3873. * @param mixed $data Variable to check.
  3874. * @return bool Whether the variable is a list.
  3875. */
  3876. function wp_is_numeric_array( $data ) {
  3877. if ( ! is_array( $data ) ) {
  3878. return false;
  3879. }
  3880. $keys = array_keys( $data );
  3881. $string_keys = array_filter( $keys, 'is_string' );
  3882. return count( $string_keys ) === 0;
  3883. }
  3884. /**
  3885. * Filters a list of objects, based on a set of key => value arguments.
  3886. *
  3887. * @since 3.0.0
  3888. * @since 4.7.0 Uses `WP_List_Util` class.
  3889. *
  3890. * @param array $list An array of objects to filter
  3891. * @param array $args Optional. An array of key => value arguments to match
  3892. * against each object. Default empty array.
  3893. * @param string $operator Optional. The logical operation to perform. 'or' means
  3894. * only one element from the array needs to match; 'and'
  3895. * means all elements must match; 'not' means no elements may
  3896. * match. Default 'and'.
  3897. * @param bool|string $field A field from the object to place instead of the entire object.
  3898. * Default false.
  3899. * @return array A list of objects or object fields.
  3900. */
  3901. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  3902. if ( ! is_array( $list ) ) {
  3903. return array();
  3904. }
  3905. $util = new WP_List_Util( $list );
  3906. $util->filter( $args, $operator );
  3907. if ( $field ) {
  3908. $util->pluck( $field );
  3909. }
  3910. return $util->get_output();
  3911. }
  3912. /**
  3913. * Filters a list of objects, based on a set of key => value arguments.
  3914. *
  3915. * @since 3.1.0
  3916. * @since 4.7.0 Uses `WP_List_Util` class.
  3917. *
  3918. * @param array $list An array of objects to filter.
  3919. * @param array $args Optional. An array of key => value arguments to match
  3920. * against each object. Default empty array.
  3921. * @param string $operator Optional. The logical operation to perform. 'AND' means
  3922. * all elements from the array must match. 'OR' means only
  3923. * one element needs to match. 'NOT' means no elements may
  3924. * match. Default 'AND'.
  3925. * @return array Array of found values.
  3926. */
  3927. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  3928. if ( ! is_array( $list ) ) {
  3929. return array();
  3930. }
  3931. $util = new WP_List_Util( $list );
  3932. return $util->filter( $args, $operator );
  3933. }
  3934. /**
  3935. * Pluck a certain field out of each object in a list.
  3936. *
  3937. * This has the same functionality and prototype of
  3938. * array_column() (PHP 5.5) but also supports objects.
  3939. *
  3940. * @since 3.1.0
  3941. * @since 4.0.0 $index_key parameter added.
  3942. * @since 4.7.0 Uses `WP_List_Util` class.
  3943. *
  3944. * @param array $list List of objects or arrays
  3945. * @param int|string $field Field from the object to place instead of the entire object
  3946. * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  3947. * Default null.
  3948. * @return array Array of found values. If `$index_key` is set, an array of found values with keys
  3949. * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
  3950. * `$list` will be preserved in the results.
  3951. */
  3952. function wp_list_pluck( $list, $field, $index_key = null ) {
  3953. $util = new WP_List_Util( $list );
  3954. return $util->pluck( $field, $index_key );
  3955. }
  3956. /**
  3957. * Sorts a list of objects, based on one or more orderby arguments.
  3958. *
  3959. * @since 4.7.0
  3960. *
  3961. * @param array $list An array of objects to sort.
  3962. * @param string|array $orderby Optional. Either the field name to order by or an array
  3963. * of multiple orderby fields as $orderby => $order.
  3964. * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
  3965. * is a string.
  3966. * @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
  3967. * @return array The sorted array.
  3968. */
  3969. function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
  3970. if ( ! is_array( $list ) ) {
  3971. return array();
  3972. }
  3973. $util = new WP_List_Util( $list );
  3974. return $util->sort( $orderby, $order, $preserve_keys );
  3975. }
  3976. /**
  3977. * Determines if Widgets library should be loaded.
  3978. *
  3979. * Checks to make sure that the widgets library hasn't already been loaded.
  3980. * If it hasn't, then it will load the widgets library and run an action hook.
  3981. *
  3982. * @since 2.2.0
  3983. */
  3984. function wp_maybe_load_widgets() {
  3985. /**
  3986. * Filters whether to load the Widgets library.
  3987. *
  3988. * Passing a falsey value to the filter will effectively short-circuit
  3989. * the Widgets library from loading.
  3990. *
  3991. * @since 2.8.0
  3992. *
  3993. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  3994. * Default true.
  3995. */
  3996. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  3997. return;
  3998. }
  3999. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  4000. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  4001. }
  4002. /**
  4003. * Append the Widgets menu to the themes main menu.
  4004. *
  4005. * @since 2.2.0
  4006. *
  4007. * @global array $submenu
  4008. */
  4009. function wp_widgets_add_menu() {
  4010. global $submenu;
  4011. if ( ! current_theme_supports( 'widgets' ) ) {
  4012. return;
  4013. }
  4014. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  4015. ksort( $submenu['themes.php'], SORT_NUMERIC );
  4016. }
  4017. /**
  4018. * Flush all output buffers for PHP 5.2.
  4019. *
  4020. * Make sure all output buffers are flushed before our singletons are destroyed.
  4021. *
  4022. * @since 2.2.0
  4023. */
  4024. function wp_ob_end_flush_all() {
  4025. $levels = ob_get_level();
  4026. for ( $i = 0; $i < $levels; $i++ ) {
  4027. ob_end_flush();
  4028. }
  4029. }
  4030. /**
  4031. * Load custom DB error or display WordPress DB error.
  4032. *
  4033. * If a file exists in the wp-content directory named db-error.php, then it will
  4034. * be loaded instead of displaying the WordPress DB error. If it is not found,
  4035. * then the WordPress DB error will be displayed instead.
  4036. *
  4037. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  4038. * search engines from caching the message. Custom DB messages should do the
  4039. * same.
  4040. *
  4041. * This function was backported to WordPress 2.3.2, but originally was added
  4042. * in WordPress 2.5.0.
  4043. *
  4044. * @since 2.3.2
  4045. *
  4046. * @global wpdb $wpdb WordPress database abstraction object.
  4047. */
  4048. function dead_db() {
  4049. global $wpdb;
  4050. wp_load_translations_early();
  4051. // Load custom DB error template, if present.
  4052. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  4053. require_once( WP_CONTENT_DIR . '/db-error.php' );
  4054. die();
  4055. }
  4056. // If installing or in the admin, provide the verbose message.
  4057. if ( wp_installing() || defined( 'WP_ADMIN' ) ) {
  4058. wp_die( $wpdb->error );
  4059. }
  4060. // Otherwise, be terse.
  4061. wp_die( '<h1>' . __( 'Error establishing a database connection' ) . '</h1>', __( 'Database Error' ) );
  4062. }
  4063. /**
  4064. * Convert a value to non-negative integer.
  4065. *
  4066. * @since 2.5.0
  4067. *
  4068. * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  4069. * @return int A non-negative integer.
  4070. */
  4071. function absint( $maybeint ) {
  4072. return abs( intval( $maybeint ) );
  4073. }
  4074. /**
  4075. * Mark a function as deprecated and inform when it has been used.
  4076. *
  4077. * There is a {@see 'hook deprecated_function_run'} that will be called that can be used
  4078. * to get the backtrace up to what file and function called the deprecated
  4079. * function.
  4080. *
  4081. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4082. *
  4083. * This function is to be used in every function that is deprecated.
  4084. *
  4085. * @since 2.5.0
  4086. * @access private
  4087. *
  4088. * @param string $function The function that was called.
  4089. * @param string $version The version of WordPress that deprecated the function.
  4090. * @param string $replacement Optional. The function that should have been called. Default null.
  4091. */
  4092. function _deprecated_function( $function, $version, $replacement = null ) {
  4093. /**
  4094. * Fires when a deprecated function is called.
  4095. *
  4096. * @since 2.5.0
  4097. *
  4098. * @param string $function The function that was called.
  4099. * @param string $replacement The function that should have been called.
  4100. * @param string $version The version of WordPress that deprecated the function.
  4101. */
  4102. do_action( 'deprecated_function_run', $function, $replacement, $version );
  4103. /**
  4104. * Filters whether to trigger an error for deprecated functions.
  4105. *
  4106. * @since 2.5.0
  4107. *
  4108. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4109. */
  4110. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  4111. if ( function_exists( '__' ) ) {
  4112. if ( ! is_null( $replacement ) ) {
  4113. /* translators: 1: PHP function name, 2: Version number, 3: Alternative function name. */
  4114. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), $function, $version, $replacement ) );
  4115. } else {
  4116. /* translators: 1: PHP function name, 2: Version number. */
  4117. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), $function, $version ) );
  4118. }
  4119. } else {
  4120. if ( ! is_null( $replacement ) ) {
  4121. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
  4122. } else {
  4123. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  4124. }
  4125. }
  4126. }
  4127. }
  4128. /**
  4129. * Marks a constructor as deprecated and informs when it has been used.
  4130. *
  4131. * Similar to _deprecated_function(), but with different strings. Used to
  4132. * remove PHP4 style constructors.
  4133. *
  4134. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4135. *
  4136. * This function is to be used in every PHP4 style constructor method that is deprecated.
  4137. *
  4138. * @since 4.3.0
  4139. * @since 4.5.0 Added the `$parent_class` parameter.
  4140. *
  4141. * @access private
  4142. *
  4143. * @param string $class The class containing the deprecated constructor.
  4144. * @param string $version The version of WordPress that deprecated the function.
  4145. * @param string $parent_class Optional. The parent class calling the deprecated constructor.
  4146. * Default empty string.
  4147. */
  4148. function _deprecated_constructor( $class, $version, $parent_class = '' ) {
  4149. /**
  4150. * Fires when a deprecated constructor is called.
  4151. *
  4152. * @since 4.3.0
  4153. * @since 4.5.0 Added the `$parent_class` parameter.
  4154. *
  4155. * @param string $class The class containing the deprecated constructor.
  4156. * @param string $version The version of WordPress that deprecated the function.
  4157. * @param string $parent_class The parent class calling the deprecated constructor.
  4158. */
  4159. do_action( 'deprecated_constructor_run', $class, $version, $parent_class );
  4160. /**
  4161. * Filters whether to trigger an error for deprecated functions.
  4162. *
  4163. * `WP_DEBUG` must be true in addition to the filter evaluating to true.
  4164. *
  4165. * @since 4.3.0
  4166. *
  4167. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  4168. */
  4169. if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
  4170. if ( function_exists( '__' ) ) {
  4171. if ( ! empty( $parent_class ) ) {
  4172. trigger_error(
  4173. sprintf(
  4174. /* translators: 1: PHP class name, 2: PHP parent class name, 3: Version number, 4: __construct() method. */
  4175. __( 'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.' ),
  4176. $class,
  4177. $parent_class,
  4178. $version,
  4179. '<pre>__construct()</pre>'
  4180. )
  4181. );
  4182. } else {
  4183. trigger_error(
  4184. sprintf(
  4185. /* translators: 1: PHP class name, 2: Version number, 3: __construct() method. */
  4186. __( 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  4187. $class,
  4188. $version,
  4189. '<pre>__construct()</pre>'
  4190. )
  4191. );
  4192. }
  4193. } else {
  4194. if ( ! empty( $parent_class ) ) {
  4195. trigger_error(
  4196. sprintf(
  4197. 'The called constructor method for %1$s in %2$s is <strong>deprecated</strong> since version %3$s! Use %4$s instead.',
  4198. $class,
  4199. $parent_class,
  4200. $version,
  4201. '<pre>__construct()</pre>'
  4202. )
  4203. );
  4204. } else {
  4205. trigger_error(
  4206. sprintf(
  4207. 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  4208. $class,
  4209. $version,
  4210. '<pre>__construct()</pre>'
  4211. )
  4212. );
  4213. }
  4214. }
  4215. }
  4216. }
  4217. /**
  4218. * Mark a file as deprecated and inform when it has been used.
  4219. *
  4220. * There is a hook {@see 'deprecated_file_included'} that will be called that can be used
  4221. * to get the backtrace up to what file and function included the deprecated
  4222. * file.
  4223. *
  4224. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4225. *
  4226. * This function is to be used in every file that is deprecated.
  4227. *
  4228. * @since 2.5.0
  4229. * @access private
  4230. *
  4231. * @param string $file The file that was included.
  4232. * @param string $version The version of WordPress that deprecated the file.
  4233. * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  4234. * Default null.
  4235. * @param string $message Optional. A message regarding the change. Default empty.
  4236. */
  4237. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  4238. /**
  4239. * Fires when a deprecated file is called.
  4240. *
  4241. * @since 2.5.0
  4242. *
  4243. * @param string $file The file that was called.
  4244. * @param string $replacement The file that should have been included based on ABSPATH.
  4245. * @param string $version The version of WordPress that deprecated the file.
  4246. * @param string $message A message regarding the change.
  4247. */
  4248. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  4249. /**
  4250. * Filters whether to trigger an error for deprecated files.
  4251. *
  4252. * @since 2.5.0
  4253. *
  4254. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  4255. */
  4256. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  4257. $message = empty( $message ) ? '' : ' ' . $message;
  4258. if ( function_exists( '__' ) ) {
  4259. if ( ! is_null( $replacement ) ) {
  4260. /* translators: 1: PHP file name, 2: Version number, 3: Alternative file name. */
  4261. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), $file, $version, $replacement ) . $message );
  4262. } else {
  4263. /* translators: 1: PHP file name, 2: Version number. */
  4264. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), $file, $version ) . $message );
  4265. }
  4266. } else {
  4267. if ( ! is_null( $replacement ) ) {
  4268. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
  4269. } else {
  4270. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $file, $version ) . $message );
  4271. }
  4272. }
  4273. }
  4274. }
  4275. /**
  4276. * Mark a function argument as deprecated and inform when it has been used.
  4277. *
  4278. * This function is to be used whenever a deprecated function argument is used.
  4279. * Before this function is called, the argument must be checked for whether it was
  4280. * used by comparing it to its default value or evaluating whether it is empty.
  4281. * For example:
  4282. *
  4283. * if ( ! empty( $deprecated ) ) {
  4284. * _deprecated_argument( __FUNCTION__, '3.0.0' );
  4285. * }
  4286. *
  4287. * There is a hook deprecated_argument_run that will be called that can be used
  4288. * to get the backtrace up to what file and function used the deprecated
  4289. * argument.
  4290. *
  4291. * The current behavior is to trigger a user error if WP_DEBUG is true.
  4292. *
  4293. * @since 3.0.0
  4294. * @access private
  4295. *
  4296. * @param string $function The function that was called.
  4297. * @param string $version The version of WordPress that deprecated the argument used.
  4298. * @param string $message Optional. A message regarding the change. Default null.
  4299. */
  4300. function _deprecated_argument( $function, $version, $message = null ) {
  4301. /**
  4302. * Fires when a deprecated argument is called.
  4303. *
  4304. * @since 3.0.0
  4305. *
  4306. * @param string $function The function that was called.
  4307. * @param string $message A message regarding the change.
  4308. * @param string $version The version of WordPress that deprecated the argument used.
  4309. */
  4310. do_action( 'deprecated_argument_run', $function, $message, $version );
  4311. /**
  4312. * Filters whether to trigger an error for deprecated arguments.
  4313. *
  4314. * @since 3.0.0
  4315. *
  4316. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  4317. */
  4318. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  4319. if ( function_exists( '__' ) ) {
  4320. if ( ! is_null( $message ) ) {
  4321. /* translators: 1: PHP function name, 2: Version number, 3: Optional message regarding the change. */
  4322. trigger_error( sprintf( __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s' ), $function, $version, $message ) );
  4323. } else {
  4324. /* translators: 1: PHP function name, 2: Version number. */
  4325. trigger_error( sprintf( __( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.' ), $function, $version ) );
  4326. }
  4327. } else {
  4328. if ( ! is_null( $message ) ) {
  4329. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) );
  4330. } else {
  4331. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  4332. }
  4333. }
  4334. }
  4335. }
  4336. /**
  4337. * Marks a deprecated action or filter hook as deprecated and throws a notice.
  4338. *
  4339. * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where
  4340. * the deprecated hook was called.
  4341. *
  4342. * Default behavior is to trigger a user error if `WP_DEBUG` is true.
  4343. *
  4344. * This function is called by the do_action_deprecated() and apply_filters_deprecated()
  4345. * functions, and so generally does not need to be called directly.
  4346. *
  4347. * @since 4.6.0
  4348. * @access private
  4349. *
  4350. * @param string $hook The hook that was used.
  4351. * @param string $version The version of WordPress that deprecated the hook.
  4352. * @param string $replacement Optional. The hook that should have been used.
  4353. * @param string $message Optional. A message regarding the change.
  4354. */
  4355. function _deprecated_hook( $hook, $version, $replacement = null, $message = null ) {
  4356. /**
  4357. * Fires when a deprecated hook is called.
  4358. *
  4359. * @since 4.6.0
  4360. *
  4361. * @param string $hook The hook that was called.
  4362. * @param string $replacement The hook that should be used as a replacement.
  4363. * @param string $version The version of WordPress that deprecated the argument used.
  4364. * @param string $message A message regarding the change.
  4365. */
  4366. do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
  4367. /**
  4368. * Filters whether to trigger deprecated hook errors.
  4369. *
  4370. * @since 4.6.0
  4371. *
  4372. * @param bool $trigger Whether to trigger deprecated hook errors. Requires
  4373. * `WP_DEBUG` to be defined true.
  4374. */
  4375. if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
  4376. $message = empty( $message ) ? '' : ' ' . $message;
  4377. if ( ! is_null( $replacement ) ) {
  4378. /* translators: 1: WordPress hook name, 2: Version number, 3: Alternative hook name. */
  4379. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), $hook, $version, $replacement ) . $message );
  4380. } else {
  4381. /* translators: 1: WordPress hook name, 2: Version number. */
  4382. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), $hook, $version ) . $message );
  4383. }
  4384. }
  4385. }
  4386. /**
  4387. * Mark something as being incorrectly called.
  4388. *
  4389. * There is a hook {@see 'doing_it_wrong_run'} that will be called that can be used
  4390. * to get the backtrace up to what file and function called the deprecated
  4391. * function.
  4392. *
  4393. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  4394. *
  4395. * @since 3.1.0
  4396. * @access private
  4397. *
  4398. * @param string $function The function that was called.
  4399. * @param string $message A message explaining what has been done incorrectly.
  4400. * @param string $version The version of WordPress where the message was added.
  4401. */
  4402. function _doing_it_wrong( $function, $message, $version ) {
  4403. /**
  4404. * Fires when the given function is being used incorrectly.
  4405. *
  4406. * @since 3.1.0
  4407. *
  4408. * @param string $function The function that was called.
  4409. * @param string $message A message explaining what has been done incorrectly.
  4410. * @param string $version The version of WordPress where the message was added.
  4411. */
  4412. do_action( 'doing_it_wrong_run', $function, $message, $version );
  4413. /**
  4414. * Filters whether to trigger an error for _doing_it_wrong() calls.
  4415. *
  4416. * @since 3.1.0
  4417. * @since 5.1.0 Added the $function, $message and $version parameters.
  4418. *
  4419. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  4420. * @param string $function The function that was called.
  4421. * @param string $message A message explaining what has been done incorrectly.
  4422. * @param string $version The version of WordPress where the message was added.
  4423. */
  4424. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true, $function, $message, $version ) ) {
  4425. if ( function_exists( '__' ) ) {
  4426. if ( is_null( $version ) ) {
  4427. $version = '';
  4428. } else {
  4429. /* translators: %s: Version number. */
  4430. $version = sprintf( __( '(This message was added in version %s.)' ), $version );
  4431. }
  4432. $message .= ' ' . sprintf(
  4433. /* translators: %s: Documentation URL. */
  4434. __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ),
  4435. __( 'https://wordpress.org/support/article/debugging-in-wordpress/' )
  4436. );
  4437. /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: Version information message. */
  4438. trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
  4439. } else {
  4440. if ( is_null( $version ) ) {
  4441. $version = '';
  4442. } else {
  4443. $version = sprintf( '(This message was added in version %s.)', $version );
  4444. }
  4445. $message .= sprintf(
  4446. ' Please see <a href="%s">Debugging in WordPress</a> for more information.',
  4447. 'https://wordpress.org/support/article/debugging-in-wordpress/'
  4448. );
  4449. trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
  4450. }
  4451. }
  4452. }
  4453. /**
  4454. * Is the server running earlier than 1.5.0 version of lighttpd?
  4455. *
  4456. * @since 2.5.0
  4457. *
  4458. * @return bool Whether the server is running lighttpd < 1.5.0.
  4459. */
  4460. function is_lighttpd_before_150() {
  4461. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] ) ? $_SERVER['SERVER_SOFTWARE'] : '' );
  4462. $server_parts[1] = isset( $server_parts[1] ) ? $server_parts[1] : '';
  4463. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  4464. }
  4465. /**
  4466. * Does the specified module exist in the Apache config?
  4467. *
  4468. * @since 2.5.0
  4469. *
  4470. * @global bool $is_apache
  4471. *
  4472. * @param string $mod The module, e.g. mod_rewrite.
  4473. * @param bool $default Optional. The default return value if the module is not found. Default false.
  4474. * @return bool Whether the specified module is loaded.
  4475. */
  4476. function apache_mod_loaded( $mod, $default = false ) {
  4477. global $is_apache;
  4478. if ( ! $is_apache ) {
  4479. return false;
  4480. }
  4481. if ( function_exists( 'apache_get_modules' ) ) {
  4482. $mods = apache_get_modules();
  4483. if ( in_array( $mod, $mods ) ) {
  4484. return true;
  4485. }
  4486. } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  4487. ob_start();
  4488. phpinfo( 8 );
  4489. $phpinfo = ob_get_clean();
  4490. if ( false !== strpos( $phpinfo, $mod ) ) {
  4491. return true;
  4492. }
  4493. }
  4494. return $default;
  4495. }
  4496. /**
  4497. * Check if IIS 7+ supports pretty permalinks.
  4498. *
  4499. * @since 2.8.0
  4500. *
  4501. * @global bool $is_iis7
  4502. *
  4503. * @return bool Whether IIS7 supports permalinks.
  4504. */
  4505. function iis7_supports_permalinks() {
  4506. global $is_iis7;
  4507. $supports_permalinks = false;
  4508. if ( $is_iis7 ) {
  4509. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  4510. * easily update the xml configuration file, hence we just bail out and tell user that
  4511. * pretty permalinks cannot be used.
  4512. *
  4513. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  4514. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  4515. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  4516. * via ISAPI then pretty permalinks will not work.
  4517. */
  4518. $supports_permalinks = class_exists( 'DOMDocument', false ) && isset( $_SERVER['IIS_UrlRewriteModule'] ) && ( PHP_SAPI == 'cgi-fcgi' );
  4519. }
  4520. /**
  4521. * Filters whether IIS 7+ supports pretty permalinks.
  4522. *
  4523. * @since 2.8.0
  4524. *
  4525. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  4526. */
  4527. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  4528. }
  4529. /**
  4530. * Validates a file name and path against an allowed set of rules.
  4531. *
  4532. * A return value of `1` means the file path contains directory traversal.
  4533. *
  4534. * A return value of `2` means the file path contains a Windows drive path.
  4535. *
  4536. * A return value of `3` means the file is not in the allowed files list.
  4537. *
  4538. * @since 1.2.0
  4539. *
  4540. * @param string $file File path.
  4541. * @param array $allowed_files Optional. List of allowed files.
  4542. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  4543. */
  4544. function validate_file( $file, $allowed_files = array() ) {
  4545. // `../` on its own is not allowed:
  4546. if ( '../' === $file ) {
  4547. return 1;
  4548. }
  4549. // More than one occurence of `../` is not allowed:
  4550. if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
  4551. return 1;
  4552. }
  4553. // `../` which does not occur at the end of the path is not allowed:
  4554. if ( false !== strpos( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
  4555. return 1;
  4556. }
  4557. // Files not in the allowed file list are not allowed:
  4558. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) ) {
  4559. return 3;
  4560. }
  4561. // Absolute Windows drive paths are not allowed:
  4562. if ( ':' == substr( $file, 1, 1 ) ) {
  4563. return 2;
  4564. }
  4565. return 0;
  4566. }
  4567. /**
  4568. * Whether to force SSL used for the Administration Screens.
  4569. *
  4570. * @since 2.6.0
  4571. *
  4572. * @staticvar bool $forced
  4573. *
  4574. * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  4575. * @return bool True if forced, false if not forced.
  4576. */
  4577. function force_ssl_admin( $force = null ) {
  4578. static $forced = false;
  4579. if ( ! is_null( $force ) ) {
  4580. $old_forced = $forced;
  4581. $forced = $force;
  4582. return $old_forced;
  4583. }
  4584. return $forced;
  4585. }
  4586. /**
  4587. * Guess the URL for the site.
  4588. *
  4589. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  4590. * directory.
  4591. *
  4592. * @since 2.6.0
  4593. *
  4594. * @return string The guessed URL.
  4595. */
  4596. function wp_guess_url() {
  4597. if ( defined( 'WP_SITEURL' ) && '' != WP_SITEURL ) {
  4598. $url = WP_SITEURL;
  4599. } else {
  4600. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  4601. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  4602. // The request is for the admin
  4603. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  4604. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  4605. // The request is for a file in ABSPATH
  4606. } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  4607. // Strip off any file/query params in the path
  4608. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  4609. } else {
  4610. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  4611. // Request is hitting a file inside ABSPATH
  4612. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  4613. // Strip off the sub directory, and any file/query params
  4614. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '', $_SERVER['REQUEST_URI'] );
  4615. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  4616. // Request is hitting a file above ABSPATH
  4617. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  4618. // Strip off any file/query params from the path, appending the sub directory to the installation
  4619. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['REQUEST_URI'] ) . $subdirectory;
  4620. } else {
  4621. $path = $_SERVER['REQUEST_URI'];
  4622. }
  4623. }
  4624. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
  4625. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  4626. }
  4627. return rtrim( $url, '/' );
  4628. }
  4629. /**
  4630. * Temporarily suspend cache additions.
  4631. *
  4632. * Stops more data being added to the cache, but still allows cache retrieval.
  4633. * This is useful for actions, such as imports, when a lot of data would otherwise
  4634. * be almost uselessly added to the cache.
  4635. *
  4636. * Suspension lasts for a single page load at most. Remember to call this
  4637. * function again if you wish to re-enable cache adds earlier.
  4638. *
  4639. * @since 3.3.0
  4640. *
  4641. * @staticvar bool $_suspend
  4642. *
  4643. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  4644. * @return bool The current suspend setting
  4645. */
  4646. function wp_suspend_cache_addition( $suspend = null ) {
  4647. static $_suspend = false;
  4648. if ( is_bool( $suspend ) ) {
  4649. $_suspend = $suspend;
  4650. }
  4651. return $_suspend;
  4652. }
  4653. /**
  4654. * Suspend cache invalidation.
  4655. *
  4656. * Turns cache invalidation on and off. Useful during imports where you don't want to do
  4657. * invalidations every time a post is inserted. Callers must be sure that what they are
  4658. * doing won't lead to an inconsistent cache when invalidation is suspended.
  4659. *
  4660. * @since 2.7.0
  4661. *
  4662. * @global bool $_wp_suspend_cache_invalidation
  4663. *
  4664. * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  4665. * @return bool The current suspend setting.
  4666. */
  4667. function wp_suspend_cache_invalidation( $suspend = true ) {
  4668. global $_wp_suspend_cache_invalidation;
  4669. $current_suspend = $_wp_suspend_cache_invalidation;
  4670. $_wp_suspend_cache_invalidation = $suspend;
  4671. return $current_suspend;
  4672. }
  4673. /**
  4674. * Determine whether a site is the main site of the current network.
  4675. *
  4676. * @since 3.0.0
  4677. * @since 4.9.0 The `$network_id` parameter was added.
  4678. *
  4679. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  4680. * @param int $network_id Optional. Network ID of the network to check for.
  4681. * Defaults to current network.
  4682. * @return bool True if $site_id is the main site of the network, or if not
  4683. * running Multisite.
  4684. */
  4685. function is_main_site( $site_id = null, $network_id = null ) {
  4686. if ( ! is_multisite() ) {
  4687. return true;
  4688. }
  4689. if ( ! $site_id ) {
  4690. $site_id = get_current_blog_id();
  4691. }
  4692. $site_id = (int) $site_id;
  4693. return $site_id === get_main_site_id( $network_id );
  4694. }
  4695. /**
  4696. * Gets the main site ID.
  4697. *
  4698. * @since 4.9.0
  4699. *
  4700. * @param int $network_id Optional. The ID of the network for which to get the main site.
  4701. * Defaults to the current network.
  4702. * @return int The ID of the main site.
  4703. */
  4704. function get_main_site_id( $network_id = null ) {
  4705. if ( ! is_multisite() ) {
  4706. return get_current_blog_id();
  4707. }
  4708. $network = get_network( $network_id );
  4709. if ( ! $network ) {
  4710. return 0;
  4711. }
  4712. return $network->site_id;
  4713. }
  4714. /**
  4715. * Determine whether a network is the main network of the Multisite installation.
  4716. *
  4717. * @since 3.7.0
  4718. *
  4719. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  4720. * @return bool True if $network_id is the main network, or if not running Multisite.
  4721. */
  4722. function is_main_network( $network_id = null ) {
  4723. if ( ! is_multisite() ) {
  4724. return true;
  4725. }
  4726. if ( null === $network_id ) {
  4727. $network_id = get_current_network_id();
  4728. }
  4729. $network_id = (int) $network_id;
  4730. return ( $network_id === get_main_network_id() );
  4731. }
  4732. /**
  4733. * Get the main network ID.
  4734. *
  4735. * @since 4.3.0
  4736. *
  4737. * @return int The ID of the main network.
  4738. */
  4739. function get_main_network_id() {
  4740. if ( ! is_multisite() ) {
  4741. return 1;
  4742. }
  4743. $current_network = get_network();
  4744. if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
  4745. $main_network_id = PRIMARY_NETWORK_ID;
  4746. } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
  4747. // If the current network has an ID of 1, assume it is the main network.
  4748. $main_network_id = 1;
  4749. } else {
  4750. $_networks = get_networks(
  4751. array(
  4752. 'fields' => 'ids',
  4753. 'number' => 1,
  4754. )
  4755. );
  4756. $main_network_id = array_shift( $_networks );
  4757. }
  4758. /**
  4759. * Filters the main network ID.
  4760. *
  4761. * @since 4.3.0
  4762. *
  4763. * @param int $main_network_id The ID of the main network.
  4764. */
  4765. return (int) apply_filters( 'get_main_network_id', $main_network_id );
  4766. }
  4767. /**
  4768. * Determine whether global terms are enabled.
  4769. *
  4770. * @since 3.0.0
  4771. *
  4772. * @staticvar bool $global_terms
  4773. *
  4774. * @return bool True if multisite and global terms enabled.
  4775. */
  4776. function global_terms_enabled() {
  4777. if ( ! is_multisite() ) {
  4778. return false;
  4779. }
  4780. static $global_terms = null;
  4781. if ( is_null( $global_terms ) ) {
  4782. /**
  4783. * Filters whether global terms are enabled.
  4784. *
  4785. * Passing a non-null value to the filter will effectively short-circuit the function,
  4786. * returning the value of the 'global_terms_enabled' site option instead.
  4787. *
  4788. * @since 3.0.0
  4789. *
  4790. * @param null $enabled Whether global terms are enabled.
  4791. */
  4792. $filter = apply_filters( 'global_terms_enabled', null );
  4793. if ( ! is_null( $filter ) ) {
  4794. $global_terms = (bool) $filter;
  4795. } else {
  4796. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  4797. }
  4798. }
  4799. return $global_terms;
  4800. }
  4801. /**
  4802. * Determines whether site meta is enabled.
  4803. *
  4804. * This function checks whether the 'blogmeta' database table exists. The result is saved as
  4805. * a setting for the main network, making it essentially a global setting. Subsequent requests
  4806. * will refer to this setting instead of running the query.
  4807. *
  4808. * @since 5.1.0
  4809. *
  4810. * @global wpdb $wpdb WordPress database abstraction object.
  4811. *
  4812. * @return bool True if site meta is supported, false otherwise.
  4813. */
  4814. function is_site_meta_supported() {
  4815. global $wpdb;
  4816. if ( ! is_multisite() ) {
  4817. return false;
  4818. }
  4819. $network_id = get_main_network_id();
  4820. $supported = get_network_option( $network_id, 'site_meta_supported', false );
  4821. if ( false === $supported ) {
  4822. $supported = $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->blogmeta}'" ) ? 1 : 0;
  4823. update_network_option( $network_id, 'site_meta_supported', $supported );
  4824. }
  4825. return (bool) $supported;
  4826. }
  4827. /**
  4828. * gmt_offset modification for smart timezone handling.
  4829. *
  4830. * Overrides the gmt_offset option if we have a timezone_string available.
  4831. *
  4832. * @since 2.8.0
  4833. *
  4834. * @return float|false Timezone GMT offset, false otherwise.
  4835. */
  4836. function wp_timezone_override_offset() {
  4837. $timezone_string = get_option( 'timezone_string' );
  4838. if ( ! $timezone_string ) {
  4839. return false;
  4840. }
  4841. $timezone_object = timezone_open( $timezone_string );
  4842. $datetime_object = date_create();
  4843. if ( false === $timezone_object || false === $datetime_object ) {
  4844. return false;
  4845. }
  4846. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  4847. }
  4848. /**
  4849. * Sort-helper for timezones.
  4850. *
  4851. * @since 2.9.0
  4852. * @access private
  4853. *
  4854. * @param array $a
  4855. * @param array $b
  4856. * @return int
  4857. */
  4858. function _wp_timezone_choice_usort_callback( $a, $b ) {
  4859. // Don't use translated versions of Etc
  4860. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  4861. // Make the order of these more like the old dropdown
  4862. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  4863. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  4864. }
  4865. if ( 'UTC' === $a['city'] ) {
  4866. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  4867. return 1;
  4868. }
  4869. return -1;
  4870. }
  4871. if ( 'UTC' === $b['city'] ) {
  4872. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  4873. return -1;
  4874. }
  4875. return 1;
  4876. }
  4877. return strnatcasecmp( $a['city'], $b['city'] );
  4878. }
  4879. if ( $a['t_continent'] == $b['t_continent'] ) {
  4880. if ( $a['t_city'] == $b['t_city'] ) {
  4881. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  4882. }
  4883. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  4884. } else {
  4885. // Force Etc to the bottom of the list
  4886. if ( 'Etc' === $a['continent'] ) {
  4887. return 1;
  4888. }
  4889. if ( 'Etc' === $b['continent'] ) {
  4890. return -1;
  4891. }
  4892. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  4893. }
  4894. }
  4895. /**
  4896. * Gives a nicely-formatted list of timezone strings.
  4897. *
  4898. * @since 2.9.0
  4899. * @since 4.7.0 Added the `$locale` parameter.
  4900. *
  4901. * @staticvar bool $mo_loaded
  4902. * @staticvar string $locale_loaded
  4903. *
  4904. * @param string $selected_zone Selected timezone.
  4905. * @param string $locale Optional. Locale to load the timezones in. Default current site locale.
  4906. * @return string
  4907. */
  4908. function wp_timezone_choice( $selected_zone, $locale = null ) {
  4909. static $mo_loaded = false, $locale_loaded = null;
  4910. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific' );
  4911. // Load translations for continents and cities.
  4912. if ( ! $mo_loaded || $locale !== $locale_loaded ) {
  4913. $locale_loaded = $locale ? $locale : get_locale();
  4914. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
  4915. unload_textdomain( 'continents-cities' );
  4916. load_textdomain( 'continents-cities', $mofile );
  4917. $mo_loaded = true;
  4918. }
  4919. $zonen = array();
  4920. foreach ( timezone_identifiers_list() as $zone ) {
  4921. $zone = explode( '/', $zone );
  4922. if ( ! in_array( $zone[0], $continents ) ) {
  4923. continue;
  4924. }
  4925. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  4926. $exists = array(
  4927. 0 => ( isset( $zone[0] ) && $zone[0] ),
  4928. 1 => ( isset( $zone[1] ) && $zone[1] ),
  4929. 2 => ( isset( $zone[2] ) && $zone[2] ),
  4930. );
  4931. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  4932. $exists[4] = ( $exists[1] && $exists[3] );
  4933. $exists[5] = ( $exists[2] && $exists[3] );
  4934. // phpcs:disable WordPress.WP.I18n.LowLevelTranslationFunction,WordPress.WP.I18n.NonSingularStringLiteralText
  4935. $zonen[] = array(
  4936. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  4937. 'city' => ( $exists[1] ? $zone[1] : '' ),
  4938. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  4939. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  4940. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  4941. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' ),
  4942. );
  4943. // phpcs:enable
  4944. }
  4945. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  4946. $structure = array();
  4947. if ( empty( $selected_zone ) ) {
  4948. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  4949. }
  4950. foreach ( $zonen as $key => $zone ) {
  4951. // Build value in an array to join later
  4952. $value = array( $zone['continent'] );
  4953. if ( empty( $zone['city'] ) ) {
  4954. // It's at the continent level (generally won't happen)
  4955. $display = $zone['t_continent'];
  4956. } else {
  4957. // It's inside a continent group
  4958. // Continent optgroup
  4959. if ( ! isset( $zonen[ $key - 1 ] ) || $zonen[ $key - 1 ]['continent'] !== $zone['continent'] ) {
  4960. $label = $zone['t_continent'];
  4961. $structure[] = '<optgroup label="' . esc_attr( $label ) . '">';
  4962. }
  4963. // Add the city to the value
  4964. $value[] = $zone['city'];
  4965. $display = $zone['t_city'];
  4966. if ( ! empty( $zone['subcity'] ) ) {
  4967. // Add the subcity to the value
  4968. $value[] = $zone['subcity'];
  4969. $display .= ' - ' . $zone['t_subcity'];
  4970. }
  4971. }
  4972. // Build the value
  4973. $value = join( '/', $value );
  4974. $selected = '';
  4975. if ( $value === $selected_zone ) {
  4976. $selected = 'selected="selected" ';
  4977. }
  4978. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . '</option>';
  4979. // Close continent optgroup
  4980. if ( ! empty( $zone['city'] ) && ( ! isset( $zonen[ $key + 1 ] ) || ( isset( $zonen[ $key + 1 ] ) && $zonen[ $key + 1 ]['continent'] !== $zone['continent'] ) ) ) {
  4981. $structure[] = '</optgroup>';
  4982. }
  4983. }
  4984. // Do UTC
  4985. $structure[] = '<optgroup label="' . esc_attr__( 'UTC' ) . '">';
  4986. $selected = '';
  4987. if ( 'UTC' === $selected_zone ) {
  4988. $selected = 'selected="selected" ';
  4989. }
  4990. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __( 'UTC' ) . '</option>';
  4991. $structure[] = '</optgroup>';
  4992. // Do manual UTC offsets
  4993. $structure[] = '<optgroup label="' . esc_attr__( 'Manual Offsets' ) . '">';
  4994. $offset_range = array(
  4995. -12,
  4996. -11.5,
  4997. -11,
  4998. -10.5,
  4999. -10,
  5000. -9.5,
  5001. -9,
  5002. -8.5,
  5003. -8,
  5004. -7.5,
  5005. -7,
  5006. -6.5,
  5007. -6,
  5008. -5.5,
  5009. -5,
  5010. -4.5,
  5011. -4,
  5012. -3.5,
  5013. -3,
  5014. -2.5,
  5015. -2,
  5016. -1.5,
  5017. -1,
  5018. -0.5,
  5019. 0,
  5020. 0.5,
  5021. 1,
  5022. 1.5,
  5023. 2,
  5024. 2.5,
  5025. 3,
  5026. 3.5,
  5027. 4,
  5028. 4.5,
  5029. 5,
  5030. 5.5,
  5031. 5.75,
  5032. 6,
  5033. 6.5,
  5034. 7,
  5035. 7.5,
  5036. 8,
  5037. 8.5,
  5038. 8.75,
  5039. 9,
  5040. 9.5,
  5041. 10,
  5042. 10.5,
  5043. 11,
  5044. 11.5,
  5045. 12,
  5046. 12.75,
  5047. 13,
  5048. 13.75,
  5049. 14,
  5050. );
  5051. foreach ( $offset_range as $offset ) {
  5052. if ( 0 <= $offset ) {
  5053. $offset_name = '+' . $offset;
  5054. } else {
  5055. $offset_name = (string) $offset;
  5056. }
  5057. $offset_value = $offset_name;
  5058. $offset_name = str_replace( array( '.25', '.5', '.75' ), array( ':15', ':30', ':45' ), $offset_name );
  5059. $offset_name = 'UTC' . $offset_name;
  5060. $offset_value = 'UTC' . $offset_value;
  5061. $selected = '';
  5062. if ( $offset_value === $selected_zone ) {
  5063. $selected = 'selected="selected" ';
  5064. }
  5065. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . '</option>';
  5066. }
  5067. $structure[] = '</optgroup>';
  5068. return join( "\n", $structure );
  5069. }
  5070. /**
  5071. * Strip close comment and close php tags from file headers used by WP.
  5072. *
  5073. * @since 2.8.0
  5074. * @access private
  5075. *
  5076. * @see https://core.trac.wordpress.org/ticket/8497
  5077. *
  5078. * @param string $str Header comment to clean up.
  5079. * @return string
  5080. */
  5081. function _cleanup_header_comment( $str ) {
  5082. return trim( preg_replace( '/\s*(?:\*\/|\?>).*/', '', $str ) );
  5083. }
  5084. /**
  5085. * Permanently delete comments or posts of any type that have held a status
  5086. * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS.
  5087. *
  5088. * The default value of `EMPTY_TRASH_DAYS` is 30 (days).
  5089. *
  5090. * @since 2.9.0
  5091. *
  5092. * @global wpdb $wpdb WordPress database abstraction object.
  5093. */
  5094. function wp_scheduled_delete() {
  5095. global $wpdb;
  5096. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  5097. $posts_to_delete = $wpdb->get_results( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < %d", $delete_timestamp ), ARRAY_A );
  5098. foreach ( (array) $posts_to_delete as $post ) {
  5099. $post_id = (int) $post['post_id'];
  5100. if ( ! $post_id ) {
  5101. continue;
  5102. }
  5103. $del_post = get_post( $post_id );
  5104. if ( ! $del_post || 'trash' != $del_post->post_status ) {
  5105. delete_post_meta( $post_id, '_wp_trash_meta_status' );
  5106. delete_post_meta( $post_id, '_wp_trash_meta_time' );
  5107. } else {
  5108. wp_delete_post( $post_id );
  5109. }
  5110. }
  5111. $comments_to_delete = $wpdb->get_results( $wpdb->prepare( "SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < %d", $delete_timestamp ), ARRAY_A );
  5112. foreach ( (array) $comments_to_delete as $comment ) {
  5113. $comment_id = (int) $comment['comment_id'];
  5114. if ( ! $comment_id ) {
  5115. continue;
  5116. }
  5117. $del_comment = get_comment( $comment_id );
  5118. if ( ! $del_comment || 'trash' != $del_comment->comment_approved ) {
  5119. delete_comment_meta( $comment_id, '_wp_trash_meta_time' );
  5120. delete_comment_meta( $comment_id, '_wp_trash_meta_status' );
  5121. } else {
  5122. wp_delete_comment( $del_comment );
  5123. }
  5124. }
  5125. }
  5126. /**
  5127. * Retrieve metadata from a file.
  5128. *
  5129. * Searches for metadata in the first 8 KB of a file, such as a plugin or theme.
  5130. * Each piece of metadata must be on its own line. Fields can not span multiple
  5131. * lines, the value will get cut at the end of the first line.
  5132. *
  5133. * If the file data is not within that first 8 KB, then the author should correct
  5134. * their plugin file and move the data headers to the top.
  5135. *
  5136. * @link https://codex.wordpress.org/File_Header
  5137. *
  5138. * @since 2.9.0
  5139. *
  5140. * @param string $file Absolute path to the file.
  5141. * @param array $default_headers List of headers, in the format `array( 'HeaderKey' => 'Header Name' )`.
  5142. * @param string $context Optional. If specified adds filter hook {@see 'extra_$context_headers'}.
  5143. * Default empty.
  5144. * @return array Array of file headers in `HeaderKey => Header Value` format.
  5145. */
  5146. function get_file_data( $file, $default_headers, $context = '' ) {
  5147. // We don't need to write to the file, so just open for reading.
  5148. $fp = fopen( $file, 'r' );
  5149. // Pull only the first 8 KB of the file in.
  5150. $file_data = fread( $fp, 8 * KB_IN_BYTES );
  5151. // PHP will close file handle, but we are good citizens.
  5152. fclose( $fp );
  5153. // Make sure we catch CR-only line endings.
  5154. $file_data = str_replace( "\r", "\n", $file_data );
  5155. /**
  5156. * Filters extra file headers by context.
  5157. *
  5158. * The dynamic portion of the hook name, `$context`, refers to
  5159. * the context where extra headers might be loaded.
  5160. *
  5161. * @since 2.9.0
  5162. *
  5163. * @param array $extra_context_headers Empty array by default.
  5164. */
  5165. $extra_headers = $context ? apply_filters( "extra_{$context}_headers", array() ) : array();
  5166. if ( $extra_headers ) {
  5167. $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
  5168. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  5169. } else {
  5170. $all_headers = $default_headers;
  5171. }
  5172. foreach ( $all_headers as $field => $regex ) {
  5173. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] ) {
  5174. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  5175. } else {
  5176. $all_headers[ $field ] = '';
  5177. }
  5178. }
  5179. return $all_headers;
  5180. }
  5181. /**
  5182. * Returns true.
  5183. *
  5184. * Useful for returning true to filters easily.
  5185. *
  5186. * @since 3.0.0
  5187. *
  5188. * @see __return_false()
  5189. *
  5190. * @return true True.
  5191. */
  5192. function __return_true() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5193. return true;
  5194. }
  5195. /**
  5196. * Returns false.
  5197. *
  5198. * Useful for returning false to filters easily.
  5199. *
  5200. * @since 3.0.0
  5201. *
  5202. * @see __return_true()
  5203. *
  5204. * @return false False.
  5205. */
  5206. function __return_false() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5207. return false;
  5208. }
  5209. /**
  5210. * Returns 0.
  5211. *
  5212. * Useful for returning 0 to filters easily.
  5213. *
  5214. * @since 3.0.0
  5215. *
  5216. * @return int 0.
  5217. */
  5218. function __return_zero() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5219. return 0;
  5220. }
  5221. /**
  5222. * Returns an empty array.
  5223. *
  5224. * Useful for returning an empty array to filters easily.
  5225. *
  5226. * @since 3.0.0
  5227. *
  5228. * @return array Empty array.
  5229. */
  5230. function __return_empty_array() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5231. return array();
  5232. }
  5233. /**
  5234. * Returns null.
  5235. *
  5236. * Useful for returning null to filters easily.
  5237. *
  5238. * @since 3.4.0
  5239. *
  5240. * @return null Null value.
  5241. */
  5242. function __return_null() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5243. return null;
  5244. }
  5245. /**
  5246. * Returns an empty string.
  5247. *
  5248. * Useful for returning an empty string to filters easily.
  5249. *
  5250. * @since 3.7.0
  5251. *
  5252. * @see __return_null()
  5253. *
  5254. * @return string Empty string.
  5255. */
  5256. function __return_empty_string() { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionDoubleUnderscore,PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.FunctionDoubleUnderscore
  5257. return '';
  5258. }
  5259. /**
  5260. * Send a HTTP header to disable content type sniffing in browsers which support it.
  5261. *
  5262. * @since 3.0.0
  5263. *
  5264. * @see https://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  5265. * @see https://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  5266. */
  5267. function send_nosniff_header() {
  5268. header( 'X-Content-Type-Options: nosniff' );
  5269. }
  5270. /**
  5271. * Return a MySQL expression for selecting the week number based on the start_of_week option.
  5272. *
  5273. * @ignore
  5274. * @since 3.0.0
  5275. *
  5276. * @param string $column Database column.
  5277. * @return string SQL clause.
  5278. */
  5279. function _wp_mysql_week( $column ) {
  5280. $start_of_week = (int) get_option( 'start_of_week' );
  5281. switch ( $start_of_week ) {
  5282. case 1:
  5283. return "WEEK( $column, 1 )";
  5284. case 2:
  5285. case 3:
  5286. case 4:
  5287. case 5:
  5288. case 6:
  5289. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  5290. case 0:
  5291. default:
  5292. return "WEEK( $column, 0 )";
  5293. }
  5294. }
  5295. /**
  5296. * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  5297. *
  5298. * @since 3.1.0
  5299. * @access private
  5300. *
  5301. * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  5302. * @param int $start The ID to start the loop check at.
  5303. * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
  5304. * Use null to always use $callback
  5305. * @param array $callback_args Optional. Additional arguments to send to $callback.
  5306. * @return array IDs of all members of loop.
  5307. */
  5308. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  5309. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  5310. $arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args );
  5311. if ( ! $arbitrary_loop_member ) {
  5312. return array();
  5313. }
  5314. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  5315. }
  5316. /**
  5317. * Use the "The Tortoise and the Hare" algorithm to detect loops.
  5318. *
  5319. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  5320. * If the hare ever laps the tortoise, there must be a loop.
  5321. *
  5322. * @since 3.1.0
  5323. * @access private
  5324. *
  5325. * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  5326. * @param int $start The ID to start the loop check at.
  5327. * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  5328. * Default empty array.
  5329. * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  5330. * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
  5331. * to true if you already know the given $start is part of a loop (otherwise
  5332. * the returned array might include branches). Default false.
  5333. * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  5334. * $_return_loop
  5335. */
  5336. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  5337. $tortoise = $start;
  5338. $hare = $start;
  5339. $evanescent_hare = $start;
  5340. $return = array();
  5341. // Set evanescent_hare to one past hare
  5342. // Increment hare two steps
  5343. while (
  5344. $tortoise
  5345. &&
  5346. ( $evanescent_hare = isset( $override[ $hare ] ) ? $override[ $hare ] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  5347. &&
  5348. ( $hare = isset( $override[ $evanescent_hare ] ) ? $override[ $evanescent_hare ] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  5349. ) {
  5350. if ( $_return_loop ) {
  5351. $return[ $tortoise ] = true;
  5352. $return[ $evanescent_hare ] = true;
  5353. $return[ $hare ] = true;
  5354. }
  5355. // tortoise got lapped - must be a loop
  5356. if ( $tortoise == $evanescent_hare || $tortoise == $hare ) {
  5357. return $_return_loop ? $return : $tortoise;
  5358. }
  5359. // Increment tortoise by one step
  5360. $tortoise = isset( $override[ $tortoise ] ) ? $override[ $tortoise ] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  5361. }
  5362. return false;
  5363. }
  5364. /**
  5365. * Send a HTTP header to limit rendering of pages to same origin iframes.
  5366. *
  5367. * @since 3.1.3
  5368. *
  5369. * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  5370. */
  5371. function send_frame_options_header() {
  5372. header( 'X-Frame-Options: SAMEORIGIN' );
  5373. }
  5374. /**
  5375. * Retrieve a list of protocols to allow in HTML attributes.
  5376. *
  5377. * @since 3.3.0
  5378. * @since 4.3.0 Added 'webcal' to the protocols array.
  5379. * @since 4.7.0 Added 'urn' to the protocols array.
  5380. * @since 5.3.0 Added 'sms' to the protocols array.
  5381. *
  5382. * @see wp_kses()
  5383. * @see esc_url()
  5384. *
  5385. * @staticvar array $protocols
  5386. *
  5387. * @return string[] Array of allowed protocols. Defaults to an array containing 'http', 'https',
  5388. * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet',
  5389. * 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
  5390. * This covers all common link protocols, except for 'javascript' which should not
  5391. * be allowed for untrusted users.
  5392. */
  5393. function wp_allowed_protocols() {
  5394. static $protocols = array();
  5395. if ( empty( $protocols ) ) {
  5396. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'sms', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
  5397. }
  5398. if ( ! did_action( 'wp_loaded' ) ) {
  5399. /**
  5400. * Filters the list of protocols allowed in HTML attributes.
  5401. *
  5402. * @since 3.0.0
  5403. *
  5404. * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  5405. */
  5406. $protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
  5407. }
  5408. return $protocols;
  5409. }
  5410. /**
  5411. * Return a comma-separated string of functions that have been called to get
  5412. * to the current point in code.
  5413. *
  5414. * @since 3.4.0
  5415. *
  5416. * @see https://core.trac.wordpress.org/ticket/19589
  5417. *
  5418. * @staticvar array $truncate_paths Array of paths to truncate.
  5419. *
  5420. * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  5421. * when you want to just give info about the callee. Default null.
  5422. * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
  5423. * back to the source of the issue. Default 0.
  5424. * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
  5425. * array returned. Default true.
  5426. * @return string|array Either a string containing a reversed comma separated trace or an array
  5427. * of individual calls.
  5428. */
  5429. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  5430. static $truncate_paths;
  5431. $trace = debug_backtrace( false );
  5432. $caller = array();
  5433. $check_class = ! is_null( $ignore_class );
  5434. $skip_frames++; // skip this function
  5435. if ( ! isset( $truncate_paths ) ) {
  5436. $truncate_paths = array(
  5437. wp_normalize_path( WP_CONTENT_DIR ),
  5438. wp_normalize_path( ABSPATH ),
  5439. );
  5440. }
  5441. foreach ( $trace as $call ) {
  5442. if ( $skip_frames > 0 ) {
  5443. $skip_frames--;
  5444. } elseif ( isset( $call['class'] ) ) {
  5445. if ( $check_class && $ignore_class == $call['class'] ) {
  5446. continue; // Filter out calls
  5447. }
  5448. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  5449. } else {
  5450. if ( in_array( $call['function'], array( 'do_action', 'apply_filters', 'do_action_ref_array', 'apply_filters_ref_array' ) ) ) {
  5451. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  5452. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
  5453. $filename = isset( $call['args'][0] ) ? $call['args'][0] : '';
  5454. $caller[] = $call['function'] . "('" . str_replace( $truncate_paths, '', wp_normalize_path( $filename ) ) . "')";
  5455. } else {
  5456. $caller[] = $call['function'];
  5457. }
  5458. }
  5459. }
  5460. if ( $pretty ) {
  5461. return join( ', ', array_reverse( $caller ) );
  5462. } else {
  5463. return $caller;
  5464. }
  5465. }
  5466. /**
  5467. * Retrieve IDs that are not already present in the cache.
  5468. *
  5469. * @since 3.4.0
  5470. * @access private
  5471. *
  5472. * @param int[] $object_ids Array of IDs.
  5473. * @param string $cache_key The cache bucket to check against.
  5474. * @return int[] Array of IDs not present in the cache.
  5475. */
  5476. function _get_non_cached_ids( $object_ids, $cache_key ) {
  5477. $clean = array();
  5478. foreach ( $object_ids as $id ) {
  5479. $id = (int) $id;
  5480. if ( ! wp_cache_get( $id, $cache_key ) ) {
  5481. $clean[] = $id;
  5482. }
  5483. }
  5484. return $clean;
  5485. }
  5486. /**
  5487. * Test if the current device has the capability to upload files.
  5488. *
  5489. * @since 3.4.0
  5490. * @access private
  5491. *
  5492. * @return bool Whether the device is able to upload files.
  5493. */
  5494. function _device_can_upload() {
  5495. if ( ! wp_is_mobile() ) {
  5496. return true;
  5497. }
  5498. $ua = $_SERVER['HTTP_USER_AGENT'];
  5499. if ( strpos( $ua, 'iPhone' ) !== false
  5500. || strpos( $ua, 'iPad' ) !== false
  5501. || strpos( $ua, 'iPod' ) !== false ) {
  5502. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  5503. }
  5504. return true;
  5505. }
  5506. /**
  5507. * Test if a given path is a stream URL
  5508. *
  5509. * @since 3.5.0
  5510. *
  5511. * @param string $path The resource path or URL.
  5512. * @return bool True if the path is a stream URL.
  5513. */
  5514. function wp_is_stream( $path ) {
  5515. $scheme_separator = strpos( $path, '://' );
  5516. if ( false === $scheme_separator ) {
  5517. // $path isn't a stream
  5518. return false;
  5519. }
  5520. $stream = substr( $path, 0, $scheme_separator );
  5521. return in_array( $stream, stream_get_wrappers(), true );
  5522. }
  5523. /**
  5524. * Test if the supplied date is valid for the Gregorian calendar.
  5525. *
  5526. * @since 3.5.0
  5527. *
  5528. * @link https://secure.php.net/manual/en/function.checkdate.php
  5529. *
  5530. * @param int $month Month number.
  5531. * @param int $day Day number.
  5532. * @param int $year Year number.
  5533. * @param string $source_date The date to filter.
  5534. * @return bool True if valid date, false if not valid date.
  5535. */
  5536. function wp_checkdate( $month, $day, $year, $source_date ) {
  5537. /**
  5538. * Filters whether the given date is valid for the Gregorian calendar.
  5539. *
  5540. * @since 3.5.0
  5541. *
  5542. * @param bool $checkdate Whether the given date is valid.
  5543. * @param string $source_date Date to check.
  5544. */
  5545. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  5546. }
  5547. /**
  5548. * Load the auth check for monitoring whether the user is still logged in.
  5549. *
  5550. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  5551. *
  5552. * This is disabled for certain screens where a login screen could cause an
  5553. * inconvenient interruption. A filter called {@see 'wp_auth_check_load'} can be used
  5554. * for fine-grained control.
  5555. *
  5556. * @since 3.6.0
  5557. */
  5558. function wp_auth_check_load() {
  5559. if ( ! is_admin() && ! is_user_logged_in() ) {
  5560. return;
  5561. }
  5562. if ( defined( 'IFRAME_REQUEST' ) ) {
  5563. return;
  5564. }
  5565. $screen = get_current_screen();
  5566. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  5567. $show = ! in_array( $screen->id, $hidden );
  5568. /**
  5569. * Filters whether to load the authentication check.
  5570. *
  5571. * Passing a falsey value to the filter will effectively short-circuit
  5572. * loading the authentication check.
  5573. *
  5574. * @since 3.6.0
  5575. *
  5576. * @param bool $show Whether to load the authentication check.
  5577. * @param WP_Screen $screen The current screen object.
  5578. */
  5579. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  5580. wp_enqueue_style( 'wp-auth-check' );
  5581. wp_enqueue_script( 'wp-auth-check' );
  5582. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  5583. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  5584. }
  5585. }
  5586. /**
  5587. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  5588. *
  5589. * @since 3.6.0
  5590. */
  5591. function wp_auth_check_html() {
  5592. $login_url = wp_login_url();
  5593. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  5594. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  5595. /**
  5596. * Filters whether the authentication check originated at the same domain.
  5597. *
  5598. * @since 3.6.0
  5599. *
  5600. * @param bool $same_domain Whether the authentication check originated at the same domain.
  5601. */
  5602. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  5603. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  5604. ?>
  5605. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  5606. <div id="wp-auth-check-bg"></div>
  5607. <div id="wp-auth-check">
  5608. <button type="button" class="wp-auth-check-close button-link"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></button>
  5609. <?php
  5610. if ( $same_domain ) {
  5611. $login_src = add_query_arg(
  5612. array(
  5613. 'interim-login' => '1',
  5614. 'wp_lang' => get_user_locale(),
  5615. ),
  5616. $login_url
  5617. );
  5618. ?>
  5619. <div id="wp-auth-check-form" class="loading" data-src="<?php echo esc_url( $login_src ); ?>"></div>
  5620. <?php
  5621. }
  5622. ?>
  5623. <div class="wp-auth-fallback">
  5624. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e( 'Session expired' ); ?></b></p>
  5625. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e( 'Please log in again.' ); ?></a>
  5626. <?php _e( 'The login page will open in a new tab. After logging in you can close it and return to this page.' ); ?></p>
  5627. </div>
  5628. </div>
  5629. </div>
  5630. <?php
  5631. }
  5632. /**
  5633. * Check whether a user is still logged in, for the heartbeat.
  5634. *
  5635. * Send a result that shows a log-in box if the user is no longer logged in,
  5636. * or if their cookie is within the grace period.
  5637. *
  5638. * @since 3.6.0
  5639. *
  5640. * @global int $login_grace_period
  5641. *
  5642. * @param array $response The Heartbeat response.
  5643. * @return array $response The Heartbeat response with 'wp-auth-check' value set.
  5644. */
  5645. function wp_auth_check( $response ) {
  5646. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  5647. return $response;
  5648. }
  5649. /**
  5650. * Return RegEx body to liberally match an opening HTML tag.
  5651. *
  5652. * Matches an opening HTML tag that:
  5653. * 1. Is self-closing or
  5654. * 2. Has no body but has a closing tag of the same name or
  5655. * 3. Contains a body and a closing tag of the same name
  5656. *
  5657. * Note: this RegEx does not balance inner tags and does not attempt
  5658. * to produce valid HTML
  5659. *
  5660. * @since 3.6.0
  5661. *
  5662. * @param string $tag An HTML tag name. Example: 'video'.
  5663. * @return string Tag RegEx.
  5664. */
  5665. function get_tag_regex( $tag ) {
  5666. if ( empty( $tag ) ) {
  5667. return;
  5668. }
  5669. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  5670. }
  5671. /**
  5672. * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  5673. * functions such as htmlspecialchars() and charset html attributes.
  5674. *
  5675. * @since 3.6.0
  5676. * @access private
  5677. *
  5678. * @see https://core.trac.wordpress.org/ticket/23688
  5679. *
  5680. * @param string $charset A charset name.
  5681. * @return string The canonical form of the charset.
  5682. */
  5683. function _canonical_charset( $charset ) {
  5684. if ( 'utf-8' === strtolower( $charset ) || 'utf8' === strtolower( $charset ) ) {
  5685. return 'UTF-8';
  5686. }
  5687. if ( 'iso-8859-1' === strtolower( $charset ) || 'iso8859-1' === strtolower( $charset ) ) {
  5688. return 'ISO-8859-1';
  5689. }
  5690. return $charset;
  5691. }
  5692. /**
  5693. * Set the mbstring internal encoding to a binary safe encoding when func_overload
  5694. * is enabled.
  5695. *
  5696. * When mbstring.func_overload is in use for multi-byte encodings, the results from
  5697. * strlen() and similar functions respect the utf8 characters, causing binary data
  5698. * to return incorrect lengths.
  5699. *
  5700. * This function overrides the mbstring encoding to a binary-safe encoding, and
  5701. * resets it to the users expected encoding afterwards through the
  5702. * `reset_mbstring_encoding` function.
  5703. *
  5704. * It is safe to recursively call this function, however each
  5705. * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  5706. * of `reset_mbstring_encoding()` calls.
  5707. *
  5708. * @since 3.7.0
  5709. *
  5710. * @see reset_mbstring_encoding()
  5711. *
  5712. * @staticvar array $encodings
  5713. * @staticvar bool $overloaded
  5714. *
  5715. * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  5716. * Default false.
  5717. */
  5718. function mbstring_binary_safe_encoding( $reset = false ) {
  5719. static $encodings = array();
  5720. static $overloaded = null;
  5721. if ( is_null( $overloaded ) ) {
  5722. $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  5723. }
  5724. if ( false === $overloaded ) {
  5725. return;
  5726. }
  5727. if ( ! $reset ) {
  5728. $encoding = mb_internal_encoding();
  5729. array_push( $encodings, $encoding );
  5730. mb_internal_encoding( 'ISO-8859-1' );
  5731. }
  5732. if ( $reset && $encodings ) {
  5733. $encoding = array_pop( $encodings );
  5734. mb_internal_encoding( $encoding );
  5735. }
  5736. }
  5737. /**
  5738. * Reset the mbstring internal encoding to a users previously set encoding.
  5739. *
  5740. * @see mbstring_binary_safe_encoding()
  5741. *
  5742. * @since 3.7.0
  5743. */
  5744. function reset_mbstring_encoding() {
  5745. mbstring_binary_safe_encoding( true );
  5746. }
  5747. /**
  5748. * Filter/validate a variable as a boolean.
  5749. *
  5750. * Alternative to `filter_var( $var, FILTER_VALIDATE_BOOLEAN )`.
  5751. *
  5752. * @since 4.0.0
  5753. *
  5754. * @param mixed $var Boolean value to validate.
  5755. * @return bool Whether the value is validated.
  5756. */
  5757. function wp_validate_boolean( $var ) {
  5758. if ( is_bool( $var ) ) {
  5759. return $var;
  5760. }
  5761. if ( is_string( $var ) && 'false' === strtolower( $var ) ) {
  5762. return false;
  5763. }
  5764. return (bool) $var;
  5765. }
  5766. /**
  5767. * Delete a file
  5768. *
  5769. * @since 4.2.0
  5770. *
  5771. * @param string $file The path to the file to delete.
  5772. */
  5773. function wp_delete_file( $file ) {
  5774. /**
  5775. * Filters the path of the file to delete.
  5776. *
  5777. * @since 2.1.0
  5778. *
  5779. * @param string $file Path to the file to delete.
  5780. */
  5781. $delete = apply_filters( 'wp_delete_file', $file );
  5782. if ( ! empty( $delete ) ) {
  5783. @unlink( $delete );
  5784. }
  5785. }
  5786. /**
  5787. * Deletes a file if its path is within the given directory.
  5788. *
  5789. * @since 4.9.7
  5790. *
  5791. * @param string $file Absolute path to the file to delete.
  5792. * @param string $directory Absolute path to a directory.
  5793. * @return bool True on success, false on failure.
  5794. */
  5795. function wp_delete_file_from_directory( $file, $directory ) {
  5796. if ( wp_is_stream( $file ) ) {
  5797. $real_file = $file;
  5798. $real_directory = $directory;
  5799. } else {
  5800. $real_file = realpath( wp_normalize_path( $file ) );
  5801. $real_directory = realpath( wp_normalize_path( $directory ) );
  5802. }
  5803. if ( false !== $real_file ) {
  5804. $real_file = wp_normalize_path( $real_file );
  5805. }
  5806. if ( false !== $real_directory ) {
  5807. $real_directory = wp_normalize_path( $real_directory );
  5808. }
  5809. if ( false === $real_file || false === $real_directory || strpos( $real_file, trailingslashit( $real_directory ) ) !== 0 ) {
  5810. return false;
  5811. }
  5812. wp_delete_file( $file );
  5813. return true;
  5814. }
  5815. /**
  5816. * Outputs a small JS snippet on preview tabs/windows to remove `window.name` on unload.
  5817. *
  5818. * This prevents reusing the same tab for a preview when the user has navigated away.
  5819. *
  5820. * @since 4.3.0
  5821. *
  5822. * @global WP_Post $post Global post object.
  5823. */
  5824. function wp_post_preview_js() {
  5825. global $post;
  5826. if ( ! is_preview() || empty( $post ) ) {
  5827. return;
  5828. }
  5829. // Has to match the window name used in post_submit_meta_box()
  5830. $name = 'wp-preview-' . (int) $post->ID;
  5831. ?>
  5832. <script>
  5833. ( function() {
  5834. var query = document.location.search;
  5835. if ( query && query.indexOf( 'preview=true' ) !== -1 ) {
  5836. window.name = '<?php echo $name; ?>';
  5837. }
  5838. if ( window.addEventListener ) {
  5839. window.addEventListener( 'unload', function() { window.name = ''; }, false );
  5840. }
  5841. }());
  5842. </script>
  5843. <?php
  5844. }
  5845. /**
  5846. * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601 (Y-m-d\TH:i:s).
  5847. *
  5848. * Explicitly strips timezones, as datetimes are not saved with any timezone
  5849. * information. Including any information on the offset could be misleading.
  5850. *
  5851. * Despite historical function name, the output does not conform to RFC3339 format,
  5852. * which must contain timezone.
  5853. *
  5854. * @since 4.4.0
  5855. *
  5856. * @param string $date_string Date string to parse and format.
  5857. * @return string Date formatted for ISO8601 without time zone.
  5858. */
  5859. function mysql_to_rfc3339( $date_string ) {
  5860. return mysql2date( 'Y-m-d\TH:i:s', $date_string, false );
  5861. }
  5862. /**
  5863. * Attempts to raise the PHP memory limit for memory intensive processes.
  5864. *
  5865. * Only allows raising the existing limit and prevents lowering it.
  5866. *
  5867. * @since 4.6.0
  5868. *
  5869. * @param string $context Optional. Context in which the function is called. Accepts either 'admin',
  5870. * 'image', or an arbitrary other context. If an arbitrary context is passed,
  5871. * the similarly arbitrary {@see '{$context}_memory_limit'} filter will be
  5872. * invoked. Default 'admin'.
  5873. * @return bool|int|string The limit that was set or false on failure.
  5874. */
  5875. function wp_raise_memory_limit( $context = 'admin' ) {
  5876. // Exit early if the limit cannot be changed.
  5877. if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
  5878. return false;
  5879. }
  5880. $current_limit = ini_get( 'memory_limit' );
  5881. $current_limit_int = wp_convert_hr_to_bytes( $current_limit );
  5882. if ( -1 === $current_limit_int ) {
  5883. return false;
  5884. }
  5885. $wp_max_limit = WP_MAX_MEMORY_LIMIT;
  5886. $wp_max_limit_int = wp_convert_hr_to_bytes( $wp_max_limit );
  5887. $filtered_limit = $wp_max_limit;
  5888. switch ( $context ) {
  5889. case 'admin':
  5890. /**
  5891. * Filters the maximum memory limit available for administration screens.
  5892. *
  5893. * This only applies to administrators, who may require more memory for tasks
  5894. * like updates. Memory limits when processing images (uploaded or edited by
  5895. * users of any role) are handled separately.
  5896. *
  5897. * The `WP_MAX_MEMORY_LIMIT` constant specifically defines the maximum memory
  5898. * limit available when in the administration back end. The default is 256M
  5899. * (256 megabytes of memory) or the original `memory_limit` php.ini value if
  5900. * this is higher.
  5901. *
  5902. * @since 3.0.0
  5903. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  5904. *
  5905. * @param int|string $filtered_limit The maximum WordPress memory limit. Accepts an integer
  5906. * (bytes), or a shorthand string notation, such as '256M'.
  5907. */
  5908. $filtered_limit = apply_filters( 'admin_memory_limit', $filtered_limit );
  5909. break;
  5910. case 'image':
  5911. /**
  5912. * Filters the memory limit allocated for image manipulation.
  5913. *
  5914. * @since 3.5.0
  5915. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  5916. *
  5917. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  5918. * Default `WP_MAX_MEMORY_LIMIT` or the original
  5919. * php.ini `memory_limit`, whichever is higher.
  5920. * Accepts an integer (bytes), or a shorthand string
  5921. * notation, such as '256M'.
  5922. */
  5923. $filtered_limit = apply_filters( 'image_memory_limit', $filtered_limit );
  5924. break;
  5925. default:
  5926. /**
  5927. * Filters the memory limit allocated for arbitrary contexts.
  5928. *
  5929. * The dynamic portion of the hook name, `$context`, refers to an arbitrary
  5930. * context passed on calling the function. This allows for plugins to define
  5931. * their own contexts for raising the memory limit.
  5932. *
  5933. * @since 4.6.0
  5934. *
  5935. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  5936. * Default '256M' or the original php.ini `memory_limit`,
  5937. * whichever is higher. Accepts an integer (bytes), or a
  5938. * shorthand string notation, such as '256M'.
  5939. */
  5940. $filtered_limit = apply_filters( "{$context}_memory_limit", $filtered_limit );
  5941. break;
  5942. }
  5943. $filtered_limit_int = wp_convert_hr_to_bytes( $filtered_limit );
  5944. if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
  5945. if ( false !== ini_set( 'memory_limit', $filtered_limit ) ) {
  5946. return $filtered_limit;
  5947. } else {
  5948. return false;
  5949. }
  5950. } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
  5951. if ( false !== ini_set( 'memory_limit', $wp_max_limit ) ) {
  5952. return $wp_max_limit;
  5953. } else {
  5954. return false;
  5955. }
  5956. }
  5957. return false;
  5958. }
  5959. /**
  5960. * Generate a random UUID (version 4).
  5961. *
  5962. * @since 4.7.0
  5963. *
  5964. * @return string UUID.
  5965. */
  5966. function wp_generate_uuid4() {
  5967. return sprintf(
  5968. '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  5969. mt_rand( 0, 0xffff ),
  5970. mt_rand( 0, 0xffff ),
  5971. mt_rand( 0, 0xffff ),
  5972. mt_rand( 0, 0x0fff ) | 0x4000,
  5973. mt_rand( 0, 0x3fff ) | 0x8000,
  5974. mt_rand( 0, 0xffff ),
  5975. mt_rand( 0, 0xffff ),
  5976. mt_rand( 0, 0xffff )
  5977. );
  5978. }
  5979. /**
  5980. * Validates that a UUID is valid.
  5981. *
  5982. * @since 4.9.0
  5983. *
  5984. * @param mixed $uuid UUID to check.
  5985. * @param int $version Specify which version of UUID to check against. Default is none,
  5986. * to accept any UUID version. Otherwise, only version allowed is `4`.
  5987. * @return bool The string is a valid UUID or false on failure.
  5988. */
  5989. function wp_is_uuid( $uuid, $version = null ) {
  5990. if ( ! is_string( $uuid ) ) {
  5991. return false;
  5992. }
  5993. if ( is_numeric( $version ) ) {
  5994. if ( 4 !== (int) $version ) {
  5995. _doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
  5996. return false;
  5997. }
  5998. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
  5999. } else {
  6000. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
  6001. }
  6002. return (bool) preg_match( $regex, $uuid );
  6003. }
  6004. /**
  6005. * Get unique ID.
  6006. *
  6007. * This is a PHP implementation of Underscore's uniqueId method. A static variable
  6008. * contains an integer that is incremented with each call. This number is returned
  6009. * with the optional prefix. As such the returned value is not universally unique,
  6010. * but it is unique across the life of the PHP process.
  6011. *
  6012. * @since 5.0.3
  6013. *
  6014. * @staticvar int $id_counter
  6015. *
  6016. * @param string $prefix Prefix for the returned ID.
  6017. * @return string Unique ID.
  6018. */
  6019. function wp_unique_id( $prefix = '' ) {
  6020. static $id_counter = 0;
  6021. return $prefix . (string) ++$id_counter;
  6022. }
  6023. /**
  6024. * Get last changed date for the specified cache group.
  6025. *
  6026. * @since 4.7.0
  6027. *
  6028. * @param string $group Where the cache contents are grouped.
  6029. *
  6030. * @return string $last_changed UNIX timestamp with microseconds representing when the group was last changed.
  6031. */
  6032. function wp_cache_get_last_changed( $group ) {
  6033. $last_changed = wp_cache_get( 'last_changed', $group );
  6034. if ( ! $last_changed ) {
  6035. $last_changed = microtime();
  6036. wp_cache_set( 'last_changed', $last_changed, $group );
  6037. }
  6038. return $last_changed;
  6039. }
  6040. /**
  6041. * Send an email to the old site admin email address when the site admin email address changes.
  6042. *
  6043. * @since 4.9.0
  6044. *
  6045. * @param string $old_email The old site admin email address.
  6046. * @param string $new_email The new site admin email address.
  6047. * @param string $option_name The relevant database option name.
  6048. */
  6049. function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) {
  6050. $send = true;
  6051. // Don't send the notification to the default 'admin_email' value.
  6052. if ( 'you@example.com' === $old_email ) {
  6053. $send = false;
  6054. }
  6055. /**
  6056. * Filters whether to send the site admin email change notification email.
  6057. *
  6058. * @since 4.9.0
  6059. *
  6060. * @param bool $send Whether to send the email notification.
  6061. * @param string $old_email The old site admin email address.
  6062. * @param string $new_email The new site admin email address.
  6063. */
  6064. $send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email );
  6065. if ( ! $send ) {
  6066. return;
  6067. }
  6068. /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
  6069. $email_change_text = __(
  6070. 'Hi,
  6071. This notice confirms that the admin email address was changed on ###SITENAME###.
  6072. The new admin email address is ###NEW_EMAIL###.
  6073. This email has been sent to ###OLD_EMAIL###
  6074. Regards,
  6075. All at ###SITENAME###
  6076. ###SITEURL###'
  6077. );
  6078. $email_change_email = array(
  6079. 'to' => $old_email,
  6080. /* translators: Site admin email change notification email subject. %s: Site title. */
  6081. 'subject' => __( '[%s] Admin Email Changed' ),
  6082. 'message' => $email_change_text,
  6083. 'headers' => '',
  6084. );
  6085. // get site name
  6086. $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  6087. /**
  6088. * Filters the contents of the email notification sent when the site admin email address is changed.
  6089. *
  6090. * @since 4.9.0
  6091. *
  6092. * @param array $email_change_email {
  6093. * Used to build wp_mail().
  6094. *
  6095. * @type string $to The intended recipient.
  6096. * @type string $subject The subject of the email.
  6097. * @type string $message The content of the email.
  6098. * The following strings have a special meaning and will get replaced dynamically:
  6099. * - ###OLD_EMAIL### The old site admin email address.
  6100. * - ###NEW_EMAIL### The new site admin email address.
  6101. * - ###SITENAME### The name of the site.
  6102. * - ###SITEURL### The URL to the site.
  6103. * @type string $headers Headers.
  6104. * }
  6105. * @param string $old_email The old site admin email address.
  6106. * @param string $new_email The new site admin email address.
  6107. */
  6108. $email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email );
  6109. $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
  6110. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
  6111. $email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] );
  6112. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  6113. wp_mail(
  6114. $email_change_email['to'],
  6115. sprintf(
  6116. $email_change_email['subject'],
  6117. $site_name
  6118. ),
  6119. $email_change_email['message'],
  6120. $email_change_email['headers']
  6121. );
  6122. }
  6123. /**
  6124. * Return an anonymized IPv4 or IPv6 address.
  6125. *
  6126. * @since 4.9.6 Abstracted from `WP_Community_Events::get_unsafe_client_ip()`.
  6127. *
  6128. * @param string $ip_addr The IPv4 or IPv6 address to be anonymized.
  6129. * @param bool $ipv6_fallback Optional. Whether to return the original IPv6 address if the needed functions
  6130. * to anonymize it are not present. Default false, return `::` (unspecified address).
  6131. * @return string The anonymized IP address.
  6132. */
  6133. function wp_privacy_anonymize_ip( $ip_addr, $ipv6_fallback = false ) {
  6134. // Detect what kind of IP address this is.
  6135. $ip_prefix = '';
  6136. $is_ipv6 = substr_count( $ip_addr, ':' ) > 1;
  6137. $is_ipv4 = ( 3 === substr_count( $ip_addr, '.' ) );
  6138. if ( $is_ipv6 && $is_ipv4 ) {
  6139. // IPv6 compatibility mode, temporarily strip the IPv6 part, and treat it like IPv4.
  6140. $ip_prefix = '::ffff:';
  6141. $ip_addr = preg_replace( '/^\[?[0-9a-f:]*:/i', '', $ip_addr );
  6142. $ip_addr = str_replace( ']', '', $ip_addr );
  6143. $is_ipv6 = false;
  6144. }
  6145. if ( $is_ipv6 ) {
  6146. // IPv6 addresses will always be enclosed in [] if there's a port.
  6147. $left_bracket = strpos( $ip_addr, '[' );
  6148. $right_bracket = strpos( $ip_addr, ']' );
  6149. $percent = strpos( $ip_addr, '%' );
  6150. $netmask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  6151. // Strip the port (and [] from IPv6 addresses), if they exist.
  6152. if ( false !== $left_bracket && false !== $right_bracket ) {
  6153. $ip_addr = substr( $ip_addr, $left_bracket + 1, $right_bracket - $left_bracket - 1 );
  6154. } elseif ( false !== $left_bracket || false !== $right_bracket ) {
  6155. // The IP has one bracket, but not both, so it's malformed.
  6156. return '::';
  6157. }
  6158. // Strip the reachability scope.
  6159. if ( false !== $percent ) {
  6160. $ip_addr = substr( $ip_addr, 0, $percent );
  6161. }
  6162. // No invalid characters should be left.
  6163. if ( preg_match( '/[^0-9a-f:]/i', $ip_addr ) ) {
  6164. return '::';
  6165. }
  6166. // Partially anonymize the IP by reducing it to the corresponding network ID.
  6167. if ( function_exists( 'inet_pton' ) && function_exists( 'inet_ntop' ) ) {
  6168. $ip_addr = inet_ntop( inet_pton( $ip_addr ) & inet_pton( $netmask ) );
  6169. if ( false === $ip_addr ) {
  6170. return '::';
  6171. }
  6172. } elseif ( ! $ipv6_fallback ) {
  6173. return '::';
  6174. }
  6175. } elseif ( $is_ipv4 ) {
  6176. // Strip any port and partially anonymize the IP.
  6177. $last_octet_position = strrpos( $ip_addr, '.' );
  6178. $ip_addr = substr( $ip_addr, 0, $last_octet_position ) . '.0';
  6179. } else {
  6180. return '0.0.0.0';
  6181. }
  6182. // Restore the IPv6 prefix to compatibility mode addresses.
  6183. return $ip_prefix . $ip_addr;
  6184. }
  6185. /**
  6186. * Return uniform "anonymous" data by type.
  6187. *
  6188. * @since 4.9.6
  6189. *
  6190. * @param string $type The type of data to be anonymized.
  6191. * @param string $data Optional The data to be anonymized.
  6192. * @return string The anonymous data for the requested type.
  6193. */
  6194. function wp_privacy_anonymize_data( $type, $data = '' ) {
  6195. switch ( $type ) {
  6196. case 'email':
  6197. $anonymous = 'deleted@site.invalid';
  6198. break;
  6199. case 'url':
  6200. $anonymous = 'https://site.invalid';
  6201. break;
  6202. case 'ip':
  6203. $anonymous = wp_privacy_anonymize_ip( $data );
  6204. break;
  6205. case 'date':
  6206. $anonymous = '0000-00-00 00:00:00';
  6207. break;
  6208. case 'text':
  6209. /* translators: Deleted text. */
  6210. $anonymous = __( '[deleted]' );
  6211. break;
  6212. case 'longtext':
  6213. /* translators: Deleted long text. */
  6214. $anonymous = __( 'This content was deleted by the author.' );
  6215. break;
  6216. default:
  6217. $anonymous = '';
  6218. break;
  6219. }
  6220. /**
  6221. * Filters the anonymous data for each type.
  6222. *
  6223. * @since 4.9.6
  6224. *
  6225. * @param string $anonymous Anonymized data.
  6226. * @param string $type Type of the data.
  6227. * @param string $data Original data.
  6228. */
  6229. return apply_filters( 'wp_privacy_anonymize_data', $anonymous, $type, $data );
  6230. }
  6231. /**
  6232. * Returns the directory used to store personal data export files.
  6233. *
  6234. * @since 4.9.6
  6235. *
  6236. * @see wp_privacy_exports_url
  6237. *
  6238. * @return string Exports directory.
  6239. */
  6240. function wp_privacy_exports_dir() {
  6241. $upload_dir = wp_upload_dir();
  6242. $exports_dir = trailingslashit( $upload_dir['basedir'] ) . 'wp-personal-data-exports/';
  6243. /**
  6244. * Filters the directory used to store personal data export files.
  6245. *
  6246. * @since 4.9.6
  6247. *
  6248. * @param string $exports_dir Exports directory.
  6249. */
  6250. return apply_filters( 'wp_privacy_exports_dir', $exports_dir );
  6251. }
  6252. /**
  6253. * Returns the URL of the directory used to store personal data export files.
  6254. *
  6255. * @since 4.9.6
  6256. *
  6257. * @see wp_privacy_exports_dir
  6258. *
  6259. * @return string Exports directory URL.
  6260. */
  6261. function wp_privacy_exports_url() {
  6262. $upload_dir = wp_upload_dir();
  6263. $exports_url = trailingslashit( $upload_dir['baseurl'] ) . 'wp-personal-data-exports/';
  6264. /**
  6265. * Filters the URL of the directory used to store personal data export files.
  6266. *
  6267. * @since 4.9.6
  6268. *
  6269. * @param string $exports_url Exports directory URL.
  6270. */
  6271. return apply_filters( 'wp_privacy_exports_url', $exports_url );
  6272. }
  6273. /**
  6274. * Schedule a `WP_Cron` job to delete expired export files.
  6275. *
  6276. * @since 4.9.6
  6277. */
  6278. function wp_schedule_delete_old_privacy_export_files() {
  6279. if ( wp_installing() ) {
  6280. return;
  6281. }
  6282. if ( ! wp_next_scheduled( 'wp_privacy_delete_old_export_files' ) ) {
  6283. wp_schedule_event( time(), 'hourly', 'wp_privacy_delete_old_export_files' );
  6284. }
  6285. }
  6286. /**
  6287. * Cleans up export files older than three days old.
  6288. *
  6289. * The export files are stored in `wp-content/uploads`, and are therefore publicly
  6290. * accessible. A CSPRN is appended to the filename to mitigate the risk of an
  6291. * unauthorized person downloading the file, but it is still possible. Deleting
  6292. * the file after the data subject has had a chance to delete it adds an additional
  6293. * layer of protection.
  6294. *
  6295. * @since 4.9.6
  6296. */
  6297. function wp_privacy_delete_old_export_files() {
  6298. $exports_dir = wp_privacy_exports_dir();
  6299. if ( ! is_dir( $exports_dir ) ) {
  6300. return;
  6301. }
  6302. require_once( ABSPATH . 'wp-admin/includes/file.php' );
  6303. $export_files = list_files( $exports_dir, 100, array( 'index.html' ) );
  6304. /**
  6305. * Filters the lifetime, in seconds, of a personal data export file.
  6306. *
  6307. * By default, the lifetime is 3 days. Once the file reaches that age, it will automatically
  6308. * be deleted by a cron job.
  6309. *
  6310. * @since 4.9.6
  6311. *
  6312. * @param int $expiration The expiration age of the export, in seconds.
  6313. */
  6314. $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
  6315. foreach ( (array) $export_files as $export_file ) {
  6316. $file_age_in_seconds = time() - filemtime( $export_file );
  6317. if ( $expiration < $file_age_in_seconds ) {
  6318. unlink( $export_file );
  6319. }
  6320. }
  6321. }
  6322. /**
  6323. * Gets the URL to learn more about updating the PHP version the site is running on.
  6324. *
  6325. * This URL can be overridden by specifying an environment variable `WP_UPDATE_PHP_URL` or by using the
  6326. * {@see 'wp_update_php_url'} filter. Providing an empty string is not allowed and will result in the
  6327. * default URL being used. Furthermore the page the URL links to should preferably be localized in the
  6328. * site language.
  6329. *
  6330. * @since 5.1.0
  6331. *
  6332. * @return string URL to learn more about updating PHP.
  6333. */
  6334. function wp_get_update_php_url() {
  6335. $default_url = wp_get_default_update_php_url();
  6336. $update_url = $default_url;
  6337. if ( false !== getenv( 'WP_UPDATE_PHP_URL' ) ) {
  6338. $update_url = getenv( 'WP_UPDATE_PHP_URL' );
  6339. }
  6340. /**
  6341. * Filters the URL to learn more about updating the PHP version the site is running on.
  6342. *
  6343. * Providing an empty string is not allowed and will result in the default URL being used. Furthermore
  6344. * the page the URL links to should preferably be localized in the site language.
  6345. *
  6346. * @since 5.1.0
  6347. *
  6348. * @param string $update_url URL to learn more about updating PHP.
  6349. */
  6350. $update_url = apply_filters( 'wp_update_php_url', $update_url );
  6351. if ( empty( $update_url ) ) {
  6352. $update_url = $default_url;
  6353. }
  6354. return $update_url;
  6355. }
  6356. /**
  6357. * Gets the default URL to learn more about updating the PHP version the site is running on.
  6358. *
  6359. * Do not use this function to retrieve this URL. Instead, use {@see wp_get_update_php_url()} when relying on the URL.
  6360. * This function does not allow modifying the returned URL, and is only used to compare the actually used URL with the
  6361. * default one.
  6362. *
  6363. * @since 5.1.0
  6364. * @access private
  6365. *
  6366. * @return string Default URL to learn more about updating PHP.
  6367. */
  6368. function wp_get_default_update_php_url() {
  6369. return _x( 'https://wordpress.org/support/update-php/', 'localized PHP upgrade information page' );
  6370. }
  6371. /**
  6372. * Prints the default annotation for the web host altering the "Update PHP" page URL.
  6373. *
  6374. * This function is to be used after {@see wp_get_update_php_url()} to display a consistent
  6375. * annotation if the web host has altered the default "Update PHP" page URL.
  6376. *
  6377. * @since 5.1.0
  6378. * @since 5.2.0 Added the `$before` and `$after` parameters.
  6379. *
  6380. * @param string $before Markup to output before the annotation. Default `<p class="description">`.
  6381. * @param string $after Markup to output after the annotation. Default `</p>`.
  6382. */
  6383. function wp_update_php_annotation( $before = '<p class="description">', $after = '</p>' ) {
  6384. $annotation = wp_get_update_php_annotation();
  6385. if ( $annotation ) {
  6386. echo $before . $annotation . $after;
  6387. }
  6388. }
  6389. /**
  6390. * Returns the default annotation for the web hosting altering the "Update PHP" page URL.
  6391. *
  6392. * This function is to be used after {@see wp_get_update_php_url()} to return a consistent
  6393. * annotation if the web host has altered the default "Update PHP" page URL.
  6394. *
  6395. * @since 5.2.0
  6396. *
  6397. * @return string $message Update PHP page annotation. An empty string if no custom URLs are provided.
  6398. */
  6399. function wp_get_update_php_annotation() {
  6400. $update_url = wp_get_update_php_url();
  6401. $default_url = wp_get_default_update_php_url();
  6402. if ( $update_url === $default_url ) {
  6403. return '';
  6404. }
  6405. $annotation = sprintf(
  6406. /* translators: %s: Default Update PHP page URL. */
  6407. __( 'This resource is provided by your web host, and is specific to your site. For more information, <a href="%s" target="_blank">see the official WordPress documentation</a>.' ),
  6408. esc_url( $default_url )
  6409. );
  6410. return $annotation;
  6411. }
  6412. /**
  6413. * Gets the URL for directly updating the PHP version the site is running on.
  6414. *
  6415. * A URL will only be returned if the `WP_DIRECT_UPDATE_PHP_URL` environment variable is specified or
  6416. * by using the {@see 'wp_direct_php_update_url'} filter. This allows hosts to send users directly to
  6417. * the page where they can update PHP to a newer version.
  6418. *
  6419. * @since 5.1.1
  6420. *
  6421. * @return string URL for directly updating PHP or empty string.
  6422. */
  6423. function wp_get_direct_php_update_url() {
  6424. $direct_update_url = '';
  6425. if ( false !== getenv( 'WP_DIRECT_UPDATE_PHP_URL' ) ) {
  6426. $direct_update_url = getenv( 'WP_DIRECT_UPDATE_PHP_URL' );
  6427. }
  6428. /**
  6429. * Filters the URL for directly updating the PHP version the site is running on from the host.
  6430. *
  6431. * @since 5.1.1
  6432. *
  6433. * @param string $direct_update_url URL for directly updating PHP.
  6434. */
  6435. $direct_update_url = apply_filters( 'wp_direct_php_update_url', $direct_update_url );
  6436. return $direct_update_url;
  6437. }
  6438. /**
  6439. * Display a button directly linking to a PHP update process.
  6440. *
  6441. * This provides hosts with a way for users to be sent directly to their PHP update process.
  6442. *
  6443. * The button is only displayed if a URL is returned by `wp_get_direct_php_update_url()`.
  6444. *
  6445. * @since 5.1.1
  6446. */
  6447. function wp_direct_php_update_button() {
  6448. $direct_update_url = wp_get_direct_php_update_url();
  6449. if ( empty( $direct_update_url ) ) {
  6450. return;
  6451. }
  6452. echo '<p class="button-container">';
  6453. printf(
  6454. '<a class="button button-primary" href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
  6455. esc_url( $direct_update_url ),
  6456. __( 'Update PHP' ),
  6457. /* translators: Accessibility text. */
  6458. __( '(opens in a new tab)' )
  6459. );
  6460. echo '</p>';
  6461. }
  6462. /**
  6463. * Get the size of a directory.
  6464. *
  6465. * A helper function that is used primarily to check whether
  6466. * a blog has exceeded its allowed upload space.
  6467. *
  6468. * @since MU (3.0.0)
  6469. * @since 5.2.0 $max_execution_time parameter added.
  6470. *
  6471. * @param string $directory Full path of a directory.
  6472. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  6473. * The timeout is global and is measured from the moment WordPress started to load.
  6474. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  6475. */
  6476. function get_dirsize( $directory, $max_execution_time = null ) {
  6477. $dirsize = get_transient( 'dirsize_cache' );
  6478. if ( is_array( $dirsize ) && isset( $dirsize[ $directory ]['size'] ) ) {
  6479. return $dirsize[ $directory ]['size'];
  6480. }
  6481. if ( ! is_array( $dirsize ) ) {
  6482. $dirsize = array();
  6483. }
  6484. // Exclude individual site directories from the total when checking the main site of a network
  6485. // as they are subdirectories and should not be counted.
  6486. if ( is_multisite() && is_main_site() ) {
  6487. $dirsize[ $directory ]['size'] = recurse_dirsize( $directory, $directory . '/sites', $max_execution_time );
  6488. } else {
  6489. $dirsize[ $directory ]['size'] = recurse_dirsize( $directory, null, $max_execution_time );
  6490. }
  6491. set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS );
  6492. return $dirsize[ $directory ]['size'];
  6493. }
  6494. /**
  6495. * Get the size of a directory recursively.
  6496. *
  6497. * Used by get_dirsize() to get a directory's size when it contains
  6498. * other directories.
  6499. *
  6500. * @since MU (3.0.0)
  6501. * @since 4.3.0 $exclude parameter added.
  6502. * @since 5.2.0 $max_execution_time parameter added.
  6503. *
  6504. * @param string $directory Full path of a directory.
  6505. * @param string|array $exclude Optional. Full path of a subdirectory to exclude from the total, or array of paths.
  6506. * Expected without trailing slash(es).
  6507. * @param int $max_execution_time Maximum time to run before giving up. In seconds.
  6508. * The timeout is global and is measured from the moment WordPress started to load.
  6509. * @return int|false|null Size in bytes if a valid directory. False if not. Null if timeout.
  6510. */
  6511. function recurse_dirsize( $directory, $exclude = null, $max_execution_time = null ) {
  6512. $size = 0;
  6513. $directory = untrailingslashit( $directory );
  6514. if ( ! file_exists( $directory ) || ! is_dir( $directory ) || ! is_readable( $directory ) ) {
  6515. return false;
  6516. }
  6517. if (
  6518. ( is_string( $exclude ) && $directory === $exclude ) ||
  6519. ( is_array( $exclude ) && in_array( $directory, $exclude, true ) )
  6520. ) {
  6521. return false;
  6522. }
  6523. if ( $max_execution_time === null ) {
  6524. // Keep the previous behavior but attempt to prevent fatal errors from timeout if possible.
  6525. if ( function_exists( 'ini_get' ) ) {
  6526. $max_execution_time = ini_get( 'max_execution_time' );
  6527. } else {
  6528. // Disable...
  6529. $max_execution_time = 0;
  6530. }
  6531. // Leave 1 second "buffer" for other operations if $max_execution_time has reasonable value.
  6532. if ( $max_execution_time > 10 ) {
  6533. $max_execution_time -= 1;
  6534. }
  6535. }
  6536. $handle = opendir( $directory );
  6537. if ( $handle ) {
  6538. while ( ( $file = readdir( $handle ) ) !== false ) {
  6539. $path = $directory . '/' . $file;
  6540. if ( $file != '.' && $file != '..' ) {
  6541. if ( is_file( $path ) ) {
  6542. $size += filesize( $path );
  6543. } elseif ( is_dir( $path ) ) {
  6544. $handlesize = recurse_dirsize( $path, $exclude, $max_execution_time );
  6545. if ( $handlesize > 0 ) {
  6546. $size += $handlesize;
  6547. }
  6548. }
  6549. if ( $max_execution_time > 0 && microtime( true ) - WP_START_TIMESTAMP > $max_execution_time ) {
  6550. // Time exceeded. Give up instead of risking a fatal timeout.
  6551. $size = null;
  6552. break;
  6553. }
  6554. }
  6555. }
  6556. closedir( $handle );
  6557. }
  6558. return $size;
  6559. }
  6560. /**
  6561. * Checks compatibility with the current WordPress version.
  6562. *
  6563. * @since 5.2.0
  6564. *
  6565. * @param string $required Minimum required WordPress version.
  6566. * @return bool True if required version is compatible or empty, false if not.
  6567. */
  6568. function is_wp_version_compatible( $required ) {
  6569. return empty( $required ) || version_compare( get_bloginfo( 'version' ), $required, '>=' );
  6570. }
  6571. /**
  6572. * Checks compatibility with the current PHP version.
  6573. *
  6574. * @since 5.2.0
  6575. *
  6576. * @param string $required Minimum required PHP version.
  6577. * @return bool True if required version is compatible or empty, false if not.
  6578. */
  6579. function is_php_version_compatible( $required ) {
  6580. return empty( $required ) || version_compare( phpversion(), $required, '>=' );
  6581. }
  6582. /**
  6583. * Check if two numbers are nearly the same.
  6584. *
  6585. * This is similar to using `round()` but the precision is more fine-grained.
  6586. *
  6587. * @since 5.3.0
  6588. *
  6589. * @param int|float $expected The expected value.
  6590. * @param int|float $actual The actual number.
  6591. * @param int|float $precision The allowed variation.
  6592. * @return bool Whether the numbers match whithin the specified precision.
  6593. */
  6594. function wp_fuzzy_number_match( $expected, $actual, $precision = 1 ) {
  6595. return abs( (float) $expected - (float) $actual ) <= $precision;
  6596. }