class-wp-customize-selective-refresh.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. /**
  3. * Customize API: WP_Customize_Selective_Refresh class
  4. *
  5. * @package WordPress
  6. * @subpackage Customize
  7. * @since 4.5.0
  8. */
  9. /**
  10. * Core Customizer class for implementing selective refresh.
  11. *
  12. * @since 4.5.0
  13. */
  14. final class WP_Customize_Selective_Refresh {
  15. /**
  16. * Query var used in requests to render partials.
  17. *
  18. * @since 4.5.0
  19. */
  20. const RENDER_QUERY_VAR = 'wp_customize_render_partials';
  21. /**
  22. * Customize manager.
  23. *
  24. * @since 4.5.0
  25. * @var WP_Customize_Manager
  26. */
  27. public $manager;
  28. /**
  29. * Registered instances of WP_Customize_Partial.
  30. *
  31. * @since 4.5.0
  32. * @var WP_Customize_Partial[]
  33. */
  34. protected $partials = array();
  35. /**
  36. * Log of errors triggered when partials are rendered.
  37. *
  38. * @since 4.5.0
  39. * @var array
  40. */
  41. protected $triggered_errors = array();
  42. /**
  43. * Keep track of the current partial being rendered.
  44. *
  45. * @since 4.5.0
  46. * @var string|null
  47. */
  48. protected $current_partial_id;
  49. /**
  50. * Plugin bootstrap for Partial Refresh functionality.
  51. *
  52. * @since 4.5.0
  53. *
  54. * @param WP_Customize_Manager $manager Manager instance.
  55. */
  56. public function __construct( WP_Customize_Manager $manager ) {
  57. $this->manager = $manager;
  58. require_once( ABSPATH . WPINC . '/customize/class-wp-customize-partial.php' );
  59. add_action( 'customize_preview_init', array( $this, 'init_preview' ) );
  60. }
  61. /**
  62. * Retrieves the registered partials.
  63. *
  64. * @since 4.5.0
  65. *
  66. * @return array Partials.
  67. */
  68. public function partials() {
  69. return $this->partials;
  70. }
  71. /**
  72. * Adds a partial.
  73. *
  74. * @since 4.5.0
  75. *
  76. * @param WP_Customize_Partial|string $id Customize Partial object, or Panel ID.
  77. * @param array $args {
  78. * Optional. Array of properties for the new Partials object. Default empty array.
  79. *
  80. * @type string $type Type of the partial to be created.
  81. * @type string $selector The jQuery selector to find the container element for the partial, that is, a partial's placement.
  82. * @type array $settings IDs for settings tied to the partial.
  83. * @type string $primary_setting The ID for the setting that this partial is primarily responsible for
  84. * rendering. If not supplied, it will default to the ID of the first setting.
  85. * @type string $capability Capability required to edit this partial.
  86. * Normally this is empty and the capability is derived from the capabilities
  87. * of the associated `$settings`.
  88. * @type callable $render_callback Render callback.
  89. * Callback is called with one argument, the instance of WP_Customize_Partial.
  90. * The callback can either echo the partial or return the partial as a string,
  91. * or return false if error.
  92. * @type bool $container_inclusive Whether the container element is included in the partial, or if only
  93. * the contents are rendered.
  94. * @type bool $fallback_refresh Whether to refresh the entire preview in case a partial cannot be refreshed.
  95. * A partial render is considered a failure if the render_callback returns
  96. * false.
  97. * }
  98. * @return WP_Customize_Partial The instance of the panel that was added.
  99. */
  100. public function add_partial( $id, $args = array() ) {
  101. if ( $id instanceof WP_Customize_Partial ) {
  102. $partial = $id;
  103. } else {
  104. $class = 'WP_Customize_Partial';
  105. /** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */
  106. $args = apply_filters( 'customize_dynamic_partial_args', $args, $id );
  107. /** This filter is documented in wp-includes/customize/class-wp-customize-selective-refresh.php */
  108. $class = apply_filters( 'customize_dynamic_partial_class', $class, $id, $args );
  109. $partial = new $class( $this, $id, $args );
  110. }
  111. $this->partials[ $partial->id ] = $partial;
  112. return $partial;
  113. }
  114. /**
  115. * Retrieves a partial.
  116. *
  117. * @since 4.5.0
  118. *
  119. * @param string $id Customize Partial ID.
  120. * @return WP_Customize_Partial|null The partial, if set. Otherwise null.
  121. */
  122. public function get_partial( $id ) {
  123. if ( isset( $this->partials[ $id ] ) ) {
  124. return $this->partials[ $id ];
  125. } else {
  126. return null;
  127. }
  128. }
  129. /**
  130. * Removes a partial.
  131. *
  132. * @since 4.5.0
  133. *
  134. * @param string $id Customize Partial ID.
  135. */
  136. public function remove_partial( $id ) {
  137. unset( $this->partials[ $id ] );
  138. }
  139. /**
  140. * Initializes the Customizer preview.
  141. *
  142. * @since 4.5.0
  143. */
  144. public function init_preview() {
  145. add_action( 'template_redirect', array( $this, 'handle_render_partials_request' ) );
  146. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_preview_scripts' ) );
  147. }
  148. /**
  149. * Enqueues preview scripts.
  150. *
  151. * @since 4.5.0
  152. */
  153. public function enqueue_preview_scripts() {
  154. wp_enqueue_script( 'customize-selective-refresh' );
  155. add_action( 'wp_footer', array( $this, 'export_preview_data' ), 1000 );
  156. }
  157. /**
  158. * Exports data in preview after it has finished rendering so that partials can be added at runtime.
  159. *
  160. * @since 4.5.0
  161. */
  162. public function export_preview_data() {
  163. $partials = array();
  164. foreach ( $this->partials() as $partial ) {
  165. if ( $partial->check_capabilities() ) {
  166. $partials[ $partial->id ] = $partial->json();
  167. }
  168. }
  169. $switched_locale = switch_to_locale( get_user_locale() );
  170. $l10n = array(
  171. 'shiftClickToEdit' => __( 'Shift-click to edit this element.' ),
  172. 'clickEditMenu' => __( 'Click to edit this menu.' ),
  173. 'clickEditWidget' => __( 'Click to edit this widget.' ),
  174. 'clickEditTitle' => __( 'Click to edit the site title.' ),
  175. 'clickEditMisc' => __( 'Click to edit this element.' ),
  176. /* translators: %s: document.write() */
  177. 'badDocumentWrite' => sprintf( __( '%s is forbidden' ), 'document.write()' ),
  178. );
  179. if ( $switched_locale ) {
  180. restore_previous_locale();
  181. }
  182. $exports = array(
  183. 'partials' => $partials,
  184. 'renderQueryVar' => self::RENDER_QUERY_VAR,
  185. 'l10n' => $l10n,
  186. );
  187. // Export data to JS.
  188. echo sprintf( '<script>var _customizePartialRefreshExports = %s;</script>', wp_json_encode( $exports ) );
  189. }
  190. /**
  191. * Registers dynamically-created partials.
  192. *
  193. * @since 4.5.0
  194. *
  195. * @see WP_Customize_Manager::add_dynamic_settings()
  196. *
  197. * @param string[] $partial_ids Array of the partial IDs to add.
  198. * @return WP_Customize_Partial[] Array of added WP_Customize_Partial instances.
  199. */
  200. public function add_dynamic_partials( $partial_ids ) {
  201. $new_partials = array();
  202. foreach ( $partial_ids as $partial_id ) {
  203. // Skip partials already created.
  204. $partial = $this->get_partial( $partial_id );
  205. if ( $partial ) {
  206. continue;
  207. }
  208. $partial_args = false;
  209. $partial_class = 'WP_Customize_Partial';
  210. /**
  211. * Filters a dynamic partial's constructor arguments.
  212. *
  213. * For a dynamic partial to be registered, this filter must be employed
  214. * to override the default false value with an array of args to pass to
  215. * the WP_Customize_Partial constructor.
  216. *
  217. * @since 4.5.0
  218. *
  219. * @param false|array $partial_args The arguments to the WP_Customize_Partial constructor.
  220. * @param string $partial_id ID for dynamic partial.
  221. */
  222. $partial_args = apply_filters( 'customize_dynamic_partial_args', $partial_args, $partial_id );
  223. if ( false === $partial_args ) {
  224. continue;
  225. }
  226. /**
  227. * Filters the class used to construct partials.
  228. *
  229. * Allow non-statically created partials to be constructed with custom WP_Customize_Partial subclass.
  230. *
  231. * @since 4.5.0
  232. *
  233. * @param string $partial_class WP_Customize_Partial or a subclass.
  234. * @param string $partial_id ID for dynamic partial.
  235. * @param array $partial_args The arguments to the WP_Customize_Partial constructor.
  236. */
  237. $partial_class = apply_filters( 'customize_dynamic_partial_class', $partial_class, $partial_id, $partial_args );
  238. $partial = new $partial_class( $this, $partial_id, $partial_args );
  239. $this->add_partial( $partial );
  240. $new_partials[] = $partial;
  241. }
  242. return $new_partials;
  243. }
  244. /**
  245. * Checks whether the request is for rendering partials.
  246. *
  247. * Note that this will not consider whether the request is authorized or valid,
  248. * just that essentially the route is a match.
  249. *
  250. * @since 4.5.0
  251. *
  252. * @return bool Whether the request is for rendering partials.
  253. */
  254. public function is_render_partials_request() {
  255. return ! empty( $_POST[ self::RENDER_QUERY_VAR ] );
  256. }
  257. /**
  258. * Handles PHP errors triggered during rendering the partials.
  259. *
  260. * These errors will be relayed back to the client in the Ajax response.
  261. *
  262. * @since 4.5.0
  263. *
  264. * @param int $errno Error number.
  265. * @param string $errstr Error string.
  266. * @param string $errfile Error file.
  267. * @param string $errline Error line.
  268. * @return true Always true.
  269. */
  270. public function handle_error( $errno, $errstr, $errfile = null, $errline = null ) {
  271. $this->triggered_errors[] = array(
  272. 'partial' => $this->current_partial_id,
  273. 'error_number' => $errno,
  274. 'error_string' => $errstr,
  275. 'error_file' => $errfile,
  276. 'error_line' => $errline,
  277. );
  278. return true;
  279. }
  280. /**
  281. * Handles the Ajax request to return the rendered partials for the requested placements.
  282. *
  283. * @since 4.5.0
  284. */
  285. public function handle_render_partials_request() {
  286. if ( ! $this->is_render_partials_request() ) {
  287. return;
  288. }
  289. /*
  290. * Note that is_customize_preview() returning true will entail that the
  291. * user passed the 'customize' capability check and the nonce check, since
  292. * WP_Customize_Manager::setup_theme() is where the previewing flag is set.
  293. */
  294. if ( ! is_customize_preview() ) {
  295. wp_send_json_error( 'expected_customize_preview', 403 );
  296. } elseif ( ! isset( $_POST['partials'] ) ) {
  297. wp_send_json_error( 'missing_partials', 400 );
  298. }
  299. // Ensure that doing selective refresh on 404 template doesn't result in fallback rendering behavior (full refreshes).
  300. status_header( 200 );
  301. $partials = json_decode( wp_unslash( $_POST['partials'] ), true );
  302. if ( ! is_array( $partials ) ) {
  303. wp_send_json_error( 'malformed_partials' );
  304. }
  305. $this->add_dynamic_partials( array_keys( $partials ) );
  306. /**
  307. * Fires immediately before partials are rendered.
  308. *
  309. * Plugins may do things like call wp_enqueue_scripts() and gather a list of the scripts
  310. * and styles which may get enqueued in the response.
  311. *
  312. * @since 4.5.0
  313. *
  314. * @param WP_Customize_Selective_Refresh $this Selective refresh component.
  315. * @param array $partials Placements' context data for the partials rendered in the request.
  316. * The array is keyed by partial ID, with each item being an array of
  317. * the placements' context data.
  318. */
  319. do_action( 'customize_render_partials_before', $this, $partials );
  320. set_error_handler( array( $this, 'handle_error' ), error_reporting() );
  321. $contents = array();
  322. foreach ( $partials as $partial_id => $container_contexts ) {
  323. $this->current_partial_id = $partial_id;
  324. if ( ! is_array( $container_contexts ) ) {
  325. wp_send_json_error( 'malformed_container_contexts' );
  326. }
  327. $partial = $this->get_partial( $partial_id );
  328. if ( ! $partial || ! $partial->check_capabilities() ) {
  329. $contents[ $partial_id ] = null;
  330. continue;
  331. }
  332. $contents[ $partial_id ] = array();
  333. // @todo The array should include not only the contents, but also whether the container is included?
  334. if ( empty( $container_contexts ) ) {
  335. // Since there are no container contexts, render just once.
  336. $contents[ $partial_id ][] = $partial->render( null );
  337. } else {
  338. foreach ( $container_contexts as $container_context ) {
  339. $contents[ $partial_id ][] = $partial->render( $container_context );
  340. }
  341. }
  342. }
  343. $this->current_partial_id = null;
  344. restore_error_handler();
  345. /**
  346. * Fires immediately after partials are rendered.
  347. *
  348. * Plugins may do things like call wp_footer() to scrape scripts output and return them
  349. * via the {@see 'customize_render_partials_response'} filter.
  350. *
  351. * @since 4.5.0
  352. *
  353. * @param WP_Customize_Selective_Refresh $this Selective refresh component.
  354. * @param array $partials Placements' context data for the partials rendered in the request.
  355. * The array is keyed by partial ID, with each item being an array of
  356. * the placements' context data.
  357. */
  358. do_action( 'customize_render_partials_after', $this, $partials );
  359. $response = array(
  360. 'contents' => $contents,
  361. );
  362. if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
  363. $response['errors'] = $this->triggered_errors;
  364. }
  365. $setting_validities = $this->manager->validate_setting_values( $this->manager->unsanitized_post_values() );
  366. $exported_setting_validities = array_map( array( $this->manager, 'prepare_setting_validity_for_js' ), $setting_validities );
  367. $response['setting_validities'] = $exported_setting_validities;
  368. /**
  369. * Filters the response from rendering the partials.
  370. *
  371. * Plugins may use this filter to inject `$scripts` and `$styles`, which are dependencies
  372. * for the partials being rendered. The response data will be available to the client via
  373. * the `render-partials-response` JS event, so the client can then inject the scripts and
  374. * styles into the DOM if they have not already been enqueued there.
  375. *
  376. * If plugins do this, they'll need to take care for any scripts that do `document.write()`
  377. * and make sure that these are not injected, or else to override the function to no-op,
  378. * or else the page will be destroyed.
  379. *
  380. * Plugins should be aware that `$scripts` and `$styles` may eventually be included by
  381. * default in the response.
  382. *
  383. * @since 4.5.0
  384. *
  385. * @param array $response {
  386. * Response.
  387. *
  388. * @type array $contents Associative array mapping a partial ID its corresponding array of contents
  389. * for the containers requested.
  390. * @type array $errors List of errors triggered during rendering of partials, if `WP_DEBUG_DISPLAY`
  391. * is enabled.
  392. * }
  393. * @param WP_Customize_Selective_Refresh $this Selective refresh component.
  394. * @param array $partials Placements' context data for the partials rendered in the request.
  395. * The array is keyed by partial ID, with each item being an array of
  396. * the placements' context data.
  397. */
  398. $response = apply_filters( 'customize_render_partials_response', $response, $this, $partials );
  399. wp_send_json_success( $response );
  400. }
  401. }