You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

2052 lines
64 KiB

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