class-wp-customize-manager.php 197 KB

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