暫無描述

class-wp-customize-manager.php 196KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108
  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 array
  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 $this 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. * Return 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. * Return 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. * Start preview and customize theme.
  436. *
  437. * Check if customize query variable exist. Init filters to filter the current theme.
  438. *
  439. * @since 3.4.0
  440. *
  441. * @global string $pagenow
  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. * Establish 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
  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 $this WP_Customize_Manager instance.
  608. */
  609. do_action( 'start_previewing_theme', $this );
  610. }
  611. /**
  612. * Stop previewing the selected theme.
  613. *
  614. * Removes filters to change the current 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 $this 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. * Get 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. * Get 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. * Get 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. * Get 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. * Get 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. * Get 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. * Get 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. * Register 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 $this 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. * Find 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. * Get 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. * Dismiss 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. * Get 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. * Get 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. * Get 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. * Import 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. 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. * Prepare 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. * Save 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. * Get 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 current 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` parameter.
  1609. * @since 4.6.0 `$default` 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 returned $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 provided.
  1619. */
  1620. public function post_value( $setting, $default = null ) {
  1621. $post_values = $this->unsanitized_post_values();
  1622. if ( ! array_key_exists( $setting->id, $post_values ) ) {
  1623. return $default;
  1624. }
  1625. $value = $post_values[ $setting->id ];
  1626. $valid = $setting->validate( $value );
  1627. if ( is_wp_error( $valid ) ) {
  1628. return $default;
  1629. }
  1630. $value = $setting->sanitize( $value );
  1631. if ( is_null( $value ) || is_wp_error( $value ) ) {
  1632. return $default;
  1633. }
  1634. return $value;
  1635. }
  1636. /**
  1637. * Override 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. * Announce 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 $this WP_Customize_Manager instance.
  1661. */
  1662. do_action( "customize_post_value_set_{$setting_id}", $value, $this );
  1663. /**
  1664. * Announce 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 $this WP_Customize_Manager instance.
  1676. */
  1677. do_action( 'customize_post_value_set', $setting_id, $value, $this );
  1678. }
  1679. /**
  1680. * Print 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 $this 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. * Add 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. * Prevent 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. * Print 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. * Print 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. * Print 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. * Remove 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. * Print 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 mixed $return Value passed through for {@see 'wp_die_handler'} filter.
  2007. * @return mixed Value passed through for {@see 'wp_die_handler'} filter.
  2008. */
  2009. public function remove_preview_signature( $return = null ) {
  2010. _deprecated_function( __METHOD__, '4.7.0' );
  2011. return $return;
  2012. }
  2013. /**
  2014. * Is it a theme preview?
  2015. *
  2016. * @since 3.4.0
  2017. *
  2018. * @return bool True if it's a preview, false if not.
  2019. */
  2020. public function is_preview() {
  2021. return (bool) $this->previewing;
  2022. }
  2023. /**
  2024. * Retrieve the template name of the previewed theme.
  2025. *
  2026. * @since 3.4.0
  2027. *
  2028. * @return string Template name.
  2029. */
  2030. public function get_template() {
  2031. return $this->theme()->get_template();
  2032. }
  2033. /**
  2034. * Retrieve the stylesheet name of the previewed theme.
  2035. *
  2036. * @since 3.4.0
  2037. *
  2038. * @return string Stylesheet name.
  2039. */
  2040. public function get_stylesheet() {
  2041. return $this->theme()->get_stylesheet();
  2042. }
  2043. /**
  2044. * Retrieve the template root of the previewed theme.
  2045. *
  2046. * @since 3.4.0
  2047. *
  2048. * @return string Theme root.
  2049. */
  2050. public function get_template_root() {
  2051. return get_raw_theme_root( $this->get_template(), true );
  2052. }
  2053. /**
  2054. * Retrieve the stylesheet root of the previewed theme.
  2055. *
  2056. * @since 3.4.0
  2057. *
  2058. * @return string Theme root.
  2059. */
  2060. public function get_stylesheet_root() {
  2061. return get_raw_theme_root( $this->get_stylesheet(), true );
  2062. }
  2063. /**
  2064. * Filters the current theme and return the name of the previewed theme.
  2065. *
  2066. * @since 3.4.0
  2067. *
  2068. * @param mixed $current_theme {@internal Parameter is not used}
  2069. * @return string Theme name.
  2070. */
  2071. public function current_theme( $current_theme ) {
  2072. return $this->theme()->display( 'Name' );
  2073. }
  2074. /**
  2075. * Validates setting values.
  2076. *
  2077. * Validation is skipped for unregistered settings or for values that are
  2078. * already null since they will be skipped anyway. Sanitization is applied
  2079. * to values that pass validation, and values that become null or `WP_Error`
  2080. * after sanitizing are marked invalid.
  2081. *
  2082. * @since 4.6.0
  2083. *
  2084. * @see WP_REST_Request::has_valid_params()
  2085. * @see WP_Customize_Setting::validate()
  2086. *
  2087. * @param array $setting_values Mapping of setting IDs to values to validate and sanitize.
  2088. * @param array $options {
  2089. * Options.
  2090. *
  2091. * @type bool $validate_existence Whether a setting's existence will be checked.
  2092. * @type bool $validate_capability Whether the setting capability will be checked.
  2093. * }
  2094. * @return array Mapping of setting IDs to return value of validate method calls, either `true` or `WP_Error`.
  2095. */
  2096. public function validate_setting_values( $setting_values, $options = array() ) {
  2097. $options = wp_parse_args(
  2098. $options,
  2099. array(
  2100. 'validate_capability' => false,
  2101. 'validate_existence' => false,
  2102. )
  2103. );
  2104. $validities = array();
  2105. foreach ( $setting_values as $setting_id => $unsanitized_value ) {
  2106. $setting = $this->get_setting( $setting_id );
  2107. if ( ! $setting ) {
  2108. if ( $options['validate_existence'] ) {
  2109. $validities[ $setting_id ] = new WP_Error( 'unrecognized', __( 'Setting does not exist or is unrecognized.' ) );
  2110. }
  2111. continue;
  2112. }
  2113. if ( $options['validate_capability'] && ! current_user_can( $setting->capability ) ) {
  2114. $validity = new WP_Error( 'unauthorized', __( 'Unauthorized to modify setting due to capability.' ) );
  2115. } else {
  2116. if ( is_null( $unsanitized_value ) ) {
  2117. continue;
  2118. }
  2119. $validity = $setting->validate( $unsanitized_value );
  2120. }
  2121. if ( ! is_wp_error( $validity ) ) {
  2122. /** This filter is documented in wp-includes/class-wp-customize-setting.php */
  2123. $late_validity = apply_filters( "customize_validate_{$setting->id}", new WP_Error(), $unsanitized_value, $setting );
  2124. if ( is_wp_error( $late_validity ) && $late_validity->has_errors() ) {
  2125. $validity = $late_validity;
  2126. }
  2127. }
  2128. if ( ! is_wp_error( $validity ) ) {
  2129. $value = $setting->sanitize( $unsanitized_value );
  2130. if ( is_null( $value ) ) {
  2131. $validity = false;
  2132. } elseif ( is_wp_error( $value ) ) {
  2133. $validity = $value;
  2134. }
  2135. }
  2136. if ( false === $validity ) {
  2137. $validity = new WP_Error( 'invalid_value', __( 'Invalid value.' ) );
  2138. }
  2139. $validities[ $setting_id ] = $validity;
  2140. }
  2141. return $validities;
  2142. }
  2143. /**
  2144. * Prepares setting validity for exporting to the client (JS).
  2145. *
  2146. * Converts `WP_Error` instance into array suitable for passing into the
  2147. * `wp.customize.Notification` JS model.
  2148. *
  2149. * @since 4.6.0
  2150. *
  2151. * @param true|WP_Error $validity Setting validity.
  2152. * @return true|array If `$validity` was a WP_Error, the error codes will be array-mapped
  2153. * to their respective `message` and `data` to pass into the
  2154. * `wp.customize.Notification` JS model.
  2155. */
  2156. public function prepare_setting_validity_for_js( $validity ) {
  2157. if ( is_wp_error( $validity ) ) {
  2158. $notification = array();
  2159. foreach ( $validity->errors as $error_code => $error_messages ) {
  2160. $notification[ $error_code ] = array(
  2161. 'message' => implode( ' ', $error_messages ),
  2162. 'data' => $validity->get_error_data( $error_code ),
  2163. );
  2164. }
  2165. return $notification;
  2166. } else {
  2167. return true;
  2168. }
  2169. }
  2170. /**
  2171. * Handle customize_save WP Ajax request to save/update a changeset.
  2172. *
  2173. * @since 3.4.0
  2174. * @since 4.7.0 The semantics of this method have changed to update a changeset, optionally to also change the status and other attributes.
  2175. */
  2176. public function save() {
  2177. if ( ! is_user_logged_in() ) {
  2178. wp_send_json_error( 'unauthenticated' );
  2179. }
  2180. if ( ! $this->is_preview() ) {
  2181. wp_send_json_error( 'not_preview' );
  2182. }
  2183. $action = 'save-customize_' . $this->get_stylesheet();
  2184. if ( ! check_ajax_referer( $action, 'nonce', false ) ) {
  2185. wp_send_json_error( 'invalid_nonce' );
  2186. }
  2187. $changeset_post_id = $this->changeset_post_id();
  2188. $is_new_changeset = empty( $changeset_post_id );
  2189. if ( $is_new_changeset ) {
  2190. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->create_posts ) ) {
  2191. wp_send_json_error( 'cannot_create_changeset_post' );
  2192. }
  2193. } else {
  2194. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) {
  2195. wp_send_json_error( 'cannot_edit_changeset_post' );
  2196. }
  2197. }
  2198. if ( ! empty( $_POST['customize_changeset_data'] ) ) {
  2199. $input_changeset_data = json_decode( wp_unslash( $_POST['customize_changeset_data'] ), true );
  2200. if ( ! is_array( $input_changeset_data ) ) {
  2201. wp_send_json_error( 'invalid_customize_changeset_data' );
  2202. }
  2203. } else {
  2204. $input_changeset_data = array();
  2205. }
  2206. // Validate title.
  2207. $changeset_title = null;
  2208. if ( isset( $_POST['customize_changeset_title'] ) ) {
  2209. $changeset_title = sanitize_text_field( wp_unslash( $_POST['customize_changeset_title'] ) );
  2210. }
  2211. // Validate changeset status param.
  2212. $is_publish = null;
  2213. $changeset_status = null;
  2214. if ( isset( $_POST['customize_changeset_status'] ) ) {
  2215. $changeset_status = wp_unslash( $_POST['customize_changeset_status'] );
  2216. if ( ! get_post_status_object( $changeset_status ) || ! in_array( $changeset_status, array( 'draft', 'pending', 'publish', 'future' ), true ) ) {
  2217. wp_send_json_error( 'bad_customize_changeset_status', 400 );
  2218. }
  2219. $is_publish = ( 'publish' === $changeset_status || 'future' === $changeset_status );
  2220. if ( $is_publish && ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts ) ) {
  2221. wp_send_json_error( 'changeset_publish_unauthorized', 403 );
  2222. }
  2223. }
  2224. /*
  2225. * Validate changeset date param. Date is assumed to be in local time for
  2226. * the WP if in MySQL format (YYYY-MM-DD HH:MM:SS). Otherwise, the date
  2227. * is parsed with strtotime() so that ISO date format may be supplied
  2228. * or a string like "+10 minutes".
  2229. */
  2230. $changeset_date_gmt = null;
  2231. if ( isset( $_POST['customize_changeset_date'] ) ) {
  2232. $changeset_date = wp_unslash( $_POST['customize_changeset_date'] );
  2233. if ( preg_match( '/^\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d$/', $changeset_date ) ) {
  2234. $mm = substr( $changeset_date, 5, 2 );
  2235. $jj = substr( $changeset_date, 8, 2 );
  2236. $aa = substr( $changeset_date, 0, 4 );
  2237. $valid_date = wp_checkdate( $mm, $jj, $aa, $changeset_date );
  2238. if ( ! $valid_date ) {
  2239. wp_send_json_error( 'bad_customize_changeset_date', 400 );
  2240. }
  2241. $changeset_date_gmt = get_gmt_from_date( $changeset_date );
  2242. } else {
  2243. $timestamp = strtotime( $changeset_date );
  2244. if ( ! $timestamp ) {
  2245. wp_send_json_error( 'bad_customize_changeset_date', 400 );
  2246. }
  2247. $changeset_date_gmt = gmdate( 'Y-m-d H:i:s', $timestamp );
  2248. }
  2249. }
  2250. $lock_user_id = null;
  2251. $autosave = ! empty( $_POST['customize_changeset_autosave'] );
  2252. if ( ! $is_new_changeset ) {
  2253. $lock_user_id = wp_check_post_lock( $this->changeset_post_id() );
  2254. }
  2255. // Force request to autosave when changeset is locked.
  2256. if ( $lock_user_id && ! $autosave ) {
  2257. $autosave = true;
  2258. $changeset_status = null;
  2259. $changeset_date_gmt = null;
  2260. }
  2261. if ( $autosave && ! defined( 'DOING_AUTOSAVE' ) ) { // Back-compat.
  2262. define( 'DOING_AUTOSAVE', true );
  2263. }
  2264. $autosaved = false;
  2265. $r = $this->save_changeset_post(
  2266. array(
  2267. 'status' => $changeset_status,
  2268. 'title' => $changeset_title,
  2269. 'date_gmt' => $changeset_date_gmt,
  2270. 'data' => $input_changeset_data,
  2271. 'autosave' => $autosave,
  2272. )
  2273. );
  2274. if ( $autosave && ! is_wp_error( $r ) ) {
  2275. $autosaved = true;
  2276. }
  2277. // If the changeset was locked and an autosave request wasn't itself an error, then now explicitly return with a failure.
  2278. if ( $lock_user_id && ! is_wp_error( $r ) ) {
  2279. $r = new WP_Error(
  2280. 'changeset_locked',
  2281. __( 'Changeset is being edited by other user.' ),
  2282. array(
  2283. 'lock_user' => $this->get_lock_user_data( $lock_user_id ),
  2284. )
  2285. );
  2286. }
  2287. if ( is_wp_error( $r ) ) {
  2288. $response = array(
  2289. 'message' => $r->get_error_message(),
  2290. 'code' => $r->get_error_code(),
  2291. );
  2292. if ( is_array( $r->get_error_data() ) ) {
  2293. $response = array_merge( $response, $r->get_error_data() );
  2294. } else {
  2295. $response['data'] = $r->get_error_data();
  2296. }
  2297. } else {
  2298. $response = $r;
  2299. $changeset_post = get_post( $this->changeset_post_id() );
  2300. // Dismiss all other auto-draft changeset posts for this user (they serve like autosave revisions), as there should only be one.
  2301. if ( $is_new_changeset ) {
  2302. $this->dismiss_user_auto_draft_changesets();
  2303. }
  2304. // Note that if the changeset status was publish, then it will get set to Trash if revisions are not supported.
  2305. $response['changeset_status'] = $changeset_post->post_status;
  2306. if ( $is_publish && 'trash' === $response['changeset_status'] ) {
  2307. $response['changeset_status'] = 'publish';
  2308. }
  2309. if ( 'publish' !== $response['changeset_status'] ) {
  2310. $this->set_changeset_lock( $changeset_post->ID );
  2311. }
  2312. if ( 'future' === $response['changeset_status'] ) {
  2313. $response['changeset_date'] = $changeset_post->post_date;
  2314. }
  2315. if ( 'publish' === $response['changeset_status'] || 'trash' === $response['changeset_status'] ) {
  2316. $response['next_changeset_uuid'] = wp_generate_uuid4();
  2317. }
  2318. }
  2319. if ( $autosave ) {
  2320. $response['autosaved'] = $autosaved;
  2321. }
  2322. if ( isset( $response['setting_validities'] ) ) {
  2323. $response['setting_validities'] = array_map( array( $this, 'prepare_setting_validity_for_js' ), $response['setting_validities'] );
  2324. }
  2325. /**
  2326. * Filters response data for a successful customize_save Ajax request.
  2327. *
  2328. * This filter does not apply if there was a nonce or authentication failure.
  2329. *
  2330. * @since 4.2.0
  2331. *
  2332. * @param array $response Additional information passed back to the 'saved'
  2333. * event on `wp.customize`.
  2334. * @param WP_Customize_Manager $this WP_Customize_Manager instance.
  2335. */
  2336. $response = apply_filters( 'customize_save_response', $response, $this );
  2337. if ( is_wp_error( $r ) ) {
  2338. wp_send_json_error( $response );
  2339. } else {
  2340. wp_send_json_success( $response );
  2341. }
  2342. }
  2343. /**
  2344. * Save the post for the loaded changeset.
  2345. *
  2346. * @since 4.7.0
  2347. *
  2348. * @param array $args {
  2349. * Args for changeset post.
  2350. *
  2351. * @type array $data Optional additional changeset data. Values will be merged on top of any existing post values.
  2352. * @type string $status Post status. Optional. If supplied, the save will be transactional and a post revision will be allowed.
  2353. * @type string $title Post title. Optional.
  2354. * @type string $date_gmt Date in GMT. Optional.
  2355. * @type int $user_id ID for user who is saving the changeset. Optional, defaults to the current user ID.
  2356. * @type bool $starter_content Whether the data is starter content. If false (default), then $starter_content will be cleared for any $data being saved.
  2357. * @type bool $autosave Whether this is a request to create an autosave revision.
  2358. * }
  2359. *
  2360. * @return array|WP_Error Returns array on success and WP_Error with array data on error.
  2361. */
  2362. function save_changeset_post( $args = array() ) {
  2363. $args = array_merge(
  2364. array(
  2365. 'status' => null,
  2366. 'title' => null,
  2367. 'data' => array(),
  2368. 'date_gmt' => null,
  2369. 'user_id' => get_current_user_id(),
  2370. 'starter_content' => false,
  2371. 'autosave' => false,
  2372. ),
  2373. $args
  2374. );
  2375. $changeset_post_id = $this->changeset_post_id();
  2376. $existing_changeset_data = array();
  2377. if ( $changeset_post_id ) {
  2378. $existing_status = get_post_status( $changeset_post_id );
  2379. if ( 'publish' === $existing_status || 'trash' === $existing_status ) {
  2380. return new WP_Error(
  2381. 'changeset_already_published',
  2382. __( 'The previous set of changes has already been published. Please try saving your current set of changes again.' ),
  2383. array(
  2384. 'next_changeset_uuid' => wp_generate_uuid4(),
  2385. )
  2386. );
  2387. }
  2388. $existing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  2389. if ( is_wp_error( $existing_changeset_data ) ) {
  2390. return $existing_changeset_data;
  2391. }
  2392. }
  2393. // Fail if attempting to publish but publish hook is missing.
  2394. if ( 'publish' === $args['status'] && false === has_action( 'transition_post_status', '_wp_customize_publish_changeset' ) ) {
  2395. return new WP_Error( 'missing_publish_callback' );
  2396. }
  2397. // Validate date.
  2398. $now = gmdate( 'Y-m-d H:i:59' );
  2399. if ( $args['date_gmt'] ) {
  2400. $is_future_dated = ( mysql2date( 'U', $args['date_gmt'], false ) > mysql2date( 'U', $now, false ) );
  2401. if ( ! $is_future_dated ) {
  2402. return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) ); // Only future dates are allowed.
  2403. }
  2404. if ( ! $this->is_theme_active() && ( 'future' === $args['status'] || $is_future_dated ) ) {
  2405. return new WP_Error( 'cannot_schedule_theme_switches' ); // This should be allowed in the future, when theme is a regular setting.
  2406. }
  2407. $will_remain_auto_draft = ( ! $args['status'] && ( ! $changeset_post_id || 'auto-draft' === get_post_status( $changeset_post_id ) ) );
  2408. if ( $will_remain_auto_draft ) {
  2409. return new WP_Error( 'cannot_supply_date_for_auto_draft_changeset' );
  2410. }
  2411. } elseif ( $changeset_post_id && 'future' === $args['status'] ) {
  2412. // Fail if the new status is future but the existing post's date is not in the future.
  2413. $changeset_post = get_post( $changeset_post_id );
  2414. if ( mysql2date( 'U', $changeset_post->post_date_gmt, false ) <= mysql2date( 'U', $now, false ) ) {
  2415. return new WP_Error( 'not_future_date', __( 'You must supply a future date to schedule.' ) );
  2416. }
  2417. }
  2418. if ( ! empty( $is_future_dated ) && 'publish' === $args['status'] ) {
  2419. $args['status'] = 'future';
  2420. }
  2421. // Validate autosave param. See _wp_post_revision_fields() for why these fields are disallowed.
  2422. if ( $args['autosave'] ) {
  2423. if ( $args['date_gmt'] ) {
  2424. return new WP_Error( 'illegal_autosave_with_date_gmt' );
  2425. } elseif ( $args['status'] ) {
  2426. return new WP_Error( 'illegal_autosave_with_status' );
  2427. } elseif ( $args['user_id'] && get_current_user_id() !== $args['user_id'] ) {
  2428. return new WP_Error( 'illegal_autosave_with_non_current_user' );
  2429. }
  2430. }
  2431. // The request was made via wp.customize.previewer.save().
  2432. $update_transactionally = (bool) $args['status'];
  2433. $allow_revision = (bool) $args['status'];
  2434. // Amend post values with any supplied data.
  2435. foreach ( $args['data'] as $setting_id => $setting_params ) {
  2436. if ( is_array( $setting_params ) && array_key_exists( 'value', $setting_params ) ) {
  2437. $this->set_post_value( $setting_id, $setting_params['value'] ); // Add to post values so that they can be validated and sanitized.
  2438. }
  2439. }
  2440. // Note that in addition to post data, this will include any stashed theme mods.
  2441. $post_values = $this->unsanitized_post_values(
  2442. array(
  2443. 'exclude_changeset' => true,
  2444. 'exclude_post_data' => false,
  2445. )
  2446. );
  2447. $this->add_dynamic_settings( array_keys( $post_values ) ); // Ensure settings get created even if they lack an input value.
  2448. /*
  2449. * Get list of IDs for settings that have values different from what is currently
  2450. * saved in the changeset. By skipping any values that are already the same, the
  2451. * subset of changed settings can be passed into validate_setting_values to prevent
  2452. * an underprivileged modifying a single setting for which they have the capability
  2453. * from being blocked from saving. This also prevents a user from touching of the
  2454. * previous saved settings and overriding the associated user_id if they made no change.
  2455. */
  2456. $changed_setting_ids = array();
  2457. foreach ( $post_values as $setting_id => $setting_value ) {
  2458. $setting = $this->get_setting( $setting_id );
  2459. if ( $setting && 'theme_mod' === $setting->type ) {
  2460. $prefixed_setting_id = $this->get_stylesheet() . '::' . $setting->id;
  2461. } else {
  2462. $prefixed_setting_id = $setting_id;
  2463. }
  2464. $is_value_changed = (
  2465. ! isset( $existing_changeset_data[ $prefixed_setting_id ] )
  2466. ||
  2467. ! array_key_exists( 'value', $existing_changeset_data[ $prefixed_setting_id ] )
  2468. ||
  2469. $existing_changeset_data[ $prefixed_setting_id ]['value'] !== $setting_value
  2470. );
  2471. if ( $is_value_changed ) {
  2472. $changed_setting_ids[] = $setting_id;
  2473. }
  2474. }
  2475. /**
  2476. * Fires before save validation happens.
  2477. *
  2478. * Plugins can add just-in-time {@see 'customize_validate_{$this->ID}'} filters
  2479. * at this point to catch any settings registered after `customize_register`.
  2480. * The dynamic portion of the hook name, `$this->ID` refers to the setting ID.
  2481. *
  2482. * @since 4.6.0
  2483. *
  2484. * @param WP_Customize_Manager $this WP_Customize_Manager instance.
  2485. */
  2486. do_action( 'customize_save_validation_before', $this );
  2487. // Validate settings.
  2488. $validated_values = array_merge(
  2489. array_fill_keys( array_keys( $args['data'] ), null ), // Make sure existence/capability checks are done on value-less setting updates.
  2490. $post_values
  2491. );
  2492. $setting_validities = $this->validate_setting_values(
  2493. $validated_values,
  2494. array(
  2495. 'validate_capability' => true,
  2496. 'validate_existence' => true,
  2497. )
  2498. );
  2499. $invalid_setting_count = count( array_filter( $setting_validities, 'is_wp_error' ) );
  2500. /*
  2501. * Short-circuit if there are invalid settings the update is transactional.
  2502. * A changeset update is transactional when a status is supplied in the request.
  2503. */
  2504. if ( $update_transactionally && $invalid_setting_count > 0 ) {
  2505. $response = array(
  2506. 'setting_validities' => $setting_validities,
  2507. /* translators: %s: Number of invalid settings. */
  2508. '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 ) ),
  2509. );
  2510. return new WP_Error( 'transaction_fail', '', $response );
  2511. }
  2512. // Obtain/merge data for changeset.
  2513. $original_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  2514. $data = $original_changeset_data;
  2515. if ( is_wp_error( $data ) ) {
  2516. $data = array();
  2517. }
  2518. // Ensure that all post values are included in the changeset data.
  2519. foreach ( $post_values as $setting_id => $post_value ) {
  2520. if ( ! isset( $args['data'][ $setting_id ] ) ) {
  2521. $args['data'][ $setting_id ] = array();
  2522. }
  2523. if ( ! isset( $args['data'][ $setting_id ]['value'] ) ) {
  2524. $args['data'][ $setting_id ]['value'] = $post_value;
  2525. }
  2526. }
  2527. foreach ( $args['data'] as $setting_id => $setting_params ) {
  2528. $setting = $this->get_setting( $setting_id );
  2529. if ( ! $setting || ! $setting->check_capabilities() ) {
  2530. continue;
  2531. }
  2532. // Skip updating changeset for invalid setting values.
  2533. if ( isset( $setting_validities[ $setting_id ] ) && is_wp_error( $setting_validities[ $setting_id ] ) ) {
  2534. continue;
  2535. }
  2536. $changeset_setting_id = $setting_id;
  2537. if ( 'theme_mod' === $setting->type ) {
  2538. $changeset_setting_id = sprintf( '%s::%s', $this->get_stylesheet(), $setting_id );
  2539. }
  2540. if ( null === $setting_params ) {
  2541. // Remove setting from changeset entirely.
  2542. unset( $data[ $changeset_setting_id ] );
  2543. } else {
  2544. if ( ! isset( $data[ $changeset_setting_id ] ) ) {
  2545. $data[ $changeset_setting_id ] = array();
  2546. }
  2547. // Merge any additional setting params that have been supplied with the existing params.
  2548. $merged_setting_params = array_merge( $data[ $changeset_setting_id ], $setting_params );
  2549. // Skip updating setting params if unchanged (ensuring the user_id is not overwritten).
  2550. if ( $data[ $changeset_setting_id ] === $merged_setting_params ) {
  2551. continue;
  2552. }
  2553. $data[ $changeset_setting_id ] = array_merge(
  2554. $merged_setting_params,
  2555. array(
  2556. 'type' => $setting->type,
  2557. 'user_id' => $args['user_id'],
  2558. 'date_modified_gmt' => current_time( 'mysql', true ),
  2559. )
  2560. );
  2561. // Clear starter_content flag in data if changeset is not explicitly being updated for starter content.
  2562. if ( empty( $args['starter_content'] ) ) {
  2563. unset( $data[ $changeset_setting_id ]['starter_content'] );
  2564. }
  2565. }
  2566. }
  2567. $filter_context = array(
  2568. 'uuid' => $this->changeset_uuid(),
  2569. 'title' => $args['title'],
  2570. 'status' => $args['status'],
  2571. 'date_gmt' => $args['date_gmt'],
  2572. 'post_id' => $changeset_post_id,
  2573. 'previous_data' => is_wp_error( $original_changeset_data ) ? array() : $original_changeset_data,
  2574. 'manager' => $this,
  2575. );
  2576. /**
  2577. * Filters the settings' data that will be persisted into the changeset.
  2578. *
  2579. * Plugins may amend additional data (such as additional meta for settings) into the changeset with this filter.
  2580. *
  2581. * @since 4.7.0
  2582. *
  2583. * @param array $data Updated changeset data, mapping setting IDs to arrays containing a $value item and optionally other metadata.
  2584. * @param array $context {
  2585. * Filter context.
  2586. *
  2587. * @type string $uuid Changeset UUID.
  2588. * @type string $title Requested title for the changeset post.
  2589. * @type string $status Requested status for the changeset post.
  2590. * @type string $date_gmt Requested date for the changeset post in MySQL format and GMT timezone.
  2591. * @type int|false $post_id Post ID for the changeset, or false if it doesn't exist yet.
  2592. * @type array $previous_data Previous data contained in the changeset.
  2593. * @type WP_Customize_Manager $manager Manager instance.
  2594. * }
  2595. */
  2596. $data = apply_filters( 'customize_changeset_save_data', $data, $filter_context );
  2597. // Switch theme if publishing changes now.
  2598. if ( 'publish' === $args['status'] && ! $this->is_theme_active() ) {
  2599. // Temporarily stop previewing the theme to allow switch_themes() to operate properly.
  2600. $this->stop_previewing_theme();
  2601. switch_theme( $this->get_stylesheet() );
  2602. update_option( 'theme_switched_via_customizer', true );
  2603. $this->start_previewing_theme();
  2604. }
  2605. // Gather the data for wp_insert_post()/wp_update_post().
  2606. $post_array = array(
  2607. // JSON_UNESCAPED_SLASHES is only to improve readability as slashes needn't be escaped in storage.
  2608. 'post_content' => wp_json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT ),
  2609. );
  2610. if ( $args['title'] ) {
  2611. $post_array['post_title'] = $args['title'];
  2612. }
  2613. if ( $changeset_post_id ) {
  2614. $post_array['ID'] = $changeset_post_id;
  2615. } else {
  2616. $post_array['post_type'] = 'customize_changeset';
  2617. $post_array['post_name'] = $this->changeset_uuid();
  2618. $post_array['post_status'] = 'auto-draft';
  2619. }
  2620. if ( $args['status'] ) {
  2621. $post_array['post_status'] = $args['status'];
  2622. }
  2623. // Reset post date to now if we are publishing, otherwise pass post_date_gmt and translate for post_date.
  2624. if ( 'publish' === $args['status'] ) {
  2625. $post_array['post_date_gmt'] = '0000-00-00 00:00:00';
  2626. $post_array['post_date'] = '0000-00-00 00:00:00';
  2627. } elseif ( $args['date_gmt'] ) {
  2628. $post_array['post_date_gmt'] = $args['date_gmt'];
  2629. $post_array['post_date'] = get_date_from_gmt( $args['date_gmt'] );
  2630. } elseif ( $changeset_post_id && 'auto-draft' === get_post_status( $changeset_post_id ) ) {
  2631. /*
  2632. * Keep bumping the date for the auto-draft whenever it is modified;
  2633. * this extends its life, preserving it from garbage-collection via
  2634. * wp_delete_auto_drafts().
  2635. */
  2636. $post_array['post_date'] = current_time( 'mysql' );
  2637. $post_array['post_date_gmt'] = '';
  2638. }
  2639. $this->store_changeset_revision = $allow_revision;
  2640. add_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ), 5, 3 );
  2641. /*
  2642. * Update the changeset post. The publish_customize_changeset action will cause the settings in the
  2643. * changeset to be saved via WP_Customize_Setting::save(). Updating a post with publish status will
  2644. * trigger WP_Customize_Manager::publish_changeset_values().
  2645. */
  2646. add_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5, 3 );
  2647. if ( $changeset_post_id ) {
  2648. if ( $args['autosave'] && 'auto-draft' !== get_post_status( $changeset_post_id ) ) {
  2649. // See _wp_translate_postdata() for why this is required as it will use the edit_post meta capability.
  2650. add_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10, 4 );
  2651. $post_array['post_ID'] = $post_array['ID'];
  2652. $post_array['post_type'] = 'customize_changeset';
  2653. $r = wp_create_post_autosave( wp_slash( $post_array ) );
  2654. remove_filter( 'map_meta_cap', array( $this, 'grant_edit_post_capability_for_changeset' ), 10 );
  2655. } else {
  2656. $post_array['edit_date'] = true; // Prevent date clearing.
  2657. $r = wp_update_post( wp_slash( $post_array ), true );
  2658. // Delete autosave revision for user when the changeset is updated.
  2659. if ( ! empty( $args['user_id'] ) ) {
  2660. $autosave_draft = wp_get_post_autosave( $changeset_post_id, $args['user_id'] );
  2661. if ( $autosave_draft ) {
  2662. wp_delete_post( $autosave_draft->ID, true );
  2663. }
  2664. }
  2665. }
  2666. } else {
  2667. $r = wp_insert_post( wp_slash( $post_array ), true );
  2668. if ( ! is_wp_error( $r ) ) {
  2669. $this->_changeset_post_id = $r; // Update cached post ID for the loaded changeset.
  2670. }
  2671. }
  2672. remove_filter( 'wp_insert_post_data', array( $this, 'preserve_insert_changeset_post_content' ), 5 );
  2673. $this->_changeset_data = null; // Reset so WP_Customize_Manager::changeset_data() will re-populate with updated contents.
  2674. remove_filter( 'wp_save_post_revision_post_has_changed', array( $this, '_filter_revision_post_has_changed' ) );
  2675. $response = array(
  2676. 'setting_validities' => $setting_validities,
  2677. );
  2678. if ( is_wp_error( $r ) ) {
  2679. $response['changeset_post_save_failure'] = $r->get_error_code();
  2680. return new WP_Error( 'changeset_post_save_failure', '', $response );
  2681. }
  2682. return $response;
  2683. }
  2684. /**
  2685. * Preserve the initial JSON post_content passed to save into the post.
  2686. *
  2687. * This is needed to prevent KSES and other {@see 'content_save_pre'} filters
  2688. * from corrupting JSON data.
  2689. *
  2690. * Note that WP_Customize_Manager::validate_setting_values() have already
  2691. * run on the setting values being serialized as JSON into the post content
  2692. * so it is pre-sanitized.
  2693. *
  2694. * Also, the sanitization logic is re-run through the respective
  2695. * WP_Customize_Setting::sanitize() method when being read out of the
  2696. * changeset, via WP_Customize_Manager::post_value(), and this sanitized
  2697. * value will also be sent into WP_Customize_Setting::update() for
  2698. * persisting to the DB.
  2699. *
  2700. * Multiple users can collaborate on a single changeset, where one user may
  2701. * have the unfiltered_html capability but another may not. A user with
  2702. * unfiltered_html may add a script tag to some field which needs to be kept
  2703. * intact even when another user updates the changeset to modify another field
  2704. * when they do not have unfiltered_html.
  2705. *
  2706. * @since 5.4.1
  2707. *
  2708. * @param array $data An array of slashed and processed post data.
  2709. * @param array $postarr An array of sanitized (and slashed) but otherwise unmodified post data.
  2710. * @param array $unsanitized_postarr An array of slashed yet *unsanitized* and unprocessed post data as originally passed to wp_insert_post().
  2711. * @return array Filtered post data.
  2712. */
  2713. public function preserve_insert_changeset_post_content( $data, $postarr, $unsanitized_postarr ) {
  2714. if (
  2715. isset( $data['post_type'] ) &&
  2716. isset( $unsanitized_postarr['post_content'] ) &&
  2717. 'customize_changeset' === $data['post_type'] ||
  2718. (
  2719. 'revision' === $data['post_type'] &&
  2720. ! empty( $data['post_parent'] ) &&
  2721. 'customize_changeset' === get_post_type( $data['post_parent'] )
  2722. )
  2723. ) {
  2724. $data['post_content'] = $unsanitized_postarr['post_content'];
  2725. }
  2726. return $data;
  2727. }
  2728. /**
  2729. * Trash or delete a changeset post.
  2730. *
  2731. * The following re-formulates the logic from `wp_trash_post()` as done in
  2732. * `wp_publish_post()`. The reason for bypassing `wp_trash_post()` is that it
  2733. * will mutate the the `post_content` and the `post_name` when they should be
  2734. * untouched.
  2735. *
  2736. * @since 4.9.0
  2737. *
  2738. * @see wp_trash_post()
  2739. * @global wpdb $wpdb WordPress database abstraction object.
  2740. *
  2741. * @param int|WP_Post $post The changeset post.
  2742. * @return mixed A WP_Post object for the trashed post or an empty value on failure.
  2743. */
  2744. public function trash_changeset_post( $post ) {
  2745. global $wpdb;
  2746. $post = get_post( $post );
  2747. if ( ! ( $post instanceof WP_Post ) ) {
  2748. return $post;
  2749. }
  2750. $post_id = $post->ID;
  2751. if ( ! EMPTY_TRASH_DAYS ) {
  2752. return wp_delete_post( $post_id, true );
  2753. }
  2754. if ( 'trash' === get_post_status( $post ) ) {
  2755. return false;
  2756. }
  2757. /** This filter is documented in wp-includes/post.php */
  2758. $check = apply_filters( 'pre_trash_post', null, $post );
  2759. if ( null !== $check ) {
  2760. return $check;
  2761. }
  2762. /** This action is documented in wp-includes/post.php */
  2763. do_action( 'wp_trash_post', $post_id );
  2764. add_post_meta( $post_id, '_wp_trash_meta_status', $post->post_status );
  2765. add_post_meta( $post_id, '_wp_trash_meta_time', time() );
  2766. $old_status = $post->post_status;
  2767. $new_status = 'trash';
  2768. $wpdb->update( $wpdb->posts, array( 'post_status' => $new_status ), array( 'ID' => $post->ID ) );
  2769. clean_post_cache( $post->ID );
  2770. $post->post_status = $new_status;
  2771. wp_transition_post_status( $new_status, $old_status, $post );
  2772. /** This action is documented in wp-includes/post.php */
  2773. do_action( "edit_post_{$post->post_type}", $post->ID, $post );
  2774. /** This action is documented in wp-includes/post.php */
  2775. do_action( 'edit_post', $post->ID, $post );
  2776. /** This action is documented in wp-includes/post.php */
  2777. do_action( "save_post_{$post->post_type}", $post->ID, $post, true );
  2778. /** This action is documented in wp-includes/post.php */
  2779. do_action( 'save_post', $post->ID, $post, true );
  2780. /** This action is documented in wp-includes/post.php */
  2781. do_action( 'wp_insert_post', $post->ID, $post, true );
  2782. wp_after_insert_post( get_post( $post_id ), true, $post );
  2783. wp_trash_post_comments( $post_id );
  2784. /** This action is documented in wp-includes/post.php */
  2785. do_action( 'trashed_post', $post_id );
  2786. return $post;
  2787. }
  2788. /**
  2789. * Handle request to trash a changeset.
  2790. *
  2791. * @since 4.9.0
  2792. */
  2793. public function handle_changeset_trash_request() {
  2794. if ( ! is_user_logged_in() ) {
  2795. wp_send_json_error( 'unauthenticated' );
  2796. }
  2797. if ( ! $this->is_preview() ) {
  2798. wp_send_json_error( 'not_preview' );
  2799. }
  2800. if ( ! check_ajax_referer( 'trash_customize_changeset', 'nonce', false ) ) {
  2801. wp_send_json_error(
  2802. array(
  2803. 'code' => 'invalid_nonce',
  2804. 'message' => __( 'There was an authentication problem. Please reload and try again.' ),
  2805. )
  2806. );
  2807. }
  2808. $changeset_post_id = $this->changeset_post_id();
  2809. if ( ! $changeset_post_id ) {
  2810. wp_send_json_error(
  2811. array(
  2812. 'message' => __( 'No changes saved yet, so there is nothing to trash.' ),
  2813. 'code' => 'non_existent_changeset',
  2814. )
  2815. );
  2816. return;
  2817. }
  2818. if ( $changeset_post_id ) {
  2819. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) {
  2820. wp_send_json_error(
  2821. array(
  2822. 'code' => 'changeset_trash_unauthorized',
  2823. 'message' => __( 'Unable to trash changes.' ),
  2824. )
  2825. );
  2826. }
  2827. $lock_user = (int) wp_check_post_lock( $changeset_post_id );
  2828. if ( $lock_user && get_current_user_id() !== $lock_user ) {
  2829. wp_send_json_error(
  2830. array(
  2831. 'code' => 'changeset_locked',
  2832. 'message' => __( 'Changeset is being edited by other user.' ),
  2833. 'lockUser' => $this->get_lock_user_data( $lock_user ),
  2834. )
  2835. );
  2836. }
  2837. }
  2838. if ( 'trash' === get_post_status( $changeset_post_id ) ) {
  2839. wp_send_json_error(
  2840. array(
  2841. 'message' => __( 'Changes have already been trashed.' ),
  2842. 'code' => 'changeset_already_trashed',
  2843. )
  2844. );
  2845. return;
  2846. }
  2847. $r = $this->trash_changeset_post( $changeset_post_id );
  2848. if ( ! ( $r instanceof WP_Post ) ) {
  2849. wp_send_json_error(
  2850. array(
  2851. 'code' => 'changeset_trash_failure',
  2852. 'message' => __( 'Unable to trash changes.' ),
  2853. )
  2854. );
  2855. }
  2856. wp_send_json_success(
  2857. array(
  2858. 'message' => __( 'Changes trashed successfully.' ),
  2859. )
  2860. );
  2861. }
  2862. /**
  2863. * Re-map 'edit_post' meta cap for a customize_changeset post to be the same as 'customize' maps.
  2864. *
  2865. * There is essentially a "meta meta" cap in play here, where 'edit_post' meta cap maps to
  2866. * the 'customize' meta cap which then maps to 'edit_theme_options'. This is currently
  2867. * required in core for `wp_create_post_autosave()` because it will call
  2868. * `_wp_translate_postdata()` which in turn will check if a user can 'edit_post', but the
  2869. * the caps for the customize_changeset post type are all mapping to the meta capability.
  2870. * This should be able to be removed once #40922 is addressed in core.
  2871. *
  2872. * @since 4.9.0
  2873. *
  2874. * @link https://core.trac.wordpress.org/ticket/40922
  2875. * @see WP_Customize_Manager::save_changeset_post()
  2876. * @see _wp_translate_postdata()
  2877. *
  2878. * @param string[] $caps Array of the user's capabilities.
  2879. * @param string $cap Capability name.
  2880. * @param int $user_id The user ID.
  2881. * @param array $args Adds the context to the cap. Typically the object ID.
  2882. * @return array Capabilities.
  2883. */
  2884. public function grant_edit_post_capability_for_changeset( $caps, $cap, $user_id, $args ) {
  2885. if ( 'edit_post' === $cap && ! empty( $args[0] ) && 'customize_changeset' === get_post_type( $args[0] ) ) {
  2886. $post_type_obj = get_post_type_object( 'customize_changeset' );
  2887. $caps = map_meta_cap( $post_type_obj->cap->$cap, $user_id );
  2888. }
  2889. return $caps;
  2890. }
  2891. /**
  2892. * Marks the changeset post as being currently edited by the current user.
  2893. *
  2894. * @since 4.9.0
  2895. *
  2896. * @param int $changeset_post_id Changeset post ID.
  2897. * @param bool $take_over Whether to take over the changeset. Default false.
  2898. */
  2899. public function set_changeset_lock( $changeset_post_id, $take_over = false ) {
  2900. if ( $changeset_post_id ) {
  2901. $can_override = ! (bool) get_post_meta( $changeset_post_id, '_edit_lock', true );
  2902. if ( $take_over ) {
  2903. $can_override = true;
  2904. }
  2905. if ( $can_override ) {
  2906. $lock = sprintf( '%s:%s', time(), get_current_user_id() );
  2907. update_post_meta( $changeset_post_id, '_edit_lock', $lock );
  2908. } else {
  2909. $this->refresh_changeset_lock( $changeset_post_id );
  2910. }
  2911. }
  2912. }
  2913. /**
  2914. * Refreshes changeset lock with the current time if current user edited the changeset before.
  2915. *
  2916. * @since 4.9.0
  2917. *
  2918. * @param int $changeset_post_id Changeset post ID.
  2919. */
  2920. public function refresh_changeset_lock( $changeset_post_id ) {
  2921. if ( ! $changeset_post_id ) {
  2922. return;
  2923. }
  2924. $lock = get_post_meta( $changeset_post_id, '_edit_lock', true );
  2925. $lock = explode( ':', $lock );
  2926. if ( $lock && ! empty( $lock[1] ) ) {
  2927. $user_id = (int) $lock[1];
  2928. $current_user_id = get_current_user_id();
  2929. if ( $user_id === $current_user_id ) {
  2930. $lock = sprintf( '%s:%s', time(), $user_id );
  2931. update_post_meta( $changeset_post_id, '_edit_lock', $lock );
  2932. }
  2933. }
  2934. }
  2935. /**
  2936. * Filters heartbeat settings for the Customizer.
  2937. *
  2938. * @since 4.9.0
  2939. * @param array $settings Current settings to filter.
  2940. * @return array Heartbeat settings.
  2941. */
  2942. public function add_customize_screen_to_heartbeat_settings( $settings ) {
  2943. global $pagenow;
  2944. if ( 'customize.php' === $pagenow ) {
  2945. $settings['screenId'] = 'customize';
  2946. }
  2947. return $settings;
  2948. }
  2949. /**
  2950. * Get lock user data.
  2951. *
  2952. * @since 4.9.0
  2953. *
  2954. * @param int $user_id User ID.
  2955. * @return array|null User data formatted for client.
  2956. */
  2957. protected function get_lock_user_data( $user_id ) {
  2958. if ( ! $user_id ) {
  2959. return null;
  2960. }
  2961. $lock_user = get_userdata( $user_id );
  2962. if ( ! $lock_user ) {
  2963. return null;
  2964. }
  2965. return array(
  2966. 'id' => $lock_user->ID,
  2967. 'name' => $lock_user->display_name,
  2968. 'avatar' => get_avatar_url( $lock_user->ID, array( 'size' => 128 ) ),
  2969. );
  2970. }
  2971. /**
  2972. * Check locked changeset with heartbeat API.
  2973. *
  2974. * @since 4.9.0
  2975. *
  2976. * @param array $response The Heartbeat response.
  2977. * @param array $data The $_POST data sent.
  2978. * @param string $screen_id The screen id.
  2979. * @return array The Heartbeat response.
  2980. */
  2981. public function check_changeset_lock_with_heartbeat( $response, $data, $screen_id ) {
  2982. if ( isset( $data['changeset_uuid'] ) ) {
  2983. $changeset_post_id = $this->find_changeset_post_id( $data['changeset_uuid'] );
  2984. } else {
  2985. $changeset_post_id = $this->changeset_post_id();
  2986. }
  2987. if (
  2988. array_key_exists( 'check_changeset_lock', $data )
  2989. && 'customize' === $screen_id
  2990. && $changeset_post_id
  2991. && current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id )
  2992. ) {
  2993. $lock_user_id = wp_check_post_lock( $changeset_post_id );
  2994. if ( $lock_user_id ) {
  2995. $response['customize_changeset_lock_user'] = $this->get_lock_user_data( $lock_user_id );
  2996. } else {
  2997. // Refreshing time will ensure that the user is sitting on customizer and has not closed the customizer tab.
  2998. $this->refresh_changeset_lock( $changeset_post_id );
  2999. }
  3000. }
  3001. return $response;
  3002. }
  3003. /**
  3004. * Removes changeset lock when take over request is sent via Ajax.
  3005. *
  3006. * @since 4.9.0
  3007. */
  3008. public function handle_override_changeset_lock_request() {
  3009. if ( ! $this->is_preview() ) {
  3010. wp_send_json_error( 'not_preview', 400 );
  3011. }
  3012. if ( ! check_ajax_referer( 'customize_override_changeset_lock', 'nonce', false ) ) {
  3013. wp_send_json_error(
  3014. array(
  3015. 'code' => 'invalid_nonce',
  3016. 'message' => __( 'Security check failed.' ),
  3017. )
  3018. );
  3019. }
  3020. $changeset_post_id = $this->changeset_post_id();
  3021. if ( empty( $changeset_post_id ) ) {
  3022. wp_send_json_error(
  3023. array(
  3024. 'code' => 'no_changeset_found_to_take_over',
  3025. 'message' => __( 'No changeset found to take over' ),
  3026. )
  3027. );
  3028. }
  3029. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) ) {
  3030. wp_send_json_error(
  3031. array(
  3032. 'code' => 'cannot_remove_changeset_lock',
  3033. 'message' => __( 'Sorry, you are not allowed to take over.' ),
  3034. )
  3035. );
  3036. }
  3037. $this->set_changeset_lock( $changeset_post_id, true );
  3038. wp_send_json_success( 'changeset_taken_over' );
  3039. }
  3040. /**
  3041. * Whether a changeset revision should be made.
  3042. *
  3043. * @since 4.7.0
  3044. * @var bool
  3045. */
  3046. protected $store_changeset_revision;
  3047. /**
  3048. * Filters whether a changeset has changed to create a new revision.
  3049. *
  3050. * Note that this will not be called while a changeset post remains in auto-draft status.
  3051. *
  3052. * @since 4.7.0
  3053. *
  3054. * @param bool $post_has_changed Whether the post has changed.
  3055. * @param WP_Post $last_revision The last revision post object.
  3056. * @param WP_Post $post The post object.
  3057. * @return bool Whether a revision should be made.
  3058. */
  3059. public function _filter_revision_post_has_changed( $post_has_changed, $last_revision, $post ) {
  3060. unset( $last_revision );
  3061. if ( 'customize_changeset' === $post->post_type ) {
  3062. $post_has_changed = $this->store_changeset_revision;
  3063. }
  3064. return $post_has_changed;
  3065. }
  3066. /**
  3067. * Publish changeset values.
  3068. *
  3069. * This will the values contained in a changeset, even changesets that do not
  3070. * correspond to current manager instance. This is called by
  3071. * `_wp_customize_publish_changeset()` when a customize_changeset post is
  3072. * transitioned to the `publish` status. As such, this method should not be
  3073. * called directly and instead `wp_publish_post()` should be used.
  3074. *
  3075. * Please note that if the settings in the changeset are for a non-activated
  3076. * theme, the theme must first be switched to (via `switch_theme()`) before
  3077. * invoking this method.
  3078. *
  3079. * @since 4.7.0
  3080. *
  3081. * @see _wp_customize_publish_changeset()
  3082. * @global wpdb $wpdb WordPress database abstraction object.
  3083. *
  3084. * @param int $changeset_post_id ID for customize_changeset post. Defaults to the changeset for the current manager instance.
  3085. * @return true|WP_Error True or error info.
  3086. */
  3087. public function _publish_changeset_values( $changeset_post_id ) {
  3088. global $wpdb;
  3089. $publishing_changeset_data = $this->get_changeset_post_data( $changeset_post_id );
  3090. if ( is_wp_error( $publishing_changeset_data ) ) {
  3091. return $publishing_changeset_data;
  3092. }
  3093. $changeset_post = get_post( $changeset_post_id );
  3094. /*
  3095. * Temporarily override the changeset context so that it will be read
  3096. * in calls to unsanitized_post_values() and so that it will be available
  3097. * on the $wp_customize object passed to hooks during the save logic.
  3098. */
  3099. $previous_changeset_post_id = $this->_changeset_post_id;
  3100. $this->_changeset_post_id = $changeset_post_id;
  3101. $previous_changeset_uuid = $this->_changeset_uuid;
  3102. $this->_changeset_uuid = $changeset_post->post_name;
  3103. $previous_changeset_data = $this->_changeset_data;
  3104. $this->_changeset_data = $publishing_changeset_data;
  3105. // Parse changeset data to identify theme mod settings and user IDs associated with settings to be saved.
  3106. $setting_user_ids = array();
  3107. $theme_mod_settings = array();
  3108. $namespace_pattern = '/^(?P<stylesheet>.+?)::(?P<setting_id>.+)$/';
  3109. $matches = array();
  3110. foreach ( $this->_changeset_data as $raw_setting_id => $setting_params ) {
  3111. $actual_setting_id = null;
  3112. $is_theme_mod_setting = (
  3113. isset( $setting_params['value'] )
  3114. &&
  3115. isset( $setting_params['type'] )
  3116. &&
  3117. 'theme_mod' === $setting_params['type']
  3118. &&
  3119. preg_match( $namespace_pattern, $raw_setting_id, $matches )
  3120. );
  3121. if ( $is_theme_mod_setting ) {
  3122. if ( ! isset( $theme_mod_settings[ $matches['stylesheet'] ] ) ) {
  3123. $theme_mod_settings[ $matches['stylesheet'] ] = array();
  3124. }
  3125. $theme_mod_settings[ $matches['stylesheet'] ][ $matches['setting_id'] ] = $setting_params;
  3126. if ( $this->get_stylesheet() === $matches['stylesheet'] ) {
  3127. $actual_setting_id = $matches['setting_id'];
  3128. }
  3129. } else {
  3130. $actual_setting_id = $raw_setting_id;
  3131. }
  3132. // Keep track of the user IDs for settings actually for this theme.
  3133. if ( $actual_setting_id && isset( $setting_params['user_id'] ) ) {
  3134. $setting_user_ids[ $actual_setting_id ] = $setting_params['user_id'];
  3135. }
  3136. }
  3137. $changeset_setting_values = $this->unsanitized_post_values(
  3138. array(
  3139. 'exclude_post_data' => true,
  3140. 'exclude_changeset' => false,
  3141. )
  3142. );
  3143. $changeset_setting_ids = array_keys( $changeset_setting_values );
  3144. $this->add_dynamic_settings( $changeset_setting_ids );
  3145. /**
  3146. * Fires once the theme has switched in the Customizer, but before settings
  3147. * have been saved.
  3148. *
  3149. * @since 3.4.0
  3150. *
  3151. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  3152. */
  3153. do_action( 'customize_save', $this );
  3154. /*
  3155. * Ensure that all settings will allow themselves to be saved. Note that
  3156. * this is safe because the setting would have checked the capability
  3157. * when the setting value was written into the changeset. So this is why
  3158. * an additional capability check is not required here.
  3159. */
  3160. $original_setting_capabilities = array();
  3161. foreach ( $changeset_setting_ids as $setting_id ) {
  3162. $setting = $this->get_setting( $setting_id );
  3163. if ( $setting && ! isset( $setting_user_ids[ $setting_id ] ) ) {
  3164. $original_setting_capabilities[ $setting->id ] = $setting->capability;
  3165. $setting->capability = 'exist';
  3166. }
  3167. }
  3168. $original_user_id = get_current_user_id();
  3169. foreach ( $changeset_setting_ids as $setting_id ) {
  3170. $setting = $this->get_setting( $setting_id );
  3171. if ( $setting ) {
  3172. /*
  3173. * Set the current user to match the user who saved the value into
  3174. * the changeset so that any filters that apply during the save
  3175. * process will respect the original user's capabilities. This
  3176. * will ensure, for example, that KSES won't strip unsafe HTML
  3177. * when a scheduled changeset publishes via WP Cron.
  3178. */
  3179. if ( isset( $setting_user_ids[ $setting_id ] ) ) {
  3180. wp_set_current_user( $setting_user_ids[ $setting_id ] );
  3181. } else {
  3182. wp_set_current_user( $original_user_id );
  3183. }
  3184. $setting->save();
  3185. }
  3186. }
  3187. wp_set_current_user( $original_user_id );
  3188. // Update the stashed theme mod settings, removing the active theme's stashed settings, if activated.
  3189. if ( did_action( 'switch_theme' ) ) {
  3190. $other_theme_mod_settings = $theme_mod_settings;
  3191. unset( $other_theme_mod_settings[ $this->get_stylesheet() ] );
  3192. $this->update_stashed_theme_mod_settings( $other_theme_mod_settings );
  3193. }
  3194. /**
  3195. * Fires after Customize settings have been saved.
  3196. *
  3197. * @since 3.6.0
  3198. *
  3199. * @param WP_Customize_Manager $manager WP_Customize_Manager instance.
  3200. */
  3201. do_action( 'customize_save_after', $this );
  3202. // Restore original capabilities.
  3203. foreach ( $original_setting_capabilities as $setting_id => $capability ) {
  3204. $setting = $this->get_setting( $setting_id );
  3205. if ( $setting ) {
  3206. $setting->capability = $capability;
  3207. }
  3208. }
  3209. // Restore original changeset data.
  3210. $this->_changeset_data = $previous_changeset_data;
  3211. $this->_changeset_post_id = $previous_changeset_post_id;
  3212. $this->_changeset_uuid = $previous_changeset_uuid;
  3213. /*
  3214. * Convert all autosave revisions into their own auto-drafts so that users can be prompted to
  3215. * restore them when a changeset is published, but they had been locked out from including
  3216. * their changes in the changeset.
  3217. */
  3218. $revisions = wp_get_post_revisions( $changeset_post_id, array( 'check_enabled' => false ) );
  3219. foreach ( $revisions as $revision ) {
  3220. if ( false !== strpos( $revision->post_name, "{$changeset_post_id}-autosave" ) ) {
  3221. $wpdb->update(
  3222. $wpdb->posts,
  3223. array(
  3224. 'post_status' => 'auto-draft',
  3225. 'post_type' => 'customize_changeset',
  3226. 'post_name' => wp_generate_uuid4(),
  3227. 'post_parent' => 0,
  3228. ),
  3229. array(
  3230. 'ID' => $revision->ID,
  3231. )
  3232. );
  3233. clean_post_cache( $revision->ID );
  3234. }
  3235. }
  3236. return true;
  3237. }
  3238. /**
  3239. * Update stashed theme mod settings.
  3240. *
  3241. * @since 4.7.0
  3242. *
  3243. * @param array $inactive_theme_mod_settings Mapping of stylesheet to arrays of theme mod settings.
  3244. * @return array|false Returns array of updated stashed theme mods or false if the update failed or there were no changes.
  3245. */
  3246. protected function update_stashed_theme_mod_settings( $inactive_theme_mod_settings ) {
  3247. $stashed_theme_mod_settings = get_option( 'customize_stashed_theme_mods' );
  3248. if ( empty( $stashed_theme_mod_settings ) ) {
  3249. $stashed_theme_mod_settings = array();
  3250. }
  3251. // Delete any stashed theme mods for the active theme since they would have been loaded and saved upon activation.
  3252. unset( $stashed_theme_mod_settings[ $this->get_stylesheet() ] );
  3253. // Merge inactive theme mods with the stashed theme mod settings.
  3254. foreach ( $inactive_theme_mod_settings as $stylesheet => $theme_mod_settings ) {
  3255. if ( ! isset( $stashed_theme_mod_settings[ $stylesheet ] ) ) {
  3256. $stashed_theme_mod_settings[ $stylesheet ] = array();
  3257. }
  3258. $stashed_theme_mod_settings[ $stylesheet ] = array_merge(
  3259. $stashed_theme_mod_settings[ $stylesheet ],
  3260. $theme_mod_settings
  3261. );
  3262. }
  3263. $autoload = false;
  3264. $result = update_option( 'customize_stashed_theme_mods', $stashed_theme_mod_settings, $autoload );
  3265. if ( ! $result ) {
  3266. return false;
  3267. }
  3268. return $stashed_theme_mod_settings;
  3269. }
  3270. /**
  3271. * Refresh nonces for the current preview.
  3272. *
  3273. * @since 4.2.0
  3274. */
  3275. public function refresh_nonces() {
  3276. if ( ! $this->is_preview() ) {
  3277. wp_send_json_error( 'not_preview' );
  3278. }
  3279. wp_send_json_success( $this->get_nonces() );
  3280. }
  3281. /**
  3282. * Delete a given auto-draft changeset or the autosave revision for a given changeset or delete changeset lock.
  3283. *
  3284. * @since 4.9.0
  3285. */
  3286. public function handle_dismiss_autosave_or_lock_request() {
  3287. // Calls to dismiss_user_auto_draft_changesets() and wp_get_post_autosave() require non-zero get_current_user_id().
  3288. if ( ! is_user_logged_in() ) {
  3289. wp_send_json_error( 'unauthenticated', 401 );
  3290. }
  3291. if ( ! $this->is_preview() ) {
  3292. wp_send_json_error( 'not_preview', 400 );
  3293. }
  3294. if ( ! check_ajax_referer( 'customize_dismiss_autosave_or_lock', 'nonce', false ) ) {
  3295. wp_send_json_error( 'invalid_nonce', 403 );
  3296. }
  3297. $changeset_post_id = $this->changeset_post_id();
  3298. $dismiss_lock = ! empty( $_POST['dismiss_lock'] );
  3299. $dismiss_autosave = ! empty( $_POST['dismiss_autosave'] );
  3300. if ( $dismiss_lock ) {
  3301. if ( empty( $changeset_post_id ) && ! $dismiss_autosave ) {
  3302. wp_send_json_error( 'no_changeset_to_dismiss_lock', 404 );
  3303. }
  3304. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->edit_post, $changeset_post_id ) && ! $dismiss_autosave ) {
  3305. wp_send_json_error( 'cannot_remove_changeset_lock', 403 );
  3306. }
  3307. delete_post_meta( $changeset_post_id, '_edit_lock' );
  3308. if ( ! $dismiss_autosave ) {
  3309. wp_send_json_success( 'changeset_lock_dismissed' );
  3310. }
  3311. }
  3312. if ( $dismiss_autosave ) {
  3313. if ( empty( $changeset_post_id ) || 'auto-draft' === get_post_status( $changeset_post_id ) ) {
  3314. $dismissed = $this->dismiss_user_auto_draft_changesets();
  3315. if ( $dismissed > 0 ) {
  3316. wp_send_json_success( 'auto_draft_dismissed' );
  3317. } else {
  3318. wp_send_json_error( 'no_auto_draft_to_delete', 404 );
  3319. }
  3320. } else {
  3321. $revision = wp_get_post_autosave( $changeset_post_id, get_current_user_id() );
  3322. if ( $revision ) {
  3323. if ( ! current_user_can( get_post_type_object( 'customize_changeset' )->cap->delete_post, $changeset_post_id ) ) {
  3324. wp_send_json_error( 'cannot_delete_autosave_revision', 403 );
  3325. }
  3326. if ( ! wp_delete_post( $revision->ID, true ) ) {
  3327. wp_send_json_error( 'autosave_revision_deletion_failure', 500 );
  3328. } else {
  3329. wp_send_json_success( 'autosave_revision_deleted' );
  3330. }
  3331. } else {
  3332. wp_send_json_error( 'no_autosave_revision_to_delete', 404 );
  3333. }
  3334. }
  3335. }
  3336. wp_send_json_error( 'unknown_error', 500 );
  3337. }
  3338. /**
  3339. * Add a customize setting.
  3340. *
  3341. * @since 3.4.0
  3342. * @since 4.5.0 Return added WP_Customize_Setting instance.
  3343. *
  3344. * @see WP_Customize_Setting::__construct()
  3345. * @link https://developer.wordpress.org/themes/customize-api
  3346. *
  3347. * @param WP_Customize_Setting|string $id Customize Setting object, or ID.
  3348. * @param array $args Optional. Array of properties for the new Setting object.
  3349. * See WP_Customize_Setting::__construct() for information
  3350. * on accepted arguments. Default empty array.
  3351. * @return WP_Customize_Setting The instance of the setting that was added.
  3352. */
  3353. public function add_setting( $id, $args = array() ) {
  3354. if ( $id instanceof WP_Customize_Setting ) {
  3355. $setting = $id;
  3356. } else {
  3357. $class = 'WP_Customize_Setting';
  3358. /** This filter is documented in wp-includes/class-wp-customize-manager.php */
  3359. $args = apply_filters( 'customize_dynamic_setting_args', $args, $id );
  3360. /** This filter is documented in wp-includes/class-wp-customize-manager.php */
  3361. $class = apply_filters( 'customize_dynamic_setting_class', $class, $id, $args );
  3362. $setting = new $class( $this, $id, $args );
  3363. }
  3364. $this->settings[ $setting->id ] = $setting;
  3365. return $setting;
  3366. }
  3367. /**
  3368. * Register any dynamically-created settings, such as those from $_POST['customized']
  3369. * that have no corresponding setting created.
  3370. *
  3371. * This is a mechanism to "wake up" settings that have been dynamically created
  3372. * on the front end and have been sent to WordPress in `$_POST['customized']`. When WP
  3373. * loads, the dynamically-created settings then will get created and previewed
  3374. * even though they are not directly created statically with code.
  3375. *
  3376. * @since 4.2.0
  3377. *
  3378. * @param array $setting_ids The setting IDs to add.
  3379. * @return array The WP_Customize_Setting objects added.
  3380. */
  3381. public function add_dynamic_settings( $setting_ids ) {
  3382. $new_settings = array();
  3383. foreach ( $setting_ids as $setting_id ) {
  3384. // Skip settings already created.
  3385. if ( $this->get_setting( $setting_id ) ) {
  3386. continue;
  3387. }
  3388. $setting_args = false;
  3389. $setting_class = 'WP_Customize_Setting';
  3390. /**
  3391. * Filters a dynamic setting's constructor args.
  3392. *
  3393. * For a dynamic setting to be registered, this filter must be employed
  3394. * to override the default false value with an array of args to pass to
  3395. * the WP_Customize_Setting constructor.
  3396. *
  3397. * @since 4.2.0
  3398. *
  3399. * @param false|array $setting_args The arguments to the WP_Customize_Setting constructor.
  3400. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  3401. */
  3402. $setting_args = apply_filters( 'customize_dynamic_setting_args', $setting_args, $setting_id );
  3403. if ( false === $setting_args ) {
  3404. continue;
  3405. }
  3406. /**
  3407. * Allow non-statically created settings to be constructed with custom WP_Customize_Setting subclass.
  3408. *
  3409. * @since 4.2.0
  3410. *
  3411. * @param string $setting_class WP_Customize_Setting or a subclass.
  3412. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  3413. * @param array $setting_args WP_Customize_Setting or a subclass.
  3414. */
  3415. $setting_class = apply_filters( 'customize_dynamic_setting_class', $setting_class, $setting_id, $setting_args );
  3416. $setting = new $setting_class( $this, $setting_id, $setting_args );
  3417. $this->add_setting( $setting );
  3418. $new_settings[] = $setting;
  3419. }
  3420. return $new_settings;
  3421. }
  3422. /**
  3423. * Retrieve a customize setting.
  3424. *
  3425. * @since 3.4.0
  3426. *
  3427. * @param string $id Customize Setting ID.
  3428. * @return WP_Customize_Setting|void The setting, if set.
  3429. */
  3430. public function get_setting( $id ) {
  3431. if ( isset( $this->settings[ $id ] ) ) {
  3432. return $this->settings[ $id ];
  3433. }
  3434. }
  3435. /**
  3436. * Remove a customize setting.
  3437. *
  3438. * Note that removing the setting doesn't destroy the WP_Customize_Setting instance or remove its filters.
  3439. *
  3440. * @since 3.4.0
  3441. *
  3442. * @param string $id Customize Setting ID.
  3443. */
  3444. public function remove_setting( $id ) {
  3445. unset( $this->settings[ $id ] );
  3446. }
  3447. /**
  3448. * Add a customize panel.
  3449. *
  3450. * @since 4.0.0
  3451. * @since 4.5.0 Return added WP_Customize_Panel instance.
  3452. *
  3453. * @see WP_Customize_Panel::__construct()
  3454. *
  3455. * @param WP_Customize_Panel|string $id Customize Panel object, or ID.
  3456. * @param array $args Optional. Array of properties for the new Panel object.
  3457. * See WP_Customize_Panel::__construct() for information
  3458. * on accepted arguments. Default empty array.
  3459. * @return WP_Customize_Panel The instance of the panel that was added.
  3460. */
  3461. public function add_panel( $id, $args = array() ) {
  3462. if ( $id instanceof WP_Customize_Panel ) {
  3463. $panel = $id;
  3464. } else {
  3465. $panel = new WP_Customize_Panel( $this, $id, $args );
  3466. }
  3467. $this->panels[ $panel->id ] = $panel;
  3468. return $panel;
  3469. }
  3470. /**
  3471. * Retrieve a customize panel.
  3472. *
  3473. * @since 4.0.0
  3474. *
  3475. * @param string $id Panel ID to get.
  3476. * @return WP_Customize_Panel|void Requested panel instance, if set.
  3477. */
  3478. public function get_panel( $id ) {
  3479. if ( isset( $this->panels[ $id ] ) ) {
  3480. return $this->panels[ $id ];
  3481. }
  3482. }
  3483. /**
  3484. * Remove a customize panel.
  3485. *
  3486. * Note that removing the panel doesn't destroy the WP_Customize_Panel instance or remove its filters.
  3487. *
  3488. * @since 4.0.0
  3489. *
  3490. * @param string $id Panel ID to remove.
  3491. */
  3492. public function remove_panel( $id ) {
  3493. // Removing core components this way is _doing_it_wrong().
  3494. if ( in_array( $id, $this->components, true ) ) {
  3495. _doing_it_wrong(
  3496. __METHOD__,
  3497. sprintf(
  3498. /* translators: 1: Panel ID, 2: Link to 'customize_loaded_components' filter reference. */
  3499. __( 'Removing %1$s manually will cause PHP warnings. Use the %2$s filter instead.' ),
  3500. $id,
  3501. sprintf(
  3502. '<a href="%1$s">%2$s</a>',
  3503. esc_url( 'https://developer.wordpress.org/reference/hooks/customize_loaded_components/' ),
  3504. '<code>customize_loaded_components</code>'
  3505. )
  3506. ),
  3507. '4.5.0'
  3508. );
  3509. }
  3510. unset( $this->panels[ $id ] );
  3511. }
  3512. /**
  3513. * Register a customize panel type.
  3514. *
  3515. * Registered types are eligible to be rendered via JS and created dynamically.
  3516. *
  3517. * @since 4.3.0
  3518. *
  3519. * @see WP_Customize_Panel
  3520. *
  3521. * @param string $panel Name of a custom panel which is a subclass of WP_Customize_Panel.
  3522. */
  3523. public function register_panel_type( $panel ) {
  3524. $this->registered_panel_types[] = $panel;
  3525. }
  3526. /**
  3527. * Render JS templates for all registered panel types.
  3528. *
  3529. * @since 4.3.0
  3530. */
  3531. public function render_panel_templates() {
  3532. foreach ( $this->registered_panel_types as $panel_type ) {
  3533. $panel = new $panel_type( $this, 'temp', array() );
  3534. $panel->print_template();
  3535. }
  3536. }
  3537. /**
  3538. * Add a customize section.
  3539. *
  3540. * @since 3.4.0
  3541. * @since 4.5.0 Return added WP_Customize_Section instance.
  3542. *
  3543. * @see WP_Customize_Section::__construct()
  3544. *
  3545. * @param WP_Customize_Section|string $id Customize Section object, or ID.
  3546. * @param array $args Optional. Array of properties for the new Section object.
  3547. * See WP_Customize_Section::__construct() for information
  3548. * on accepted arguments. Default empty array.
  3549. * @return WP_Customize_Section The instance of the section that was added.
  3550. */
  3551. public function add_section( $id, $args = array() ) {
  3552. if ( $id instanceof WP_Customize_Section ) {
  3553. $section = $id;
  3554. } else {
  3555. $section = new WP_Customize_Section( $this, $id, $args );
  3556. }
  3557. $this->sections[ $section->id ] = $section;
  3558. return $section;
  3559. }
  3560. /**
  3561. * Retrieve a customize section.
  3562. *
  3563. * @since 3.4.0
  3564. *
  3565. * @param string $id Section ID.
  3566. * @return WP_Customize_Section|void The section, if set.
  3567. */
  3568. public function get_section( $id ) {
  3569. if ( isset( $this->sections[ $id ] ) ) {
  3570. return $this->sections[ $id ];
  3571. }
  3572. }
  3573. /**
  3574. * Remove a customize section.
  3575. *
  3576. * Note that removing the section doesn't destroy the WP_Customize_Section instance or remove its filters.
  3577. *
  3578. * @since 3.4.0
  3579. *
  3580. * @param string $id Section ID.
  3581. */
  3582. public function remove_section( $id ) {
  3583. unset( $this->sections[ $id ] );
  3584. }
  3585. /**
  3586. * Register a customize section type.
  3587. *
  3588. * Registered types are eligible to be rendered via JS and created dynamically.
  3589. *
  3590. * @since 4.3.0
  3591. *
  3592. * @see WP_Customize_Section
  3593. *
  3594. * @param string $section Name of a custom section which is a subclass of WP_Customize_Section.
  3595. */
  3596. public function register_section_type( $section ) {
  3597. $this->registered_section_types[] = $section;
  3598. }
  3599. /**
  3600. * Render JS templates for all registered section types.
  3601. *
  3602. * @since 4.3.0
  3603. */
  3604. public function render_section_templates() {
  3605. foreach ( $this->registered_section_types as $section_type ) {
  3606. $section = new $section_type( $this, 'temp', array() );
  3607. $section->print_template();
  3608. }
  3609. }
  3610. /**
  3611. * Add a customize control.
  3612. *
  3613. * @since 3.4.0
  3614. * @since 4.5.0 Return added WP_Customize_Control instance.
  3615. *
  3616. * @see WP_Customize_Control::__construct()
  3617. *
  3618. * @param WP_Customize_Control|string $id Customize Control object, or ID.
  3619. * @param array $args Optional. Array of properties for the new Control object.
  3620. * See WP_Customize_Control::__construct() for information
  3621. * on accepted arguments. Default empty array.
  3622. * @return WP_Customize_Control The instance of the control that was added.
  3623. */
  3624. public function add_control( $id, $args = array() ) {
  3625. if ( $id instanceof WP_Customize_Control ) {
  3626. $control = $id;
  3627. } else {
  3628. $control = new WP_Customize_Control( $this, $id, $args );
  3629. }
  3630. $this->controls[ $control->id ] = $control;
  3631. return $control;
  3632. }
  3633. /**
  3634. * Retrieve a customize control.
  3635. *
  3636. * @since 3.4.0
  3637. *
  3638. * @param string $id ID of the control.
  3639. * @return WP_Customize_Control|void The control object, if set.
  3640. */
  3641. public function get_control( $id ) {
  3642. if ( isset( $this->controls[ $id ] ) ) {
  3643. return $this->controls[ $id ];
  3644. }
  3645. }
  3646. /**
  3647. * Remove a customize control.
  3648. *
  3649. * Note that removing the control doesn't destroy the WP_Customize_Control instance or remove its filters.
  3650. *
  3651. * @since 3.4.0
  3652. *
  3653. * @param string $id ID of the control.
  3654. */
  3655. public function remove_control( $id ) {
  3656. unset( $this->controls[ $id ] );
  3657. }
  3658. /**
  3659. * Register a customize control type.
  3660. *
  3661. * Registered types are eligible to be rendered via JS and created dynamically.
  3662. *
  3663. * @since 4.1.0
  3664. *
  3665. * @param string $control Name of a custom control which is a subclass of
  3666. * WP_Customize_Control.
  3667. */
  3668. public function register_control_type( $control ) {
  3669. $this->registered_control_types[] = $control;
  3670. }
  3671. /**
  3672. * Render JS templates for all registered control types.
  3673. *
  3674. * @since 4.1.0
  3675. */
  3676. public function render_control_templates() {
  3677. if ( $this->branching() ) {
  3678. $l10n = array(
  3679. /* translators: %s: User who is customizing the changeset in customizer. */
  3680. 'locked' => __( '%s is already customizing this changeset. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ),
  3681. /* translators: %s: User who is customizing the changeset in customizer. */
  3682. 'locked_allow_override' => __( '%s is already customizing this changeset. Do you want to take over?' ),
  3683. );
  3684. } else {
  3685. $l10n = array(
  3686. /* translators: %s: User who is customizing the changeset in customizer. */
  3687. 'locked' => __( '%s is already customizing this site. Please wait until they are done to try customizing. Your latest changes have been autosaved.' ),
  3688. /* translators: %s: User who is customizing the changeset in customizer. */
  3689. 'locked_allow_override' => __( '%s is already customizing this site. Do you want to take over?' ),
  3690. );
  3691. }
  3692. foreach ( $this->registered_control_types as $control_type ) {
  3693. $control = new $control_type(
  3694. $this,
  3695. 'temp',
  3696. array(
  3697. 'settings' => array(),
  3698. )
  3699. );
  3700. $control->print_template();
  3701. }
  3702. ?>
  3703. <script type="text/html" id="tmpl-customize-control-default-content">
  3704. <#
  3705. var inputId = _.uniqueId( 'customize-control-default-input-' );
  3706. var descriptionId = _.uniqueId( 'customize-control-default-description-' );
  3707. var describedByAttr = data.description ? ' aria-describedby="' + descriptionId + '" ' : '';
  3708. #>
  3709. <# switch ( data.type ) {
  3710. case 'checkbox': #>
  3711. <span class="customize-inside-control-row">
  3712. <input
  3713. id="{{ inputId }}"
  3714. {{{ describedByAttr }}}
  3715. type="checkbox"
  3716. value="{{ data.value }}"
  3717. data-customize-setting-key-link="default"
  3718. >
  3719. <label for="{{ inputId }}">
  3720. {{ data.label }}
  3721. </label>
  3722. <# if ( data.description ) { #>
  3723. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3724. <# } #>
  3725. </span>
  3726. <#
  3727. break;
  3728. case 'radio':
  3729. if ( ! data.choices ) {
  3730. return;
  3731. }
  3732. #>
  3733. <# if ( data.label ) { #>
  3734. <label for="{{ inputId }}" class="customize-control-title">
  3735. {{ data.label }}
  3736. </label>
  3737. <# } #>
  3738. <# if ( data.description ) { #>
  3739. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3740. <# } #>
  3741. <# _.each( data.choices, function( val, key ) { #>
  3742. <span class="customize-inside-control-row">
  3743. <#
  3744. var value, text;
  3745. if ( _.isObject( val ) ) {
  3746. value = val.value;
  3747. text = val.text;
  3748. } else {
  3749. value = key;
  3750. text = val;
  3751. }
  3752. #>
  3753. <input
  3754. id="{{ inputId + '-' + value }}"
  3755. type="radio"
  3756. value="{{ value }}"
  3757. name="{{ inputId }}"
  3758. data-customize-setting-key-link="default"
  3759. {{{ describedByAttr }}}
  3760. >
  3761. <label for="{{ inputId + '-' + value }}">{{ text }}</label>
  3762. </span>
  3763. <# } ); #>
  3764. <#
  3765. break;
  3766. default:
  3767. #>
  3768. <# if ( data.label ) { #>
  3769. <label for="{{ inputId }}" class="customize-control-title">
  3770. {{ data.label }}
  3771. </label>
  3772. <# } #>
  3773. <# if ( data.description ) { #>
  3774. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3775. <# } #>
  3776. <#
  3777. var inputAttrs = {
  3778. id: inputId,
  3779. 'data-customize-setting-key-link': 'default'
  3780. };
  3781. if ( 'textarea' === data.type ) {
  3782. inputAttrs.rows = '5';
  3783. } else if ( 'button' === data.type ) {
  3784. inputAttrs['class'] = 'button button-secondary';
  3785. inputAttrs.type = 'button';
  3786. } else {
  3787. inputAttrs.type = data.type;
  3788. }
  3789. if ( data.description ) {
  3790. inputAttrs['aria-describedby'] = descriptionId;
  3791. }
  3792. _.extend( inputAttrs, data.input_attrs );
  3793. #>
  3794. <# if ( 'button' === data.type ) { #>
  3795. <button
  3796. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3797. {{{ key }}}="{{ value }}"
  3798. <# } ); #>
  3799. >{{ inputAttrs.value }}</button>
  3800. <# } else if ( 'textarea' === data.type ) { #>
  3801. <textarea
  3802. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3803. {{{ key }}}="{{ value }}"
  3804. <# }); #>
  3805. >{{ inputAttrs.value }}</textarea>
  3806. <# } else if ( 'select' === data.type ) { #>
  3807. <# delete inputAttrs.type; #>
  3808. <select
  3809. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3810. {{{ key }}}="{{ value }}"
  3811. <# }); #>
  3812. >
  3813. <# _.each( data.choices, function( val, key ) { #>
  3814. <#
  3815. var value, text;
  3816. if ( _.isObject( val ) ) {
  3817. value = val.value;
  3818. text = val.text;
  3819. } else {
  3820. value = key;
  3821. text = val;
  3822. }
  3823. #>
  3824. <option value="{{ value }}">{{ text }}</option>
  3825. <# } ); #>
  3826. </select>
  3827. <# } else { #>
  3828. <input
  3829. <# _.each( _.extend( inputAttrs ), function( value, key ) { #>
  3830. {{{ key }}}="{{ value }}"
  3831. <# }); #>
  3832. >
  3833. <# } #>
  3834. <# } #>
  3835. </script>
  3836. <script type="text/html" id="tmpl-customize-notification">
  3837. <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 }}">
  3838. <div class="notification-message">{{{ data.message || data.code }}}</div>
  3839. <# if ( data.dismissible ) { #>
  3840. <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php _e( 'Dismiss' ); ?></span></button>
  3841. <# } #>
  3842. </li>
  3843. </script>
  3844. <script type="text/html" id="tmpl-customize-changeset-locked-notification">
  3845. <li class="notice notice-{{ data.type || 'info' }} {{ data.containerClasses || '' }}" data-code="{{ data.code }}" data-type="{{ data.type }}">
  3846. <div class="notification-message customize-changeset-locked-message">
  3847. <img class="customize-changeset-locked-avatar" src="{{ data.lockUser.avatar }}" alt="{{ data.lockUser.name }}" />
  3848. <p class="currently-editing">
  3849. <# if ( data.message ) { #>
  3850. {{{ data.message }}}
  3851. <# } else if ( data.allowOverride ) { #>
  3852. <?php
  3853. echo esc_html( sprintf( $l10n['locked_allow_override'], '{{ data.lockUser.name }}' ) );
  3854. ?>
  3855. <# } else { #>
  3856. <?php
  3857. echo esc_html( sprintf( $l10n['locked'], '{{ data.lockUser.name }}' ) );
  3858. ?>
  3859. <# } #>
  3860. </p>
  3861. <p class="notice notice-error notice-alt" hidden></p>
  3862. <p class="action-buttons">
  3863. <# if ( data.returnUrl !== data.previewUrl ) { #>
  3864. <a class="button customize-notice-go-back-button" href="{{ data.returnUrl }}"><?php _e( 'Go back' ); ?></a>
  3865. <# } #>
  3866. <a class="button customize-notice-preview-button" href="{{ data.frontendPreviewUrl }}"><?php _e( 'Preview' ); ?></a>
  3867. <# if ( data.allowOverride ) { #>
  3868. <button class="button button-primary wp-tab-last customize-notice-take-over-button"><?php _e( 'Take over' ); ?></button>
  3869. <# } #>
  3870. </p>
  3871. </div>
  3872. </li>
  3873. </script>
  3874. <script type="text/html" id="tmpl-customize-code-editor-lint-error-notification">
  3875. <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 }}">
  3876. <div class="notification-message">{{{ data.message || data.code }}}</div>
  3877. <p>
  3878. <# var elementId = 'el-' + String( Math.random() ); #>
  3879. <input id="{{ elementId }}" type="checkbox">
  3880. <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label>
  3881. </p>
  3882. </li>
  3883. </script>
  3884. <?php
  3885. /* The following template is obsolete in core but retained for plugins. */
  3886. ?>
  3887. <script type="text/html" id="tmpl-customize-control-notifications">
  3888. <ul>
  3889. <# _.each( data.notifications, function( notification ) { #>
  3890. <li class="notice notice-{{ notification.type || 'info' }} {{ data.altNotice ? 'notice-alt' : '' }}" data-code="{{ notification.code }}" data-type="{{ notification.type }}">{{{ notification.message || notification.code }}}</li>
  3891. <# } ); #>
  3892. </ul>
  3893. </script>
  3894. <script type="text/html" id="tmpl-customize-preview-link-control" >
  3895. <# var elementPrefix = _.uniqueId( 'el' ) + '-' #>
  3896. <p class="customize-control-title">
  3897. <?php esc_html_e( 'Share Preview Link' ); ?>
  3898. </p>
  3899. <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>
  3900. <div class="customize-control-notifications-container"></div>
  3901. <div class="preview-link-wrapper">
  3902. <label for="{{ elementPrefix }}customize-preview-link-input" class="screen-reader-text"><?php esc_html_e( 'Preview Link' ); ?></label>
  3903. <a href="" target="">
  3904. <span class="preview-control-element" data-component="url"></span>
  3905. <span class="screen-reader-text"><?php _e( '(opens in a new tab)' ); ?></span>
  3906. </a>
  3907. <input id="{{ elementPrefix }}customize-preview-link-input" readonly tabindex="-1" class="preview-control-element" data-component="input">
  3908. <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>
  3909. </div>
  3910. </script>
  3911. <script type="text/html" id="tmpl-customize-selected-changeset-status-control">
  3912. <# var inputId = _.uniqueId( 'customize-selected-changeset-status-control-input-' ); #>
  3913. <# var descriptionId = _.uniqueId( 'customize-selected-changeset-status-control-description-' ); #>
  3914. <# if ( data.label ) { #>
  3915. <label for="{{ inputId }}" class="customize-control-title">{{ data.label }}</label>
  3916. <# } #>
  3917. <# if ( data.description ) { #>
  3918. <span id="{{ descriptionId }}" class="description customize-control-description">{{{ data.description }}}</span>
  3919. <# } #>
  3920. <# _.each( data.choices, function( choice ) { #>
  3921. <# var choiceId = inputId + '-' + choice.status; #>
  3922. <span class="customize-inside-control-row">
  3923. <input id="{{ choiceId }}" type="radio" value="{{ choice.status }}" name="{{ inputId }}" data-customize-setting-key-link="default">
  3924. <label for="{{ choiceId }}">{{ choice.label }}</label>
  3925. </span>
  3926. <# } ); #>
  3927. </script>
  3928. <?php
  3929. }
  3930. /**
  3931. * Helper function to compare two objects by priority, ensuring sort stability via instance_number.
  3932. *
  3933. * @since 3.4.0
  3934. * @deprecated 4.7.0 Use wp_list_sort()
  3935. *
  3936. * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $a Object A.
  3937. * @param WP_Customize_Panel|WP_Customize_Section|WP_Customize_Control $b Object B.
  3938. * @return int
  3939. */
  3940. protected function _cmp_priority( $a, $b ) {
  3941. _deprecated_function( __METHOD__, '4.7.0', 'wp_list_sort' );
  3942. if ( $a->priority === $b->priority ) {
  3943. return $a->instance_number - $b->instance_number;
  3944. } else {
  3945. return $a->priority - $b->priority;
  3946. }
  3947. }
  3948. /**
  3949. * Prepare panels, sections, and controls.
  3950. *
  3951. * For each, check if required related components exist,
  3952. * whether the user has the necessary capabilities,
  3953. * and sort by priority.
  3954. *
  3955. * @since 3.4.0
  3956. */
  3957. public function prepare_controls() {
  3958. $controls = array();
  3959. $this->controls = wp_list_sort(
  3960. $this->controls,
  3961. array(
  3962. 'priority' => 'ASC',
  3963. 'instance_number' => 'ASC',
  3964. ),
  3965. 'ASC',
  3966. true
  3967. );
  3968. foreach ( $this->controls as $id => $control ) {
  3969. if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) {
  3970. continue;
  3971. }
  3972. $this->sections[ $control->section ]->controls[] = $control;
  3973. $controls[ $id ] = $control;
  3974. }
  3975. $this->controls = $controls;
  3976. // Prepare sections.
  3977. $this->sections = wp_list_sort(
  3978. $this->sections,
  3979. array(
  3980. 'priority' => 'ASC',
  3981. 'instance_number' => 'ASC',
  3982. ),
  3983. 'ASC',
  3984. true
  3985. );
  3986. $sections = array();
  3987. foreach ( $this->sections as $section ) {
  3988. if ( ! $section->check_capabilities() ) {
  3989. continue;
  3990. }
  3991. $section->controls = wp_list_sort(
  3992. $section->controls,
  3993. array(
  3994. 'priority' => 'ASC',
  3995. 'instance_number' => 'ASC',
  3996. )
  3997. );
  3998. if ( ! $section->panel ) {
  3999. // Top-level section.
  4000. $sections[ $section->id ] = $section;
  4001. } else {
  4002. // This section belongs to a panel.
  4003. if ( isset( $this->panels [ $section->panel ] ) ) {
  4004. $this->panels[ $section->panel ]->sections[ $section->id ] = $section;
  4005. }
  4006. }
  4007. }
  4008. $this->sections = $sections;
  4009. // Prepare panels.
  4010. $this->panels = wp_list_sort(
  4011. $this->panels,
  4012. array(
  4013. 'priority' => 'ASC',
  4014. 'instance_number' => 'ASC',
  4015. ),
  4016. 'ASC',
  4017. true
  4018. );
  4019. $panels = array();
  4020. foreach ( $this->panels as $panel ) {
  4021. if ( ! $panel->check_capabilities() ) {
  4022. continue;
  4023. }
  4024. $panel->sections = wp_list_sort(
  4025. $panel->sections,
  4026. array(
  4027. 'priority' => 'ASC',
  4028. 'instance_number' => 'ASC',
  4029. ),
  4030. 'ASC',
  4031. true
  4032. );
  4033. $panels[ $panel->id ] = $panel;
  4034. }
  4035. $this->panels = $panels;
  4036. // Sort panels and top-level sections together.
  4037. $this->containers = array_merge( $this->panels, $this->sections );
  4038. $this->containers = wp_list_sort(
  4039. $this->containers,
  4040. array(
  4041. 'priority' => 'ASC',
  4042. 'instance_number' => 'ASC',
  4043. ),
  4044. 'ASC',
  4045. true
  4046. );
  4047. }
  4048. /**
  4049. * Enqueue scripts for customize controls.
  4050. *
  4051. * @since 3.4.0
  4052. */
  4053. public function enqueue_control_scripts() {
  4054. foreach ( $this->controls as $control ) {
  4055. $control->enqueue();
  4056. }
  4057. if ( ! is_multisite() && ( current_user_can( 'install_themes' ) || current_user_can( 'update_themes' ) || current_user_can( 'delete_themes' ) ) ) {
  4058. wp_enqueue_script( 'updates' );
  4059. wp_localize_script(
  4060. 'updates',
  4061. '_wpUpdatesItemCounts',
  4062. array(
  4063. 'totals' => wp_get_update_data(),
  4064. )
  4065. );
  4066. }
  4067. }
  4068. /**
  4069. * Determine whether the user agent is iOS.
  4070. *
  4071. * @since 4.4.0
  4072. *
  4073. * @return bool Whether the user agent is iOS.
  4074. */
  4075. public function is_ios() {
  4076. return wp_is_mobile() && preg_match( '/iPad|iPod|iPhone/', $_SERVER['HTTP_USER_AGENT'] );
  4077. }
  4078. /**
  4079. * Get the template string for the Customizer pane document title.
  4080. *
  4081. * @since 4.4.0
  4082. *
  4083. * @return string The template string for the document title.
  4084. */
  4085. public function get_document_title_template() {
  4086. if ( $this->is_theme_active() ) {
  4087. /* translators: %s: Document title from the preview. */
  4088. $document_title_tmpl = __( 'Customize: %s' );
  4089. } else {
  4090. /* translators: %s: Document title from the preview. */
  4091. $document_title_tmpl = __( 'Live Preview: %s' );
  4092. }
  4093. $document_title_tmpl = html_entity_decode( $document_title_tmpl, ENT_QUOTES, 'UTF-8' ); // Because exported to JS and assigned to document.title.
  4094. return $document_title_tmpl;
  4095. }
  4096. /**
  4097. * Set the initial URL to be previewed.
  4098. *
  4099. * URL is validated.
  4100. *
  4101. * @since 4.4.0
  4102. *
  4103. * @param string $preview_url URL to be previewed.
  4104. */
  4105. public function set_preview_url( $preview_url ) {
  4106. $preview_url = esc_url_raw( $preview_url );
  4107. $this->preview_url = wp_validate_redirect( $preview_url, home_url( '/' ) );
  4108. }
  4109. /**
  4110. * Get the initial URL to be previewed.
  4111. *
  4112. * @since 4.4.0
  4113. *
  4114. * @return string URL being previewed.
  4115. */
  4116. public function get_preview_url() {
  4117. if ( empty( $this->preview_url ) ) {
  4118. $preview_url = home_url( '/' );
  4119. } else {
  4120. $preview_url = $this->preview_url;
  4121. }
  4122. return $preview_url;
  4123. }
  4124. /**
  4125. * Determines whether the admin and the frontend are on different domains.
  4126. *
  4127. * @since 4.7.0
  4128. *
  4129. * @return bool Whether cross-domain.
  4130. */
  4131. public function is_cross_domain() {
  4132. $admin_origin = wp_parse_url( admin_url() );
  4133. $home_origin = wp_parse_url( home_url() );
  4134. $cross_domain = ( strtolower( $admin_origin['host'] ) !== strtolower( $home_origin['host'] ) );
  4135. return $cross_domain;
  4136. }
  4137. /**
  4138. * Get URLs allowed to be previewed.
  4139. *
  4140. * If the front end and the admin are served from the same domain, load the
  4141. * preview over ssl if the Customizer is being loaded over ssl. This avoids
  4142. * insecure content warnings. This is not attempted if the admin and front end
  4143. * are on different domains to avoid the case where the front end doesn't have
  4144. * ssl certs. Domain mapping plugins can allow other urls in these conditions
  4145. * using the customize_allowed_urls filter.
  4146. *
  4147. * @since 4.7.0
  4148. *
  4149. * @return array Allowed URLs.
  4150. */
  4151. public function get_allowed_urls() {
  4152. $allowed_urls = array( home_url( '/' ) );
  4153. if ( is_ssl() && ! $this->is_cross_domain() ) {
  4154. $allowed_urls[] = home_url( '/', 'https' );
  4155. }
  4156. /**
  4157. * Filters the list of URLs allowed to be clicked and followed in the Customizer preview.
  4158. *
  4159. * @since 3.4.0
  4160. *
  4161. * @param string[] $allowed_urls An array of allowed URLs.
  4162. */
  4163. $allowed_urls = array_unique( apply_filters( 'customize_allowed_urls', $allowed_urls ) );
  4164. return $allowed_urls;
  4165. }
  4166. /**
  4167. * Get messenger channel.
  4168. *
  4169. * @since 4.7.0
  4170. *
  4171. * @return string Messenger channel.
  4172. */
  4173. public function get_messenger_channel() {
  4174. return $this->messenger_channel;
  4175. }
  4176. /**
  4177. * Set URL to link the user to when closing the Customizer.
  4178. *
  4179. * URL is validated.
  4180. *
  4181. * @since 4.4.0
  4182. *
  4183. * @param string $return_url URL for return link.
  4184. */
  4185. public function set_return_url( $return_url ) {
  4186. $return_url = esc_url_raw( $return_url );
  4187. $return_url = remove_query_arg( wp_removable_query_args(), $return_url );
  4188. $return_url = wp_validate_redirect( $return_url );
  4189. $this->return_url = $return_url;
  4190. }
  4191. /**
  4192. * Get URL to link the user to when closing the Customizer.
  4193. *
  4194. * @since 4.4.0
  4195. *
  4196. * @global array $_registered_pages
  4197. *
  4198. * @return string URL for link to close Customizer.
  4199. */
  4200. public function get_return_url() {
  4201. global $_registered_pages;
  4202. $referer = wp_get_referer();
  4203. $excluded_referer_basenames = array( 'customize.php', 'wp-login.php' );
  4204. if ( $this->return_url ) {
  4205. $return_url = $this->return_url;
  4206. } elseif ( $referer && ! in_array( wp_basename( parse_url( $referer, PHP_URL_PATH ) ), $excluded_referer_basenames, true ) ) {
  4207. $return_url = $referer;
  4208. } elseif ( $this->preview_url ) {
  4209. $return_url = $this->preview_url;
  4210. } else {
  4211. $return_url = home_url( '/' );
  4212. }
  4213. $return_url_basename = wp_basename( parse_url( $this->return_url, PHP_URL_PATH ) );
  4214. $return_url_query = parse_url( $this->return_url, PHP_URL_QUERY );
  4215. if ( 'themes.php' === $return_url_basename && $return_url_query ) {
  4216. parse_str( $return_url_query, $query_vars );
  4217. /*
  4218. * If the return URL is a page added by a theme to the Appearance menu via add_submenu_page(),
  4219. * verify that belongs to the active theme, otherwise fall back to the Themes screen.
  4220. */
  4221. if ( isset( $query_vars['page'] ) && ! isset( $_registered_pages[ "appearance_page_{$query_vars['page']}" ] ) ) {
  4222. $return_url = admin_url( 'themes.php' );
  4223. }
  4224. }
  4225. return $return_url;
  4226. }
  4227. /**
  4228. * Set the autofocused constructs.
  4229. *
  4230. * @since 4.4.0
  4231. *
  4232. * @param array $autofocus {
  4233. * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
  4234. *
  4235. * @type string $control ID for control to be autofocused.
  4236. * @type string $section ID for section to be autofocused.
  4237. * @type string $panel ID for panel to be autofocused.
  4238. * }
  4239. */
  4240. public function set_autofocus( $autofocus ) {
  4241. $this->autofocus = array_filter( wp_array_slice_assoc( $autofocus, array( 'panel', 'section', 'control' ) ), 'is_string' );
  4242. }
  4243. /**
  4244. * Get the autofocused constructs.
  4245. *
  4246. * @since 4.4.0
  4247. *
  4248. * @return array {
  4249. * Mapping of 'panel', 'section', 'control' to the ID which should be autofocused.
  4250. *
  4251. * @type string $control ID for control to be autofocused.
  4252. * @type string $section ID for section to be autofocused.
  4253. * @type string $panel ID for panel to be autofocused.
  4254. * }
  4255. */
  4256. public function get_autofocus() {
  4257. return $this->autofocus;
  4258. }
  4259. /**
  4260. * Get nonces for the Customizer.
  4261. *
  4262. * @since 4.5.0
  4263. *
  4264. * @return array Nonces.
  4265. */
  4266. public function get_nonces() {
  4267. $nonces = array(
  4268. 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ),
  4269. 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ),
  4270. 'switch_themes' => wp_create_nonce( 'switch_themes' ),
  4271. 'dismiss_autosave_or_lock' => wp_create_nonce( 'customize_dismiss_autosave_or_lock' ),
  4272. 'override_lock' => wp_create_nonce( 'customize_override_changeset_lock' ),
  4273. 'trash' => wp_create_nonce( 'trash_customize_changeset' ),
  4274. );
  4275. /**
  4276. * Filters nonces for Customizer.
  4277. *
  4278. * @since 4.2.0
  4279. *
  4280. * @param string[] $nonces Array of refreshed nonces for save and
  4281. * preview actions.
  4282. * @param WP_Customize_Manager $this WP_Customize_Manager instance.
  4283. */
  4284. $nonces = apply_filters( 'customize_refresh_nonces', $nonces, $this );
  4285. return $nonces;
  4286. }
  4287. /**
  4288. * Print JavaScript settings for parent window.
  4289. *
  4290. * @since 4.4.0
  4291. */
  4292. public function customize_pane_settings() {
  4293. $login_url = add_query_arg(
  4294. array(
  4295. 'interim-login' => 1,
  4296. 'customize-login' => 1,
  4297. ),
  4298. wp_login_url()
  4299. );
  4300. // Ensure dirty flags are set for modified settings.
  4301. foreach ( array_keys( $this->unsanitized_post_values() ) as $setting_id ) {
  4302. $setting = $this->get_setting( $setting_id );
  4303. if ( $setting ) {
  4304. $setting->dirty = true;
  4305. }
  4306. }
  4307. $autosave_revision_post = null;
  4308. $autosave_autodraft_post = null;
  4309. $changeset_post_id = $this->changeset_post_id();
  4310. if ( ! $this->saved_starter_content_changeset && ! $this->autosaved() ) {
  4311. if ( $changeset_post_id ) {
  4312. if ( is_user_logged_in() ) {
  4313. $autosave_revision_post = wp_get_post_autosave( $changeset_post_id, get_current_user_id() );
  4314. }
  4315. } else {
  4316. $autosave_autodraft_posts = $this->get_changeset_posts(
  4317. array(
  4318. 'posts_per_page' => 1,
  4319. 'post_status' => 'auto-draft',
  4320. 'exclude_restore_dismissed' => true,
  4321. )
  4322. );
  4323. if ( ! empty( $autosave_autodraft_posts ) ) {
  4324. $autosave_autodraft_post = array_shift( $autosave_autodraft_posts );
  4325. }
  4326. }
  4327. }
  4328. $current_user_can_publish = current_user_can( get_post_type_object( 'customize_changeset' )->cap->publish_posts );
  4329. // @todo Include all of the status labels here from script-loader.php, and then allow it to be filtered.
  4330. $status_choices = array();
  4331. if ( $current_user_can_publish ) {
  4332. $status_choices[] = array(
  4333. 'status' => 'publish',
  4334. 'label' => __( 'Publish' ),
  4335. );
  4336. }
  4337. $status_choices[] = array(
  4338. 'status' => 'draft',
  4339. 'label' => __( 'Save Draft' ),
  4340. );
  4341. if ( $current_user_can_publish ) {
  4342. $status_choices[] = array(
  4343. 'status' => 'future',
  4344. 'label' => _x( 'Schedule', 'customizer changeset action/button label' ),
  4345. );
  4346. }
  4347. // Prepare Customizer settings to pass to JavaScript.
  4348. $changeset_post = null;
  4349. if ( $changeset_post_id ) {
  4350. $changeset_post = get_post( $changeset_post_id );
  4351. }
  4352. // Determine initial date to be at present or future, not past.
  4353. $current_time = current_time( 'mysql', false );
  4354. $initial_date = $current_time;
  4355. if ( $changeset_post ) {
  4356. $initial_date = get_the_time( 'Y-m-d H:i:s', $changeset_post->ID );
  4357. if ( $initial_date < $current_time ) {
  4358. $initial_date = $current_time;
  4359. }
  4360. }
  4361. $lock_user_id = false;
  4362. if ( $this->changeset_post_id() ) {
  4363. $lock_user_id = wp_check_post_lock( $this->changeset_post_id() );
  4364. }
  4365. $settings = array(
  4366. 'changeset' => array(
  4367. 'uuid' => $this->changeset_uuid(),
  4368. 'branching' => $this->branching(),
  4369. 'autosaved' => $this->autosaved(),
  4370. 'hasAutosaveRevision' => ! empty( $autosave_revision_post ),
  4371. 'latestAutoDraftUuid' => $autosave_autodraft_post ? $autosave_autodraft_post->post_name : null,
  4372. 'status' => $changeset_post ? $changeset_post->post_status : '',
  4373. 'currentUserCanPublish' => $current_user_can_publish,
  4374. 'publishDate' => $initial_date,
  4375. 'statusChoices' => $status_choices,
  4376. 'lockUser' => $lock_user_id ? $this->get_lock_user_data( $lock_user_id ) : null,
  4377. ),
  4378. 'initialServerDate' => $current_time,
  4379. 'dateFormat' => get_option( 'date_format' ),
  4380. 'timeFormat' => get_option( 'time_format' ),
  4381. 'initialServerTimestamp' => floor( microtime( true ) * 1000 ),
  4382. 'initialClientTimestamp' => -1, // To be set with JS below.
  4383. 'timeouts' => array(
  4384. 'windowRefresh' => 250,
  4385. 'changesetAutoSave' => AUTOSAVE_INTERVAL * 1000,
  4386. 'keepAliveCheck' => 2500,
  4387. 'reflowPaneContents' => 100,
  4388. 'previewFrameSensitivity' => 2000,
  4389. ),
  4390. 'theme' => array(
  4391. 'stylesheet' => $this->get_stylesheet(),
  4392. 'active' => $this->is_theme_active(),
  4393. '_canInstall' => current_user_can( 'install_themes' ),
  4394. ),
  4395. 'url' => array(
  4396. 'preview' => esc_url_raw( $this->get_preview_url() ),
  4397. 'return' => esc_url_raw( $this->get_return_url() ),
  4398. 'parent' => esc_url_raw( admin_url() ),
  4399. 'activated' => esc_url_raw( home_url( '/' ) ),
  4400. 'ajax' => esc_url_raw( admin_url( 'admin-ajax.php', 'relative' ) ),
  4401. 'allowed' => array_map( 'esc_url_raw', $this->get_allowed_urls() ),
  4402. 'isCrossDomain' => $this->is_cross_domain(),
  4403. 'home' => esc_url_raw( home_url( '/' ) ),
  4404. 'login' => esc_url_raw( $login_url ),
  4405. ),
  4406. 'browser' => array(
  4407. 'mobile' => wp_is_mobile(),
  4408. 'ios' => $this->is_ios(),
  4409. ),
  4410. 'panels' => array(),
  4411. 'sections' => array(),
  4412. 'nonce' => $this->get_nonces(),
  4413. 'autofocus' => $this->get_autofocus(),
  4414. 'documentTitleTmpl' => $this->get_document_title_template(),
  4415. 'previewableDevices' => $this->get_previewable_devices(),
  4416. 'l10n' => array(
  4417. 'confirmDeleteTheme' => __( 'Are you sure you want to delete this theme?' ),
  4418. /* translators: %d: Number of theme search results, which cannot currently consider singular vs. plural forms. */
  4419. 'themeSearchResults' => __( '%d themes found' ),
  4420. /* translators: %d: Number of themes being displayed, which cannot currently consider singular vs. plural forms. */
  4421. 'announceThemeCount' => __( 'Displaying %d themes' ),
  4422. /* translators: %s: Theme name. */
  4423. 'announceThemeDetails' => __( 'Showing details for theme: %s' ),
  4424. ),
  4425. );
  4426. // Temporarily disable installation in Customizer. See #42184.
  4427. $filesystem_method = get_filesystem_method();
  4428. ob_start();
  4429. $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
  4430. ob_end_clean();
  4431. if ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored ) {
  4432. $settings['theme']['_filesystemCredentialsNeeded'] = true;
  4433. }
  4434. // Prepare Customize Section objects to pass to JavaScript.
  4435. foreach ( $this->sections() as $id => $section ) {
  4436. if ( $section->check_capabilities() ) {
  4437. $settings['sections'][ $id ] = $section->json();
  4438. }
  4439. }
  4440. // Prepare Customize Panel objects to pass to JavaScript.
  4441. foreach ( $this->panels() as $panel_id => $panel ) {
  4442. if ( $panel->check_capabilities() ) {
  4443. $settings['panels'][ $panel_id ] = $panel->json();
  4444. foreach ( $panel->sections as $section_id => $section ) {
  4445. if ( $section->check_capabilities() ) {
  4446. $settings['sections'][ $section_id ] = $section->json();
  4447. }
  4448. }
  4449. }
  4450. }
  4451. ?>
  4452. <script type="text/javascript">
  4453. var _wpCustomizeSettings = <?php echo wp_json_encode( $settings ); ?>;
  4454. _wpCustomizeSettings.initialClientTimestamp = _.now();
  4455. _wpCustomizeSettings.controls = {};
  4456. _wpCustomizeSettings.settings = {};
  4457. <?php
  4458. // Serialize settings one by one to improve memory usage.
  4459. echo "(function ( s ){\n";
  4460. foreach ( $this->settings() as $setting ) {
  4461. if ( $setting->check_capabilities() ) {
  4462. printf(
  4463. "s[%s] = %s;\n",
  4464. wp_json_encode( $setting->id ),
  4465. wp_json_encode( $setting->json() )
  4466. );
  4467. }
  4468. }
  4469. echo "})( _wpCustomizeSettings.settings );\n";
  4470. // Serialize controls one by one to improve memory usage.
  4471. echo "(function ( c ){\n";
  4472. foreach ( $this->controls() as $control ) {
  4473. if ( $control->check_capabilities() ) {
  4474. printf(
  4475. "c[%s] = %s;\n",
  4476. wp_json_encode( $control->id ),
  4477. wp_json_encode( $control->json() )
  4478. );
  4479. }
  4480. }
  4481. echo "})( _wpCustomizeSettings.controls );\n";
  4482. ?>
  4483. </script>
  4484. <?php
  4485. }
  4486. /**
  4487. * Returns a list of devices to allow previewing.
  4488. *
  4489. * @since 4.5.0
  4490. *
  4491. * @return array List of devices with labels and default setting.
  4492. */
  4493. public function get_previewable_devices() {
  4494. $devices = array(
  4495. 'desktop' => array(
  4496. 'label' => __( 'Enter desktop preview mode' ),
  4497. 'default' => true,
  4498. ),
  4499. 'tablet' => array(
  4500. 'label' => __( 'Enter tablet preview mode' ),
  4501. ),
  4502. 'mobile' => array(
  4503. 'label' => __( 'Enter mobile preview mode' ),
  4504. ),
  4505. );
  4506. /**
  4507. * Filters the available devices to allow previewing in the Customizer.
  4508. *
  4509. * @since 4.5.0
  4510. *
  4511. * @see WP_Customize_Manager::get_previewable_devices()
  4512. *
  4513. * @param array $devices List of devices with labels and default setting.
  4514. */
  4515. $devices = apply_filters( 'customize_previewable_devices', $devices );
  4516. return $devices;
  4517. }
  4518. /**
  4519. * Register some default controls.
  4520. *
  4521. * @since 3.4.0
  4522. */
  4523. public function register_controls() {
  4524. /* Themes (controls are loaded via ajax) */
  4525. $this->add_panel(
  4526. new WP_Customize_Themes_Panel(
  4527. $this,
  4528. 'themes',
  4529. array(
  4530. 'title' => $this->theme()->display( 'Name' ),
  4531. 'description' => (
  4532. '<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>' .
  4533. '<p>' . __( 'While previewing a new theme, you can continue to tailor things like widgets and menus, and explore theme-specific options.' ) . '</p>'
  4534. ),
  4535. 'capability' => 'switch_themes',
  4536. 'priority' => 0,
  4537. )
  4538. )
  4539. );
  4540. $this->add_section(
  4541. new WP_Customize_Themes_Section(
  4542. $this,
  4543. 'installed_themes',
  4544. array(
  4545. 'title' => __( 'Installed themes' ),
  4546. 'action' => 'installed',
  4547. 'capability' => 'switch_themes',
  4548. 'panel' => 'themes',
  4549. 'priority' => 0,
  4550. )
  4551. )
  4552. );
  4553. if ( ! is_multisite() ) {
  4554. $this->add_section(
  4555. new WP_Customize_Themes_Section(
  4556. $this,
  4557. 'wporg_themes',
  4558. array(
  4559. 'title' => __( 'WordPress.org themes' ),
  4560. 'action' => 'wporg',
  4561. 'filter_type' => 'remote',
  4562. 'capability' => 'install_themes',
  4563. 'panel' => 'themes',
  4564. 'priority' => 5,
  4565. )
  4566. )
  4567. );
  4568. }
  4569. // Themes Setting (unused - the theme is considerably more fundamental to the Customizer experience).
  4570. $this->add_setting(
  4571. new WP_Customize_Filter_Setting(
  4572. $this,
  4573. 'active_theme',
  4574. array(
  4575. 'capability' => 'switch_themes',
  4576. )
  4577. )
  4578. );
  4579. /* Site Identity */
  4580. $this->add_section(
  4581. 'title_tagline',
  4582. array(
  4583. 'title' => __( 'Site Identity' ),
  4584. 'priority' => 20,
  4585. )
  4586. );
  4587. $this->add_setting(
  4588. 'blogname',
  4589. array(
  4590. 'default' => get_option( 'blogname' ),
  4591. 'type' => 'option',
  4592. 'capability' => 'manage_options',
  4593. )
  4594. );
  4595. $this->add_control(
  4596. 'blogname',
  4597. array(
  4598. 'label' => __( 'Site Title' ),
  4599. 'section' => 'title_tagline',
  4600. )
  4601. );
  4602. $this->add_setting(
  4603. 'blogdescription',
  4604. array(
  4605. 'default' => get_option( 'blogdescription' ),
  4606. 'type' => 'option',
  4607. 'capability' => 'manage_options',
  4608. )
  4609. );
  4610. $this->add_control(
  4611. 'blogdescription',
  4612. array(
  4613. 'label' => __( 'Tagline' ),
  4614. 'section' => 'title_tagline',
  4615. )
  4616. );
  4617. // Add a setting to hide header text if the theme doesn't support custom headers.
  4618. if ( ! current_theme_supports( 'custom-header', 'header-text' ) ) {
  4619. $this->add_setting(
  4620. 'header_text',
  4621. array(
  4622. 'theme_supports' => array( 'custom-logo', 'header-text' ),
  4623. 'default' => 1,
  4624. 'sanitize_callback' => 'absint',
  4625. )
  4626. );
  4627. $this->add_control(
  4628. 'header_text',
  4629. array(
  4630. 'label' => __( 'Display Site Title and Tagline' ),
  4631. 'section' => 'title_tagline',
  4632. 'settings' => 'header_text',
  4633. 'type' => 'checkbox',
  4634. )
  4635. );
  4636. }
  4637. $this->add_setting(
  4638. 'site_icon',
  4639. array(
  4640. 'type' => 'option',
  4641. 'capability' => 'manage_options',
  4642. 'transport' => 'postMessage', // Previewed with JS in the Customizer controls window.
  4643. )
  4644. );
  4645. $this->add_control(
  4646. new WP_Customize_Site_Icon_Control(
  4647. $this,
  4648. 'site_icon',
  4649. array(
  4650. 'label' => __( 'Site Icon' ),
  4651. 'description' => sprintf(
  4652. '<p>' . __( 'Site Icons are what you see in browser tabs, bookmark bars, and within the WordPress mobile apps. Upload one here!' ) . '</p>' .
  4653. /* translators: %s: Site icon size in pixels. */
  4654. '<p>' . __( 'Site Icons should be square and at least %s pixels.' ) . '</p>',
  4655. '<strong>512 &times; 512</strong>'
  4656. ),
  4657. 'section' => 'title_tagline',
  4658. 'priority' => 60,
  4659. 'height' => 512,
  4660. 'width' => 512,
  4661. )
  4662. )
  4663. );
  4664. $this->add_setting(
  4665. 'custom_logo',
  4666. array(
  4667. 'theme_supports' => array( 'custom-logo' ),
  4668. 'transport' => 'postMessage',
  4669. )
  4670. );
  4671. $custom_logo_args = get_theme_support( 'custom-logo' );
  4672. $this->add_control(
  4673. new WP_Customize_Cropped_Image_Control(
  4674. $this,
  4675. 'custom_logo',
  4676. array(
  4677. 'label' => __( 'Logo' ),
  4678. 'section' => 'title_tagline',
  4679. 'priority' => 8,
  4680. 'height' => isset( $custom_logo_args[0]['height'] ) ? $custom_logo_args[0]['height'] : null,
  4681. 'width' => isset( $custom_logo_args[0]['width'] ) ? $custom_logo_args[0]['width'] : null,
  4682. 'flex_height' => isset( $custom_logo_args[0]['flex-height'] ) ? $custom_logo_args[0]['flex-height'] : null,
  4683. 'flex_width' => isset( $custom_logo_args[0]['flex-width'] ) ? $custom_logo_args[0]['flex-width'] : null,
  4684. 'button_labels' => array(
  4685. 'select' => __( 'Select logo' ),
  4686. 'change' => __( 'Change logo' ),
  4687. 'remove' => __( 'Remove' ),
  4688. 'default' => __( 'Default' ),
  4689. 'placeholder' => __( 'No logo selected' ),
  4690. 'frame_title' => __( 'Select logo' ),
  4691. 'frame_button' => __( 'Choose logo' ),
  4692. ),
  4693. )
  4694. )
  4695. );
  4696. $this->selective_refresh->add_partial(
  4697. 'custom_logo',
  4698. array(
  4699. 'settings' => array( 'custom_logo' ),
  4700. 'selector' => '.custom-logo-link',
  4701. 'render_callback' => array( $this, '_render_custom_logo_partial' ),
  4702. 'container_inclusive' => true,
  4703. )
  4704. );
  4705. /* Colors */
  4706. $this->add_section(
  4707. 'colors',
  4708. array(
  4709. 'title' => __( 'Colors' ),
  4710. 'priority' => 40,
  4711. )
  4712. );
  4713. $this->add_setting(
  4714. 'header_textcolor',
  4715. array(
  4716. 'theme_supports' => array( 'custom-header', 'header-text' ),
  4717. 'default' => get_theme_support( 'custom-header', 'default-text-color' ),
  4718. 'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ),
  4719. 'sanitize_js_callback' => 'maybe_hash_hex_color',
  4720. )
  4721. );
  4722. // Input type: checkbox.
  4723. // With custom value.
  4724. $this->add_control(
  4725. 'display_header_text',
  4726. array(
  4727. 'settings' => 'header_textcolor',
  4728. 'label' => __( 'Display Site Title and Tagline' ),
  4729. 'section' => 'title_tagline',
  4730. 'type' => 'checkbox',
  4731. 'priority' => 40,
  4732. )
  4733. );
  4734. $this->add_control(
  4735. new WP_Customize_Color_Control(
  4736. $this,
  4737. 'header_textcolor',
  4738. array(
  4739. 'label' => __( 'Header Text Color' ),
  4740. 'section' => 'colors',
  4741. )
  4742. )
  4743. );
  4744. // Input type: color.
  4745. // With sanitize_callback.
  4746. $this->add_setting(
  4747. 'background_color',
  4748. array(
  4749. 'default' => get_theme_support( 'custom-background', 'default-color' ),
  4750. 'theme_supports' => 'custom-background',
  4751. 'sanitize_callback' => 'sanitize_hex_color_no_hash',
  4752. 'sanitize_js_callback' => 'maybe_hash_hex_color',
  4753. )
  4754. );
  4755. $this->add_control(
  4756. new WP_Customize_Color_Control(
  4757. $this,
  4758. 'background_color',
  4759. array(
  4760. 'label' => __( 'Background Color' ),
  4761. 'section' => 'colors',
  4762. )
  4763. )
  4764. );
  4765. /* Custom Header */
  4766. if ( current_theme_supports( 'custom-header', 'video' ) ) {
  4767. $title = __( 'Header Media' );
  4768. $description = '<p>' . __( 'If you add a video, the image will be used as a fallback while the video loads.' ) . '</p>';
  4769. $width = absint( get_theme_support( 'custom-header', 'width' ) );
  4770. $height = absint( get_theme_support( 'custom-header', 'height' ) );
  4771. if ( $width && $height ) {
  4772. $control_description = sprintf(
  4773. /* translators: 1: .mp4, 2: Header size in pixels. */
  4774. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends dimensions of %2$s pixels.' ),
  4775. '<code>.mp4</code>',
  4776. sprintf( '<strong>%s &times; %s</strong>', $width, $height )
  4777. );
  4778. } elseif ( $width ) {
  4779. $control_description = sprintf(
  4780. /* translators: 1: .mp4, 2: Header width in pixels. */
  4781. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a width of %2$s pixels.' ),
  4782. '<code>.mp4</code>',
  4783. sprintf( '<strong>%s</strong>', $width )
  4784. );
  4785. } else {
  4786. $control_description = sprintf(
  4787. /* translators: 1: .mp4, 2: Header height in pixels. */
  4788. __( 'Upload your video in %1$s format and minimize its file size for best results. Your theme recommends a height of %2$s pixels.' ),
  4789. '<code>.mp4</code>',
  4790. sprintf( '<strong>%s</strong>', $height )
  4791. );
  4792. }
  4793. } else {
  4794. $title = __( 'Header Image' );
  4795. $description = '';
  4796. $control_description = '';
  4797. }
  4798. $this->add_section(
  4799. 'header_image',
  4800. array(
  4801. 'title' => $title,
  4802. 'description' => $description,
  4803. 'theme_supports' => 'custom-header',
  4804. 'priority' => 60,
  4805. )
  4806. );
  4807. $this->add_setting(
  4808. 'header_video',
  4809. array(
  4810. 'theme_supports' => array( 'custom-header', 'video' ),
  4811. 'transport' => 'postMessage',
  4812. 'sanitize_callback' => 'absint',
  4813. 'validate_callback' => array( $this, '_validate_header_video' ),
  4814. )
  4815. );
  4816. $this->add_setting(
  4817. 'external_header_video',
  4818. array(
  4819. 'theme_supports' => array( 'custom-header', 'video' ),
  4820. 'transport' => 'postMessage',
  4821. 'sanitize_callback' => array( $this, '_sanitize_external_header_video' ),
  4822. 'validate_callback' => array( $this, '_validate_external_header_video' ),
  4823. )
  4824. );
  4825. $this->add_setting(
  4826. new WP_Customize_Filter_Setting(
  4827. $this,
  4828. 'header_image',
  4829. array(
  4830. 'default' => sprintf( get_theme_support( 'custom-header', 'default-image' ), get_template_directory_uri(), get_stylesheet_directory_uri() ),
  4831. 'theme_supports' => 'custom-header',
  4832. )
  4833. )
  4834. );
  4835. $this->add_setting(
  4836. new WP_Customize_Header_Image_Setting(
  4837. $this,
  4838. 'header_image_data',
  4839. array(
  4840. 'theme_supports' => 'custom-header',
  4841. )
  4842. )
  4843. );
  4844. /*
  4845. * Switch image settings to postMessage when video support is enabled since
  4846. * it entails that the_custom_header_markup() will be used, and thus selective
  4847. * refresh can be utilized.
  4848. */
  4849. if ( current_theme_supports( 'custom-header', 'video' ) ) {
  4850. $this->get_setting( 'header_image' )->transport = 'postMessage';
  4851. $this->get_setting( 'header_image_data' )->transport = 'postMessage';
  4852. }
  4853. $this->add_control(
  4854. new WP_Customize_Media_Control(
  4855. $this,
  4856. 'header_video',
  4857. array(
  4858. 'theme_supports' => array( 'custom-header', 'video' ),
  4859. 'label' => __( 'Header Video' ),
  4860. 'description' => $control_description,
  4861. 'section' => 'header_image',
  4862. 'mime_type' => 'video',
  4863. 'active_callback' => 'is_header_video_active',
  4864. )
  4865. )
  4866. );
  4867. $this->add_control(
  4868. 'external_header_video',
  4869. array(
  4870. 'theme_supports' => array( 'custom-header', 'video' ),
  4871. 'type' => 'url',
  4872. 'description' => __( 'Or, enter a YouTube URL:' ),
  4873. 'section' => 'header_image',
  4874. 'active_callback' => 'is_header_video_active',
  4875. )
  4876. );
  4877. $this->add_control( new WP_Customize_Header_Image_Control( $this ) );
  4878. $this->selective_refresh->add_partial(
  4879. 'custom_header',
  4880. array(
  4881. 'selector' => '#wp-custom-header',
  4882. 'render_callback' => 'the_custom_header_markup',
  4883. 'settings' => array( 'header_video', 'external_header_video', 'header_image' ), // The image is used as a video fallback here.
  4884. 'container_inclusive' => true,
  4885. )
  4886. );
  4887. /* Custom Background */
  4888. $this->add_section(
  4889. 'background_image',
  4890. array(
  4891. 'title' => __( 'Background Image' ),
  4892. 'theme_supports' => 'custom-background',
  4893. 'priority' => 80,
  4894. )
  4895. );
  4896. $this->add_setting(
  4897. 'background_image',
  4898. array(
  4899. 'default' => get_theme_support( 'custom-background', 'default-image' ),
  4900. 'theme_supports' => 'custom-background',
  4901. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4902. )
  4903. );
  4904. $this->add_setting(
  4905. new WP_Customize_Background_Image_Setting(
  4906. $this,
  4907. 'background_image_thumb',
  4908. array(
  4909. 'theme_supports' => 'custom-background',
  4910. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4911. )
  4912. )
  4913. );
  4914. $this->add_control( new WP_Customize_Background_Image_Control( $this ) );
  4915. $this->add_setting(
  4916. 'background_preset',
  4917. array(
  4918. 'default' => get_theme_support( 'custom-background', 'default-preset' ),
  4919. 'theme_supports' => 'custom-background',
  4920. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4921. )
  4922. );
  4923. $this->add_control(
  4924. 'background_preset',
  4925. array(
  4926. 'label' => _x( 'Preset', 'Background Preset' ),
  4927. 'section' => 'background_image',
  4928. 'type' => 'select',
  4929. 'choices' => array(
  4930. 'default' => _x( 'Default', 'Default Preset' ),
  4931. 'fill' => __( 'Fill Screen' ),
  4932. 'fit' => __( 'Fit to Screen' ),
  4933. 'repeat' => _x( 'Repeat', 'Repeat Image' ),
  4934. 'custom' => _x( 'Custom', 'Custom Preset' ),
  4935. ),
  4936. )
  4937. );
  4938. $this->add_setting(
  4939. 'background_position_x',
  4940. array(
  4941. 'default' => get_theme_support( 'custom-background', 'default-position-x' ),
  4942. 'theme_supports' => 'custom-background',
  4943. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4944. )
  4945. );
  4946. $this->add_setting(
  4947. 'background_position_y',
  4948. array(
  4949. 'default' => get_theme_support( 'custom-background', 'default-position-y' ),
  4950. 'theme_supports' => 'custom-background',
  4951. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4952. )
  4953. );
  4954. $this->add_control(
  4955. new WP_Customize_Background_Position_Control(
  4956. $this,
  4957. 'background_position',
  4958. array(
  4959. 'label' => __( 'Image Position' ),
  4960. 'section' => 'background_image',
  4961. 'settings' => array(
  4962. 'x' => 'background_position_x',
  4963. 'y' => 'background_position_y',
  4964. ),
  4965. )
  4966. )
  4967. );
  4968. $this->add_setting(
  4969. 'background_size',
  4970. array(
  4971. 'default' => get_theme_support( 'custom-background', 'default-size' ),
  4972. 'theme_supports' => 'custom-background',
  4973. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4974. )
  4975. );
  4976. $this->add_control(
  4977. 'background_size',
  4978. array(
  4979. 'label' => __( 'Image Size' ),
  4980. 'section' => 'background_image',
  4981. 'type' => 'select',
  4982. 'choices' => array(
  4983. 'auto' => _x( 'Original', 'Original Size' ),
  4984. 'contain' => __( 'Fit to Screen' ),
  4985. 'cover' => __( 'Fill Screen' ),
  4986. ),
  4987. )
  4988. );
  4989. $this->add_setting(
  4990. 'background_repeat',
  4991. array(
  4992. 'default' => get_theme_support( 'custom-background', 'default-repeat' ),
  4993. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  4994. 'theme_supports' => 'custom-background',
  4995. )
  4996. );
  4997. $this->add_control(
  4998. 'background_repeat',
  4999. array(
  5000. 'label' => __( 'Repeat Background Image' ),
  5001. 'section' => 'background_image',
  5002. 'type' => 'checkbox',
  5003. )
  5004. );
  5005. $this->add_setting(
  5006. 'background_attachment',
  5007. array(
  5008. 'default' => get_theme_support( 'custom-background', 'default-attachment' ),
  5009. 'sanitize_callback' => array( $this, '_sanitize_background_setting' ),
  5010. 'theme_supports' => 'custom-background',
  5011. )
  5012. );
  5013. $this->add_control(
  5014. 'background_attachment',
  5015. array(
  5016. 'label' => __( 'Scroll with Page' ),
  5017. 'section' => 'background_image',
  5018. 'type' => 'checkbox',
  5019. )
  5020. );
  5021. // If the theme is using the default background callback, we can update
  5022. // the background CSS using postMessage.
  5023. if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) {
  5024. foreach ( array( 'color', 'image', 'preset', 'position_x', 'position_y', 'size', 'repeat', 'attachment' ) as $prop ) {
  5025. $this->get_setting( 'background_' . $prop )->transport = 'postMessage';
  5026. }
  5027. }
  5028. /*
  5029. * Static Front Page
  5030. * See also https://core.trac.wordpress.org/ticket/19627 which introduces the static-front-page theme_support.
  5031. * The following replicates behavior from options-reading.php.
  5032. */
  5033. $this->add_section(
  5034. 'static_front_page',
  5035. array(
  5036. 'title' => __( 'Homepage Settings' ),
  5037. 'priority' => 120,
  5038. '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.' ),
  5039. 'active_callback' => array( $this, 'has_published_pages' ),
  5040. )
  5041. );
  5042. $this->add_setting(
  5043. 'show_on_front',
  5044. array(
  5045. 'default' => get_option( 'show_on_front' ),
  5046. 'capability' => 'manage_options',
  5047. 'type' => 'option',
  5048. )
  5049. );
  5050. $this->add_control(
  5051. 'show_on_front',
  5052. array(
  5053. 'label' => __( 'Your homepage displays' ),
  5054. 'section' => 'static_front_page',
  5055. 'type' => 'radio',
  5056. 'choices' => array(
  5057. 'posts' => __( 'Your latest posts' ),
  5058. 'page' => __( 'A static page' ),
  5059. ),
  5060. )
  5061. );
  5062. $this->add_setting(
  5063. 'page_on_front',
  5064. array(
  5065. 'type' => 'option',
  5066. 'capability' => 'manage_options',
  5067. )
  5068. );
  5069. $this->add_control(
  5070. 'page_on_front',
  5071. array(
  5072. 'label' => __( 'Homepage' ),
  5073. 'section' => 'static_front_page',
  5074. 'type' => 'dropdown-pages',
  5075. 'allow_addition' => true,
  5076. )
  5077. );
  5078. $this->add_setting(
  5079. 'page_for_posts',
  5080. array(
  5081. 'type' => 'option',
  5082. 'capability' => 'manage_options',
  5083. )
  5084. );
  5085. $this->add_control(
  5086. 'page_for_posts',
  5087. array(
  5088. 'label' => __( 'Posts page' ),
  5089. 'section' => 'static_front_page',
  5090. 'type' => 'dropdown-pages',
  5091. 'allow_addition' => true,
  5092. )
  5093. );
  5094. /* Custom CSS */
  5095. $section_description = '<p>';
  5096. $section_description .= __( 'Add your own CSS code here to customize the appearance and layout of your site.' );
  5097. $section_description .= sprintf(
  5098. ' <a href="%1$s" class="external-link" target="_blank">%2$s<span class="screen-reader-text"> %3$s</span></a>',
  5099. esc_url( __( 'https://codex.wordpress.org/CSS' ) ),
  5100. __( 'Learn more about CSS' ),
  5101. /* translators: Accessibility text. */
  5102. __( '(opens in a new tab)' )
  5103. );
  5104. $section_description .= '</p>';
  5105. $section_description .= '<p id="editor-keyboard-trap-help-1">' . __( 'When using a keyboard to navigate:' ) . '</p>';
  5106. $section_description .= '<ul>';
  5107. $section_description .= '<li id="editor-keyboard-trap-help-2">' . __( 'In the editing area, the Tab key enters a tab character.' ) . '</li>';
  5108. $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>';
  5109. $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>';
  5110. $section_description .= '</ul>';
  5111. if ( 'false' !== wp_get_current_user()->syntax_highlighting ) {
  5112. $section_description .= '<p>';
  5113. $section_description .= sprintf(
  5114. /* translators: 1: Link to user profile, 2: Additional link attributes, 3: Accessibility text. */
  5115. __( '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.' ),
  5116. esc_url( get_edit_profile_url() ),
  5117. 'class="external-link" target="_blank"',
  5118. sprintf(
  5119. '<span class="screen-reader-text"> %s</span>',
  5120. /* translators: Accessibility text. */
  5121. __( '(opens in a new tab)' )
  5122. )
  5123. );
  5124. $section_description .= '</p>';
  5125. }
  5126. $section_description .= '<p class="section-description-buttons">';
  5127. $section_description .= '<button type="button" class="button-link section-description-close">' . __( 'Close' ) . '</button>';
  5128. $section_description .= '</p>';
  5129. $this->add_section(
  5130. 'custom_css',
  5131. array(
  5132. 'title' => __( 'Additional CSS' ),
  5133. 'priority' => 200,
  5134. 'description_hidden' => true,
  5135. 'description' => $section_description,
  5136. )
  5137. );
  5138. $custom_css_setting = new WP_Customize_Custom_CSS_Setting(
  5139. $this,
  5140. sprintf( 'custom_css[%s]', get_stylesheet() ),
  5141. array(
  5142. 'capability' => 'edit_css',
  5143. 'default' => '',
  5144. )
  5145. );
  5146. $this->add_setting( $custom_css_setting );
  5147. $this->add_control(
  5148. new WP_Customize_Code_Editor_Control(
  5149. $this,
  5150. 'custom_css',
  5151. array(
  5152. 'label' => __( 'CSS code' ),
  5153. 'section' => 'custom_css',
  5154. 'settings' => array( 'default' => $custom_css_setting->id ),
  5155. 'code_type' => 'text/css',
  5156. 'input_attrs' => array(
  5157. 'aria-describedby' => 'editor-keyboard-trap-help-1 editor-keyboard-trap-help-2 editor-keyboard-trap-help-3 editor-keyboard-trap-help-4',
  5158. ),
  5159. )
  5160. )
  5161. );
  5162. }
  5163. /**
  5164. * Return whether there are published pages.
  5165. *
  5166. * Used as active callback for static front page section and controls.
  5167. *
  5168. * @since 4.7.0
  5169. *
  5170. * @return bool Whether there are published (or to be published) pages.
  5171. */
  5172. public function has_published_pages() {
  5173. $setting = $this->get_setting( 'nav_menus_created_posts' );
  5174. if ( $setting ) {
  5175. foreach ( $setting->value() as $post_id ) {
  5176. if ( 'page' === get_post_type( $post_id ) ) {
  5177. return true;
  5178. }
  5179. }
  5180. }
  5181. return 0 !== count( get_pages() );
  5182. }
  5183. /**
  5184. * Add settings from the POST data that were not added with code, e.g. dynamically-created settings for Widgets
  5185. *
  5186. * @since 4.2.0
  5187. *
  5188. * @see add_dynamic_settings()
  5189. */
  5190. public function register_dynamic_settings() {
  5191. $setting_ids = array_keys( $this->unsanitized_post_values() );
  5192. $this->add_dynamic_settings( $setting_ids );
  5193. }
  5194. /**
  5195. * Load themes into the theme browsing/installation UI.
  5196. *
  5197. * @since 4.9.0
  5198. */
  5199. public function handle_load_themes_request() {
  5200. check_ajax_referer( 'switch_themes', 'nonce' );
  5201. if ( ! current_user_can( 'switch_themes' ) ) {
  5202. wp_die( -1 );
  5203. }
  5204. if ( empty( $_POST['theme_action'] ) ) {
  5205. wp_send_json_error( 'missing_theme_action' );
  5206. }
  5207. $theme_action = sanitize_key( $_POST['theme_action'] );
  5208. $themes = array();
  5209. $args = array();
  5210. // Define query filters based on user input.
  5211. if ( ! array_key_exists( 'search', $_POST ) ) {
  5212. $args['search'] = '';
  5213. } else {
  5214. $args['search'] = sanitize_text_field( wp_unslash( $_POST['search'] ) );
  5215. }
  5216. if ( ! array_key_exists( 'tags', $_POST ) ) {
  5217. $args['tag'] = '';
  5218. } else {
  5219. $args['tag'] = array_map( 'sanitize_text_field', wp_unslash( (array) $_POST['tags'] ) );
  5220. }
  5221. if ( ! array_key_exists( 'page', $_POST ) ) {
  5222. $args['page'] = 1;
  5223. } else {
  5224. $args['page'] = absint( $_POST['page'] );
  5225. }
  5226. require_once ABSPATH . 'wp-admin/includes/theme.php';
  5227. if ( 'installed' === $theme_action ) {
  5228. // Load all installed themes from wp_prepare_themes_for_js().
  5229. $themes = array( 'themes' => wp_prepare_themes_for_js() );
  5230. foreach ( $themes['themes'] as &$theme ) {
  5231. $theme['type'] = 'installed';
  5232. $theme['active'] = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme['id'] );
  5233. }
  5234. } elseif ( 'wporg' === $theme_action ) {
  5235. // Load WordPress.org themes from the .org API and normalize data to match installed theme objects.
  5236. if ( ! current_user_can( 'install_themes' ) ) {
  5237. wp_die( -1 );
  5238. }
  5239. // Arguments for all queries.
  5240. $wporg_args = array(
  5241. 'per_page' => 100,
  5242. 'fields' => array(
  5243. 'reviews_url' => true, // Explicitly request the reviews URL to be linked from the customizer.
  5244. ),
  5245. );
  5246. $args = array_merge( $wporg_args, $args );
  5247. if ( '' === $args['search'] && '' === $args['tag'] ) {
  5248. $args['browse'] = 'new'; // Sort by latest themes by default.
  5249. }
  5250. // Load themes from the .org API.
  5251. $themes = themes_api( 'query_themes', $args );
  5252. if ( is_wp_error( $themes ) ) {
  5253. wp_send_json_error();
  5254. }
  5255. // This list matches the allowed tags in wp-admin/includes/theme-install.php.
  5256. $themes_allowedtags = array_fill_keys(
  5257. array( 'a', 'abbr', 'acronym', 'code', 'pre', 'em', 'strong', 'div', 'p', 'ul', 'ol', 'li', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'img' ),
  5258. array()
  5259. );
  5260. $themes_allowedtags['a'] = array_fill_keys( array( 'href', 'title', 'target' ), true );
  5261. $themes_allowedtags['acronym']['title'] = true;
  5262. $themes_allowedtags['abbr']['title'] = true;
  5263. $themes_allowedtags['img'] = array_fill_keys( array( 'src', 'class', 'alt' ), true );
  5264. // Prepare a list of installed themes to check against before the loop.
  5265. $installed_themes = array();
  5266. $wp_themes = wp_get_themes();
  5267. foreach ( $wp_themes as $theme ) {
  5268. $installed_themes[] = $theme->get_stylesheet();
  5269. }
  5270. $update_php = network_admin_url( 'update.php?action=install-theme' );
  5271. // Set up properties for themes available on WordPress.org.
  5272. foreach ( $themes->themes as &$theme ) {
  5273. $theme->install_url = add_query_arg(
  5274. array(
  5275. 'theme' => $theme->slug,
  5276. '_wpnonce' => wp_create_nonce( 'install-theme_' . $theme->slug ),
  5277. ),
  5278. $update_php
  5279. );
  5280. $theme->name = wp_kses( $theme->name, $themes_allowedtags );
  5281. $theme->version = wp_kses( $theme->version, $themes_allowedtags );
  5282. $theme->description = wp_kses( $theme->description, $themes_allowedtags );
  5283. $theme->stars = wp_star_rating(
  5284. array(
  5285. 'rating' => $theme->rating,
  5286. 'type' => 'percent',
  5287. 'number' => $theme->num_ratings,
  5288. 'echo' => false,
  5289. )
  5290. );
  5291. $theme->num_ratings = number_format_i18n( $theme->num_ratings );
  5292. $theme->preview_url = set_url_scheme( $theme->preview_url );
  5293. // Handle themes that are already installed as installed themes.
  5294. if ( in_array( $theme->slug, $installed_themes, true ) ) {
  5295. $theme->type = 'installed';
  5296. } else {
  5297. $theme->type = $theme_action;
  5298. }
  5299. // Set active based on customized theme.
  5300. $theme->active = ( isset( $_POST['customized_theme'] ) && $_POST['customized_theme'] === $theme->slug );
  5301. // Map available theme properties to installed theme properties.
  5302. $theme->id = $theme->slug;
  5303. $theme->screenshot = array( $theme->screenshot_url );
  5304. $theme->authorAndUri = wp_kses( $theme->author['display_name'], $themes_allowedtags );
  5305. $theme->compatibleWP = is_wp_version_compatible( $theme->requires ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName
  5306. $theme->compatiblePHP = is_php_version_compatible( $theme->requires_php ); // phpcs:ignore WordPress.NamingConventions.ValidVariableName
  5307. if ( isset( $theme->parent ) ) {
  5308. $theme->parent = $theme->parent['slug'];
  5309. } else {
  5310. $theme->parent = false;
  5311. }
  5312. unset( $theme->slug );
  5313. unset( $theme->screenshot_url );
  5314. unset( $theme->author );
  5315. } // End foreach().
  5316. } // End if().
  5317. /**
  5318. * Filters the theme data loaded in the customizer.
  5319. *
  5320. * This allows theme data to be loading from an external source,
  5321. * or modification of data loaded from `wp_prepare_themes_for_js()`
  5322. * or WordPress.org via `themes_api()`.
  5323. *
  5324. * @since 4.9.0
  5325. *
  5326. * @see wp_prepare_themes_for_js()
  5327. * @see themes_api()
  5328. * @see WP_Customize_Manager::__construct()
  5329. *
  5330. * @param array $themes Nested array of theme data.
  5331. * @param array $args List of arguments, such as page, search term, and tags to query for.
  5332. * @param WP_Customize_Manager $manager Instance of Customize manager.
  5333. */
  5334. $themes = apply_filters( 'customize_load_themes', $themes, $args, $this );
  5335. wp_send_json_success( $themes );
  5336. }
  5337. /**
  5338. * Callback for validating the header_textcolor value.
  5339. *
  5340. * Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash().
  5341. * Returns default text color if hex color is empty.
  5342. *
  5343. * @since 3.4.0
  5344. *
  5345. * @param string $color
  5346. * @return mixed
  5347. */
  5348. public function _sanitize_header_textcolor( $color ) {
  5349. if ( 'blank' === $color ) {
  5350. return 'blank';
  5351. }
  5352. $color = sanitize_hex_color_no_hash( $color );
  5353. if ( empty( $color ) ) {
  5354. $color = get_theme_support( 'custom-header', 'default-text-color' );
  5355. }
  5356. return $color;
  5357. }
  5358. /**
  5359. * Callback for validating a background setting value.
  5360. *
  5361. * @since 4.7.0
  5362. *
  5363. * @param string $value Repeat value.
  5364. * @param WP_Customize_Setting $setting Setting.
  5365. * @return string|WP_Error Background value or validation error.
  5366. */
  5367. public function _sanitize_background_setting( $value, $setting ) {
  5368. if ( 'background_repeat' === $setting->id ) {
  5369. if ( ! in_array( $value, array( 'repeat-x', 'repeat-y', 'repeat', 'no-repeat' ), true ) ) {
  5370. return new WP_Error( 'invalid_value', __( 'Invalid value for background repeat.' ) );
  5371. }
  5372. } elseif ( 'background_attachment' === $setting->id ) {
  5373. if ( ! in_array( $value, array( 'fixed', 'scroll' ), true ) ) {
  5374. return new WP_Error( 'invalid_value', __( 'Invalid value for background attachment.' ) );
  5375. }
  5376. } elseif ( 'background_position_x' === $setting->id ) {
  5377. if ( ! in_array( $value, array( 'left', 'center', 'right' ), true ) ) {
  5378. return new WP_Error( 'invalid_value', __( 'Invalid value for background position X.' ) );
  5379. }
  5380. } elseif ( 'background_position_y' === $setting->id ) {
  5381. if ( ! in_array( $value, array( 'top', 'center', 'bottom' ), true ) ) {
  5382. return new WP_Error( 'invalid_value', __( 'Invalid value for background position Y.' ) );
  5383. }
  5384. } elseif ( 'background_size' === $setting->id ) {
  5385. if ( ! in_array( $value, array( 'auto', 'contain', 'cover' ), true ) ) {
  5386. return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
  5387. }
  5388. } elseif ( 'background_preset' === $setting->id ) {
  5389. if ( ! in_array( $value, array( 'default', 'fill', 'fit', 'repeat', 'custom' ), true ) ) {
  5390. return new WP_Error( 'invalid_value', __( 'Invalid value for background size.' ) );
  5391. }
  5392. } elseif ( 'background_image' === $setting->id || 'background_image_thumb' === $setting->id ) {
  5393. $value = empty( $value ) ? '' : esc_url_raw( $value );
  5394. } else {
  5395. return new WP_Error( 'unrecognized_setting', __( 'Unrecognized background setting.' ) );
  5396. }
  5397. return $value;
  5398. }
  5399. /**
  5400. * Export header video settings to facilitate selective refresh.
  5401. *
  5402. * @since 4.7.0
  5403. *
  5404. * @param array $response Response.
  5405. * @param WP_Customize_Selective_Refresh $selective_refresh Selective refresh component.
  5406. * @param array $partials Array of partials.
  5407. * @return array
  5408. */
  5409. public function export_header_video_settings( $response, $selective_refresh, $partials ) {
  5410. if ( isset( $partials['custom_header'] ) ) {
  5411. $response['custom_header_settings'] = get_header_video_settings();
  5412. }
  5413. return $response;
  5414. }
  5415. /**
  5416. * Callback for validating the header_video value.
  5417. *
  5418. * Ensures that the selected video is less than 8MB and provides an error message.
  5419. *
  5420. * @since 4.7.0
  5421. *
  5422. * @param WP_Error $validity
  5423. * @param mixed $value
  5424. * @return mixed
  5425. */
  5426. public function _validate_header_video( $validity, $value ) {
  5427. $video = get_attached_file( absint( $value ) );
  5428. if ( $video ) {
  5429. $size = filesize( $video );
  5430. if ( $size > 8 * MB_IN_BYTES ) {
  5431. $validity->add(
  5432. 'size_too_large',
  5433. __( '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.' )
  5434. );
  5435. }
  5436. 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.
  5437. $validity->add(
  5438. 'invalid_file_type',
  5439. sprintf(
  5440. /* translators: 1: .mp4, 2: .mov */
  5441. __( '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.' ),
  5442. '<code>.mp4</code>',
  5443. '<code>.mov</code>'
  5444. )
  5445. );
  5446. }
  5447. }
  5448. return $validity;
  5449. }
  5450. /**
  5451. * Callback for validating the external_header_video value.
  5452. *
  5453. * Ensures that the provided URL is supported.
  5454. *
  5455. * @since 4.7.0
  5456. *
  5457. * @param WP_Error $validity
  5458. * @param mixed $value
  5459. * @return mixed
  5460. */
  5461. public function _validate_external_header_video( $validity, $value ) {
  5462. $video = esc_url_raw( $value );
  5463. if ( $video ) {
  5464. if ( ! preg_match( '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#', $video ) ) {
  5465. $validity->add( 'invalid_url', __( 'Please enter a valid YouTube URL.' ) );
  5466. }
  5467. }
  5468. return $validity;
  5469. }
  5470. /**
  5471. * Callback for sanitizing the external_header_video value.
  5472. *
  5473. * @since 4.7.1
  5474. *
  5475. * @param string $value URL.
  5476. * @return string Sanitized URL.
  5477. */
  5478. public function _sanitize_external_header_video( $value ) {
  5479. return esc_url_raw( trim( $value ) );
  5480. }
  5481. /**
  5482. * Callback for rendering the custom logo, used in the custom_logo partial.
  5483. *
  5484. * This method exists because the partial object and context data are passed
  5485. * into a partial's render_callback so we cannot use get_custom_logo() as
  5486. * the render_callback directly since it expects a blog ID as the first
  5487. * argument. When WP no longer supports PHP 5.3, this method can be removed
  5488. * in favor of an anonymous function.
  5489. *
  5490. * @see WP_Customize_Manager::register_controls()
  5491. *
  5492. * @since 4.5.0
  5493. *
  5494. * @return string Custom logo.
  5495. */
  5496. public function _render_custom_logo_partial() {
  5497. return get_custom_logo();
  5498. }
  5499. }