functions.php 183 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077
  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. // We need to find the permissions of the parent folder that exists and inherit that.
  1450. $target_parent = dirname( $target );
  1451. while ( '.' != $target_parent && ! is_dir( $target_parent ) && dirname( $target_parent ) !== $target_parent ) {
  1452. $target_parent = dirname( $target_parent );
  1453. }
  1454. // Get the permission bits.
  1455. if ( $stat = @stat( $target_parent ) ) {
  1456. $dir_perms = $stat['mode'] & 0007777;
  1457. } else {
  1458. $dir_perms = 0777;
  1459. }
  1460. if ( @mkdir( $target, $dir_perms, true ) ) {
  1461. /*
  1462. * If a umask is set that modifies $dir_perms, we'll have to re-set
  1463. * the $dir_perms correctly with chmod()
  1464. */
  1465. if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
  1466. $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1467. for ( $i = 1, $c = count( $folder_parts ); $i <= $c; $i++ ) {
  1468. @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1469. }
  1470. }
  1471. return true;
  1472. }
  1473. return false;
  1474. }
  1475. /**
  1476. * Test if a given filesystem path is absolute.
  1477. *
  1478. * For example, '/foo/bar', or 'c:\windows'.
  1479. *
  1480. * @since 2.5.0
  1481. *
  1482. * @param string $path File path.
  1483. * @return bool True if path is absolute, false is not absolute.
  1484. */
  1485. function path_is_absolute( $path ) {
  1486. /*
  1487. * This is definitive if true but fails if $path does not exist or contains
  1488. * a symbolic link.
  1489. */
  1490. if ( realpath($path) == $path )
  1491. return true;
  1492. if ( strlen($path) == 0 || $path[0] == '.' )
  1493. return false;
  1494. // Windows allows absolute paths like this.
  1495. if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1496. return true;
  1497. // A path starting with / or \ is absolute; anything else is relative.
  1498. return ( $path[0] == '/' || $path[0] == '\\' );
  1499. }
  1500. /**
  1501. * Join two filesystem paths together.
  1502. *
  1503. * For example, 'give me $path relative to $base'. If the $path is absolute,
  1504. * then it the full path is returned.
  1505. *
  1506. * @since 2.5.0
  1507. *
  1508. * @param string $base Base path.
  1509. * @param string $path Path relative to $base.
  1510. * @return string The path with the base or absolute path.
  1511. */
  1512. function path_join( $base, $path ) {
  1513. if ( path_is_absolute($path) )
  1514. return $path;
  1515. return rtrim($base, '/') . '/' . ltrim($path, '/');
  1516. }
  1517. /**
  1518. * Normalize a filesystem path.
  1519. *
  1520. * On windows systems, replaces backslashes with forward slashes
  1521. * and forces upper-case drive letters.
  1522. * Allows for two leading slashes for Windows network shares, but
  1523. * ensures that all other duplicate slashes are reduced to a single.
  1524. *
  1525. * @since 3.9.0
  1526. * @since 4.4.0 Ensures upper-case drive letters on Windows systems.
  1527. * @since 4.5.0 Allows for Windows network shares.
  1528. * @since 4.9.7 Allows for PHP file wrappers.
  1529. *
  1530. * @param string $path Path to normalize.
  1531. * @return string Normalized path.
  1532. */
  1533. function wp_normalize_path( $path ) {
  1534. $wrapper = '';
  1535. if ( wp_is_stream( $path ) ) {
  1536. list( $wrapper, $path ) = explode( '://', $path, 2 );
  1537. $wrapper .= '://';
  1538. }
  1539. // Standardise all paths to use /
  1540. $path = str_replace( '\\', '/', $path );
  1541. // Replace multiple slashes down to a singular, allowing for network shares having two slashes.
  1542. $path = preg_replace( '|(?<=.)/+|', '/', $path );
  1543. // Windows paths should uppercase the drive letter
  1544. if ( ':' === substr( $path, 1, 1 ) ) {
  1545. $path = ucfirst( $path );
  1546. }
  1547. return $wrapper . $path;
  1548. }
  1549. /**
  1550. * Determine a writable directory for temporary files.
  1551. *
  1552. * Function's preference is the return value of sys_get_temp_dir(),
  1553. * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1554. * before finally defaulting to /tmp/
  1555. *
  1556. * In the event that this function does not find a writable location,
  1557. * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
  1558. *
  1559. * @since 2.5.0
  1560. *
  1561. * @staticvar string $temp
  1562. *
  1563. * @return string Writable temporary directory.
  1564. */
  1565. function get_temp_dir() {
  1566. static $temp = '';
  1567. if ( defined('WP_TEMP_DIR') )
  1568. return trailingslashit(WP_TEMP_DIR);
  1569. if ( $temp )
  1570. return trailingslashit( $temp );
  1571. if ( function_exists('sys_get_temp_dir') ) {
  1572. $temp = sys_get_temp_dir();
  1573. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1574. return trailingslashit( $temp );
  1575. }
  1576. $temp = ini_get('upload_tmp_dir');
  1577. if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1578. return trailingslashit( $temp );
  1579. $temp = WP_CONTENT_DIR . '/';
  1580. if ( is_dir( $temp ) && wp_is_writable( $temp ) )
  1581. return $temp;
  1582. return '/tmp/';
  1583. }
  1584. /**
  1585. * Determine if a directory is writable.
  1586. *
  1587. * This function is used to work around certain ACL issues in PHP primarily
  1588. * affecting Windows Servers.
  1589. *
  1590. * @since 3.6.0
  1591. *
  1592. * @see win_is_writable()
  1593. *
  1594. * @param string $path Path to check for write-ability.
  1595. * @return bool Whether the path is writable.
  1596. */
  1597. function wp_is_writable( $path ) {
  1598. if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
  1599. return win_is_writable( $path );
  1600. else
  1601. return @is_writable( $path );
  1602. }
  1603. /**
  1604. * Workaround for Windows bug in is_writable() function
  1605. *
  1606. * PHP has issues with Windows ACL's for determine if a
  1607. * directory is writable or not, this works around them by
  1608. * checking the ability to open files rather than relying
  1609. * upon PHP to interprate the OS ACL.
  1610. *
  1611. * @since 2.8.0
  1612. *
  1613. * @see https://bugs.php.net/bug.php?id=27609
  1614. * @see https://bugs.php.net/bug.php?id=30931
  1615. *
  1616. * @param string $path Windows path to check for write-ability.
  1617. * @return bool Whether the path is writable.
  1618. */
  1619. function win_is_writable( $path ) {
  1620. if ( $path[strlen( $path ) - 1] == '/' ) { // if it looks like a directory, check a random file within the directory
  1621. return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
  1622. } elseif ( is_dir( $path ) ) { // If it's a directory (and not a file) check a random file within the directory
  1623. return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1624. }
  1625. // check tmp file for read/write capabilities
  1626. $should_delete_tmp_file = !file_exists( $path );
  1627. $f = @fopen( $path, 'a' );
  1628. if ( $f === false )
  1629. return false;
  1630. fclose( $f );
  1631. if ( $should_delete_tmp_file )
  1632. unlink( $path );
  1633. return true;
  1634. }
  1635. /**
  1636. * Retrieves uploads directory information.
  1637. *
  1638. * Same as wp_upload_dir() but "light weight" as it doesn't attempt to create the uploads directory.
  1639. * Intended for use in themes, when only 'basedir' and 'baseurl' are needed, generally in all cases
  1640. * when not uploading files.
  1641. *
  1642. * @since 4.5.0
  1643. *
  1644. * @see wp_upload_dir()
  1645. *
  1646. * @return array See wp_upload_dir() for description.
  1647. */
  1648. function wp_get_upload_dir() {
  1649. return wp_upload_dir( null, false );
  1650. }
  1651. /**
  1652. * Get an array containing the current upload directory's path and url.
  1653. *
  1654. * Checks the 'upload_path' option, which should be from the web root folder,
  1655. * and if it isn't empty it will be used. If it is empty, then the path will be
  1656. * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1657. * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1658. *
  1659. * The upload URL path is set either by the 'upload_url_path' option or by using
  1660. * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1661. *
  1662. * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1663. * the administration settings panel), then the time will be used. The format
  1664. * will be year first and then month.
  1665. *
  1666. * If the path couldn't be created, then an error will be returned with the key
  1667. * 'error' containing the error message. The error suggests that the parent
  1668. * directory is not writable by the server.
  1669. *
  1670. * On success, the returned array will have many indices:
  1671. * 'path' - base directory and sub directory or full path to upload directory.
  1672. * 'url' - base url and sub directory or absolute URL to upload directory.
  1673. * 'subdir' - sub directory if uploads use year/month folders option is on.
  1674. * 'basedir' - path without subdir.
  1675. * 'baseurl' - URL path without subdir.
  1676. * 'error' - false or error message.
  1677. *
  1678. * @since 2.0.0
  1679. * @uses _wp_upload_dir()
  1680. *
  1681. * @staticvar array $cache
  1682. * @staticvar array $tested_paths
  1683. *
  1684. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1685. * @param bool $create_dir Optional. Whether to check and create the uploads directory.
  1686. * Default true for backward compatibility.
  1687. * @param bool $refresh_cache Optional. Whether to refresh the cache. Default false.
  1688. * @return array See above for description.
  1689. */
  1690. function wp_upload_dir( $time = null, $create_dir = true, $refresh_cache = false ) {
  1691. static $cache = array(), $tested_paths = array();
  1692. $key = sprintf( '%d-%s', get_current_blog_id(), (string) $time );
  1693. if ( $refresh_cache || empty( $cache[ $key ] ) ) {
  1694. $cache[ $key ] = _wp_upload_dir( $time );
  1695. }
  1696. /**
  1697. * Filters the uploads directory data.
  1698. *
  1699. * @since 2.0.0
  1700. *
  1701. * @param array $uploads Array of upload directory data with keys of 'path',
  1702. * 'url', 'subdir, 'basedir', and 'error'.
  1703. */
  1704. $uploads = apply_filters( 'upload_dir', $cache[ $key ] );
  1705. if ( $create_dir ) {
  1706. $path = $uploads['path'];
  1707. if ( array_key_exists( $path, $tested_paths ) ) {
  1708. $uploads['error'] = $tested_paths[ $path ];
  1709. } else {
  1710. if ( ! wp_mkdir_p( $path ) ) {
  1711. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
  1712. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  1713. } else {
  1714. $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  1715. }
  1716. $uploads['error'] = sprintf(
  1717. /* translators: %s: directory path */
  1718. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  1719. esc_html( $error_path )
  1720. );
  1721. }
  1722. $tested_paths[ $path ] = $uploads['error'];
  1723. }
  1724. }
  1725. return $uploads;
  1726. }
  1727. /**
  1728. * A non-filtered, non-cached version of wp_upload_dir() that doesn't check the path.
  1729. *
  1730. * @since 4.5.0
  1731. * @access private
  1732. *
  1733. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1734. * @return array See wp_upload_dir()
  1735. */
  1736. function _wp_upload_dir( $time = null ) {
  1737. $siteurl = get_option( 'siteurl' );
  1738. $upload_path = trim( get_option( 'upload_path' ) );
  1739. if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1740. $dir = WP_CONTENT_DIR . '/uploads';
  1741. } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1742. // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1743. $dir = path_join( ABSPATH, $upload_path );
  1744. } else {
  1745. $dir = $upload_path;
  1746. }
  1747. if ( !$url = get_option( 'upload_url_path' ) ) {
  1748. if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1749. $url = WP_CONTENT_URL . '/uploads';
  1750. else
  1751. $url = trailingslashit( $siteurl ) . $upload_path;
  1752. }
  1753. /*
  1754. * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  1755. * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  1756. */
  1757. if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  1758. $dir = ABSPATH . UPLOADS;
  1759. $url = trailingslashit( $siteurl ) . UPLOADS;
  1760. }
  1761. // If multisite (and if not the main site in a post-MU network)
  1762. if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  1763. if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  1764. /*
  1765. * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  1766. * straightforward: Append sites/%d if we're not on the main site (for post-MU
  1767. * networks). (The extra directory prevents a four-digit ID from conflicting with
  1768. * a year-based directory for the main site. But if a MU-era network has disabled
  1769. * ms-files rewriting manually, they don't need the extra directory, as they never
  1770. * had wp-content/uploads for the main site.)
  1771. */
  1772. if ( defined( 'MULTISITE' ) )
  1773. $ms_dir = '/sites/' . get_current_blog_id();
  1774. else
  1775. $ms_dir = '/' . get_current_blog_id();
  1776. $dir .= $ms_dir;
  1777. $url .= $ms_dir;
  1778. } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  1779. /*
  1780. * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  1781. * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  1782. * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  1783. * there, and
  1784. * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  1785. * the original blog ID.
  1786. *
  1787. * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  1788. * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  1789. * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  1790. * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  1791. */
  1792. if ( defined( 'BLOGUPLOADDIR' ) )
  1793. $dir = untrailingslashit( BLOGUPLOADDIR );
  1794. else
  1795. $dir = ABSPATH . UPLOADS;
  1796. $url = trailingslashit( $siteurl ) . 'files';
  1797. }
  1798. }
  1799. $basedir = $dir;
  1800. $baseurl = $url;
  1801. $subdir = '';
  1802. if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1803. // Generate the yearly and monthly dirs
  1804. if ( !$time )
  1805. $time = current_time( 'mysql' );
  1806. $y = substr( $time, 0, 4 );
  1807. $m = substr( $time, 5, 2 );
  1808. $subdir = "/$y/$m";
  1809. }
  1810. $dir .= $subdir;
  1811. $url .= $subdir;
  1812. return array(
  1813. 'path' => $dir,
  1814. 'url' => $url,
  1815. 'subdir' => $subdir,
  1816. 'basedir' => $basedir,
  1817. 'baseurl' => $baseurl,
  1818. 'error' => false,
  1819. );
  1820. }
  1821. /**
  1822. * Get a filename that is sanitized and unique for the given directory.
  1823. *
  1824. * If the filename is not unique, then a number will be added to the filename
  1825. * before the extension, and will continue adding numbers until the filename is
  1826. * unique.
  1827. *
  1828. * The callback is passed three parameters, the first one is the directory, the
  1829. * second is the filename, and the third is the extension.
  1830. *
  1831. * @since 2.5.0
  1832. *
  1833. * @param string $dir Directory.
  1834. * @param string $filename File name.
  1835. * @param callable $unique_filename_callback Callback. Default null.
  1836. * @return string New filename, if given wasn't unique.
  1837. */
  1838. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1839. // Sanitize the file name before we begin processing.
  1840. $filename = sanitize_file_name($filename);
  1841. // Separate the filename into a name and extension.
  1842. $ext = pathinfo( $filename, PATHINFO_EXTENSION );
  1843. $name = pathinfo( $filename, PATHINFO_BASENAME );
  1844. if ( $ext ) {
  1845. $ext = '.' . $ext;
  1846. }
  1847. // Edge case: if file is named '.ext', treat as an empty name.
  1848. if ( $name === $ext ) {
  1849. $name = '';
  1850. }
  1851. /*
  1852. * Increment the file number until we have a unique file to save in $dir.
  1853. * Use callback if supplied.
  1854. */
  1855. if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  1856. $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  1857. } else {
  1858. $number = '';
  1859. // Change '.ext' to lower case.
  1860. if ( $ext && strtolower($ext) != $ext ) {
  1861. $ext2 = strtolower($ext);
  1862. $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
  1863. // Check for both lower and upper case extension or image sub-sizes may be overwritten.
  1864. while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
  1865. $new_number = (int) $number + 1;
  1866. $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-$new_number$ext", $filename );
  1867. $filename2 = str_replace( array( "-$number$ext2", "$number$ext2" ), "-$new_number$ext2", $filename2 );
  1868. $number = $new_number;
  1869. }
  1870. /**
  1871. * Filters the result when generating a unique file name.
  1872. *
  1873. * @since 4.5.0
  1874. *
  1875. * @param string $filename Unique file name.
  1876. * @param string $ext File extension, eg. ".png".
  1877. * @param string $dir Directory path.
  1878. * @param callable|null $unique_filename_callback Callback function that generates the unique file name.
  1879. */
  1880. return apply_filters( 'wp_unique_filename', $filename2, $ext, $dir, $unique_filename_callback );
  1881. }
  1882. while ( file_exists( $dir . "/$filename" ) ) {
  1883. $new_number = (int) $number + 1;
  1884. if ( '' == "$number$ext" ) {
  1885. $filename = "$filename-" . $new_number;
  1886. } else {
  1887. $filename = str_replace( array( "-$number$ext", "$number$ext" ), "-" . $new_number . $ext, $filename );
  1888. }
  1889. $number = $new_number;
  1890. }
  1891. }
  1892. /** This filter is documented in wp-includes/functions.php */
  1893. return apply_filters( 'wp_unique_filename', $filename, $ext, $dir, $unique_filename_callback );
  1894. }
  1895. /**
  1896. * Create a file in the upload folder with given content.
  1897. *
  1898. * If there is an error, then the key 'error' will exist with the error message.
  1899. * If success, then the key 'file' will have the unique file path, the 'url' key
  1900. * will have the link to the new file. and the 'error' key will be set to false.
  1901. *
  1902. * This function will not move an uploaded file to the upload folder. It will
  1903. * create a new file with the content in $bits parameter. If you move the upload
  1904. * file, read the content of the uploaded file, and then you can give the
  1905. * filename and content to this function, which will add it to the upload
  1906. * folder.
  1907. *
  1908. * The permissions will be set on the new file automatically by this function.
  1909. *
  1910. * @since 2.0.0
  1911. *
  1912. * @param string $name Filename.
  1913. * @param null|string $deprecated Never used. Set to null.
  1914. * @param mixed $bits File content
  1915. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1916. * @return array
  1917. */
  1918. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  1919. if ( !empty( $deprecated ) )
  1920. _deprecated_argument( __FUNCTION__, '2.0.0' );
  1921. if ( empty( $name ) )
  1922. return array( 'error' => __( 'Empty filename' ) );
  1923. $wp_filetype = wp_check_filetype( $name );
  1924. if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
  1925. return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.' ) );
  1926. $upload = wp_upload_dir( $time );
  1927. if ( $upload['error'] !== false )
  1928. return $upload;
  1929. /**
  1930. * Filters whether to treat the upload bits as an error.
  1931. *
  1932. * Passing a non-array to the filter will effectively short-circuit preparing
  1933. * the upload bits, returning that value instead.
  1934. *
  1935. * @since 3.0.0
  1936. *
  1937. * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
  1938. */
  1939. $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
  1940. if ( !is_array( $upload_bits_error ) ) {
  1941. $upload[ 'error' ] = $upload_bits_error;
  1942. return $upload;
  1943. }
  1944. $filename = wp_unique_filename( $upload['path'], $name );
  1945. $new_file = $upload['path'] . "/$filename";
  1946. if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  1947. if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
  1948. $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  1949. else
  1950. $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
  1951. $message = sprintf(
  1952. /* translators: %s: directory path */
  1953. __( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
  1954. $error_path
  1955. );
  1956. return array( 'error' => $message );
  1957. }
  1958. $ifp = @ fopen( $new_file, 'wb' );
  1959. if ( ! $ifp )
  1960. return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  1961. @fwrite( $ifp, $bits );
  1962. fclose( $ifp );
  1963. clearstatcache();
  1964. // Set correct file permissions
  1965. $stat = @ stat( dirname( $new_file ) );
  1966. $perms = $stat['mode'] & 0007777;
  1967. $perms = $perms & 0000666;
  1968. @ chmod( $new_file, $perms );
  1969. clearstatcache();
  1970. // Compute the URL
  1971. $url = $upload['url'] . "/$filename";
  1972. /** This filter is documented in wp-admin/includes/file.php */
  1973. return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $wp_filetype['type'], 'error' => false ), 'sideload' );
  1974. }
  1975. /**
  1976. * Retrieve the file type based on the extension name.
  1977. *
  1978. * @since 2.5.0
  1979. *
  1980. * @param string $ext The extension to search.
  1981. * @return string|void The file type, example: audio, video, document, spreadsheet, etc.
  1982. */
  1983. function wp_ext2type( $ext ) {
  1984. $ext = strtolower( $ext );
  1985. $ext2type = wp_get_ext_types();
  1986. foreach ( $ext2type as $type => $exts )
  1987. if ( in_array( $ext, $exts ) )
  1988. return $type;
  1989. }
  1990. /**
  1991. * Retrieve the file type from the file name.
  1992. *
  1993. * You can optionally define the mime array, if needed.
  1994. *
  1995. * @since 2.0.4
  1996. *
  1997. * @param string $filename File name or path.
  1998. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  1999. * @return array Values with extension first and mime type.
  2000. */
  2001. function wp_check_filetype( $filename, $mimes = null ) {
  2002. if ( empty($mimes) )
  2003. $mimes = get_allowed_mime_types();
  2004. $type = false;
  2005. $ext = false;
  2006. foreach ( $mimes as $ext_preg => $mime_match ) {
  2007. $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2008. if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2009. $type = $mime_match;
  2010. $ext = $ext_matches[1];
  2011. break;
  2012. }
  2013. }
  2014. return compact( 'ext', 'type' );
  2015. }
  2016. /**
  2017. * Attempt to determine the real file type of a file.
  2018. *
  2019. * If unable to, the file name extension will be used to determine type.
  2020. *
  2021. * If it's determined that the extension does not match the file's real type,
  2022. * then the "proper_filename" value will be set with a proper filename and extension.
  2023. *
  2024. * Currently this function only supports renaming images validated via wp_get_image_mime().
  2025. *
  2026. * @since 3.0.0
  2027. *
  2028. * @param string $file Full path to the file.
  2029. * @param string $filename The name of the file (may differ from $file due to $file being
  2030. * in a tmp directory).
  2031. * @param array $mimes Optional. Key is the file extension with value as the mime type.
  2032. * @return array Values for the extension, MIME, and either a corrected filename or false
  2033. * if original $filename is valid.
  2034. */
  2035. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2036. $proper_filename = false;
  2037. // Do basic extension validation and MIME mapping
  2038. $wp_filetype = wp_check_filetype( $filename, $mimes );
  2039. $ext = $wp_filetype['ext'];
  2040. $type = $wp_filetype['type'];
  2041. // We can't do any further validation without a file to work with
  2042. if ( ! file_exists( $file ) ) {
  2043. return compact( 'ext', 'type', 'proper_filename' );
  2044. }
  2045. $real_mime = false;
  2046. // Validate image types.
  2047. if ( $type && 0 === strpos( $type, 'image/' ) ) {
  2048. // Attempt to figure out what type of image it actually is
  2049. $real_mime = wp_get_image_mime( $file );
  2050. if ( $real_mime && $real_mime != $type ) {
  2051. /**
  2052. * Filters the list mapping image mime types to their respective extensions.
  2053. *
  2054. * @since 3.0.0
  2055. *
  2056. * @param array $mime_to_ext Array of image mime types and their matching extensions.
  2057. */
  2058. $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
  2059. 'image/jpeg' => 'jpg',
  2060. 'image/png' => 'png',
  2061. 'image/gif' => 'gif',
  2062. 'image/bmp' => 'bmp',
  2063. 'image/tiff' => 'tif',
  2064. ) );
  2065. // Replace whatever is after the last period in the filename with the correct extension
  2066. if ( ! empty( $mime_to_ext[ $real_mime ] ) ) {
  2067. $filename_parts = explode( '.', $filename );
  2068. array_pop( $filename_parts );
  2069. $filename_parts[] = $mime_to_ext[ $real_mime ];
  2070. $new_filename = implode( '.', $filename_parts );
  2071. if ( $new_filename != $filename ) {
  2072. $proper_filename = $new_filename; // Mark that it changed
  2073. }
  2074. // Redefine the extension / MIME
  2075. $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2076. $ext = $wp_filetype['ext'];
  2077. $type = $wp_filetype['type'];
  2078. } else {
  2079. // Reset $real_mime and try validating again.
  2080. $real_mime = false;
  2081. }
  2082. }
  2083. }
  2084. // Validate files that didn't get validated during previous checks.
  2085. if ( $type && ! $real_mime && extension_loaded( 'fileinfo' ) ) {
  2086. $finfo = finfo_open( FILEINFO_MIME_TYPE );
  2087. $real_mime = finfo_file( $finfo, $file );
  2088. finfo_close( $finfo );
  2089. /*
  2090. * If $real_mime doesn't match what we're expecting, we need to do some extra
  2091. * vetting of application mime types to make sure this type of file is allowed.
  2092. * Other mime types are assumed to be safe, but should be considered unverified.
  2093. */
  2094. if ( $real_mime && ( $real_mime !== $type ) && ( 0 === strpos( $real_mime, 'application' ) ) ) {
  2095. $allowed = get_allowed_mime_types();
  2096. if ( ! in_array( $real_mime, $allowed ) ) {
  2097. $type = $ext = false;
  2098. }
  2099. }
  2100. }
  2101. /**
  2102. * Filters the "real" file type of the given file.
  2103. *
  2104. * @since 3.0.0
  2105. *
  2106. * @param array $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
  2107. * 'proper_filename' keys.
  2108. * @param string $file Full path to the file.
  2109. * @param string $filename The name of the file (may differ from $file due to
  2110. * $file being in a tmp directory).
  2111. * @param array $mimes Key is the file extension with value as the mime type.
  2112. */
  2113. return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
  2114. }
  2115. /**
  2116. * Returns the real mime type of an image file.
  2117. *
  2118. * This depends on exif_imagetype() or getimagesize() to determine real mime types.
  2119. *
  2120. * @since 4.7.1
  2121. *
  2122. * @param string $file Full path to the file.
  2123. * @return string|false The actual mime type or false if the type cannot be determined.
  2124. */
  2125. function wp_get_image_mime( $file ) {
  2126. /*
  2127. * Use exif_imagetype() to check the mimetype if available or fall back to
  2128. * getimagesize() if exif isn't avaialbe. If either function throws an Exception
  2129. * we assume the file could not be validated.
  2130. */
  2131. try {
  2132. if ( is_callable( 'exif_imagetype' ) ) {
  2133. $imagetype = exif_imagetype( $file );
  2134. $mime = ( $imagetype ) ? image_type_to_mime_type( $imagetype ) : false;
  2135. } elseif ( function_exists( 'getimagesize' ) ) {
  2136. $imagesize = getimagesize( $file );
  2137. $mime = ( isset( $imagesize['mime'] ) ) ? $imagesize['mime'] : false;
  2138. } else {
  2139. $mime = false;
  2140. }
  2141. } catch ( Exception $e ) {
  2142. $mime = false;
  2143. }
  2144. return $mime;
  2145. }
  2146. /**
  2147. * Retrieve list of mime types and file extensions.
  2148. *
  2149. * @since 3.5.0
  2150. * @since 4.2.0 Support was added for GIMP (xcf) files.
  2151. *
  2152. * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  2153. */
  2154. function wp_get_mime_types() {
  2155. /**
  2156. * Filters the list of mime types and file extensions.
  2157. *
  2158. * This filter should be used to add, not remove, mime types. To remove
  2159. * mime types, use the {@see 'upload_mimes'} filter.
  2160. *
  2161. * @since 3.5.0
  2162. *
  2163. * @param array $wp_get_mime_types Mime types keyed by the file extension regex
  2164. * corresponding to those types.
  2165. */
  2166. return apply_filters( 'mime_types', array(
  2167. // Image formats.
  2168. 'jpg|jpeg|jpe' => 'image/jpeg',
  2169. 'gif' => 'image/gif',
  2170. 'png' => 'image/png',
  2171. 'bmp' => 'image/bmp',
  2172. 'tiff|tif' => 'image/tiff',
  2173. 'ico' => 'image/x-icon',
  2174. // Video formats.
  2175. 'asf|asx' => 'video/x-ms-asf',
  2176. 'wmv' => 'video/x-ms-wmv',
  2177. 'wmx' => 'video/x-ms-wmx',
  2178. 'wm' => 'video/x-ms-wm',
  2179. 'avi' => 'video/avi',
  2180. 'divx' => 'video/divx',
  2181. 'flv' => 'video/x-flv',
  2182. 'mov|qt' => 'video/quicktime',
  2183. 'mpeg|mpg|mpe' => 'video/mpeg',
  2184. 'mp4|m4v' => 'video/mp4',
  2185. 'ogv' => 'video/ogg',
  2186. 'webm' => 'video/webm',
  2187. 'mkv' => 'video/x-matroska',
  2188. '3gp|3gpp' => 'video/3gpp', // Can also be audio
  2189. '3g2|3gp2' => 'video/3gpp2', // Can also be audio
  2190. // Text formats.
  2191. 'txt|asc|c|cc|h|srt' => 'text/plain',
  2192. 'csv' => 'text/csv',
  2193. 'tsv' => 'text/tab-separated-values',
  2194. 'ics' => 'text/calendar',
  2195. 'rtx' => 'text/richtext',
  2196. 'css' => 'text/css',
  2197. 'htm|html' => 'text/html',
  2198. 'vtt' => 'text/vtt',
  2199. 'dfxp' => 'application/ttaf+xml',
  2200. // Audio formats.
  2201. 'mp3|m4a|m4b' => 'audio/mpeg',
  2202. 'aac' => 'audio/aac',
  2203. 'ra|ram' => 'audio/x-realaudio',
  2204. 'wav' => 'audio/wav',
  2205. 'ogg|oga' => 'audio/ogg',
  2206. 'flac' => 'audio/flac',
  2207. 'mid|midi' => 'audio/midi',
  2208. 'wma' => 'audio/x-ms-wma',
  2209. 'wax' => 'audio/x-ms-wax',
  2210. 'mka' => 'audio/x-matroska',
  2211. // Misc application formats.
  2212. 'rtf' => 'application/rtf',
  2213. 'js' => 'application/javascript',
  2214. 'pdf' => 'application/pdf',
  2215. 'swf' => 'application/x-shockwave-flash',
  2216. 'class' => 'application/java',
  2217. 'tar' => 'application/x-tar',
  2218. 'zip' => 'application/zip',
  2219. 'gz|gzip' => 'application/x-gzip',
  2220. 'rar' => 'application/rar',
  2221. '7z' => 'application/x-7z-compressed',
  2222. 'exe' => 'application/x-msdownload',
  2223. 'psd' => 'application/octet-stream',
  2224. 'xcf' => 'application/octet-stream',
  2225. // MS Office formats.
  2226. 'doc' => 'application/msword',
  2227. 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  2228. 'wri' => 'application/vnd.ms-write',
  2229. 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  2230. 'mdb' => 'application/vnd.ms-access',
  2231. 'mpp' => 'application/vnd.ms-project',
  2232. 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  2233. 'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  2234. 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  2235. 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  2236. 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  2237. 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  2238. 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2239. 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2240. 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  2241. 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2242. 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2243. 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  2244. 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2245. 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  2246. 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2247. 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  2248. 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  2249. 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2250. 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  2251. 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2252. 'oxps' => 'application/oxps',
  2253. 'xps' => 'application/vnd.ms-xpsdocument',
  2254. // OpenOffice formats.
  2255. 'odt' => 'application/vnd.oasis.opendocument.text',
  2256. 'odp' => 'application/vnd.oasis.opendocument.presentation',
  2257. 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2258. 'odg' => 'application/vnd.oasis.opendocument.graphics',
  2259. 'odc' => 'application/vnd.oasis.opendocument.chart',
  2260. 'odb' => 'application/vnd.oasis.opendocument.database',
  2261. 'odf' => 'application/vnd.oasis.opendocument.formula',
  2262. // WordPerfect formats.
  2263. 'wp|wpd' => 'application/wordperfect',
  2264. // iWork formats.
  2265. 'key' => 'application/vnd.apple.keynote',
  2266. 'numbers' => 'application/vnd.apple.numbers',
  2267. 'pages' => 'application/vnd.apple.pages',
  2268. ) );
  2269. }
  2270. /**
  2271. * Retrieves the list of common file extensions and their types.
  2272. *
  2273. * @since 4.6.0
  2274. *
  2275. * @return array Array of file extensions types keyed by the type of file.
  2276. */
  2277. function wp_get_ext_types() {
  2278. /**
  2279. * Filters file type based on the extension name.
  2280. *
  2281. * @since 2.5.0
  2282. *
  2283. * @see wp_ext2type()
  2284. *
  2285. * @param array $ext2type Multi-dimensional array with extensions for a default set
  2286. * of file types.
  2287. */
  2288. return apply_filters( 'ext2type', array(
  2289. 'image' => array( 'jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'tif', 'tiff', 'ico' ),
  2290. 'audio' => array( 'aac', 'ac3', 'aif', 'aiff', 'flac', 'm3a', 'm4a', 'm4b', 'mka', 'mp1', 'mp2', 'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  2291. 'video' => array( '3g2', '3gp', '3gpp', 'asf', 'avi', 'divx', 'dv', 'flv', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt', 'rm', 'vob', 'wmv' ),
  2292. 'document' => array( 'doc', 'docx', 'docm', 'dotm', 'odt', 'pages', 'pdf', 'xps', 'oxps', 'rtf', 'wp', 'wpd', 'psd', 'xcf' ),
  2293. 'spreadsheet' => array( 'numbers', 'ods', 'xls', 'xlsx', 'xlsm', 'xlsb' ),
  2294. 'interactive' => array( 'swf', 'key', 'ppt', 'pptx', 'pptm', 'pps', 'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  2295. 'text' => array( 'asc', 'csv', 'tsv', 'txt' ),
  2296. 'archive' => array( 'bz2', 'cab', 'dmg', 'gz', 'rar', 'sea', 'sit', 'sqx', 'tar', 'tgz', 'zip', '7z' ),
  2297. 'code' => array( 'css', 'htm', 'html', 'php', 'js' ),
  2298. ) );
  2299. }
  2300. /**
  2301. * Retrieve list of allowed mime types and file extensions.
  2302. *
  2303. * @since 2.8.6
  2304. *
  2305. * @param int|WP_User $user Optional. User to check. Defaults to current user.
  2306. * @return array Array of mime types keyed by the file extension regex corresponding
  2307. * to those types.
  2308. */
  2309. function get_allowed_mime_types( $user = null ) {
  2310. $t = wp_get_mime_types();
  2311. unset( $t['swf'], $t['exe'] );
  2312. if ( function_exists( 'current_user_can' ) )
  2313. $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  2314. if ( empty( $unfiltered ) ) {
  2315. unset( $t['htm|html'], $t['js'] );
  2316. }
  2317. /**
  2318. * Filters list of allowed mime types and file extensions.
  2319. *
  2320. * @since 2.0.0
  2321. *
  2322. * @param array $t Mime types keyed by the file extension regex corresponding to
  2323. * those types. 'swf' and 'exe' removed from full list. 'htm|html' also
  2324. * removed depending on '$user' capabilities.
  2325. * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  2326. */
  2327. return apply_filters( 'upload_mimes', $t, $user );
  2328. }
  2329. /**
  2330. * Display "Are You Sure" message to confirm the action being taken.
  2331. *
  2332. * If the action has the nonce explain message, then it will be displayed
  2333. * along with the "Are you sure?" message.
  2334. *
  2335. * @since 2.0.4
  2336. *
  2337. * @param string $action The nonce action.
  2338. */
  2339. function wp_nonce_ays( $action ) {
  2340. if ( 'log-out' == $action ) {
  2341. $html = sprintf(
  2342. /* translators: %s: site name */
  2343. __( 'You are attempting to log out of %s' ),
  2344. get_bloginfo( 'name' )
  2345. );
  2346. $html .= '</p><p>';
  2347. $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  2348. $html .= sprintf(
  2349. /* translators: %s: logout URL */
  2350. __( 'Do you really want to <a href="%s">log out</a>?' ),
  2351. wp_logout_url( $redirect_to )
  2352. );
  2353. } else {
  2354. $html = __( 'The link you followed has expired.' );
  2355. if ( wp_get_referer() ) {
  2356. $html .= '</p><p>';
  2357. $html .= sprintf( '<a href="%s">%s</a>',
  2358. esc_url( remove_query_arg( 'updated', wp_get_referer() ) ),
  2359. __( 'Please try again.' )
  2360. );
  2361. }
  2362. }
  2363. wp_die( $html, __( 'Something went wrong.' ), 403 );
  2364. }
  2365. /**
  2366. * Kill WordPress execution and display HTML message with error message.
  2367. *
  2368. * This function complements the `die()` PHP function. The difference is that
  2369. * HTML will be displayed to the user. It is recommended to use this function
  2370. * only when the execution should not continue any further. It is not recommended
  2371. * to call this function very often, and try to handle as many errors as possible
  2372. * silently or more gracefully.
  2373. *
  2374. * As a shorthand, the desired HTTP response code may be passed as an integer to
  2375. * the `$title` parameter (the default title would apply) or the `$args` parameter.
  2376. *
  2377. * @since 2.0.4
  2378. * @since 4.1.0 The `$title` and `$args` parameters were changed to optionally accept
  2379. * an integer to be used as the response code.
  2380. *
  2381. * @param string|WP_Error $message Optional. Error message. If this is a WP_Error object,
  2382. * and not an Ajax or XML-RPC request, the error's messages are used.
  2383. * Default empty.
  2384. * @param string|int $title Optional. Error title. If `$message` is a `WP_Error` object,
  2385. * error data with the key 'title' may be used to specify the title.
  2386. * If `$title` is an integer, then it is treated as the response
  2387. * code. Default empty.
  2388. * @param string|array|int $args {
  2389. * Optional. Arguments to control behavior. If `$args` is an integer, then it is treated
  2390. * as the response code. Default empty array.
  2391. *
  2392. * @type int $response The HTTP response code. Default 200 for Ajax requests, 500 otherwise.
  2393. * @type bool $back_link Whether to include a link to go back. Default false.
  2394. * @type string $text_direction The text direction. This is only useful internally, when WordPress
  2395. * is still loading and the site's locale is not set up yet. Accepts 'rtl'.
  2396. * Default is the value of is_rtl().
  2397. * }
  2398. */
  2399. function wp_die( $message = '', $title = '', $args = array() ) {
  2400. if ( is_int( $args ) ) {
  2401. $args = array( 'response' => $args );
  2402. } elseif ( is_int( $title ) ) {
  2403. $args = array( 'response' => $title );
  2404. $title = '';
  2405. }
  2406. if ( wp_doing_ajax() ) {
  2407. /**
  2408. * Filters the callback for killing WordPress execution for Ajax requests.
  2409. *
  2410. * @since 3.4.0
  2411. *
  2412. * @param callable $function Callback function name.
  2413. */
  2414. $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2415. } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2416. /**
  2417. * Filters the callback for killing WordPress execution for XML-RPC requests.
  2418. *
  2419. * @since 3.4.0
  2420. *
  2421. * @param callable $function Callback function name.
  2422. */
  2423. $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2424. } else {
  2425. /**
  2426. * Filters the callback for killing WordPress execution for all non-Ajax, non-XML-RPC requests.
  2427. *
  2428. * @since 3.0.0
  2429. *
  2430. * @param callable $function Callback function name.
  2431. */
  2432. $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  2433. }
  2434. call_user_func( $function, $message, $title, $args );
  2435. }
  2436. /**
  2437. * Kills WordPress execution and display HTML message with error message.
  2438. *
  2439. * This is the default handler for wp_die if you want a custom one for your
  2440. * site then you can overload using the {@see 'wp_die_handler'} filter in wp_die().
  2441. *
  2442. * @since 3.0.0
  2443. * @access private
  2444. *
  2445. * @param string|WP_Error $message Error message or WP_Error object.
  2446. * @param string $title Optional. Error title. Default empty.
  2447. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2448. */
  2449. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2450. $defaults = array( 'response' => 500 );
  2451. $r = wp_parse_args($args, $defaults);
  2452. $have_gettext = function_exists('__');
  2453. if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2454. if ( empty( $title ) ) {
  2455. $error_data = $message->get_error_data();
  2456. if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2457. $title = $error_data['title'];
  2458. }
  2459. $errors = $message->get_error_messages();
  2460. switch ( count( $errors ) ) {
  2461. case 0 :
  2462. $message = '';
  2463. break;
  2464. case 1 :
  2465. $message = "<p>{$errors[0]}</p>";
  2466. break;
  2467. default :
  2468. $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2469. break;
  2470. }
  2471. } elseif ( is_string( $message ) ) {
  2472. $message = "<p>$message</p>";
  2473. }
  2474. if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2475. $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2476. $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  2477. }
  2478. if ( ! did_action( 'admin_head' ) ) :
  2479. if ( !headers_sent() ) {
  2480. status_header( $r['response'] );
  2481. nocache_headers();
  2482. header( 'Content-Type: text/html; charset=utf-8' );
  2483. }
  2484. if ( empty($title) )
  2485. $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2486. $text_direction = 'ltr';
  2487. if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
  2488. $text_direction = 'rtl';
  2489. elseif ( function_exists( 'is_rtl' ) && is_rtl() )
  2490. $text_direction = 'rtl';
  2491. ?>
  2492. <!DOCTYPE html>
  2493. <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'"; ?>>
  2494. <head>
  2495. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2496. <meta name="viewport" content="width=device-width">
  2497. <?php
  2498. if ( function_exists( 'wp_no_robots' ) ) {
  2499. wp_no_robots();
  2500. }
  2501. ?>
  2502. <title><?php echo $title ?></title>
  2503. <style type="text/css">
  2504. html {
  2505. background: #f1f1f1;
  2506. }
  2507. body {
  2508. background: #fff;
  2509. color: #444;
  2510. font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
  2511. margin: 2em auto;
  2512. padding: 1em 2em;
  2513. max-width: 700px;
  2514. -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2515. box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2516. }
  2517. h1 {
  2518. border-bottom: 1px solid #dadada;
  2519. clear: both;
  2520. color: #666;
  2521. font-size: 24px;
  2522. margin: 30px 0 0 0;
  2523. padding: 0;
  2524. padding-bottom: 7px;
  2525. }
  2526. #error-page {
  2527. margin-top: 50px;
  2528. }
  2529. #error-page p {
  2530. font-size: 14px;
  2531. line-height: 1.5;
  2532. margin: 25px 0 20px;
  2533. }
  2534. #error-page code {
  2535. font-family: Consolas, Monaco, monospace;
  2536. }
  2537. ul li {
  2538. margin-bottom: 10px;
  2539. font-size: 14px ;
  2540. }
  2541. a {
  2542. color: #0073aa;
  2543. }
  2544. a:hover,
  2545. a:active {
  2546. color: #00a0d2;
  2547. }
  2548. a:focus {
  2549. color: #124964;
  2550. -webkit-box-shadow:
  2551. 0 0 0 1px #5b9dd9,
  2552. 0 0 2px 1px rgba(30, 140, 190, .8);
  2553. box-shadow:
  2554. 0 0 0 1px #5b9dd9,
  2555. 0 0 2px 1px rgba(30, 140, 190, .8);
  2556. outline: none;
  2557. }
  2558. .button {
  2559. background: #f7f7f7;
  2560. border: 1px solid #ccc;
  2561. color: #555;
  2562. display: inline-block;
  2563. text-decoration: none;
  2564. font-size: 13px;
  2565. line-height: 26px;
  2566. height: 28px;
  2567. margin: 0;
  2568. padding: 0 10px 1px;
  2569. cursor: pointer;
  2570. -webkit-border-radius: 3px;
  2571. -webkit-appearance: none;
  2572. border-radius: 3px;
  2573. white-space: nowrap;
  2574. -webkit-box-sizing: border-box;
  2575. -moz-box-sizing: border-box;
  2576. box-sizing: border-box;
  2577. -webkit-box-shadow: 0 1px 0 #ccc;
  2578. box-shadow: 0 1px 0 #ccc;
  2579. vertical-align: top;
  2580. }
  2581. .button.button-large {
  2582. height: 30px;
  2583. line-height: 28px;
  2584. padding: 0 12px 2px;
  2585. }
  2586. .button:hover,
  2587. .button:focus {
  2588. background: #fafafa;
  2589. border-color: #999;
  2590. color: #23282d;
  2591. }
  2592. .button:focus {
  2593. border-color: #5b9dd9;
  2594. -webkit-box-shadow: 0 0 3px rgba( 0, 115, 170, .8 );
  2595. box-shadow: 0 0 3px rgba( 0, 115, 170, .8 );
  2596. outline: none;
  2597. }
  2598. .button:active {
  2599. background: #eee;
  2600. border-color: #999;
  2601. -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2602. box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2603. -webkit-transform: translateY(1px);
  2604. -ms-transform: translateY(1px);
  2605. transform: translateY(1px);
  2606. }
  2607. <?php
  2608. if ( 'rtl' == $text_direction ) {
  2609. echo 'body { font-family: Tahoma, Arial; }';
  2610. }
  2611. ?>
  2612. </style>
  2613. </head>
  2614. <body id="error-page">
  2615. <?php endif; // ! did_action( 'admin_head' ) ?>
  2616. <?php echo $message; ?>
  2617. </body>
  2618. </html>
  2619. <?php
  2620. die();
  2621. }
  2622. /**
  2623. * Kill WordPress execution and display XML message with error message.
  2624. *
  2625. * This is the handler for wp_die when processing XMLRPC requests.
  2626. *
  2627. * @since 3.2.0
  2628. * @access private
  2629. *
  2630. * @global wp_xmlrpc_server $wp_xmlrpc_server
  2631. *
  2632. * @param string $message Error message.
  2633. * @param string $title Optional. Error title. Default empty.
  2634. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2635. */
  2636. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  2637. global $wp_xmlrpc_server;
  2638. $defaults = array( 'response' => 500 );
  2639. $r = wp_parse_args($args, $defaults);
  2640. if ( $wp_xmlrpc_server ) {
  2641. $error = new IXR_Error( $r['response'] , $message);
  2642. $wp_xmlrpc_server->output( $error->getXml() );
  2643. }
  2644. die();
  2645. }
  2646. /**
  2647. * Kill WordPress ajax execution.
  2648. *
  2649. * This is the handler for wp_die when processing Ajax requests.
  2650. *
  2651. * @since 3.4.0
  2652. * @access private
  2653. *
  2654. * @param string $message Error message.
  2655. * @param string $title Optional. Error title (unused). Default empty.
  2656. * @param string|array $args Optional. Arguments to control behavior. Default empty array.
  2657. */
  2658. function _ajax_wp_die_handler( $message, $title = '', $args = array() ) {
  2659. $defaults = array(
  2660. 'response' => 200,
  2661. );
  2662. $r = wp_parse_args( $args, $defaults );
  2663. if ( ! headers_sent() && null !== $r['response'] ) {
  2664. status_header( $r['response'] );
  2665. }
  2666. if ( is_scalar( $message ) )
  2667. die( (string) $message );
  2668. die( '0' );
  2669. }
  2670. /**
  2671. * Kill WordPress execution.
  2672. *
  2673. * This is the handler for wp_die when processing APP requests.
  2674. *
  2675. * @since 3.4.0
  2676. * @access private
  2677. *
  2678. * @param string $message Optional. Response to print. Default empty.
  2679. */
  2680. function _scalar_wp_die_handler( $message = '' ) {
  2681. if ( is_scalar( $message ) )
  2682. die( (string) $message );
  2683. die();
  2684. }
  2685. /**
  2686. * Encode a variable into JSON, with some sanity checks.
  2687. *
  2688. * @since 4.1.0
  2689. *
  2690. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  2691. * @param int $options Optional. Options to be passed to json_encode(). Default 0.
  2692. * @param int $depth Optional. Maximum depth to walk through $data. Must be
  2693. * greater than 0. Default 512.
  2694. * @return string|false The JSON encoded string, or false if it cannot be encoded.
  2695. */
  2696. function wp_json_encode( $data, $options = 0, $depth = 512 ) {
  2697. /*
  2698. * json_encode() has had extra params added over the years.
  2699. * $options was added in 5.3, and $depth in 5.5.
  2700. * We need to make sure we call it with the correct arguments.
  2701. */
  2702. if ( version_compare( PHP_VERSION, '5.5', '>=' ) ) {
  2703. $args = array( $data, $options, $depth );
  2704. } elseif ( version_compare( PHP_VERSION, '5.3', '>=' ) ) {
  2705. $args = array( $data, $options );
  2706. } else {
  2707. $args = array( $data );
  2708. }
  2709. // Prepare the data for JSON serialization.
  2710. $args[0] = _wp_json_prepare_data( $data );
  2711. $json = @call_user_func_array( 'json_encode', $args );
  2712. // If json_encode() was successful, no need to do more sanity checking.
  2713. // ... unless we're in an old version of PHP, and json_encode() returned
  2714. // a string containing 'null'. Then we need to do more sanity checking.
  2715. if ( false !== $json && ( version_compare( PHP_VERSION, '5.5', '>=' ) || false === strpos( $json, 'null' ) ) ) {
  2716. return $json;
  2717. }
  2718. try {
  2719. $args[0] = _wp_json_sanity_check( $data, $depth );
  2720. } catch ( Exception $e ) {
  2721. return false;
  2722. }
  2723. return call_user_func_array( 'json_encode', $args );
  2724. }
  2725. /**
  2726. * Perform sanity checks on data that shall be encoded to JSON.
  2727. *
  2728. * @ignore
  2729. * @since 4.1.0
  2730. * @access private
  2731. *
  2732. * @see wp_json_encode()
  2733. *
  2734. * @param mixed $data Variable (usually an array or object) to encode as JSON.
  2735. * @param int $depth Maximum depth to walk through $data. Must be greater than 0.
  2736. * @return mixed The sanitized data that shall be encoded to JSON.
  2737. */
  2738. function _wp_json_sanity_check( $data, $depth ) {
  2739. if ( $depth < 0 ) {
  2740. throw new Exception( 'Reached depth limit' );
  2741. }
  2742. if ( is_array( $data ) ) {
  2743. $output = array();
  2744. foreach ( $data as $id => $el ) {
  2745. // Don't forget to sanitize the ID!
  2746. if ( is_string( $id ) ) {
  2747. $clean_id = _wp_json_convert_string( $id );
  2748. } else {
  2749. $clean_id = $id;
  2750. }
  2751. // Check the element type, so that we're only recursing if we really have to.
  2752. if ( is_array( $el ) || is_object( $el ) ) {
  2753. $output[ $clean_id ] = _wp_json_sanity_check( $el, $depth - 1 );
  2754. } elseif ( is_string( $el ) ) {
  2755. $output[ $clean_id ] = _wp_json_convert_string( $el );
  2756. } else {
  2757. $output[ $clean_id ] = $el;
  2758. }
  2759. }
  2760. } elseif ( is_object( $data ) ) {
  2761. $output = new stdClass;
  2762. foreach ( $data as $id => $el ) {
  2763. if ( is_string( $id ) ) {
  2764. $clean_id = _wp_json_convert_string( $id );
  2765. } else {
  2766. $clean_id = $id;
  2767. }
  2768. if ( is_array( $el ) || is_object( $el ) ) {
  2769. $output->$clean_id = _wp_json_sanity_check( $el, $depth - 1 );
  2770. } elseif ( is_string( $el ) ) {
  2771. $output->$clean_id = _wp_json_convert_string( $el );
  2772. } else {
  2773. $output->$clean_id = $el;
  2774. }
  2775. }
  2776. } elseif ( is_string( $data ) ) {
  2777. return _wp_json_convert_string( $data );
  2778. } else {
  2779. return $data;
  2780. }
  2781. return $output;
  2782. }
  2783. /**
  2784. * Convert a string to UTF-8, so that it can be safely encoded to JSON.
  2785. *
  2786. * @ignore
  2787. * @since 4.1.0
  2788. * @access private
  2789. *
  2790. * @see _wp_json_sanity_check()
  2791. *
  2792. * @staticvar bool $use_mb
  2793. *
  2794. * @param string $string The string which is to be converted.
  2795. * @return string The checked string.
  2796. */
  2797. function _wp_json_convert_string( $string ) {
  2798. static $use_mb = null;
  2799. if ( is_null( $use_mb ) ) {
  2800. $use_mb = function_exists( 'mb_convert_encoding' );
  2801. }
  2802. if ( $use_mb ) {
  2803. $encoding = mb_detect_encoding( $string, mb_detect_order(), true );
  2804. if ( $encoding ) {
  2805. return mb_convert_encoding( $string, 'UTF-8', $encoding );
  2806. } else {
  2807. return mb_convert_encoding( $string, 'UTF-8', 'UTF-8' );
  2808. }
  2809. } else {
  2810. return wp_check_invalid_utf8( $string, true );
  2811. }
  2812. }
  2813. /**
  2814. * Prepares response data to be serialized to JSON.
  2815. *
  2816. * This supports the JsonSerializable interface for PHP 5.2-5.3 as well.
  2817. *
  2818. * @ignore
  2819. * @since 4.4.0
  2820. * @access private
  2821. *
  2822. * @param mixed $data Native representation.
  2823. * @return bool|int|float|null|string|array Data ready for `json_encode()`.
  2824. */
  2825. function _wp_json_prepare_data( $data ) {
  2826. if ( ! defined( 'WP_JSON_SERIALIZE_COMPATIBLE' ) || WP_JSON_SERIALIZE_COMPATIBLE === false ) {
  2827. return $data;
  2828. }
  2829. switch ( gettype( $data ) ) {
  2830. case 'boolean':
  2831. case 'integer':
  2832. case 'double':
  2833. case 'string':
  2834. case 'NULL':
  2835. // These values can be passed through.
  2836. return $data;
  2837. case 'array':
  2838. // Arrays must be mapped in case they also return objects.
  2839. return array_map( '_wp_json_prepare_data', $data );
  2840. case 'object':
  2841. // If this is an incomplete object (__PHP_Incomplete_Class), bail.
  2842. if ( ! is_object( $data ) ) {
  2843. return null;
  2844. }
  2845. if ( $data instanceof JsonSerializable ) {
  2846. $data = $data->jsonSerialize();
  2847. } else {
  2848. $data = get_object_vars( $data );
  2849. }
  2850. // Now, pass the array (or whatever was returned from jsonSerialize through).
  2851. return _wp_json_prepare_data( $data );
  2852. default:
  2853. return null;
  2854. }
  2855. }
  2856. /**
  2857. * Send a JSON response back to an Ajax request.
  2858. *
  2859. * @since 3.5.0
  2860. * @since 4.7.0 The `$status_code` parameter was added.
  2861. *
  2862. * @param mixed $response Variable (usually an array or object) to encode as JSON,
  2863. * then print and die.
  2864. * @param int $status_code The HTTP status code to output.
  2865. */
  2866. function wp_send_json( $response, $status_code = null ) {
  2867. @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  2868. if ( null !== $status_code ) {
  2869. status_header( $status_code );
  2870. }
  2871. echo wp_json_encode( $response );
  2872. if ( wp_doing_ajax() ) {
  2873. wp_die( '', '', array(
  2874. 'response' => null,
  2875. ) );
  2876. } else {
  2877. die;
  2878. }
  2879. }
  2880. /**
  2881. * Send a JSON response back to an Ajax request, indicating success.
  2882. *
  2883. * @since 3.5.0
  2884. * @since 4.7.0 The `$status_code` parameter was added.
  2885. *
  2886. * @param mixed $data Data to encode as JSON, then print and die.
  2887. * @param int $status_code The HTTP status code to output.
  2888. */
  2889. function wp_send_json_success( $data = null, $status_code = null ) {
  2890. $response = array( 'success' => true );
  2891. if ( isset( $data ) )
  2892. $response['data'] = $data;
  2893. wp_send_json( $response, $status_code );
  2894. }
  2895. /**
  2896. * Send a JSON response back to an Ajax request, indicating failure.
  2897. *
  2898. * If the `$data` parameter is a WP_Error object, the errors
  2899. * within the object are processed and output as an array of error
  2900. * codes and corresponding messages. All other types are output
  2901. * without further processing.
  2902. *
  2903. * @since 3.5.0
  2904. * @since 4.1.0 The `$data` parameter is now processed if a WP_Error object is passed in.
  2905. * @since 4.7.0 The `$status_code` parameter was added.
  2906. *
  2907. * @param mixed $data Data to encode as JSON, then print and die.
  2908. * @param int $status_code The HTTP status code to output.
  2909. */
  2910. function wp_send_json_error( $data = null, $status_code = null ) {
  2911. $response = array( 'success' => false );
  2912. if ( isset( $data ) ) {
  2913. if ( is_wp_error( $data ) ) {
  2914. $result = array();
  2915. foreach ( $data->errors as $code => $messages ) {
  2916. foreach ( $messages as $message ) {
  2917. $result[] = array( 'code' => $code, 'message' => $message );
  2918. }
  2919. }
  2920. $response['data'] = $result;
  2921. } else {
  2922. $response['data'] = $data;
  2923. }
  2924. }
  2925. wp_send_json( $response, $status_code );
  2926. }
  2927. /**
  2928. * Checks that a JSONP callback is a valid JavaScript callback.
  2929. *
  2930. * Only allows alphanumeric characters and the dot character in callback
  2931. * function names. This helps to mitigate XSS attacks caused by directly
  2932. * outputting user input.
  2933. *
  2934. * @since 4.6.0
  2935. *
  2936. * @param string $callback Supplied JSONP callback function.
  2937. * @return bool True if valid callback, otherwise false.
  2938. */
  2939. function wp_check_jsonp_callback( $callback ) {
  2940. if ( ! is_string( $callback ) ) {
  2941. return false;
  2942. }
  2943. preg_replace( '/[^\w\.]/', '', $callback, -1, $illegal_char_count );
  2944. return 0 === $illegal_char_count;
  2945. }
  2946. /**
  2947. * Retrieve the WordPress home page URL.
  2948. *
  2949. * If the constant named 'WP_HOME' exists, then it will be used and returned
  2950. * by the function. This can be used to counter the redirection on your local
  2951. * development environment.
  2952. *
  2953. * @since 2.2.0
  2954. * @access private
  2955. *
  2956. * @see WP_HOME
  2957. *
  2958. * @param string $url URL for the home location.
  2959. * @return string Homepage location.
  2960. */
  2961. function _config_wp_home( $url = '' ) {
  2962. if ( defined( 'WP_HOME' ) )
  2963. return untrailingslashit( WP_HOME );
  2964. return $url;
  2965. }
  2966. /**
  2967. * Retrieve the WordPress site URL.
  2968. *
  2969. * If the constant named 'WP_SITEURL' is defined, then the value in that
  2970. * constant will always be returned. This can be used for debugging a site
  2971. * on your localhost while not having to change the database to your URL.
  2972. *
  2973. * @since 2.2.0
  2974. * @access private
  2975. *
  2976. * @see WP_SITEURL
  2977. *
  2978. * @param string $url URL to set the WordPress site location.
  2979. * @return string The WordPress Site URL.
  2980. */
  2981. function _config_wp_siteurl( $url = '' ) {
  2982. if ( defined( 'WP_SITEURL' ) )
  2983. return untrailingslashit( WP_SITEURL );
  2984. return $url;
  2985. }
  2986. /**
  2987. * Delete the fresh site option.
  2988. *
  2989. * @since 4.7.0
  2990. * @access private
  2991. */
  2992. function _delete_option_fresh_site() {
  2993. update_option( 'fresh_site', '0' );
  2994. }
  2995. /**
  2996. * Set the localized direction for MCE plugin.
  2997. *
  2998. * Will only set the direction to 'rtl', if the WordPress locale has
  2999. * the text direction set to 'rtl'.
  3000. *
  3001. * Fills in the 'directionality' setting, enables the 'directionality'
  3002. * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  3003. * 'theme_advanced_buttons1' array keys. These keys are then returned
  3004. * in the $mce_init (TinyMCE settings) array.
  3005. *
  3006. * @since 2.1.0
  3007. * @access private
  3008. *
  3009. * @param array $mce_init MCE settings array.
  3010. * @return array Direction set for 'rtl', if needed by locale.
  3011. */
  3012. function _mce_set_direction( $mce_init ) {
  3013. if ( is_rtl() ) {
  3014. $mce_init['directionality'] = 'rtl';
  3015. $mce_init['rtl_ui'] = true;
  3016. if ( ! empty( $mce_init['plugins'] ) && strpos( $mce_init['plugins'], 'directionality' ) === false ) {
  3017. $mce_init['plugins'] .= ',directionality';
  3018. }
  3019. if ( ! empty( $mce_init['toolbar1'] ) && ! preg_match( '/\bltr\b/', $mce_init['toolbar1'] ) ) {
  3020. $mce_init['toolbar1'] .= ',ltr';
  3021. }
  3022. }
  3023. return $mce_init;
  3024. }
  3025. /**
  3026. * Convert smiley code to the icon graphic file equivalent.
  3027. *
  3028. * You can turn off smilies, by going to the write setting screen and unchecking
  3029. * the box, or by setting 'use_smilies' option to false or removing the option.
  3030. *
  3031. * Plugins may override the default smiley list by setting the $wpsmiliestrans
  3032. * to an array, with the key the code the blogger types in and the value the
  3033. * image file.
  3034. *
  3035. * The $wp_smiliessearch global is for the regular expression and is set each
  3036. * time the function is called.
  3037. *
  3038. * The full list of smilies can be found in the function and won't be listed in
  3039. * the description. Probably should create a Codex page for it, so that it is
  3040. * available.
  3041. *
  3042. * @global array $wpsmiliestrans
  3043. * @global array $wp_smiliessearch
  3044. *
  3045. * @since 2.2.0
  3046. */
  3047. function smilies_init() {
  3048. global $wpsmiliestrans, $wp_smiliessearch;
  3049. // don't bother setting up smilies if they are disabled
  3050. if ( !get_option( 'use_smilies' ) )
  3051. return;
  3052. if ( !isset( $wpsmiliestrans ) ) {
  3053. $wpsmiliestrans = array(
  3054. ':mrgreen:' => 'mrgreen.png',
  3055. ':neutral:' => "\xf0\x9f\x98\x90",
  3056. ':twisted:' => "\xf0\x9f\x98\x88",
  3057. ':arrow:' => "\xe2\x9e\xa1",
  3058. ':shock:' => "\xf0\x9f\x98\xaf",
  3059. ':smile:' => "\xf0\x9f\x99\x82",
  3060. ':???:' => "\xf0\x9f\x98\x95",
  3061. ':cool:' => "\xf0\x9f\x98\x8e",
  3062. ':evil:' => "\xf0\x9f\x91\xbf",
  3063. ':grin:' => "\xf0\x9f\x98\x80",
  3064. ':idea:' => "\xf0\x9f\x92\xa1",
  3065. ':oops:' => "\xf0\x9f\x98\xb3",
  3066. ':razz:' => "\xf0\x9f\x98\x9b",
  3067. ':roll:' => "\xf0\x9f\x99\x84",
  3068. ':wink:' => "\xf0\x9f\x98\x89",
  3069. ':cry:' => "\xf0\x9f\x98\xa5",
  3070. ':eek:' => "\xf0\x9f\x98\xae",
  3071. ':lol:' => "\xf0\x9f\x98\x86",
  3072. ':mad:' => "\xf0\x9f\x98\xa1",
  3073. ':sad:' => "\xf0\x9f\x99\x81",
  3074. '8-)' => "\xf0\x9f\x98\x8e",
  3075. '8-O' => "\xf0\x9f\x98\xaf",
  3076. ':-(' => "\xf0\x9f\x99\x81",
  3077. ':-)' => "\xf0\x9f\x99\x82",
  3078. ':-?' => "\xf0\x9f\x98\x95",
  3079. ':-D' => "\xf0\x9f\x98\x80",
  3080. ':-P' => "\xf0\x9f\x98\x9b",
  3081. ':-o' => "\xf0\x9f\x98\xae",
  3082. ':-x' => "\xf0\x9f\x98\xa1",
  3083. ':-|' => "\xf0\x9f\x98\x90",
  3084. ';-)' => "\xf0\x9f\x98\x89",
  3085. // This one transformation breaks regular text with frequency.
  3086. // '8)' => "\xf0\x9f\x98\x8e",
  3087. '8O' => "\xf0\x9f\x98\xaf",
  3088. ':(' => "\xf0\x9f\x99\x81",
  3089. ':)' => "\xf0\x9f\x99\x82",
  3090. ':?' => "\xf0\x9f\x98\x95",
  3091. ':D' => "\xf0\x9f\x98\x80",
  3092. ':P' => "\xf0\x9f\x98\x9b",
  3093. ':o' => "\xf0\x9f\x98\xae",
  3094. ':x' => "\xf0\x9f\x98\xa1",
  3095. ':|' => "\xf0\x9f\x98\x90",
  3096. ';)' => "\xf0\x9f\x98\x89",
  3097. ':!:' => "\xe2\x9d\x97",
  3098. ':?:' => "\xe2\x9d\x93",
  3099. );
  3100. }
  3101. /**
  3102. * Filters all the smilies.
  3103. *
  3104. * This filter must be added before `smilies_init` is run, as
  3105. * it is normally only run once to setup the smilies regex.
  3106. *
  3107. * @since 4.7.0
  3108. *
  3109. * @param array $wpsmiliestrans List of the smilies.
  3110. */
  3111. $wpsmiliestrans = apply_filters('smilies', $wpsmiliestrans);
  3112. if (count($wpsmiliestrans) == 0) {
  3113. return;
  3114. }
  3115. /*
  3116. * NOTE: we sort the smilies in reverse key order. This is to make sure
  3117. * we match the longest possible smilie (:???: vs :?) as the regular
  3118. * expression used below is first-match
  3119. */
  3120. krsort($wpsmiliestrans);
  3121. $spaces = wp_spaces_regexp();
  3122. // Begin first "subpattern"
  3123. $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  3124. $subchar = '';
  3125. foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  3126. $firstchar = substr($smiley, 0, 1);
  3127. $rest = substr($smiley, 1);
  3128. // new subpattern?
  3129. if ($firstchar != $subchar) {
  3130. if ($subchar != '') {
  3131. $wp_smiliessearch .= ')(?=' . $spaces . '|$)'; // End previous "subpattern"
  3132. $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
  3133. }
  3134. $subchar = $firstchar;
  3135. $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  3136. } else {
  3137. $wp_smiliessearch .= '|';
  3138. }
  3139. $wp_smiliessearch .= preg_quote($rest, '/');
  3140. }
  3141. $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  3142. }
  3143. /**
  3144. * Merge user defined arguments into defaults array.
  3145. *
  3146. * This function is used throughout WordPress to allow for both string or array
  3147. * to be merged into another array.
  3148. *
  3149. * @since 2.2.0
  3150. * @since 2.3.0 `$args` can now also be an object.
  3151. *
  3152. * @param string|array|object $args Value to merge with $defaults.
  3153. * @param array $defaults Optional. Array that serves as the defaults. Default empty.
  3154. * @return array Merged user defined values with defaults.
  3155. */
  3156. function wp_parse_args( $args, $defaults = '' ) {
  3157. if ( is_object( $args ) )
  3158. $r = get_object_vars( $args );
  3159. elseif ( is_array( $args ) )
  3160. $r =& $args;
  3161. else
  3162. wp_parse_str( $args, $r );
  3163. if ( is_array( $defaults ) )
  3164. return array_merge( $defaults, $r );
  3165. return $r;
  3166. }
  3167. /**
  3168. * Clean up an array, comma- or space-separated list of IDs.
  3169. *
  3170. * @since 3.0.0
  3171. *
  3172. * @param array|string $list List of ids.
  3173. * @return array Sanitized array of IDs.
  3174. */
  3175. function wp_parse_id_list( $list ) {
  3176. if ( !is_array($list) )
  3177. $list = preg_split('/[\s,]+/', $list);
  3178. return array_unique(array_map('absint', $list));
  3179. }
  3180. /**
  3181. * Clean up an array, comma- or space-separated list of slugs.
  3182. *
  3183. * @since 4.7.0
  3184. *
  3185. * @param array|string $list List of slugs.
  3186. * @return array Sanitized array of slugs.
  3187. */
  3188. function wp_parse_slug_list( $list ) {
  3189. if ( ! is_array( $list ) ) {
  3190. $list = preg_split( '/[\s,]+/', $list );
  3191. }
  3192. foreach ( $list as $key => $value ) {
  3193. $list[ $key ] = sanitize_title( $value );
  3194. }
  3195. return array_unique( $list );
  3196. }
  3197. /**
  3198. * Extract a slice of an array, given a list of keys.
  3199. *
  3200. * @since 3.1.0
  3201. *
  3202. * @param array $array The original array.
  3203. * @param array $keys The list of keys.
  3204. * @return array The array slice.
  3205. */
  3206. function wp_array_slice_assoc( $array, $keys ) {
  3207. $slice = array();
  3208. foreach ( $keys as $key )
  3209. if ( isset( $array[ $key ] ) )
  3210. $slice[ $key ] = $array[ $key ];
  3211. return $slice;
  3212. }
  3213. /**
  3214. * Determines if the variable is a numeric-indexed array.
  3215. *
  3216. * @since 4.4.0
  3217. *
  3218. * @param mixed $data Variable to check.
  3219. * @return bool Whether the variable is a list.
  3220. */
  3221. function wp_is_numeric_array( $data ) {
  3222. if ( ! is_array( $data ) ) {
  3223. return false;
  3224. }
  3225. $keys = array_keys( $data );
  3226. $string_keys = array_filter( $keys, 'is_string' );
  3227. return count( $string_keys ) === 0;
  3228. }
  3229. /**
  3230. * Filters a list of objects, based on a set of key => value arguments.
  3231. *
  3232. * @since 3.0.0
  3233. * @since 4.7.0 Uses WP_List_Util class.
  3234. *
  3235. * @param array $list An array of objects to filter
  3236. * @param array $args Optional. An array of key => value arguments to match
  3237. * against each object. Default empty array.
  3238. * @param string $operator Optional. The logical operation to perform. 'or' means
  3239. * only one element from the array needs to match; 'and'
  3240. * means all elements must match; 'not' means no elements may
  3241. * match. Default 'and'.
  3242. * @param bool|string $field A field from the object to place instead of the entire object.
  3243. * Default false.
  3244. * @return array A list of objects or object fields.
  3245. */
  3246. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  3247. if ( ! is_array( $list ) ) {
  3248. return array();
  3249. }
  3250. $util = new WP_List_Util( $list );
  3251. $util->filter( $args, $operator );
  3252. if ( $field ) {
  3253. $util->pluck( $field );
  3254. }
  3255. return $util->get_output();
  3256. }
  3257. /**
  3258. * Filters a list of objects, based on a set of key => value arguments.
  3259. *
  3260. * @since 3.1.0
  3261. * @since 4.7.0 Uses WP_List_Util class.
  3262. *
  3263. * @param array $list An array of objects to filter.
  3264. * @param array $args Optional. An array of key => value arguments to match
  3265. * against each object. Default empty array.
  3266. * @param string $operator Optional. The logical operation to perform. 'AND' means
  3267. * all elements from the array must match. 'OR' means only
  3268. * one element needs to match. 'NOT' means no elements may
  3269. * match. Default 'AND'.
  3270. * @return array Array of found values.
  3271. */
  3272. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  3273. if ( ! is_array( $list ) ) {
  3274. return array();
  3275. }
  3276. $util = new WP_List_Util( $list );
  3277. return $util->filter( $args, $operator );
  3278. }
  3279. /**
  3280. * Pluck a certain field out of each object in a list.
  3281. *
  3282. * This has the same functionality and prototype of
  3283. * array_column() (PHP 5.5) but also supports objects.
  3284. *
  3285. * @since 3.1.0
  3286. * @since 4.0.0 $index_key parameter added.
  3287. * @since 4.7.0 Uses WP_List_Util class.
  3288. *
  3289. * @param array $list List of objects or arrays
  3290. * @param int|string $field Field from the object to place instead of the entire object
  3291. * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  3292. * Default null.
  3293. * @return array Array of found values. If `$index_key` is set, an array of found values with keys
  3294. * corresponding to `$index_key`. If `$index_key` is null, array keys from the original
  3295. * `$list` will be preserved in the results.
  3296. */
  3297. function wp_list_pluck( $list, $field, $index_key = null ) {
  3298. $util = new WP_List_Util( $list );
  3299. return $util->pluck( $field, $index_key );
  3300. }
  3301. /**
  3302. * Sorts a list of objects, based on one or more orderby arguments.
  3303. *
  3304. * @since 4.7.0
  3305. *
  3306. * @param array $list An array of objects to filter.
  3307. * @param string|array $orderby Optional. Either the field name to order by or an array
  3308. * of multiple orderby fields as $orderby => $order.
  3309. * @param string $order Optional. Either 'ASC' or 'DESC'. Only used if $orderby
  3310. * is a string.
  3311. * @param bool $preserve_keys Optional. Whether to preserve keys. Default false.
  3312. * @return array The sorted array.
  3313. */
  3314. function wp_list_sort( $list, $orderby = array(), $order = 'ASC', $preserve_keys = false ) {
  3315. if ( ! is_array( $list ) ) {
  3316. return array();
  3317. }
  3318. $util = new WP_List_Util( $list );
  3319. return $util->sort( $orderby, $order, $preserve_keys );
  3320. }
  3321. /**
  3322. * Determines if Widgets library should be loaded.
  3323. *
  3324. * Checks to make sure that the widgets library hasn't already been loaded.
  3325. * If it hasn't, then it will load the widgets library and run an action hook.
  3326. *
  3327. * @since 2.2.0
  3328. */
  3329. function wp_maybe_load_widgets() {
  3330. /**
  3331. * Filters whether to load the Widgets library.
  3332. *
  3333. * Passing a falsey value to the filter will effectively short-circuit
  3334. * the Widgets library from loading.
  3335. *
  3336. * @since 2.8.0
  3337. *
  3338. * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  3339. * Default true.
  3340. */
  3341. if ( ! apply_filters( 'load_default_widgets', true ) ) {
  3342. return;
  3343. }
  3344. require_once( ABSPATH . WPINC . '/default-widgets.php' );
  3345. add_action( '_admin_menu', 'wp_widgets_add_menu' );
  3346. }
  3347. /**
  3348. * Append the Widgets menu to the themes main menu.
  3349. *
  3350. * @since 2.2.0
  3351. *
  3352. * @global array $submenu
  3353. */
  3354. function wp_widgets_add_menu() {
  3355. global $submenu;
  3356. if ( ! current_theme_supports( 'widgets' ) )
  3357. return;
  3358. $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  3359. ksort( $submenu['themes.php'], SORT_NUMERIC );
  3360. }
  3361. /**
  3362. * Flush all output buffers for PHP 5.2.
  3363. *
  3364. * Make sure all output buffers are flushed before our singletons are destroyed.
  3365. *
  3366. * @since 2.2.0
  3367. */
  3368. function wp_ob_end_flush_all() {
  3369. $levels = ob_get_level();
  3370. for ($i=0; $i<$levels; $i++)
  3371. ob_end_flush();
  3372. }
  3373. /**
  3374. * Load custom DB error or display WordPress DB error.
  3375. *
  3376. * If a file exists in the wp-content directory named db-error.php, then it will
  3377. * be loaded instead of displaying the WordPress DB error. If it is not found,
  3378. * then the WordPress DB error will be displayed instead.
  3379. *
  3380. * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  3381. * search engines from caching the message. Custom DB messages should do the
  3382. * same.
  3383. *
  3384. * This function was backported to WordPress 2.3.2, but originally was added
  3385. * in WordPress 2.5.0.
  3386. *
  3387. * @since 2.3.2
  3388. *
  3389. * @global wpdb $wpdb WordPress database abstraction object.
  3390. */
  3391. function dead_db() {
  3392. global $wpdb;
  3393. wp_load_translations_early();
  3394. // Load custom DB error template, if present.
  3395. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  3396. require_once( WP_CONTENT_DIR . '/db-error.php' );
  3397. die();
  3398. }
  3399. // If installing or in the admin, provide the verbose message.
  3400. if ( wp_installing() || defined( 'WP_ADMIN' ) )
  3401. wp_die($wpdb->error);
  3402. // Otherwise, be terse.
  3403. status_header( 500 );
  3404. nocache_headers();
  3405. header( 'Content-Type: text/html; charset=utf-8' );
  3406. ?>
  3407. <!DOCTYPE html>
  3408. <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
  3409. <head>
  3410. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  3411. <title><?php _e( 'Database Error' ); ?></title>
  3412. </head>
  3413. <body>
  3414. <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
  3415. </body>
  3416. </html>
  3417. <?php
  3418. die();
  3419. }
  3420. /**
  3421. * Convert a value to non-negative integer.
  3422. *
  3423. * @since 2.5.0
  3424. *
  3425. * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  3426. * @return int A non-negative integer.
  3427. */
  3428. function absint( $maybeint ) {
  3429. return abs( intval( $maybeint ) );
  3430. }
  3431. /**
  3432. * Mark a function as deprecated and inform when it has been used.
  3433. *
  3434. * There is a {@see 'hook deprecated_function_run'} that will be called that can be used
  3435. * to get the backtrace up to what file and function called the deprecated
  3436. * function.
  3437. *
  3438. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  3439. *
  3440. * This function is to be used in every function that is deprecated.
  3441. *
  3442. * @since 2.5.0
  3443. * @access private
  3444. *
  3445. * @param string $function The function that was called.
  3446. * @param string $version The version of WordPress that deprecated the function.
  3447. * @param string $replacement Optional. The function that should have been called. Default null.
  3448. */
  3449. function _deprecated_function( $function, $version, $replacement = null ) {
  3450. /**
  3451. * Fires when a deprecated function is called.
  3452. *
  3453. * @since 2.5.0
  3454. *
  3455. * @param string $function The function that was called.
  3456. * @param string $replacement The function that should have been called.
  3457. * @param string $version The version of WordPress that deprecated the function.
  3458. */
  3459. do_action( 'deprecated_function_run', $function, $replacement, $version );
  3460. /**
  3461. * Filters whether to trigger an error for deprecated functions.
  3462. *
  3463. * @since 2.5.0
  3464. *
  3465. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  3466. */
  3467. if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  3468. if ( function_exists( '__' ) ) {
  3469. if ( ! is_null( $replacement ) ) {
  3470. /* translators: 1: PHP function name, 2: version number, 3: alternative function name */
  3471. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  3472. } else {
  3473. /* translators: 1: PHP function name, 2: version number */
  3474. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  3475. }
  3476. } else {
  3477. if ( ! is_null( $replacement ) ) {
  3478. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
  3479. } else {
  3480. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  3481. }
  3482. }
  3483. }
  3484. }
  3485. /**
  3486. * Marks a constructor as deprecated and informs when it has been used.
  3487. *
  3488. * Similar to _deprecated_function(), but with different strings. Used to
  3489. * remove PHP4 style constructors.
  3490. *
  3491. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  3492. *
  3493. * This function is to be used in every PHP4 style constructor method that is deprecated.
  3494. *
  3495. * @since 4.3.0
  3496. * @since 4.5.0 Added the `$parent_class` parameter.
  3497. *
  3498. * @access private
  3499. *
  3500. * @param string $class The class containing the deprecated constructor.
  3501. * @param string $version The version of WordPress that deprecated the function.
  3502. * @param string $parent_class Optional. The parent class calling the deprecated constructor.
  3503. * Default empty string.
  3504. */
  3505. function _deprecated_constructor( $class, $version, $parent_class = '' ) {
  3506. /**
  3507. * Fires when a deprecated constructor is called.
  3508. *
  3509. * @since 4.3.0
  3510. * @since 4.5.0 Added the `$parent_class` parameter.
  3511. *
  3512. * @param string $class The class containing the deprecated constructor.
  3513. * @param string $version The version of WordPress that deprecated the function.
  3514. * @param string $parent_class The parent class calling the deprecated constructor.
  3515. */
  3516. do_action( 'deprecated_constructor_run', $class, $version, $parent_class );
  3517. /**
  3518. * Filters whether to trigger an error for deprecated functions.
  3519. *
  3520. * `WP_DEBUG` must be true in addition to the filter evaluating to true.
  3521. *
  3522. * @since 4.3.0
  3523. *
  3524. * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  3525. */
  3526. if ( WP_DEBUG && apply_filters( 'deprecated_constructor_trigger_error', true ) ) {
  3527. if ( function_exists( '__' ) ) {
  3528. if ( ! empty( $parent_class ) ) {
  3529. /* translators: 1: PHP class name, 2: PHP parent class name, 3: version number, 4: __construct() method */
  3530. 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.' ),
  3531. $class, $parent_class, $version, '<pre>__construct()</pre>' ) );
  3532. } else {
  3533. /* translators: 1: PHP class name, 2: version number, 3: __construct() method */
  3534. trigger_error( sprintf( __( 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ),
  3535. $class, $version, '<pre>__construct()</pre>' ) );
  3536. }
  3537. } else {
  3538. if ( ! empty( $parent_class ) ) {
  3539. 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.',
  3540. $class, $parent_class, $version, '<pre>__construct()</pre>' ) );
  3541. } else {
  3542. trigger_error( sprintf( 'The called constructor method for %1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.',
  3543. $class, $version, '<pre>__construct()</pre>' ) );
  3544. }
  3545. }
  3546. }
  3547. }
  3548. /**
  3549. * Mark a file as deprecated and inform when it has been used.
  3550. *
  3551. * There is a hook {@see 'deprecated_file_included'} that will be called that can be used
  3552. * to get the backtrace up to what file and function included the deprecated
  3553. * file.
  3554. *
  3555. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  3556. *
  3557. * This function is to be used in every file that is deprecated.
  3558. *
  3559. * @since 2.5.0
  3560. * @access private
  3561. *
  3562. * @param string $file The file that was included.
  3563. * @param string $version The version of WordPress that deprecated the file.
  3564. * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  3565. * Default null.
  3566. * @param string $message Optional. A message regarding the change. Default empty.
  3567. */
  3568. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  3569. /**
  3570. * Fires when a deprecated file is called.
  3571. *
  3572. * @since 2.5.0
  3573. *
  3574. * @param string $file The file that was called.
  3575. * @param string $replacement The file that should have been included based on ABSPATH.
  3576. * @param string $version The version of WordPress that deprecated the file.
  3577. * @param string $message A message regarding the change.
  3578. */
  3579. do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  3580. /**
  3581. * Filters whether to trigger an error for deprecated files.
  3582. *
  3583. * @since 2.5.0
  3584. *
  3585. * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  3586. */
  3587. if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  3588. $message = empty( $message ) ? '' : ' ' . $message;
  3589. if ( function_exists( '__' ) ) {
  3590. if ( ! is_null( $replacement ) ) {
  3591. /* translators: 1: PHP file name, 2: version number, 3: alternative file name */
  3592. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
  3593. } else {
  3594. /* translators: 1: PHP file name, 2: version number */
  3595. trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
  3596. }
  3597. } else {
  3598. if ( ! is_null( $replacement ) ) {
  3599. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
  3600. } else {
  3601. trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $file, $version ) . $message );
  3602. }
  3603. }
  3604. }
  3605. }
  3606. /**
  3607. * Mark a function argument as deprecated and inform when it has been used.
  3608. *
  3609. * This function is to be used whenever a deprecated function argument is used.
  3610. * Before this function is called, the argument must be checked for whether it was
  3611. * used by comparing it to its default value or evaluating whether it is empty.
  3612. * For example:
  3613. *
  3614. * if ( ! empty( $deprecated ) ) {
  3615. * _deprecated_argument( __FUNCTION__, '3.0.0' );
  3616. * }
  3617. *
  3618. *
  3619. * There is a hook deprecated_argument_run that will be called that can be used
  3620. * to get the backtrace up to what file and function used the deprecated
  3621. * argument.
  3622. *
  3623. * The current behavior is to trigger a user error if WP_DEBUG is true.
  3624. *
  3625. * @since 3.0.0
  3626. * @access private
  3627. *
  3628. * @param string $function The function that was called.
  3629. * @param string $version The version of WordPress that deprecated the argument used.
  3630. * @param string $message Optional. A message regarding the change. Default null.
  3631. */
  3632. function _deprecated_argument( $function, $version, $message = null ) {
  3633. /**
  3634. * Fires when a deprecated argument is called.
  3635. *
  3636. * @since 3.0.0
  3637. *
  3638. * @param string $function The function that was called.
  3639. * @param string $message A message regarding the change.
  3640. * @param string $version The version of WordPress that deprecated the argument used.
  3641. */
  3642. do_action( 'deprecated_argument_run', $function, $message, $version );
  3643. /**
  3644. * Filters whether to trigger an error for deprecated arguments.
  3645. *
  3646. * @since 3.0.0
  3647. *
  3648. * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  3649. */
  3650. if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  3651. if ( function_exists( '__' ) ) {
  3652. if ( ! is_null( $message ) ) {
  3653. /* translators: 1: PHP function name, 2: version number, 3: optional message regarding the change */
  3654. trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
  3655. } else {
  3656. /* translators: 1: PHP function name, 2: version number */
  3657. 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 ) );
  3658. }
  3659. } else {
  3660. if ( ! is_null( $message ) ) {
  3661. trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) );
  3662. } else {
  3663. 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 ) );
  3664. }
  3665. }
  3666. }
  3667. }
  3668. /**
  3669. * Marks a deprecated action or filter hook as deprecated and throws a notice.
  3670. *
  3671. * Use the {@see 'deprecated_hook_run'} action to get the backtrace describing where
  3672. * the deprecated hook was called.
  3673. *
  3674. * Default behavior is to trigger a user error if `WP_DEBUG` is true.
  3675. *
  3676. * This function is called by the do_action_deprecated() and apply_filters_deprecated()
  3677. * functions, and so generally does not need to be called directly.
  3678. *
  3679. * @since 4.6.0
  3680. * @access private
  3681. *
  3682. * @param string $hook The hook that was used.
  3683. * @param string $version The version of WordPress that deprecated the hook.
  3684. * @param string $replacement Optional. The hook that should have been used.
  3685. * @param string $message Optional. A message regarding the change.
  3686. */
  3687. function _deprecated_hook( $hook, $version, $replacement = null, $message = null ) {
  3688. /**
  3689. * Fires when a deprecated hook is called.
  3690. *
  3691. * @since 4.6.0
  3692. *
  3693. * @param string $hook The hook that was called.
  3694. * @param string $replacement The hook that should be used as a replacement.
  3695. * @param string $version The version of WordPress that deprecated the argument used.
  3696. * @param string $message A message regarding the change.
  3697. */
  3698. do_action( 'deprecated_hook_run', $hook, $replacement, $version, $message );
  3699. /**
  3700. * Filters whether to trigger deprecated hook errors.
  3701. *
  3702. * @since 4.6.0
  3703. *
  3704. * @param bool $trigger Whether to trigger deprecated hook errors. Requires
  3705. * `WP_DEBUG` to be defined true.
  3706. */
  3707. if ( WP_DEBUG && apply_filters( 'deprecated_hook_trigger_error', true ) ) {
  3708. $message = empty( $message ) ? '' : ' ' . $message;
  3709. if ( ! is_null( $replacement ) ) {
  3710. /* translators: 1: WordPress hook name, 2: version number, 3: alternative hook name */
  3711. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.' ), $hook, $version, $replacement ) . $message );
  3712. } else {
  3713. /* translators: 1: WordPress hook name, 2: version number */
  3714. trigger_error( sprintf( __( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.' ), $hook, $version ) . $message );
  3715. }
  3716. }
  3717. }
  3718. /**
  3719. * Mark something as being incorrectly called.
  3720. *
  3721. * There is a hook {@see 'doing_it_wrong_run'} that will be called that can be used
  3722. * to get the backtrace up to what file and function called the deprecated
  3723. * function.
  3724. *
  3725. * The current behavior is to trigger a user error if `WP_DEBUG` is true.
  3726. *
  3727. * @since 3.1.0
  3728. * @access private
  3729. *
  3730. * @param string $function The function that was called.
  3731. * @param string $message A message explaining what has been done incorrectly.
  3732. * @param string $version The version of WordPress where the message was added.
  3733. */
  3734. function _doing_it_wrong( $function, $message, $version ) {
  3735. /**
  3736. * Fires when the given function is being used incorrectly.
  3737. *
  3738. * @since 3.1.0
  3739. *
  3740. * @param string $function The function that was called.
  3741. * @param string $message A message explaining what has been done incorrectly.
  3742. * @param string $version The version of WordPress where the message was added.
  3743. */
  3744. do_action( 'doing_it_wrong_run', $function, $message, $version );
  3745. /**
  3746. * Filters whether to trigger an error for _doing_it_wrong() calls.
  3747. *
  3748. * @since 3.1.0
  3749. *
  3750. * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  3751. */
  3752. if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
  3753. if ( function_exists( '__' ) ) {
  3754. if ( is_null( $version ) ) {
  3755. $version = '';
  3756. } else {
  3757. /* translators: %s: version number */
  3758. $version = sprintf( __( '(This message was added in version %s.)' ), $version );
  3759. }
  3760. /* translators: %s: Codex URL */
  3761. $message .= ' ' . sprintf( __( 'Please see <a href="%s">Debugging in WordPress</a> for more information.' ),
  3762. __( 'https://codex.wordpress.org/Debugging_in_WordPress' )
  3763. );
  3764. /* translators: Developer debugging message. 1: PHP function name, 2: Explanatory message, 3: Version information message */
  3765. trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
  3766. } else {
  3767. if ( is_null( $version ) ) {
  3768. $version = '';
  3769. } else {
  3770. $version = sprintf( '(This message was added in version %s.)', $version );
  3771. }
  3772. $message .= sprintf( ' Please see <a href="%s">Debugging in WordPress</a> for more information.',
  3773. 'https://codex.wordpress.org/Debugging_in_WordPress'
  3774. );
  3775. trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
  3776. }
  3777. }
  3778. }
  3779. /**
  3780. * Is the server running earlier than 1.5.0 version of lighttpd?
  3781. *
  3782. * @since 2.5.0
  3783. *
  3784. * @return bool Whether the server is running lighttpd < 1.5.0.
  3785. */
  3786. function is_lighttpd_before_150() {
  3787. $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  3788. $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  3789. return 'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  3790. }
  3791. /**
  3792. * Does the specified module exist in the Apache config?
  3793. *
  3794. * @since 2.5.0
  3795. *
  3796. * @global bool $is_apache
  3797. *
  3798. * @param string $mod The module, e.g. mod_rewrite.
  3799. * @param bool $default Optional. The default return value if the module is not found. Default false.
  3800. * @return bool Whether the specified module is loaded.
  3801. */
  3802. function apache_mod_loaded($mod, $default = false) {
  3803. global $is_apache;
  3804. if ( !$is_apache )
  3805. return false;
  3806. if ( function_exists( 'apache_get_modules' ) ) {
  3807. $mods = apache_get_modules();
  3808. if ( in_array($mod, $mods) )
  3809. return true;
  3810. } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  3811. ob_start();
  3812. phpinfo(8);
  3813. $phpinfo = ob_get_clean();
  3814. if ( false !== strpos($phpinfo, $mod) )
  3815. return true;
  3816. }
  3817. return $default;
  3818. }
  3819. /**
  3820. * Check if IIS 7+ supports pretty permalinks.
  3821. *
  3822. * @since 2.8.0
  3823. *
  3824. * @global bool $is_iis7
  3825. *
  3826. * @return bool Whether IIS7 supports permalinks.
  3827. */
  3828. function iis7_supports_permalinks() {
  3829. global $is_iis7;
  3830. $supports_permalinks = false;
  3831. if ( $is_iis7 ) {
  3832. /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  3833. * easily update the xml configuration file, hence we just bail out and tell user that
  3834. * pretty permalinks cannot be used.
  3835. *
  3836. * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  3837. * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  3838. * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  3839. * via ISAPI then pretty permalinks will not work.
  3840. */
  3841. $supports_permalinks = class_exists( 'DOMDocument', false ) && isset($_SERVER['IIS_UrlRewriteModule']) && ( PHP_SAPI == 'cgi-fcgi' );
  3842. }
  3843. /**
  3844. * Filters whether IIS 7+ supports pretty permalinks.
  3845. *
  3846. * @since 2.8.0
  3847. *
  3848. * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  3849. */
  3850. return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  3851. }
  3852. /**
  3853. * Validates a file name and path against an allowed set of rules.
  3854. *
  3855. * A return value of `1` means the file path contains directory traversal.
  3856. *
  3857. * A return value of `2` means the file path contains a Windows drive path.
  3858. *
  3859. * A return value of `3` means the file is not in the allowed files list.
  3860. *
  3861. * @since 1.2.0
  3862. *
  3863. * @param string $file File path.
  3864. * @param array $allowed_files Optional. List of allowed files.
  3865. * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  3866. */
  3867. function validate_file( $file, $allowed_files = array() ) {
  3868. // `../` on its own is not allowed:
  3869. if ( '../' === $file ) {
  3870. return 1;
  3871. }
  3872. // More than one occurence of `../` is not allowed:
  3873. if ( preg_match_all( '#\.\./#', $file, $matches, PREG_SET_ORDER ) && ( count( $matches ) > 1 ) ) {
  3874. return 1;
  3875. }
  3876. // `../` which does not occur at the end of the path is not allowed:
  3877. if ( false !== strpos( $file, '../' ) && '../' !== mb_substr( $file, -3, 3 ) ) {
  3878. return 1;
  3879. }
  3880. // Files not in the allowed file list are not allowed:
  3881. if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
  3882. return 3;
  3883. // Absolute Windows drive paths are not allowed:
  3884. if (':' == substr( $file, 1, 1 ) )
  3885. return 2;
  3886. return 0;
  3887. }
  3888. /**
  3889. * Whether to force SSL used for the Administration Screens.
  3890. *
  3891. * @since 2.6.0
  3892. *
  3893. * @staticvar bool $forced
  3894. *
  3895. * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  3896. * @return bool True if forced, false if not forced.
  3897. */
  3898. function force_ssl_admin( $force = null ) {
  3899. static $forced = false;
  3900. if ( !is_null( $force ) ) {
  3901. $old_forced = $forced;
  3902. $forced = $force;
  3903. return $old_forced;
  3904. }
  3905. return $forced;
  3906. }
  3907. /**
  3908. * Guess the URL for the site.
  3909. *
  3910. * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  3911. * directory.
  3912. *
  3913. * @since 2.6.0
  3914. *
  3915. * @return string The guessed URL.
  3916. */
  3917. function wp_guess_url() {
  3918. if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  3919. $url = WP_SITEURL;
  3920. } else {
  3921. $abspath_fix = str_replace( '\\', '/', ABSPATH );
  3922. $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  3923. // The request is for the admin
  3924. if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  3925. $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  3926. // The request is for a file in ABSPATH
  3927. } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  3928. // Strip off any file/query params in the path
  3929. $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  3930. } else {
  3931. if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  3932. // Request is hitting a file inside ABSPATH
  3933. $directory = str_replace( ABSPATH, '', $script_filename_dir );
  3934. // Strip off the sub directory, and any file/query params
  3935. $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
  3936. } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  3937. // Request is hitting a file above ABSPATH
  3938. $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  3939. // Strip off any file/query params from the path, appending the sub directory to the installation
  3940. $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
  3941. } else {
  3942. $path = $_SERVER['REQUEST_URI'];
  3943. }
  3944. }
  3945. $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
  3946. $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  3947. }
  3948. return rtrim($url, '/');
  3949. }
  3950. /**
  3951. * Temporarily suspend cache additions.
  3952. *
  3953. * Stops more data being added to the cache, but still allows cache retrieval.
  3954. * This is useful for actions, such as imports, when a lot of data would otherwise
  3955. * be almost uselessly added to the cache.
  3956. *
  3957. * Suspension lasts for a single page load at most. Remember to call this
  3958. * function again if you wish to re-enable cache adds earlier.
  3959. *
  3960. * @since 3.3.0
  3961. *
  3962. * @staticvar bool $_suspend
  3963. *
  3964. * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  3965. * @return bool The current suspend setting
  3966. */
  3967. function wp_suspend_cache_addition( $suspend = null ) {
  3968. static $_suspend = false;
  3969. if ( is_bool( $suspend ) )
  3970. $_suspend = $suspend;
  3971. return $_suspend;
  3972. }
  3973. /**
  3974. * Suspend cache invalidation.
  3975. *
  3976. * Turns cache invalidation on and off. Useful during imports where you don't want to do
  3977. * invalidations every time a post is inserted. Callers must be sure that what they are
  3978. * doing won't lead to an inconsistent cache when invalidation is suspended.
  3979. *
  3980. * @since 2.7.0
  3981. *
  3982. * @global bool $_wp_suspend_cache_invalidation
  3983. *
  3984. * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  3985. * @return bool The current suspend setting.
  3986. */
  3987. function wp_suspend_cache_invalidation( $suspend = true ) {
  3988. global $_wp_suspend_cache_invalidation;
  3989. $current_suspend = $_wp_suspend_cache_invalidation;
  3990. $_wp_suspend_cache_invalidation = $suspend;
  3991. return $current_suspend;
  3992. }
  3993. /**
  3994. * Determine whether a site is the main site of the current network.
  3995. *
  3996. * @since 3.0.0
  3997. * @since 4.9.0 The $network_id parameter has been added.
  3998. *
  3999. * @param int $site_id Optional. Site ID to test. Defaults to current site.
  4000. * @param int $network_id Optional. Network ID of the network to check for.
  4001. * Defaults to current network.
  4002. * @return bool True if $site_id is the main site of the network, or if not
  4003. * running Multisite.
  4004. */
  4005. function is_main_site( $site_id = null, $network_id = null ) {
  4006. if ( ! is_multisite() ) {
  4007. return true;
  4008. }
  4009. if ( ! $site_id ) {
  4010. $site_id = get_current_blog_id();
  4011. }
  4012. $site_id = (int) $site_id;
  4013. return $site_id === get_main_site_id( $network_id );
  4014. }
  4015. /**
  4016. * Gets the main site ID.
  4017. *
  4018. * @since 4.9.0
  4019. *
  4020. * @param int $network_id Optional. The ID of the network for which to get the main site.
  4021. * Defaults to the current network.
  4022. * @return int The ID of the main site.
  4023. */
  4024. function get_main_site_id( $network_id = null ) {
  4025. if ( ! is_multisite() ) {
  4026. return get_current_blog_id();
  4027. }
  4028. $network = get_network( $network_id );
  4029. if ( ! $network ) {
  4030. return 0;
  4031. }
  4032. return $network->site_id;
  4033. }
  4034. /**
  4035. * Determine whether a network is the main network of the Multisite installation.
  4036. *
  4037. * @since 3.7.0
  4038. *
  4039. * @param int $network_id Optional. Network ID to test. Defaults to current network.
  4040. * @return bool True if $network_id is the main network, or if not running Multisite.
  4041. */
  4042. function is_main_network( $network_id = null ) {
  4043. if ( ! is_multisite() ) {
  4044. return true;
  4045. }
  4046. if ( null === $network_id ) {
  4047. $network_id = get_current_network_id();
  4048. }
  4049. $network_id = (int) $network_id;
  4050. return ( $network_id === get_main_network_id() );
  4051. }
  4052. /**
  4053. * Get the main network ID.
  4054. *
  4055. * @since 4.3.0
  4056. *
  4057. * @return int The ID of the main network.
  4058. */
  4059. function get_main_network_id() {
  4060. if ( ! is_multisite() ) {
  4061. return 1;
  4062. }
  4063. $current_network = get_network();
  4064. if ( defined( 'PRIMARY_NETWORK_ID' ) ) {
  4065. $main_network_id = PRIMARY_NETWORK_ID;
  4066. } elseif ( isset( $current_network->id ) && 1 === (int) $current_network->id ) {
  4067. // If the current network has an ID of 1, assume it is the main network.
  4068. $main_network_id = 1;
  4069. } else {
  4070. $_networks = get_networks( array( 'fields' => 'ids', 'number' => 1 ) );
  4071. $main_network_id = array_shift( $_networks );
  4072. }
  4073. /**
  4074. * Filters the main network ID.
  4075. *
  4076. * @since 4.3.0
  4077. *
  4078. * @param int $main_network_id The ID of the main network.
  4079. */
  4080. return (int) apply_filters( 'get_main_network_id', $main_network_id );
  4081. }
  4082. /**
  4083. * Determine whether global terms are enabled.
  4084. *
  4085. * @since 3.0.0
  4086. *
  4087. * @staticvar bool $global_terms
  4088. *
  4089. * @return bool True if multisite and global terms enabled.
  4090. */
  4091. function global_terms_enabled() {
  4092. if ( ! is_multisite() )
  4093. return false;
  4094. static $global_terms = null;
  4095. if ( is_null( $global_terms ) ) {
  4096. /**
  4097. * Filters whether global terms are enabled.
  4098. *
  4099. * Passing a non-null value to the filter will effectively short-circuit the function,
  4100. * returning the value of the 'global_terms_enabled' site option instead.
  4101. *
  4102. * @since 3.0.0
  4103. *
  4104. * @param null $enabled Whether global terms are enabled.
  4105. */
  4106. $filter = apply_filters( 'global_terms_enabled', null );
  4107. if ( ! is_null( $filter ) )
  4108. $global_terms = (bool) $filter;
  4109. else
  4110. $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  4111. }
  4112. return $global_terms;
  4113. }
  4114. /**
  4115. * gmt_offset modification for smart timezone handling.
  4116. *
  4117. * Overrides the gmt_offset option if we have a timezone_string available.
  4118. *
  4119. * @since 2.8.0
  4120. *
  4121. * @return float|false Timezone GMT offset, false otherwise.
  4122. */
  4123. function wp_timezone_override_offset() {
  4124. if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  4125. return false;
  4126. }
  4127. $timezone_object = timezone_open( $timezone_string );
  4128. $datetime_object = date_create();
  4129. if ( false === $timezone_object || false === $datetime_object ) {
  4130. return false;
  4131. }
  4132. return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  4133. }
  4134. /**
  4135. * Sort-helper for timezones.
  4136. *
  4137. * @since 2.9.0
  4138. * @access private
  4139. *
  4140. * @param array $a
  4141. * @param array $b
  4142. * @return int
  4143. */
  4144. function _wp_timezone_choice_usort_callback( $a, $b ) {
  4145. // Don't use translated versions of Etc
  4146. if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  4147. // Make the order of these more like the old dropdown
  4148. if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  4149. return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  4150. }
  4151. if ( 'UTC' === $a['city'] ) {
  4152. if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  4153. return 1;
  4154. }
  4155. return -1;
  4156. }
  4157. if ( 'UTC' === $b['city'] ) {
  4158. if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  4159. return -1;
  4160. }
  4161. return 1;
  4162. }
  4163. return strnatcasecmp( $a['city'], $b['city'] );
  4164. }
  4165. if ( $a['t_continent'] == $b['t_continent'] ) {
  4166. if ( $a['t_city'] == $b['t_city'] ) {
  4167. return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  4168. }
  4169. return strnatcasecmp( $a['t_city'], $b['t_city'] );
  4170. } else {
  4171. // Force Etc to the bottom of the list
  4172. if ( 'Etc' === $a['continent'] ) {
  4173. return 1;
  4174. }
  4175. if ( 'Etc' === $b['continent'] ) {
  4176. return -1;
  4177. }
  4178. return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  4179. }
  4180. }
  4181. /**
  4182. * Gives a nicely-formatted list of timezone strings.
  4183. *
  4184. * @since 2.9.0
  4185. * @since 4.7.0 Added the `$locale` parameter.
  4186. *
  4187. * @staticvar bool $mo_loaded
  4188. * @staticvar string $locale_loaded
  4189. *
  4190. * @param string $selected_zone Selected timezone.
  4191. * @param string $locale Optional. Locale to load the timezones in. Default current site locale.
  4192. * @return string
  4193. */
  4194. function wp_timezone_choice( $selected_zone, $locale = null ) {
  4195. static $mo_loaded = false, $locale_loaded = null;
  4196. $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
  4197. // Load translations for continents and cities.
  4198. if ( ! $mo_loaded || $locale !== $locale_loaded ) {
  4199. $locale_loaded = $locale ? $locale : get_locale();
  4200. $mofile = WP_LANG_DIR . '/continents-cities-' . $locale_loaded . '.mo';
  4201. unload_textdomain( 'continents-cities' );
  4202. load_textdomain( 'continents-cities', $mofile );
  4203. $mo_loaded = true;
  4204. }
  4205. $zonen = array();
  4206. foreach ( timezone_identifiers_list() as $zone ) {
  4207. $zone = explode( '/', $zone );
  4208. if ( !in_array( $zone[0], $continents ) ) {
  4209. continue;
  4210. }
  4211. // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  4212. $exists = array(
  4213. 0 => ( isset( $zone[0] ) && $zone[0] ),
  4214. 1 => ( isset( $zone[1] ) && $zone[1] ),
  4215. 2 => ( isset( $zone[2] ) && $zone[2] ),
  4216. );
  4217. $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  4218. $exists[4] = ( $exists[1] && $exists[3] );
  4219. $exists[5] = ( $exists[2] && $exists[3] );
  4220. $zonen[] = array(
  4221. 'continent' => ( $exists[0] ? $zone[0] : '' ),
  4222. 'city' => ( $exists[1] ? $zone[1] : '' ),
  4223. 'subcity' => ( $exists[2] ? $zone[2] : '' ),
  4224. 't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  4225. 't_city' => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  4226. 't_subcity' => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  4227. );
  4228. }
  4229. usort( $zonen, '_wp_timezone_choice_usort_callback' );
  4230. $structure = array();
  4231. if ( empty( $selected_zone ) ) {
  4232. $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  4233. }
  4234. foreach ( $zonen as $key => $zone ) {
  4235. // Build value in an array to join later
  4236. $value = array( $zone['continent'] );
  4237. if ( empty( $zone['city'] ) ) {
  4238. // It's at the continent level (generally won't happen)
  4239. $display = $zone['t_continent'];
  4240. } else {
  4241. // It's inside a continent group
  4242. // Continent optgroup
  4243. if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  4244. $label = $zone['t_continent'];
  4245. $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  4246. }
  4247. // Add the city to the value
  4248. $value[] = $zone['city'];
  4249. $display = $zone['t_city'];
  4250. if ( !empty( $zone['subcity'] ) ) {
  4251. // Add the subcity to the value
  4252. $value[] = $zone['subcity'];
  4253. $display .= ' - ' . $zone['t_subcity'];
  4254. }
  4255. }
  4256. // Build the value
  4257. $value = join( '/', $value );
  4258. $selected = '';
  4259. if ( $value === $selected_zone ) {
  4260. $selected = 'selected="selected" ';
  4261. }
  4262. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  4263. // Close continent optgroup
  4264. if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  4265. $structure[] = '</optgroup>';
  4266. }
  4267. }
  4268. // Do UTC
  4269. $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
  4270. $selected = '';
  4271. if ( 'UTC' === $selected_zone )
  4272. $selected = 'selected="selected" ';
  4273. $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
  4274. $structure[] = '</optgroup>';
  4275. // Do manual UTC offsets
  4276. $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
  4277. $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,
  4278. 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);
  4279. foreach ( $offset_range as $offset ) {
  4280. if ( 0 <= $offset )
  4281. $offset_name = '+' . $offset;
  4282. else
  4283. $offset_name = (string) $offset;
  4284. $offset_value = $offset_name;
  4285. $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
  4286. $offset_name = 'UTC' . $offset_name;
  4287. $offset_value = 'UTC' . $offset_value;
  4288. $selected = '';
  4289. if ( $offset_value === $selected_zone )
  4290. $selected = 'selected="selected" ';
  4291. $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
  4292. }
  4293. $structure[] = '</optgroup>';
  4294. return join( "\n", $structure );
  4295. }
  4296. /**
  4297. * Strip close comment and close php tags from file headers used by WP.
  4298. *
  4299. * @since 2.8.0
  4300. * @access private
  4301. *
  4302. * @see https://core.trac.wordpress.org/ticket/8497
  4303. *
  4304. * @param string $str Header comment to clean up.
  4305. * @return string
  4306. */
  4307. function _cleanup_header_comment( $str ) {
  4308. return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  4309. }
  4310. /**
  4311. * Permanently delete comments or posts of any type that have held a status
  4312. * of 'trash' for the number of days defined in EMPTY_TRASH_DAYS.
  4313. *
  4314. * The default value of `EMPTY_TRASH_DAYS` is 30 (days).
  4315. *
  4316. * @since 2.9.0
  4317. *
  4318. * @global wpdb $wpdb WordPress database abstraction object.
  4319. */
  4320. function wp_scheduled_delete() {
  4321. global $wpdb;
  4322. $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  4323. $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);
  4324. foreach ( (array) $posts_to_delete as $post ) {
  4325. $post_id = (int) $post['post_id'];
  4326. if ( !$post_id )
  4327. continue;
  4328. $del_post = get_post($post_id);
  4329. if ( !$del_post || 'trash' != $del_post->post_status ) {
  4330. delete_post_meta($post_id, '_wp_trash_meta_status');
  4331. delete_post_meta($post_id, '_wp_trash_meta_time');
  4332. } else {
  4333. wp_delete_post($post_id);
  4334. }
  4335. }
  4336. $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);
  4337. foreach ( (array) $comments_to_delete as $comment ) {
  4338. $comment_id = (int) $comment['comment_id'];
  4339. if ( !$comment_id )
  4340. continue;
  4341. $del_comment = get_comment($comment_id);
  4342. if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
  4343. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  4344. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  4345. } else {
  4346. wp_delete_comment( $del_comment );
  4347. }
  4348. }
  4349. }
  4350. /**
  4351. * Retrieve metadata from a file.
  4352. *
  4353. * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
  4354. * Each piece of metadata must be on its own line. Fields can not span multiple
  4355. * lines, the value will get cut at the end of the first line.
  4356. *
  4357. * If the file data is not within that first 8kiB, then the author should correct
  4358. * their plugin file and move the data headers to the top.
  4359. *
  4360. * @link https://codex.wordpress.org/File_Header
  4361. *
  4362. * @since 2.9.0
  4363. *
  4364. * @param string $file Path to the file.
  4365. * @param array $default_headers List of headers, in the format array('HeaderKey' => 'Header Name').
  4366. * @param string $context Optional. If specified adds filter hook {@see 'extra_$context_headers'}.
  4367. * Default empty.
  4368. * @return array Array of file headers in `HeaderKey => Header Value` format.
  4369. */
  4370. function get_file_data( $file, $default_headers, $context = '' ) {
  4371. // We don't need to write to the file, so just open for reading.
  4372. $fp = fopen( $file, 'r' );
  4373. // Pull only the first 8kiB of the file in.
  4374. $file_data = fread( $fp, 8192 );
  4375. // PHP will close file handle, but we are good citizens.
  4376. fclose( $fp );
  4377. // Make sure we catch CR-only line endings.
  4378. $file_data = str_replace( "\r", "\n", $file_data );
  4379. /**
  4380. * Filters extra file headers by context.
  4381. *
  4382. * The dynamic portion of the hook name, `$context`, refers to
  4383. * the context where extra headers might be loaded.
  4384. *
  4385. * @since 2.9.0
  4386. *
  4387. * @param array $extra_context_headers Empty array by default.
  4388. */
  4389. if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
  4390. $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
  4391. $all_headers = array_merge( $extra_headers, (array) $default_headers );
  4392. } else {
  4393. $all_headers = $default_headers;
  4394. }
  4395. foreach ( $all_headers as $field => $regex ) {
  4396. if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
  4397. $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  4398. else
  4399. $all_headers[ $field ] = '';
  4400. }
  4401. return $all_headers;
  4402. }
  4403. /**
  4404. * Returns true.
  4405. *
  4406. * Useful for returning true to filters easily.
  4407. *
  4408. * @since 3.0.0
  4409. *
  4410. * @see __return_false()
  4411. *
  4412. * @return true True.
  4413. */
  4414. function __return_true() {
  4415. return true;
  4416. }
  4417. /**
  4418. * Returns false.
  4419. *
  4420. * Useful for returning false to filters easily.
  4421. *
  4422. * @since 3.0.0
  4423. *
  4424. * @see __return_true()
  4425. *
  4426. * @return false False.
  4427. */
  4428. function __return_false() {
  4429. return false;
  4430. }
  4431. /**
  4432. * Returns 0.
  4433. *
  4434. * Useful for returning 0 to filters easily.
  4435. *
  4436. * @since 3.0.0
  4437. *
  4438. * @return int 0.
  4439. */
  4440. function __return_zero() {
  4441. return 0;
  4442. }
  4443. /**
  4444. * Returns an empty array.
  4445. *
  4446. * Useful for returning an empty array to filters easily.
  4447. *
  4448. * @since 3.0.0
  4449. *
  4450. * @return array Empty array.
  4451. */
  4452. function __return_empty_array() {
  4453. return array();
  4454. }
  4455. /**
  4456. * Returns null.
  4457. *
  4458. * Useful for returning null to filters easily.
  4459. *
  4460. * @since 3.4.0
  4461. *
  4462. * @return null Null value.
  4463. */
  4464. function __return_null() {
  4465. return null;
  4466. }
  4467. /**
  4468. * Returns an empty string.
  4469. *
  4470. * Useful for returning an empty string to filters easily.
  4471. *
  4472. * @since 3.7.0
  4473. *
  4474. * @see __return_null()
  4475. *
  4476. * @return string Empty string.
  4477. */
  4478. function __return_empty_string() {
  4479. return '';
  4480. }
  4481. /**
  4482. * Send a HTTP header to disable content type sniffing in browsers which support it.
  4483. *
  4484. * @since 3.0.0
  4485. *
  4486. * @see https://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  4487. * @see https://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  4488. */
  4489. function send_nosniff_header() {
  4490. @header( 'X-Content-Type-Options: nosniff' );
  4491. }
  4492. /**
  4493. * Return a MySQL expression for selecting the week number based on the start_of_week option.
  4494. *
  4495. * @ignore
  4496. * @since 3.0.0
  4497. *
  4498. * @param string $column Database column.
  4499. * @return string SQL clause.
  4500. */
  4501. function _wp_mysql_week( $column ) {
  4502. switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
  4503. case 1 :
  4504. return "WEEK( $column, 1 )";
  4505. case 2 :
  4506. case 3 :
  4507. case 4 :
  4508. case 5 :
  4509. case 6 :
  4510. return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  4511. case 0 :
  4512. default :
  4513. return "WEEK( $column, 0 )";
  4514. }
  4515. }
  4516. /**
  4517. * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  4518. *
  4519. * @since 3.1.0
  4520. * @access private
  4521. *
  4522. * @param callable $callback Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  4523. * @param int $start The ID to start the loop check at.
  4524. * @param int $start_parent The parent_ID of $start to use instead of calling $callback( $start ).
  4525. * Use null to always use $callback
  4526. * @param array $callback_args Optional. Additional arguments to send to $callback.
  4527. * @return array IDs of all members of loop.
  4528. */
  4529. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  4530. $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  4531. if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
  4532. return array();
  4533. return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  4534. }
  4535. /**
  4536. * Use the "The Tortoise and the Hare" algorithm to detect loops.
  4537. *
  4538. * For every step of the algorithm, the hare takes two steps and the tortoise one.
  4539. * If the hare ever laps the tortoise, there must be a loop.
  4540. *
  4541. * @since 3.1.0
  4542. * @access private
  4543. *
  4544. * @param callable $callback Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  4545. * @param int $start The ID to start the loop check at.
  4546. * @param array $override Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  4547. * Default empty array.
  4548. * @param array $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  4549. * @param bool $_return_loop Optional. Return loop members or just detect presence of loop? Only set
  4550. * to true if you already know the given $start is part of a loop (otherwise
  4551. * the returned array might include branches). Default false.
  4552. * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  4553. * $_return_loop
  4554. */
  4555. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  4556. $tortoise = $hare = $evanescent_hare = $start;
  4557. $return = array();
  4558. // Set evanescent_hare to one past hare
  4559. // Increment hare two steps
  4560. while (
  4561. $tortoise
  4562. &&
  4563. ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  4564. &&
  4565. ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  4566. ) {
  4567. if ( $_return_loop )
  4568. $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
  4569. // tortoise got lapped - must be a loop
  4570. if ( $tortoise == $evanescent_hare || $tortoise == $hare )
  4571. return $_return_loop ? $return : $tortoise;
  4572. // Increment tortoise by one step
  4573. $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  4574. }
  4575. return false;
  4576. }
  4577. /**
  4578. * Send a HTTP header to limit rendering of pages to same origin iframes.
  4579. *
  4580. * @since 3.1.3
  4581. *
  4582. * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  4583. */
  4584. function send_frame_options_header() {
  4585. @header( 'X-Frame-Options: SAMEORIGIN' );
  4586. }
  4587. /**
  4588. * Retrieve a list of protocols to allow in HTML attributes.
  4589. *
  4590. * @since 3.3.0
  4591. * @since 4.3.0 Added 'webcal' to the protocols array.
  4592. * @since 4.7.0 Added 'urn' to the protocols array.
  4593. *
  4594. * @see wp_kses()
  4595. * @see esc_url()
  4596. *
  4597. * @staticvar array $protocols
  4598. *
  4599. * @return array Array of allowed protocols. Defaults to an array containing 'http', 'https',
  4600. * 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet',
  4601. * 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', 'webcal', and 'urn'.
  4602. */
  4603. function wp_allowed_protocols() {
  4604. static $protocols = array();
  4605. if ( empty( $protocols ) ) {
  4606. $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp', 'webcal', 'urn' );
  4607. }
  4608. if ( ! did_action( 'wp_loaded' ) ) {
  4609. /**
  4610. * Filters the list of protocols allowed in HTML attributes.
  4611. *
  4612. * @since 3.0.0
  4613. *
  4614. * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  4615. */
  4616. $protocols = array_unique( (array) apply_filters( 'kses_allowed_protocols', $protocols ) );
  4617. }
  4618. return $protocols;
  4619. }
  4620. /**
  4621. * Return a comma-separated string of functions that have been called to get
  4622. * to the current point in code.
  4623. *
  4624. * @since 3.4.0
  4625. *
  4626. * @see https://core.trac.wordpress.org/ticket/19589
  4627. *
  4628. * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  4629. * when you want to just give info about the callee. Default null.
  4630. * @param int $skip_frames Optional. A number of stack frames to skip - useful for unwinding
  4631. * back to the source of the issue. Default 0.
  4632. * @param bool $pretty Optional. Whether or not you want a comma separated string or raw
  4633. * array returned. Default true.
  4634. * @return string|array Either a string containing a reversed comma separated trace or an array
  4635. * of individual calls.
  4636. */
  4637. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  4638. if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
  4639. $trace = debug_backtrace( false );
  4640. else
  4641. $trace = debug_backtrace();
  4642. $caller = array();
  4643. $check_class = ! is_null( $ignore_class );
  4644. $skip_frames++; // skip this function
  4645. foreach ( $trace as $call ) {
  4646. if ( $skip_frames > 0 ) {
  4647. $skip_frames--;
  4648. } elseif ( isset( $call['class'] ) ) {
  4649. if ( $check_class && $ignore_class == $call['class'] )
  4650. continue; // Filter out calls
  4651. $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  4652. } else {
  4653. if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
  4654. $caller[] = "{$call['function']}('{$call['args'][0]}')";
  4655. } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
  4656. $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
  4657. } else {
  4658. $caller[] = $call['function'];
  4659. }
  4660. }
  4661. }
  4662. if ( $pretty )
  4663. return join( ', ', array_reverse( $caller ) );
  4664. else
  4665. return $caller;
  4666. }
  4667. /**
  4668. * Retrieve ids that are not already present in the cache.
  4669. *
  4670. * @since 3.4.0
  4671. * @access private
  4672. *
  4673. * @param array $object_ids ID list.
  4674. * @param string $cache_key The cache bucket to check against.
  4675. *
  4676. * @return array List of ids not present in the cache.
  4677. */
  4678. function _get_non_cached_ids( $object_ids, $cache_key ) {
  4679. $clean = array();
  4680. foreach ( $object_ids as $id ) {
  4681. $id = (int) $id;
  4682. if ( !wp_cache_get( $id, $cache_key ) ) {
  4683. $clean[] = $id;
  4684. }
  4685. }
  4686. return $clean;
  4687. }
  4688. /**
  4689. * Test if the current device has the capability to upload files.
  4690. *
  4691. * @since 3.4.0
  4692. * @access private
  4693. *
  4694. * @return bool Whether the device is able to upload files.
  4695. */
  4696. function _device_can_upload() {
  4697. if ( ! wp_is_mobile() )
  4698. return true;
  4699. $ua = $_SERVER['HTTP_USER_AGENT'];
  4700. if ( strpos($ua, 'iPhone') !== false
  4701. || strpos($ua, 'iPad') !== false
  4702. || strpos($ua, 'iPod') !== false ) {
  4703. return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  4704. }
  4705. return true;
  4706. }
  4707. /**
  4708. * Test if a given path is a stream URL
  4709. *
  4710. * @since 3.5.0
  4711. *
  4712. * @param string $path The resource path or URL.
  4713. * @return bool True if the path is a stream URL.
  4714. */
  4715. function wp_is_stream( $path ) {
  4716. if ( false === strpos( $path, '://' ) ) {
  4717. // $path isn't a stream
  4718. return false;
  4719. }
  4720. $wrappers = stream_get_wrappers();
  4721. $wrappers = array_map( 'preg_quote', $wrappers );
  4722. $wrappers_re = '(' . join( '|', $wrappers ) . ')';
  4723. return preg_match( "!^$wrappers_re://!", $path ) === 1;
  4724. }
  4725. /**
  4726. * Test if the supplied date is valid for the Gregorian calendar.
  4727. *
  4728. * @since 3.5.0
  4729. *
  4730. * @see checkdate()
  4731. *
  4732. * @param int $month Month number.
  4733. * @param int $day Day number.
  4734. * @param int $year Year number.
  4735. * @param string $source_date The date to filter.
  4736. * @return bool True if valid date, false if not valid date.
  4737. */
  4738. function wp_checkdate( $month, $day, $year, $source_date ) {
  4739. /**
  4740. * Filters whether the given date is valid for the Gregorian calendar.
  4741. *
  4742. * @since 3.5.0
  4743. *
  4744. * @param bool $checkdate Whether the given date is valid.
  4745. * @param string $source_date Date to check.
  4746. */
  4747. return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  4748. }
  4749. /**
  4750. * Load the auth check for monitoring whether the user is still logged in.
  4751. *
  4752. * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  4753. *
  4754. * This is disabled for certain screens where a login screen could cause an
  4755. * inconvenient interruption. A filter called {@see 'wp_auth_check_load'} can be used
  4756. * for fine-grained control.
  4757. *
  4758. * @since 3.6.0
  4759. */
  4760. function wp_auth_check_load() {
  4761. if ( ! is_admin() && ! is_user_logged_in() )
  4762. return;
  4763. if ( defined( 'IFRAME_REQUEST' ) )
  4764. return;
  4765. $screen = get_current_screen();
  4766. $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  4767. $show = ! in_array( $screen->id, $hidden );
  4768. /**
  4769. * Filters whether to load the authentication check.
  4770. *
  4771. * Passing a falsey value to the filter will effectively short-circuit
  4772. * loading the authentication check.
  4773. *
  4774. * @since 3.6.0
  4775. *
  4776. * @param bool $show Whether to load the authentication check.
  4777. * @param WP_Screen $screen The current screen object.
  4778. */
  4779. if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  4780. wp_enqueue_style( 'wp-auth-check' );
  4781. wp_enqueue_script( 'wp-auth-check' );
  4782. add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  4783. add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  4784. }
  4785. }
  4786. /**
  4787. * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  4788. *
  4789. * @since 3.6.0
  4790. */
  4791. function wp_auth_check_html() {
  4792. $login_url = wp_login_url();
  4793. $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  4794. $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  4795. /**
  4796. * Filters whether the authentication check originated at the same domain.
  4797. *
  4798. * @since 3.6.0
  4799. *
  4800. * @param bool $same_domain Whether the authentication check originated at the same domain.
  4801. */
  4802. $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  4803. $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  4804. ?>
  4805. <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  4806. <div id="wp-auth-check-bg"></div>
  4807. <div id="wp-auth-check">
  4808. <button type="button" class="wp-auth-check-close button-link"><span class="screen-reader-text"><?php _e( 'Close dialog' ); ?></span></button>
  4809. <?php
  4810. if ( $same_domain ) {
  4811. $login_src = add_query_arg( array(
  4812. 'interim-login' => '1',
  4813. 'wp_lang' => get_user_locale(),
  4814. ), $login_url );
  4815. ?>
  4816. <div id="wp-auth-check-form" class="loading" data-src="<?php echo esc_url( $login_src ); ?>"></div>
  4817. <?php
  4818. }
  4819. ?>
  4820. <div class="wp-auth-fallback">
  4821. <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e('Session expired'); ?></b></p>
  4822. <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e('Please log in again.'); ?></a>
  4823. <?php _e('The login page will open in a new window. After logging in you can close it and return to this page.'); ?></p>
  4824. </div>
  4825. </div>
  4826. </div>
  4827. <?php
  4828. }
  4829. /**
  4830. * Check whether a user is still logged in, for the heartbeat.
  4831. *
  4832. * Send a result that shows a log-in box if the user is no longer logged in,
  4833. * or if their cookie is within the grace period.
  4834. *
  4835. * @since 3.6.0
  4836. *
  4837. * @global int $login_grace_period
  4838. *
  4839. * @param array $response The Heartbeat response.
  4840. * @return array $response The Heartbeat response with 'wp-auth-check' value set.
  4841. */
  4842. function wp_auth_check( $response ) {
  4843. $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  4844. return $response;
  4845. }
  4846. /**
  4847. * Return RegEx body to liberally match an opening HTML tag.
  4848. *
  4849. * Matches an opening HTML tag that:
  4850. * 1. Is self-closing or
  4851. * 2. Has no body but has a closing tag of the same name or
  4852. * 3. Contains a body and a closing tag of the same name
  4853. *
  4854. * Note: this RegEx does not balance inner tags and does not attempt
  4855. * to produce valid HTML
  4856. *
  4857. * @since 3.6.0
  4858. *
  4859. * @param string $tag An HTML tag name. Example: 'video'.
  4860. * @return string Tag RegEx.
  4861. */
  4862. function get_tag_regex( $tag ) {
  4863. if ( empty( $tag ) )
  4864. return;
  4865. return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  4866. }
  4867. /**
  4868. * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  4869. * functions such as htmlspecialchars() and charset html attributes.
  4870. *
  4871. * @since 3.6.0
  4872. * @access private
  4873. *
  4874. * @see https://core.trac.wordpress.org/ticket/23688
  4875. *
  4876. * @param string $charset A charset name.
  4877. * @return string The canonical form of the charset.
  4878. */
  4879. function _canonical_charset( $charset ) {
  4880. if ( 'utf-8' === strtolower( $charset ) || 'utf8' === strtolower( $charset) ) {
  4881. return 'UTF-8';
  4882. }
  4883. if ( 'iso-8859-1' === strtolower( $charset ) || 'iso8859-1' === strtolower( $charset ) ) {
  4884. return 'ISO-8859-1';
  4885. }
  4886. return $charset;
  4887. }
  4888. /**
  4889. * Set the mbstring internal encoding to a binary safe encoding when func_overload
  4890. * is enabled.
  4891. *
  4892. * When mbstring.func_overload is in use for multi-byte encodings, the results from
  4893. * strlen() and similar functions respect the utf8 characters, causing binary data
  4894. * to return incorrect lengths.
  4895. *
  4896. * This function overrides the mbstring encoding to a binary-safe encoding, and
  4897. * resets it to the users expected encoding afterwards through the
  4898. * `reset_mbstring_encoding` function.
  4899. *
  4900. * It is safe to recursively call this function, however each
  4901. * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  4902. * of `reset_mbstring_encoding()` calls.
  4903. *
  4904. * @since 3.7.0
  4905. *
  4906. * @see reset_mbstring_encoding()
  4907. *
  4908. * @staticvar array $encodings
  4909. * @staticvar bool $overloaded
  4910. *
  4911. * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  4912. * Default false.
  4913. */
  4914. function mbstring_binary_safe_encoding( $reset = false ) {
  4915. static $encodings = array();
  4916. static $overloaded = null;
  4917. if ( is_null( $overloaded ) )
  4918. $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  4919. if ( false === $overloaded )
  4920. return;
  4921. if ( ! $reset ) {
  4922. $encoding = mb_internal_encoding();
  4923. array_push( $encodings, $encoding );
  4924. mb_internal_encoding( 'ISO-8859-1' );
  4925. }
  4926. if ( $reset && $encodings ) {
  4927. $encoding = array_pop( $encodings );
  4928. mb_internal_encoding( $encoding );
  4929. }
  4930. }
  4931. /**
  4932. * Reset the mbstring internal encoding to a users previously set encoding.
  4933. *
  4934. * @see mbstring_binary_safe_encoding()
  4935. *
  4936. * @since 3.7.0
  4937. */
  4938. function reset_mbstring_encoding() {
  4939. mbstring_binary_safe_encoding( true );
  4940. }
  4941. /**
  4942. * Filter/validate a variable as a boolean.
  4943. *
  4944. * Alternative to `filter_var( $var, FILTER_VALIDATE_BOOLEAN )`.
  4945. *
  4946. * @since 4.0.0
  4947. *
  4948. * @param mixed $var Boolean value to validate.
  4949. * @return bool Whether the value is validated.
  4950. */
  4951. function wp_validate_boolean( $var ) {
  4952. if ( is_bool( $var ) ) {
  4953. return $var;
  4954. }
  4955. if ( is_string( $var ) && 'false' === strtolower( $var ) ) {
  4956. return false;
  4957. }
  4958. return (bool) $var;
  4959. }
  4960. /**
  4961. * Delete a file
  4962. *
  4963. * @since 4.2.0
  4964. *
  4965. * @param string $file The path to the file to delete.
  4966. */
  4967. function wp_delete_file( $file ) {
  4968. /**
  4969. * Filters the path of the file to delete.
  4970. *
  4971. * @since 2.1.0
  4972. *
  4973. * @param string $file Path to the file to delete.
  4974. */
  4975. $delete = apply_filters( 'wp_delete_file', $file );
  4976. if ( ! empty( $delete ) ) {
  4977. @unlink( $delete );
  4978. }
  4979. }
  4980. /**
  4981. * Deletes a file if its path is within the given directory.
  4982. *
  4983. * @since 4.9.7
  4984. *
  4985. * @param string $file Absolute path to the file to delete.
  4986. * @param string $directory Absolute path to a directory.
  4987. * @return bool True on success, false on failure.
  4988. */
  4989. function wp_delete_file_from_directory( $file, $directory ) {
  4990. $real_file = realpath( wp_normalize_path( $file ) );
  4991. $real_directory = realpath( wp_normalize_path( $directory ) );
  4992. if ( false === $real_file || false === $real_directory || strpos( wp_normalize_path( $real_file ), trailingslashit( wp_normalize_path( $real_directory ) ) ) !== 0 ) {
  4993. return false;
  4994. }
  4995. wp_delete_file( $file );
  4996. return true;
  4997. }
  4998. /**
  4999. * Outputs a small JS snippet on preview tabs/windows to remove `window.name` on unload.
  5000. *
  5001. * This prevents reusing the same tab for a preview when the user has navigated away.
  5002. *
  5003. * @since 4.3.0
  5004. *
  5005. * @global WP_Post $post
  5006. */
  5007. function wp_post_preview_js() {
  5008. global $post;
  5009. if ( ! is_preview() || empty( $post ) ) {
  5010. return;
  5011. }
  5012. // Has to match the window name used in post_submit_meta_box()
  5013. $name = 'wp-preview-' . (int) $post->ID;
  5014. ?>
  5015. <script>
  5016. ( function() {
  5017. var query = document.location.search;
  5018. if ( query && query.indexOf( 'preview=true' ) !== -1 ) {
  5019. window.name = '<?php echo $name; ?>';
  5020. }
  5021. if ( window.addEventListener ) {
  5022. window.addEventListener( 'unload', function() { window.name = ''; }, false );
  5023. }
  5024. }());
  5025. </script>
  5026. <?php
  5027. }
  5028. /**
  5029. * Parses and formats a MySQL datetime (Y-m-d H:i:s) for ISO8601/RFC3339.
  5030. *
  5031. * Explicitly strips timezones, as datetimes are not saved with any timezone
  5032. * information. Including any information on the offset could be misleading.
  5033. *
  5034. * @since 4.4.0
  5035. *
  5036. * @param string $date_string Date string to parse and format.
  5037. * @return string Date formatted for ISO8601/RFC3339.
  5038. */
  5039. function mysql_to_rfc3339( $date_string ) {
  5040. $formatted = mysql2date( 'c', $date_string, false );
  5041. // Strip timezone information
  5042. return preg_replace( '/(?:Z|[+-]\d{2}(?::\d{2})?)$/', '', $formatted );
  5043. }
  5044. /**
  5045. * Attempts to raise the PHP memory limit for memory intensive processes.
  5046. *
  5047. * Only allows raising the existing limit and prevents lowering it.
  5048. *
  5049. * @since 4.6.0
  5050. *
  5051. * @param string $context Optional. Context in which the function is called. Accepts either 'admin',
  5052. * 'image', or an arbitrary other context. If an arbitrary context is passed,
  5053. * the similarly arbitrary {@see '{$context}_memory_limit'} filter will be
  5054. * invoked. Default 'admin'.
  5055. * @return bool|int|string The limit that was set or false on failure.
  5056. */
  5057. function wp_raise_memory_limit( $context = 'admin' ) {
  5058. // Exit early if the limit cannot be changed.
  5059. if ( false === wp_is_ini_value_changeable( 'memory_limit' ) ) {
  5060. return false;
  5061. }
  5062. $current_limit = @ini_get( 'memory_limit' );
  5063. $current_limit_int = wp_convert_hr_to_bytes( $current_limit );
  5064. if ( -1 === $current_limit_int ) {
  5065. return false;
  5066. }
  5067. $wp_max_limit = WP_MAX_MEMORY_LIMIT;
  5068. $wp_max_limit_int = wp_convert_hr_to_bytes( $wp_max_limit );
  5069. $filtered_limit = $wp_max_limit;
  5070. switch ( $context ) {
  5071. case 'admin':
  5072. /**
  5073. * Filters the maximum memory limit available for administration screens.
  5074. *
  5075. * This only applies to administrators, who may require more memory for tasks
  5076. * like updates. Memory limits when processing images (uploaded or edited by
  5077. * users of any role) are handled separately.
  5078. *
  5079. * The `WP_MAX_MEMORY_LIMIT` constant specifically defines the maximum memory
  5080. * limit available when in the administration back end. The default is 256M
  5081. * (256 megabytes of memory) or the original `memory_limit` php.ini value if
  5082. * this is higher.
  5083. *
  5084. * @since 3.0.0
  5085. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  5086. *
  5087. * @param int|string $filtered_limit The maximum WordPress memory limit. Accepts an integer
  5088. * (bytes), or a shorthand string notation, such as '256M'.
  5089. */
  5090. $filtered_limit = apply_filters( 'admin_memory_limit', $filtered_limit );
  5091. break;
  5092. case 'image':
  5093. /**
  5094. * Filters the memory limit allocated for image manipulation.
  5095. *
  5096. * @since 3.5.0
  5097. * @since 4.6.0 The default now takes the original `memory_limit` into account.
  5098. *
  5099. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  5100. * Default `WP_MAX_MEMORY_LIMIT` or the original
  5101. * php.ini `memory_limit`, whichever is higher.
  5102. * Accepts an integer (bytes), or a shorthand string
  5103. * notation, such as '256M'.
  5104. */
  5105. $filtered_limit = apply_filters( 'image_memory_limit', $filtered_limit );
  5106. break;
  5107. default:
  5108. /**
  5109. * Filters the memory limit allocated for arbitrary contexts.
  5110. *
  5111. * The dynamic portion of the hook name, `$context`, refers to an arbitrary
  5112. * context passed on calling the function. This allows for plugins to define
  5113. * their own contexts for raising the memory limit.
  5114. *
  5115. * @since 4.6.0
  5116. *
  5117. * @param int|string $filtered_limit Maximum memory limit to allocate for images.
  5118. * Default '256M' or the original php.ini `memory_limit`,
  5119. * whichever is higher. Accepts an integer (bytes), or a
  5120. * shorthand string notation, such as '256M'.
  5121. */
  5122. $filtered_limit = apply_filters( "{$context}_memory_limit", $filtered_limit );
  5123. break;
  5124. }
  5125. $filtered_limit_int = wp_convert_hr_to_bytes( $filtered_limit );
  5126. if ( -1 === $filtered_limit_int || ( $filtered_limit_int > $wp_max_limit_int && $filtered_limit_int > $current_limit_int ) ) {
  5127. if ( false !== @ini_set( 'memory_limit', $filtered_limit ) ) {
  5128. return $filtered_limit;
  5129. } else {
  5130. return false;
  5131. }
  5132. } elseif ( -1 === $wp_max_limit_int || $wp_max_limit_int > $current_limit_int ) {
  5133. if ( false !== @ini_set( 'memory_limit', $wp_max_limit ) ) {
  5134. return $wp_max_limit;
  5135. } else {
  5136. return false;
  5137. }
  5138. }
  5139. return false;
  5140. }
  5141. /**
  5142. * Generate a random UUID (version 4).
  5143. *
  5144. * @since 4.7.0
  5145. *
  5146. * @return string UUID.
  5147. */
  5148. function wp_generate_uuid4() {
  5149. return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  5150. mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
  5151. mt_rand( 0, 0xffff ),
  5152. mt_rand( 0, 0x0fff ) | 0x4000,
  5153. mt_rand( 0, 0x3fff ) | 0x8000,
  5154. mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
  5155. );
  5156. }
  5157. /**
  5158. * Validates that a UUID is valid.
  5159. *
  5160. * @since 4.9.0
  5161. *
  5162. * @param mixed $uuid UUID to check.
  5163. * @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`.
  5164. * @return bool The string is a valid UUID or false on failure.
  5165. */
  5166. function wp_is_uuid( $uuid, $version = null ) {
  5167. if ( ! is_string( $uuid ) ) {
  5168. return false;
  5169. }
  5170. if ( is_numeric( $version ) ) {
  5171. if ( 4 !== (int) $version ) {
  5172. _doing_it_wrong( __FUNCTION__, __( 'Only UUID V4 is supported at this time.' ), '4.9.0' );
  5173. return false;
  5174. }
  5175. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/';
  5176. } else {
  5177. $regex = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/';
  5178. }
  5179. return (bool) preg_match( $regex, $uuid );
  5180. }
  5181. /**
  5182. * Get last changed date for the specified cache group.
  5183. *
  5184. * @since 4.7.0
  5185. *
  5186. * @param string $group Where the cache contents are grouped.
  5187. *
  5188. * @return string $last_changed UNIX timestamp with microseconds representing when the group was last changed.
  5189. */
  5190. function wp_cache_get_last_changed( $group ) {
  5191. $last_changed = wp_cache_get( 'last_changed', $group );
  5192. if ( ! $last_changed ) {
  5193. $last_changed = microtime();
  5194. wp_cache_set( 'last_changed', $last_changed, $group );
  5195. }
  5196. return $last_changed;
  5197. }
  5198. /**
  5199. * Send an email to the old site admin email address when the site admin email address changes.
  5200. *
  5201. * @since 4.9.0
  5202. *
  5203. * @param string $old_email The old site admin email address.
  5204. * @param string $new_email The new site admin email address.
  5205. * @param string $option_name The relevant database option name.
  5206. */
  5207. function wp_site_admin_email_change_notification( $old_email, $new_email, $option_name ) {
  5208. $send = true;
  5209. // Don't send the notification to the default 'admin_email' value.
  5210. if ( 'you@example.com' === $old_email ) {
  5211. $send = false;
  5212. }
  5213. /**
  5214. * Filters whether to send the site admin email change notification email.
  5215. *
  5216. * @since 4.9.0
  5217. *
  5218. * @param bool $send Whether to send the email notification.
  5219. * @param string $old_email The old site admin email address.
  5220. * @param string $new_email The new site admin email address.
  5221. */
  5222. $send = apply_filters( 'send_site_admin_email_change_email', $send, $old_email, $new_email );
  5223. if ( ! $send ) {
  5224. return;
  5225. }
  5226. /* translators: Do not translate OLD_EMAIL, NEW_EMAIL, SITENAME, SITEURL: those are placeholders. */
  5227. $email_change_text = __( 'Hi,
  5228. This notice confirms that the admin email address was changed on ###SITENAME###.
  5229. The new admin email address is ###NEW_EMAIL###.
  5230. This email has been sent to ###OLD_EMAIL###
  5231. Regards,
  5232. All at ###SITENAME###
  5233. ###SITEURL###' );
  5234. $email_change_email = array(
  5235. 'to' => $old_email,
  5236. /* translators: Site admin email change notification email subject. %s: Site title */
  5237. 'subject' => __( '[%s] Notice of Admin Email Change' ),
  5238. 'message' => $email_change_text,
  5239. 'headers' => '',
  5240. );
  5241. // get site name
  5242. $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  5243. /**
  5244. * Filters the contents of the email notification sent when the site admin email address is changed.
  5245. *
  5246. * @since 4.9.0
  5247. *
  5248. * @param array $email_change_email {
  5249. * Used to build wp_mail().
  5250. *
  5251. * @type string $to The intended recipient.
  5252. * @type string $subject The subject of the email.
  5253. * @type string $message The content of the email.
  5254. * The following strings have a special meaning and will get replaced dynamically:
  5255. * - ###OLD_EMAIL### The old site admin email address.
  5256. * - ###NEW_EMAIL### The new site admin email address.
  5257. * - ###SITENAME### The name of the site.
  5258. * - ###SITEURL### The URL to the site.
  5259. * @type string $headers Headers.
  5260. * }
  5261. * @param string $old_email The old site admin email address.
  5262. * @param string $new_email The new site admin email address.
  5263. */
  5264. $email_change_email = apply_filters( 'site_admin_email_change_email', $email_change_email, $old_email, $new_email );
  5265. $email_change_email['message'] = str_replace( '###OLD_EMAIL###', $old_email, $email_change_email['message'] );
  5266. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $new_email, $email_change_email['message'] );
  5267. $email_change_email['message'] = str_replace( '###SITENAME###', $site_name, $email_change_email['message'] );
  5268. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  5269. wp_mail( $email_change_email['to'], sprintf(
  5270. $email_change_email['subject'],
  5271. $site_name
  5272. ), $email_change_email['message'], $email_change_email['headers'] );
  5273. }
  5274. /**
  5275. * Return an anonymized IPv4 or IPv6 address.
  5276. *
  5277. * @since 4.9.6 Abstracted from `WP_Community_Events::get_unsafe_client_ip()`.
  5278. *
  5279. * @param string $ip_addr The IPv4 or IPv6 address to be anonymized.
  5280. * @param bool $ipv6_fallback Optional. Whether to return the original IPv6 address if the needed functions
  5281. * to anonymize it are not present. Default false, return `::` (unspecified address).
  5282. * @return string The anonymized IP address.
  5283. */
  5284. function wp_privacy_anonymize_ip( $ip_addr, $ipv6_fallback = false ) {
  5285. // Detect what kind of IP address this is.
  5286. $ip_prefix = '';
  5287. $is_ipv6 = substr_count( $ip_addr, ':' ) > 1;
  5288. $is_ipv4 = ( 3 === substr_count( $ip_addr, '.' ) );
  5289. if ( $is_ipv6 && $is_ipv4 ) {
  5290. // IPv6 compatibility mode, temporarily strip the IPv6 part, and treat it like IPv4.
  5291. $ip_prefix = '::ffff:';
  5292. $ip_addr = preg_replace( '/^\[?[0-9a-f:]*:/i', '', $ip_addr );
  5293. $ip_addr = str_replace( ']', '', $ip_addr );
  5294. $is_ipv6 = false;
  5295. }
  5296. if ( $is_ipv6 ) {
  5297. // IPv6 addresses will always be enclosed in [] if there's a port.
  5298. $left_bracket = strpos( $ip_addr, '[' );
  5299. $right_bracket = strpos( $ip_addr, ']' );
  5300. $percent = strpos( $ip_addr, '%' );
  5301. $netmask = 'ffff:ffff:ffff:ffff:0000:0000:0000:0000';
  5302. // Strip the port (and [] from IPv6 addresses), if they exist.
  5303. if ( false !== $left_bracket && false !== $right_bracket ) {
  5304. $ip_addr = substr( $ip_addr, $left_bracket + 1, $right_bracket - $left_bracket - 1 );
  5305. } elseif ( false !== $left_bracket || false !== $right_bracket ) {
  5306. // The IP has one bracket, but not both, so it's malformed.
  5307. return '::';
  5308. }
  5309. // Strip the reachability scope.
  5310. if ( false !== $percent ) {
  5311. $ip_addr = substr( $ip_addr, 0, $percent );
  5312. }
  5313. // No invalid characters should be left.
  5314. if ( preg_match( '/[^0-9a-f:]/i', $ip_addr ) ) {
  5315. return '::';
  5316. }
  5317. // Partially anonymize the IP by reducing it to the corresponding network ID.
  5318. if ( function_exists( 'inet_pton' ) && function_exists( 'inet_ntop' ) ) {
  5319. $ip_addr = inet_ntop( inet_pton( $ip_addr ) & inet_pton( $netmask ) );
  5320. if ( false === $ip_addr) {
  5321. return '::';
  5322. }
  5323. } elseif ( ! $ipv6_fallback ) {
  5324. return '::';
  5325. }
  5326. } elseif ( $is_ipv4 ) {
  5327. // Strip any port and partially anonymize the IP.
  5328. $last_octet_position = strrpos( $ip_addr, '.' );
  5329. $ip_addr = substr( $ip_addr, 0, $last_octet_position ) . '.0';
  5330. } else {
  5331. return '0.0.0.0';
  5332. }
  5333. // Restore the IPv6 prefix to compatibility mode addresses.
  5334. return $ip_prefix . $ip_addr;
  5335. }
  5336. /**
  5337. * Return uniform "anonymous" data by type.
  5338. *
  5339. * @since 4.9.6
  5340. *
  5341. * @param string $type The type of data to be anonymized.
  5342. * @param string $data Optional The data to be anonymized.
  5343. * @return string The anonymous data for the requested type.
  5344. */
  5345. function wp_privacy_anonymize_data( $type, $data = '' ) {
  5346. switch ( $type ) {
  5347. case 'email':
  5348. $anonymous = 'deleted@site.invalid';
  5349. break;
  5350. case 'url':
  5351. $anonymous = 'https://site.invalid';
  5352. break;
  5353. case 'ip':
  5354. $anonymous = wp_privacy_anonymize_ip( $data );
  5355. break;
  5356. case 'date':
  5357. $anonymous = '0000-00-00 00:00:00';
  5358. break;
  5359. case 'text':
  5360. /* translators: deleted text */
  5361. $anonymous = __( '[deleted]' );
  5362. break;
  5363. case 'longtext':
  5364. /* translators: deleted long text */
  5365. $anonymous = __( 'This content was deleted by the author.' );
  5366. break;
  5367. default:
  5368. $anonymous = '';
  5369. }
  5370. /**
  5371. * Filters the anonymous data for each type.
  5372. *
  5373. * @since 4.9.6
  5374. *
  5375. * @param string $anonymous Anonymized data.
  5376. * @param string $type Type of the data.
  5377. * @param string $data Original data.
  5378. */
  5379. return apply_filters( 'wp_privacy_anonymize_data', $anonymous, $type, $data );
  5380. }
  5381. /**
  5382. * Returns the directory used to store personal data export files.
  5383. *
  5384. * @since 4.9.6
  5385. *
  5386. * @see wp_privacy_exports_url
  5387. *
  5388. * @return string Exports directory.
  5389. */
  5390. function wp_privacy_exports_dir() {
  5391. $upload_dir = wp_upload_dir();
  5392. $exports_dir = trailingslashit( $upload_dir['basedir'] ) . 'wp-personal-data-exports/';
  5393. /**
  5394. * Filters the directory used to store personal data export files.
  5395. *
  5396. * @since 4.9.6
  5397. *
  5398. * @param string $exports_dir Exports directory.
  5399. */
  5400. return apply_filters( 'wp_privacy_exports_dir', $exports_dir );
  5401. }
  5402. /**
  5403. * Returns the URL of the directory used to store personal data export files.
  5404. *
  5405. * @since 4.9.6
  5406. *
  5407. * @see wp_privacy_exports_dir
  5408. *
  5409. * @return string Exports directory URL.
  5410. */
  5411. function wp_privacy_exports_url() {
  5412. $upload_dir = wp_upload_dir();
  5413. $exports_url = trailingslashit( $upload_dir['baseurl'] ) . 'wp-personal-data-exports/';
  5414. /**
  5415. * Filters the URL of the directory used to store personal data export files.
  5416. *
  5417. * @since 4.9.6
  5418. *
  5419. * @param string $exports_url Exports directory URL.
  5420. */
  5421. return apply_filters( 'wp_privacy_exports_url', $exports_url );
  5422. }
  5423. /**
  5424. * Schedule a `WP_Cron` job to delete expired export files.
  5425. *
  5426. * @since 4.9.6
  5427. */
  5428. function wp_schedule_delete_old_privacy_export_files() {
  5429. if ( wp_installing() ) {
  5430. return;
  5431. }
  5432. if ( ! wp_next_scheduled( 'wp_privacy_delete_old_export_files' ) ) {
  5433. wp_schedule_event( time(), 'hourly', 'wp_privacy_delete_old_export_files' );
  5434. }
  5435. }
  5436. /**
  5437. * Cleans up export files older than three days old.
  5438. *
  5439. * The export files are stored in `wp-content/uploads`, and are therefore publicly
  5440. * accessible. A CSPRN is appended to the filename to mitigate the risk of an
  5441. * unauthorized person downloading the file, but it is still possible. Deleting
  5442. * the file after the data subject has had a chance to delete it adds an additional
  5443. * layer of protection.
  5444. *
  5445. * @since 4.9.6
  5446. */
  5447. function wp_privacy_delete_old_export_files() {
  5448. require_once( ABSPATH . 'wp-admin/includes/file.php' );
  5449. $exports_dir = wp_privacy_exports_dir();
  5450. $export_files = list_files( $exports_dir, 100, array( 'index.html' ) );
  5451. /**
  5452. * Filters the lifetime, in seconds, of a personal data export file.
  5453. *
  5454. * By default, the lifetime is 3 days. Once the file reaches that age, it will automatically
  5455. * be deleted by a cron job.
  5456. *
  5457. * @since 4.9.6
  5458. *
  5459. * @param int $expiration The expiration age of the export, in seconds.
  5460. */
  5461. $expiration = apply_filters( 'wp_privacy_export_expiration', 3 * DAY_IN_SECONDS );
  5462. foreach ( (array) $export_files as $export_file ) {
  5463. $file_age_in_seconds = time() - filemtime( $export_file );
  5464. if ( $expiration < $file_age_in_seconds ) {
  5465. unlink( $export_file );
  5466. }
  5467. }
  5468. }