PageRenderTime 68ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/class-wp-customize-widgets.php

https://github.com/markjaquith/WordPress
PHP | 2207 lines | 1107 code | 246 blank | 854 comment | 113 complexity | 7b4419bed7b3eeaf7f629861d2dbaa5e MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  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. final class WP_Customize_Widgets {
  19. /**
  20. * WP_Customize_Manager instance.
  21. *
  22. * @since 3.9.0
  23. * @var WP_Customize_Manager
  24. */
  25. public $manager;
  26. /**
  27. * All id_bases for widgets defined in core.
  28. *
  29. * @since 3.9.0
  30. * @var array
  31. */
  32. protected $core_widget_id_bases = array(
  33. 'archives',
  34. 'calendar',
  35. 'categories',
  36. 'custom_html',
  37. 'links',
  38. 'media_audio',
  39. 'media_image',
  40. 'media_video',
  41. 'meta',
  42. 'nav_menu',
  43. 'pages',
  44. 'recent-comments',
  45. 'recent-posts',
  46. 'rss',
  47. 'search',
  48. 'tag_cloud',
  49. 'text',
  50. );
  51. /**
  52. * @since 3.9.0
  53. * @var array
  54. */
  55. protected $rendered_sidebars = array();
  56. /**
  57. * @since 3.9.0
  58. * @var array
  59. */
  60. protected $rendered_widgets = array();
  61. /**
  62. * @since 3.9.0
  63. * @var array
  64. */
  65. protected $old_sidebars_widgets = array();
  66. /**
  67. * Mapping of widget ID base to whether it supports selective refresh.
  68. *
  69. * @since 4.5.0
  70. * @var array
  71. */
  72. protected $selective_refreshable_widgets;
  73. /**
  74. * Mapping of setting type to setting ID pattern.
  75. *
  76. * @since 4.2.0
  77. * @var array
  78. */
  79. protected $setting_id_patterns = array(
  80. 'widget_instance' => '/^widget_(?P<id_base>.+?)(?:\[(?P<widget_number>\d+)\])?$/',
  81. 'sidebar_widgets' => '/^sidebars_widgets\[(?P<sidebar_id>.+?)\]$/',
  82. );
  83. /**
  84. * Initial loader.
  85. *
  86. * @since 3.9.0
  87. *
  88. * @param WP_Customize_Manager $manager Customizer bootstrap instance.
  89. */
  90. public function __construct( $manager ) {
  91. $this->manager = $manager;
  92. // See https://github.com/xwp/wp-customize-snapshots/blob/962586659688a5b1fd9ae93618b7ce2d4e7a421c/php/class-customize-snapshot-manager.php#L420-L449
  93. add_filter( 'customize_dynamic_setting_args', array( $this, 'filter_customize_dynamic_setting_args' ), 10, 2 );
  94. add_action( 'widgets_init', array( $this, 'register_settings' ), 95 );
  95. add_action( 'customize_register', array( $this, 'schedule_customize_register' ), 1 );
  96. // Skip remaining hooks when the user can't manage widgets anyway.
  97. if ( ! current_user_can( 'edit_theme_options' ) ) {
  98. return;
  99. }
  100. add_action( 'wp_loaded', array( $this, 'override_sidebars_widgets_for_theme_switch' ) );
  101. add_action( 'customize_controls_init', array( $this, 'customize_controls_init' ) );
  102. add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  103. add_action( 'customize_controls_print_styles', array( $this, 'print_styles' ) );
  104. add_action( 'customize_controls_print_scripts', array( $this, 'print_scripts' ) );
  105. add_action( 'customize_controls_print_footer_scripts', array( $this, 'print_footer_scripts' ) );
  106. add_action( 'customize_controls_print_footer_scripts', array( $this, 'output_widget_control_templates' ) );
  107. add_action( 'customize_preview_init', array( $this, 'customize_preview_init' ) );
  108. add_filter( 'customize_refresh_nonces', array( $this, 'refresh_nonces' ) );
  109. add_filter( 'should_load_block_editor_scripts_and_styles', array( $this, 'should_load_block_editor_scripts_and_styles' ) );
  110. add_action( 'dynamic_sidebar', array( $this, 'tally_rendered_widgets' ) );
  111. add_filter( 'is_active_sidebar', array( $this, 'tally_sidebars_via_is_active_sidebar_calls' ), 10, 2 );
  112. add_filter( 'dynamic_sidebar_has_widgets', array( $this, 'tally_sidebars_via_dynamic_sidebar_calls' ), 10, 2 );
  113. // Selective Refresh.
  114. add_filter( 'customize_dynamic_partial_args', array( $this, 'customize_dynamic_partial_args' ), 10, 2 );
  115. add_action( 'customize_preview_init', array( $this, 'selective_refresh_init' ) );
  116. }
  117. /**
  118. * List whether each registered widget can be use selective refresh.
  119. *
  120. * If the theme does not support the customize-selective-refresh-widgets feature,
  121. * then this will always return an empty array.
  122. *
  123. * @since 4.5.0
  124. *
  125. * @global WP_Widget_Factory $wp_widget_factory
  126. *
  127. * @return array Mapping of id_base to support. If theme doesn't support
  128. * selective refresh, an empty array is returned.
  129. */
  130. public function get_selective_refreshable_widgets() {
  131. global $wp_widget_factory;
  132. if ( ! current_theme_supports( 'customize-selective-refresh-widgets' ) ) {
  133. return array();
  134. }
  135. if ( ! isset( $this->selective_refreshable_widgets ) ) {
  136. $this->selective_refreshable_widgets = array();
  137. foreach ( $wp_widget_factory->widgets as $wp_widget ) {
  138. $this->selective_refreshable_widgets[ $wp_widget->id_base ] = ! empty( $wp_widget->widget_options['customize_selective_refresh'] );
  139. }
  140. }
  141. return $this->selective_refreshable_widgets;
  142. }
  143. /**
  144. * Determines if a widget supports selective refresh.
  145. *
  146. * @since 4.5.0
  147. *
  148. * @param string $id_base Widget ID Base.
  149. * @return bool Whether the widget can be selective refreshed.
  150. */
  151. public function is_widget_selective_refreshable( $id_base ) {
  152. $selective_refreshable_widgets = $this->get_selective_refreshable_widgets();
  153. return ! empty( $selective_refreshable_widgets[ $id_base ] );
  154. }
  155. /**
  156. * Retrieves the widget setting type given a setting ID.
  157. *
  158. * @since 4.2.0
  159. *
  160. * @param string $setting_id Setting ID.
  161. * @return string|void Setting type.
  162. */
  163. protected function get_setting_type( $setting_id ) {
  164. static $cache = array();
  165. if ( isset( $cache[ $setting_id ] ) ) {
  166. return $cache[ $setting_id ];
  167. }
  168. foreach ( $this->setting_id_patterns as $type => $pattern ) {
  169. if ( preg_match( $pattern, $setting_id ) ) {
  170. $cache[ $setting_id ] = $type;
  171. return $type;
  172. }
  173. }
  174. }
  175. /**
  176. * Inspects the incoming customized data for any widget settings, and dynamically adds
  177. * them up-front so widgets will be initialized properly.
  178. *
  179. * @since 4.2.0
  180. */
  181. public function register_settings() {
  182. $widget_setting_ids = array();
  183. $incoming_setting_ids = array_keys( $this->manager->unsanitized_post_values() );
  184. foreach ( $incoming_setting_ids as $setting_id ) {
  185. if ( ! is_null( $this->get_setting_type( $setting_id ) ) ) {
  186. $widget_setting_ids[] = $setting_id;
  187. }
  188. }
  189. if ( $this->manager->doing_ajax( 'update-widget' ) && isset( $_REQUEST['widget-id'] ) ) {
  190. $widget_setting_ids[] = $this->get_setting_id( wp_unslash( $_REQUEST['widget-id'] ) );
  191. }
  192. $settings = $this->manager->add_dynamic_settings( array_unique( $widget_setting_ids ) );
  193. if ( $this->manager->settings_previewed() ) {
  194. foreach ( $settings as $setting ) {
  195. $setting->preview();
  196. }
  197. }
  198. }
  199. /**
  200. * Determines the arguments for a dynamically-created setting.
  201. *
  202. * @since 4.2.0
  203. *
  204. * @param false|array $args The arguments to the WP_Customize_Setting constructor.
  205. * @param string $setting_id ID for dynamic setting, usually coming from `$_POST['customized']`.
  206. * @return array|false Setting arguments, false otherwise.
  207. */
  208. public function filter_customize_dynamic_setting_args( $args, $setting_id ) {
  209. if ( $this->get_setting_type( $setting_id ) ) {
  210. $args = $this->get_setting_args( $setting_id );
  211. }
  212. return $args;
  213. }
  214. /**
  215. * Retrieves an unslashed post value or return a default.
  216. *
  217. * @since 3.9.0
  218. *
  219. * @param string $name Post value.
  220. * @param mixed $default Default post value.
  221. * @return mixed Unslashed post value or default value.
  222. */
  223. protected function get_post_value( $name, $default = null ) {
  224. if ( ! isset( $_POST[ $name ] ) ) {
  225. return $default;
  226. }
  227. return wp_unslash( $_POST[ $name ] );
  228. }
  229. /**
  230. * Override sidebars_widgets for theme switch.
  231. *
  232. * When switching a theme via the Customizer, supply any previously-configured
  233. * sidebars_widgets from the target theme as the initial sidebars_widgets
  234. * setting. Also store the old theme's existing settings so that they can
  235. * be passed along for storing in the sidebars_widgets theme_mod when the
  236. * theme gets switched.
  237. *
  238. * @since 3.9.0
  239. *
  240. * @global array $sidebars_widgets
  241. * @global array $_wp_sidebars_widgets
  242. */
  243. public function override_sidebars_widgets_for_theme_switch() {
  244. global $sidebars_widgets;
  245. if ( $this->manager->doing_ajax() || $this->manager->is_theme_active() ) {
  246. return;
  247. }
  248. $this->old_sidebars_widgets = wp_get_sidebars_widgets();
  249. add_filter( 'customize_value_old_sidebars_widgets_data', array( $this, 'filter_customize_value_old_sidebars_widgets_data' ) );
  250. $this->manager->set_post_value( 'old_sidebars_widgets_data', $this->old_sidebars_widgets ); // Override any value cached in changeset.
  251. // retrieve_widgets() looks at the global $sidebars_widgets.
  252. $sidebars_widgets = $this->old_sidebars_widgets;
  253. $sidebars_widgets = retrieve_widgets( 'customize' );
  254. add_filter( 'option_sidebars_widgets', array( $this, 'filter_option_sidebars_widgets_for_theme_switch' ), 1 );
  255. // Reset global cache var used by wp_get_sidebars_widgets().
  256. unset( $GLOBALS['_wp_sidebars_widgets'] );
  257. }
  258. /**
  259. * Filters old_sidebars_widgets_data Customizer setting.
  260. *
  261. * When switching themes, filter the Customizer setting old_sidebars_widgets_data
  262. * to supply initial $sidebars_widgets before they were overridden by retrieve_widgets().
  263. * The value for old_sidebars_widgets_data gets set in the old theme's sidebars_widgets
  264. * theme_mod.
  265. *
  266. * @since 3.9.0
  267. *
  268. * @see WP_Customize_Widgets::handle_theme_switch()
  269. *
  270. * @param array $old_sidebars_widgets
  271. * @return array
  272. */
  273. public function filter_customize_value_old_sidebars_widgets_data( $old_sidebars_widgets ) {
  274. return $this->old_sidebars_widgets;
  275. }
  276. /**
  277. * Filters sidebars_widgets option for theme switch.
  278. *
  279. * When switching themes, the retrieve_widgets() function is run when the Customizer initializes,
  280. * and then the new sidebars_widgets here get supplied as the default value for the sidebars_widgets
  281. * option.
  282. *
  283. * @since 3.9.0
  284. *
  285. * @see WP_Customize_Widgets::handle_theme_switch()
  286. * @global array $sidebars_widgets
  287. *
  288. * @param array $sidebars_widgets
  289. * @return array
  290. */
  291. public function filter_option_sidebars_widgets_for_theme_switch( $sidebars_widgets ) {
  292. $sidebars_widgets = $GLOBALS['sidebars_widgets'];
  293. $sidebars_widgets['array_version'] = 3;
  294. return $sidebars_widgets;
  295. }
  296. /**
  297. * Ensures all widgets get loaded into the Customizer.
  298. *
  299. * Note: these actions are also fired in wp_ajax_update_widget().
  300. *
  301. * @since 3.9.0
  302. */
  303. public function customize_controls_init() {
  304. /** This action is documented in wp-admin/includes/ajax-actions.php */
  305. do_action( 'load-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  306. /** This action is documented in wp-admin/includes/ajax-actions.php */
  307. do_action( 'widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  308. /** This action is documented in wp-admin/widgets.php */
  309. do_action( 'sidebar_admin_setup' );
  310. }
  311. /**
  312. * Ensures widgets are available for all types of previews.
  313. *
  314. * When in preview, hook to {@see 'customize_register'} for settings after WordPress is loaded
  315. * so that all filters have been initialized (e.g. Widget Visibility).
  316. *
  317. * @since 3.9.0
  318. */
  319. public function schedule_customize_register() {
  320. if ( is_admin() ) {
  321. $this->customize_register();
  322. } else {
  323. add_action( 'wp', array( $this, 'customize_register' ) );
  324. }
  325. }
  326. /**
  327. * Registers Customizer settings and controls for all sidebars and widgets.
  328. *
  329. * @since 3.9.0
  330. *
  331. * @global array $wp_registered_widgets
  332. * @global array $wp_registered_widget_controls
  333. * @global array $wp_registered_sidebars
  334. */
  335. public function customize_register() {
  336. global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_sidebars;
  337. $use_widgets_block_editor = wp_use_widgets_block_editor();
  338. add_filter( 'sidebars_widgets', array( $this, 'preview_sidebars_widgets' ), 1 );
  339. $sidebars_widgets = array_merge(
  340. array( 'wp_inactive_widgets' => array() ),
  341. array_fill_keys( array_keys( $wp_registered_sidebars ), array() ),
  342. wp_get_sidebars_widgets()
  343. );
  344. $new_setting_ids = array();
  345. /*
  346. * Register a setting for all widgets, including those which are active,
  347. * inactive, and orphaned since a widget may get suppressed from a sidebar
  348. * via a plugin (like Widget Visibility).
  349. */
  350. foreach ( array_keys( $wp_registered_widgets ) as $widget_id ) {
  351. $setting_id = $this->get_setting_id( $widget_id );
  352. $setting_args = $this->get_setting_args( $setting_id );
  353. if ( ! $this->manager->get_setting( $setting_id ) ) {
  354. $this->manager->add_setting( $setting_id, $setting_args );
  355. }
  356. $new_setting_ids[] = $setting_id;
  357. }
  358. /*
  359. * Add a setting which will be supplied for the theme's sidebars_widgets
  360. * theme_mod when the theme is switched.
  361. */
  362. if ( ! $this->manager->is_theme_active() ) {
  363. $setting_id = 'old_sidebars_widgets_data';
  364. $setting_args = $this->get_setting_args(
  365. $setting_id,
  366. array(
  367. 'type' => 'global_variable',
  368. 'dirty' => true,
  369. )
  370. );
  371. $this->manager->add_setting( $setting_id, $setting_args );
  372. }
  373. $this->manager->add_panel(
  374. 'widgets',
  375. array(
  376. 'type' => 'widgets',
  377. 'title' => __( 'Widgets' ),
  378. 'description' => __( 'Widgets are independent sections of content that can be placed into widgetized areas provided by your theme (commonly called sidebars).' ),
  379. 'priority' => 110,
  380. 'active_callback' => array( $this, 'is_panel_active' ),
  381. 'auto_expand_sole_section' => true,
  382. 'theme_supports' => 'widgets',
  383. )
  384. );
  385. foreach ( $sidebars_widgets as $sidebar_id => $sidebar_widget_ids ) {
  386. if ( empty( $sidebar_widget_ids ) ) {
  387. $sidebar_widget_ids = array();
  388. }
  389. $is_registered_sidebar = is_registered_sidebar( $sidebar_id );
  390. $is_inactive_widgets = ( 'wp_inactive_widgets' === $sidebar_id );
  391. $is_active_sidebar = ( $is_registered_sidebar && ! $is_inactive_widgets );
  392. // Add setting for managing the sidebar's widgets.
  393. if ( $is_registered_sidebar || $is_inactive_widgets ) {
  394. $setting_id = sprintf( 'sidebars_widgets[%s]', $sidebar_id );
  395. $setting_args = $this->get_setting_args( $setting_id );
  396. if ( ! $this->manager->get_setting( $setting_id ) ) {
  397. if ( ! $this->manager->is_theme_active() ) {
  398. $setting_args['dirty'] = true;
  399. }
  400. $this->manager->add_setting( $setting_id, $setting_args );
  401. }
  402. $new_setting_ids[] = $setting_id;
  403. // Add section to contain controls.
  404. $section_id = sprintf( 'sidebar-widgets-%s', $sidebar_id );
  405. if ( $is_active_sidebar ) {
  406. $section_args = array(
  407. 'title' => $wp_registered_sidebars[ $sidebar_id ]['name'],
  408. 'priority' => array_search( $sidebar_id, array_keys( $wp_registered_sidebars ), true ),
  409. 'panel' => 'widgets',
  410. 'sidebar_id' => $sidebar_id,
  411. );
  412. if ( $use_widgets_block_editor ) {
  413. $section_args['description'] = '';
  414. } else {
  415. $section_args['description'] = $wp_registered_sidebars[ $sidebar_id ]['description'];
  416. }
  417. /**
  418. * Filters Customizer widget section arguments for a given sidebar.
  419. *
  420. * @since 3.9.0
  421. *
  422. * @param array $section_args Array of Customizer widget section arguments.
  423. * @param string $section_id Customizer section ID.
  424. * @param int|string $sidebar_id Sidebar ID.
  425. */
  426. $section_args = apply_filters( 'customizer_widgets_section_args', $section_args, $section_id, $sidebar_id );
  427. $section = new WP_Customize_Sidebar_Section( $this->manager, $section_id, $section_args );
  428. $this->manager->add_section( $section );
  429. if ( $use_widgets_block_editor ) {
  430. $control = new WP_Sidebar_Block_Editor_Control(
  431. $this->manager,
  432. $setting_id,
  433. array(
  434. 'section' => $section_id,
  435. 'sidebar_id' => $sidebar_id,
  436. 'label' => $section_args['title'],
  437. 'description' => $section_args['description'],
  438. )
  439. );
  440. } else {
  441. $control = new WP_Widget_Area_Customize_Control(
  442. $this->manager,
  443. $setting_id,
  444. array(
  445. 'section' => $section_id,
  446. 'sidebar_id' => $sidebar_id,
  447. 'priority' => count( $sidebar_widget_ids ), // place 'Add Widget' and 'Reorder' buttons at end.
  448. )
  449. );
  450. }
  451. $this->manager->add_control( $control );
  452. $new_setting_ids[] = $setting_id;
  453. }
  454. }
  455. if ( ! $use_widgets_block_editor ) {
  456. // Add a control for each active widget (located in a sidebar).
  457. foreach ( $sidebar_widget_ids as $i => $widget_id ) {
  458. // Skip widgets that may have gone away due to a plugin being deactivated.
  459. if ( ! $is_active_sidebar || ! isset( $wp_registered_widgets[ $widget_id ] ) ) {
  460. continue;
  461. }
  462. $registered_widget = $wp_registered_widgets[ $widget_id ];
  463. $setting_id = $this->get_setting_id( $widget_id );
  464. $id_base = $wp_registered_widget_controls[ $widget_id ]['id_base'];
  465. $control = new WP_Widget_Form_Customize_Control(
  466. $this->manager,
  467. $setting_id,
  468. array(
  469. 'label' => $registered_widget['name'],
  470. 'section' => $section_id,
  471. 'sidebar_id' => $sidebar_id,
  472. 'widget_id' => $widget_id,
  473. 'widget_id_base' => $id_base,
  474. 'priority' => $i,
  475. 'width' => $wp_registered_widget_controls[ $widget_id ]['width'],
  476. 'height' => $wp_registered_widget_controls[ $widget_id ]['height'],
  477. 'is_wide' => $this->is_wide_widget( $widget_id ),
  478. )
  479. );
  480. $this->manager->add_control( $control );
  481. }
  482. }
  483. }
  484. if ( $this->manager->settings_previewed() ) {
  485. foreach ( $new_setting_ids as $new_setting_id ) {
  486. $this->manager->get_setting( $new_setting_id )->preview();
  487. }
  488. }
  489. }
  490. /**
  491. * Determines whether the widgets panel is active, based on whether there are sidebars registered.
  492. *
  493. * @since 4.4.0
  494. *
  495. * @see WP_Customize_Panel::$active_callback
  496. *
  497. * @global array $wp_registered_sidebars
  498. * @return bool Active.
  499. */
  500. public function is_panel_active() {
  501. global $wp_registered_sidebars;
  502. return ! empty( $wp_registered_sidebars );
  503. }
  504. /**
  505. * Converts a widget_id into its corresponding Customizer setting ID (option name).
  506. *
  507. * @since 3.9.0
  508. *
  509. * @param string $widget_id Widget ID.
  510. * @return string Maybe-parsed widget ID.
  511. */
  512. public function get_setting_id( $widget_id ) {
  513. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  514. $setting_id = sprintf( 'widget_%s', $parsed_widget_id['id_base'] );
  515. if ( ! is_null( $parsed_widget_id['number'] ) ) {
  516. $setting_id .= sprintf( '[%d]', $parsed_widget_id['number'] );
  517. }
  518. return $setting_id;
  519. }
  520. /**
  521. * Determines whether the widget is considered "wide".
  522. *
  523. * Core widgets which may have controls wider than 250, but can still be shown
  524. * in the narrow Customizer panel. The RSS and Text widgets in Core, for example,
  525. * have widths of 400 and yet they still render fine in the Customizer panel.
  526. *
  527. * This method will return all Core widgets as being not wide, but this can be
  528. * overridden with the {@see 'is_wide_widget_in_customizer'} filter.
  529. *
  530. * @since 3.9.0
  531. *
  532. * @global array $wp_registered_widget_controls
  533. *
  534. * @param string $widget_id Widget ID.
  535. * @return bool Whether or not the widget is a "wide" widget.
  536. */
  537. public function is_wide_widget( $widget_id ) {
  538. global $wp_registered_widget_controls;
  539. $parsed_widget_id = $this->parse_widget_id( $widget_id );
  540. $width = $wp_registered_widget_controls[ $widget_id ]['width'];
  541. $is_core = in_array( $parsed_widget_id['id_base'], $this->core_widget_id_bases, true );
  542. $is_wide = ( $width > 250 && ! $is_core );
  543. /**
  544. * Filters whether the given widget is considered "wide".
  545. *
  546. * @since 3.9.0
  547. *
  548. * @param bool $is_wide Whether the widget is wide, Default false.
  549. * @param string $widget_id Widget ID.
  550. */
  551. return apply_filters( 'is_wide_widget_in_customizer', $is_wide, $widget_id );
  552. }
  553. /**
  554. * Converts a widget ID into its id_base and number components.
  555. *
  556. * @since 3.9.0
  557. *
  558. * @param string $widget_id Widget ID.
  559. * @return array Array containing a widget's id_base and number components.
  560. */
  561. public function parse_widget_id( $widget_id ) {
  562. $parsed = array(
  563. 'number' => null,
  564. 'id_base' => null,
  565. );
  566. if ( preg_match( '/^(.+)-(\d+)$/', $widget_id, $matches ) ) {
  567. $parsed['id_base'] = $matches[1];
  568. $parsed['number'] = (int) $matches[2];
  569. } else {
  570. // Likely an old single widget.
  571. $parsed['id_base'] = $widget_id;
  572. }
  573. return $parsed;
  574. }
  575. /**
  576. * Converts a widget setting ID (option path) to its id_base and number components.
  577. *
  578. * @since 3.9.0
  579. *
  580. * @param string $setting_id Widget setting ID.
  581. * @return array|WP_Error Array containing a widget's id_base and number components,
  582. * or a WP_Error object.
  583. */
  584. public function parse_widget_setting_id( $setting_id ) {
  585. if ( ! preg_match( '/^(widget_(.+?))(?:\[(\d+)\])?$/', $setting_id, $matches ) ) {
  586. return new WP_Error( 'widget_setting_invalid_id' );
  587. }
  588. $id_base = $matches[2];
  589. $number = isset( $matches[3] ) ? (int) $matches[3] : null;
  590. return compact( 'id_base', 'number' );
  591. }
  592. /**
  593. * Calls admin_print_styles-widgets.php and admin_print_styles hooks to
  594. * allow custom styles from plugins.
  595. *
  596. * @since 3.9.0
  597. */
  598. public function print_styles() {
  599. /** This action is documented in wp-admin/admin-header.php */
  600. do_action( 'admin_print_styles-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  601. /** This action is documented in wp-admin/admin-header.php */
  602. do_action( 'admin_print_styles' );
  603. }
  604. /**
  605. * Calls admin_print_scripts-widgets.php and admin_print_scripts hooks to
  606. * allow custom scripts from plugins.
  607. *
  608. * @since 3.9.0
  609. */
  610. public function print_scripts() {
  611. /** This action is documented in wp-admin/admin-header.php */
  612. do_action( 'admin_print_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  613. /** This action is documented in wp-admin/admin-header.php */
  614. do_action( 'admin_print_scripts' );
  615. }
  616. /**
  617. * Enqueues scripts and styles for Customizer panel and export data to JavaScript.
  618. *
  619. * @since 3.9.0
  620. *
  621. * @global WP_Scripts $wp_scripts
  622. * @global array $wp_registered_sidebars
  623. * @global array $wp_registered_widgets
  624. */
  625. public function enqueue_scripts() {
  626. global $wp_scripts, $wp_registered_sidebars, $wp_registered_widgets;
  627. wp_enqueue_style( 'customize-widgets' );
  628. wp_enqueue_script( 'customize-widgets' );
  629. /** This action is documented in wp-admin/admin-header.php */
  630. do_action( 'admin_enqueue_scripts', 'widgets.php' );
  631. /*
  632. * Export available widgets with control_tpl removed from model
  633. * since plugins need templates to be in the DOM.
  634. */
  635. $available_widgets = array();
  636. foreach ( $this->get_available_widgets() as $available_widget ) {
  637. unset( $available_widget['control_tpl'] );
  638. $available_widgets[] = $available_widget;
  639. }
  640. $widget_reorder_nav_tpl = sprintf(
  641. '<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>',
  642. __( 'Move to another area&hellip;' ),
  643. __( 'Move down' ),
  644. __( 'Move up' )
  645. );
  646. $move_widget_area_tpl = str_replace(
  647. array( '{description}', '{btn}' ),
  648. array(
  649. __( 'Select an area to move this widget into:' ),
  650. _x( 'Move', 'Move widget' ),
  651. ),
  652. '<div class="move-widget-area">
  653. <p class="description">{description}</p>
  654. <ul class="widget-area-select">
  655. <% _.each( sidebars, function ( sidebar ){ %>
  656. <li class="" data-id="<%- sidebar.id %>" title="<%- sidebar.description %>" tabindex="0"><%- sidebar.name %></li>
  657. <% }); %>
  658. </ul>
  659. <div class="move-widget-actions">
  660. <button class="move-widget-btn button" type="button">{btn}</button>
  661. </div>
  662. </div>'
  663. );
  664. /*
  665. * Gather all strings in PHP that may be needed by JS on the client.
  666. * Once JS i18n is implemented (in #20491), this can be removed.
  667. */
  668. $some_non_rendered_areas_messages = array();
  669. $some_non_rendered_areas_messages[1] = html_entity_decode(
  670. __( 'Your theme has 1 other widget area, but this particular page doesn&#8217;t display it.' ),
  671. ENT_QUOTES,
  672. get_bloginfo( 'charset' )
  673. );
  674. $registered_sidebar_count = count( $wp_registered_sidebars );
  675. for ( $non_rendered_count = 2; $non_rendered_count < $registered_sidebar_count; $non_rendered_count++ ) {
  676. $some_non_rendered_areas_messages[ $non_rendered_count ] = html_entity_decode(
  677. sprintf(
  678. /* translators: %s: The number of other widget areas registered but not rendered. */
  679. _n(
  680. 'Your theme has %s other widget area, but this particular page doesn&#8217;t display it.',
  681. 'Your theme has %s other widget areas, but this particular page doesn&#8217;t display them.',
  682. $non_rendered_count
  683. ),
  684. number_format_i18n( $non_rendered_count )
  685. ),
  686. ENT_QUOTES,
  687. get_bloginfo( 'charset' )
  688. );
  689. }
  690. if ( 1 === $registered_sidebar_count ) {
  691. $no_areas_shown_message = html_entity_decode(
  692. sprintf(
  693. __( 'Your theme has 1 widget area, but this particular page doesn&#8217;t display it.' )
  694. ),
  695. ENT_QUOTES,
  696. get_bloginfo( 'charset' )
  697. );
  698. } else {
  699. $no_areas_shown_message = html_entity_decode(
  700. sprintf(
  701. /* translators: %s: The total number of widget areas registered. */
  702. _n(
  703. 'Your theme has %s widget area, but this particular page doesn&#8217;t display it.',
  704. 'Your theme has %s widget areas, but this particular page doesn&#8217;t display them.',
  705. $registered_sidebar_count
  706. ),
  707. number_format_i18n( $registered_sidebar_count )
  708. ),
  709. ENT_QUOTES,
  710. get_bloginfo( 'charset' )
  711. );
  712. }
  713. $settings = array(
  714. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  715. 'registeredWidgets' => $wp_registered_widgets,
  716. 'availableWidgets' => $available_widgets, // @todo Merge this with registered_widgets.
  717. 'l10n' => array(
  718. 'saveBtnLabel' => __( 'Apply' ),
  719. 'saveBtnTooltip' => __( 'Save and preview changes before publishing them.' ),
  720. 'removeBtnLabel' => __( 'Remove' ),
  721. 'removeBtnTooltip' => __( 'Keep widget settings and move it to the inactive widgets' ),
  722. 'error' => __( 'An error has occurred. Please reload the page and try again.' ),
  723. 'widgetMovedUp' => __( 'Widget moved up' ),
  724. 'widgetMovedDown' => __( 'Widget moved down' ),
  725. 'navigatePreview' => __( 'You can navigate to other pages on your site while using the Customizer to view and edit the widgets displayed on those pages.' ),
  726. 'someAreasShown' => $some_non_rendered_areas_messages,
  727. 'noAreasShown' => $no_areas_shown_message,
  728. 'reorderModeOn' => __( 'Reorder mode enabled' ),
  729. 'reorderModeOff' => __( 'Reorder mode closed' ),
  730. 'reorderLabelOn' => esc_attr__( 'Reorder widgets' ),
  731. /* translators: %d: The number of widgets found. */
  732. 'widgetsFound' => __( 'Number of widgets found: %d' ),
  733. 'noWidgetsFound' => __( 'No widgets found.' ),
  734. ),
  735. 'tpl' => array(
  736. 'widgetReorderNav' => $widget_reorder_nav_tpl,
  737. 'moveWidgetArea' => $move_widget_area_tpl,
  738. ),
  739. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  740. );
  741. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  742. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  743. }
  744. $wp_scripts->add_data(
  745. 'customize-widgets',
  746. 'data',
  747. sprintf( 'var _wpCustomizeWidgetsSettings = %s;', wp_json_encode( $settings ) )
  748. );
  749. /*
  750. * TODO: Update 'wp-customize-widgets' to not rely so much on things in
  751. * 'customize-widgets'. This will let us skip most of the above and not
  752. * enqueue 'customize-widgets' which saves bytes.
  753. */
  754. if ( wp_use_widgets_block_editor() ) {
  755. $block_editor_context = new WP_Block_Editor_Context();
  756. $editor_settings = get_block_editor_settings(
  757. get_legacy_widget_block_editor_settings(),
  758. $block_editor_context
  759. );
  760. wp_add_inline_script(
  761. 'wp-customize-widgets',
  762. sprintf(
  763. 'wp.domReady( function() {
  764. wp.customizeWidgets.initialize( "widgets-customizer", %s );
  765. } );',
  766. wp_json_encode( $editor_settings )
  767. )
  768. );
  769. // Preload server-registered block schemas.
  770. wp_add_inline_script(
  771. 'wp-blocks',
  772. 'wp.blocks.unstable__bootstrapServerSideBlockDefinitions(' . wp_json_encode( get_block_editor_server_block_settings() ) . ');'
  773. );
  774. wp_add_inline_script(
  775. 'wp-blocks',
  776. sprintf( 'wp.blocks.setCategories( %s );', wp_json_encode( get_block_categories( $block_editor_context ) ) ),
  777. 'after'
  778. );
  779. wp_enqueue_script( 'wp-customize-widgets' );
  780. wp_enqueue_style( 'wp-customize-widgets' );
  781. /** This action is documented in edit-form-blocks.php */
  782. do_action( 'enqueue_block_editor_assets' );
  783. }
  784. }
  785. /**
  786. * Renders the widget form control templates into the DOM.
  787. *
  788. * @since 3.9.0
  789. */
  790. public function output_widget_control_templates() {
  791. ?>
  792. <div id="widgets-left"><!-- compatibility with JS which looks for widget templates here -->
  793. <div id="available-widgets">
  794. <div class="customize-section-title">
  795. <button class="customize-section-back" tabindex="-1">
  796. <span class="screen-reader-text"><?php _e( 'Back' ); ?></span>
  797. </button>
  798. <h3>
  799. <span class="customize-action">
  800. <?php
  801. /* translators: &#9656; is the unicode right-pointing triangle. %s: Section title in the Customizer. */
  802. printf( __( 'Customizing &#9656; %s' ), esc_html( $this->manager->get_panel( 'widgets' )->title ) );
  803. ?>
  804. </span>
  805. <?php _e( 'Add a Widget' ); ?>
  806. </h3>
  807. </div>
  808. <div id="available-widgets-filter">
  809. <label class="screen-reader-text" for="widgets-search"><?php _e( 'Search Widgets' ); ?></label>
  810. <input type="text" id="widgets-search" placeholder="<?php esc_attr_e( 'Search widgets&hellip;' ); ?>" aria-describedby="widgets-search-desc" />
  811. <div class="search-icon" aria-hidden="true"></div>
  812. <button type="button" class="clear-results"><span class="screen-reader-text"><?php _e( 'Clear Results' ); ?></span></button>
  813. <p class="screen-reader-text" id="widgets-search-desc"><?php _e( 'The search results will be updated as you type.' ); ?></p>
  814. </div>
  815. <div id="available-widgets-list">
  816. <?php foreach ( $this->get_available_widgets() as $available_widget ) : ?>
  817. <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">
  818. <?php echo $available_widget['control_tpl']; ?>
  819. </div>
  820. <?php endforeach; ?>
  821. <p class="no-widgets-found-message"><?php _e( 'No widgets found.' ); ?></p>
  822. </div><!-- #available-widgets-list -->
  823. </div><!-- #available-widgets -->
  824. </div><!-- #widgets-left -->
  825. <?php
  826. }
  827. /**
  828. * Calls admin_print_footer_scripts and admin_print_scripts hooks to
  829. * allow custom scripts from plugins.
  830. *
  831. * @since 3.9.0
  832. */
  833. public function print_footer_scripts() {
  834. /** This action is documented in wp-admin/admin-footer.php */
  835. do_action( 'admin_print_footer_scripts-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  836. /** This action is documented in wp-admin/admin-footer.php */
  837. do_action( 'admin_print_footer_scripts' );
  838. /** This action is documented in wp-admin/admin-footer.php */
  839. do_action( 'admin_footer-widgets.php' ); // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
  840. }
  841. /**
  842. * Retrieves common arguments to supply when constructing a Customizer setting.
  843. *
  844. * @since 3.9.0
  845. *
  846. * @param string $id Widget setting ID.
  847. * @param array $overrides Array of setting overrides.
  848. * @return array Possibly modified setting arguments.
  849. */
  850. public function get_setting_args( $id, $overrides = array() ) {
  851. $args = array(
  852. 'type' => 'option',
  853. 'capability' => 'edit_theme_options',
  854. 'default' => array(),
  855. );
  856. if ( preg_match( $this->setting_id_patterns['sidebar_widgets'], $id, $matches ) ) {
  857. $args['sanitize_callback'] = array( $this, 'sanitize_sidebar_widgets' );
  858. $args['sanitize_js_callback'] = array( $this, 'sanitize_sidebar_widgets_js_instance' );
  859. $args['transport'] = current_theme_supports( 'customize-selective-refresh-widgets' ) ? 'postMessage' : 'refresh';
  860. } elseif ( preg_match( $this->setting_id_patterns['widget_instance'], $id, $matches ) ) {
  861. $id_base = $matches['id_base'];
  862. $args['sanitize_callback'] = function( $value ) use ( $id_base ) {
  863. return $this->sanitize_widget_instance( $value, $id_base );
  864. };
  865. $args['sanitize_js_callback'] = function( $value ) use ( $id_base ) {
  866. return $this->sanitize_widget_js_instance( $value, $id_base );
  867. };
  868. $args['transport'] = $this->is_widget_selective_refreshable( $matches['id_base'] ) ? 'postMessage' : 'refresh';
  869. }
  870. $args = array_merge( $args, $overrides );
  871. /**
  872. * Filters the common arguments supplied when constructing a Customizer setting.
  873. *
  874. * @since 3.9.0
  875. *
  876. * @see WP_Customize_Setting
  877. *
  878. * @param array $args Array of Customizer setting arguments.
  879. * @param string $id Widget setting ID.
  880. */
  881. return apply_filters( 'widget_customizer_setting_args', $args, $id );
  882. }
  883. /**
  884. * Ensures sidebar widget arrays only ever contain widget IDS.
  885. *
  886. * Used as the 'sanitize_callback' for each $sidebars_widgets setting.
  887. *
  888. * @since 3.9.0
  889. *
  890. * @param string[] $widget_ids Array of widget IDs.
  891. * @return string[] Array of sanitized widget IDs.
  892. */
  893. public function sanitize_sidebar_widgets( $widget_ids ) {
  894. $widget_ids = array_map( 'strval', (array) $widget_ids );
  895. $sanitized_widget_ids = array();
  896. foreach ( $widget_ids as $widget_id ) {
  897. $sanitized_widget_ids[] = preg_replace( '/[^a-z0-9_\-]/', '', $widget_id );
  898. }
  899. return $sanitized_widget_ids;
  900. }
  901. /**
  902. * Builds up an index of all available widgets for use in Backbone models.
  903. *
  904. * @since 3.9.0
  905. *
  906. * @global array $wp_registered_widgets
  907. * @global array $wp_registered_widget_controls
  908. *
  909. * @see wp_list_widgets()
  910. *
  911. * @return array List of available widgets.
  912. */
  913. public function get_available_widgets() {
  914. static $available_widgets = array();
  915. if ( ! empty( $available_widgets ) ) {
  916. return $available_widgets;
  917. }
  918. global $wp_registered_widgets, $wp_registered_widget_controls;
  919. require_once ABSPATH . 'wp-admin/includes/widgets.php'; // For next_widget_id_number().
  920. $sort = $wp_registered_widgets;
  921. usort( $sort, array( $this, '_sort_name_callback' ) );
  922. $done = array();
  923. foreach ( $sort as $widget ) {
  924. if ( in_array( $widget['callback'], $done, true ) ) { // We already showed this multi-widget.
  925. continue;
  926. }
  927. $sidebar = is_active_widget( $widget['callback'], $widget['id'], false, false );
  928. $done[] = $widget['callback'];
  929. if ( ! isset( $widget['params'][0] ) ) {
  930. $widget['params'][0] = array();
  931. }
  932. $available_widget = $widget;
  933. unset( $available_widget['callback'] ); // Not serializable to JSON.
  934. $args = array(
  935. 'widget_id' => $widget['id'],
  936. 'widget_name' => $widget['name'],
  937. '_display' => 'template',
  938. );
  939. $is_disabled = false;
  940. $is_multi_widget = ( isset( $wp_registered_widget_controls[ $widget['id'] ]['id_base'] ) && isset( $widget['params'][0]['number'] ) );
  941. if ( $is_multi_widget ) {
  942. $id_base = $wp_registered_widget_controls[ $widget['id'] ]['id_base'];
  943. $args['_temp_id'] = "$id_base-__i__";
  944. $args['_multi_num'] = next_widget_id_number( $id_base );
  945. $args['_add'] = 'multi';
  946. } else {
  947. $args['_add'] = 'single';
  948. if ( $sidebar && 'wp_inactive_widgets' !== $sidebar ) {
  949. $is_disabled = true;
  950. }
  951. $id_base = $widget['id'];
  952. }
  953. $list_widget_controls_args = wp_list_widget_controls_dynamic_sidebar(
  954. array(
  955. 0 => $args,
  956. 1 => $widget['params'][0],
  957. )
  958. );
  959. $control_tpl = $this->get_widget_control( $list_widget_controls_args );
  960. // The properties here are mapped to the Backbone Widget model.
  961. $available_widget = array_merge(
  962. $available_widget,
  963. array(
  964. 'temp_id' => isset( $args['_temp_id'] ) ? $args['_temp_id'] : null,
  965. 'is_multi' => $is_multi_widget,
  966. 'control_tpl' => $control_tpl,
  967. 'multi_number' => ( 'multi' === $args['_add'] ) ? $args['_multi_num'] : false,
  968. 'is_disabled' => $is_disabled,
  969. 'id_base' => $id_base,
  970. 'transport' => $this->is_widget_selective_refreshable( $id_base ) ? 'postMessage' : 'refresh',
  971. 'width' => $wp_registered_widget_controls[ $widget['id'] ]['width'],
  972. 'height' => $wp_registered_widget_controls[ $widget['id'] ]['height'],
  973. 'is_wide' => $this->is_wide_widget( $widget['id'] ),
  974. )
  975. );
  976. $available_widgets[] = $available_widget;
  977. }
  978. return $available_widgets;
  979. }
  980. /**
  981. * Naturally orders available widgets by name.
  982. *
  983. * @since 3.9.0
  984. *
  985. * @param array $widget_a The first widget to compare.
  986. * @param array $widget_b The second widget to compare.
  987. * @return int Reorder position for the current widget comparison.
  988. */
  989. protected function _sort_name_callback( $widget_a, $widget_b ) {
  990. return strnatcasecmp( $widget_a['name'], $widget_b['name'] );
  991. }
  992. /**
  993. * Retrieves the widget control markup.
  994. *
  995. * @since 3.9.0
  996. *
  997. * @param array $args Widget control arguments.
  998. * @return string Widget control form HTML markup.
  999. */
  1000. public function get_widget_control( $args ) {
  1001. $args[0]['before_form'] = '<div class="form">';
  1002. $args[0]['after_form'] = '</div><!-- .form -->';
  1003. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1004. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1005. ob_start();
  1006. wp_widget_control( ...$args );
  1007. $control_tpl = ob_get_clean();
  1008. return $control_tpl;
  1009. }
  1010. /**
  1011. * Retrieves the widget control markup parts.
  1012. *
  1013. * @since 4.4.0
  1014. *
  1015. * @param array $args Widget control arguments.
  1016. * @return array {
  1017. * @type string $control Markup for widget control wrapping form.
  1018. * @type string $content The contents of the widget form itself.
  1019. * }
  1020. */
  1021. public function get_widget_control_parts( $args ) {
  1022. $args[0]['before_widget_content'] = '<div class="widget-content">';
  1023. $args[0]['after_widget_content'] = '</div><!-- .widget-content -->';
  1024. $control_markup = $this->get_widget_control( $args );
  1025. $content_start_pos = strpos( $control_markup, $args[0]['before_widget_content'] );
  1026. $content_end_pos = strrpos( $control_markup, $args[0]['after_widget_content'] );
  1027. $control = substr( $control_markup, 0, $content_start_pos + strlen( $args[0]['before_widget_content'] ) );
  1028. $control .= substr( $control_markup, $content_end_pos );
  1029. $content = trim(
  1030. substr(
  1031. $control_markup,
  1032. $content_start_pos + strlen( $args[0]['before_widget_content'] ),
  1033. $content_end_pos - $content_start_pos - strlen( $args[0]['before_widget_content'] )
  1034. )
  1035. );
  1036. return compact( 'control', 'content' );
  1037. }
  1038. /**
  1039. * Adds hooks for the Customizer preview.
  1040. *
  1041. * @since 3.9.0
  1042. */
  1043. public function customize_preview_init() {
  1044. add_action( 'wp_enqueue_scripts', array( $this, 'customize_preview_enqueue' ) );
  1045. add_action( 'wp_print_styles', array( $this, 'print_preview_css' ), 1 );
  1046. add_action( 'wp_footer', array( $this, 'export_preview_data' ), 20 );
  1047. }
  1048. /**
  1049. * Refreshes the nonce for widget updates.
  1050. *
  1051. * @since 4.2.0
  1052. *
  1053. * @param array $nonces Array of nonces.
  1054. * @return array Array of nonces.
  1055. */
  1056. public function refresh_nonces( $nonces ) {
  1057. $nonces['update-widget'] = wp_create_nonce( 'update-widget' );
  1058. return $nonces;
  1059. }
  1060. /**
  1061. * Tells the script loader to load the scripts and styles of custom blocks
  1062. * if the widgets block editor is enabled.
  1063. *
  1064. * @since 5.8.0
  1065. *
  1066. * @param bool $is_block_editor_screen Current decision about loading block assets.
  1067. * @return bool Filtered decision about loading block assets.
  1068. */
  1069. public function should_load_block_editor_scripts_and_styles( $is_block_editor_screen ) {
  1070. if ( wp_use_widgets_block_editor() ) {
  1071. return true;
  1072. }
  1073. return $is_block_editor_screen;
  1074. }
  1075. /**
  1076. * When previewing, ensures the proper previewing widgets are used.
  1077. *
  1078. * Because wp_get_sidebars_widgets() gets called early at {@see 'init' } (via
  1079. * wp_convert_widget_settings()) and can set global variable `$_wp_sidebars_widgets`
  1080. * to the value of `get_option( 'sidebars_widgets' )` before the Customizer preview
  1081. * filter is added, it has to be reset after the filter has been added.
  1082. *
  1083. * @since 3.9.0
  1084. *
  1085. * @param array $sidebars_widgets List of widgets for the current sidebar.
  1086. * @return array
  1087. */
  1088. public function preview_sidebars_widgets( $sidebars_widgets ) {
  1089. $sidebars_widgets = get_option( 'sidebars_widgets', array() );
  1090. unset( $sidebars_widgets['array_version'] );
  1091. return $sidebars_widgets;
  1092. }
  1093. /**
  1094. * Enqueues scripts for the Customizer preview.
  1095. *
  1096. * @since 3.9.0
  1097. */
  1098. public function customize_preview_enqueue() {
  1099. wp_enqueue_script( 'customize-preview-widgets' );
  1100. }
  1101. /**
  1102. * Inserts default style for highlighted widget at early point so theme
  1103. * stylesheet can override.
  1104. *
  1105. * @since 3.9.0
  1106. */
  1107. public function print_preview_css() {
  1108. ?>
  1109. <style>
  1110. .widget-customizer-highlighted-widget {
  1111. outline: none;
  1112. -webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1113. box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
  1114. position: relative;
  1115. z-index: 1;
  1116. }
  1117. </style>
  1118. <?php
  1119. }
  1120. /**
  1121. * Communicates the sidebars that appeared on the page at the very end of the page,
  1122. * and at the very end of the wp_footer,
  1123. *
  1124. * @since 3.9.0
  1125. *
  1126. * @global array $wp_registered_sidebars
  1127. * @global array $wp_registered_widgets
  1128. */
  1129. public function export_preview_data() {
  1130. global $wp_registered_sidebars, $wp_registered_widgets;
  1131. $switched_locale = switch_to_locale( get_user_locale() );
  1132. $l10n = array(
  1133. 'widgetTooltip' => __( 'Shift-click to edit this widget.' ),
  1134. );
  1135. if ( $switched_locale ) {
  1136. restore_previous_locale();
  1137. }
  1138. $rendered_sidebars = array_filter( $this->rendered_sidebars );
  1139. $rendered_widgets = array_filter( $this->rendered_widgets );
  1140. // Prepare Customizer settings to pass to JavaScript.
  1141. $settings = array(
  1142. 'renderedSidebars' => array_fill_keys( array_keys( $rendered_sidebars ), true ),
  1143. 'renderedWidgets' => array_fill_keys( array_keys( $rendered_widgets ), true ),
  1144. 'registeredSidebars' => array_values( $wp_registered_sidebars ),
  1145. 'registeredWidgets' => $wp_registered_widgets,
  1146. 'l10n' => $l10n,
  1147. 'selectiveRefreshableWidgets' => $this->get_selective_refreshable_widgets(),
  1148. );
  1149. foreach ( $settings['registeredWidgets'] as &$registered_widget ) {
  1150. unset( $registered_widget['callback'] ); // May not be JSON-serializeable.
  1151. }
  1152. ?>
  1153. <script type="text/javascript">
  1154. var _wpWidgetCustomizerPreviewSettings = <?php echo wp_json_encode( $settings ); ?>;
  1155. </script>
  1156. <?php
  1157. }
  1158. /**
  1159. * Tracks the widgets that were rendered.
  1160. *
  1161. * @since 3.9.0
  1162. *
  1163. * @param array $widget Rendered widget to tally.
  1164. */
  1165. public function tally_rendered_widgets( $widget ) {
  1166. $this->rendered_widgets[ $widget['id'] ] = true;
  1167. }
  1168. /**
  1169. * Determine if a widget is rendered on the page.
  1170. *
  1171. * @since 4.0.0
  1172. *
  1173. * @param string $widget_id Widget ID to check.
  1174. * @return bool Whether the widget is rendered.
  1175. */
  1176. public function is_widget_rendered( $widget_id ) {
  1177. return ! empty( $this->rendered_widgets[ $widget_id ] );
  1178. }
  1179. /**
  1180. * Determines if a sidebar is rendered on the page.
  1181. *
  1182. * @since 4.0.0
  1183. *
  1184. * @param string $sidebar_id Sidebar ID to check.
  1185. * @return bool Whether the sidebar is rendered.
  1186. */
  1187. public function is_sidebar_rendered( $sidebar_id ) {
  1188. return ! empty( $this->rendered_sidebars[ $sidebar_id ] );
  1189. }
  1190. /**
  1191. * Tallies the sidebars rendered via is_active_sidebar().
  1192. *
  1193. * Keep track of the times that is_active_sidebar() is called in the template,
  1194. * and assume that this means that the sidebar would be rendered on the template
  1195. * if there were widgets populating it.
  1196. *
  1197. * @since 3.9.0
  1198. *
  1199. * @param bool $is_active Whether the sidebar is active.
  1200. * @param string $sidebar_id Sidebar ID.
  1201. * @return bool Whether the sidebar is active.
  1202. */
  1203. public function tally_sidebars_via_is_active_sidebar_calls( $is_active, $sidebar_id ) {
  1204. if ( is_registered_sidebar( $sidebar_id ) ) {
  1205. $this->rendered_sidebars[ $sidebar_id ] = true;
  1206. }
  1207. /*
  1208. * We may need to force this to true, and also force-true the value
  1209. * for 'dynamic_sidebar_has_widgets' if we want to ensure that there
  1210. * is an area to drop widgets into, if the sidebar is empty.
  1211. */
  1212. return $is_active;
  1213. }
  1214. /**
  1215. * Tallies the sidebars rendered via dynamic_sidebar().
  1216. *
  1217. * Keep track of the times that dynamic_sidebar() is called in the template,
  1218. * and assume this means the sidebar would be rendered on the template if
  1219. * there were widgets populating it.
  1220. *
  1221. * @since 3.9.0
  1222. *
  1223. * @param bool $has_widgets Whether the current sidebar has widgets.
  1224. * @param string $sidebar_id Sidebar ID.
  1225. * @return bool Whether the current sidebar has widgets.
  1226. */
  1227. public function tally_sidebars_via_dynamic_sidebar_calls( $has_widgets, $sidebar_id ) {
  1228. if ( is_registered_sidebar( $sidebar_id ) ) {
  1229. $this->rendered_sidebars[ $sidebar_id ] = true;
  1230. }
  1231. /*
  1232. * We may need to force this to true, and also force-true the value
  1233. * for 'is_active_sidebar' if we want to ensure there is an area to
  1234. * drop widgets into, if the sidebar is empty.
  1235. */
  1236. return $has_widgets;
  1237. }
  1238. /**
  1239. * Retrieves MAC for a serialized widget instance string.
  1240. *
  1241. * Allows values posted back from JS to be rejected if any tampering of the
  1242. * data has occurred.
  1243. *
  1244. * @since 3.9.0
  1245. *
  1246. * @param string $serialized_instance Widget instance.
  1247. * @return string MAC for serialized widget instance.
  1248. */
  1249. protected function get_instance_hash_key( $serialized_instance ) {
  1250. return wp_hash( $serialized_instance );
  1251. }
  1252. /**
  1253. * Sanitizes a widget instance.
  1254. *
  1255. * Unserialize the JS-instance for storing in the options. It's important that this filter
  1256. * only get applied to an instance *once*.
  1257. *
  1258. * @since 3.9.0
  1259. * @since 5.8.0 Added the `$id_base` parameter.
  1260. *
  1261. * @global WP_Widget_Factory $wp_widget_factory
  1262. *
  1263. * @param array $value Widget instance to sanitize.
  1264. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1265. * @return array|void Sanitized widget instance.
  1266. */
  1267. public function sanitize_widget_instance( $value, $id_base = null ) {
  1268. global $wp_widget_factory;
  1269. if ( array() === $value ) {
  1270. return $value;
  1271. }
  1272. if ( isset( $value['raw_instance'] ) && $id_base && wp_use_widgets_block_editor() ) {
  1273. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1274. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1275. if ( 'block' === $id_base && ! current_user_can( 'unfiltered_html' ) ) {
  1276. /*
  1277. * The content of the 'block' widget is not filtered on the fly while editing.
  1278. * Filter the content here to prevent vulnerabilities.
  1279. */
  1280. $value['raw_instance']['content'] = wp_kses_post( $value['raw_instance']['content'] );
  1281. }
  1282. return $value['raw_instance'];
  1283. }
  1284. }
  1285. if (
  1286. empty( $value['is_widget_customizer_js_value'] ) ||
  1287. empty( $value['instance_hash_key'] ) ||
  1288. empty( $value['encoded_serialized_instance'] )
  1289. ) {
  1290. return;
  1291. }
  1292. $decoded = base64_decode( $value['encoded_serialized_instance'], true );
  1293. if ( false === $decoded ) {
  1294. return;
  1295. }
  1296. if ( ! hash_equals( $this->get_instance_hash_key( $decoded ), $value['instance_hash_key'] ) ) {
  1297. return;
  1298. }
  1299. $instance = unserialize( $decoded );
  1300. if ( false === $instance ) {
  1301. return;
  1302. }
  1303. return $instance;
  1304. }
  1305. /**
  1306. * Converts a widget instance into JSON-representable format.
  1307. *
  1308. * @since 3.9.0
  1309. * @since 5.8.0 Added the `$id_base` parameter.
  1310. *
  1311. * @global WP_Widget_Factory $wp_widget_factory
  1312. *
  1313. * @param array $value Widget instance to convert to JSON.
  1314. * @param string $id_base Optional. Base of the ID of the widget being sanitized. Default null.
  1315. * @return array JSON-converted widget instance.
  1316. */
  1317. public function sanitize_widget_js_instance( $value, $id_base = null ) {
  1318. global $wp_widget_factory;
  1319. if ( empty( $value['is_widget_customizer_js_value'] ) ) {
  1320. $serialized = serialize( $value );
  1321. $js_value = array(
  1322. 'encoded_serialized_instance' => base64_encode( $serialized ),
  1323. 'title' => empty( $value['title'] ) ? '' : $value['title'],
  1324. 'is_widget_customizer_js_value' => true,
  1325. 'instance_hash_key' => $this->get_instance_hash_key( $serialized ),
  1326. );
  1327. if ( $id_base && wp_use_widgets_block_editor() ) {
  1328. $widget_object = $wp_widget_factory->get_widget_object( $id_base );
  1329. if ( ! empty( $widget_object->widget_options['show_instance_in_rest'] ) ) {
  1330. $js_value['raw_instance'] = (object) $value;
  1331. }
  1332. }
  1333. return $js_value;
  1334. }
  1335. return $value;
  1336. }
  1337. /**
  1338. * Strips out widget IDs for widgets which are no longer registered.
  1339. *
  1340. * One example where this might happen is when a plugin orphans a widget
  1341. * in a sidebar upon deactivation.
  1342. *
  1343. * @since 3.9.0
  1344. *
  1345. * @global array $wp_registered_widgets
  1346. *
  1347. * @param array $widget_ids List of widget IDs.
  1348. * @return array Parsed list of widget IDs.
  1349. */
  1350. public function sanitize_sidebar_widgets_js_instance( $widget_ids ) {
  1351. global $wp_registered_widgets;
  1352. $widget_ids = array_values(

Large files files are truncated, but you can click here to view the full file