functions.php 254 KB

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