class-wp-customize-manager.php 193 KB

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