functions.php 185 KB

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