Nav apraksta

class-wp-customize-manager.php 197KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122
  1. <?php
  2. /**
  3. * WordPress Customize Manager classes
  4. *
  5. * @package WordPress
  6. * @subpackage Customize
  7. * @since 3.4.0
  8. */
  9. /**
  10. * Customize Manager class.
  11. *
  12. * Bootstraps the Customize experience on the server-side.
  13. *
  14. * Sets up the theme-switching process if a theme other than the active one is
  15. * being previewed and customized.
  16. *
  17. * Serves as a factory for Customize Controls and Settings, and
  18. * instantiates default Customize Controls and Settings.
  19. *
  20. * @since 3.4.0
  21. */
  22. final class WP_Customize_Manager {
  23. /**
  24. * An instance of the theme being previewed.
  25. *
  26. * @since 3.4.0
  27. * @var WP_Theme
  28. */
  29. protected $theme;
  30. /**
  31. * The directory name of the previously active theme (within the theme_root).
  32. *
  33. * @since 3.4.0
  34. * @var string
  35. */
  36. protected $original_stylesheet;
  37. /**
  38. * Whether this is a Customizer pageload.
  39. *
  40. * @since 3.4.0
  41. * @var bool
  42. */
  43. protected $previewing = false;
  44. /**
  45. * Methods and properties dealing with managing widgets in the Customizer.
  46. *
  47. * @since 3.9.0
  48. * @var WP_Customize_Widgets
  49. */
  50. public $widgets;
  51. /**
  52. * Methods and properties dealing with managing nav menus in the Customizer.
  53. *
  54. * @since 4.3.0
  55. * @var WP_Customize_Nav_Menus
  56. */
  57. public $nav_menus;
  58. /**
  59. * Methods and properties dealing with selective refresh in the Customizer preview.
  60. *
  61. * @since 4.5.0
  62. * @var WP_Customize_Selective_Refresh
  63. */
  64. public $selective_refresh;
  65. /**
  66. * Registered instances of WP_Customize_Setting.
  67. *
  68. * @since 3.4.0
  69. * @var array
  70. */
  71. protected $settings = array();
  72. /**
  73. * Sorted top-level instances of WP_Customize_Panel and WP_Customize_Section.
  74. *
  75. * @since 4.0.0
  76. * @var array
  77. */
  78. protected $containers = array();
  79. /**
  80. * Registered instances of WP_Customize_Panel.
  81. *
  82. * @since 4.0.0
  83. * @var array
  84. */
  85. protected $panels = array();
  86. /**
  87. * List of core components.
  88. *
  89. * @since 4.5.0
  90. * @var array
  91. */
  92. protected $components = array( 'widgets', 'nav_menus' );
  93. /**
  94. * Registered instances of WP_Customize_Section.
  95. *
  96. * @since 3.4.0
  97. * @var array
  98. */
  99. protected $sections = array();
  100. /**
  101. * Registered instances of WP_Customize_Control.
  102. *
  103. * @since 3.4.0
  104. * @var array
  105. */
  106. protected $controls = array();
  107. /**
  108. * Panel types that may be rendered from JS templates.
  109. *
  110. * @since 4.3.0
  111. * @var array
  112. */
  113. protected $registered_panel_types = array();
  114. /**
  115. * Section types that may be rendered from JS templates.
  116. *
  117. * @since 4.3.0
  118. * @var array
  119. */
  120. protected $registered_section_types = array();
  121. /**
  122. * Control types that may be rendered from JS templates.
  123. *
  124. * @since 4.1.0
  125. * @var array
  126. */
  127. protected $registered_control_types = array();
  128. /**
  129. * Initial URL being previewed.
  130. *
  131. * @since 4.4.0
  132. * @var string
  133. */
  134. protected $preview_url;
  135. /**
  136. * URL to link the user to when closing the Customizer.
  137. *
  138. * @since 4.4.0
  139. * @var string
  140. */
  141. protected $return_url;
  142. /**
  143. * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
  144. *
  145. * @since 4.4.0
  146. * @var string[]
  147. */
  148. protected $autofocus = array();
  149. /**
  150. * Messenger channel.
  151. *
  152. * @since 4.7.0
  153. * @var string
  154. */
  155. protected $messenger_channel;
  156. /**
  157. * Whether the autosave revision of the changeset should be loaded.
  158. *
  159. * @since 4.9.0
  160. * @var bool
  161. */
  162. protected $autosaved = false;
  163. /**
  164. * Whether the changeset branching is allowed.
  165. *
  166. * @since 4.9.0
  167. * @var bool
  168. */
  169. protected $branching = true;
  170. /**
  171. * Whether settings should be previewed.
  172. *
  173. * @since 4.9.0
  174. * @var bool
  175. */
  176. protected $settings_previewed = true;
  177. /**
  178. * Whether a starter content changeset was saved.
  179. *
  180. * @since 4.9.0
  181. * @var bool
  182. */
  183. protected $saved_starter_content_changeset = false;
  184. /**
  185. * Unsanitized values for Customize Settings parsed from $_POST['customized'].
  186. *
  187. * @var array
  188. */
  189. private $_post_values;
  190. /**
  191. * Changeset UUID.
  192. *
  193. * @since 4.7.0
  194. * @var string
  195. */
  196. private $_changeset_uuid;
  197. /**
  198. * Changeset post ID.
  199. *
  200. * @since 4.7.0
  201. * @var int|false
  202. */
  203. private $_changeset_post_id;
  204. /**
  205. * Changeset data loaded from a customize_changeset post.
  206. *
  207. * @since 4.7.0
  208. * @var array|null
  209. */
  210. private $_changeset_data;
  211. /**
  212. * Constructor.
  213. *
  214. * @since 3.4.0
  215. * @since 4.7.0 Added `$args` parameter.
  216. *
  217. * @param array $args {
  218. * Args.
  219. *
  220. * @type null|string|false $changeset_uuid Changeset UUID, the `post_name` for the customize_changeset post containing the customized state.
  221. * Defaults to `null` resulting in a UUID to be immediately generated. If `false` is provided, then
  222. * then the changeset UUID will be determined during `after_setup_theme`: when the
  223. * `customize_changeset_branching` filter returns false, then the default UUID will be that
  224. * of the most recent `customize_changeset` post that has a status other than 'auto-draft',
  225. * 'publish', or 'trash'. Otherwise, if changeset branching is enabled, then a random UUID will be used.
  226. * @type string $theme Theme to be previewed (for theme switch). Defaults to customize_theme or theme query params.
  227. * @type string $messenger_channel Messenger channel. Defaults to customize_messenger_channel query param.
  228. * @type bool $settings_previewed If settings should be previewed. Defaults to true.
  229. * @type bool $branching If changeset branching is allowed; otherwise, changesets are linear. Defaults to true.
  230. * @type bool $autosaved If data from a changeset's autosaved revision should be loaded if it exists. Defaults to false.
  231. * }
  232. */
  233. public function __construct( $args = array() ) {
  234. $args = array_merge(
  235. array_fill_keys( array( 'changeset_uuid', 'theme', 'messenger_channel', 'settings_previewed', 'autosaved', 'branching' ), null ),
  236. $args
  237. );
  238. // Note that the UUID format will be validated in the setup_theme() method.
  239. if ( ! isset( $args['changeset_uuid'] ) ) {
  240. $args['changeset_uuid'] = wp_generate_uuid4();
  241. }
  242. // The theme and messenger_channel should be supplied via $args,
  243. // but they are also looked at in the $_REQUEST global here for back-compat.
  244. if ( ! isset( $args['theme'] ) ) {
  245. if ( isset( $_REQUEST['customize_theme'] ) ) {
  246. $args['theme'] = wp_unslash( $_REQUEST['customize_theme'] );
  247. } elseif ( isset( $_REQUEST['theme'] ) ) { // Deprecated.
  248. $args['theme'] = wp_unslash( $_REQUEST['theme'] );
  249. }
  250. }
  251. if ( ! isset( $args['messenger_channel'] ) && isset( $_REQUEST['customize_messenger_channel'] ) ) {
  252. $args['messenger_channel'] = sanitize_key( wp_unslash( $_REQUEST['customize_messenger_channel'] ) );
  253. }
  254. $this->original_stylesheet = get_stylesheet();
  255. $this->theme = wp_get_theme( 0 === validate_file( $args['theme'] ) ? $args['theme'] : null );
  256. $this->messenger_channel = $args['messenger_channel'];
  257. $this->_changeset_uuid = $args['changeset_uuid'];
  258. foreach ( array( 'settings_previewed', 'autosaved', 'branching' ) as $key ) {
  259. if ( isset( $args[ $key ] ) ) {
  260. $this->$key = (bool) $args[ $key ];
  261. }
  262. }
  263. require_once ABSPATH . WPINC . '/class-wp-customize-setting.php';
  264. require_once ABSPATH . WPINC . '/class-wp-customize-panel.php';
  265. require_once ABSPATH . WPINC . '/class-wp-customize-section.php';
  266. require_once ABSPATH . WPINC . '/class-wp-customize-control.php';
  267. require_once ABSPATH . WPINC . '/customize/class-wp-customize-color-control.php';
  268. require_once ABSPATH . WPINC . '/customize/class-wp-customize-media-control.php';
  269. require_once ABSPATH . WPINC . '/customize/class-wp-customize-upload-control.php';
  270. require_once ABSPATH . WPINC . '/customize/class-wp-customize-image-control.php';
  271. require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-control.php';
  272. require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-position-control.php';
  273. require_once ABSPATH . WPINC . '/customize/class-wp-customize-cropped-image-control.php';
  274. require_once ABSPATH . WPINC . '/customize/class-wp-customize-site-icon-control.php';
  275. require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-control.php';
  276. require_once ABSPATH . WPINC . '/customize/class-wp-customize-theme-control.php';
  277. require_once ABSPATH . WPINC . '/customize/class-wp-customize-code-editor-control.php';
  278. require_once ABSPATH . WPINC . '/customize/class-wp-widget-area-customize-control.php';
  279. require_once ABSPATH . WPINC . '/customize/class-wp-widget-form-customize-control.php';
  280. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-control.php';
  281. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-control.php';
  282. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-location-control.php';
  283. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-name-control.php';
  284. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-locations-control.php';
  285. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-auto-add-control.php';
  286. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menus-panel.php';
  287. require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-panel.php';
  288. require_once ABSPATH . WPINC . '/customize/class-wp-customize-themes-section.php';
  289. require_once ABSPATH . WPINC . '/customize/class-wp-customize-sidebar-section.php';
  290. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-section.php';
  291. require_once ABSPATH . WPINC . '/customize/class-wp-customize-custom-css-setting.php';
  292. require_once ABSPATH . WPINC . '/customize/class-wp-customize-filter-setting.php';
  293. require_once ABSPATH . WPINC . '/customize/class-wp-customize-header-image-setting.php';
  294. require_once ABSPATH . WPINC . '/customize/class-wp-customize-background-image-setting.php';
  295. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-item-setting.php';
  296. require_once ABSPATH . WPINC . '/customize/class-wp-customize-nav-menu-setting.php';
  297. /**
  298. * Filters the core Customizer components to load.
  299. *
  300. * This allows Core components to be excluded from being instantiated by
  301. * filtering them out of the array. Note that this filter generally runs
  302. * during the {@see 'plugins_loaded'} action, so it cannot be added
  303. * in a theme.
  304. *
  305. * @since 4.4.0
  306. *
  307. * @see WP_Customize_Manager::__construct()
  308. *
  309. * @param string[] $components Array of core components to load.
  310. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  311. */
  312. $components = apply_filters( 'customize_loaded_components', $this->components, $this );
  313. require_once ABSPATH . WPINC . '/customize/class-wp-customize-selective-refresh.php';
  314. $this->selective_refresh = new WP_Customize_Selective_Refresh( $this );
  315. if ( in_array( 'widgets', $components, true ) ) {
  316. require_once ABSPATH . WPINC . '/class-wp-customize-widgets.php';
  317. $this->widgets = new WP_Customize_Widgets( $this );
  318. }
  319. if ( in_array( 'nav_menus', $components, true ) ) {
  320. require_once ABSPATH . WPINC . '/class-wp-customize-nav-menus.php';
  321. $this->nav_menus = new WP_Customize_Nav_Menus( $this );
  322. }
  323. add_action( 'setup_theme', array( $this, 'setup_theme' ) );
  324. add_action( 'wp_loaded', array( $this, 'wp_loaded' ) );
  325. // Do not spawn cron (especially the alternate cron) while running the Customizer.
  326. remove_action( 'init', 'wp_cron' );
  327. // Do not run update checks when rendering the controls.
  328. remove_action( 'admin_init', '_maybe_update_core' );
  329. remove_action( 'admin_init', '_maybe_update_plugins' );
  330. remove_action( 'admin_init', '_maybe_update_themes' );
  331. add_action( 'wp_ajax_customize_save', array( $this, 'save' ) );
  332. add_action( 'wp_ajax_customize_trash', array( $this, 'handle_changeset_trash_request' ) );
  333. add_action( 'wp_ajax_customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
  334. add_action( 'wp_ajax_customize_load_themes', array( $this, 'handle_load_themes_request' ) );
  335. add_filter( 'heartbeat_settings', array( $this, 'add_customize_screen_to_heartbeat_settings' ) );
  336. add_filter( 'heartbeat_received', array( $this, 'check_changeset_lock_with_heartbeat' ), 10, 3 );
  337. add_action( 'wp_ajax_customize_override_changeset_lock', array( $this, 'handle_override_changeset_lock_request' ) );
  338. add_action( 'wp_ajax_customize_dismiss_autosave_or_lock', array( $this, 'handle_dismiss_autosave_or_lock_request' ) );
  339. add_action( 'customize_register', array( $this, 'register_controls' ) );
  340. add_action( 'customize_register', array( $this, 'register_dynamic_settings' ), 11 ); // Allow code to create settings first.
  341. add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) );
  342. add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) );
  343. // Render Common, Panel, Section, and Control templates.
  344. add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_panel_templates' ), 1 );
  345. add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_section_templates' ), 1 );
  346. add_action( 'customize_controls_print_footer_scripts', array( $this, 'render_control_templates' ), 1 );
  347. // Export header video settings with the partial response.
  348. add_filter( 'customize_render_partials_response', array( $this, 'export_header_video_settings' ), 10, 3 );
  349. // Export the settings to JS via the _wpCustomizeSettings variable.
  350. add_action( 'customize_controls_print_footer_scripts', array( $this, 'customize_pane_settings' ), 1000 );
  351. // Add theme update notices.
  352. if ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) ) {
  353. require_once ABSPATH . 'wp-admin/includes/update.php';
  354. add_action( 'customize_controls_print_footer_scripts', 'wp_print_admin_notice_templates' );
  355. }
  356. }
  357. /**
  358. * Returns true if it's an Ajax request.
  359. *
  360. * @since 3.4.0
  361. * @since 4.2.0 Added `$action` param.
  362. *
  363. * @param string|null $action Whether the supplied Ajax action is being run.
  364. * @return bool True if it's an Ajax request, false otherwise.
  365. */
  366. public function doing_ajax( $action = null ) {
  367. if ( ! wp_doing_ajax() ) {
  368. return false;
  369. }
  370. if ( ! $action ) {
  371. return true;
  372. } else {
  373. /*
  374. * Note: we can't just use doing_action( "wp_ajax_{$action}" ) because we need
  375. * to check before admin-ajax.php gets to that point.
  376. */
  377. return isset( $_REQUEST['action'] ) && wp_unslash( $_REQUEST['action'] ) === $action;
  378. }
  379. }
  380. /**
  381. * Custom wp_die wrapper. Returns either the standard message for UI
  382. * or the Ajax message.
  383. *
  384. * @since 3.4.0
  385. *
  386. * @param string|WP_Error $ajax_message Ajax return.
  387. * @param string $message Optional. UI message.
  388. */
  389. protected function wp_die( $ajax_message, $message = null ) {
  390. if ( $this->doing_ajax() ) {
  391. wp_die( $ajax_message );
  392. }
  393. if ( ! $message ) {
  394. $message = __( 'Something went wrong.' );
  395. }
  396. if ( $this->messenger_channel ) {
  397. ob_start();
  398. wp_enqueue_scripts();
  399. wp_print_scripts( array( 'customize-base' ) );
  400. $settings = array(
  401. 'messengerArgs' => array(
  402. 'channel' => $this->messenger_channel,
  403. 'url' => wp_customize_url(),
  404. ),
  405. 'error' => $ajax_message,
  406. );
  407. ?>
  408. <script>
  409. ( function( api, settings ) {
  410. var preview = new api.Messenger( settings.messengerArgs );
  411. preview.send( 'iframe-loading-error', settings.error );
  412. } )( wp.customize, <?php echo wp_json_encode( $settings ); ?> );
  413. </script>
  414. <?php
  415. $message .= ob_get_clean();
  416. }
  417. wp_die( $message );
  418. }
  419. /**
  420. * Returns the Ajax wp_die() handler if it's a customized request.
  421. *
  422. * @since 3.4.0
  423. * @deprecated 4.7.0
  424. *
  425. * @return callable Die handler.
  426. */
  427. public function wp_die_handler() {
  428. _deprecated_function( __METHOD__, '4.7.0' );
  429. if ( $this->doing_ajax() || isset( $_POST['customized'] ) ) {
  430. return '_ajax_wp_die_handler';
  431. }
  432. return '_default_wp_die_handler';
  433. }
  434. /**
  435. * Starts preview and customize theme.
  436. *
  437. * Check if customize query variable exist. Init filters to filter the active theme.
  438. *
  439. * @since 3.4.0
  440. *
  441. * @global string $pagenow The filename of the current screen.
  442. */
  443. public function setup_theme() {
  444. global $pagenow;
  445. // Check permissions for customize.php access since this method is called before customize.php can run any code.
  446. if ( 'customize.php' === $pagenow && ! current_user_can( 'customize' ) ) {
  447. if ( ! is_user_logged_in() ) {
  448. auth_redirect();
  449. } else {
  450. wp_die(
  451. '<h1>' . __( 'You need a higher level of permission.' ) . '</h1>' .
  452. '<p>' . __( 'Sorry, you are not allowed to customize this site.' ) . '</p>',
  453. 403
  454. );
  455. }
  456. return;
  457. }
  458. // If a changeset was provided is invalid.
  459. if ( isset( $this->_changeset_uuid ) && false !== $this->_changeset_uuid && ! wp_is_uuid( $this->_changeset_uuid ) ) {
  460. $this->wp_die( -1, __( 'Invalid changeset UUID' ) );
  461. }
  462. /*
  463. * Clear incoming post data if the user lacks a CSRF token (nonce). Note that the customizer
  464. * application will inject the customize_preview_nonce query parameter into all Ajax requests.
  465. * For similar behavior elsewhere in WordPress, see rest_cookie_check_errors() which logs out
  466. * a user when a valid nonce isn't present.
  467. */
  468. $has_post_data_nonce = (
  469. check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce', false )
  470. ||
  471. check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce', false )
  472. ||
  473. check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'customize_preview_nonce', false )
  474. );
  475. if ( ! current_user_can( 'customize' ) || ! $has_post_data_nonce ) {
  476. unset( $_POST['customized'] );
  477. unset( $_REQUEST['customized'] );
  478. }
  479. /*
  480. * If unauthenticated then require a valid changeset UUID to load the preview.
  481. * In this way, the UUID serves as a secret key. If the messenger channel is present,
  482. * then send unauthenticated code to prompt re-auth.
  483. */
  484. if ( ! current_user_can( 'customize' ) && ! $this->changeset_post_id() ) {
  485. $this->wp_die( $this->messenger_channel ? 0 : -1, __( 'Non-existent changeset UUID.' ) );
  486. }
  487. if ( ! headers_sent() ) {
  488. send_origin_headers();
  489. }
  490. // Hide the admin bar if we're embedded in the customizer iframe.
  491. if ( $this->messenger_channel ) {
  492. show_admin_bar( false );
  493. }
  494. if ( $this->is_theme_active() ) {
  495. // Once the theme is loaded, we'll validate it.
  496. add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) );
  497. } else {
  498. // If the requested theme is not the active theme and the user doesn't have
  499. // the switch_themes cap, bail.
  500. if ( ! current_user_can( 'switch_themes' ) ) {
  501. $this->wp_die( -1, __( 'Sorry, you are not allowed to edit theme options on this site.' ) );
  502. }
  503. // If the theme has errors while loading, bail.
  504. if ( $this->theme()->errors() ) {
  505. $this->wp_die( -1, $this->theme()->errors()->get_error_message() );
  506. }
  507. // If the theme isn't allowed per multisite settings, bail.
  508. if ( ! $this->theme()->is_allowed() ) {
  509. $this->wp_die( -1, __( 'The requested theme does not exist.' ) );
  510. }
  511. }
  512. // Make sure changeset UUID is established immediately after the theme is loaded.
  513. add_action( 'after_setup_theme', array( $this, 'establish_loaded_changeset' ), 5 );
  514. /*
  515. * Import theme starter content for fresh installations when landing in the customizer.
  516. * Import starter content at after_setup_theme:100 so that any
  517. * add_theme_support( 'starter-content' ) calls will have been made.
  518. */
  519. if ( get_option( 'fresh_site' ) && 'customize.php' === $pagenow ) {
  520. add_action( 'after_setup_theme', array( $this, 'import_theme_starter_content' ), 100 );
  521. }
  522. $this->start_previewing_theme();
  523. }
  524. /**
  525. * Establishes the loaded changeset.
  526. *
  527. * This method runs right at after_setup_theme and applies the 'customize_changeset_branching' filter to determine
  528. * whether concurrent changesets are allowed. Then if the Customizer is not initialized with a `changeset_uuid` param,
  529. * this method will determine which UUID should be used. If changeset branching is disabled, then the most saved
  530. * changeset will be loaded by default. Otherwise, if there are no existing saved changesets or if changeset branching is
  531. * enabled, then a new UUID will be generated.
  532. *
  533. * @since 4.9.0
  534. *
  535. * @global string $pagenow The filename of the current screen.
  536. */
  537. public function establish_loaded_changeset() {
  538. global $pagenow;
  539. if ( empty( $this->_changeset_uuid ) ) {
  540. $changeset_uuid = null;
  541. if ( ! $this->branching() && $this->is_theme_active() ) {
  542. $unpublished_changeset_posts = $this->get_changeset_posts(
  543. array(
  544. 'post_status' => array_diff( get_post_stati(), array( 'auto-draft', 'publish', 'trash', 'inherit', 'private' ) ),
  545. 'exclude_restore_dismissed' => false,
  546. 'author' => 'any',
  547. 'posts_per_page' => 1,
  548. 'order' => 'DESC',
  549. 'orderby' => 'date',
  550. )
  551. );
  552. $unpublished_changeset_post = array_shift( $unpublished_changeset_posts );
  553. if ( ! empty( $unpublished_changeset_post ) && wp_is_uuid( $unpublished_changeset_post->post_name ) ) {
  554. $changeset_uuid = $unpublished_changeset_post->post_name;
  555. }
  556. }
  557. // If no changeset UUID has been set yet, then generate a new one.
  558. if ( empty( $changeset_uuid ) ) {
  559. $changeset_uuid = wp_generate_uuid4();
  560. }
  561. $this->_changeset_uuid = $changeset_uuid;
  562. }
  563. if ( is_admin() && 'customize.php' === $pagenow ) {
  564. $this->set_changeset_lock( $this->changeset_post_id() );
  565. }
  566. }
  567. /**
  568. * Callback to validate a theme once it is loaded
  569. *
  570. * @since 3.4.0
  571. */
  572. public function after_setup_theme() {
  573. $doing_ajax_or_is_customized = ( $this->doing_ajax() || isset( $_POST['customized'] ) );
  574. if ( ! $doing_ajax_or_is_customized && ! validate_current_theme() ) {
  575. wp_redirect( 'themes.php?broken=true' );
  576. exit;
  577. }
  578. }
  579. /**
  580. * If the theme to be previewed isn't the active theme, add filter callbacks
  581. * to swap it out at runtime.
  582. *
  583. * @since 3.4.0
  584. */
  585. public function start_previewing_theme() {
  586. // Bail if we're already previewing.
  587. if ( $this->is_preview() ) {
  588. return;
  589. }
  590. $this->previewing = true;
  591. if ( ! $this->is_theme_active() ) {
  592. add_filter( 'template', array( $this, 'get_template' ) );
  593. add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
  594. add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
  595. // @link: https://core.trac.wordpress.org/ticket/20027
  596. add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
  597. add_filter( 'pre_option_template', array( $this, 'get_template' ) );
  598. // Handle custom theme roots.
  599. add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
  600. add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
  601. }
  602. /**
  603. * Fires once the Customizer theme preview has started.
  604. *
  605. * @since 3.4.0
  606. *
  607. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  608. */
  609. do_action( 'start_previewing_theme', $this );
  610. }
  611. /**
  612. * Stops previewing the selected theme.
  613. *
  614. * Removes filters to change the active theme.
  615. *
  616. * @since 3.4.0
  617. */
  618. public function stop_previewing_theme() {
  619. if ( ! $this->is_preview() ) {
  620. return;
  621. }
  622. $this->previewing = false;
  623. if ( ! $this->is_theme_active() ) {
  624. remove_filter( 'template', array( $this, 'get_template' ) );
  625. remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) );
  626. remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) );
  627. // @link: https://core.trac.wordpress.org/ticket/20027
  628. remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) );
  629. remove_filter( 'pre_option_template', array( $this, 'get_template' ) );
  630. // Handle custom theme roots.
  631. remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) );
  632. remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) );
  633. }
  634. /**
  635. * Fires once the Customizer theme preview has stopped.
  636. *
  637. * @since 3.4.0
  638. *
  639. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  640. */
  641. do_action( 'stop_previewing_theme', $this );
  642. }
  643. /**
  644. * Gets whether settings are or will be previewed.
  645. *
  646. * @since 4.9.0
  647. *
  648. * @see WP_Customize_Setting::preview()
  649. *
  650. * @return bool
  651. */
  652. public function settings_previewed() {
  653. return $this->settings_previewed;
  654. }
  655. /**
  656. * Gets whether data from a changeset's autosaved revision should be loaded if it exists.
  657. *
  658. * @since 4.9.0
  659. *
  660. * @see WP_Customize_Manager::changeset_data()
  661. *
  662. * @return bool Is using autosaved changeset revision.
  663. */
  664. public function autosaved() {
  665. return $this->autosaved;
  666. }
  667. /**
  668. * Whether the changeset branching is allowed.
  669. *
  670. * @since 4.9.0
  671. *
  672. * @see WP_Customize_Manager::establish_loaded_changeset()
  673. *
  674. * @return bool Is changeset branching.
  675. */
  676. public function branching() {
  677. /**
  678. * Filters whether or not changeset branching is allowed.
  679. *
  680. * By default in core, when changeset branching is not allowed, changesets will operate
  681. * linearly in that only one saved changeset will exist at a time (with a 'draft' or
  682. * 'future' status). This makes the Customizer operate in a way that is similar to going to
  683. * "edit" to one existing post: all users will be making changes to the same post, and autosave
  684. * revisions will be made for that post.
  685. *
  686. * By contrast, when changeset branching is allowed, then the model is like users going
  687. * to "add new" for a page and each user makes changes independently of each other since
  688. * they are all operating on their own separate pages, each getting their own separate
  689. * initial auto-drafts and then once initially saved, autosave revisions on top of that
  690. * user's specific post.
  691. *
  692. * Since linear changesets are deemed to be more suitable for the majority of WordPress users,
  693. * they are the default. For WordPress sites that have heavy site management in the Customizer
  694. * by multiple users then branching changesets should be enabled by means of this filter.
  695. *
  696. * @since 4.9.0
  697. *
  698. * @param bool $allow_branching Whether branching is allowed. If `false`, the default,
  699. * then only one saved changeset exists at a time.
  700. * @param WP_Customize_Manager $wp_customize Manager instance.
  701. */
  702. $this->branching = apply_filters( 'customize_changeset_branching', $this->branching, $this );
  703. return $this->branching;
  704. }
  705. /**
  706. * Gets the changeset UUID.
  707. *
  708. * @since 4.7.0
  709. *
  710. * @see WP_Customize_Manager::establish_loaded_changeset()
  711. *
  712. * @return string UUID.
  713. */
  714. public function changeset_uuid() {
  715. if ( empty( $this->_changeset_uuid ) ) {
  716. $this->establish_loaded_changeset();
  717. }
  718. return $this->_changeset_uuid;
  719. }
  720. /**
  721. * Gets the theme being customized.
  722. *
  723. * @since 3.4.0
  724. *
  725. * @return WP_Theme
  726. */
  727. public function theme() {
  728. if ( ! $this->theme ) {
  729. $this->theme = wp_get_theme();
  730. }
  731. return $this->theme;
  732. }
  733. /**
  734. * Gets the registered settings.
  735. *
  736. * @since 3.4.0
  737. *
  738. * @return array
  739. */
  740. public function settings() {
  741. return $this->settings;
  742. }
  743. /**
  744. * Gets the registered controls.
  745. *
  746. * @since 3.4.0
  747. *
  748. * @return array
  749. */
  750. public function controls() {
  751. return $this->controls;
  752. }
  753. /**
  754. * Gets the registered containers.
  755. *
  756. * @since 4.0.0
  757. *
  758. * @return array
  759. */
  760. public function containers() {
  761. return $this->containers;
  762. }
  763. /**
  764. * Gets the registered sections.
  765. *
  766. * @since 3.4.0
  767. *
  768. * @return array
  769. */
  770. public function sections() {
  771. return $this->sections;
  772. }
  773. /**
  774. * Gets the registered panels.
  775. *
  776. * @since 4.0.0
  777. *
  778. * @return array Panels.
  779. */
  780. public function panels() {
  781. return $this->panels;
  782. }
  783. /**
  784. * Checks if the current theme is active.
  785. *
  786. * @since 3.4.0
  787. *
  788. * @return bool
  789. */
  790. public function is_theme_active() {
  791. return $this->get_stylesheet() === $this->original_stylesheet;
  792. }
  793. /**
  794. * Registers styles/scripts and initialize the preview of each setting
  795. *
  796. * @since 3.4.0
  797. */
  798. public function wp_loaded() {
  799. // Unconditionally register core types for panels, sections, and controls
  800. // in case plugin unhooks all customize_register actions.
  801. $this->register_panel_type( 'WP_Customize_Panel' );
  802. $this->register_panel_type( 'WP_Customize_Themes_Panel' );
  803. $this->register_section_type( 'WP_Customize_Section' );
  804. $this->register_section_type( 'WP_Customize_Sidebar_Section' );
  805. $this->register_section_type( 'WP_Customize_Themes_Section' );
  806. $this->register_control_type( 'WP_Customize_Color_Control' );
  807. $this->register_control_type( 'WP_Customize_Media_Control' );
  808. $this->register_control_type( 'WP_Customize_Upload_Control' );
  809. $this->register_control_type( 'WP_Customize_Image_Control' );
  810. $this->register_control_type( 'WP_Customize_Background_Image_Control' );
  811. $this->register_control_type( 'WP_Customize_Background_Position_Control' );
  812. $this->register_control_type( 'WP_Customize_Cropped_Image_Control' );
  813. $this->register_control_type( 'WP_Customize_Site_Icon_Control' );
  814. $this->register_control_type( 'WP_Customize_Theme_Control' );
  815. $this->register_control_type( 'WP_Customize_Code_Editor_Control' );
  816. $this->register_control_type( 'WP_Customize_Date_Time_Control' );
  817. /**
  818. * Fires once WordPress has loaded, allowing scripts and styles to be initialized.
  819. *
  820. * @since 3.4.0
  821. *
  822. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  823. */
  824. do_action( 'customize_register', $this );
  825. if ( $this->settings_previewed() ) {
  826. foreach ( $this->settings as $setting ) {
  827. $setting->preview();
  828. }
  829. }
  830. if ( $this->is_preview() && ! is_admin() ) {
  831. $this->customize_preview_init();
  832. }
  833. }
  834. /**
  835. * Prevents Ajax requests from following redirects when previewing a theme
  836. * by issuing a 200 response instead of a 30x.
  837. *
  838. * Instead, the JS will sniff out the location header.
  839. *
  840. * @since 3.4.0
  841. * @deprecated 4.7.0
  842. *
  843. * @param int $status Status.
  844. * @return int
  845. */
  846. public function wp_redirect_status( $status ) {
  847. _deprecated_function( __FUNCTION__, '4.7.0' );
  848. if ( $this->is_preview() && ! is_admin() ) {
  849. return 200;
  850. }
  851. return $status;
  852. }
  853. /**
  854. * Finds the changeset post ID for a given changeset UUID.
  855. *
  856. * @since 4.7.0
  857. *
  858. * @param string $uuid Changeset UUID.
  859. * @return int|null Returns post ID on success and null on failure.
  860. */
  861. public function find_changeset_post_id( $uuid ) {
  862. $cache_group = 'customize_changeset_post';
  863. $changeset_post_id = wp_cache_get( $uuid, $cache_group );
  864. if ( $changeset_post_id && 'customize_changeset' === get_post_type( $changeset_post_id ) ) {
  865. return $changeset_post_id;
  866. }
  867. $changeset_post_query = new WP_Query(
  868. array(
  869. 'post_type' => 'customize_changeset',
  870. 'post_status' => get_post_stati(),
  871. 'name' => $uuid,
  872. 'posts_per_page' => 1,
  873. 'no_found_rows' => true,
  874. 'cache_results' => true,
  875. 'update_post_meta_cache' => false,
  876. 'update_post_term_cache' => false,
  877. 'lazy_load_term_meta' => false,
  878. )
  879. );
  880. if ( ! empty( $changeset_post_query->posts ) ) {
  881. // Note: 'fields'=>'ids' is not being used in order to cache the post object as it will be needed.
  882. $changeset_post_id = $changeset_post_query->posts[0]->ID;
  883. wp_cache_set( $uuid, $changeset_post_id, $cache_group );
  884. return $changeset_post_id;
  885. }
  886. return null;
  887. }
  888. /**
  889. * Gets changeset posts.
  890. *
  891. * @since 4.9.0
  892. *
  893. * @param array $args {
  894. * Args to pass into `get_posts()` to query changesets.
  895. *
  896. * @type int $posts_per_page Number of posts to return. Defaults to -1 (all posts).
  897. * @type int $author Post author. Defaults to current user.
  898. * @type string $post_status Status of changeset. Defaults to 'auto-draft'.
  899. * @type bool $exclude_restore_dismissed Whether to exclude changeset auto-drafts that have been dismissed. Defaults to true.
  900. * }
  901. * @return WP_Post[] Auto-draft changesets.
  902. */
  903. protected function get_changeset_posts( $args = array() ) {
  904. $default_args = array(
  905. 'exclude_restore_dismissed' => true,
  906. 'posts_per_page' => -1,
  907. 'post_type' => 'customize_changeset',
  908. 'post_status' => 'auto-draft',
  909. 'order' => 'DESC',
  910. 'orderby' => 'date',
  911. 'no_found_rows' => true,
  912. 'cache_results' => true,
  913. 'update_post_meta_cache' => false,
  914. 'update_post_term_cache' => false,
  915. 'lazy_load_term_meta' => false,
  916. );
  917. if ( get_current_user_id() ) {
  918. $default_args['author'] = get_current_user_id();
  919. }
  920. $args = array_merge( $default_args, $args );
  921. if ( ! empty( $args['exclude_restore_dismissed'] ) ) {
  922. unset( $args['exclude_restore_dismissed'] );
  923. $args['meta_query'] = array(
  924. array(
  925. 'key' => '_customize_restore_dismissed',
  926. 'compare' => 'NOT EXISTS',
  927. ),
  928. );
  929. }
  930. return get_posts( $args );
  931. }
  932. /**
  933. * Dismisses all of the current user's auto-drafts (other than the present one).
  934. *
  935. * @since 4.9.0
  936. * @return int The number of auto-drafts that were dismissed.
  937. */
  938. protected function dismiss_user_auto_draft_changesets() {
  939. $changeset_autodraft_posts = $this->get_changeset_posts(
  940. array(
  941. 'post_status' => 'auto-draft',
  942. 'exclude_restore_dismissed' => true,
  943. 'posts_per_page' => -1,
  944. )
  945. );
  946. $dismissed = 0;
  947. foreach ( $changeset_autodraft_posts as $autosave_autodraft_post ) {
  948. if ( $autosave_autodraft_post->ID === $this->changeset_post_id() ) {
  949. continue;
  950. }
  951. if ( update_post_meta( $autosave_autodraft_post->ID, '_customize_restore_dismissed', true ) ) {
  952. $dismissed++;
  953. }
  954. }
  955. return $dismissed;
  956. }
  957. /**
  958. * Gets the changeset post ID for the loaded changeset.
  959. *
  960. * @since 4.7.0
  961. *
  962. * @return int|null Post ID on success or null if there is no post yet saved.
  963. */
  964. public function changeset_post_id() {
  965. if ( ! isset( $this->_changeset_post_id ) ) {
  966. $post_id = $this->find_changeset_post_id( $this->changeset_uuid() );
  967. if ( ! $post_id ) {
  968. $post_id = false;
  969. }
  970. $this->_changeset_post_id = $post_id;
  971. }
  972. if ( false === $this->_changeset_post_id ) {
  973. return null;
  974. }
  975. return $this->_changeset_post_id;
  976. }
  977. /**
  978. * Gets the data stored in a changeset post.
  979. *
  980. * @since 4.7.0
  981. *
  982. * @param int $post_id Changeset post ID.
  983. * @return array|WP_Error Changeset data or WP_Error on error.
  984. */
  985. protected function get_changeset_post_data( $post_id ) {
  986. if ( ! $post_id ) {
  987. return new WP_Error( 'empty_post_id' );
  988. }
  989. $changeset_post = get_post( $post_id );
  990. if ( ! $changeset_post ) {
  991. return new WP_Error( 'missing_post' );
  992. }
  993. if ( 'revision' === $changeset_post->post_type ) {
  994. if ( 'customize_changeset' !== get_post_type( $changeset_post->post_parent ) ) {
  995. return new WP_Error( 'wrong_post_type' );
  996. }
  997. } elseif ( 'customize_changeset' !== $changeset_post->post_type ) {
  998. return new WP_Error( 'wrong_post_type' );
  999. }
  1000. $changeset_data = json_decode( $changeset_post->post_content, true );
  1001. $last_error = json_last_error();
  1002. if ( $last_error ) {
  1003. return new WP_Error( 'json_parse_error', '', $last_error );
  1004. }
  1005. if ( ! is_array( $changeset_data ) ) {
  1006. return new WP_Error( 'expected_array' );
  1007. }
  1008. return $changeset_data;
  1009. }
  1010. /**
  1011. * Gets changeset data.
  1012. *
  1013. * @since 4.7.0
  1014. * @since 4.9.0 This will return the changeset's data with a user's autosave revision merged on top, if one exists and $autosaved is true.
  1015. *
  1016. * @return array Changeset data.
  1017. */
  1018. public function changeset_data() {
  1019. if ( isset( $this->_changeset_data ) ) {
  1020. return $this->_changeset_data;
  1021. }
  1022. $changeset_post_id = $this->changeset_post_id();
  1023. if ( ! $changeset_post_id ) {
  1024. $this->_changeset_data = array();
  1025. } else {
  1026. if ( $this->autosaved() && is_user_logged_in() ) {
  1027. $autosave_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() );
  1028. if ( $autosave_post ) {
  1029. $data = $this->get_changeset_post_data( $autosave_post->ID );
  1030. if ( ! is_wp_error( $data ) ) {
  1031. $this->_changeset_data = $data;
  1032. }
  1033. }
  1034. }
  1035. // Load data from the changeset if it was not loaded from an autosave.
  1036. if ( ! isset( $this->_changeset_data ) ) {
  1037. $data = $this->get_changeset_post_data( $changeset_post_id );
  1038. if ( ! is_wp_error( $data ) ) {
  1039. $this->_changeset_data = $data;
  1040. } else {
  1041. $this->_changeset_data = array();
  1042. }
  1043. }
  1044. }
  1045. return $this->_changeset_data;
  1046. }
  1047. /**
  1048. * Starter content setting IDs.
  1049. *
  1050. * @since 4.7.0
  1051. * @var array
  1052. */
  1053. protected $pending_starter_content_settings_ids = array();
  1054. /**
  1055. * Imports theme starter content into the customized state.
  1056. *
  1057. * @since 4.7.0
  1058. *
  1059. * @param array $starter_content Starter content. Defaults to `get_theme_starter_content()`.
  1060. */
  1061. public function import_theme_starter_content( $starter_content = array() ) {
  1062. if ( empty( $starter_content ) ) {
  1063. $starter_content = get_theme_starter_content();
  1064. }
  1065. $changeset_data = array();
  1066. if ( $this->changeset_post_id() ) {
  1067. /*
  1068. * Don't re-import starter content into a changeset saved persistently.
  1069. * This will need to be revisited in the future once theme switching
  1070. * is allowed with drafted/scheduled changesets, since switching to
  1071. * another theme could result in more starter content being applied.
  1072. * However, when doing an explicit save it is currently possible for
  1073. * nav menus and nav menu items specifically to lose their starter_content
  1074. * flags, thus resulting in duplicates being created since they fail
  1075. * to get re-used. See #40146.
  1076. */
  1077. if ( 'auto-draft' !== get_post_status( $this->changeset_post_id() ) ) {
  1078. return;
  1079. }
  1080. $changeset_data = $this->get_changeset_post_data( $this->changeset_post_id() );
  1081. }
  1082. $sidebars_widgets = isset( $starter_content['widgets'] ) && ! empty( $this->widgets ) ? $starter_content['widgets'] : array();
  1083. $attachments = isset( $starter_content['attachments'] ) && ! empty( $this->nav_menus ) ? $starter_content['attachments'] : array();
  1084. $posts = isset( $starter_content['posts'] ) && ! empty( $this->nav_menus ) ? $starter_content['posts'] : array();
  1085. $options = isset( $starter_content['options'] ) ? $starter_content['options'] : array();
  1086. $nav_menus = isset( $starter_content['nav_menus'] ) && ! empty( $this->nav_menus ) ? $starter_content['nav_menus'] : array();
  1087. $theme_mods = isset( $starter_content['theme_mods'] ) ? $starter_content['theme_mods'] : array();
  1088. // Widgets.
  1089. $max_widget_numbers = array();
  1090. foreach ( $sidebars_widgets as $sidebar_id => $widgets ) {
  1091. $sidebar_widget_ids = array();
  1092. foreach ( $widgets as $widget ) {
  1093. list( $id_base, $instance ) = $widget;
  1094. if ( ! isset( $max_widget_numbers[ $id_base ] ) ) {
  1095. // When $settings is an array-like object, get an intrinsic array for use with array_keys().
  1096. $settings = get_option( "widget_{$id_base}", array() );
  1097. if ( $settings instanceof ArrayObject || $settings instanceof ArrayIterator ) {
  1098. $settings = $settings->getArrayCopy();
  1099. }
  1100. unset( $settings['_multiwidget'] );
  1101. // Find the max widget number for this type.
  1102. $widget_numbers = array_keys( $settings );
  1103. if ( count( $widget_numbers ) > 0 ) {
  1104. $widget_numbers[] = 1;
  1105. $max_widget_numbers[ $id_base ] = max( ...$widget_numbers );
  1106. } else {
  1107. $max_widget_numbers[ $id_base ] = 1;
  1108. }
  1109. }
  1110. $max_widget_numbers[ $id_base ] += 1;
  1111. $widget_id = sprintf( '%s-%d', $id_base, $max_widget_numbers[ $id_base ] );
  1112. $setting_id = sprintf( 'widget_%s[%d]', $id_base, $max_widget_numbers[ $id_base ] );
  1113. $setting_value = $this->widgets->sanitize_widget_js_instance( $instance );
  1114. if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
  1115. $this->set_post_value( $setting_id, $setting_value );
  1116. $this->pending_starter_content_settings_ids[] = $setting_id;
  1117. }
  1118. $sidebar_widget_ids[] = $widget_id;
  1119. }
  1120. $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
  1121. if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
  1122. $this->set_post_value( $setting_id, $sidebar_widget_ids );
  1123. $this->pending_starter_content_settings_ids[] = $setting_id;
  1124. }
  1125. }
  1126. $starter_content_auto_draft_post_ids = array();
  1127. if ( ! empty( $changeset_data['nav_menus_created_posts']['value'] ) ) {
  1128. $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, $changeset_data['nav_menus_created_posts']['value'] );
  1129. }
  1130. // Make an index of all the posts needed and what their slugs are.
  1131. $needed_posts = array();
  1132. $attachments = $this->prepare_starter_content_attachments( $attachments );
  1133. foreach ( $attachments as $attachment ) {
  1134. $key = 'attachment:' . $attachment['post_name'];
  1135. $needed_posts[ $key ] = true;
  1136. }
  1137. foreach ( array_keys( $posts ) as $post_symbol ) {
  1138. if ( empty( $posts[ $post_symbol ]['post_name'] ) && empty( $posts[ $post_symbol ]['post_title'] ) ) {
  1139. unset( $posts[ $post_symbol ] );
  1140. continue;
  1141. }
  1142. if ( empty( $posts[ $post_symbol ]['post_name'] ) ) {
  1143. $posts[ $post_symbol ]['post_name'] = sanitize_title( $posts[ $post_symbol ]['post_title'] );
  1144. }
  1145. if ( empty( $posts[ $post_symbol ]['post_type'] ) ) {
  1146. $posts[ $post_symbol ]['post_type'] = 'post';
  1147. }
  1148. $needed_posts[ $posts[ $post_symbol ]['post_type'] . ':' . $posts[ $post_symbol ]['post_name'] ] = true;
  1149. }
  1150. $all_post_slugs = array_merge(
  1151. wp_list_pluck( $attachments, 'post_name' ),
  1152. wp_list_pluck( $posts, 'post_name' )
  1153. );
  1154. /*
  1155. * Obtain all post types referenced in starter content to use in query.
  1156. * This is needed because 'any' will not account for post types not yet registered.
  1157. */
  1158. $post_types = array_filter( array_merge( array( 'attachment' ), wp_list_pluck( $posts, 'post_type' ) ) );
  1159. // Re-use auto-draft starter content posts referenced in the current customized state.
  1160. $existing_starter_content_posts = array();
  1161. if ( ! empty( $starter_content_auto_draft_post_ids ) ) {
  1162. $existing_posts_query = new WP_Query(
  1163. array(
  1164. 'post__in' => $starter_content_auto_draft_post_ids,
  1165. 'post_status' => 'auto-draft',
  1166. 'post_type' => $post_types,
  1167. 'posts_per_page' => -1,
  1168. )
  1169. );
  1170. foreach ( $existing_posts_query->posts as $existing_post ) {
  1171. $post_name = $existing_post->post_name;
  1172. if ( empty( $post_name ) ) {
  1173. $post_name = get_post_meta( $existing_post->ID, '_customize_draft_post_name', true );
  1174. }
  1175. $existing_starter_content_posts[ $existing_post->post_type . ':' . $post_name ] = $existing_post;
  1176. }
  1177. }
  1178. // Re-use non-auto-draft posts.
  1179. if ( ! empty( $all_post_slugs ) ) {
  1180. $existing_posts_query = new WP_Query(
  1181. array(
  1182. 'post_name__in' => $all_post_slugs,
  1183. 'post_status' => array_diff( get_post_stati(), array( 'auto-draft' ) ),
  1184. 'post_type' => 'any',
  1185. 'posts_per_page' => -1,
  1186. )
  1187. );
  1188. foreach ( $existing_posts_query->posts as $existing_post ) {
  1189. $key = $existing_post->post_type . ':' . $existing_post->post_name;
  1190. if ( isset( $needed_posts[ $key ] ) && ! isset( $existing_starter_content_posts[ $key ] ) ) {
  1191. $existing_starter_content_posts[ $key ] = $existing_post;
  1192. }
  1193. }
  1194. }
  1195. // Attachments are technically posts but handled differently.
  1196. if ( ! empty( $attachments ) ) {
  1197. $attachment_ids = array();
  1198. foreach ( $attachments as $symbol => $attachment ) {
  1199. $file_array = array(
  1200. 'name' => $attachment['file_name'],
  1201. );
  1202. $file_path = $attachment['file_path'];
  1203. $attachment_id = null;
  1204. $attached_file = null;
  1205. if ( isset( $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ] ) ) {
  1206. $attachment_post = $existing_starter_content_posts[ 'attachment:' . $attachment['post_name'] ];
  1207. $attachment_id = $attachment_post->ID;
  1208. $attached_file = get_attached_file( $attachment_id );
  1209. if ( empty( $attached_file ) || ! file_exists( $attached_file ) ) {
  1210. $attachment_id = null;
  1211. $attached_file = null;
  1212. } elseif ( $this->get_stylesheet() !== get_post_meta( $attachment_post->ID, '_starter_content_theme', true ) ) {
  1213. // Re-generate attachment metadata since it was previously generated for a different theme.
  1214. $metadata = wp_generate_attachment_metadata( $attachment_post->ID, $attached_file );
  1215. wp_update_attachment_metadata( $attachment_id, $metadata );
  1216. update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() );
  1217. }
  1218. }
  1219. // Insert the attachment auto-draft because it doesn't yet exist or the attached file is gone.
  1220. if ( ! $attachment_id ) {
  1221. // Copy file to temp location so that original file won't get deleted from theme after sideloading.
  1222. $temp_file_name = wp_tempnam( wp_basename( $file_path ) );
  1223. if ( $temp_file_name && copy( $file_path, $temp_file_name ) ) {
  1224. $file_array['tmp_name'] = $temp_file_name;
  1225. }
  1226. if ( empty( $file_array['tmp_name'] ) ) {
  1227. continue;
  1228. }
  1229. $attachment_post_data = array_merge(
  1230. wp_array_slice_assoc( $attachment, array( 'post_title', 'post_content', 'post_excerpt' ) ),
  1231. array(
  1232. 'post_status' => 'auto-draft', // So attachment will be garbage collected in a week if changeset is never published.
  1233. )
  1234. );
  1235. $attachment_id = media_handle_sideload( $file_array, 0, null, $attachment_post_data );
  1236. if ( is_wp_error( $attachment_id ) ) {
  1237. continue;
  1238. }
  1239. update_post_meta( $attachment_id, '_starter_content_theme', $this->get_stylesheet() );
  1240. update_post_meta( $attachment_id, '_customize_draft_post_name', $attachment['post_name'] );
  1241. }
  1242. $attachment_ids[ $symbol ] = $attachment_id;
  1243. }
  1244. $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, array_values( $attachment_ids ) );
  1245. }
  1246. // Posts & pages.
  1247. if ( ! empty( $posts ) ) {
  1248. foreach ( array_keys( $posts ) as $post_symbol ) {
  1249. if ( empty( $posts[ $post_symbol ]['post_type'] ) || empty( $posts[ $post_symbol ]['post_name'] ) ) {
  1250. continue;
  1251. }
  1252. $post_type = $posts[ $post_symbol ]['post_type'];
  1253. if ( ! empty( $posts[ $post_symbol ]['post_name'] ) ) {
  1254. $post_name = $posts[ $post_symbol ]['post_name'];
  1255. } elseif ( ! empty( $posts[ $post_symbol ]['post_title'] ) ) {
  1256. $post_name = sanitize_title( $posts[ $post_symbol ]['post_title'] );
  1257. } else {
  1258. continue;
  1259. }
  1260. // Use existing auto-draft post if one already exists with the same type and name.
  1261. if ( isset( $existing_starter_content_posts[ $post_type . ':' . $post_name ] ) ) {
  1262. $posts[ $post_symbol ]['ID'] = $existing_starter_content_posts[ $post_type . ':' . $post_name ]->ID;
  1263. continue;
  1264. }
  1265. // Translate the featured image symbol.
  1266. if ( ! empty( $posts[ $post_symbol ]['thumbnail'] )
  1267. && preg_match( '/^{{(?P<symbol>.+)}}$/', $posts[ $post_symbol ]['thumbnail'], $matches )
  1268. && isset( $attachment_ids[ $matches['symbol'] ] ) ) {
  1269. $posts[ $post_symbol ]['meta_input']['_thumbnail_id'] = $attachment_ids[ $matches['symbol'] ];
  1270. }
  1271. if ( ! empty( $posts[ $post_symbol ]['template'] ) ) {
  1272. $posts[ $post_symbol ]['meta_input']['_wp_page_template'] = $posts[ $post_symbol ]['template'];
  1273. }
  1274. $r = $this->nav_menus->insert_auto_draft_post( $posts[ $post_symbol ] );
  1275. if ( $r instanceof WP_Post ) {
  1276. $posts[ $post_symbol ]['ID'] = $r->ID;
  1277. }
  1278. }
  1279. $starter_content_auto_draft_post_ids = array_merge( $starter_content_auto_draft_post_ids, wp_list_pluck( $posts, 'ID' ) );
  1280. }
  1281. // The nav_menus_created_posts setting is why nav_menus component is dependency for adding posts.
  1282. if ( ! empty( $this->nav_menus ) && ! empty( $starter_content_auto_draft_post_ids ) ) {
  1283. $setting_id = 'nav_menus_created_posts';
  1284. $this->set_post_value( $setting_id, array_unique( array_values( $starter_content_auto_draft_post_ids ) ) );
  1285. $this->pending_starter_content_settings_ids[] = $setting_id;
  1286. }
  1287. // Nav menus.
  1288. $placeholder_id = -1;
  1289. $reused_nav_menu_setting_ids = array();
  1290. foreach ( $nav_menus as $nav_menu_location => $nav_menu ) {
  1291. $nav_menu_term_id = null;
  1292. $nav_menu_setting_id = null;
  1293. $matches = array();
  1294. // Look for an existing placeholder menu with starter content to re-use.
  1295. foreach ( $changeset_data as $setting_id => $setting_params ) {
  1296. $can_reuse = (
  1297. ! empty( $setting_params['starter_content'] )
  1298. &&
  1299. ! in_array( $setting_id, $reused_nav_menu_setting_ids, true )
  1300. &&
  1301. preg_match( '#^nav_menu\[(?P<nav_menu_id>-?\d+)\]$#', $setting_id, $matches )
  1302. );
  1303. if ( $can_reuse ) {
  1304. $nav_menu_term_id = (int) $matches['nav_menu_id'];
  1305. $nav_menu_setting_id = $setting_id;
  1306. $reused_nav_menu_setting_ids[] = $setting_id;
  1307. break;
  1308. }
  1309. }
  1310. if ( ! $nav_menu_term_id ) {
  1311. while ( isset( $changeset_data[ sprintf( 'nav_menu[%d]', $placeholder_id ) ] ) ) {
  1312. $placeholder_id--;
  1313. }
  1314. $nav_menu_term_id = $placeholder_id;
  1315. $nav_menu_setting_id = sprintf( 'nav_menu[%d]', $placeholder_id );
  1316. }
  1317. $this->set_post_value(
  1318. $nav_menu_setting_id,
  1319. array(
  1320. 'name' => isset( $nav_menu['name'] ) ? $nav_menu['name'] : $nav_menu_location,
  1321. )
  1322. );
  1323. $this->pending_starter_content_settings_ids[] = $nav_menu_setting_id;
  1324. // @todo Add support for menu_item_parent.
  1325. $position = 0;
  1326. foreach ( $nav_menu['items'] as $nav_menu_item ) {
  1327. $nav_menu_item_setting_id = sprintf( 'nav_menu_item[%d]', $placeholder_id-- );
  1328. if ( ! isset( $nav_menu_item['position'] ) ) {
  1329. $nav_menu_item['position'] = $position++;
  1330. }
  1331. $nav_menu_item['nav_menu_term_id'] = $nav_menu_term_id;
  1332. if ( isset( $nav_menu_item['object_id'] ) ) {
  1333. if ( 'post_type' === $nav_menu_item['type'] && preg_match( '/^{{(?P<symbol>.+)}}$/', $nav_menu_item['object_id'], $matches ) && isset( $posts[ $matches['symbol'] ] ) ) {
  1334. $nav_menu_item['object_id'] = $posts[ $matches['symbol'] ]['ID'];
  1335. if ( empty( $nav_menu_item['title'] ) ) {
  1336. $original_object = get_post( $nav_menu_item['object_id'] );
  1337. $nav_menu_item['title'] = $original_object->post_title;
  1338. }
  1339. } else {
  1340. continue;
  1341. }
  1342. } else {
  1343. $nav_menu_item['object_id'] = 0;
  1344. }
  1345. if ( empty( $changeset_data[ $nav_menu_item_setting_id ] ) || ! empty( $changeset_data[ $nav_menu_item_setting_id ]['starter_content'] ) ) {
  1346. $this->set_post_value( $nav_menu_item_setting_id, $nav_menu_item );
  1347. $this->pending_starter_content_settings_ids[] = $nav_menu_item_setting_id;
  1348. }
  1349. }
  1350. $setting_id = sprintf( 'nav_menu_locations[%s]', $nav_menu_location );
  1351. if ( empty( $changeset_data[ $setting_id ] ) || ! empty( $changeset_data[ $setting_id ]['starter_content'] ) ) {
  1352. $this->set_post_value( $setting_id, $nav_menu_term_id );
  1353. $this->pending_starter_content_settings_ids[] = $setting_id;
  1354. }
  1355. }
  1356. // Options.
  1357. foreach ( $options as $name => $value ) {
  1358. // Serialize the value to check for post symbols.
  1359. $value = maybe_serialize( $value );
  1360. if ( is_serialized( $value ) ) {
  1361. if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) {
  1362. if ( isset( $posts[ $matches['symbol'] ] ) ) {
  1363. $symbol_match = $posts[ $matches['symbol'] ]['ID'];
  1364. } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
  1365. $symbol_match = $attachment_ids[ $matches['symbol'] ];
  1366. }
  1367. // If we have any symbol matches, update the values.
  1368. if ( isset( $symbol_match ) ) {
  1369. // Replace found string matches with post IDs.
  1370. $value = str_replace( $matches[0], "i:{$symbol_match}", $value );
  1371. } else {
  1372. continue;
  1373. }
  1374. }
  1375. } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) {
  1376. if ( isset( $posts[ $matches['symbol'] ] ) ) {
  1377. $value = $posts[ $matches['symbol'] ]['ID'];
  1378. } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
  1379. $value = $attachment_ids[ $matches['symbol'] ];
  1380. } else {
  1381. continue;
  1382. }
  1383. }
  1384. // Unserialize values after checking for post symbols, so they can be properly referenced.
  1385. $value = maybe_unserialize( $value );
  1386. if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) {
  1387. $this->set_post_value( $name, $value );
  1388. $this->pending_starter_content_settings_ids[] = $name;
  1389. }
  1390. }
  1391. // Theme mods.
  1392. foreach ( $theme_mods as $name => $value ) {
  1393. // Serialize the value to check for post symbols.
  1394. $value = maybe_serialize( $value );
  1395. // Check if value was serialized.
  1396. if ( is_serialized( $value ) ) {
  1397. if ( preg_match( '/s:\d+:"{{(?P<symbol>.+)}}"/', $value, $matches ) ) {
  1398. if ( isset( $posts[ $matches['symbol'] ] ) ) {
  1399. $symbol_match = $posts[ $matches['symbol'] ]['ID'];
  1400. } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
  1401. $symbol_match = $attachment_ids[ $matches['symbol'] ];
  1402. }
  1403. // If we have any symbol matches, update the values.
  1404. if ( isset( $symbol_match ) ) {
  1405. // Replace found string matches with post IDs.
  1406. $value = str_replace( $matches[0], "i:{$symbol_match}", $value );
  1407. } else {
  1408. continue;
  1409. }
  1410. }
  1411. } elseif ( preg_match( '/^{{(?P<symbol>.+)}}$/', $value, $matches ) ) {
  1412. if ( isset( $posts[ $matches['symbol'] ] ) ) {
  1413. $value = $posts[ $matches['symbol'] ]['ID'];
  1414. } elseif ( isset( $attachment_ids[ $matches['symbol'] ] ) ) {
  1415. $value = $attachment_ids[ $matches['symbol'] ];
  1416. } else {
  1417. continue;
  1418. }
  1419. }
  1420. // Unserialize values after checking for post symbols, so they can be properly referenced.
  1421. $value = maybe_unserialize( $value );
  1422. // Handle header image as special case since setting has a legacy format.
  1423. if ( 'header_image' === $name ) {
  1424. $name = 'header_image_data';
  1425. $metadata = wp_get_attachment_metadata( $value );
  1426. if ( empty( $metadata ) ) {
  1427. continue;
  1428. }
  1429. $value = array(
  1430. 'attachment_id' => $value,
  1431. 'url' => wp_get_attachment_url( $value ),
  1432. 'height' => $metadata['height'],
  1433. 'width' => $metadata['width'],
  1434. );
  1435. } elseif ( 'background_image' === $name ) {
  1436. $value = wp_get_attachment_url( $value );
  1437. }
  1438. if ( empty( $changeset_data[ $name ] ) || ! empty( $changeset_data[ $name ]['starter_content'] ) ) {
  1439. $this->set_post_value( $name, $value );
  1440. $this->pending_starter_content_settings_ids[] = $name;
  1441. }
  1442. }
  1443. if ( ! empty( $this->pending_starter_content_settings_ids ) ) {
  1444. if ( did_action( 'customize_register' ) ) {
  1445. $this->_save_starter_content_changeset();
  1446. } else {
  1447. add_action( 'customize_register', array( $this, '_save_starter_content_changeset' ), 1000 );
  1448. }
  1449. }
  1450. }
  1451. /**
  1452. * Prepares starter content attachments.
  1453. *
  1454. * Ensure that the attachments are valid and that they have slugs and file name/path.
  1455. *
  1456. * @since 4.7.0
  1457. *
  1458. * @param array $attachments Attachments.
  1459. * @return array Prepared attachments.
  1460. */
  1461. protected function prepare_starter_content_attachments( $attachments ) {
  1462. $prepared_attachments = array();
  1463. if ( empty( $attachments ) ) {
  1464. return $prepared_attachments;
  1465. }
  1466. // Such is The WordPress Way.
  1467. require_once ABSPATH . 'wp-admin/includes/file.php';
  1468. require_once ABSPATH . 'wp-admin/includes/media.php';
  1469. require_once ABSPATH . 'wp-admin/includes/image.php';
  1470. foreach ( $attachments as $symbol => $attachment ) {
  1471. // A file is required and URLs to files are not currently allowed.
  1472. if ( empty( $attachment['file'] ) || preg_match( '#^https?://$#', $attachment['file'] ) ) {
  1473. continue;
  1474. }
  1475. $file_path = null;
  1476. if ( file_exists( $attachment['file'] ) ) {
  1477. $file_path = $attachment['file']; // Could be absolute path to file in plugin.
  1478. } elseif ( is_child_theme() && file_exists( get_stylesheet_directory() . '/' . $attachment['file'] ) ) {
  1479. $file_path = get_stylesheet_directory() . '/' . $attachment['file'];
  1480. } elseif ( file_exists( get_template_directory() . '/' . $attachment['file'] ) ) {
  1481. $file_path = get_template_directory() . '/' . $attachment['file'];
  1482. } else {
  1483. continue;
  1484. }
  1485. $file_name = wp_basename( $attachment['file'] );
  1486. // Skip file types that are not recognized.
  1487. $checked_filetype = wp_check_filetype( $file_name );
  1488. if ( empty( $checked_filetype['type'] ) ) {
  1489. continue;
  1490. }
  1491. // Ensure post_name is set since not automatically derived from post_title for new auto-draft posts.
  1492. if ( empty( $attachment['post_name'] ) ) {
  1493. if ( ! empty( $attachment['post_title'] ) ) {
  1494. $attachment['post_name'] = sanitize_title( $attachment['post_title'] );
  1495. } else {
  1496. $attachment['post_name'] = sanitize_title( preg_replace( '/\.\w+$/', '', $file_name ) );
  1497. }
  1498. }
  1499. $attachment['file_name'] = $file_name;
  1500. $attachment['file_path'] = $file_path;
  1501. $prepared_attachments[ $symbol ] = $attachment;
  1502. }
  1503. return $prepared_attachments;
  1504. }
  1505. /**
  1506. * Saves starter content changeset.
  1507. *
  1508. * @since 4.7.0
  1509. */
  1510. public function _save_starter_content_changeset() {
  1511. if ( empty( $this->pending_starter_content_settings_ids ) ) {
  1512. return;
  1513. }
  1514. $this->save_changeset_post(
  1515. array(
  1516. 'data' => array_fill_keys( $this->pending_starter_content_settings_ids, array( 'starter_content' => true ) ),
  1517. 'starter_content' => true,
  1518. )
  1519. );
  1520. $this->saved_starter_content_changeset = true;
  1521. $this->pending_starter_content_settings_ids = array();
  1522. }
  1523. /**
  1524. * Gets dirty pre-sanitized setting values in the current customized state.
  1525. *
  1526. * The returned array consists of a merge of three sources:
  1527. * 1. If the theme is not currently active, then the base array is any stashed
  1528. * theme mods that were modified previously but never published.
  1529. * 2. The values from the current changeset, if it exists.
  1530. * 3. If the user can customize, the values parsed from the incoming
  1531. * `$_POST['customized']` JSON data.
  1532. * 4. Any programmatically-set post values via `WP_Customize_Manager::set_post_value()`.
  1533. *
  1534. * The name "unsanitized_post_values" is a carry-over from when the customized
  1535. * state was exclusively sourced from `$_POST['customized']`. Nevertheless,
  1536. * the value returned will come from the current changeset post and from the
  1537. * incoming post data.
  1538. *
  1539. * @since 4.1.1
  1540. * @since 4.7.0 Added `$args` parameter and merging with changeset values and stashed theme mods.
  1541. *
  1542. * @param array $args {
  1543. * Args.
  1544. *
  1545. * @type bool $exclude_changeset Whether the changeset values should also be excluded. Defaults to false.
  1546. * @type bool $exclude_post_data Whether the post input values should also be excluded. Defaults to false when lacking the customize capability.
  1547. * }
  1548. * @return array
  1549. */
  1550. public function unsanitized_post_values( $args = array() ) {
  1551. $args = array_merge(
  1552. array(
  1553. 'exclude_changeset' => false,
  1554. 'exclude_post_data' => ! current_user_can( 'customize' ),
  1555. ),
  1556. $args
  1557. );
  1558. $values = array();
  1559. // Let default values be from the stashed theme mods if doing a theme switch and if no changeset is present.
  1560. if ( ! $this->is_theme_active() ) {
  1561. $stashed_theme_mods = get_option( 'customize_stashed_theme_mods' );
  1562. $stylesheet = $this->get_stylesheet();
  1563. if ( isset( $stashed_theme_mods[ $stylesheet ] ) ) {
  1564. $values = array_merge( $values, wp_list_pluck( $stashed_theme_mods[ $stylesheet ], 'value' ) );
  1565. }
  1566. }
  1567. if ( ! $args['exclude_changeset'] ) {
  1568. foreach ( $this->changeset_data() as $setting_id => $setting_params ) {
  1569. if ( ! array_key_exists( 'value', $setting_params ) ) {
  1570. continue;
  1571. }
  1572. if ( isset( $setting_params['type'] ) && 'theme_mod' === $setting_params['type'] ) {
  1573. // Ensure that theme mods values are only used if they were saved under the active theme.
  1574. $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/';
  1575. if ( preg_match( $namespace_pattern, $setting_id, $matches ) && $this->get_stylesheet() === $matches['stylesheet'] ) {
  1576. $values[ $matches['setting_id'] ] = $setting_params['value'];
  1577. }
  1578. } else {
  1579. $values[ $setting_id ] = $setting_params['value'];
  1580. }
  1581. }
  1582. }
  1583. if ( ! $args['exclude_post_data'] ) {
  1584. if ( ! isset( $this->_post_values ) ) {
  1585. if ( isset( $_POST['customized'] ) ) {
  1586. $post_values = json_decode( wp_unslash( $_POST['customized'] ), true );
  1587. } else {
  1588. $post_values = array();
  1589. }
  1590. if ( is_array( $post_values ) ) {
  1591. $this->_post_values = $post_values;
  1592. } else {
  1593. $this->_post_values = array();
  1594. }
  1595. }
  1596. $values = array_merge( $values, $this->_post_values );
  1597. }
  1598. return $values;
  1599. }
  1600. /**
  1601. * Returns the sanitized value for a given setting from the current customized state.
  1602. *
  1603. * The name "post_value" is a carry-over from when the customized state was exclusively
  1604. * sourced from `$_POST['customized']`. Nevertheless, the value returned will come
  1605. * from the current changeset post and from the incoming post data.
  1606. *
  1607. * @since 3.4.0
  1608. * @since 4.1.1 Introduced the `$default_value` parameter.
  1609. * @since 4.6.0 `$default_value` is now returned early when the setting post value is invalid.
  1610. *
  1611. * @see WP_REST_Server::dispatch()
  1612. * @see WP_REST_Request::sanitize_params()
  1613. * @see WP_REST_Request::has_valid_params()
  1614. *
  1615. * @param WP_Customize_Setting $setting A WP_Customize_Setting derived object.
  1616. * @param mixed $default_value Value returned if `$setting` has no post value (added in 4.2.0)
  1617. * or the post value is invalid (added in 4.6.0).
  1618. * @return string|mixed Sanitized value or the `$default_value` provided.
  1619. */
  1620. public function post_value( $setting, $default_value = null ) {
  1621. $post_values = $this->unsanitized_post_values();
  1622. if ( ! array_key_exists( $setting->id, $post_values ) ) {
  1623. return $default_value;
  1624. }
  1625. $value = $post_values[ $setting->id ];
  1626. $valid = $setting->validate( $value );
  1627. if ( is_wp_error( $valid ) ) {
  1628. return $default_value;
  1629. }
  1630. $value = $setting->sanitize( $value );
  1631. if ( is_null( $value ) || is_wp_error( $value ) ) {
  1632. return $default_value;
  1633. }
  1634. return $value;
  1635. }
  1636. /**
  1637. * Overrides a setting's value in the current customized state.
  1638. *
  1639. * The name "post_value" is a carry-over from when the customized state was
  1640. * exclusively sourced from `$_POST['customized']`.
  1641. *
  1642. * @since 4.2.0
  1643. *
  1644. * @param string $setting_id ID for the WP_Customize_Setting instance.
  1645. * @param mixed $value Post value.
  1646. */
  1647. public function set_post_value( $setting_id, $value ) {
  1648. $this->unsanitized_post_values(); // Populate _post_values from $_POST['customized'].
  1649. $this->_post_values[ $setting_id ] = $value;
  1650. /**
  1651. * Announces when a specific setting's unsanitized post value has been set.
  1652. *
  1653. * Fires when the WP_Customize_Manager::set_post_value() method is called.
  1654. *
  1655. * The dynamic portion of the hook name, `$setting_id`, refers to the setting ID.
  1656. *
  1657. * @since 4.4.0
  1658. *
  1659. * @param mixed $value Unsanitized setting post value.
  1660. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  1661. */
  1662. do_action( "customize_post_value_set_{$setting_id}", $value, $this );
  1663. /**
  1664. * Announces when any setting's unsanitized post value has been set.
  1665. *
  1666. * Fires when the WP_Customize_Manager::set_post_value() method is called.
  1667. *
  1668. * This is useful for `WP_Customize_Setting` instances to watch
  1669. * in order to update a cached previewed value.
  1670. *
  1671. * @since 4.4.0
  1672. *
  1673. * @param string $setting_id Setting ID.
  1674. * @param mixed $value Unsanitized setting post value.
  1675. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  1676. */
  1677. do_action( 'customize_post_value_set', $setting_id, $value, $this );
  1678. }
  1679. /**
  1680. * Prints JavaScript settings.
  1681. *
  1682. * @since 3.4.0
  1683. */
  1684. public function customize_preview_init() {
  1685. /*
  1686. * Now that Customizer previews are loaded into iframes via GET requests
  1687. * and natural URLs with transaction UUIDs added, we need to ensure that
  1688. * the responses are never cached by proxies. In practice, this will not
  1689. * be needed if the user is logged-in anyway. But if anonymous access is
  1690. * allowed then the auth cookies would not be sent and WordPress would
  1691. * not send no-cache headers by default.
  1692. */
  1693. if ( ! headers_sent() ) {
  1694. nocache_headers();
  1695. header( 'X-Robots: noindex, nofollow, noarchive' );
  1696. }
  1697. add_filter( 'wp_robots', 'wp_robots_no_robots' );
  1698. add_filter( 'wp_headers', array( $this, 'filter_iframe_security_headers' ) );
  1699. /*
  1700. * If preview is being served inside the customizer preview iframe, and
  1701. * if the user doesn't have customize capability, then it is assumed
  1702. * that the user's session has expired and they need to re-authenticate.
  1703. */
  1704. if ( $this->messenger_channel && ! current_user_can( 'customize' ) ) {
  1705. $this->wp_die(
  1706. -1,
  1707. sprintf(
  1708. /* translators: %s: customize_messenger_channel */
  1709. __( 'Unauthorized. You may remove the %s param to preview as frontend.' ),
  1710. '<code>customize_messenger_channel<code>'
  1711. )
  1712. );
  1713. return;
  1714. }
  1715. $this->prepare_controls();
  1716. add_filter( 'wp_redirect', array( $this, 'add_state_query_params' ) );
  1717. wp_enqueue_script( 'customize-preview' );
  1718. wp_enqueue_style( 'customize-preview' );
  1719. add_action( 'wp_head', array( $this, 'customize_preview_loading_style' ) );
  1720. add_action( 'wp_head', array( $this, 'remove_frameless_preview_messenger_channel' ) );
  1721. add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 );
  1722. add_filter( 'get_edit_post_link', '__return_empty_string' );
  1723. /**
  1724. * Fires once the Customizer preview has initialized and JavaScript
  1725. * settings have been printed.
  1726. *
  1727. * @since 3.4.0
  1728. *
  1729. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  1730. */
  1731. do_action( 'customize_preview_init', $this );
  1732. }
  1733. /**
  1734. * Filters the X-Frame-Options and Content-Security-Policy headers to ensure frontend can load in customizer.
  1735. *
  1736. * @since 4.7.0
  1737. *
  1738. * @param array $headers Headers.
  1739. * @return array Headers.
  1740. */
  1741. public function filter_iframe_security_headers( $headers ) {
  1742. $headers['X-Frame-Options'] = 'SAMEORIGIN';
  1743. $headers['Content-Security-Policy'] = "frame-ancestors 'self'";
  1744. return $headers;
  1745. }
  1746. /**
  1747. * Adds customize state query params to a given URL if preview is allowed.
  1748. *
  1749. * @since 4.7.0
  1750. *
  1751. * @see wp_redirect()
  1752. * @see WP_Customize_Manager::get_allowed_url()
  1753. *
  1754. * @param string $url URL.
  1755. * @return string URL.
  1756. */
  1757. public function add_state_query_params( $url ) {
  1758. $parsed_original_url = wp_parse_url( $url );
  1759. $is_allowed = false;
  1760. foreach ( $this->get_allowed_urls() as $allowed_url ) {
  1761. $parsed_allowed_url = wp_parse_url( $allowed_url );
  1762. $is_allowed = (
  1763. $parsed_allowed_url['scheme'] === $parsed_original_url['scheme']
  1764. &&
  1765. $parsed_allowed_url['host'] === $parsed_original_url['host']
  1766. &&
  1767. 0 === strpos( $parsed_original_url['path'], $parsed_allowed_url['path'] )
  1768. );
  1769. if ( $is_allowed ) {
  1770. break;
  1771. }
  1772. }
  1773. if ( $is_allowed ) {
  1774. $query_params = array(
  1775. 'customize_changeset_uuid' => $this->changeset_uuid(),
  1776. );
  1777. if ( ! $this->is_theme_active() ) {
  1778. $query_params['customize_theme'] = $this->get_stylesheet();
  1779. }
  1780. if ( $this->messenger_channel ) {
  1781. $query_params['customize_messenger_channel'] = $this->messenger_channel;
  1782. }
  1783. $url = add_query_arg( $query_params, $url );
  1784. }
  1785. return $url;
  1786. }
  1787. /**
  1788. * Prevents sending a 404 status when returning the response for the customize
  1789. * preview, since it causes the jQuery Ajax to fail. Send 200 instead.
  1790. *
  1791. * @since 4.0.0
  1792. * @deprecated 4.7.0
  1793. */
  1794. public function customize_preview_override_404_status() {
  1795. _deprecated_function( __METHOD__, '4.7.0' );
  1796. }
  1797. /**
  1798. * Prints base element for preview frame.
  1799. *
  1800. * @since 3.4.0
  1801. * @deprecated 4.7.0
  1802. */
  1803. public function customize_preview_base() {
  1804. _deprecated_function( __METHOD__, '4.7.0' );
  1805. }
  1806. /**
  1807. * Prints a workaround to handle HTML5 tags in IE < 9.
  1808. *
  1809. * @since 3.4.0
  1810. * @deprecated 4.7.0 Customizer no longer supports IE8, so all supported browsers recognize HTML5.
  1811. */
  1812. public function customize_preview_html5() {
  1813. _deprecated_function( __FUNCTION__, '4.7.0' );
  1814. }
  1815. /**
  1816. * Prints CSS for loading indicators for the Customizer preview.
  1817. *
  1818. * @since 4.2.0
  1819. */
  1820. public function customize_preview_loading_style() {
  1821. ?>
  1822. <style>
  1823. body.wp-customizer-unloading {
  1824. opacity: 0.25;
  1825. cursor: progress !important;
  1826. -webkit-transition: opacity 0.5s;
  1827. transition: opacity 0.5s;
  1828. }
  1829. body.wp-customizer-unloading * {
  1830. pointer-events: none !important;
  1831. }
  1832. form.customize-unpreviewable,
  1833. form.customize-unpreviewable input,
  1834. form.customize-unpreviewable select,
  1835. form.customize-unpreviewable button,
  1836. a.customize-unpreviewable,
  1837. area.customize-unpreviewable {
  1838. cursor: not-allowed !important;
  1839. }
  1840. </style>
  1841. <?php
  1842. }
  1843. /**
  1844. * Removes customize_messenger_channel query parameter from the preview window when it is not in an iframe.
  1845. *
  1846. * This ensures that the admin bar will be shown. It also ensures that link navigation will
  1847. * work as expected since the parent frame is not being sent the URL to navigate to.
  1848. *
  1849. * @since 4.7.0
  1850. */
  1851. public function remove_frameless_preview_messenger_channel() {
  1852. if ( ! $this->messenger_channel ) {
  1853. return;
  1854. }
  1855. ?>
  1856. <script>
  1857. ( function() {
  1858. var urlParser, oldQueryParams, newQueryParams, i;
  1859. if ( parent !== window ) {
  1860. return;
  1861. }
  1862. urlParser = document.createElement( 'a' );
  1863. urlParser.href = location.href;
  1864. oldQueryParams = urlParser.search.substr( 1 ).split( /&/ );
  1865. newQueryParams = [];
  1866. for ( i = 0; i < oldQueryParams.length; i += 1 ) {
  1867. if ( ! /^customize_messenger_channel=/.test( oldQueryParams[ i ] ) ) {
  1868. newQueryParams.push( oldQueryParams[ i ] );
  1869. }
  1870. }
  1871. urlParser.search = newQueryParams.join( '&' );
  1872. if ( urlParser.search !== location.search ) {
  1873. location.replace( urlParser.href );
  1874. }
  1875. } )();
  1876. </script>
  1877. <?php
  1878. }
  1879. /**
  1880. * Prints JavaScript settings for preview frame.
  1881. *
  1882. * @since 3.4.0
  1883. */
  1884. public function customize_preview_settings() {
  1885. $post_values = $this->unsanitized_post_values( array( 'exclude_changeset' => true ) );
  1886. $setting_validities = $this->validate_setting_values( $post_values );
  1887. $exported_setting_validities = array_map( array( $this, 'prepare_setting_validity_for_js' ), $setting_validities );
  1888. // Note that the REQUEST_URI is not passed into home_url() since this breaks subdirectory installations.
  1889. $self_url = empty( $_SERVER['REQUEST_URI'] ) ? home_url( '/' ) : esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) );
  1890. $state_query_params = array(
  1891. 'customize_theme',
  1892. 'customize_changeset_uuid',
  1893. 'customize_messenger_channel',
  1894. );
  1895. $self_url = remove_query_arg( $state_query_params, $self_url );
  1896. $allowed_urls = $this->get_allowed_urls();
  1897. $allowed_hosts = array();
  1898. foreach ( $allowed_urls as $allowed_url ) {
  1899. $parsed = wp_parse_url( $allowed_url );
  1900. if ( empty( $parsed['host'] ) ) {
  1901. continue;
  1902. }
  1903. $host = $parsed['host'];
  1904. if ( ! empty( $parsed['port'] ) ) {
  1905. $host .= ':' . $parsed['port'];
  1906. }
  1907. $allowed_hosts[] = $host;
  1908. }
  1909. $switched_locale = switch_to_locale( get_user_locale() );
  1910. $l10n = array(
  1911. 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ),
  1912. 'linkUnpreviewable' => __( 'This link is not live-previewable.' ),
  1913. 'formUnpreviewable' => __( 'This form is not live-previewable.' ),
  1914. );
  1915. if ( $switched_locale ) {
  1916. restore_previous_locale();
  1917. }
  1918. $settings = array(
  1919. 'changeset' => array(
  1920. 'uuid' => $this->changeset_uuid(),
  1921. 'autosaved' => $this->autosaved(),
  1922. ),
  1923. 'timeouts' => array(
  1924. 'selectiveRefresh' => 250,
  1925. 'keepAliveSend' => 1000,
  1926. ),
  1927. 'theme' => array(
  1928. 'stylesheet' => $this->get_stylesheet(),
  1929. 'active' => $this->is_theme_active(),
  1930. ),
  1931. 'url' => array(
  1932. 'self' => $self_url,
  1933. 'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ),
  1934. 'allowedHosts' => array_unique( $allowed_hosts ),
  1935. 'isCrossDomain' => $this->is_cross_domain(),
  1936. ),
  1937. 'channel' => $this->messenger_channel,
  1938. 'activePanels' => array(),
  1939. 'activeSections' => array(),
  1940. 'activeControls' => array(),
  1941. 'settingValidities' => $exported_setting_validities,
  1942. 'nonce' => current_user_can( 'customize' ) ? $this->get_nonces() : array(),
  1943. 'l10n' => $l10n,
  1944. '_dirty' => array_keys( $post_values ),
  1945. );
  1946. foreach ( $this->panels as $panel_id => $panel ) {
  1947. if ( $panel->check_capabilities() ) {
  1948. $settings['activePanels'][ $panel_id ] = $panel->active();
  1949. foreach ( $panel->sections as $section_id => $section ) {
  1950. if ( $section->check_capabilities() ) {
  1951. $settings['activeSections'][ $section_id ] = $section->active();
  1952. }
  1953. }
  1954. }
  1955. }
  1956. foreach ( $this->sections as $id => $section ) {
  1957. if ( $section->check_capabilities() ) {
  1958. $settings['activeSections'][ $id ] = $section->active();
  1959. }
  1960. }
  1961. foreach ( $this->controls as $id => $control ) {
  1962. if ( $control->check_capabilities() ) {
  1963. $settings['activeControls'][ $id ] = $control->active();
  1964. }
  1965. }
  1966. ?>
  1967. <script type="text/javascript">
  1968. var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>;
  1969. _wpCustomizeSettings.values = {};
  1970. (function( v ) {
  1971. <?php
  1972. /*
  1973. * Serialize settings separately from the initial _wpCustomizeSettings
  1974. * serialization in order to avoid a peak memory usage spike.
  1975. * @todo We may not even need to export the values at all since the pane syncs them anyway.
  1976. */
  1977. foreach ( $this->settings as $id => $setting ) {
  1978. if ( $setting->check_capabilities() ) {
  1979. printf(
  1980. "v[%s] = %s;\n",
  1981. wp_json_encode( $id ),
  1982. wp_json_encode( $setting->js_value() )
  1983. );
  1984. }
  1985. }
  1986. ?>
  1987. })( _wpCustomizeSettings.values );
  1988. </script>
  1989. <?php
  1990. }
  1991. /**
  1992. * Prints a signature so we can ensure the Customizer was properly executed.
  1993. *
  1994. * @since 3.4.0
  1995. * @deprecated 4.7.0
  1996. */
  1997. public function customize_preview_signature() {
  1998. _deprecated_function( __METHOD__, '4.7.0' );
  1999. }
  2000. /**
  2001. * Removes the signature in case we experience a case where the Customizer was not properly executed.
  2002. *
  2003. * @since 3.4.0
  2004. * @deprecated 4.7.0
  2005. *
  2006. * @param callable|null $callback Optional. Value passed through for {@see 'wp_die_handler'} filter.
  2007. * Default null.
  2008. * @return callable|null Value passed through for {@see 'wp_die_handler'} filter.
  2009. */
  2010. public function remove_preview_signature( $callback = null ) {
  2011. _deprecated_function( __METHOD__, '4.7.0' );
  2012. return $callback;
  2013. }
  2014. /**
  2015. * Determines whether it is a theme preview or not.
  2016. *
  2017. * @since 3.4.0
  2018. *
  2019. * @return bool True if it's a preview, false if not.
  2020. */
  2021. public function is_preview() {
  2022. return (bool) $this->previewing;
  2023. }
  2024. /**
  2025. * Retrieves the template name of the previewed theme.
  2026. *
  2027. * @since 3.4.0
  2028. *
  2029. * @return string Template name.
  2030. */
  2031. public function get_template() {
  2032. return $this->theme()->get_template();
  2033. }
  2034. /**
  2035. * Retrieves the stylesheet name of the previewed theme.
  2036. *
  2037. * @since 3.4.0
  2038. *
  2039. * @return string Stylesheet name.
  2040. */
  2041. public function get_stylesheet() {
  2042. return $this->theme()->get_stylesheet();
  2043. }
  2044. /**
  2045. * Retrieves the template root of the previewed theme.
  2046. *
  2047. * @since 3.4.0
  2048. *
  2049. * @return string Theme root.
  2050. */
  2051. public function get_template_root() {
  2052. return get_raw_theme_root( $this->get_template(), true );
  2053. }
  2054. /**
  2055. * Retrieves the stylesheet root of the previewed theme.
  2056. *
  2057. * @since 3.4.0
  2058. *
  2059. * @return string Theme root.
  2060. */
  2061. public function get_stylesheet_root() {
  2062. return get_raw_theme_root( $this->get_stylesheet(), true );
  2063. }
  2064. /**
  2065. * Filters the active theme and return the name of the previewed theme.
  2066. *
  2067. * @since 3.4.0
  2068. *
  2069. * @param mixed $current_theme {@internal Parameter is not used}
  2070. * @return string Theme name.
  2071. */
  2072. public function current_theme( $current_theme ) {
  2073. return $this->theme()->display( 'Name' );
  2074. }
  2075. /**
  2076. * Validates setting values.
  2077. *
  2078. * Validation is skipped for unregistered settings or for values that are
  2079. * already null since they will be skipped anyway. Sanitization is applied
  2080. * to values that pass validation, and values that become null or `WP_Error`
  2081. * after sanitizing are marked invalid.
  2082. *
  2083. * @since 4.6.0
  2084. *
  2085. * @see WP_REST_Request::has_valid_params()
  2086. * @see WP_Customize_Setting::validate()
  2087. *
  2088. * @param array $setting_values Mapping of setting IDs to values to validate and sanitize.
  2089. * @param array $options {
  2090. * Options.
  2091. *
  2092. * @type bool $validate_existence Whether a setting's existence will be checked.
  2093. * @type bool $validate_capability Whether the setting capability will be checked.
  2094. * }
  2095. * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`.
  2096. */
  2097. public function validate_setting_values( $setting_values, $options = array() ) {
  2098. $options = wp_parse_args(
  2099. $options,
  2100. array(
  2101. 'validate_capability' => false,
  2102. 'validate_existence' => false,
  2103. )
  2104. );
  2105. $validities = array();
  2106. foreach ( $setting_values as $setting_id => $unsanitized_value ) {
  2107. $setting = $this->get_setting( $setting_id );
  2108. if ( ! $setting ) {
  2109. if ( $options['validate_existence'] ) {
  2110. $validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) );
  2111. }
  2112. continue;
  2113. }
  2114. if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) {
  2115. $validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) );
  2116. } else {
  2117. if ( is_null( $unsanitized_value ) ) {
  2118. continue;
  2119. }
  2120. $validity = $setting->validate( $unsanitized_value );
  2121. }
  2122. if ( ! is_wp_error( $validity ) ) {
  2123. /** This filter is documented in wp-includes/class-wp-customize-setting.php */
  2124. $late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting );
  2125. if ( is_wp_error( $late_validity ) && $late_validity->has_errors() ) {
  2126. $validity = $late_validity;
  2127. }
  2128. }
  2129. if ( ! is_wp_error( $validity ) ) {
  2130. $value = $setting->sanitize( $unsanitized_value );
  2131. if ( is_null( $value ) ) {
  2132. $validity = false;
  2133. } elseif ( is_wp_error( $value ) ) {
  2134. $validity = $value;
  2135. }
  2136. }
  2137. if ( false === $validity ) {
  2138. $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
  2139. }
  2140. $validities[ $setting_id ] = $validity;
  2141. }
  2142. return $validities;
  2143. }
  2144. /**
  2145. * Prepares setting validity for exporting to the client (JS).
  2146. *
  2147. * Converts `WP_Error` instance into array suitable for passing into the
  2148. * `wp.customize.Notification` JS model.
  2149. *
  2150. * @since 4.6.0
  2151. *
  2152. * @param true|WP_Error $validity Setting validity.
  2153. * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped
  2154. * to their respective `message` and `data` to pass into the
  2155. * `wp.customize.Notification` JS model.
  2156. */
  2157. public function prepare_setting_validity_for_js( $validity ) {
  2158. if ( is_wp_error( $validity ) ) {
  2159. $notification = array();
  2160. foreach ( $validity->errors as $error_code => $error_messages ) {
  2161. $notification[ $error_code ] = array(
  2162. 'message' => implode( ' ', $error_messages ),
  2163. 'data' => $validity->get_error_data( $error_code ),
  2164. );
  2165. }
  2166. return $notification;
  2167. } else {
  2168. return true;
  2169. }
  2170. }
  2171. /**
  2172. * Handles customize_save WP Ajax request to save/update a changeset.
  2173. *
  2174. * @since 3.4.0
  2175. * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes.
  2176. */
  2177. public function save() {
  2178. if ( ! is_user_logged_in() ) {
  2179. wp_send_json_error( 'unauthenticated' );
  2180. }
  2181. if ( ! $this->is_preview() ) {
  2182. wp_send_json_error( 'not_preview' );
  2183. }
  2184. $action = 'save-customize_' . $this->get_stylesheet();
  2185. if ( ! check_ajax_referer( $action, 'nonce', false ) ) {
  2186. wp_send_json_error( 'invalid_nonce' );
  2187. }
  2188. $changeset_post_id = $this->changeset_post_id();
  2189. $is_new_changeset = empty( $changeset_post_id );
  2190. if ( $is_new_changeset ) {
  2191. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) {
  2192. wp_send_json_error( 'cannot_create_changeset_post' );
  2193. }
  2194. } else {
  2195. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) {
  2196. wp_send_json_error( 'cannot_edit_changeset_post' );
  2197. }
  2198. }
  2199. if ( ! empty( $_POST['customize_changeset_data'] ) ) {
  2200. $input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true );
  2201. if ( ! is_array( $input_changeset_data ) ) {
  2202. wp_send_json_error( 'invalid_customize_changeset_data' );
  2203. }
  2204. } else {
  2205. $input_changeset_data = array();
  2206. }
  2207. // Validate title.
  2208. $changeset_title = null;
  2209. if ( isset( $_POST['customize_changeset_title'] ) ) {
  2210. $changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) );
  2211. }
  2212. // Validate changeset status param.
  2213. $is_publish = null;
  2214. $changeset_status = null;
  2215. if ( isset( $_POST['customize_changeset_status'] ) ) {
  2216. $changeset_status = wp_unslash( $_POST['customize_changeset_status'] );
  2217. if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) {
  2218. wp_send_json_error( 'bad_customize_changeset_status', 400 );
  2219. }
  2220. $is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status );
  2221. if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) {
  2222. wp_send_json_error( 'changeset_publish_unauthorized', 403 );
  2223. }
  2224. }
  2225. /*
  2226. * Validate changeset date param. Date is assumed to be in local time for
  2227. * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date
  2228. * is parsed with strtotime() so that ISO date format may be supplied
  2229. * or a string like "+10 minutes".
  2230. */
  2231. $changeset_date_gmt = null;
  2232. if ( isset( $_POST['customize_changeset_date'] ) ) {
  2233. $changeset_date = wp_unslash( $_POST['customize_changeset_date'] );
  2234. if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) {
  2235. $mm = substr( $changeset_date, 5, 2 );
  2236. $jj = substr( $changeset_date, 8, 2 );
  2237. $aa = substr( $changeset_date, 0, 4 );
  2238. $valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date );
  2239. if ( ! $valid_date ) {
  2240. wp_send_json_error( 'bad_customize_changeset_date', 400 );
  2241. }
  2242. $changeset_date_gmt = get_gmt_from_date( $changeset_date );
  2243. } else {
  2244. $timestamp = strtotime( $changeset_date );
  2245. if ( ! $timestamp ) {
  2246. wp_send_json_error( 'bad_customize_changeset_date', 400 );
  2247. }
  2248. $changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp );
  2249. }
  2250. }
  2251. $lock_user_id = null;
  2252. $autosave = ! empty( $_POST['customize_changeset_autosave'] );
  2253. if ( ! $is_new_changeset ) {
  2254. $lock_user_id = wp_check_post_lock( $this->changeset_post_id() );
  2255. }
  2256. // Force request to autosave when changeset is locked.
  2257. if ( $lock_user_id && ! $autosave ) {
  2258. $autosave = true;
  2259. $changeset_status = null;
  2260. $changeset_date_gmt = null;
  2261. }
  2262. if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat.
  2263. define( 'DOING_AUTOSAVE', true );
  2264. }
  2265. $autosaved = false;
  2266. $r = $this->save_changeset_post(
  2267. array(
  2268. 'status' => $changeset_status,
  2269. 'title' => $changeset_title,
  2270. 'date_gmt' => $changeset_date_gmt,
  2271. 'data' => $input_changeset_data,
  2272. 'autosave' => $autosave,
  2273. )
  2274. );
  2275. if ( $autosave && ! is_wp_error( $r ) ) {
  2276. $autosaved = true;
  2277. }
  2278. // If the changeset was locked and an autosave request wasn't itself an error, then now explicitly return with a failure.
  2279. if ( $lock_user_id && ! is_wp_error( $r ) ) {
  2280. $r = new WP_Error(
  2281. 'changeset_locked',
  2282. __( 'Changeset is being edited by other user.' ),
  2283. array(
  2284. 'lock_user' => $this->get_lock_user_data( $lock_user_id ),
  2285. )
  2286. );
  2287. }
  2288. if ( is_wp_error( $r ) ) {
  2289. $response = array(
  2290. 'message' => $r->get_error_message(),
  2291. 'code' => $r->get_error_code(),
  2292. );
  2293. if ( is_array( $r->get_error_data() ) ) {
  2294. $response = array_merge( $response, $r->get_error_data() );
  2295. } else {
  2296. $response['data'] = $r->get_error_data();
  2297. }
  2298. } else {
  2299. $response = $r;
  2300. $changeset_post = get_post( $this->changeset_post_id() );
  2301. // Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one.
  2302. if ( $is_new_changeset ) {
  2303. $this->dismiss_user_auto_draft_changesets();
  2304. }
  2305. // Note that if the changeset status was publish, then it will get set to Trash if revisions are not supported.
  2306. $response['changeset_status'] = $changeset_post->post_status;
  2307. if ( $is_publish && 'trash' === $response['changeset_status'] ) {
  2308. $response['changeset_status'] = 'publish';
  2309. }
  2310. if ( 'publish' !== $response['changeset_status'] ) {
  2311. $this->set_changeset_lock( $changeset_post->ID );
  2312. }
  2313. if ( 'future' === $response['changeset_status'] ) {
  2314. $response['changeset_date'] = $changeset_post->post_date;
  2315. }
  2316. if ( 'publish' === $response['changeset_status'] || 'trash' === $response['changeset_status'] ) {
  2317. $response['next_changeset_uuid'] = wp_generate_uuid4();
  2318. }
  2319. }
  2320. if ( $autosave ) {
  2321. $response['autosaved'] = $autosaved;
  2322. }
  2323. if ( isset( $response['setting_validities'] ) ) {
  2324. $response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] );
  2325. }
  2326. /**
  2327. * Filters response data for a successful customize_save Ajax request.
  2328. *
  2329. * This filter does not apply if there was a nonce or authentication failure.
  2330. *
  2331. * @since 4.2.0
  2332. *
  2333. * @param array $response Additional information passed back to the 'saved'
  2334. * event on `wp.customize`.
  2335. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  2336. */
  2337. $response = apply_filters( 'customize_save_response', $response, $this );
  2338. if ( is_wp_error( $r ) ) {
  2339. wp_send_json_error( $response );
  2340. } else {
  2341. wp_send_json_success( $response );
  2342. }
  2343. }
  2344. /**
  2345. * Saves the post for the loaded changeset.
  2346. *
  2347. * @since 4.7.0
  2348. *
  2349. * @param array $args {
  2350. * Args for changeset post.
  2351. *
  2352. * @type array $data Optional additional changeset data. Values will be merged on top of any existing post values.
  2353. * @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed.
  2354. * @type string $title Post title. Optional.
  2355. * @type string $date_gmt Date in GMT. Optional.
  2356. * @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID.
  2357. * @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved.
  2358. * @type bool $autosave Whether this is a request to create an autosave revision.
  2359. * }
  2360. *
  2361. * @return array|WP_Error Returns array on success and WP_Error with array data on error.
  2362. */
  2363. public function save_changeset_post( $args = array() ) {
  2364. $args = array_merge(
  2365. array(
  2366. 'status' => null,
  2367. 'title' => null,
  2368. 'data' => array(),
  2369. 'date_gmt' => null,
  2370. 'user_id' => get_current_user_id(),
  2371. 'starter_content' => false,
  2372. 'autosave' => false,
  2373. ),
  2374. $args
  2375. );
  2376. $changeset_post_id = $this->changeset_post_id();
  2377. $existing_changeset_data = array();
  2378. if ( $changeset_post_id ) {
  2379. $existing_status = get_post_status( $changeset_post_id );
  2380. if ( 'publish' === $existing_status || 'trash' === $existing_status ) {
  2381. return new WP_Error(
  2382. 'changeset_already_published',
  2383. __( 'The previous set of changes has already been published. Please try saving your current set of changes again.' ),
  2384. array(
  2385. 'next_changeset_uuid' => wp_generate_uuid4(),
  2386. )
  2387. );
  2388. }
  2389. $existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  2390. if ( is_wp_error( $existing_changeset_data ) ) {
  2391. return $existing_changeset_data;
  2392. }
  2393. }
  2394. // Fail if attempting to publish but publish hook is missing.
  2395. if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) {
  2396. return new WP_Error( 'missing_publish_callback' );
  2397. }
  2398. // Validate date.
  2399. $now = gmdate( 'Y-m-d H:i:59' );
  2400. if ( $args['date_gmt'] ) {
  2401. $is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) );
  2402. if ( ! $is_future_dated ) {
  2403. return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); // Only future dates are allowed.
  2404. }
  2405. if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) {
  2406. return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting.
  2407. }
  2408. $will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) );
  2409. if ( $will_remain_auto_draft ) {
  2410. return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' );
  2411. }
  2412. } elseif ( $changeset_post_id && 'future' === $args['status'] ) {
  2413. // Fail if the new status is future but the existing post's date is not in the future.
  2414. $changeset_post = get_post( $changeset_post_id );
  2415. if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) {
  2416. return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) );
  2417. }
  2418. }
  2419. if ( ! empty( $is_future_dated ) && 'publish' === $args['status'] ) {
  2420. $args['status'] = 'future';
  2421. }
  2422. // Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed.
  2423. if ( $args['autosave'] ) {
  2424. if ( $args['date_gmt'] ) {
  2425. return new WP_Error( 'illegal_autosave_with_date_gmt' );
  2426. } elseif ( $args['status'] ) {
  2427. return new WP_Error( 'illegal_autosave_with_status' );
  2428. } elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) {
  2429. return new WP_Error( 'illegal_autosave_with_non_current_user' );
  2430. }
  2431. }
  2432. // The request was made via wp.customize.previewer.save().
  2433. $update_transactionally = (bool) $args['status'];
  2434. $allow_revision = (bool) $args['status'];
  2435. // Amend post values with any supplied data.
  2436. foreach ( $args['data'] as $setting_id => $setting_params ) {
  2437. if ( is_array( $setting_params ) && array_key_exists( 'value', $setting_params ) ) {
  2438. $this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized.
  2439. }
  2440. }
  2441. // Note that in addition to post data, this will include any stashed theme mods.
  2442. $post_values = $this->unsanitized_post_values(
  2443. array(
  2444. 'exclude_changeset' => true,
  2445. 'exclude_post_data' => false,
  2446. )
  2447. );
  2448. $this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value.
  2449. /*
  2450. * Get list of IDs for settings that have values different from what is currently
  2451. * saved in the changeset. By skipping any values that are already the same, the
  2452. * subset of changed settings can be passed into validate_setting_values to prevent
  2453. * an underprivileged modifying a single setting for which they have the capability
  2454. * from being blocked from saving. This also prevents a user from touching of the
  2455. * previous saved settings and overriding the associated user_id if they made no change.
  2456. */
  2457. $changed_setting_ids = array();
  2458. foreach ( $post_values as $setting_id => $setting_value ) {
  2459. $setting = $this->get_setting( $setting_id );
  2460. if ( $setting && 'theme_mod' === $setting->type ) {
  2461. $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id;
  2462. } else {
  2463. $prefixed_setting_id = $setting_id;
  2464. }
  2465. $is_value_changed = (
  2466. ! isset( $existing_changeset_data[ $prefixed_setting_id ] )
  2467. ||
  2468. ! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] )
  2469. ||
  2470. $existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value
  2471. );
  2472. if ( $is_value_changed ) {
  2473. $changed_setting_ids[] = $setting_id;
  2474. }
  2475. }
  2476. /**
  2477. * Fires before save validation happens.
  2478. *
  2479. * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters
  2480. * at this point to catch any settings registered after `customize_register`.
  2481. * The dynamic portion of the hook name, `$this->ID` refers to the setting ID.
  2482. *
  2483. * @since 4.6.0
  2484. *
  2485. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  2486. */
  2487. do_action( 'customize_save_validation_before', $this );
  2488. // Validate settings.
  2489. $validated_values = array_merge(
  2490. array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates.
  2491. $post_values
  2492. );
  2493. $setting_validities = $this->validate_setting_values(
  2494. $validated_values,
  2495. array(
  2496. 'validate_capability' => true,
  2497. 'validate_existence' => true,
  2498. )
  2499. );
  2500. $invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) );
  2501. /*
  2502. * Short-circuit if there are invalid settings the update is transactional.
  2503. * A changeset update is transactional when a status is supplied in the request.
  2504. */
  2505. if ( $update_transactionally && $invalid_setting_count > 0 ) {
  2506. $response = array(
  2507. 'setting_validities' => $setting_validities,
  2508. /* translators: %s: Number of invalid settings. */
  2509. 'message' => sprintf( _n( 'Unable to save due to %s invalid setting.', 'Unable to save due to %s invalid settings.', $invalid_setting_count ), number_format_i18n( $invalid_setting_count ) ),
  2510. );
  2511. return new WP_Error( 'transaction_fail', '', $response );
  2512. }
  2513. // Obtain/merge data for changeset.
  2514. $original_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  2515. $data = $original_changeset_data;
  2516. if ( is_wp_error( $data ) ) {
  2517. $data = array();
  2518. }
  2519. // Ensure that all post values are included in the changeset data.
  2520. foreach ( $post_values as $setting_id => $post_value ) {
  2521. if ( ! isset( $args['data'][ $setting_id ] ) ) {
  2522. $args['data'][ $setting_id ] = array();
  2523. }
  2524. if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) {
  2525. $args['data'][ $setting_id ]['value'] = $post_value;
  2526. }
  2527. }
  2528. foreach ( $args['data'] as $setting_id => $setting_params ) {
  2529. $setting = $this->get_setting( $setting_id );
  2530. if ( ! $setting || ! $setting->check_capabilities() ) {
  2531. continue;
  2532. }
  2533. // Skip updating changeset for invalid setting values.
  2534. if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) {
  2535. continue;
  2536. }
  2537. $changeset_setting_id = $setting_id;
  2538. if ( 'theme_mod' === $setting->type ) {
  2539. $changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id );
  2540. }
  2541. if ( null === $setting_params ) {
  2542. // Remove setting from changeset entirely.
  2543. unset( $data[ $changeset_setting_id ] );
  2544. } else {
  2545. if ( ! isset( $data[ $changeset_setting_id ] ) ) {
  2546. $data[ $changeset_setting_id ] = array();
  2547. }
  2548. // Merge any additional setting params that have been supplied with the existing params.
  2549. $merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params );
  2550. // Skip updating setting params if unchanged (ensuring the user_id is not overwritten).
  2551. if ( $data[ $changeset_setting_id ] === $merged_setting_params ) {
  2552. continue;
  2553. }
  2554. $data[ $changeset_setting_id ] = array_merge(
  2555. $merged_setting_params,
  2556. array(
  2557. 'type' => $setting->type,
  2558. 'user_id' => $args['user_id'],
  2559. 'date_modified_gmt' => current_time( 'mysql', true ),
  2560. )
  2561. );
  2562. // Clear starter_content flag in data if changeset is not explicitly being updated for starter content.
  2563. if ( empty( $args['starter_content'] ) ) {
  2564. unset( $data[ $changeset_setting_id ]['starter_content'] );
  2565. }
  2566. }
  2567. }
  2568. $filter_context = array(
  2569. 'uuid' => $this->changeset_uuid(),
  2570. 'title' => $args['title'],
  2571. 'status' => $args['status'],
  2572. 'date_gmt' => $args['date_gmt'],
  2573. 'post_id' => $changeset_post_id,
  2574. 'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data,
  2575. 'manager' => $this,
  2576. );
  2577. /**
  2578. * Filters the settings' data that will be persisted into the changeset.
  2579. *
  2580. * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter.
  2581. *
  2582. * @since 4.7.0
  2583. *
  2584. * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata.
  2585. * @param array $context {
  2586. * Filter context.
  2587. *
  2588. * @type string $uuid Changeset UUID.
  2589. * @type string $title Requested title for the changeset post.
  2590. * @type string $status Requested status for the changeset post.
  2591. * @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone.
  2592. * @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet.
  2593. * @type array $previous_data Previous data contained in the changeset.
  2594. * @type WP_Customize_Manager $manager Manager instance.
  2595. * }
  2596. */
  2597. $data = apply_filters( 'customize_changeset_save_data', $data, $filter_context );
  2598. // Switch theme if publishing changes now.
  2599. if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) {
  2600. // Temporarily stop previewing the theme to allow switch_themes() to operate properly.
  2601. $this->stop_previewing_theme();
  2602. switch_theme( $this->get_stylesheet() );
  2603. update_option( 'theme_switched_via_customizer', true );
  2604. $this->start_previewing_theme();
  2605. }
  2606. // Gather the data for wp_insert_post()/wp_update_post().
  2607. $post_array = array(
  2608. // JSON_UNESCAPED_SLASHES is only to improve readability as slashes needn't be escaped in storage.
  2609. 'post_content' => wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ),
  2610. );
  2611. if ( $args['title'] ) {
  2612. $post_array['post_title'] = $args['title'];
  2613. }
  2614. if ( $changeset_post_id ) {
  2615. $post_array['ID'] = $changeset_post_id;
  2616. } else {
  2617. $post_array['post_type'] = 'customize_changeset';
  2618. $post_array['post_name'] = $this->changeset_uuid();
  2619. $post_array['post_status'] = 'auto-draft';
  2620. }
  2621. if ( $args['status'] ) {
  2622. $post_array['post_status'] = $args['status'];
  2623. }
  2624. // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date.
  2625. if ( 'publish' === $args['status'] ) {
  2626. $post_array['post_date_gmt'] = '0000-00-00 00:00:00';
  2627. $post_array['post_date'] = '0000-00-00 00:00:00';
  2628. } elseif ( $args['date_gmt'] ) {
  2629. $post_array['post_date_gmt'] = $args['date_gmt'];
  2630. $post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] );
  2631. } elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) {
  2632. /*
  2633. * Keep bumping the date for the auto-draft whenever it is modified;
  2634. * this extends its life, preserving it from garbage-collection via
  2635. * wp_delete_auto_drafts().
  2636. */
  2637. $post_array['post_date'] = current_time( 'mysql' );
  2638. $post_array['post_date_gmt'] = '';
  2639. }
  2640. $this->store_changeset_revision = $allow_revision;
  2641. add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 );
  2642. /*
  2643. * Update the changeset post. The publish_customize_changeset action will cause the settings in the
  2644. * changeset to be saved via WP_Customize_Setting::save(). Updating a post with publish status will
  2645. * trigger WP_Customize_Manager::publish_changeset_values().
  2646. */
  2647. add_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5, 3 );
  2648. if ( $changeset_post_id ) {
  2649. if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) {
  2650. // See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability.
  2651. add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 );
  2652. $post_array['post_ID'] = $post_array['ID'];
  2653. $post_array['post_type'] = 'customize_changeset';
  2654. $r = wp_create_post_autosave( wp_slash( $post_array ) );
  2655. remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 );
  2656. } else {
  2657. $post_array['edit_date'] = true; // Prevent date clearing.
  2658. $r = wp_update_post( wp_slash( $post_array ), true );
  2659. // Delete autosave revision for user when the changeset is updated.
  2660. if ( ! empty( $args['user_id'] ) ) {
  2661. $autosave_draft = wp_get_post_autosave( $changeset_post_id, $args['user_id'] );
  2662. if ( $autosave_draft ) {
  2663. wp_delete_post( $autosave_draft->ID, true );
  2664. }
  2665. }
  2666. }
  2667. } else {
  2668. $r = wp_insert_post( wp_slash( $post_array ), true );
  2669. if ( ! is_wp_error( $r ) ) {
  2670. $this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset.
  2671. }
  2672. }
  2673. remove_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5 );
  2674. $this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents.
  2675. remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) );
  2676. $response = array(
  2677. 'setting_validities' => $setting_validities,
  2678. );
  2679. if ( is_wp_error( $r ) ) {
  2680. $response['changeset_post_save_failure'] = $r->get_error_code();
  2681. return new WP_Error( 'changeset_post_save_failure', '', $response );
  2682. }
  2683. return $response;
  2684. }
  2685. /**
  2686. * Preserves the initial JSON post_content passed to save into the post.
  2687. *
  2688. * This is needed to prevent KSES and other {@see 'content_save_pre'} filters
  2689. * from corrupting JSON data.
  2690. *
  2691. * Note that WP_Customize_Manager::validate_setting_values() have already
  2692. * run on the setting values being serialized as JSON into the post content
  2693. * so it is pre-sanitized.
  2694. *
  2695. * Also, the sanitization logic is re-run through the respective
  2696. * WP_Customize_Setting::sanitize() method when being read out of the
  2697. * changeset, via WP_Customize_Manager::post_value(), and this sanitized
  2698. * value will also be sent into WP_Customize_Setting::update() for
  2699. * persisting to the DB.
  2700. *
  2701. * Multiple users can collaborate on a single changeset, where one user may
  2702. * have the unfiltered_html capability but another may not. A user with
  2703. * unfiltered_html may add a script tag to some field which needs to be kept
  2704. * intact even when another user updates the changeset to modify another field
  2705. * when they do not have unfiltered_html.
  2706. *
  2707. * @since 5.4.1
  2708. *
  2709. * @param array $data An array of slashed and processed post data.
  2710. * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
  2711. * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post().
  2712. * @return array Filtered post data.
  2713. */
  2714. public function preserve_insert_changeset_post_content( $data, $postarr, $unsanitized_postarr ) {
  2715. if (
  2716. isset( $data['post_type'] ) &&
  2717. isset( $unsanitized_postarr['post_content'] ) &&
  2718. 'customize_changeset' === $data['post_type'] ||
  2719. (
  2720. 'revision' === $data['post_type'] &&
  2721. ! empty( $data['post_parent'] ) &&
  2722. 'customize_changeset' === get_post_type( $data['post_parent'] )
  2723. )
  2724. ) {
  2725. $data['post_content'] = $unsanitized_postarr['post_content'];
  2726. }
  2727. return $data;
  2728. }
  2729. /**
  2730. * Trashes or deletes a changeset post.
  2731. *
  2732. * The following re-formulates the logic from `wp_trash_post()` as done in
  2733. * `wp_publish_post()`. The reason for bypassing `wp_trash_post()` is that it
  2734. * will mutate the the `post_content` and the `post_name` when they should be
  2735. * untouched.
  2736. *
  2737. * @since 4.9.0
  2738. *
  2739. * @see wp_trash_post()
  2740. * @global wpdb $wpdb WordPress database abstraction object.
  2741. *
  2742. * @param int|WP_Post $post The changeset post.
  2743. * @return mixed A WP_Post object for the trashed post or an empty value on failure.
  2744. */
  2745. public function trash_changeset_post( $post ) {
  2746. global $wpdb;
  2747. $post = get_post( $post );
  2748. if ( ! ( $post instanceof WP_Post ) ) {
  2749. return $post;
  2750. }
  2751. $post_id = $post->ID;
  2752. if ( ! EMPTY_TRASH_DAYS ) {
  2753. return wp_delete_post( $post_id, true );
  2754. }
  2755. if ( 'trash' === get_post_status( $post ) ) {
  2756. return false;
  2757. }
  2758. /** This filter is documented in wp-includes/post.php */
  2759. $check = apply_filters( 'pre_trash_post', null, $post );
  2760. if ( null !== $check ) {
  2761. return $check;
  2762. }
  2763. /** This action is documented in wp-includes/post.php */
  2764. do_action( 'wp_trash_post', $post_id );
  2765. add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status );
  2766. add_post_meta( $post_id, '_wp_trash_meta_time', time() );
  2767. $old_status = $post->post_status;
  2768. $new_status = 'trash';
  2769. $wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $post->ID ) );
  2770. clean_post_cache( $post->ID );
  2771. $post->post_status = $new_status;
  2772. wp_transition_post_status( $new_status, $old_status, $post );
  2773. /** This action is documented in wp-includes/post.php */
  2774. do_action( "edit_post_{$post->post_type}", $post->ID, $post );
  2775. /** This action is documented in wp-includes/post.php */
  2776. do_action( 'edit_post', $post->ID, $post );
  2777. /** This action is documented in wp-includes/post.php */
  2778. do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
  2779. /** This action is documented in wp-includes/post.php */
  2780. do_action( 'save_post', $post->ID, $post, true );
  2781. /** This action is documented in wp-includes/post.php */
  2782. do_action( 'wp_insert_post', $post->ID, $post, true );
  2783. wp_after_insert_post( get_post( $post_id ), true, $post );
  2784. wp_trash_post_comments( $post_id );
  2785. /** This action is documented in wp-includes/post.php */
  2786. do_action( 'trashed_post', $post_id );
  2787. return $post;
  2788. }
  2789. /**
  2790. * Handles request to trash a changeset.
  2791. *
  2792. * @since 4.9.0
  2793. */
  2794. public function handle_changeset_trash_request() {
  2795. if ( ! is_user_logged_in() ) {
  2796. wp_send_json_error( 'unauthenticated' );
  2797. }
  2798. if ( ! $this->is_preview() ) {
  2799. wp_send_json_error( 'not_preview' );
  2800. }
  2801. if ( ! check_ajax_referer( 'trash_customize_changeset', 'nonce', false ) ) {
  2802. wp_send_json_error(
  2803. array(
  2804. 'code' => 'invalid_nonce',
  2805. 'message' => __( 'There was an authentication problem. Please reload and try again.' ),
  2806. )
  2807. );
  2808. }
  2809. $changeset_post_id = $this->changeset_post_id();
  2810. if ( ! $changeset_post_id ) {
  2811. wp_send_json_error(
  2812. array(
  2813. 'message' => __( 'No changes saved yet, so there is nothing to trash.' ),
  2814. 'code' => 'non_existent_changeset',
  2815. )
  2816. );
  2817. return;
  2818. }
  2819. if ( $changeset_post_id ) {
  2820. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) {
  2821. wp_send_json_error(
  2822. array(
  2823. 'code' => 'changeset_trash_unauthorized',
  2824. 'message' => __( 'Unable to trash changes.' ),
  2825. )
  2826. );
  2827. }
  2828. $lock_user = (int) wp_check_post_lock( $changeset_post_id );
  2829. if ( $lock_user && get_current_user_id() !== $lock_user ) {
  2830. wp_send_json_error(
  2831. array(
  2832. 'code' => 'changeset_locked',
  2833. 'message' => __( 'Changeset is being edited by other user.' ),
  2834. 'lockUser' => $this->get_lock_user_data( $lock_user ),
  2835. )
  2836. );
  2837. }
  2838. }
  2839. if ( 'trash' === get_post_status( $changeset_post_id ) ) {
  2840. wp_send_json_error(
  2841. array(
  2842. 'message' => __( 'Changes have already been trashed.' ),
  2843. 'code' => 'changeset_already_trashed',
  2844. )
  2845. );
  2846. return;
  2847. }
  2848. $r = $this->trash_changeset_post( $changeset_post_id );
  2849. if ( ! ( $r instanceof WP_Post ) ) {
  2850. wp_send_json_error(
  2851. array(
  2852. 'code' => 'changeset_trash_failure',
  2853. 'message' => __( 'Unable to trash changes.' ),
  2854. )
  2855. );
  2856. }
  2857. wp_send_json_success(
  2858. array(
  2859. 'message' => __( 'Changes trashed successfully.' ),
  2860. )
  2861. );
  2862. }
  2863. /**
  2864. * Re-maps 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps.
  2865. *
  2866. * There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to
  2867. * the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently
  2868. * required in core for `wp_create_post_autosave()` because it will call
  2869. * `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the
  2870. * the caps for the customize_changeset post type are all mapping to the meta capability.
  2871. * This should be able to be removed once #40922 is addressed in core.
  2872. *
  2873. * @since 4.9.0
  2874. *
  2875. * @link https://core.trac.wordpress.org/ticket/40922
  2876. * @see WP_Customize_Manager::save_changeset_post()
  2877. * @see _wp_translate_postdata()
  2878. *
  2879. * @param string[] $caps Array of the user's capabilities.
  2880. * @param string $cap Capability name.
  2881. * @param int $user_id The user ID.
  2882. * @param array $args Adds the context to the cap. Typically the object ID.
  2883. * @return array Capabilities.
  2884. */
  2885. public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) {
  2886. if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) {
  2887. $post_type_obj = get_post_type_object( 'customize_changeset' );
  2888. $caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id );
  2889. }
  2890. return $caps;
  2891. }
  2892. /**
  2893. * Marks the changeset post as being currently edited by the current user.
  2894. *
  2895. * @since 4.9.0
  2896. *
  2897. * @param int $changeset_post_id Changeset post ID.
  2898. * @param bool $take_over Whether to take over the changeset. Default false.
  2899. */
  2900. public function set_changeset_lock( $changeset_post_id, $take_over = false ) {
  2901. if ( $changeset_post_id ) {
  2902. $can_override = ! (bool) get_post_meta( $changeset_post_id, '_edit_lock', true );
  2903. if ( $take_over ) {
  2904. $can_override = true;
  2905. }
  2906. if ( $can_override ) {
  2907. $lock = sprintf( '%s:%s', time(), get_current_user_id() );
  2908. update_post_meta( $changeset_post_id, '_edit_lock', $lock );
  2909. } else {
  2910. $this->refresh_changeset_lock( $changeset_post_id );
  2911. }
  2912. }
  2913. }
  2914. /**
  2915. * Refreshes changeset lock with the current time if current user edited the changeset before.
  2916. *
  2917. * @since 4.9.0
  2918. *
  2919. * @param int $changeset_post_id Changeset post ID.
  2920. */
  2921. public function refresh_changeset_lock( $changeset_post_id ) {
  2922. if ( ! $changeset_post_id ) {
  2923. return;
  2924. }
  2925. $lock = get_post_meta( $changeset_post_id, '_edit_lock', true );
  2926. $lock = explode( ':', $lock );
  2927. if ( $lock && ! empty( $lock[1] ) ) {
  2928. $user_id = (int) $lock[1];
  2929. $current_user_id = get_current_user_id();
  2930. if ( $user_id === $current_user_id ) {
  2931. $lock = sprintf( '%s:%s', time(), $user_id );
  2932. update_post_meta( $changeset_post_id, '_edit_lock', $lock );
  2933. }
  2934. }
  2935. }
  2936. /**
  2937. * Filters heartbeat settings for the Customizer.
  2938. *
  2939. * @since 4.9.0
  2940. *
  2941. * @global string $pagenow The filename of the current screen.
  2942. *
  2943. * @param array $settings Current settings to filter.
  2944. * @return array Heartbeat settings.
  2945. */
  2946. public function add_customize_screen_to_heartbeat_settings( $settings ) {
  2947. global $pagenow;
  2948. if ( 'customize.php' === $pagenow ) {
  2949. $settings['screenId'] = 'customize';
  2950. }
  2951. return $settings;
  2952. }
  2953. /**
  2954. * Gets lock user data.
  2955. *
  2956. * @since 4.9.0
  2957. *
  2958. * @param int $user_id User ID.
  2959. * @return array|null User data formatted for client.
  2960. */
  2961. protected function get_lock_user_data( $user_id ) {
  2962. if ( ! $user_id ) {
  2963. return null;
  2964. }
  2965. $lock_user = get_userdata( $user_id );
  2966. if ( ! $lock_user ) {
  2967. return null;
  2968. }
  2969. return array(
  2970. 'id' => $lock_user->ID,
  2971. 'name' => $lock_user->display_name,
  2972. 'avatar' => get_avatar_url( $lock_user->ID, array( 'size' => 128 ) ),
  2973. );
  2974. }
  2975. /**
  2976. * Checks locked changeset with heartbeat API.
  2977. *
  2978. * @since 4.9.0
  2979. *
  2980. * @param array $response The Heartbeat response.
  2981. * @param array $data The $_POST data sent.
  2982. * @param string $screen_id The screen id.
  2983. * @return array The Heartbeat response.
  2984. */
  2985. public function check_changeset_lock_with_heartbeat( $response, $data, $screen_id ) {
  2986. if ( isset( $data['changeset_uuid'] ) ) {
  2987. $changeset_post_id = $this->find_changeset_post_id( $data['changeset_uuid'] );
  2988. } else {
  2989. $changeset_post_id = $this->changeset_post_id();
  2990. }
  2991. if (
  2992. array_key_exists( 'check_changeset_lock', $data )
  2993. && 'customize' === $screen_id
  2994. && $changeset_post_id
  2995. && current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id )
  2996. ) {
  2997. $lock_user_id = wp_check_post_lock( $changeset_post_id );
  2998. if ( $lock_user_id ) {
  2999. $response['customize_changeset_lock_user'] = $this->get_lock_user_data( $lock_user_id );
  3000. } else {
  3001. // Refreshing time will ensure that the user is sitting on customizer and has not closed the customizer tab.
  3002. $this->refresh_changeset_lock( $changeset_post_id );
  3003. }
  3004. }
  3005. return $response;
  3006. }
  3007. /**
  3008. * Removes changeset lock when take over request is sent via Ajax.
  3009. *
  3010. * @since 4.9.0
  3011. */
  3012. public function handle_override_changeset_lock_request() {
  3013. if ( ! $this->is_preview() ) {
  3014. wp_send_json_error( 'not_preview', 400 );
  3015. }
  3016. if ( ! check_ajax_referer( 'customize_override_changeset_lock', 'nonce', false ) ) {
  3017. wp_send_json_error(
  3018. array(
  3019. 'code' => 'invalid_nonce',
  3020. 'message' => __( 'Security check failed.' ),
  3021. )
  3022. );
  3023. }
  3024. $changeset_post_id = $this->changeset_post_id();
  3025. if ( empty( $changeset_post_id ) ) {
  3026. wp_send_json_error(
  3027. array(
  3028. 'code' => 'no_changeset_found_to_take_over',
  3029. 'message' => __( 'No changeset found to take over' ),
  3030. )
  3031. );
  3032. }
  3033. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) {
  3034. wp_send_json_error(
  3035. array(
  3036. 'code' => 'cannot_remove_changeset_lock',
  3037. 'message' => __( 'Sorry, you are not allowed to take over.' ),
  3038. )
  3039. );
  3040. }
  3041. $this->set_changeset_lock( $changeset_post_id, true );
  3042. wp_send_json_success( 'changeset_taken_over' );
  3043. }
  3044. /**
  3045. * Determines whether a changeset revision should be made.
  3046. *
  3047. * @since 4.7.0
  3048. * @var bool
  3049. */
  3050. protected $store_changeset_revision;
  3051. /**
  3052. * Filters whether a changeset has changed to create a new revision.
  3053. *
  3054. * Note that this will not be called while a changeset post remains in auto-draft status.
  3055. *
  3056. * @since 4.7.0
  3057. *
  3058. * @param bool $post_has_changed Whether the post has changed.
  3059. * @param WP_Post $last_revision The last revision post object.
  3060. * @param WP_Post $post The post object.
  3061. * @return bool Whether a revision should be made.
  3062. */
  3063. public function _filter_revision_post_has_changed( $post_has_changed, $last_revision, $post ) {
  3064. unset( $last_revision );
  3065. if ( 'customize_changeset' === $post->post_type ) {
  3066. $post_has_changed = $this->store_changeset_revision;
  3067. }
  3068. return $post_has_changed;
  3069. }
  3070. /**
  3071. * Publishes the values of a changeset.
  3072. *
  3073. * This will publish the values contained in a changeset, even changesets that do not
  3074. * correspond to current manager instance. This is called by
  3075. * `_wp_customize_publish_changeset()` when a customize_changeset post is
  3076. * transitioned to the `publish` status. As such, this method should not be
  3077. * called directly and instead `wp_publish_post()` should be used.
  3078. *
  3079. * Please note that if the settings in the changeset are for a non-activated
  3080. * theme, the theme must first be switched to (via `switch_theme()`) before
  3081. * invoking this method.
  3082. *
  3083. * @since 4.7.0
  3084. *
  3085. * @see _wp_customize_publish_changeset()
  3086. * @global wpdb $wpdb WordPress database abstraction object.
  3087. *
  3088. * @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance.
  3089. * @return true|WP_Error True or error info.
  3090. */
  3091. public function _publish_changeset_values( $changeset_post_id ) {
  3092. global $wpdb;
  3093. $publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  3094. if ( is_wp_error( $publishing_changeset_data ) ) {
  3095. return $publishing_changeset_data;
  3096. }
  3097. $changeset_post = get_post( $changeset_post_id );
  3098. /*
  3099. * Temporarily override the changeset context so that it will be read
  3100. * in calls to unsanitized_post_values() and so that it will be available
  3101. * on the $wp_customize object passed to hooks during the save logic.
  3102. */
  3103. $previous_changeset_post_id = $this->_changeset_post_id;
  3104. $this->_changeset_post_id = $changeset_post_id;
  3105. $previous_changeset_uuid = $this->_changeset_uuid;
  3106. $this->_changeset_uuid = $changeset_post->post_name;
  3107. $previous_changeset_data = $this->_changeset_data;
  3108. $this->_changeset_data = $publishing_changeset_data;
  3109. // Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved.
  3110. $setting_user_ids = array();
  3111. $theme_mod_settings = array();
  3112. $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/';
  3113. $matches = array();
  3114. foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) {
  3115. $actual_setting_id = null;
  3116. $is_theme_mod_setting = (
  3117. isset( $setting_params['value'] )
  3118. &&
  3119. isset( $setting_params['type'] )
  3120. &&
  3121. 'theme_mod' === $setting_params['type']
  3122. &&
  3123. preg_match( $namespace_pattern, $raw_setting_id, $matches )
  3124. );
  3125. if ( $is_theme_mod_setting ) {
  3126. if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) {
  3127. $theme_mod_settings[ $matches['stylesheet'] ] = array();
  3128. }
  3129. $theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params;
  3130. if ( $this->get_stylesheet() === $matches['stylesheet'] ) {
  3131. $actual_setting_id = $matches['setting_id'];
  3132. }
  3133. } else {
  3134. $actual_setting_id = $raw_setting_id;
  3135. }
  3136. // Keep track of the user IDs for settings actually for this theme.
  3137. if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) {
  3138. $setting_user_ids[ $actual_setting_id ] = $setting_params['user_id'];
  3139. }
  3140. }
  3141. $changeset_setting_values = $this->unsanitized_post_values(
  3142. array(
  3143. 'exclude_post_data' => true,
  3144. 'exclude_changeset' => false,
  3145. )
  3146. );
  3147. $changeset_setting_ids = array_keys( $changeset_setting_values );
  3148. $this->add_dynamic_settings( $changeset_setting_ids );
  3149. /**
  3150. * Fires once the theme has switched in the Customizer, but before settings
  3151. * have been saved.
  3152. *
  3153. * @since 3.4.0
  3154. *
  3155. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  3156. */
  3157. do_action( 'customize_save', $this );
  3158. /*
  3159. * Ensure that all settings will allow themselves to be saved. Note that
  3160. * this is safe because the setting would have checked the capability
  3161. * when the setting value was written into the changeset. So this is why
  3162. * an additional capability check is not required here.
  3163. */
  3164. $original_setting_capabilities = array();
  3165. foreach ( $changeset_setting_ids as $setting_id ) {
  3166. $setting = $this->get_setting( $setting_id );
  3167. if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) {
  3168. $original_setting_capabilities[ $setting->id ] = $setting->capability;
  3169. $setting->capability = 'exist';
  3170. }
  3171. }
  3172. $original_user_id = get_current_user_id();
  3173. foreach ( $changeset_setting_ids as $setting_id ) {
  3174. $setting = $this->get_setting( $setting_id );
  3175. if ( $setting ) {
  3176. /*
  3177. * Set the current user to match the user who saved the value into
  3178. * the changeset so that any filters that apply during the save
  3179. * process will respect the original user's capabilities. This
  3180. * will ensure, for example, that KSES won't strip unsafe HTML
  3181. * when a scheduled changeset publishes via WP Cron.
  3182. */
  3183. if ( isset( $setting_user_ids[ $setting_id ] ) ) {
  3184. wp_set_current_user( $setting_user_ids[ $setting_id ] );
  3185. } else {
  3186. wp_set_current_user( $original_user_id );
  3187. }
  3188. $setting->save();
  3189. }
  3190. }
  3191. wp_set_current_user( $original_user_id );
  3192. // Update the stashed theme mod settings, removing the active theme's stashed settings, if activated.
  3193. if ( did_action( 'switch_theme' ) ) {
  3194. $other_theme_mod_settings = $theme_mod_settings;
  3195. unset( $other_theme_mod_settings[ $this->get_stylesheet() ] );
  3196. $this->update_stashed_theme_mod_settings( $other_theme_mod_settings );
  3197. }
  3198. /**
  3199. * Fires after Customize settings have been saved.
  3200. *
  3201. * @since 3.6.0
  3202. *
  3203. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  3204. */
  3205. do_action( 'customize_save_after', $this );
  3206. // Restore original capabilities.
  3207. foreach ( $original_setting_capabilities as $setting_id => $capability ) {
  3208. $setting = $this->get_setting( $setting_id );
  3209. if ( $setting ) {
  3210. $setting->capability = $capability;
  3211. }
  3212. }
  3213. // Restore original changeset data.
  3214. $this->_changeset_data = $previous_changeset_data;
  3215. $this->_changeset_post_id = $previous_changeset_post_id;
  3216. $this->_changeset_uuid = $previous_changeset_uuid;
  3217. /*
  3218. * Convert all autosave revisions into their own auto-drafts so that users can be prompted to
  3219. * restore them when a changeset is published, but they had been locked out from including
  3220. * their changes in the changeset.
  3221. */
  3222. $revisions = wp_get_post_revisions( $changeset_post_id, array( 'check_enabled' => false ) );
  3223. foreach ( $revisions as $revision ) {
  3224. if ( false !== strpos( $revision->post_name, "{$changeset_post_id}-autosave" ) ) {
  3225. $wpdb->update(
  3226. $wpdb->posts,
  3227. array(
  3228. 'post_status' => 'auto-draft',
  3229. 'post_type' => 'customize_changeset',
  3230. 'post_name' => wp_generate_uuid4(),
  3231. 'post_parent' => 0,
  3232. ),
  3233. array(
  3234. 'ID' => $revision->ID,
  3235. )
  3236. );
  3237. clean_post_cache( $revision->ID );
  3238. }
  3239. }
  3240. return true;
  3241. }
  3242. /**
  3243. * Updates stashed theme mod settings.
  3244. *
  3245. * @since 4.7.0
  3246. *
  3247. * @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings.
  3248. * @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes.
  3249. */
  3250. protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) {
  3251. $stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' );
  3252. if ( empty( $stashed_theme_mod_settings ) ) {
  3253. $stashed_theme_mod_settings = array();
  3254. }
  3255. // Delete any stashed theme mods for the active theme since they would have been loaded and saved upon activation.
  3256. unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] );
  3257. // Merge inactive theme mods with the stashed theme mod settings.
  3258. foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) {
  3259. if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) {
  3260. $stashed_theme_mod_settings[ $stylesheet ] = array();
  3261. }
  3262. $stashed_theme_mod_settings[ $stylesheet ] = array_merge(
  3263. $stashed_theme_mod_settings[ $stylesheet ],
  3264. $theme_mod_settings
  3265. );
  3266. }
  3267. $autoload = false;
  3268. $result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload );
  3269. if ( ! $result ) {
  3270. return false;
  3271. }
  3272. return $stashed_theme_mod_settings;
  3273. }
  3274. /**
  3275. * Refreshes nonces for the current preview.
  3276. *
  3277. * @since 4.2.0
  3278. */
  3279. public function refresh_nonces() {
  3280. if ( ! $this->is_preview() ) {
  3281. wp_send_json_error( 'not_preview' );
  3282. }
  3283. wp_send_json_success( $this->get_nonces() );
  3284. }
  3285. /**
  3286. * Deletes a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock.
  3287. *
  3288. * @since 4.9.0
  3289. */
  3290. public function handle_dismiss_autosave_or_lock_request() {
  3291. // Calls to dismiss_user_auto_draft_changesets() and wp_get_post_autosave() require non-zero get_current_user_id().
  3292. if ( ! is_user_logged_in() ) {
  3293. wp_send_json_error( 'unauthenticated', 401 );
  3294. }
  3295. if ( ! $this->is_preview() ) {
  3296. wp_send_json_error( 'not_preview', 400 );
  3297. }
  3298. if ( ! check_ajax_referer( 'customize_dismiss_autosave_or_lock', 'nonce', false ) ) {
  3299. wp_send_json_error( 'invalid_nonce', 403 );
  3300. }
  3301. $changeset_post_id = $this->changeset_post_id();
  3302. $dismiss_lock = ! empty( $_POST['dismiss_lock'] );
  3303. $dismiss_autosave = ! empty( $_POST['dismiss_autosave'] );
  3304. if ( $dismiss_lock ) {
  3305. if ( empty( $changeset_post_id ) && ! $dismiss_autosave ) {
  3306. wp_send_json_error( 'no_changeset_to_dismiss_lock', 404 );
  3307. }
  3308. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) && ! $dismiss_autosave ) {
  3309. wp_send_json_error( 'cannot_remove_changeset_lock', 403 );
  3310. }
  3311. delete_post_meta( $changeset_post_id, '_edit_lock' );
  3312. if ( ! $dismiss_autosave ) {
  3313. wp_send_json_success( 'changeset_lock_dismissed' );
  3314. }
  3315. }
  3316. if ( $dismiss_autosave ) {
  3317. if ( empty( $changeset_post_id ) || 'auto-draft' === get_post_status( $changeset_post_id ) ) {
  3318. $dismissed = $this->dismiss_user_auto_draft_changesets();
  3319. if ( $dismissed > 0 ) {
  3320. wp_send_json_success( 'auto_draft_dismissed' );
  3321. } else {
  3322. wp_send_json_error( 'no_auto_draft_to_delete', 404 );
  3323. }
  3324. } else {
  3325. $revision = wp_get_post_autosave( $changeset_post_id, get_current_user_id() );
  3326. if ( $revision ) {
  3327. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) {
  3328. wp_send_json_error( 'cannot_delete_autosave_revision', 403 );
  3329. }
  3330. if ( ! wp_delete_post( $revision->ID, true ) ) {
  3331. wp_send_json_error( 'autosave_revision_deletion_failure', 500 );
  3332. } else {
  3333. wp_send_json_success( 'autosave_revision_deleted' );
  3334. }
  3335. } else {
  3336. wp_send_json_error( 'no_autosave_revision_to_delete', 404 );
  3337. }
  3338. }
  3339. }
  3340. wp_send_json_error( 'unknown_error', 500 );
  3341. }
  3342. /**
  3343. * Adds a customize setting.
  3344. *
  3345. * @since 3.4.0
  3346. * @since 4.5.0 Return added WP_Customize_Setting instance.
  3347. *
  3348. * @see WP_Customize_Setting::__construct()
  3349. * @link https://developer.wordpress.org/themes/customize-api
  3350. *
  3351. * @param WP_Customize_Setting|string $id Customize Setting object, or ID.
  3352. * @param array $args Optional. Array of properties for the new Setting object.
  3353. * See WP_Customize_Setting::__construct() for information
  3354. * on accepted arguments. Default empty array.
  3355. * @return WP_Customize_Setting The instance of the setting that was added.
  3356. */
  3357. public function add_setting( $id, $args = array() ) {
  3358. if ( $id instanceof WP_Customize_Setting ) {
  3359. $setting = $id;
  3360. } else {
  3361. $class = 'WP_Customize_Setting';
  3362. /** This filter is documented in wp-includes/class-wp-customize-manager.php */
  3363. $args = apply_filters( 'customize_dynamic_setting_args', $args, $id );
  3364. /** This filter is documented in wp-includes/class-wp-customize-manager.php */
  3365. $class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args );
  3366. $setting = new $class( $this, $id, $args );
  3367. }
  3368. $this->settings[ $setting->id ] = $setting;
  3369. return $setting;
  3370. }
  3371. /**
  3372. * Registers any dynamically-created settings, such as those from $_POST['customized']
  3373. * that have no corresponding setting created.
  3374. *
  3375. * This is a mechanism to "wake up" settings that have been dynamically created
  3376. * on the front end and have been sent to WordPress in `$_POST['customized']`. When WP
  3377. * loads, the dynamically-created settings then will get created and previewed
  3378. * even though they are not directly created statically with code.
  3379. *
  3380. * @since 4.2.0
  3381. *
  3382. * @param array $setting_ids The setting IDs to add.
  3383. * @return array The WP_Customize_Setting objects added.
  3384. */
  3385. public function add_dynamic_settings( $setting_ids ) {
  3386. $new_settings = array();
  3387. foreach ( $setting_ids as $setting_id ) {
  3388. // Skip settings already created.
  3389. if ( $this->get_setting( $setting_id ) ) {
  3390. continue;
  3391. }
  3392. $setting_args = false;
  3393. $setting_class = 'WP_Customize_Setting';
  3394. /**
  3395. * Filters a dynamic setting's constructor args.
  3396. *
  3397. * For a dynamic setting to be registered, this filter must be employed
  3398. * to override the default false value with an array of args to pass to
  3399. * the WP_Customize_Setting constructor.
  3400. *
  3401. * @since 4.2.0
  3402. *
  3403. * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
  3404. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  3405. */
  3406. $setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id );
  3407. if ( false === $setting_args ) {
  3408. continue;
  3409. }
  3410. /**
  3411. * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
  3412. *
  3413. * @since 4.2.0
  3414. *
  3415. * @param string $setting_class WP_Customize_Setting or a subclass.
  3416. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  3417. * @param array $setting_args WP_Customize_Setting or a subclass.
  3418. */
  3419. $setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args );
  3420. $setting = new $setting_class( $this, $setting_id, $setting_args );
  3421. $this->add_setting( $setting );
  3422. $new_settings[] = $setting;
  3423. }
  3424. return $new_settings;
  3425. }
  3426. /**
  3427. * Retrieves a customize setting.
  3428. *
  3429. * @since 3.4.0
  3430. *
  3431. * @param string $id Customize Setting ID.
  3432. * @return WP_Customize_Setting|void The setting, if set.
  3433. */
  3434. public function get_setting( $id ) {
  3435. if ( isset( $this->settings[ $id ] ) ) {
  3436. return $this->settings[ $id ];
  3437. }
  3438. }
  3439. /**
  3440. * Removes a customize setting.
  3441. *
  3442. * Note that removing the setting doesn't destroy the WP_Customize_Setting instance or remove its filters.
  3443. *
  3444. * @since 3.4.0
  3445. *
  3446. * @param string $id Customize Setting ID.
  3447. */
  3448. public function remove_setting( $id ) {
  3449. unset( $this->settings[ $id ] );
  3450. }
  3451. /**
  3452. * Adds a customize panel.
  3453. *
  3454. * @since 4.0.0
  3455. * @since 4.5.0 Return added WP_Customize_Panel instance.
  3456. *
  3457. * @see WP_Customize_Panel::__construct()
  3458. *
  3459. * @param WP_Customize_Panel|string $id Customize Panel object, or ID.
  3460. * @param array $args Optional. Array of properties for the new Panel object.
  3461. * See WP_Customize_Panel::__construct() for information
  3462. * on accepted arguments. Default empty array.
  3463. * @return WP_Customize_Panel The instance of the panel that was added.
  3464. */
  3465. public function add_panel( $id, $args = array() ) {
  3466. if ( $id instanceof WP_Customize_Panel ) {
  3467. $panel = $id;
  3468. } else {
  3469. $panel = new WP_Customize_Panel( $this, $id, $args );
  3470. }
  3471. $this->panels[ $panel->id ] = $panel;
  3472. return $panel;
  3473. }
  3474. /**
  3475. * Retrieves a customize panel.
  3476. *
  3477. * @since 4.0.0
  3478. *
  3479. * @param string $id Panel ID to get.
  3480. * @return WP_Customize_Panel|void Requested panel instance, if set.
  3481. */
  3482. public function get_panel( $id ) {
  3483. if ( isset( $this->panels[ $id ] ) ) {
  3484. return $this->panels[ $id ];
  3485. }
  3486. }
  3487. /**
  3488. * Removes a customize panel.
  3489. *
  3490. * Note that removing the panel doesn't destroy the WP_Customize_Panel instance or remove its filters.
  3491. *
  3492. * @since 4.0.0
  3493. *
  3494. * @param string $id Panel ID to remove.
  3495. */
  3496. public function remove_panel( $id ) {
  3497. // Removing core components this way is _doing_it_wrong().
  3498. if ( in_array( $id, $this->components, true ) ) {
  3499. _doing_it_wrong(
  3500. __METHOD__,
  3501. sprintf(
  3502. /* translators: 1: Panel ID, 2: Link to 'customize_loaded_components' filter reference. */
  3503. __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ),
  3504. $id,
  3505. sprintf(
  3506. '<a href="%1$s">%2$s</a>',
  3507. esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ),
  3508. '<code>customize_loaded_components</code>'
  3509. )
  3510. ),
  3511. '4.5.0'
  3512. );
  3513. }
  3514. unset( $this->panels[ $id ] );
  3515. }
  3516. /**
  3517. * Registers a customize panel type.
  3518. *
  3519. * Registered types are eligible to be rendered via JS and created dynamically.
  3520. *
  3521. * @since 4.3.0
  3522. *
  3523. * @see WP_Customize_Panel
  3524. *
  3525. * @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel.
  3526. */
  3527. public function register_panel_type( $panel ) {
  3528. $this->registered_panel_types[] = $panel;
  3529. }
  3530. /**
  3531. * Renders JS templates for all registered panel types.
  3532. *
  3533. * @since 4.3.0
  3534. */
  3535. public function render_panel_templates() {
  3536. foreach ( $this->registered_panel_types as $panel_type ) {
  3537. $panel = new $panel_type( $this, 'temp', array() );
  3538. $panel->print_template();
  3539. }
  3540. }
  3541. /**
  3542. * Adds a customize section.
  3543. *
  3544. * @since 3.4.0
  3545. * @since 4.5.0 Return added WP_Customize_Section instance.
  3546. *
  3547. * @see WP_Customize_Section::__construct()
  3548. *
  3549. * @param WP_Customize_Section|string $id Customize Section object, or ID.
  3550. * @param array $args Optional. Array of properties for the new Section object.
  3551. * See WP_Customize_Section::__construct() for information
  3552. * on accepted arguments. Default empty array.
  3553. * @return WP_Customize_Section The instance of the section that was added.
  3554. */
  3555. public function add_section( $id, $args = array() ) {
  3556. if ( $id instanceof WP_Customize_Section ) {
  3557. $section = $id;
  3558. } else {
  3559. $section = new WP_Customize_Section( $this, $id, $args );
  3560. }
  3561. $this->sections[ $section->id ] = $section;
  3562. return $section;
  3563. }
  3564. /**
  3565. * Retrieves a customize section.
  3566. *
  3567. * @since 3.4.0
  3568. *
  3569. * @param string $id Section ID.
  3570. * @return WP_Customize_Section|void The section, if set.
  3571. */
  3572. public function get_section( $id ) {
  3573. if ( isset( $this->sections[ $id ] ) ) {
  3574. return $this->sections[ $id ];
  3575. }
  3576. }
  3577. /**
  3578. * Removes a customize section.
  3579. *
  3580. * Note that removing the section doesn't destroy the WP_Customize_Section instance or remove its filters.
  3581. *
  3582. * @since 3.4.0
  3583. *
  3584. * @param string $id Section ID.
  3585. */
  3586. public function remove_section( $id ) {
  3587. unset( $this->sections[ $id ] );
  3588. }
  3589. /**
  3590. * Registers a customize section type.
  3591. *
  3592. * Registered types are eligible to be rendered via JS and created dynamically.
  3593. *
  3594. * @since 4.3.0
  3595. *
  3596. * @see WP_Customize_Section
  3597. *
  3598. * @param string $section Name of a custom section which is a subclass of WP_Customize_Section.
  3599. */
  3600. public function register_section_type( $section ) {
  3601. $this->registered_section_types[] = $section;
  3602. }
  3603. /**
  3604. * Renders JS templates for all registered section types.
  3605. *
  3606. * @since 4.3.0
  3607. */
  3608. public function render_section_templates() {
  3609. foreach ( $this->registered_section_types as $section_type ) {
  3610. $section = new $section_type( $this, 'temp', array() );
  3611. $section->print_template();
  3612. }
  3613. }
  3614. /**
  3615. * Adds a customize control.
  3616. *
  3617. * @since 3.4.0
  3618. * @since 4.5.0 Return added WP_Customize_Control instance.
  3619. *
  3620. * @see WP_Customize_Control::__construct()
  3621. *
  3622. * @param WP_Customize_Control|string $id Customize Control object, or ID.
  3623. * @param array $args Optional. Array of properties for the new Control object.
  3624. * See WP_Customize_Control::__construct() for information
  3625. * on accepted arguments. Default empty array.
  3626. * @return WP_Customize_Control The instance of the control that was added.
  3627. */
  3628. public function add_control( $id, $args = array() ) {
  3629. if ( $id instanceof WP_Customize_Control ) {
  3630. $control = $id;
  3631. } else {
  3632. $control = new WP_Customize_Control( $this, $id, $args );
  3633. }
  3634. $this->controls[ $control->id ] = $control;
  3635. return $control;
  3636. }
  3637. /**
  3638. * Retrieves a customize control.
  3639. *
  3640. * @since 3.4.0
  3641. *
  3642. * @param string $id ID of the control.
  3643. * @return WP_Customize_Control|void The control object, if set.
  3644. */
  3645. public function get_control( $id ) {
  3646. if ( isset( $this->controls[ $id ] ) ) {
  3647. return $this->controls[ $id ];
  3648. }
  3649. }
  3650. /**
  3651. * Removes a customize control.
  3652. *
  3653. * Note that removing the control doesn't destroy the WP_Customize_Control instance or remove its filters.
  3654. *
  3655. * @since 3.4.0
  3656. *
  3657. * @param string $id ID of the control.
  3658. */
  3659. public function remove_control( $id ) {
  3660. unset( $this->controls[ $id ] );
  3661. }
  3662. /**
  3663. * Registers a customize control type.
  3664. *
  3665. * Registered types are eligible to be rendered via JS and created dynamically.
  3666. *
  3667. * @since 4.1.0
  3668. *
  3669. * @param string $control Name of a custom control which is a subclass of
  3670. * WP_Customize_Control.
  3671. */
  3672. public function register_control_type( $control ) {
  3673. $this->registered_control_types[] = $control;
  3674. }
  3675. /**
  3676. * Renders JS templates for all registered control types.
  3677. *
  3678. * @since 4.1.0
  3679. */
  3680. public function render_control_templates() {
  3681. if ( $this->branching() ) {
  3682. $l10n = array(
  3683. /* translators: %s: User who is customizing the changeset in customizer. */
  3684. 'locked' => __( '%s is already customizing this changeset. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ),
  3685. /* translators: %s: User who is customizing the changeset in customizer. */
  3686. 'locked_allow_override' => __( '%s is already customizing this changeset. Do you want to take over?' ),
  3687. );
  3688. } else {
  3689. $l10n = array(
  3690. /* translators: %s: User who is customizing the changeset in customizer. */
  3691. 'locked' => __( '%s is already customizing this site. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ),
  3692. /* translators: %s: User who is customizing the changeset in customizer. */
  3693. 'locked_allow_override' => __( '%s is already customizing this site. Do you want to take over?' ),
  3694. );
  3695. }
  3696. foreach ( $this->registered_control_types as $control_type ) {
  3697. $control = new $control_type(
  3698. $this,
  3699. 'temp',
  3700. array(
  3701. 'settings' => array(),
  3702. )
  3703. );
  3704. $control->print_template();
  3705. }
  3706. ?>
  3707. <script type="text/html" id="tmpl-customize-control-default-content">
  3708. <#
  3709. var inputId = _.uniqueId( 'customize-control-default-input-' );
  3710. var descriptionId = _.uniqueId( 'customize-control-default-description-' );
  3711. var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : '';
  3712. #>
  3713. <# switch ( data.type ) {
  3714. case 'checkbox': #>
  3715. <span class="customize-inside-control-row">
  3716. <input
  3717. id="{{ inputId }}"
  3718. {{{ describedByAttr }}}
  3719. type="checkbox"
  3720. value="{{ data.value }}"
  3721. data-customize-setting-key-link="default"
  3722. >
  3723. <label for="{{ inputId }}">
  3724. {{ data.label }}
  3725. </label>
  3726. <# if ( data.description ) { #>
  3727. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3728. <# } #>
  3729. </span>
  3730. <#
  3731. break;
  3732. case 'radio':
  3733. if ( ! data.choices ) {
  3734. return;
  3735. }
  3736. #>
  3737. <# if ( data.label ) { #>
  3738. <label for="{{ inputId }}" class="customize-control-title">
  3739. {{ data.label }}
  3740. </label>
  3741. <# } #>
  3742. <# if ( data.description ) { #>
  3743. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3744. <# } #>
  3745. <# _.each( data.choices, function( val, key ) { #>
  3746. <span class="customize-inside-control-row">
  3747. <#
  3748. var value, text;
  3749. if ( _.isObject( val ) ) {
  3750. value = val.value;
  3751. text = val.text;
  3752. } else {
  3753. value = key;
  3754. text = val;
  3755. }
  3756. #>
  3757. <input
  3758. id="{{ inputId + '-' + value }}"
  3759. type="radio"
  3760. value="{{ value }}"
  3761. name="{{ inputId }}"
  3762. data-customize-setting-key-link="default"
  3763. {{{ describedByAttr }}}
  3764. >
  3765. <label for="{{ inputId + '-' + value }}">{{ text }}</label>
  3766. </span>
  3767. <# } ); #>
  3768. <#
  3769. break;
  3770. default:
  3771. #>
  3772. <# if ( data.label ) { #>
  3773. <label for="{{ inputId }}" class="customize-control-title">
  3774. {{ data.label }}
  3775. </label>
  3776. <# } #>
  3777. <# if ( data.description ) { #>
  3778. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3779. <# } #>
  3780. <#
  3781. var inputAttrs = {
  3782. id: inputId,
  3783. 'data-customize-setting-key-link': 'default'
  3784. };
  3785. if ( 'textarea' === data.type ) {
  3786. inputAttrs.rows = '5';
  3787. } else if ( 'button' === data.type ) {
  3788. inputAttrs['class'] = 'button button-secondary';
  3789. inputAttrs.type = 'button';
  3790. } else {
  3791. inputAttrs.type = data.type;
  3792. }
  3793. if ( data.description ) {
  3794. inputAttrs['aria-describedby'] = descriptionId;
  3795. }
  3796. _.extend( inputAttrs, data.input_attrs );
  3797. #>
  3798. <# if ( 'button' === data.type ) { #>
  3799. <button
  3800. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3801. {{{ key }}}="{{ value }}"
  3802. <# } ); #>
  3803. >{{ inputAttrs.value }}</button>
  3804. <# } else if ( 'textarea' === data.type ) { #>
  3805. <textarea
  3806. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3807. {{{ key }}}="{{ value }}"
  3808. <# }); #>
  3809. >{{ inputAttrs.value }}</textarea>
  3810. <# } else if ( 'select' === data.type ) { #>
  3811. <# delete inputAttrs.type; #>
  3812. <select
  3813. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3814. {{{ key }}}="{{ value }}"
  3815. <# }); #>
  3816. >
  3817. <# _.each( data.choices, function( val, key ) { #>
  3818. <#
  3819. var value, text;
  3820. if ( _.isObject( val ) ) {
  3821. value = val.value;
  3822. text = val.text;
  3823. } else {
  3824. value = key;
  3825. text = val;
  3826. }
  3827. #>
  3828. <option value="{{ value }}">{{ text }}</option>
  3829. <# } ); #>
  3830. </select>
  3831. <# } else { #>
  3832. <input
  3833. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3834. {{{ key }}}="{{ value }}"
  3835. <# }); #>
  3836. >
  3837. <# } #>
  3838. <# } #>
  3839. </script>
  3840. <script type="text/html" id="tmpl-customize-notification">
  3841. <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}">
  3842. <div class="notification-message">{{{ data.message || data.code }}}</div>
  3843. <# if ( data.dismissible ) { #>
  3844. <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php _e( 'Dismiss' ); ?></span></button>
  3845. <# } #>
  3846. </li>
  3847. </script>
  3848. <script type="text/html" id="tmpl-customize-changeset-locked-notification">
  3849. <li class="notice notice-{{ data.type || 'info' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}">
  3850. <div class="notification-message customize-changeset-locked-message">
  3851. <img class="customize-changeset-locked-avatar" src="{{ data.lockUser.avatar }}" alt="{{ data.lockUser.name }}" />
  3852. <p class="currently-editing">
  3853. <# if ( data.message ) { #>
  3854. {{{ data.message }}}
  3855. <# } else if ( data.allowOverride ) { #>
  3856. <?php
  3857. echo esc_html( sprintf( $l10n['locked_allow_override'], '{{ data.lockUser.name }}' ) );
  3858. ?>
  3859. <# } else { #>
  3860. <?php
  3861. echo esc_html( sprintf( $l10n['locked'], '{{ data.lockUser.name }}' ) );
  3862. ?>
  3863. <# } #>
  3864. </p>
  3865. <p class="notice notice-error notice-alt" hidden></p>
  3866. <p class="action-buttons">
  3867. <# if ( data.returnUrl !== data.previewUrl ) { #>
  3868. <a class="button customize-notice-go-back-button" href="{{ data.returnUrl }}"><?php _e( 'Go back' ); ?></a>
  3869. <# } #>
  3870. <a class="button customize-notice-preview-button" href="{{ data.frontendPreviewUrl }}"><?php _e( 'Preview' ); ?></a>
  3871. <# if ( data.allowOverride ) { #>
  3872. <button class="button button-primary wp-tab-last customize-notice-take-over-button"><?php _e( 'Take over' ); ?></button>
  3873. <# } #>
  3874. </p>
  3875. </div>
  3876. </li>
  3877. </script>
  3878. <script type="text/html" id="tmpl-customize-code-editor-lint-error-notification">
  3879. <li class="notice notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}">
  3880. <div class="notification-message">{{{ data.message || data.code }}}</div>
  3881. <p>
  3882. <# var elementId = 'el-' + String( Math.random() ); #>
  3883. <input id="{{ elementId }}" type="checkbox">
  3884. <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label>
  3885. </p>
  3886. </li>
  3887. </script>
  3888. <?php
  3889. /* The following template is obsolete in core but retained for plugins. */
  3890. ?>
  3891. <script type="text/html" id="tmpl-customize-control-notifications">
  3892. <ul>
  3893. <# _.each( data.notifications, function( notification ) { #>
  3894. <li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li>
  3895. <# } ); #>
  3896. </ul>
  3897. </script>
  3898. <script type="text/html" id="tmpl-customize-preview-link-control" >
  3899. <# var elementPrefix = _.uniqueId( 'el' ) + '-' #>
  3900. <p class="customize-control-title">
  3901. <?php esc_html_e( 'Share Preview Link' ); ?>
  3902. </p>
  3903. <p class="description customize-control-description"><?php esc_html_e( 'See how changes would look live on your website, and share the preview with people who can\'t access the Customizer.' ); ?></p>
  3904. <div class="customize-control-notifications-container"></div>
  3905. <div class="preview-link-wrapper">
  3906. <label for="{{ elementPrefix }}customize-preview-link-input" class="screen-reader-text"><?php esc_html_e( 'Preview Link' ); ?></label>
  3907. <a href="" target="">
  3908. <span class="preview-control-element" data-component="url"></span>
  3909. <span class="screen-reader-text"><?php _e( '(opens in a new tab)' ); ?></span>
  3910. </a>
  3911. <input id="{{ elementPrefix }}customize-preview-link-input" readonly tabindex="-1" class="preview-control-element" data-component="input">
  3912. <button class="customize-copy-preview-link preview-control-element button button-secondary" data-component="button" data-copy-text="<?php esc_attr_e( 'Copy' ); ?>" data-copied-text="<?php esc_attr_e( 'Copied' ); ?>" ><?php esc_html_e( 'Copy' ); ?></button>
  3913. </div>
  3914. </script>
  3915. <script type="text/html" id="tmpl-customize-selected-changeset-status-control">
  3916. <# var inputId = _.uniqueId( 'customize-selected-changeset-status-control-input-' ); #>
  3917. <# var descriptionId = _.uniqueId( 'customize-selected-changeset-status-control-description-' ); #>
  3918. <# if ( data.label ) { #>
  3919. <label for="{{ inputId }}" class="customize-control-title">{{ data.label }}</label>
  3920. <# } #>
  3921. <# if ( data.description ) { #>
  3922. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3923. <# } #>
  3924. <# _.each( data.choices, function( choice ) { #>
  3925. <# var choiceId = inputId + '-' + choice.status; #>
  3926. <span class="customize-inside-control-row">
  3927. <input id="{{ choiceId }}" type="radio" value="{{ choice.status }}" name="{{ inputId }}" data-customize-setting-key-link="default">
  3928. <label for="{{ choiceId }}">{{ choice.label }}</label>
  3929. </span>
  3930. <# } ); #>
  3931. </script>
  3932. <?php
  3933. }
  3934. /**
  3935. * Helper function to compare two objects by priority, ensuring sort stability via instance_number.
  3936. *
  3937. * @since 3.4.0
  3938. * @deprecated 4.7.0 Use wp_list_sort()
  3939. *
  3940. * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A.
  3941. * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B.
  3942. * @return int
  3943. */
  3944. protected function _cmp_priority( $a, $b ) {
  3945. _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' );
  3946. if ( $a->priority === $b->priority ) {
  3947. return $a->instance_number - $b->instance_number;
  3948. } else {
  3949. return $a->priority - $b->priority;
  3950. }
  3951. }
  3952. /**
  3953. * Prepares panels, sections, and controls.
  3954. *
  3955. * For each, check if required related components exist,
  3956. * whether the user has the necessary capabilities,
  3957. * and sort by priority.
  3958. *
  3959. * @since 3.4.0
  3960. */
  3961. public function prepare_controls() {
  3962. $controls = array();
  3963. $this->controls = wp_list_sort(
  3964. $this->controls,
  3965. array(
  3966. 'priority' => 'ASC',
  3967. 'instance_number' => 'ASC',
  3968. ),
  3969. 'ASC',
  3970. true
  3971. );
  3972. foreach ( $this->controls as $id => $control ) {
  3973. if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) {
  3974. continue;
  3975. }
  3976. $this->sections[ $control->section ]->controls[] = $control;
  3977. $controls[ $id ] = $control;
  3978. }
  3979. $this->controls = $controls;
  3980. // Prepare sections.
  3981. $this->sections = wp_list_sort(
  3982. $this->sections,
  3983. array(
  3984. 'priority' => 'ASC',
  3985. 'instance_number' => 'ASC',
  3986. ),
  3987. 'ASC',
  3988. true
  3989. );
  3990. $sections = array();
  3991. foreach ( $this->sections as $section ) {
  3992. if ( ! $section->check_capabilities() ) {
  3993. continue;
  3994. }
  3995. $section->controls = wp_list_sort(
  3996. $section->controls,
  3997. array(
  3998. 'priority' => 'ASC',
  3999. 'instance_number' => 'ASC',
  4000. )
  4001. );
  4002. if ( ! $section->panel ) {
  4003. // Top-level section.
  4004. $sections[ $section->id ] = $section;
  4005. } else {
  4006. // This section belongs to a panel.
  4007. if ( isset( $this->panels [ $section->panel ] ) ) {
  4008. $this->panels[ $section->panel ]->sections[ $section->id ] = $section;
  4009. }
  4010. }
  4011. }
  4012. $this->sections = $sections;
  4013. // Prepare panels.
  4014. $this->panels = wp_list_sort(
  4015. $this->panels,
  4016. array(
  4017. 'priority' => 'ASC',
  4018. 'instance_number' => 'ASC',
  4019. ),
  4020. 'ASC',
  4021. true
  4022. );
  4023. $panels = array();
  4024. foreach ( $this->panels as $panel ) {
  4025. if ( ! $panel->check_capabilities() ) {
  4026. continue;
  4027. }
  4028. $panel->sections = wp_list_sort(
  4029. $panel->sections,
  4030. array(
  4031. 'priority' => 'ASC',
  4032. 'instance_number' => 'ASC',
  4033. ),
  4034. 'ASC',
  4035. true
  4036. );
  4037. $panels[ $panel->id ] = $panel;
  4038. }
  4039. $this->panels = $panels;
  4040. // Sort panels and top-level sections together.
  4041. $this->containers = array_merge( $this->panels, $this->sections );
  4042. $this->containers = wp_list_sort(
  4043. $this->containers,
  4044. array(
  4045. 'priority' => 'ASC',
  4046. 'instance_number' => 'ASC',
  4047. ),
  4048. 'ASC',
  4049. true
  4050. );
  4051. }
  4052. /**
  4053. * Enqueues scripts for customize controls.
  4054. *
  4055. * @since 3.4.0
  4056. */
  4057. public function enqueue_control_scripts() {
  4058. foreach ( $this->controls as $control ) {
  4059. $control->enqueue();
  4060. }
  4061. if ( ! is_multisite() && ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) || current_user_can( 'delete_themes' ) ) ) {
  4062. wp_enqueue_script( 'updates' );
  4063. wp_localize_script(
  4064. 'updates',
  4065. '_wpUpdatesItemCounts',
  4066. array(
  4067. 'totals' => wp_get_update_data(),
  4068. )
  4069. );
  4070. }
  4071. }
  4072. /**
  4073. * Determines whether the user agent is iOS.
  4074. *
  4075. * @since 4.4.0
  4076. *
  4077. * @return bool Whether the user agent is iOS.
  4078. */
  4079. public function is_ios() {
  4080. return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] );
  4081. }
  4082. /**
  4083. * Gets the template string for the Customizer pane document title.
  4084. *
  4085. * @since 4.4.0
  4086. *
  4087. * @return string The template string for the document title.
  4088. */
  4089. public function get_document_title_template() {
  4090. if ( $this->is_theme_active() ) {
  4091. /* translators: %s: Document title from the preview. */
  4092. $document_title_tmpl = __( 'Customize: %s' );
  4093. } else {
  4094. /* translators: %s: Document title from the preview. */
  4095. $document_title_tmpl = __( 'Live Preview: %s' );
  4096. }
  4097. $document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title.
  4098. return $document_title_tmpl;
  4099. }
  4100. /**
  4101. * Sets the initial URL to be previewed.
  4102. *
  4103. * URL is validated.
  4104. *
  4105. * @since 4.4.0
  4106. *
  4107. * @param string $preview_url URL to be previewed.
  4108. */
  4109. public function set_preview_url( $preview_url ) {
  4110. $preview_url = esc_url_raw( $preview_url );
  4111. $this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) );
  4112. }
  4113. /**
  4114. * Gets the initial URL to be previewed.
  4115. *
  4116. * @since 4.4.0
  4117. *
  4118. * @return string URL being previewed.
  4119. */
  4120. public function get_preview_url() {
  4121. if ( empty( $this->preview_url ) ) {
  4122. $preview_url = home_url( '/' );
  4123. } else {
  4124. $preview_url = $this->preview_url;
  4125. }
  4126. return $preview_url;
  4127. }
  4128. /**
  4129. * Determines whether the admin and the frontend are on different domains.
  4130. *
  4131. * @since 4.7.0
  4132. *
  4133. * @return bool Whether cross-domain.
  4134. */
  4135. public function is_cross_domain() {
  4136. $admin_origin = wp_parse_url( admin_url() );
  4137. $home_origin = wp_parse_url( home_url() );
  4138. $cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) );
  4139. return $cross_domain;
  4140. }
  4141. /**
  4142. * Gets URLs allowed to be previewed.
  4143. *
  4144. * If the front end and the admin are served from the same domain, load the
  4145. * preview over ssl if the Customizer is being loaded over ssl. This avoids
  4146. * insecure content warnings. This is not attempted if the admin and front end
  4147. * are on different domains to avoid the case where the front end doesn't have
  4148. * ssl certs. Domain mapping plugins can allow other urls in these conditions
  4149. * using the customize_allowed_urls filter.
  4150. *
  4151. * @since 4.7.0
  4152. *
  4153. * @return array Allowed URLs.
  4154. */
  4155. public function get_allowed_urls() {
  4156. $allowed_urls = array( home_url( '/' ) );
  4157. if ( is_ssl() && ! $this->is_cross_domain() ) {
  4158. $allowed_urls[] = home_url( '/', 'https' );
  4159. }
  4160. /**
  4161. * Filters the list of URLs allowed to be clicked and followed in the Customizer preview.
  4162. *
  4163. * @since 3.4.0
  4164. *
  4165. * @param string[] $allowed_urls An array of allowed URLs.
  4166. */
  4167. $allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) );
  4168. return $allowed_urls;
  4169. }
  4170. /**
  4171. * Gets messenger channel.
  4172. *
  4173. * @since 4.7.0
  4174. *
  4175. * @return string Messenger channel.
  4176. */
  4177. public function get_messenger_channel() {
  4178. return $this->messenger_channel;
  4179. }
  4180. /**
  4181. * Sets URL to link the user to when closing the Customizer.
  4182. *
  4183. * URL is validated.
  4184. *
  4185. * @since 4.4.0
  4186. *
  4187. * @param string $return_url URL for return link.
  4188. */
  4189. public function set_return_url( $return_url ) {
  4190. $return_url = esc_url_raw( $return_url );
  4191. $return_url = remove_query_arg( wp_removable_query_args(), $return_url );
  4192. $return_url = wp_validate_redirect( $return_url );
  4193. $this->return_url = $return_url;
  4194. }
  4195. /**
  4196. * Gets URL to link the user to when closing the Customizer.
  4197. *
  4198. * @since 4.4.0
  4199. *
  4200. * @global array $_registered_pages
  4201. *
  4202. * @return string URL for link to close Customizer.
  4203. */
  4204. public function get_return_url() {
  4205. global $_registered_pages;
  4206. $referer = wp_get_referer();
  4207. $excluded_referer_basenames = array( 'customize.php', 'wp-login.php' );
  4208. if ( $this->return_url ) {
  4209. $return_url = $this->return_url;
  4210. } elseif ( $referer && ! in_array( wp_basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) {
  4211. $return_url = $referer;
  4212. } elseif ( $this->preview_url ) {
  4213. $return_url = $this->preview_url;
  4214. } else {
  4215. $return_url = home_url( '/' );
  4216. }
  4217. $return_url_basename = wp_basename( parse_url( $this->return_url, PHP_URL_PATH ) );
  4218. $return_url_query = parse_url( $this->return_url, PHP_URL_QUERY );
  4219. if ( 'themes.php' === $return_url_basename && $return_url_query ) {
  4220. parse_str( $return_url_query, $query_vars );
  4221. /*
  4222. * If the return URL is a page added by a theme to the Appearance menu via add_submenu_page(),
  4223. * verify that it belongs to the active theme, otherwise fall back to the Themes screen.
  4224. */
  4225. if ( isset( $query_vars['page'] ) && ! isset( $_registered_pages[ "appearance_page_{$query_vars['page']}" ] ) ) {
  4226. $return_url = admin_url( 'themes.php' );
  4227. }
  4228. }
  4229. return $return_url;
  4230. }
  4231. /**
  4232. * Sets the autofocused constructs.
  4233. *
  4234. * @since 4.4.0
  4235. *
  4236. * @param array $autofocus {
  4237. * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
  4238. *
  4239. * @type string $control ID for control to be autofocused.
  4240. * @type string $section ID for section to be autofocused.
  4241. * @type string $panel ID for panel to be autofocused.
  4242. * }
  4243. */
  4244. public function set_autofocus( $autofocus ) {
  4245. $this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' );
  4246. }
  4247. /**
  4248. * Gets the autofocused constructs.
  4249. *
  4250. * @since 4.4.0
  4251. *
  4252. * @return string[] {
  4253. * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
  4254. *
  4255. * @type string $control ID for control to be autofocused.
  4256. * @type string $section ID for section to be autofocused.
  4257. * @type string $panel ID for panel to be autofocused.
  4258. * }
  4259. */
  4260. public function get_autofocus() {
  4261. return $this->autofocus;
  4262. }
  4263. /**
  4264. * Gets nonces for the Customizer.
  4265. *
  4266. * @since 4.5.0
  4267. *
  4268. * @return array Nonces.
  4269. */
  4270. public function get_nonces() {
  4271. $nonces = array(
  4272. 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ),
  4273. 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ),
  4274. 'switch_themes' => wp_create_nonce( 'switch_themes' ),
  4275. 'dismiss_autosave_or_lock' => wp_create_nonce( 'customize_dismiss_autosave_or_lock' ),
  4276. 'override_lock' => wp_create_nonce( 'customize_override_changeset_lock' ),
  4277. 'trash' => wp_create_nonce( 'trash_customize_changeset' ),
  4278. );
  4279. /**
  4280. * Filters nonces for Customizer.
  4281. *
  4282. * @since 4.2.0
  4283. *
  4284. * @param string[] $nonces Array of refreshed nonces for save and
  4285. * preview actions.
  4286. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  4287. */
  4288. $nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this );
  4289. return $nonces;
  4290. }
  4291. /**
  4292. * Prints JavaScript settings for parent window.
  4293. *
  4294. * @since 4.4.0
  4295. */
  4296. public function customize_pane_settings() {
  4297. $login_url = add_query_arg(
  4298. array(
  4299. 'interim-login' => 1,
  4300. 'customize-login' => 1,
  4301. ),
  4302. wp_login_url()
  4303. );
  4304. // Ensure dirty flags are set for modified settings.
  4305. foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) {
  4306. $setting = $this->get_setting( $setting_id );
  4307. if ( $setting ) {
  4308. $setting->dirty = true;
  4309. }
  4310. }
  4311. $autosave_revision_post = null;
  4312. $autosave_autodraft_post = null;
  4313. $changeset_post_id = $this->changeset_post_id();
  4314. if ( ! $this->saved_starter_content_changeset && ! $this->autosaved() ) {
  4315. if ( $changeset_post_id ) {
  4316. if ( is_user_logged_in() ) {
  4317. $autosave_revision_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() );
  4318. }
  4319. } else {
  4320. $autosave_autodraft_posts = $this->get_changeset_posts(
  4321. array(
  4322. 'posts_per_page' => 1,
  4323. 'post_status' => 'auto-draft',
  4324. 'exclude_restore_dismissed' => true,
  4325. )
  4326. );
  4327. if ( ! empty( $autosave_autodraft_posts ) ) {
  4328. $autosave_autodraft_post = array_shift( $autosave_autodraft_posts );
  4329. }
  4330. }
  4331. }
  4332. $current_user_can_publish = current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts );
  4333. // @todo Include all of the status labels here from script-loader.php, and then allow it to be filtered.
  4334. $status_choices = array();
  4335. if ( $current_user_can_publish ) {
  4336. $status_choices[] = array(
  4337. 'status' => 'publish',
  4338. 'label' => __( 'Publish' ),
  4339. );
  4340. }
  4341. $status_choices[] = array(
  4342. 'status' => 'draft',
  4343. 'label' => __( 'Save Draft' ),
  4344. );
  4345. if ( $current_user_can_publish ) {
  4346. $status_choices[] = array(
  4347. 'status' => 'future',
  4348. 'label' => _x( 'Schedule', 'customizer changeset action/button label' ),
  4349. );
  4350. }
  4351. // Prepare Customizer settings to pass to JavaScript.
  4352. $changeset_post = null;
  4353. if ( $changeset_post_id ) {
  4354. $changeset_post = get_post( $changeset_post_id );
  4355. }
  4356. // Determine initial date to be at present or future, not past.
  4357. $current_time = current_time( 'mysql', false );
  4358. $initial_date = $current_time;
  4359. if ( $changeset_post ) {
  4360. $initial_date = get_the_time( 'Y-m-d H:i:s', $changeset_post->ID );
  4361. if ( $initial_date < $current_time ) {
  4362. $initial_date = $current_time;
  4363. }
  4364. }
  4365. $lock_user_id = false;
  4366. if ( $this->changeset_post_id() ) {
  4367. $lock_user_id = wp_check_post_lock( $this->changeset_post_id() );
  4368. }
  4369. $settings = array(
  4370. 'changeset' => array(
  4371. 'uuid' => $this->changeset_uuid(),
  4372. 'branching' => $this->branching(),
  4373. 'autosaved' => $this->autosaved(),
  4374. 'hasAutosaveRevision' => ! empty( $autosave_revision_post ),
  4375. 'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null,
  4376. 'status' => $changeset_post ? $changeset_post->post_status : '',
  4377. 'currentUserCanPublish' => $current_user_can_publish,
  4378. 'publishDate' => $initial_date,
  4379. 'statusChoices' => $status_choices,
  4380. 'lockUser' => $lock_user_id ? $this->get_lock_user_data( $lock_user_id ) : null,
  4381. ),
  4382. 'initialServerDate' => $current_time,
  4383. 'dateFormat' => get_option( 'date_format' ),
  4384. 'timeFormat' => get_option( 'time_format' ),
  4385. 'initialServerTimestamp' => floor( microtime( true ) * 1000 ),
  4386. 'initialClientTimestamp' => -1, // To be set with JS below.
  4387. 'timeouts' => array(
  4388. 'windowRefresh' => 250,
  4389. 'changesetAutoSave' => AUTOSAVE_INTERVAL * 1000,
  4390. 'keepAliveCheck' => 2500,
  4391. 'reflowPaneContents' => 100,
  4392. 'previewFrameSensitivity' => 2000,
  4393. ),
  4394. 'theme' => array(
  4395. 'stylesheet' => $this->get_stylesheet(),
  4396. 'active' => $this->is_theme_active(),
  4397. '_canInstall' => current_user_can( 'install_themes' ),
  4398. ),
  4399. 'url' => array(
  4400. 'preview' => esc_url_raw( $this->get_preview_url() ),
  4401. 'return' => esc_url_raw( $this->get_return_url() ),
  4402. 'parent' => esc_url_raw( admin_url() ),
  4403. 'activated' => esc_url_raw( home_url( '/' ) ),
  4404. 'ajax' => esc_url_raw( admin_url( 'admin-ajax.php', 'relative' ) ),
  4405. 'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ),
  4406. 'isCrossDomain' => $this->is_cross_domain(),
  4407. 'home' => esc_url_raw( home_url( '/' ) ),
  4408. 'login' => esc_url_raw( $login_url ),
  4409. ),
  4410. 'browser' => array(
  4411. 'mobile' => wp_is_mobile(),
  4412. 'ios' => $this->is_ios(),
  4413. ),
  4414. 'panels' => array(),
  4415. 'sections' => array(),
  4416. 'nonce' => $this->get_nonces(),
  4417. 'autofocus' => $this->get_autofocus(),
  4418. 'documentTitleTmpl' => $this->get_document_title_template(),
  4419. 'previewableDevices' => $this->get_previewable_devices(),
  4420. 'l10n' => array(
  4421. 'confirmDeleteTheme' => __( 'Are you sure you want to delete this theme?' ),
  4422. /* translators: %d: Number of theme search results, which cannot currently consider singular vs. plural forms. */
  4423. 'themeSearchResults' => __( '%d themes found' ),
  4424. /* translators: %d: Number of themes being displayed, which cannot currently consider singular vs. plural forms. */
  4425. 'announceThemeCount' => __( 'Displaying %d themes' ),
  4426. /* translators: %s: Theme name. */
  4427. 'announceThemeDetails' => __( 'Showing details for theme: %s' ),
  4428. ),
  4429. );
  4430. // Temporarily disable installation in Customizer. See #42184.
  4431. $filesystem_method = get_filesystem_method();
  4432. ob_start();
  4433. $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
  4434. ob_end_clean();
  4435. if ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored ) {
  4436. $settings['theme']['_filesystemCredentialsNeeded'] = true;
  4437. }
  4438. // Prepare Customize Section objects to pass to JavaScript.
  4439. foreach ( $this->sections() as $id => $section ) {
  4440. if ( $section->check_capabilities() ) {
  4441. $settings['sections'][ $id ] = $section->json();
  4442. }
  4443. }
  4444. // Prepare Customize Panel objects to pass to JavaScript.
  4445. foreach ( $this->panels() as $panel_id => $panel ) {
  4446. if ( $panel->check_capabilities() ) {
  4447. $settings['panels'][ $panel_id ] = $panel->json();
  4448. foreach ( $panel->sections as $section_id => $section ) {
  4449. if ( $section->check_capabilities() ) {
  4450. $settings['sections'][ $section_id ] = $section->json();
  4451. }
  4452. }
  4453. }
  4454. }
  4455. ?>
  4456. <script type="text/javascript">
  4457. var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>;
  4458. _wpCustomizeSettings.initialClientTimestamp = _.now();
  4459. _wpCustomizeSettings.controls = {};
  4460. _wpCustomizeSettings.settings = {};
  4461. <?php
  4462. // Serialize settings one by one to improve memory usage.
  4463. echo "(function ( s ){\n";
  4464. foreach ( $this->settings() as $setting ) {
  4465. if ( $setting->check_capabilities() ) {
  4466. printf(
  4467. "s[%s] = %s;\n",
  4468. wp_json_encode( $setting->id ),
  4469. wp_json_encode( $setting->json() )
  4470. );
  4471. }
  4472. }
  4473. echo "})( _wpCustomizeSettings.settings );\n";
  4474. // Serialize controls one by one to improve memory usage.
  4475. echo "(function ( c ){\n";
  4476. foreach ( $this->controls() as $control ) {
  4477. if ( $control->check_capabilities() ) {
  4478. printf(
  4479. "c[%s] = %s;\n",
  4480. wp_json_encode( $control->id ),
  4481. wp_json_encode( $control->json() )
  4482. );
  4483. }
  4484. }
  4485. echo "})( _wpCustomizeSettings.controls );\n";
  4486. ?>
  4487. </script>
  4488. <?php
  4489. }
  4490. /**
  4491. * Returns a list of devices to allow previewing.
  4492. *
  4493. * @since 4.5.0
  4494. *
  4495. * @return array List of devices with labels and default setting.
  4496. */
  4497. public function get_previewable_devices() {
  4498. $devices = array(
  4499. 'desktop' => array(
  4500. 'label' => __( 'Enter desktop preview mode' ),
  4501. 'default' => true,
  4502. ),
  4503. 'tablet' => array(
  4504. 'label' => __( 'Enter tablet preview mode' ),
  4505. ),
  4506. 'mobile' => array(
  4507. 'label' => __( 'Enter mobile preview mode' ),
  4508. ),
  4509. );
  4510. /**
  4511. * Filters the available devices to allow previewing in the Customizer.
  4512. *
  4513. * @since 4.5.0
  4514. *
  4515. * @see WP_Customize_Manager::get_previewable_devices()
  4516. *
  4517. * @param array $devices List of devices with labels and default setting.
  4518. */
  4519. $devices = apply_filters( 'customize_previewable_devices', $devices );
  4520. return $devices;
  4521. }
  4522. /**
  4523. * Registers some default controls.
  4524. *
  4525. * @since 3.4.0
  4526. */
  4527. public function register_controls() {
  4528. /* Themes (controls are loaded via ajax) */
  4529. $this->add_panel(
  4530. new WP_Customize_Themes_Panel(
  4531. $this,
  4532. 'themes',
  4533. array(
  4534. 'title' => $this->theme()->display( 'Name' ),
  4535. 'description' => (
  4536. '<p>' . __( 'Looking for a theme? You can search or browse the WordPress.org theme directory, install and preview themes, then activate them right here.' ) . '</p>' .
  4537. '<p>' . __( 'While previewing a new theme, you can continue to tailor things like widgets and menus, and explore theme-specific options.' ) . '</p>'
  4538. ),
  4539. 'capability' => 'switch_themes',
  4540. 'priority' => 0,
  4541. )
  4542. )
  4543. );
  4544. $this->add_section(
  4545. new WP_Customize_Themes_Section(
  4546. $this,
  4547. 'installed_themes',
  4548. array(
  4549. 'title' => __( 'Installed themes' ),
  4550. 'action' => 'installed',
  4551. 'capability' => 'switch_themes',
  4552. 'panel' => 'themes',
  4553. 'priority' => 0,
  4554. )
  4555. )
  4556. );
  4557. if ( ! is_multisite() ) {
  4558. $this->add_section(
  4559. new WP_Customize_Themes_Section(
  4560. $this,
  4561. 'wporg_themes',
  4562. array(
  4563. 'title' => __( 'WordPress.org themes' ),
  4564. 'action' => 'wporg',
  4565. 'filter_type' => 'remote',
  4566. 'capability' => 'install_themes',
  4567. 'panel' => 'themes',
  4568. 'priority' => 5,
  4569. )
  4570. )
  4571. );
  4572. }
  4573. // Themes Setting (unused - the theme is considerably more fundamental to the Customizer experience).
  4574. $this->add_setting(
  4575. new WP_Customize_Filter_Setting(
  4576. $this,
  4577. 'active_theme',
  4578. array(
  4579. 'capability' => 'switch_themes',
  4580. )
  4581. )
  4582. );
  4583. /* Site Identity */
  4584. $this->add_section(
  4585. 'title_tagline',
  4586. array(
  4587. 'title' => __( 'Site Identity' ),
  4588. 'priority' => 20,
  4589. )
  4590. );
  4591. $this->add_setting(
  4592. 'blogname',
  4593. array(
  4594. 'default' => get_option( 'blogname' ),
  4595. 'type' => 'option',
  4596. 'capability' => 'manage_options',
  4597. )
  4598. );
  4599. $this->add_control(
  4600. 'blogname',
  4601. array(
  4602. 'label' => __( 'Site Title' ),
  4603. 'section' => 'title_tagline',
  4604. )
  4605. );
  4606. $this->add_setting(
  4607. 'blogdescription',
  4608. array(
  4609. 'default' => get_option( 'blogdescription' ),
  4610. 'type' => 'option',
  4611. 'capability' => 'manage_options',
  4612. )
  4613. );
  4614. $this->add_control(
  4615. 'blogdescription',
  4616. array(
  4617. 'label' => __( 'Tagline' ),
  4618. 'section' => 'title_tagline',
  4619. )
  4620. );
  4621. // Add a setting to hide header text if the theme doesn't support custom headers.
  4622. if ( ! current_theme_supports( 'custom-header', 'header-text' ) ) {
  4623. $this->add_setting(
  4624. 'header_text',
  4625. array(
  4626. 'theme_supports' => array( 'custom-logo', 'header-text' ),
  4627. 'default' => 1,
  4628. 'sanitize_callback' => 'absint',
  4629. )
  4630. );
  4631. $this->add_control(
  4632. 'header_text',
  4633. array(
  4634. 'label' => __( 'Display Site Title and Tagline' ),
  4635. 'section' => 'title_tagline',
  4636. 'settings' => 'header_text',
  4637. 'type' => 'checkbox',
  4638. )
  4639. );
  4640. }
  4641. $this->add_setting(
  4642. 'site_icon',
  4643. array(
  4644. 'type' => 'option',
  4645. 'capability' => 'manage_options',
  4646. 'transport' => 'postMessage', // Previewed with JS in the Customizer controls window.
  4647. )
  4648. );
  4649. $this->add_control(
  4650. new WP_Customize_Site_Icon_Control(
  4651. $this,
  4652. 'site_icon',
  4653. array(
  4654. 'label' => __( 'Site Icon' ),
  4655. 'description' => sprintf(
  4656. '<p>' . __( 'Site Icons are what you see in browser tabs, bookmark bars, and within the WordPress mobile apps. Upload one here!' ) . '</p>' .
  4657. /* translators: %s: Site icon size in pixels. */
  4658. '<p>' . __( 'Site Icons should be square and at least %s pixels.' ) . '</p>',
  4659. '<strong>512 &times; 512</strong>'
  4660. ),
  4661. 'section' => 'title_tagline',
  4662. 'priority' => 60,
  4663. 'height' => 512,
  4664. 'width' => 512,
  4665. )
  4666. )
  4667. );
  4668. $this->add_setting(
  4669. 'custom_logo',
  4670. array(
  4671. 'theme_supports' => array( 'custom-logo' ),
  4672. 'transport' => 'postMessage',
  4673. )
  4674. );
  4675. $custom_logo_args = get_theme_support( 'custom-logo' );
  4676. $this->add_control(
  4677. new WP_Customize_Cropped_Image_Control(
  4678. $this,
  4679. 'custom_logo',
  4680. array(
  4681. 'label' => __( 'Logo' ),
  4682. 'section' => 'title_tagline',
  4683. 'priority' => 8,
  4684. 'height' => isset( $custom_logo_args[0]['height'] ) ? $custom_logo_args[0]['height'] : null,
  4685. 'width' => isset( $custom_logo_args[0]['width'] ) ? $custom_logo_args[0]['width'] : null,
  4686. 'flex_height' => isset( $custom_logo_args[0]['flex-height'] ) ? $custom_logo_args[0]['flex-height'] : null,
  4687. 'flex_width' => isset( $custom_logo_args[0]['flex-width'] ) ? $custom_logo_args[0]['flex-width'] : null,
  4688. 'button_labels' => array(
  4689. 'select' => __( 'Select logo' ),
  4690. 'change' => __( 'Change logo' ),
  4691. 'remove' => __( 'Remove' ),
  4692. 'default' => __( 'Default' ),
  4693. 'placeholder' => __( 'No logo selected' ),
  4694. 'frame_title' => __( 'Select logo' ),
  4695. 'frame_button' => __( 'Choose logo' ),
  4696. ),
  4697. )
  4698. )
  4699. );
  4700. $this->selective_refresh->add_partial(
  4701. 'custom_logo',
  4702. array(
  4703. 'settings' => array( 'custom_logo' ),
  4704. 'selector' => '.custom-logo-link',
  4705. 'render_callback' => array( $this, '_render_custom_logo_partial' ),
  4706. 'container_inclusive' => true,
  4707. )
  4708. );
  4709. /* Colors */
  4710. $this->add_section(
  4711. 'colors',
  4712. array(
  4713. 'title' => __( 'Colors' ),
  4714. 'priority' => 40,
  4715. )
  4716. );
  4717. $this->add_setting(
  4718. 'header_textcolor',
  4719. array(
  4720. 'theme_supports' => array( 'custom-header', 'header-text' ),
  4721. 'default' => get_theme_support( 'custom-header', 'default-text-color' ),
  4722. 'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ),
  4723. 'sanitize_js_callback' => 'maybe_hash_hex_color',
  4724. )
  4725. );
  4726. // Input type: checkbox.
  4727. // With custom value.
  4728. $this->add_control(
  4729. 'display_header_text',
  4730. array(
  4731. 'settings' => 'header_textcolor',
  4732. 'label' => __( 'Display Site Title and Tagline' ),
  4733. 'section' => 'title_tagline',
  4734. 'type' => 'checkbox',
  4735. 'priority' => 40,
  4736. )
  4737. );
  4738. $this->add_control(
  4739. new WP_Customize_Color_Control(
  4740. $this,
  4741. 'header_textcolor',
  4742. array(
  4743. 'label' => __( 'Header Text Color' ),
  4744. 'section' => 'colors',
  4745. )
  4746. )
  4747. );
  4748. // Input type: color.
  4749. // With sanitize_callback.
  4750. $this->add_setting(
  4751. 'background_color',
  4752. array(
  4753. 'default' => get_theme_support( 'custom-background', 'default-color' ),
  4754. 'theme_supports' => 'custom-background',
  4755. 'sanitize_callback' => 'sanitize_hex_color_no_hash',
  4756. 'sanitize_js_callback' => 'maybe_hash_hex_color',
  4757. )
  4758. );
  4759. $this->add_control(
  4760. new WP_Customize_Color_Control(
  4761. $this,
  4762. 'background_color',
  4763. array(
  4764. 'label' => __( 'Background Color' ),
  4765. 'section' => 'colors',
  4766. )
  4767. )
  4768. );
  4769. /* Custom Header */
  4770. if ( current_theme_supports( 'custom-header', 'video' ) ) {
  4771. $title = __( 'Header Media' );
  4772. $description = '<p>' . __( 'If you add a video, the image will be used as a fallback while the video loads.' ) . '</p>';
  4773. $width = absint( get_theme_support( 'custom-header', 'width' ) );
  4774. $height = absint( get_theme_support( 'custom-header', 'height' ) );
  4775. if ( $width && $height ) {
  4776. $control_description = sprintf(
  4777. /* translators: 1: .mp4, 2: Header size in pixels. */
  4778. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends dimensions of %2$s pixels.' ),
  4779. '<code>.mp4</code>',
  4780. sprintf( '<strong>%s &times; %s</strong>', $width, $height )
  4781. );
  4782. } elseif ( $width ) {
  4783. $control_description = sprintf(
  4784. /* translators: 1: .mp4, 2: Header width in pixels. */
  4785. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a width of %2$s pixels.' ),
  4786. '<code>.mp4</code>',
  4787. sprintf( '<strong>%s</strong>', $width )
  4788. );
  4789. } else {
  4790. $control_description = sprintf(
  4791. /* translators: 1: .mp4, 2: Header height in pixels. */
  4792. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a height of %2$s pixels.' ),
  4793. '<code>.mp4</code>',
  4794. sprintf( '<strong>%s</strong>', $height )
  4795. );
  4796. }
  4797. } else {
  4798. $title = __( 'Header Image' );
  4799. $description = '';
  4800. $control_description = '';
  4801. }
  4802. $this->add_section(
  4803. 'header_image',
  4804. array(
  4805. 'title' => $title,
  4806. 'description' => $description,
  4807. 'theme_supports' => 'custom-header',
  4808. 'priority' => 60,
  4809. )
  4810. );
  4811. $this->add_setting(
  4812. 'header_video',
  4813. array(
  4814. 'theme_supports' => array( 'custom-header', 'video' ),
  4815. 'transport' => 'postMessage',
  4816. 'sanitize_callback' => 'absint',
  4817. 'validate_callback' => array( $this, '_validate_header_video' ),
  4818. )
  4819. );
  4820. $this->add_setting(
  4821. 'external_header_video',
  4822. array(
  4823. 'theme_supports' => array( 'custom-header', 'video' ),
  4824. 'transport' => 'postMessage',
  4825. 'sanitize_callback' => array( $this, '_sanitize_external_header_video' ),
  4826. 'validate_callback' => array( $this, '_validate_external_header_video' ),
  4827. )
  4828. );
  4829. $this->add_setting(
  4830. new WP_Customize_Filter_Setting(
  4831. $this,
  4832. 'header_image',
  4833. array(
  4834. 'default' => sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ),
  4835. 'theme_supports' => 'custom-header',
  4836. )
  4837. )
  4838. );
  4839. $this->add_setting(
  4840. new WP_Customize_Header_Image_Setting(
  4841. $this,
  4842. 'header_image_data',
  4843. array(
  4844. 'theme_supports' => 'custom-header',
  4845. )
  4846. )
  4847. );
  4848. /*
  4849. * Switch image settings to postMessage when video support is enabled since
  4850. * it entails that the_custom_header_markup() will be used, and thus selective
  4851. * refresh can be utilized.
  4852. */
  4853. if ( current_theme_supports( 'custom-header', 'video' ) ) {
  4854. $this->get_setting( 'header_image' )->transport = 'postMessage';
  4855. $this->get_setting( 'header_image_data' )->transport = 'postMessage';
  4856. }
  4857. $this->add_control(
  4858. new WP_Customize_Media_Control(
  4859. $this,
  4860. 'header_video',
  4861. array(
  4862. 'theme_supports' => array( 'custom-header', 'video' ),
  4863. 'label' => __( 'Header Video' ),
  4864. 'description' => $control_description,
  4865. 'section' => 'header_image',
  4866. 'mime_type' => 'video',
  4867. 'active_callback' => 'is_header_video_active',
  4868. )
  4869. )
  4870. );
  4871. $this->add_control(
  4872. 'external_header_video',
  4873. array(
  4874. 'theme_supports' => array( 'custom-header', 'video' ),
  4875. 'type' => 'url',
  4876. 'description' => __( 'Or, enter a YouTube URL:' ),
  4877. 'section' => 'header_image',
  4878. 'active_callback' => 'is_header_video_active',
  4879. )
  4880. );
  4881. $this->add_control( new WP_Customize_Header_Image_Control( $this ) );
  4882. $this->selective_refresh->add_partial(
  4883. 'custom_header',
  4884. array(
  4885. 'selector' => '#wp-custom-header',
  4886. 'render_callback' => 'the_custom_header_markup',
  4887. 'settings' => array( 'header_video', 'external_header_video', 'header_image' ), // The image is used as a video fallback here.
  4888. 'container_inclusive' => true,
  4889. )
  4890. );
  4891. /* Custom Background */
  4892. $this->add_section(
  4893. 'background_image',
  4894. array(
  4895. 'title' => __( 'Background Image' ),
  4896. 'theme_supports' => 'custom-background',
  4897. 'priority' => 80,
  4898. )
  4899. );
  4900. $this->add_setting(
  4901. 'background_image',
  4902. array(
  4903. 'default' => get_theme_support( 'custom-background', 'default-image' ),
  4904. 'theme_supports' => 'custom-background',
  4905. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4906. )
  4907. );
  4908. $this->add_setting(
  4909. new WP_Customize_Background_Image_Setting(
  4910. $this,
  4911. 'background_image_thumb',
  4912. array(
  4913. 'theme_supports' => 'custom-background',
  4914. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4915. )
  4916. )
  4917. );
  4918. $this->add_control( new WP_Customize_Background_Image_Control( $this ) );
  4919. $this->add_setting(
  4920. 'background_preset',
  4921. array(
  4922. 'default' => get_theme_support( 'custom-background', 'default-preset' ),
  4923. 'theme_supports' => 'custom-background',
  4924. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4925. )
  4926. );
  4927. $this->add_control(
  4928. 'background_preset',
  4929. array(
  4930. 'label' => _x( 'Preset', 'Background Preset' ),
  4931. 'section' => 'background_image',
  4932. 'type' => 'select',
  4933. 'choices' => array(
  4934. 'default' => _x( 'Default', 'Default Preset' ),
  4935. 'fill' => __( 'Fill Screen' ),
  4936. 'fit' => __( 'Fit to Screen' ),
  4937. 'repeat' => _x( 'Repeat', 'Repeat Image' ),
  4938. 'custom' => _x( 'Custom', 'Custom Preset' ),
  4939. ),
  4940. )
  4941. );
  4942. $this->add_setting(
  4943. 'background_position_x',
  4944. array(
  4945. 'default' => get_theme_support( 'custom-background', 'default-position-x' ),
  4946. 'theme_supports' => 'custom-background',
  4947. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4948. )
  4949. );
  4950. $this->add_setting(
  4951. 'background_position_y',
  4952. array(
  4953. 'default' => get_theme_support( 'custom-background', 'default-position-y' ),
  4954. 'theme_supports' => 'custom-background',
  4955. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4956. )
  4957. );
  4958. $this->add_control(
  4959. new WP_Customize_Background_Position_Control(
  4960. $this,
  4961. 'background_position',
  4962. array(
  4963. 'label' => __( 'Image Position' ),
  4964. 'section' => 'background_image',
  4965. 'settings' => array(
  4966. 'x' => 'background_position_x',
  4967. 'y' => 'background_position_y',
  4968. ),
  4969. )
  4970. )
  4971. );
  4972. $this->add_setting(
  4973. 'background_size',
  4974. array(
  4975. 'default' => get_theme_support( 'custom-background', 'default-size' ),
  4976. 'theme_supports' => 'custom-background',
  4977. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4978. )
  4979. );
  4980. $this->add_control(
  4981. 'background_size',
  4982. array(
  4983. 'label' => __( 'Image Size' ),
  4984. 'section' => 'background_image',
  4985. 'type' => 'select',
  4986. 'choices' => array(
  4987. 'auto' => _x( 'Original', 'Original Size' ),
  4988. 'contain' => __( 'Fit to Screen' ),
  4989. 'cover' => __( 'Fill Screen' ),
  4990. ),
  4991. )
  4992. );
  4993. $this->add_setting(
  4994. 'background_repeat',
  4995. array(
  4996. 'default' => get_theme_support( 'custom-background', 'default-repeat' ),
  4997. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4998. 'theme_supports' => 'custom-background',
  4999. )
  5000. );
  5001. $this->add_control(
  5002. 'background_repeat',
  5003. array(
  5004. 'label' => __( 'Repeat Background Image' ),
  5005. 'section' => 'background_image',
  5006. 'type' => 'checkbox',
  5007. )
  5008. );
  5009. $this->add_setting(
  5010. 'background_attachment',
  5011. array(
  5012. 'default' => get_theme_support( 'custom-background', 'default-attachment' ),
  5013. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  5014. 'theme_supports' => 'custom-background',
  5015. )
  5016. );
  5017. $this->add_control(
  5018. 'background_attachment',
  5019. array(
  5020. 'label' => __( 'Scroll with Page' ),
  5021. 'section' => 'background_image',
  5022. 'type' => 'checkbox',
  5023. )
  5024. );
  5025. // If the theme is using the default background callback, we can update
  5026. // the background CSS using postMessage.
  5027. if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) {
  5028. foreach ( array( 'color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment' ) as $prop ) {
  5029. $this->get_setting( 'background_' . $prop )->transport = 'postMessage';
  5030. }
  5031. }
  5032. /*
  5033. * Static Front Page
  5034. * See also https://core.trac.wordpress.org/ticket/19627 which introduces the static-front-page theme_support.
  5035. * The following replicates behavior from options-reading.php.
  5036. */
  5037. $this->add_section(
  5038. 'static_front_page',
  5039. array(
  5040. 'title' => __( 'Homepage Settings' ),
  5041. 'priority' => 120,
  5042. 'description' => __( 'You can choose what&#8217;s displayed on the homepage of your site. It can be posts in reverse chronological order (classic blog), or a fixed/static page. To set a static homepage, you first need to create two Pages. One will become the homepage, and the other will be where your posts are displayed.' ),
  5043. 'active_callback' => array( $this, 'has_published_pages' ),
  5044. )
  5045. );
  5046. $this->add_setting(
  5047. 'show_on_front',
  5048. array(
  5049. 'default' => get_option( 'show_on_front' ),
  5050. 'capability' => 'manage_options',
  5051. 'type' => 'option',
  5052. )
  5053. );
  5054. $this->add_control(
  5055. 'show_on_front',
  5056. array(
  5057. 'label' => __( 'Your homepage displays' ),
  5058. 'section' => 'static_front_page',
  5059. 'type' => 'radio',
  5060. 'choices' => array(
  5061. 'posts' => __( 'Your latest posts' ),
  5062. 'page' => __( 'A static page' ),
  5063. ),
  5064. )
  5065. );
  5066. $this->add_setting(
  5067. 'page_on_front',
  5068. array(
  5069. 'type' => 'option',
  5070. 'capability' => 'manage_options',
  5071. )
  5072. );
  5073. $this->add_control(
  5074. 'page_on_front',
  5075. array(
  5076. 'label' => __( 'Homepage' ),
  5077. 'section' => 'static_front_page',
  5078. 'type' => 'dropdown-pages',
  5079. 'allow_addition' => true,
  5080. )
  5081. );
  5082. $this->add_setting(
  5083. 'page_for_posts',
  5084. array(
  5085. 'type' => 'option',
  5086. 'capability' => 'manage_options',
  5087. )
  5088. );
  5089. $this->add_control(
  5090. 'page_for_posts',
  5091. array(
  5092. 'label' => __( 'Posts page' ),
  5093. 'section' => 'static_front_page',
  5094. 'type' => 'dropdown-pages',
  5095. 'allow_addition' => true,
  5096. )
  5097. );
  5098. /* Custom CSS */
  5099. $section_description = '<p>';
  5100. $section_description .= __( 'Add your own CSS code here to customize the appearance and layout of your site.' );
  5101. $section_description .= sprintf(
  5102. ' <a href="%1$s" class="external-link" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span></a>',
  5103. esc_url( __( 'https://codex.wordpress.org/CSS' ) ),
  5104. __( 'Learn more about CSS' ),
  5105. /* translators: Accessibility text. */
  5106. __( '(opens in a new tab)' )
  5107. );
  5108. $section_description .= '</p>';
  5109. $section_description .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>';
  5110. $section_description .= '<ul>';
  5111. $section_description .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>';
  5112. $section_description .= '<li id="editor-keyboard-trap-help-3">' . __( 'To move away from this area, press the Esc key followed by the Tab key.' ) . '</li>';
  5113. $section_description .= '<li id="editor-keyboard-trap-help-4">' . __( 'Screen reader users: when in forms mode, you may need to press the Esc key twice.' ) . '</li>';
  5114. $section_description .= '</ul>';
  5115. if ( 'false' !== wp_get_current_user()->syntax_highlighting ) {
  5116. $section_description .= '<p>';
  5117. $section_description .= sprintf(
  5118. /* translators: 1: Link to user profile, 2: Additional link attributes, 3: Accessibility text. */
  5119. __( 'The edit field automatically highlights code syntax. You can disable this in your <a href="%1$s" %2$s>user profile%3$s</a> to work in plain text mode.' ),
  5120. esc_url( get_edit_profile_url() ),
  5121. 'class="external-link" target="_blank"',
  5122. sprintf(
  5123. '<span class="screen-reader-text"> %s</span>',
  5124. /* translators: Accessibility text. */
  5125. __( '(opens in a new tab)' )
  5126. )
  5127. );
  5128. $section_description .= '</p>';
  5129. }
  5130. $section_description .= '<p class="section-description-buttons">';
  5131. $section_description .= '<button type="button" class="button-link section-description-close">' . __( 'Close' ) . '</button>';
  5132. $section_description .= '</p>';
  5133. $this->add_section(
  5134. 'custom_css',
  5135. array(
  5136. 'title' => __( 'Additional CSS' ),
  5137. 'priority' => 200,
  5138. 'description_hidden' => true,
  5139. 'description' => $section_description,
  5140. )
  5141. );
  5142. $custom_css_setting = new WP_Customize_Custom_CSS_Setting(
  5143. $this,
  5144. sprintf( 'custom_css[%s]', get_stylesheet() ),
  5145. array(
  5146. 'capability' => 'edit_css',
  5147. 'default' => '',
  5148. )
  5149. );
  5150. $this->add_setting( $custom_css_setting );
  5151. $this->add_control(
  5152. new WP_Customize_Code_Editor_Control(
  5153. $this,
  5154. 'custom_css',
  5155. array(
  5156. 'label' => __( 'CSS code' ),
  5157. 'section' => 'custom_css',
  5158. 'settings' => array( 'default' => $custom_css_setting->id ),
  5159. 'code_type' => 'text/css',
  5160. 'input_attrs' => array(
  5161. 'aria-describedby' => 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4',
  5162. ),
  5163. )
  5164. )
  5165. );
  5166. }
  5167. /**
  5168. * Returns whether there are published pages.
  5169. *
  5170. * Used as active callback for static front page section and controls.
  5171. *
  5172. * @since 4.7.0
  5173. *
  5174. * @return bool Whether there are published (or to be published) pages.
  5175. */
  5176. public function has_published_pages() {
  5177. $setting = $this->get_setting( 'nav_menus_created_posts' );
  5178. if ( $setting ) {
  5179. foreach ( $setting->value() as $post_id ) {
  5180. if ( 'page' === get_post_type( $post_id ) ) {
  5181. return true;
  5182. }
  5183. }
  5184. }
  5185. return 0 !== count( get_pages( array( 'number' => 1 ) ) );
  5186. }
  5187. /**
  5188. * Adds settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets
  5189. *
  5190. * @since 4.2.0
  5191. *
  5192. * @see add_dynamic_settings()
  5193. */
  5194. public function register_dynamic_settings() {
  5195. $setting_ids = array_keys( $this->unsanitized_post_values() );
  5196. $this->add_dynamic_settings( $setting_ids );
  5197. }
  5198. /**
  5199. * Loads themes into the theme browsing/installation UI.
  5200. *
  5201. * @since 4.9.0
  5202. */
  5203. public function handle_load_themes_request() {
  5204. check_ajax_referer( 'switch_themes', 'nonce' );
  5205. if ( ! current_user_can( 'switch_themes' ) ) {
  5206. wp_die( -1 );
  5207. }
  5208. if ( empty( $_POST['theme_action'] ) ) {
  5209. wp_send_json_error( 'missing_theme_action' );
  5210. }
  5211. $theme_action = sanitize_key( $_POST['theme_action'] );
  5212. $themes = array();
  5213. $args = array();
  5214. // Define query filters based on user input.
  5215. if ( ! array_key_exists( 'search', $_POST ) ) {
  5216. $args['search'] = '';
  5217. } else {
  5218. $args['search'] = sanitize_text_field( wp_unslash( $_POST['search'] ) );
  5219. }
  5220. if ( ! array_key_exists( 'tags', $_POST ) ) {
  5221. $args['tag'] = '';
  5222. } else {
  5223. $args['tag'] = array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['tags'] ) );
  5224. }
  5225. if ( ! array_key_exists( 'page', $_POST ) ) {
  5226. $args['page'] = 1;
  5227. } else {
  5228. $args['page'] = absint( $_POST['page'] );
  5229. }
  5230. require_once ABSPATH . 'wp-admin/includes/theme.php';
  5231. if ( 'installed' === $theme_action ) {
  5232. // Load all installed themes from wp_prepare_themes_for_js().
  5233. $themes = array( 'themes' => array() );
  5234. foreach ( wp_prepare_themes_for_js() as $theme ) {
  5235. $theme['type'] = 'installed';
  5236. $theme['active'] = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme['id'] );
  5237. $themes['themes'][] = $theme;
  5238. }
  5239. } elseif ( 'wporg' === $theme_action ) {
  5240. // Load WordPress.org themes from the .org API and normalize data to match installed theme objects.
  5241. if ( ! current_user_can( 'install_themes' ) ) {
  5242. wp_die( -1 );
  5243. }
  5244. // Arguments for all queries.
  5245. $wporg_args = array(
  5246. 'per_page' => 100,
  5247. 'fields' => array(
  5248. 'reviews_url' => true, // Explicitly request the reviews URL to be linked from the customizer.
  5249. ),
  5250. );
  5251. $args = array_merge( $wporg_args, $args );
  5252. if ( '' === $args['search'] && '' === $args['tag'] ) {
  5253. $args['browse'] = 'new'; // Sort by latest themes by default.
  5254. }
  5255. // Load themes from the .org API.
  5256. $themes = themes_api( 'query_themes', $args );
  5257. if ( is_wp_error( $themes ) ) {
  5258. wp_send_json_error();
  5259. }
  5260. // This list matches the allowed tags in wp-admin/includes/theme-install.php.
  5261. $themes_allowedtags = array_fill_keys(
  5262. array( 'a', 'abbr', 'acronym', 'code', 'pre', 'em', 'strong', 'div', 'p', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'img' ),
  5263. array()
  5264. );
  5265. $themes_allowedtags['a'] = array_fill_keys( array( 'href', 'title', 'target' ), true );
  5266. $themes_allowedtags['acronym']['title'] = true;
  5267. $themes_allowedtags['abbr']['title'] = true;
  5268. $themes_allowedtags['img'] = array_fill_keys( array( 'src', 'class', 'alt' ), true );
  5269. // Prepare a list of installed themes to check against before the loop.
  5270. $installed_themes = array();
  5271. $wp_themes = wp_get_themes();
  5272. foreach ( $wp_themes as $theme ) {
  5273. $installed_themes[] = $theme->get_stylesheet();
  5274. }
  5275. $update_php = network_admin_url( 'update.php?action=install-theme' );
  5276. // Set up properties for themes available on WordPress.org.
  5277. foreach ( $themes->themes as &$theme ) {
  5278. $theme->install_url = add_query_arg(
  5279. array(
  5280. 'theme' => $theme->slug,
  5281. '_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ),
  5282. ),
  5283. $update_php
  5284. );
  5285. $theme->name = wp_kses( $theme->name, $themes_allowedtags );
  5286. $theme->version = wp_kses( $theme->version, $themes_allowedtags );
  5287. $theme->description = wp_kses( $theme->description, $themes_allowedtags );
  5288. $theme->stars = wp_star_rating(
  5289. array(
  5290. 'rating' => $theme->rating,
  5291. 'type' => 'percent',
  5292. 'number' => $theme->num_ratings,
  5293. 'echo' => false,
  5294. )
  5295. );
  5296. $theme->num_ratings = number_format_i18n( $theme->num_ratings );
  5297. $theme->preview_url = set_url_scheme( $theme->preview_url );
  5298. // Handle themes that are already installed as installed themes.
  5299. if ( in_array( $theme->slug, $installed_themes, true ) ) {
  5300. $theme->type = 'installed';
  5301. } else {
  5302. $theme->type = $theme_action;
  5303. }
  5304. // Set active based on customized theme.
  5305. $theme->active = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme->slug );
  5306. // Map available theme properties to installed theme properties.
  5307. $theme->id = $theme->slug;
  5308. $theme->screenshot = array( $theme->screenshot_url );
  5309. $theme->authorAndUri = wp_kses( $theme->author['display_name'], $themes_allowedtags );
  5310. $theme->compatibleWP = is_wp_version_compatible( $theme->requires ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName
  5311. $theme->compatiblePHP = is_php_version_compatible( $theme->requires_php ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName
  5312. if ( isset( $theme->parent ) ) {
  5313. $theme->parent = $theme->parent['slug'];
  5314. } else {
  5315. $theme->parent = false;
  5316. }
  5317. unset( $theme->slug );
  5318. unset( $theme->screenshot_url );
  5319. unset( $theme->author );
  5320. } // End foreach().
  5321. } // End if().
  5322. /**
  5323. * Filters the theme data loaded in the customizer.
  5324. *
  5325. * This allows theme data to be loading from an external source,
  5326. * or modification of data loaded from `wp_prepare_themes_for_js()`
  5327. * or WordPress.org via `themes_api()`.
  5328. *
  5329. * @since 4.9.0
  5330. *
  5331. * @see wp_prepare_themes_for_js()
  5332. * @see themes_api()
  5333. * @see WP_Customize_Manager::__construct()
  5334. *
  5335. * @param array|stdClass $themes Nested array or object of theme data.
  5336. * @param array $args List of arguments, such as page, search term, and tags to query for.
  5337. * @param WP_Customize_Manager $manager Instance of Customize manager.
  5338. */
  5339. $themes = apply_filters( 'customize_load_themes', $themes, $args, $this );
  5340. wp_send_json_success( $themes );
  5341. }
  5342. /**
  5343. * Callback for validating the header_textcolor value.
  5344. *
  5345. * Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash().
  5346. * Returns default text color if hex color is empty.
  5347. *
  5348. * @since 3.4.0
  5349. *
  5350. * @param string $color
  5351. * @return mixed
  5352. */
  5353. public function _sanitize_header_textcolor( $color ) {
  5354. if ( 'blank' === $color ) {
  5355. return 'blank';
  5356. }
  5357. $color = sanitize_hex_color_no_hash( $color );
  5358. if ( empty( $color ) ) {
  5359. $color = get_theme_support( 'custom-header', 'default-text-color' );
  5360. }
  5361. return $color;
  5362. }
  5363. /**
  5364. * Callback for validating a background setting value.
  5365. *
  5366. * @since 4.7.0
  5367. *
  5368. * @param string $value Repeat value.
  5369. * @param WP_Customize_Setting $setting Setting.
  5370. * @return string|WP_Error Background value or validation error.
  5371. */
  5372. public function _sanitize_background_setting( $value, $setting ) {
  5373. if ( 'background_repeat' === $setting->id ) {
  5374. if ( ! in_array( $value, array( 'repeat-x', 'repeat-y', 'repeat', 'no-repeat' ), true ) ) {
  5375. return new WP_Error( 'invalid_value', __( 'Invalid value for background repeat.' ) );
  5376. }
  5377. } elseif ( 'background_attachment' === $setting->id ) {
  5378. if ( ! in_array( $value, array( 'fixed', 'scroll' ), true ) ) {
  5379. return new WP_Error( 'invalid_value', __( 'Invalid value for background attachment.' ) );
  5380. }
  5381. } elseif ( 'background_position_x' === $setting->id ) {
  5382. if ( ! in_array( $value, array( 'left', 'center', 'right' ), true ) ) {
  5383. return new WP_Error( 'invalid_value', __( 'Invalid value for background position X.' ) );
  5384. }
  5385. } elseif ( 'background_position_y' === $setting->id ) {
  5386. if ( ! in_array( $value, array( 'top', 'center', 'bottom' ), true ) ) {
  5387. return new WP_Error( 'invalid_value', __( 'Invalid value for background position Y.' ) );
  5388. }
  5389. } elseif ( 'background_size' === $setting->id ) {
  5390. if ( ! in_array( $value, array( 'auto', 'contain', 'cover' ), true ) ) {
  5391. return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
  5392. }
  5393. } elseif ( 'background_preset' === $setting->id ) {
  5394. if ( ! in_array( $value, array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) {
  5395. return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
  5396. }
  5397. } elseif ( 'background_image' === $setting->id || 'background_image_thumb' === $setting->id ) {
  5398. $value = empty( $value ) ? '' : esc_url_raw( $value );
  5399. } else {
  5400. return new WP_Error( 'unrecognized_setting', __( 'Unrecognized background setting.' ) );
  5401. }
  5402. return $value;
  5403. }
  5404. /**
  5405. * Exports header video settings to facilitate selective refresh.
  5406. *
  5407. * @since 4.7.0
  5408. *
  5409. * @param array $response Response.
  5410. * @param WP_Customize_Selective_Refresh $selective_refresh Selective refresh component.
  5411. * @param array $partials Array of partials.
  5412. * @return array
  5413. */
  5414. public function export_header_video_settings( $response, $selective_refresh, $partials ) {
  5415. if ( isset( $partials['custom_header'] ) ) {
  5416. $response['custom_header_settings'] = get_header_video_settings();
  5417. }
  5418. return $response;
  5419. }
  5420. /**
  5421. * Callback for validating the header_video value.
  5422. *
  5423. * Ensures that the selected video is less than 8MB and provides an error message.
  5424. *
  5425. * @since 4.7.0
  5426. *
  5427. * @param WP_Error $validity
  5428. * @param mixed $value
  5429. * @return mixed
  5430. */
  5431. public function _validate_header_video( $validity, $value ) {
  5432. $video = get_attached_file( absint( $value ) );
  5433. if ( $video ) {
  5434. $size = filesize( $video );
  5435. if ( $size > 8 * MB_IN_BYTES ) {
  5436. $validity->add(
  5437. 'size_too_large',
  5438. __( 'This video file is too large to use as a header video. Try a shorter video or optimize the compression settings and re-upload a file that is less than 8MB. Or, upload your video to YouTube and link it with the option below.' )
  5439. );
  5440. }
  5441. if ( '.mp4' !== substr( $video, -4 ) && '.mov' !== substr( $video, -4 ) ) { // Check for .mp4 or .mov format, which (assuming h.264 encoding) are the only cross-browser-supported formats.
  5442. $validity->add(
  5443. 'invalid_file_type',
  5444. sprintf(
  5445. /* translators: 1: .mp4, 2: .mov */
  5446. __( 'Only %1$s or %2$s files may be used for header video. Please convert your video file and try again, or, upload your video to YouTube and link it with the option below.' ),
  5447. '<code>.mp4</code>',
  5448. '<code>.mov</code>'
  5449. )
  5450. );
  5451. }
  5452. }
  5453. return $validity;
  5454. }
  5455. /**
  5456. * Callback for validating the external_header_video value.
  5457. *
  5458. * Ensures that the provided URL is supported.
  5459. *
  5460. * @since 4.7.0
  5461. *
  5462. * @param WP_Error $validity
  5463. * @param mixed $value
  5464. * @return mixed
  5465. */
  5466. public function _validate_external_header_video( $validity, $value ) {
  5467. $video = esc_url_raw( $value );
  5468. if ( $video ) {
  5469. if ( ! preg_match( '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#', $video ) ) {
  5470. $validity->add( 'invalid_url', __( 'Please enter a valid YouTube URL.' ) );
  5471. }
  5472. }
  5473. return $validity;
  5474. }
  5475. /**
  5476. * Callback for sanitizing the external_header_video value.
  5477. *
  5478. * @since 4.7.1
  5479. *
  5480. * @param string $value URL.
  5481. * @return string Sanitized URL.
  5482. */
  5483. public function _sanitize_external_header_video( $value ) {
  5484. return esc_url_raw( trim( $value ) );
  5485. }
  5486. /**
  5487. * Callback for rendering the custom logo, used in the custom_logo partial.
  5488. *
  5489. * This method exists because the partial object and context data are passed
  5490. * into a partial's render_callback so we cannot use get_custom_logo() as
  5491. * the render_callback directly since it expects a blog ID as the first
  5492. * argument. When WP no longer supports PHP 5.3, this method can be removed
  5493. * in favor of an anonymous function.
  5494. *
  5495. * @see WP_Customize_Manager::register_controls()
  5496. *
  5497. * @since 4.5.0
  5498. *
  5499. * @return string Custom logo.
  5500. */
  5501. public function _render_custom_logo_partial() {
  5502. return get_custom_logo();
  5503. }
  5504. }