class-wp-customize-widgets.php 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212
  1. <?php
  2. /**
  3. * WordPress Customize Widgets classes
  4. *
  5. * @package WordPress
  6. * @subpackage Customize
  7. * @since 3.9.0
  8. */
  9. /**
  10. * Customize Widgets class.
  11. *
  12. * Implements widget management in the Customizer.
  13. *
  14. * @since 3.9.0
  15. *
  16. * @see WP_Customize_Manager
  17. */
  18. #[AllowDynamicProperties]
  19. final class WP_Customize_Widgets {
  20. /**
  21. * WP_Customize_Manager instance.
  22. *
  23. * @since 3.9.0
  24. * @var WP_Customize_Manager
  25. */
  26. public $manager;
  27. /**
  28. * All id_bases for widgets defined in core.
  29. *
  30. * @since 3.9.0
  31. * @var array
  32. */
  33. protected $core_widget_id_bases = array(
  34. 'archives',
  35. 'calendar',
  36. 'categories',
  37. 'custom_html',
  38. 'links',
  39. 'media_audio',
  40. 'media_image',
  41. 'media_video',
  42. 'meta',
  43. 'nav_menu',
  44. 'pages',
  45. 'recent-comments',
  46. 'recent-posts',
  47. 'rss',
  48. 'search',
  49. 'tag_cloud',
  50. 'text',
  51. );
  52. /**
  53. * @since 3.9.0
  54. * @var array
  55. */
  56. protected $rendered_sidebars = array();
  57. /**
  58. * @since 3.9.0
  59. * @var array
  60. */
  61. protected $rendered_widgets = array();
  62. /**
  63. * @since 3.9.0
  64. * @var array
  65. */
  66. protected $old_sidebars_widgets = array();
  67. /**
  68. * Mapping of widget ID base to whether it supports selective refresh.
  69. *
  70. * @since 4.5.0
  71. * @var array
  72. */
  73. protected $selective_refreshable_widgets;
  74. /**
  75. * Mapping of setting type to setting ID pattern.
  76. *
  77. * @since 4.2.0
  78. * @var array
  79. */
  80. protected $setting_id_patterns = array(
  81. 'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/',
  82. 'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/',
  83. );
  84. /**
  85. * Initial loader.
  86. *
  87. * @since 3.9.0
  88. *
  89. * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  90. */
  91. public function __construct( $manager ) {
  92. $this->manager = $manager;
  93. // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
  94. add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
  95. add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
  96. add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
  97. // Skip remaining hooks when the user can't manage widgets anyway.
  98. if ( ! current_user_can( 'edit_theme_options' ) ) {
  99. return;
  100. }
  101. add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
  102. add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
  103. add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  104. add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
  105. add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
  106. add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
  107. add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
  108. add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
  109. add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
  110. add_filter( 'should_load_block_editor_scripts_and_styles', array( $this, 'should_load_block_editor_scripts_and_styles' ) );
  111. add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
  112. add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
  113. add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
  114. // Selective Refresh.
  115. add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
  116. add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
  117. }
  118. /**
  119. * List whether each registered widget can be use selective refresh.
  120. *
  121. * If the theme does not support the customize-selective-refresh-widgets feature,
  122. * then this will always return an empty array.
  123. *
  124. * @since 4.5.0
  125. *
  126. * @global WP_Widget_Factory $wp_widget_factory
  127. *
  128. * @return array Mapping of id_base to support. If theme doesn't support
  129. * selective refresh, an empty array is returned.
  130. */
  131. public function get_selective_refreshable_widgets() {
  132. global $wp_widget_factory;
  133. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  134. return array();
  135. }
  136. if ( ! isset( $this->selective_refreshable_widgets ) ) {
  137. $this->selective_refreshable_widgets = array();
  138. foreach ( $wp_widget_factory->widgets as $wp_widget ) {
  139. $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
  140. }
  141. }
  142. return $this->selective_refreshable_widgets;
  143. }
  144. /**
  145. * Determines if a widget supports selective refresh.
  146. *
  147. * @since 4.5.0
  148. *
  149. * @param string $id_base Widget ID Base.
  150. * @return bool Whether the widget can be selective refreshed.
  151. */
  152. public function is_widget_selective_refreshable( $id_base ) {
  153. $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
  154. return ! empty( $selective_refreshable_widgets[ $id_base ] );
  155. }
  156. /**
  157. * Retrieves the widget setting type given a setting ID.
  158. *
  159. * @since 4.2.0
  160. *
  161. * @param string $setting_id Setting ID.
  162. * @return string|void Setting type.
  163. */
  164. protected function get_setting_type( $setting_id ) {
  165. static $cache = array();
  166. if ( isset( $cache[ $setting_id ] ) ) {
  167. return $cache[ $setting_id ];
  168. }
  169. foreach ( $this->setting_id_patterns as $type => $pattern ) {
  170. if ( preg_match( $pattern, $setting_id ) ) {
  171. $cache[ $setting_id ] = $type;
  172. return $type;
  173. }
  174. }
  175. }
  176. /**
  177. * Inspects the incoming customized data for any widget settings, and dynamically adds
  178. * them up-front so widgets will be initialized properly.
  179. *
  180. * @since 4.2.0
  181. */
  182. public function register_settings() {
  183. $widget_setting_ids = array();
  184. $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
  185. foreach ( $incoming_setting_ids as $setting_id ) {
  186. if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
  187. $widget_setting_ids[] = $setting_id;
  188. }
  189. }
  190. if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
  191. $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
  192. }
  193. $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
  194. if ( $this->manager->settings_previewed() ) {
  195. foreach ( $settings as $setting ) {
  196. $setting->preview();
  197. }
  198. }
  199. }
  200. /**
  201. * Determines the arguments for a dynamically-created setting.
  202. *
  203. * @since 4.2.0
  204. *
  205. * @param false|array $args The arguments to the WP_Customize_Setting constructor.
  206. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  207. * @return array|false Setting arguments, false otherwise.
  208. */
  209. public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
  210. if ( $this->get_setting_type( $setting_id ) ) {
  211. $args = $this->get_setting_args( $setting_id );
  212. }
  213. return $args;
  214. }
  215. /**
  216. * Retrieves an unslashed post value or return a default.
  217. *
  218. * @since 3.9.0
  219. *
  220. * @param string $name Post value.
  221. * @param mixed $default_value Default post value.
  222. * @return mixed Unslashed post value or default value.
  223. */
  224. protected function get_post_value( $name, $default_value = null ) {
  225. if ( ! isset( $_POST[ $name ] ) ) {
  226. return $default_value;
  227. }
  228. return wp_unslash( $_POST[ $name ] );
  229. }
  230. /**
  231. * Override sidebars_widgets for theme switch.
  232. *
  233. * When switching a theme via the Customizer, supply any previously-configured
  234. * sidebars_widgets from the target theme as the initial sidebars_widgets
  235. * setting. Also store the old theme's existing settings so that they can
  236. * be passed along for storing in the sidebars_widgets theme_mod when the
  237. * theme gets switched.
  238. *
  239. * @since 3.9.0
  240. *
  241. * @global array $sidebars_widgets
  242. * @global array $_wp_sidebars_widgets
  243. */
  244. public function override_sidebars_widgets_for_theme_switch() {
  245. global $sidebars_widgets;
  246. if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
  247. return;
  248. }
  249. $this->old_sidebars_widgets = wp_get_sidebars_widgets();
  250. add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
  251. $this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
  252. // retrieve_widgets() looks at the global $sidebars_widgets.
  253. $sidebars_widgets = $this->old_sidebars_widgets;
  254. $sidebars_widgets = retrieve_widgets( 'customize' );
  255. add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
  256. // Reset global cache var used by wp_get_sidebars_widgets().
  257. unset( $GLOBALS['_wp_sidebars_widgets'] );
  258. }
  259. /**
  260. * Filters old_sidebars_widgets_data Customizer setting.
  261. *
  262. * When switching themes, filter the Customizer setting old_sidebars_widgets_data
  263. * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
  264. * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
  265. * theme_mod.
  266. *
  267. * @since 3.9.0
  268. *
  269. * @see WP_Customize_Widgets::handle_theme_switch()
  270. *
  271. * @param array $old_sidebars_widgets
  272. * @return array
  273. */
  274. public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
  275. return $this->old_sidebars_widgets;
  276. }
  277. /**
  278. * Filters sidebars_widgets option for theme switch.
  279. *
  280. * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
  281. * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
  282. * option.
  283. *
  284. * @since 3.9.0
  285. *
  286. * @see WP_Customize_Widgets::handle_theme_switch()
  287. * @global array $sidebars_widgets
  288. *
  289. * @param array $sidebars_widgets
  290. * @return array
  291. */
  292. public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
  293. $sidebars_widgets = $GLOBALS['sidebars_widgets'];
  294. $sidebars_widgets['array_version'] = 3;
  295. return $sidebars_widgets;
  296. }
  297. /**
  298. * Ensures all widgets get loaded into the Customizer.
  299. *
  300. * Note: these actions are also fired in wp_ajax_update_widget().
  301. *
  302. * @since 3.9.0
  303. */
  304. public function customize_controls_init() {
  305. /** This action is documented in wp-admin/includes/ajax-actions.php */
  306. do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  307. /** This action is documented in wp-admin/includes/ajax-actions.php */
  308. do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  309. /** This action is documented in wp-admin/widgets.php */
  310. do_action( 'sidebar_admin_setup' );
  311. }
  312. /**
  313. * Ensures widgets are available for all types of previews.
  314. *
  315. * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
  316. * so that all filters have been initialized (e.g. Widget Visibility).
  317. *
  318. * @since 3.9.0
  319. */
  320. public function schedule_customize_register() {
  321. if ( is_admin() ) {
  322. $this->customize_register();
  323. } else {
  324. add_action( 'wp', array( $this, 'customize_register' ) );
  325. }
  326. }
  327. /**
  328. * Registers Customizer settings and controls for all sidebars and widgets.
  329. *
  330. * @since 3.9.0
  331. *
  332. * @global array $wp_registered_widgets
  333. * @global array $wp_registered_widget_controls
  334. * @global array $wp_registered_sidebars
  335. */
  336. public function customize_register() {
  337. global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
  338. $use_widgets_block_editor = wp_use_widgets_block_editor();
  339. add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
  340. $sidebars_widgets = array_merge(
  341. array( 'wp_inactive_widgets' => array() ),
  342. array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
  343. wp_get_sidebars_widgets()
  344. );
  345. $new_setting_ids = array();
  346. /*
  347. * Register a setting for all widgets, including those which are active,
  348. * inactive, and orphaned since a widget may get suppressed from a sidebar
  349. * via a plugin (like Widget Visibility).
  350. */
  351. foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
  352. $setting_id = $this->get_setting_id( $widget_id );
  353. $setting_args = $this->get_setting_args( $setting_id );
  354. if ( ! $this->manager->get_setting( $setting_id ) ) {
  355. $this->manager->add_setting( $setting_id, $setting_args );
  356. }
  357. $new_setting_ids[] = $setting_id;
  358. }
  359. /*
  360. * Add a setting which will be supplied for the theme's sidebars_widgets
  361. * theme_mod when the theme is switched.
  362. */
  363. if ( ! $this->manager->is_theme_active() ) {
  364. $setting_id = 'old_sidebars_widgets_data';
  365. $setting_args = $this->get_setting_args(
  366. $setting_id,
  367. array(
  368. 'type' => 'global_variable',
  369. 'dirty' => true,
  370. )
  371. );
  372. $this->manager->add_setting( $setting_id, $setting_args );
  373. }
  374. $this->manager->add_panel(
  375. 'widgets',
  376. array(
  377. 'type' => 'widgets',
  378. 'title' => __( 'Widgets' ),
  379. 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
  380. 'priority' => 110,
  381. 'active_callback' => array( $this, 'is_panel_active' ),
  382. 'auto_expand_sole_section' => true,
  383. 'theme_supports' => 'widgets',
  384. )
  385. );
  386. foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
  387. if ( empty( $sidebar_widget_ids ) ) {
  388. $sidebar_widget_ids = array();
  389. }
  390. $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
  391. $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
  392. $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
  393. // Add setting for managing the sidebar's widgets.
  394. if ( $is_registered_sidebar || $is_inactive_widgets ) {
  395. $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
  396. $setting_args = $this->get_setting_args( $setting_id );
  397. if ( ! $this->manager->get_setting( $setting_id ) ) {
  398. if ( ! $this->manager->is_theme_active() ) {
  399. $setting_args['dirty'] = true;
  400. }
  401. $this->manager->add_setting( $setting_id, $setting_args );
  402. }
  403. $new_setting_ids[] = $setting_id;
  404. // Add section to contain controls.
  405. $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
  406. if ( $is_active_sidebar ) {
  407. $section_args = array(
  408. 'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
  409. 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ), true ),
  410. 'panel' => 'widgets',
  411. 'sidebar_id' => $sidebar_id,
  412. );
  413. if ( $use_widgets_block_editor ) {
  414. $section_args['description'] = '';
  415. } else {
  416. $section_args['description'] = $wp_registered_sidebars[ $sidebar_id ]['description'];
  417. }
  418. /**
  419. * Filters Customizer widget section arguments for a given sidebar.
  420. *
  421. * @since 3.9.0
  422. *
  423. * @param array $section_args Array of Customizer widget section arguments.
  424. * @param string $section_id Customizer section ID.
  425. * @param int|string $sidebar_id Sidebar ID.
  426. */
  427. $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
  428. $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
  429. $this->manager->add_section( $section );
  430. if ( $use_widgets_block_editor ) {
  431. $control = new WP_Sidebar_Block_Editor_Control(
  432. $this->manager,
  433. $setting_id,
  434. array(
  435. 'section' => $section_id,
  436. 'sidebar_id' => $sidebar_id,
  437. 'label' => $section_args['title'],
  438. 'description' => $section_args['description'],
  439. )
  440. );
  441. } else {
  442. $control = new WP_Widget_Area_Customize_Control(
  443. $this->manager,
  444. $setting_id,
  445. array(
  446. 'section' => $section_id,
  447. 'sidebar_id' => $sidebar_id,
  448. 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
  449. )
  450. );
  451. }
  452. $this->manager->add_control( $control );
  453. $new_setting_ids[] = $setting_id;
  454. }
  455. }
  456. if ( ! $use_widgets_block_editor ) {
  457. // Add a control for each active widget (located in a sidebar).
  458. foreach ( $sidebar_widget_ids as $i => $widget_id ) {
  459. // Skip widgets that may have gone away due to a plugin being deactivated.
  460. if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
  461. continue;
  462. }
  463. $registered_widget = $wp_registered_widgets[ $widget_id ];
  464. $setting_id = $this->get_setting_id( $widget_id );
  465. $id_base = $wp_registered_widget_controls[ $widget_id ]['id_base'];
  466. $control = new WP_Widget_Form_Customize_Control(
  467. $this->manager,
  468. $setting_id,
  469. array(
  470. 'label' => $registered_widget['name'],
  471. 'section' => $section_id,
  472. 'sidebar_id' => $sidebar_id,
  473. 'widget_id' => $widget_id,
  474. 'widget_id_base' => $id_base,
  475. 'priority' => $i,
  476. 'width' => $wp_registered_widget_controls[ $widget_id ]['width'],
  477. 'height' => $wp_registered_widget_controls[ $widget_id ]['height'],
  478. 'is_wide' => $this->is_wide_widget( $widget_id ),
  479. )
  480. );
  481. $this->manager->add_control( $control );
  482. }
  483. }
  484. }
  485. if ( $this->manager->settings_previewed() ) {
  486. foreach ( $new_setting_ids as $new_setting_id ) {
  487. $this->manager->get_setting( $new_setting_id )->preview();
  488. }
  489. }
  490. }
  491. /**
  492. * Determines whether the widgets panel is active, based on whether there are sidebars registered.
  493. *
  494. * @since 4.4.0
  495. *
  496. * @see WP_Customize_Panel::$active_callback
  497. *
  498. * @global array $wp_registered_sidebars
  499. * @return bool Active.
  500. */
  501. public function is_panel_active() {
  502. global $wp_registered_sidebars;
  503. return ! empty( $wp_registered_sidebars );
  504. }
  505. /**
  506. * Converts a widget_id into its corresponding Customizer setting ID (option name).
  507. *
  508. * @since 3.9.0
  509. *
  510. * @param string $widget_id Widget ID.
  511. * @return string Maybe-parsed widget ID.
  512. */
  513. public function get_setting_id( $widget_id ) {
  514. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  515. $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
  516. if ( ! is_null( $parsed_widget_id['number'] ) ) {
  517. $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
  518. }
  519. return $setting_id;
  520. }
  521. /**
  522. * Determines whether the widget is considered "wide".
  523. *
  524. * Core widgets which may have controls wider than 250, but can still be shown
  525. * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
  526. * have widths of 400 and yet they still render fine in the Customizer panel.
  527. *
  528. * This method will return all Core widgets as being not wide, but this can be
  529. * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
  530. *
  531. * @since 3.9.0
  532. *
  533. * @global array $wp_registered_widget_controls
  534. *
  535. * @param string $widget_id Widget ID.
  536. * @return bool Whether or not the widget is a "wide" widget.
  537. */
  538. public function is_wide_widget( $widget_id ) {
  539. global $wp_registered_widget_controls;
  540. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  541. $width = $wp_registered_widget_controls[ $widget_id ]['width'];
  542. $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases, true );
  543. $is_wide = ( $width > 250 && ! $is_core );
  544. /**
  545. * Filters whether the given widget is considered "wide".
  546. *
  547. * @since 3.9.0
  548. *
  549. * @param bool $is_wide Whether the widget is wide, Default false.
  550. * @param string $widget_id Widget ID.
  551. */
  552. return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
  553. }
  554. /**
  555. * Converts a widget ID into its id_base and number components.
  556. *
  557. * @since 3.9.0
  558. *
  559. * @param string $widget_id Widget ID.
  560. * @return array Array containing a widget's id_base and number components.
  561. */
  562. public function parse_widget_id( $widget_id ) {
  563. $parsed = array(
  564. 'number' => null,
  565. 'id_base' => null,
  566. );
  567. if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
  568. $parsed['id_base'] = $matches[1];
  569. $parsed['number'] = (int) $matches[2];
  570. } else {
  571. // Likely an old single widget.
  572. $parsed['id_base'] = $widget_id;
  573. }
  574. return $parsed;
  575. }
  576. /**
  577. * Converts a widget setting ID (option path) to its id_base and number components.
  578. *
  579. * @since 3.9.0
  580. *
  581. * @param string $setting_id Widget setting ID.
  582. * @return array|WP_Error Array containing a widget's id_base and number components,
  583. * or a WP_Error object.
  584. */
  585. public function parse_widget_setting_id( $setting_id ) {
  586. if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
  587. return new WP_Error( 'widget_setting_invalid_id' );
  588. }
  589. $id_base = $matches[2];
  590. $number = isset( $matches[3] ) ? (int) $matches[3] : null;
  591. return compact( 'id_base', 'number' );
  592. }
  593. /**
  594. * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
  595. * allow custom styles from plugins.
  596. *
  597. * @since 3.9.0
  598. */
  599. public function print_styles() {
  600. /** This action is documented in wp-admin/admin-header.php */
  601. do_action( 'admin_print_styles-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  602. /** This action is documented in wp-admin/admin-header.php */
  603. do_action( 'admin_print_styles' );
  604. }
  605. /**
  606. * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
  607. * allow custom scripts from plugins.
  608. *
  609. * @since 3.9.0
  610. */
  611. public function print_scripts() {
  612. /** This action is documented in wp-admin/admin-header.php */
  613. do_action( 'admin_print_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  614. /** This action is documented in wp-admin/admin-header.php */
  615. do_action( 'admin_print_scripts' );
  616. }
  617. /**
  618. * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
  619. *
  620. * @since 3.9.0
  621. *
  622. * @global WP_Scripts $wp_scripts
  623. * @global array $wp_registered_sidebars
  624. * @global array $wp_registered_widgets
  625. */
  626. public function enqueue_scripts() {
  627. global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
  628. wp_enqueue_style( 'customize-widgets' );
  629. wp_enqueue_script( 'customize-widgets' );
  630. /** This action is documented in wp-admin/admin-header.php */
  631. do_action( 'admin_enqueue_scripts', 'widgets.php' );
  632. /*
  633. * Export available widgets with control_tpl removed from model
  634. * since plugins need templates to be in the DOM.
  635. */
  636. $available_widgets = array();
  637. foreach ( $this->get_available_widgets() as $available_widget ) {
  638. unset( $available_widget['control_tpl'] );
  639. $available_widgets[] = $available_widget;
  640. }
  641. $widget_reorder_nav_tpl = sprintf(
  642. '<div class="widget-reorder-nav"><span class="move-widget" tabindex="0">%1$s</span><span class="move-widget-down" tabindex="0">%2$s</span><span class="move-widget-up" tabindex="0">%3$s</span></div>',
  643. __( 'Move to another area&hellip;' ),
  644. __( 'Move down' ),
  645. __( 'Move up' )
  646. );
  647. $move_widget_area_tpl = str_replace(
  648. array( '{description}', '{btn}' ),
  649. array(
  650. __( 'Select an area to move this widget into:' ),
  651. _x( 'Move', 'Move widget' ),
  652. ),
  653. '<div class="move-widget-area">
  654. <p class="description">{description}</p>
  655. <ul class="widget-area-select">
  656. <% _.each( sidebars, function ( sidebar ){ %>
  657. <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
  658. <% }); %>
  659. </ul>
  660. <div class="move-widget-actions">
  661. <button class="move-widget-btn button" type="button">{btn}</button>
  662. </div>
  663. </div>'
  664. );
  665. /*
  666. * Gather all strings in PHP that may be needed by JS on the client.
  667. * Once JS i18n is implemented (in #20491), this can be removed.
  668. */
  669. $some_non_rendered_areas_messages = array();
  670. $some_non_rendered_areas_messages[1] = html_entity_decode(
  671. __( 'Your theme has 1 other widget area, but this particular page does not display it.' ),
  672. ENT_QUOTES,
  673. get_bloginfo( 'charset' )
  674. );
  675. $registered_sidebar_count = count( $wp_registered_sidebars );
  676. for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
  677. $some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
  678. sprintf(
  679. /* translators: %s: The number of other widget areas registered but not rendered. */
  680. _n(
  681. 'Your theme has %s other widget area, but this particular page does not display it.',
  682. 'Your theme has %s other widget areas, but this particular page does not display them.',
  683. $non_rendered_count
  684. ),
  685. number_format_i18n( $non_rendered_count )
  686. ),
  687. ENT_QUOTES,
  688. get_bloginfo( 'charset' )
  689. );
  690. }
  691. if ( 1 === $registered_sidebar_count ) {
  692. $no_areas_shown_message = html_entity_decode(
  693. sprintf(
  694. __( 'Your theme has 1 widget area, but this particular page does not display it.' )
  695. ),
  696. ENT_QUOTES,
  697. get_bloginfo( 'charset' )
  698. );
  699. } else {
  700. $no_areas_shown_message = html_entity_decode(
  701. sprintf(
  702. /* translators: %s: The total number of widget areas registered. */
  703. _n(
  704. 'Your theme has %s widget area, but this particular page does not display it.',
  705. 'Your theme has %s widget areas, but this particular page does not display them.',
  706. $registered_sidebar_count
  707. ),
  708. number_format_i18n( $registered_sidebar_count )
  709. ),
  710. ENT_QUOTES,
  711. get_bloginfo( 'charset' )
  712. );
  713. }
  714. $settings = array(
  715. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  716. 'registeredWidgets' => $wp_registered_widgets,
  717. 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets.
  718. 'l10n' => array(
  719. 'saveBtnLabel' => __( 'Apply' ),
  720. 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
  721. 'removeBtnLabel' => __( 'Remove' ),
  722. 'removeBtnTooltip' => __( 'Keep widget settings and move it to the inactive widgets' ),
  723. 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
  724. 'widgetMovedUp' => __( 'Widget moved up' ),
  725. 'widgetMovedDown' => __( 'Widget moved down' ),
  726. 'navigatePreview' => __( 'You can navigate to other pages on your site while using the Customizer to view and edit the widgets displayed on those pages.' ),
  727. 'someAreasShown' => $some_non_rendered_areas_messages,
  728. 'noAreasShown' => $no_areas_shown_message,
  729. 'reorderModeOn' => __( 'Reorder mode enabled' ),
  730. 'reorderModeOff' => __( 'Reorder mode closed' ),
  731. 'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
  732. /* translators: %d: The number of widgets found. */
  733. 'widgetsFound' => __( 'Number of widgets found: %d' ),
  734. 'noWidgetsFound' => __( 'No widgets found.' ),
  735. ),
  736. 'tpl' => array(
  737. 'widgetReorderNav' => $widget_reorder_nav_tpl,
  738. 'moveWidgetArea' => $move_widget_area_tpl,
  739. ),
  740. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  741. );
  742. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  743. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  744. }
  745. $wp_scripts->add_data(
  746. 'customize-widgets',
  747. 'data',
  748. sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
  749. );
  750. /*
  751. * TODO: Update 'wp-customize-widgets' to not rely so much on things in
  752. * 'customize-widgets'. This will let us skip most of the above and not
  753. * enqueue 'customize-widgets' which saves bytes.
  754. */
  755. if ( wp_use_widgets_block_editor() ) {
  756. $block_editor_context = new WP_Block_Editor_Context(
  757. array(
  758. 'name' => 'core/customize-widgets',
  759. )
  760. );
  761. $editor_settings = get_block_editor_settings(
  762. get_legacy_widget_block_editor_settings(),
  763. $block_editor_context
  764. );
  765. wp_add_inline_script(
  766. 'wp-customize-widgets',
  767. sprintf(
  768. 'wp.domReady( function() {
  769. wp.customizeWidgets.initialize( "widgets-customizer", %s );
  770. } );',
  771. wp_json_encode( $editor_settings )
  772. )
  773. );
  774. // Preload server-registered block schemas.
  775. wp_add_inline_script(
  776. 'wp-blocks',
  777. 'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . wp_json_encode( get_block_editor_server_block_settings() ) . ');'
  778. );
  779. wp_add_inline_script(
  780. 'wp-blocks',
  781. sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $block_editor_context ) ) ),
  782. 'after'
  783. );
  784. wp_enqueue_script( 'wp-customize-widgets' );
  785. wp_enqueue_style( 'wp-customize-widgets' );
  786. /** This action is documented in edit-form-blocks.php */
  787. do_action( 'enqueue_block_editor_assets' );
  788. }
  789. }
  790. /**
  791. * Renders the widget form control templates into the DOM.
  792. *
  793. * @since 3.9.0
  794. */
  795. public function output_widget_control_templates() {
  796. ?>
  797. <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
  798. <div id="available-widgets">
  799. <div class="customize-section-title">
  800. <button class="customize-section-back" tabindex="-1">
  801. <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
  802. </button>
  803. <h3>
  804. <span class="customize-action">
  805. <?php
  806. /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
  807. printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
  808. ?>
  809. </span>
  810. <?php _e( 'Add a Widget' ); ?>
  811. </h3>
  812. </div>
  813. <div id="available-widgets-filter">
  814. <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
  815. <input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ); ?>" aria-describedby="widgets-search-desc" />
  816. <div class="search-icon" aria-hidden="true"></div>
  817. <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
  818. <p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
  819. </div>
  820. <div id="available-widgets-list">
  821. <?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
  822. <div id="widget-tpl-<?php echo esc_attr( $available_widget['id'] ); ?>" data-widget-id="<?php echo esc_attr( $available_widget['id'] ); ?>" class="widget-tpl <?php echo esc_attr( $available_widget['id'] ); ?>" tabindex="0">
  823. <?php echo $available_widget['control_tpl']; ?>
  824. </div>
  825. <?php endforeach; ?>
  826. <p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
  827. </div><!-- #available-widgets-list -->
  828. </div><!-- #available-widgets -->
  829. </div><!-- #widgets-left -->
  830. <?php
  831. }
  832. /**
  833. * Calls admin_print_footer_scripts and admin_print_scripts hooks to
  834. * allow custom scripts from plugins.
  835. *
  836. * @since 3.9.0
  837. */
  838. public function print_footer_scripts() {
  839. /** This action is documented in wp-admin/admin-footer.php */
  840. do_action( 'admin_print_footer_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  841. /** This action is documented in wp-admin/admin-footer.php */
  842. do_action( 'admin_print_footer_scripts' );
  843. /** This action is documented in wp-admin/admin-footer.php */
  844. do_action( 'admin_footer-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  845. }
  846. /**
  847. * Retrieves common arguments to supply when constructing a Customizer setting.
  848. *
  849. * @since 3.9.0
  850. *
  851. * @param string $id Widget setting ID.
  852. * @param array $overrides Array of setting overrides.
  853. * @return array Possibly modified setting arguments.
  854. */
  855. public function get_setting_args( $id, $overrides = array() ) {
  856. $args = array(
  857. 'type' => 'option',
  858. 'capability' => 'edit_theme_options',
  859. 'default' => array(),
  860. );
  861. if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
  862. $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
  863. $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
  864. $args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
  865. } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
  866. $id_base = $matches['id_base'];
  867. $args['sanitize_callback'] = function( $value ) use ( $id_base ) {
  868. return $this->sanitize_widget_instance( $value, $id_base );
  869. };
  870. $args['sanitize_js_callback'] = function( $value ) use ( $id_base ) {
  871. return $this->sanitize_widget_js_instance( $value, $id_base );
  872. };
  873. $args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
  874. }
  875. $args = array_merge( $args, $overrides );
  876. /**
  877. * Filters the common arguments supplied when constructing a Customizer setting.
  878. *
  879. * @since 3.9.0
  880. *
  881. * @see WP_Customize_Setting
  882. *
  883. * @param array $args Array of Customizer setting arguments.
  884. * @param string $id Widget setting ID.
  885. */
  886. return apply_filters( 'widget_customizer_setting_args', $args, $id );
  887. }
  888. /**
  889. * Ensures sidebar widget arrays only ever contain widget IDS.
  890. *
  891. * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
  892. *
  893. * @since 3.9.0
  894. *
  895. * @param string[] $widget_ids Array of widget IDs.
  896. * @return string[] Array of sanitized widget IDs.
  897. */
  898. public function sanitize_sidebar_widgets( $widget_ids ) {
  899. $widget_ids = array_map( 'strval', (array) $widget_ids );
  900. $sanitized_widget_ids = array();
  901. foreach ( $widget_ids as $widget_id ) {
  902. $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
  903. }
  904. return $sanitized_widget_ids;
  905. }
  906. /**
  907. * Builds up an index of all available widgets for use in Backbone models.
  908. *
  909. * @since 3.9.0
  910. *
  911. * @global array $wp_registered_widgets
  912. * @global array $wp_registered_widget_controls
  913. *
  914. * @see wp_list_widgets()
  915. *
  916. * @return array List of available widgets.
  917. */
  918. public function get_available_widgets() {
  919. static $available_widgets = array();
  920. if ( ! empty( $available_widgets ) ) {
  921. return $available_widgets;
  922. }
  923. global $wp_registered_widgets, $wp_registered_widget_controls;
  924. require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
  925. $sort = $wp_registered_widgets;
  926. usort( $sort, array( $this, '_sort_name_callback' ) );
  927. $done = array();
  928. foreach ( $sort as $widget ) {
  929. if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget.
  930. continue;
  931. }
  932. $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
  933. $done[] = $widget['callback'];
  934. if ( ! isset( $widget['params'][0] ) ) {
  935. $widget['params'][0] = array();
  936. }
  937. $available_widget = $widget;
  938. unset( $available_widget['callback'] ); // Not serializable to JSON.
  939. $args = array(
  940. 'widget_id' => $widget['id'],
  941. 'widget_name' => $widget['name'],
  942. '_display' => 'template',
  943. );
  944. $is_disabled = false;
  945. $is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
  946. if ( $is_multi_widget ) {
  947. $id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
  948. $args['_temp_id'] = "$id_base-__i__";
  949. $args['_multi_num'] = next_widget_id_number( $id_base );
  950. $args['_add'] = 'multi';
  951. } else {
  952. $args['_add'] = 'single';
  953. if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
  954. $is_disabled = true;
  955. }
  956. $id_base = $widget['id'];
  957. }
  958. $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
  959. array(
  960. 0 => $args,
  961. 1 => $widget['params'][0],
  962. )
  963. );
  964. $control_tpl = $this->get_widget_control( $list_widget_controls_args );
  965. // The properties here are mapped to the Backbone Widget model.
  966. $available_widget = array_merge(
  967. $available_widget,
  968. array(
  969. 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
  970. 'is_multi' => $is_multi_widget,
  971. 'control_tpl' => $control_tpl,
  972. 'multi_number' => ( 'multi' === $args['_add'] ) ? $args['_multi_num'] : false,
  973. 'is_disabled' => $is_disabled,
  974. 'id_base' => $id_base,
  975. 'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
  976. 'width' => $wp_registered_widget_controls[ $widget['id'] ]['width'],
  977. 'height' => $wp_registered_widget_controls[ $widget['id'] ]['height'],
  978. 'is_wide' => $this->is_wide_widget( $widget['id'] ),
  979. )
  980. );
  981. $available_widgets[] = $available_widget;
  982. }
  983. return $available_widgets;
  984. }
  985. /**
  986. * Naturally orders available widgets by name.
  987. *
  988. * @since 3.9.0
  989. *
  990. * @param array $widget_a The first widget to compare.
  991. * @param array $widget_b The second widget to compare.
  992. * @return int Reorder position for the current widget comparison.
  993. */
  994. protected function _sort_name_callback( $widget_a, $widget_b ) {
  995. return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
  996. }
  997. /**
  998. * Retrieves the widget control markup.
  999. *
  1000. * @since 3.9.0
  1001. *
  1002. * @param array $args Widget control arguments.
  1003. * @return string Widget control form HTML markup.
  1004. */
  1005. public function get_widget_control( $args ) {
  1006. $args[0]['before_form'] = '<div class="form">';
  1007. $args[0]['after_form'] = '</div><!-- .form -->';
  1008. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1009. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1010. ob_start();
  1011. wp_widget_control( ...$args );
  1012. $control_tpl = ob_get_clean();
  1013. return $control_tpl;
  1014. }
  1015. /**
  1016. * Retrieves the widget control markup parts.
  1017. *
  1018. * @since 4.4.0
  1019. *
  1020. * @param array $args Widget control arguments.
  1021. * @return array {
  1022. * @type string $control Markup for widget control wrapping form.
  1023. * @type string $content The contents of the widget form itself.
  1024. * }
  1025. */
  1026. public function get_widget_control_parts( $args ) {
  1027. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1028. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1029. $control_markup = $this->get_widget_control( $args );
  1030. $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
  1031. $content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
  1032. $control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
  1033. $control .= substr( $control_markup, $content_end_pos );
  1034. $content = trim(
  1035. substr(
  1036. $control_markup,
  1037. $content_start_pos + strlen( $args[0]['before_widget_content'] ),
  1038. $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
  1039. )
  1040. );
  1041. return compact( 'control', 'content' );
  1042. }
  1043. /**
  1044. * Adds hooks for the Customizer preview.
  1045. *
  1046. * @since 3.9.0
  1047. */
  1048. public function customize_preview_init() {
  1049. add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
  1050. add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
  1051. add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
  1052. }
  1053. /**
  1054. * Refreshes the nonce for widget updates.
  1055. *
  1056. * @since 4.2.0
  1057. *
  1058. * @param array $nonces Array of nonces.
  1059. * @return array Array of nonces.
  1060. */
  1061. public function refresh_nonces( $nonces ) {
  1062. $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
  1063. return $nonces;
  1064. }
  1065. /**
  1066. * Tells the script loader to load the scripts and styles of custom blocks
  1067. * if the widgets block editor is enabled.
  1068. *
  1069. * @since 5.8.0
  1070. *
  1071. * @param bool $is_block_editor_screen Current decision about loading block assets.
  1072. * @return bool Filtered decision about loading block assets.
  1073. */
  1074. public function should_load_block_editor_scripts_and_styles( $is_block_editor_screen ) {
  1075. if ( wp_use_widgets_block_editor() ) {
  1076. return true;
  1077. }
  1078. return $is_block_editor_screen;
  1079. }
  1080. /**
  1081. * When previewing, ensures the proper previewing widgets are used.
  1082. *
  1083. * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
  1084. * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
  1085. * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
  1086. * filter is added, it has to be reset after the filter has been added.
  1087. *
  1088. * @since 3.9.0
  1089. *
  1090. * @param array $sidebars_widgets List of widgets for the current sidebar.
  1091. * @return array
  1092. */
  1093. public function preview_sidebars_widgets( $sidebars_widgets ) {
  1094. $sidebars_widgets = get_option( 'sidebars_widgets', array() );
  1095. unset( $sidebars_widgets['array_version'] );
  1096. return $sidebars_widgets;
  1097. }
  1098. /**
  1099. * Enqueues scripts for the Customizer preview.
  1100. *
  1101. * @since 3.9.0
  1102. */
  1103. public function customize_preview_enqueue() {
  1104. wp_enqueue_script( 'customize-preview-widgets' );
  1105. }
  1106. /**
  1107. * Inserts default style for highlighted widget at early point so theme
  1108. * stylesheet can override.
  1109. *
  1110. * @since 3.9.0
  1111. */
  1112. public function print_preview_css() {
  1113. ?>
  1114. <style>
  1115. .widget-customizer-highlighted-widget {
  1116. outline: none;
  1117. -webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1118. box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1119. position: relative;
  1120. z-index: 1;
  1121. }
  1122. </style>
  1123. <?php
  1124. }
  1125. /**
  1126. * Communicates the sidebars that appeared on the page at the very end of the page,
  1127. * and at the very end of the wp_footer,
  1128. *
  1129. * @since 3.9.0
  1130. *
  1131. * @global array $wp_registered_sidebars
  1132. * @global array $wp_registered_widgets
  1133. */
  1134. public function export_preview_data() {
  1135. global $wp_registered_sidebars, $wp_registered_widgets;
  1136. $switched_locale = switch_to_locale( get_user_locale() );
  1137. $l10n = array(
  1138. 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
  1139. );
  1140. if ( $switched_locale ) {
  1141. restore_previous_locale();
  1142. }
  1143. $rendered_sidebars = array_filter( $this->rendered_sidebars );
  1144. $rendered_widgets = array_filter( $this->rendered_widgets );
  1145. // Prepare Customizer settings to pass to JavaScript.
  1146. $settings = array(
  1147. 'renderedSidebars' => array_fill_keys( array_keys( $rendered_sidebars ), true ),
  1148. 'renderedWidgets' => array_fill_keys( array_keys( $rendered_widgets ), true ),
  1149. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  1150. 'registeredWidgets' => $wp_registered_widgets,
  1151. 'l10n' => $l10n,
  1152. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  1153. );
  1154. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  1155. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  1156. }
  1157. ?>
  1158. <script type="text/javascript">
  1159. var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
  1160. </script>
  1161. <?php
  1162. }
  1163. /**
  1164. * Tracks the widgets that were rendered.
  1165. *
  1166. * @since 3.9.0
  1167. *
  1168. * @param array $widget Rendered widget to tally.
  1169. */
  1170. public function tally_rendered_widgets( $widget ) {
  1171. $this->rendered_widgets[ $widget['id'] ] = true;
  1172. }
  1173. /**
  1174. * Determine if a widget is rendered on the page.
  1175. *
  1176. * @since 4.0.0
  1177. *
  1178. * @param string $widget_id Widget ID to check.
  1179. * @return bool Whether the widget is rendered.
  1180. */
  1181. public function is_widget_rendered( $widget_id ) {
  1182. return ! empty( $this->rendered_widgets[ $widget_id ] );
  1183. }
  1184. /**
  1185. * Determines if a sidebar is rendered on the page.
  1186. *
  1187. * @since 4.0.0
  1188. *
  1189. * @param string $sidebar_id Sidebar ID to check.
  1190. * @return bool Whether the sidebar is rendered.
  1191. */
  1192. public function is_sidebar_rendered( $sidebar_id ) {
  1193. return ! empty( $this->rendered_sidebars[ $sidebar_id ] );
  1194. }
  1195. /**
  1196. * Tallies the sidebars rendered via is_active_sidebar().
  1197. *
  1198. * Keep track of the times that is_active_sidebar() is called in the template,
  1199. * and assume that this means that the sidebar would be rendered on the template
  1200. * if there were widgets populating it.
  1201. *
  1202. * @since 3.9.0
  1203. *
  1204. * @param bool $is_active Whether the sidebar is active.
  1205. * @param string $sidebar_id Sidebar ID.
  1206. * @return bool Whether the sidebar is active.
  1207. */
  1208. public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
  1209. if ( is_registered_sidebar( $sidebar_id ) ) {
  1210. $this->rendered_sidebars[ $sidebar_id ] = true;
  1211. }
  1212. /*
  1213. * We may need to force this to true, and also force-true the value
  1214. * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
  1215. * is an area to drop widgets into, if the sidebar is empty.
  1216. */
  1217. return $is_active;
  1218. }
  1219. /**
  1220. * Tallies the sidebars rendered via dynamic_sidebar().
  1221. *
  1222. * Keep track of the times that dynamic_sidebar() is called in the template,
  1223. * and assume this means the sidebar would be rendered on the template if
  1224. * there were widgets populating it.
  1225. *
  1226. * @since 3.9.0
  1227. *
  1228. * @param bool $has_widgets Whether the current sidebar has widgets.
  1229. * @param string $sidebar_id Sidebar ID.
  1230. * @return bool Whether the current sidebar has widgets.
  1231. */
  1232. public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
  1233. if ( is_registered_sidebar( $sidebar_id ) ) {
  1234. $this->rendered_sidebars[ $sidebar_id ] = true;
  1235. }
  1236. /*
  1237. * We may need to force this to true, and also force-true the value
  1238. * for 'is_active_sidebar' if we want to ensure there is an area to
  1239. * drop widgets into, if the sidebar is empty.
  1240. */
  1241. return $has_widgets;
  1242. }
  1243. /**
  1244. * Retrieves MAC for a serialized widget instance string.
  1245. *
  1246. * Allows values posted back from JS to be rejected if any tampering of the
  1247. * data has occurred.
  1248. *
  1249. * @since 3.9.0
  1250. *
  1251. * @param string $serialized_instance Widget instance.
  1252. * @return string MAC for serialized widget instance.
  1253. */
  1254. protected function get_instance_hash_key( $serialized_instance ) {
  1255. return wp_hash( $serialized_instance );
  1256. }
  1257. /**
  1258. * Sanitizes a widget instance.
  1259. *
  1260. * Unserialize the JS-instance for storing in the options. It's important that this filter
  1261. * only get applied to an instance *once*.
  1262. *
  1263. * @since 3.9.0
  1264. * @since 5.8.0 Added the `$id_base` parameter.
  1265. *
  1266. * @global WP_Widget_Factory $wp_widget_factory
  1267. *
  1268. * @param array $value Widget instance to sanitize.
  1269. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1270. * @return array|void Sanitized widget instance.
  1271. */
  1272. public function sanitize_widget_instance( $value, $id_base = null ) {
  1273. global $wp_widget_factory;
  1274. if ( array() === $value ) {
  1275. return $value;
  1276. }
  1277. if ( isset( $value['raw_instance'] ) && $id_base && wp_use_widgets_block_editor() ) {
  1278. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1279. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1280. if ( 'block' === $id_base && ! current_user_can( 'unfiltered_html' ) ) {
  1281. /*
  1282. * The content of the 'block' widget is not filtered on the fly while editing.
  1283. * Filter the content here to prevent vulnerabilities.
  1284. */
  1285. $value['raw_instance']['content'] = wp_kses_post( $value['raw_instance']['content'] );
  1286. }
  1287. return $value['raw_instance'];
  1288. }
  1289. }
  1290. if (
  1291. empty( $value['is_widget_customizer_js_value'] ) ||
  1292. empty( $value['instance_hash_key'] ) ||
  1293. empty( $value['encoded_serialized_instance'] )
  1294. ) {
  1295. return;
  1296. }
  1297. $decoded = base64_decode( $value['encoded_serialized_instance'], true );
  1298. if ( false === $decoded ) {
  1299. return;
  1300. }
  1301. if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
  1302. return;
  1303. }
  1304. $instance = unserialize( $decoded );
  1305. if ( false === $instance ) {
  1306. return;
  1307. }
  1308. return $instance;
  1309. }
  1310. /**
  1311. * Converts a widget instance into JSON-representable format.
  1312. *
  1313. * @since 3.9.0
  1314. * @since 5.8.0 Added the `$id_base` parameter.
  1315. *
  1316. * @global WP_Widget_Factory $wp_widget_factory
  1317. *
  1318. * @param array $value Widget instance to convert to JSON.
  1319. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1320. * @return array JSON-converted widget instance.
  1321. */
  1322. public function sanitize_widget_js_instance( $value, $id_base = null ) {
  1323. global $wp_widget_factory;
  1324. if ( empty( $value['is_widget_customizer_js_value'] ) ) {
  1325. $serialized = serialize( $value );
  1326. $js_value = array(
  1327. 'encoded_serialized_instance' => base64_encode( $serialized ),
  1328. 'title' => empty( $value['title'] ) ? '' : $value['title'],
  1329. 'is_widget_customizer_js_value' => true,
  1330. 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
  1331. );
  1332. if ( $id_base && wp_use_widgets_block_editor() ) {
  1333. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1334. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1335. $js_value['raw_instance'] = (object) $value;
  1336. }
  1337. }
  1338. return $js_value;
  1339. }
  1340. return $value;
  1341. }
  1342. /**
  1343. * Strips out widget IDs for widgets which are no longer registered.
  1344. *
  1345. * One example where this might happen is when a plugin orphans a widget
  1346. * in a sidebar upon deactivation.
  1347. *
  1348. * @since 3.9.0
  1349. *
  1350. * @global array $wp_registered_widgets
  1351. *
  1352. * @param array $widget_ids List of widget IDs.
  1353. * @return array Parsed list of widget IDs.
  1354. */
  1355. public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
  1356. global $wp_registered_widgets;
  1357. $widget_ids = array_values( array_intersect( $widget_ids, array_keys( $wp_registered_widgets ) ) );
  1358. return $widget_ids;
  1359. }
  1360. /**
  1361. * Finds and invokes the widget update and control callbacks.
  1362. *
  1363. * Requires that `$_POST` be populated with the instance data.
  1364. *
  1365. * @since 3.9.0
  1366. *
  1367. * @global array $wp_registered_widget_updates
  1368. * @global array $wp_registered_widget_controls
  1369. *
  1370. * @param string $widget_id Widget ID.
  1371. * @return array|WP_Error Array containing the updated widget information.
  1372. * A WP_Error object, otherwise.
  1373. */
  1374. public function call_widget_update( $widget_id ) {
  1375. global $wp_registered_widget_updates, $wp_registered_widget_controls;
  1376. $setting_id = $this->get_setting_id( $widget_id );
  1377. /*
  1378. * Make sure that other setting changes have previewed since this widget
  1379. * may depend on them (e.g. Menus being present for Navigation Menu widget).
  1380. */
  1381. if ( ! did_action( 'customize_preview_init' ) ) {
  1382. foreach ( $this->manager->settings() as $setting ) {
  1383. if ( $setting->id !== $setting_id ) {
  1384. $setting->preview();
  1385. }
  1386. }
  1387. }
  1388. $this->start_capturing_option_updates();
  1389. $parsed_id = $this->parse_widget_id( $widget_id );
  1390. $option_name = 'widget_' . $parsed_id['id_base'];
  1391. /*
  1392. * If a previously-sanitized instance is provided, populate the input vars
  1393. * with its values so that the widget update callback will read this instance
  1394. */
  1395. $added_input_vars = array();
  1396. if ( ! empty( $_POST['sanitized_widget_setting'] ) ) {
  1397. $sanitized_widget_setting = json_decode( $this->get_post_value( 'sanitized_widget_setting' ), true );
  1398. if ( false === $sanitized_widget_setting ) {
  1399. $this->stop_capturing_option_updates();
  1400. return new WP_Error( 'widget_setting_malformed' );
  1401. }
  1402. $instance = $this->sanitize_widget_instance( $sanitized_widget_setting, $parsed_id['id_base'] );
  1403. if ( is_null( $instance ) ) {
  1404. $this->stop_capturing_option_updates();
  1405. return new WP_Error( 'widget_setting_unsanitized' );
  1406. }
  1407. if ( ! is_null( $parsed_id['number'] ) ) {
  1408. $value = array();
  1409. $value[ $parsed_id['number'] ] = $instance;
  1410. $key = 'widget-' . $parsed_id['id_base'];
  1411. $_REQUEST[ $key ] = wp_slash( $value );
  1412. $_POST[ $key ] = $_REQUEST[ $key ];
  1413. $added_input_vars[] = $key;
  1414. } else {
  1415. foreach ( $instance as $key => $value ) {
  1416. $_REQUEST[ $key ] = wp_slash( $value );
  1417. $_POST[ $key ] = $_REQUEST[ $key ];
  1418. $added_input_vars[] = $key;
  1419. }
  1420. }
  1421. }
  1422. // Invoke the widget update callback.
  1423. foreach ( (array) $wp_registered_widget_updates as $name => $control ) {
  1424. if ( $name === $parsed_id['id_base'] && is_callable( $control['callback'] ) ) {
  1425. ob_start();
  1426. call_user_func_array( $control['callback'], $control['params'] );
  1427. ob_end_clean();
  1428. break;
  1429. }
  1430. }
  1431. // Clean up any input vars that were manually added.
  1432. foreach ( $added_input_vars as $key ) {
  1433. unset( $_POST[ $key ] );
  1434. unset( $_REQUEST[ $key ] );
  1435. }
  1436. // Make sure the expected option was updated.
  1437. if ( 0 !== $this->count_captured_options() ) {
  1438. if ( $this->count_captured_options() > 1 ) {
  1439. $this->stop_capturing_option_updates();
  1440. return new WP_Error( 'widget_setting_too_many_options' );
  1441. }
  1442. $updated_option_name = key( $this->get_captured_options() );
  1443. if ( $updated_option_name !== $option_name ) {
  1444. $this->stop_capturing_option_updates();
  1445. return new WP_Error( 'widget_setting_unexpected_option' );
  1446. }
  1447. }
  1448. // Obtain the widget instance.
  1449. $option = $this->get_captured_option( $option_name );
  1450. if ( null !== $parsed_id['number'] ) {
  1451. $instance = $option[ $parsed_id['number'] ];
  1452. } else {
  1453. $instance = $option;
  1454. }
  1455. /*
  1456. * Override the incoming $_POST['customized'] for a newly-created widget's
  1457. * setting with the new $instance so that the preview filter currently
  1458. * in place from WP_Customize_Setting::preview() will use this value
  1459. * instead of the default widget instance value (an empty array).
  1460. */
  1461. $this->manager->set_post_value( $setting_id, $this->sanitize_widget_js_instance( $instance, $parsed_id['id_base'] ) );
  1462. // Obtain the widget control with the updated instance in place.
  1463. ob_start();
  1464. $form = $wp_registered_widget_controls[ $widget_id ];
  1465. if ( $form ) {
  1466. call_user_func_array( $form['callback'], $form['params'] );
  1467. }
  1468. $form = ob_get_clean();
  1469. $this->stop_capturing_option_updates();
  1470. return compact( 'instance', 'form' );
  1471. }
  1472. /**
  1473. * Updates widget settings asynchronously.
  1474. *
  1475. * Allows the Customizer to update a widget using its form, but return the new
  1476. * instance info via Ajax instead of saving it to the options table.
  1477. *
  1478. * Most code here copied from wp_ajax_save_widget().
  1479. *
  1480. * @since 3.9.0
  1481. *
  1482. * @see wp_ajax_save_widget()
  1483. */
  1484. public function wp_ajax_update_widget() {
  1485. if ( ! is_user_logged_in() ) {
  1486. wp_die( 0 );
  1487. }
  1488. check_ajax_referer( 'update-widget', 'nonce' );
  1489. if ( ! current_user_can( 'edit_theme_options' ) ) {
  1490. wp_die( -1 );
  1491. }
  1492. if ( empty( $_POST['widget-id'] ) ) {
  1493. wp_send_json_error( 'missing_widget-id' );
  1494. }
  1495. /** This action is documented in wp-admin/includes/ajax-actions.php */
  1496. do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  1497. /** This action is documented in wp-admin/includes/ajax-actions.php */
  1498. do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  1499. /** This action is documented in wp-admin/widgets.php */
  1500. do_action( 'sidebar_admin_setup' );
  1501. $widget_id = $this->get_post_value( 'widget-id' );
  1502. $parsed_id = $this->parse_widget_id( $widget_id );
  1503. $id_base = $parsed_id['id_base'];
  1504. $is_updating_widget_template = (
  1505. isset( $_POST[ 'widget-' . $id_base ] )
  1506. &&
  1507. is_array( $_POST[ 'widget-' . $id_base ] )
  1508. &&
  1509. preg_match( '/__i__|%i%/', key( $_POST[ 'widget-' . $id_base ] ) )
  1510. );
  1511. if ( $is_updating_widget_template ) {
  1512. wp_send_json_error( 'template_widget_not_updatable' );
  1513. }
  1514. $updated_widget = $this->call_widget_update( $widget_id ); // => {instance,form}
  1515. if ( is_wp_error( $updated_widget ) ) {
  1516. wp_send_json_error( $updated_widget->get_error_code() );
  1517. }
  1518. $form = $updated_widget['form'];
  1519. $instance = $this->sanitize_widget_js_instance( $updated_widget['instance'], $id_base );
  1520. wp_send_json_success( compact( 'form', 'instance' ) );
  1521. }
  1522. /*
  1523. * Selective Refresh Methods
  1524. */
  1525. /**
  1526. * Filters arguments for dynamic widget partials.
  1527. *
  1528. * @since 4.5.0
  1529. *
  1530. * @param array|false $partial_args Partial arguments.
  1531. * @param string $partial_id Partial ID.
  1532. * @return array (Maybe) modified partial arguments.
  1533. */
  1534. public function customize_dynamic_partial_args( $partial_args, $partial_id ) {
  1535. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  1536. return $partial_args;
  1537. }
  1538. if ( preg_match( '/^widget\[(?P<widget_id>.+)\]$/', $partial_id, $matches ) ) {
  1539. if ( false === $partial_args ) {
  1540. $partial_args = array();
  1541. }
  1542. $partial_args = array_merge(
  1543. $partial_args,
  1544. array(
  1545. 'type' => 'widget',
  1546. 'render_callback' => array( $this, 'render_widget_partial' ),
  1547. 'container_inclusive' => true,
  1548. 'settings' => array( $this->get_setting_id( $matches['widget_id'] ) ),
  1549. 'capability' => 'edit_theme_options',
  1550. )
  1551. );
  1552. }
  1553. return $partial_args;
  1554. }
  1555. /**
  1556. * Adds hooks for selective refresh.
  1557. *
  1558. * @since 4.5.0
  1559. */
  1560. public function selective_refresh_init() {
  1561. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  1562. return;
  1563. }
  1564. add_filter( 'dynamic_sidebar_params', array( $this, 'filter_dynamic_sidebar_params' ) );
  1565. add_filter( 'wp_kses_allowed_html', array( $this, 'filter_wp_kses_allowed_data_attributes' ) );
  1566. add_action( 'dynamic_sidebar_before', array( $this, 'start_dynamic_sidebar' ) );
  1567. add_action( 'dynamic_sidebar_after', array( $this, 'end_dynamic_sidebar' ) );
  1568. }
  1569. /**
  1570. * Inject selective refresh data attributes into widget container elements.
  1571. *
  1572. * @since 4.5.0
  1573. *
  1574. * @param array $params {
  1575. * Dynamic sidebar params.
  1576. *
  1577. * @type array $args Sidebar args.
  1578. * @type array $widget_args Widget args.
  1579. * }
  1580. * @see WP_Customize_Nav_Menus::filter_wp_nav_menu_args()
  1581. *
  1582. * @return array Params.
  1583. */
  1584. public function filter_dynamic_sidebar_params( $params ) {
  1585. $sidebar_args = array_merge(
  1586. array(
  1587. 'before_widget' => '',
  1588. 'after_widget' => '',
  1589. ),
  1590. $params[0]
  1591. );
  1592. // Skip widgets not in a registered sidebar or ones which lack a proper wrapper element to attach the data-* attributes to.
  1593. $matches = array();
  1594. $is_valid = (
  1595. isset( $sidebar_args['id'] )
  1596. &&
  1597. is_registered_sidebar( $sidebar_args['id'] )
  1598. &&
  1599. ( isset( $this->current_dynamic_sidebar_id_stack[0] ) && $this->current_dynamic_sidebar_id_stack[0] === $sidebar_args['id'] )
  1600. &&
  1601. preg_match( '#^<(?P<tag_name>\w+)#', $sidebar_args['before_widget'], $matches )
  1602. );
  1603. if ( ! $is_valid ) {
  1604. return $params;
  1605. }
  1606. $this->before_widget_tags_seen[ $matches['tag_name'] ] = true;
  1607. $context = array(
  1608. 'sidebar_id' => $sidebar_args['id'],
  1609. );
  1610. if ( isset( $this->context_sidebar_instance_number ) ) {
  1611. $context['sidebar_instance_number'] = $this->context_sidebar_instance_number;
  1612. } elseif ( isset( $sidebar_args['id'] ) && isset( $this->sidebar_instance_count[ $sidebar_args['id'] ] ) ) {
  1613. $context['sidebar_instance_number'] = $this->sidebar_instance_count[ $sidebar_args['id'] ];
  1614. }
  1615. $attributes = sprintf( ' data-customize-partial-id="%s"', esc_attr( 'widget[' . $sidebar_args['widget_id'] . ']' ) );
  1616. $attributes .= ' data-customize-partial-type="widget"';
  1617. $attributes .= sprintf( ' data-customize-partial-placement-context="%s"', esc_attr( wp_json_encode( $context ) ) );
  1618. $attributes .= sprintf( ' data-customize-widget-id="%s"', esc_attr( $sidebar_args['widget_id'] ) );
  1619. $sidebar_args['before_widget'] = preg_replace( '#^(<\w+)#', '$1 ' . $attributes, $sidebar_args['before_widget'] );
  1620. $params[0] = $sidebar_args;
  1621. return $params;
  1622. }
  1623. /**
  1624. * List of the tag names seen for before_widget strings.
  1625. *
  1626. * This is used in the {@see 'filter_wp_kses_allowed_html'} filter to ensure that the
  1627. * data-* attributes can be allowed.
  1628. *
  1629. * @since 4.5.0
  1630. * @var array
  1631. */
  1632. protected $before_widget_tags_seen = array();
  1633. /**
  1634. * Ensures the HTML data-* attributes for selective refresh are allowed by kses.
  1635. *
  1636. * This is needed in case the `$before_widget` is run through wp_kses() when printed.
  1637. *
  1638. * @since 4.5.0
  1639. *
  1640. * @param array $allowed_html Allowed HTML.
  1641. * @return array (Maybe) modified allowed HTML.
  1642. */
  1643. public function filter_wp_kses_allowed_data_attributes( $allowed_html ) {
  1644. foreach ( array_keys( $this->before_widget_tags_seen ) as $tag_name ) {
  1645. if ( ! isset( $allowed_html[ $tag_name ] ) ) {
  1646. $allowed_html[ $tag_name ] = array();
  1647. }
  1648. $allowed_html[ $tag_name ] = array_merge(
  1649. $allowed_html[ $tag_name ],
  1650. array_fill_keys(
  1651. array(
  1652. 'data-customize-partial-id',
  1653. 'data-customize-partial-type',
  1654. 'data-customize-partial-placement-context',
  1655. 'data-customize-partial-widget-id',
  1656. 'data-customize-partial-options',
  1657. ),
  1658. true
  1659. )
  1660. );
  1661. }
  1662. return $allowed_html;
  1663. }
  1664. /**
  1665. * Keep track of the number of times that dynamic_sidebar() was called for a given sidebar index.
  1666. *
  1667. * This helps facilitate the uncommon scenario where a single sidebar is rendered multiple times on a template.
  1668. *
  1669. * @since 4.5.0
  1670. * @var array
  1671. */
  1672. protected $sidebar_instance_count = array();
  1673. /**
  1674. * The current request's sidebar_instance_number context.
  1675. *
  1676. * @since 4.5.0
  1677. * @var int|null
  1678. */
  1679. protected $context_sidebar_instance_number;
  1680. /**
  1681. * Current sidebar ID being rendered.
  1682. *
  1683. * @since 4.5.0
  1684. * @var array
  1685. */
  1686. protected $current_dynamic_sidebar_id_stack = array();
  1687. /**
  1688. * Begins keeping track of the current sidebar being rendered.
  1689. *
  1690. * Insert marker before widgets are rendered in a dynamic sidebar.
  1691. *
  1692. * @since 4.5.0
  1693. *
  1694. * @param int|string $index Index, name, or ID of the dynamic sidebar.
  1695. */
  1696. public function start_dynamic_sidebar( $index ) {
  1697. array_unshift( $this->current_dynamic_sidebar_id_stack, $index );
  1698. if ( ! isset( $this->sidebar_instance_count[ $index ] ) ) {
  1699. $this->sidebar_instance_count[ $index ] = 0;
  1700. }
  1701. $this->sidebar_instance_count[ $index ] += 1;
  1702. if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
  1703. printf( "\n<!--dynamic_sidebar_before:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
  1704. }
  1705. }
  1706. /**
  1707. * Finishes keeping track of the current sidebar being rendered.
  1708. *
  1709. * Inserts a marker after widgets are rendered in a dynamic sidebar.
  1710. *
  1711. * @since 4.5.0
  1712. *
  1713. * @param int|string $index Index, name, or ID of the dynamic sidebar.
  1714. */
  1715. public function end_dynamic_sidebar( $index ) {
  1716. array_shift( $this->current_dynamic_sidebar_id_stack );
  1717. if ( ! $this->manager->selective_refresh->is_render_partials_request() ) {
  1718. printf( "\n<!--dynamic_sidebar_after:%s:%d-->\n", esc_html( $index ), (int) $this->sidebar_instance_count[ $index ] );
  1719. }
  1720. }
  1721. /**
  1722. * Current sidebar being rendered.
  1723. *
  1724. * @since 4.5.0
  1725. * @var string|null
  1726. */
  1727. protected $rendering_widget_id;
  1728. /**
  1729. * Current widget being rendered.
  1730. *
  1731. * @since 4.5.0
  1732. * @var string|null
  1733. */
  1734. protected $rendering_sidebar_id;
  1735. /**
  1736. * Filters sidebars_widgets to ensure the currently-rendered widget is the only widget in the current sidebar.
  1737. *
  1738. * @since 4.5.0
  1739. *
  1740. * @param array $sidebars_widgets Sidebars widgets.
  1741. * @return array Filtered sidebars widgets.
  1742. */
  1743. public function filter_sidebars_widgets_for_rendering_widget( $sidebars_widgets ) {
  1744. $sidebars_widgets[ $this->rendering_sidebar_id ] = array( $this->rendering_widget_id );
  1745. return $sidebars_widgets;
  1746. }
  1747. /**
  1748. * Renders a specific widget using the supplied sidebar arguments.
  1749. *
  1750. * @since 4.5.0
  1751. *
  1752. * @see dynamic_sidebar()
  1753. *
  1754. * @param WP_Customize_Partial $partial Partial.
  1755. * @param array $context {
  1756. * Sidebar args supplied as container context.
  1757. *
  1758. * @type string $sidebar_id ID for sidebar for widget to render into.
  1759. * @type int $sidebar_instance_number Disambiguating instance number.
  1760. * }
  1761. * @return string|false
  1762. */
  1763. public function render_widget_partial( $partial, $context ) {
  1764. $id_data = $partial->id_data();
  1765. $widget_id = array_shift( $id_data['keys'] );
  1766. if ( ! is_array( $context )
  1767. || empty( $context['sidebar_id'] )
  1768. || ! is_registered_sidebar( $context['sidebar_id'] )
  1769. ) {
  1770. return false;
  1771. }
  1772. $this->rendering_sidebar_id = $context['sidebar_id'];
  1773. if ( isset( $context['sidebar_instance_number'] ) ) {
  1774. $this->context_sidebar_instance_number = (int) $context['sidebar_instance_number'];
  1775. }
  1776. // Filter sidebars_widgets so that only the queried widget is in the sidebar.
  1777. $this->rendering_widget_id = $widget_id;
  1778. $filter_callback = array( $this, 'filter_sidebars_widgets_for_rendering_widget' );
  1779. add_filter( 'sidebars_widgets', $filter_callback, 1000 );
  1780. // Render the widget.
  1781. ob_start();
  1782. $this->rendering_sidebar_id = $context['sidebar_id'];
  1783. dynamic_sidebar( $this->rendering_sidebar_id );
  1784. $container = ob_get_clean();
  1785. // Reset variables for next partial render.
  1786. remove_filter( 'sidebars_widgets', $filter_callback, 1000 );
  1787. $this->context_sidebar_instance_number = null;
  1788. $this->rendering_sidebar_id = null;
  1789. $this->rendering_widget_id = null;
  1790. return $container;
  1791. }
  1792. //
  1793. // Option Update Capturing.
  1794. //
  1795. /**
  1796. * List of captured widget option updates.
  1797. *
  1798. * @since 3.9.0
  1799. * @var array $_captured_options Values updated while option capture is happening.
  1800. */
  1801. protected $_captured_options = array();
  1802. /**
  1803. * Whether option capture is currently happening.
  1804. *
  1805. * @since 3.9.0
  1806. * @var bool $_is_current Whether option capture is currently happening or not.
  1807. */
  1808. protected $_is_capturing_option_updates = false;
  1809. /**
  1810. * Determines whether the captured option update should be ignored.
  1811. *
  1812. * @since 3.9.0
  1813. *
  1814. * @param string $option_name Option name.
  1815. * @return bool Whether the option capture is ignored.
  1816. */
  1817. protected function is_option_capture_ignored( $option_name ) {
  1818. return ( 0 === strpos( $option_name, '_transient_' ) );
  1819. }
  1820. /**
  1821. * Retrieves captured widget option updates.
  1822. *
  1823. * @since 3.9.0
  1824. *
  1825. * @return array Array of captured options.
  1826. */
  1827. protected function get_captured_options() {
  1828. return $this->_captured_options;
  1829. }
  1830. /**
  1831. * Retrieves the option that was captured from being saved.
  1832. *
  1833. * @since 4.2.0
  1834. *
  1835. * @param string $option_name Option name.
  1836. * @param mixed $default_value Optional. Default value to return if the option does not exist. Default false.
  1837. * @return mixed Value set for the option.
  1838. */
  1839. protected function get_captured_option( $option_name, $default_value = false ) {
  1840. if ( array_key_exists( $option_name, $this->_captured_options ) ) {
  1841. $value = $this->_captured_options[ $option_name ];
  1842. } else {
  1843. $value = $default_value;
  1844. }
  1845. return $value;
  1846. }
  1847. /**
  1848. * Retrieves the number of captured widget option updates.
  1849. *
  1850. * @since 3.9.0
  1851. *
  1852. * @return int Number of updated options.
  1853. */
  1854. protected function count_captured_options() {
  1855. return count( $this->_captured_options );
  1856. }
  1857. /**
  1858. * Begins keeping track of changes to widget options, caching new values.
  1859. *
  1860. * @since 3.9.0
  1861. */
  1862. protected function start_capturing_option_updates() {
  1863. if ( $this->_is_capturing_option_updates ) {
  1864. return;
  1865. }
  1866. $this->_is_capturing_option_updates = true;
  1867. add_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10, 3 );
  1868. }
  1869. /**
  1870. * Pre-filters captured option values before updating.
  1871. *
  1872. * @since 3.9.0
  1873. *
  1874. * @param mixed $new_value The new option value.
  1875. * @param string $option_name Name of the option.
  1876. * @param mixed $old_value The old option value.
  1877. * @return mixed Filtered option value.
  1878. */
  1879. public function capture_filter_pre_update_option( $new_value, $option_name, $old_value ) {
  1880. if ( $this->is_option_capture_ignored( $option_name ) ) {
  1881. return $new_value;
  1882. }
  1883. if ( ! isset( $this->_captured_options[ $option_name ] ) ) {
  1884. add_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
  1885. }
  1886. $this->_captured_options[ $option_name ] = $new_value;
  1887. return $old_value;
  1888. }
  1889. /**
  1890. * Pre-filters captured option values before retrieving.
  1891. *
  1892. * @since 3.9.0
  1893. *
  1894. * @param mixed $value Value to return instead of the option value.
  1895. * @return mixed Filtered option value.
  1896. */
  1897. public function capture_filter_pre_get_option( $value ) {
  1898. $option_name = preg_replace( '/^pre_option_/', '', current_filter() );
  1899. if ( isset( $this->_captured_options[ $option_name ] ) ) {
  1900. $value = $this->_captured_options[ $option_name ];
  1901. /** This filter is documented in wp-includes/option.php */
  1902. $value = apply_filters( 'option_' . $option_name, $value, $option_name );
  1903. }
  1904. return $value;
  1905. }
  1906. /**
  1907. * Undoes any changes to the options since options capture began.
  1908. *
  1909. * @since 3.9.0
  1910. */
  1911. protected function stop_capturing_option_updates() {
  1912. if ( ! $this->_is_capturing_option_updates ) {
  1913. return;
  1914. }
  1915. remove_filter( 'pre_update_option', array( $this, 'capture_filter_pre_update_option' ), 10 );
  1916. foreach ( array_keys( $this->_captured_options ) as $option_name ) {
  1917. remove_filter( "pre_option_{$option_name}", array( $this, 'capture_filter_pre_get_option' ) );
  1918. }
  1919. $this->_captured_options = array();
  1920. $this->_is_capturing_option_updates = false;
  1921. }
  1922. /**
  1923. * {@internal Missing Summary}
  1924. *
  1925. * See the {@see 'customize_dynamic_setting_args'} filter.
  1926. *
  1927. * @since 3.9.0
  1928. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1929. */
  1930. public function setup_widget_addition_previews() {
  1931. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1932. }
  1933. /**
  1934. * {@internal Missing Summary}
  1935. *
  1936. * See the {@see 'customize_dynamic_setting_args'} filter.
  1937. *
  1938. * @since 3.9.0
  1939. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1940. */
  1941. public function prepreview_added_sidebars_widgets() {
  1942. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1943. }
  1944. /**
  1945. * {@internal Missing Summary}
  1946. *
  1947. * See the {@see 'customize_dynamic_setting_args'} filter.
  1948. *
  1949. * @since 3.9.0
  1950. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1951. */
  1952. public function prepreview_added_widget_instance() {
  1953. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1954. }
  1955. /**
  1956. * {@internal Missing Summary}
  1957. *
  1958. * See the {@see 'customize_dynamic_setting_args'} filter.
  1959. *
  1960. * @since 3.9.0
  1961. * @deprecated 4.2.0 Deprecated in favor of the {@see 'customize_dynamic_setting_args'} filter.
  1962. */
  1963. public function remove_prepreview_filters() {
  1964. _deprecated_function( __METHOD__, '4.2.0', 'customize_dynamic_setting_args' );
  1965. }
  1966. }