class-wp-customize-manager.php 197 KB

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