Sin descripción

functions.php 247KB

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