PluginProbe
Gutenberg / 8.7.1
Gutenberg v8.7.1
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / lib / template-loader.php

template-loader.php in Gutenberg 8.7.1, at lib/template-loader.php

474 lines 16.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Block template loader functions.
4 *
5 * @package gutenberg
6 */
7
8 /**
9 * Return a list of all overrideable default template types.
10 *
11 * @see get_query_template
12 *
13 * @return string[] List of all overrideable default template types.
14 */
15 function get_template_types() {
16 return array(
17 'index',
18 '404',
19 'archive',
20 'author',
21 'category',
22 'tag',
23 'taxonomy',
24 'date',
25 'embed',
26 'home',
27 'front-page',
28 'privacy-policy',
29 'page',
30 'search',
31 'single',
32 'singular',
33 'attachment',
34 );
35 }
36
37 /**
38 * Adds necessary filters to use 'wp_template' posts instead of theme template files.
39 */
40 function gutenberg_add_template_loader_filters() {
41 if ( ! post_type_exists( 'wp_template' ) ) {
42 return;
43 }
44
45 foreach ( get_template_types() as $template_type ) {
46 if ( 'embed' === $template_type ) { // Skip 'embed' for now because it is not a regular template type.
47 continue;
48 }
49 add_filter( str_replace( '-', '', $template_type ) . '_template', 'gutenberg_override_query_template', 20, 3 );
50 }
51 }
52 add_action( 'wp_loaded', 'gutenberg_add_template_loader_filters' );
53
54 /**
55 * Get the template hierarchy for a given template type.
56 *
57 * Internally, this filters into the "{$type}_template_hierarchy" hook to record the type-specific template hierarchy.
58 *
59 * @param string $template_type A template type.
60 * @return string[] A list of template candidates, in descending order of priority.
61 */
62 function get_template_hierarchy( $template_type ) {
63 if ( ! in_array( $template_type, get_template_types(), true ) ) {
64 return array();
65 }
66
67 $get_template_function = 'get_' . str_replace( '-', '_', $template_type ) . '_template'; // front-page -> get_front_page_template.
68 $template_hierarchy_filter = str_replace( '-', '', $template_type ) . '_template_hierarchy'; // front-page -> frontpage_template_hierarchy.
69
70 $result = array();
71 $template_hierarchy_filter_function = function( $templates ) use ( &$result ) {
72 $result = $templates;
73 return $templates;
74 };
75
76 add_filter( $template_hierarchy_filter, $template_hierarchy_filter_function, 20, 1 );
77 call_user_func( $get_template_function ); // This invokes template_hierarchy_filter.
78 remove_filter( $template_hierarchy_filter, $template_hierarchy_filter_function, 20 );
79
80 return $result;
81 }
82
83 /**
84 * Filters into the "{$type}_template" hooks to redirect them to the Full Site Editing template canvas.
85 *
86 * Internally, this communicates the block content that needs to be used by the template canvas through a global variable.
87 *
88 * @param string $template Path to the template. See locate_template().
89 * @param string $type Sanitized filename without extension.
90 * @param array $templates A list of template candidates, in descending order of priority.
91 * @return string The path to the Full Site Editing template canvas file.
92 */
93 function gutenberg_override_query_template( $template, $type, array $templates = array() ) {
94 global $_wp_current_template_content;
95
96 $current_template = gutenberg_find_template_post_and_parts( $type, $templates );
97
98 if ( $current_template ) {
99 $_wp_current_template_content = empty( $current_template['template_post']->post_content ) ? __( 'Empty template.', 'gutenberg' ) : $current_template['template_post']->post_content;
100
101 if ( isset( $_GET['_wp-find-template'] ) ) {
102 wp_send_json_success( $current_template['template_post'] );
103 }
104 } else {
105 if ( 'index' === $type ) {
106 if ( isset( $_GET['_wp-find-template'] ) ) {
107 wp_send_json_error( array( 'message' => __( 'No matching template found.', 'gutenberg' ) ) );
108 }
109 } else {
110 return false; // So that the template loader keeps looking for templates.
111 }
112 }
113
114 // Add hooks for template canvas.
115 // Add viewport meta tag.
116 add_action( 'wp_head', 'gutenberg_viewport_meta_tag', 0 );
117
118 // Render title tag with content, regardless of whether theme has title-tag support.
119 remove_action( 'wp_head', '_wp_render_title_tag', 1 ); // Remove conditional title tag rendering...
120 add_action( 'wp_head', 'gutenberg_render_title_tag', 1 ); // ...and make it unconditional.
121
122 // This file will be included instead of the theme's template file.
123 return gutenberg_dir_path() . 'lib/template-canvas.php';
124 }
125
126 /**
127 * Recursively traverses a block tree, creating auto drafts
128 * for any encountered template parts without a fixed post.
129 *
130 * @access private
131 *
132 * @param array $block The root block to start traversing from.
133 * @return int[] A list of template parts IDs for the given block.
134 */
135 function create_auto_draft_for_template_part_block( $block ) {
136 $template_part_ids = array();
137
138 if ( 'core/template-part' === $block['blockName'] && isset( $block['attrs']['slug'] ) ) {
139 if ( isset( $block['attrs']['postId'] ) ) {
140 // Template part is customized.
141 $template_part_id = $block['attrs']['postId'];
142 } else {
143 // A published post might already exist if this template part
144 // was customized elsewhere or if it's part of a customized
145 // template. We also check if an auto-draft was already created
146 // because preloading can make this run twice, so, different code
147 // paths can end up with different posts for the same template part.
148 // E.g. The server could send back post ID 1 to the client, preload,
149 // and create another auto-draft. So, if the client tries to resolve the
150 // post ID from the slug and theme, it won't match with what the server sent.
151 $template_part_query = new WP_Query(
152 array(
153 'post_type' => 'wp_template_part',
154 'post_status' => array( 'publish', 'auto-draft' ),
155 'name' => $block['attrs']['slug'],
156 'meta_key' => 'theme',
157 'meta_value' => $block['attrs']['theme'],
158 'posts_per_page' => 1,
159 'no_found_rows' => true,
160 )
161 );
162 $template_part_post = $template_part_query->have_posts() ? $template_part_query->next_post() : null;
163 if ( $template_part_post && 'auto-draft' !== $template_part_post->post_status ) {
164 $template_part_id = $template_part_post->ID;
165 } else {
166 // Template part is not customized, get it from a file and make an auto-draft for it, unless one already exists
167 // and the underlying file hasn't changed.
168 $template_part_file_path =
169 get_stylesheet_directory() . '/block-template-parts/' . $block['attrs']['slug'] . '.html';
170 if ( ! file_exists( $template_part_file_path ) ) {
171 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
172 $template_part_file_path =
173 dirname( __FILE__ ) . '/demo-block-template-parts/' . $block['attrs']['slug'] . '.html';
174 if ( ! file_exists( $template_part_file_path ) ) {
175 $template_part_file_path = false;
176 }
177 } else {
178 $template_part_file_path = false;
179 }
180 }
181
182 if ( $template_part_file_path ) {
183 $file_contents = file_get_contents( $template_part_file_path );
184 if ( $template_part_post && $template_part_post->post_content === $file_contents ) {
185 $template_part_id = $template_part_post->ID;
186 } else {
187 $template_part_id = wp_insert_post(
188 array(
189 'post_content' => $file_contents,
190 'post_title' => $block['attrs']['slug'],
191 'post_status' => 'auto-draft',
192 'post_type' => 'wp_template_part',
193 'post_name' => $block['attrs']['slug'],
194 'meta_input' => array(
195 'theme' => $block['attrs']['theme'],
196 ),
197 )
198 );
199 }
200 }
201 }
202 }
203 $template_part_ids[ $block['attrs']['slug'] ] = $template_part_id;
204 }
205
206 foreach ( $block['innerBlocks'] as $inner_block ) {
207 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $inner_block ) );
208 }
209 return $template_part_ids;
210 }
211
212 /**
213 * Return the correct 'wp_template' post and template part IDs for the current template.
214 *
215 * Accepts an optional $template_hierarchy argument as a hint.
216 *
217 * @param string $template_type The current template type.
218 * @param string[] $template_hierarchy (optional) The current template hierarchy, ordered by priority.
219 * @return null|array {
220 * @type WP_Post|null template_post A template post object, or null if none could be found.
221 * @type int[] A list of template parts IDs for the template.
222 * }
223 */
224 function gutenberg_find_template_post_and_parts( $template_type, $template_hierarchy = array() ) {
225 if ( ! $template_type ) {
226 return null;
227 }
228
229 if ( empty( $template_hierarchy ) ) {
230 if ( 'index' === $template_type ) {
231 $template_hierarchy = get_template_hierarchy( 'index' );
232 } else {
233 $template_hierarchy = array_merge( get_template_hierarchy( $template_type ), get_template_hierarchy( 'index' ) );
234 }
235 }
236
237 $slugs = array_map(
238 'gutenberg_strip_php_suffix',
239 $template_hierarchy
240 );
241
242 // Find most specific 'wp_template' post matching the hierarchy.
243 $template_query = new WP_Query(
244 array(
245 'post_type' => 'wp_template',
246 'post_status' => 'publish',
247 'post_name__in' => $slugs,
248 'orderby' => 'post_name__in',
249 'posts_per_page' => 1,
250 'no_found_rows' => true,
251 )
252 );
253
254 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : null;
255
256 // Build map of template slugs to their priority in the current hierarchy.
257 $slug_priorities = array_flip( $slugs );
258
259 // See if there is a theme block template with higher priority than the resolved template post.
260 $higher_priority_block_template_path = null;
261 $higher_priority_block_template_priority = PHP_INT_MAX;
262 $block_template_files = glob( get_stylesheet_directory() . '/block-templates/*.html' );
263 $block_template_files = is_array( $block_template_files ) ? $block_template_files : array();
264 if ( is_child_theme() ) {
265 $child_block_template_files = glob( get_template_directory() . '/block-templates/*.html' );
266 $child_block_template_files = is_array( $child_block_template_files ) ? $child_block_template_files : array();
267 $block_template_files = array_merge( $block_template_files, $child_block_template_files );
268 }
269 if ( gutenberg_is_experiment_enabled( 'gutenberg-full-site-editing-demo' ) ) {
270 $demo_block_template_files = glob( dirname( __FILE__ ) . '/demo-block-templates/*.html' );
271 $demo_block_template_files = is_array( $demo_block_template_files ) ? $demo_block_template_files : array();
272 $block_template_files = array_merge( $block_template_files, $demo_block_template_files );
273 }
274 foreach ( $block_template_files as $path ) {
275 if ( ! isset( $slug_priorities[ basename( $path, '.html' ) ] ) ) {
276 continue;
277 }
278 $theme_block_template_priority = $slug_priorities[ basename( $path, '.html' ) ];
279 if (
280 $theme_block_template_priority < $higher_priority_block_template_priority &&
281 ( empty( $current_template_post ) || $theme_block_template_priority < $slug_priorities[ $current_template_post->post_name ] )
282 ) {
283 $higher_priority_block_template_path = $path;
284 $higher_priority_block_template_priority = $theme_block_template_priority;
285 }
286 }
287
288 // If there is, use it instead.
289 if ( isset( $higher_priority_block_template_path ) ) {
290 $post_name = basename( $higher_priority_block_template_path, '.html' );
291 $file_contents = file_get_contents( $higher_priority_block_template_path );
292 $current_template_post = array(
293 'post_content' => $file_contents,
294 'post_title' => $post_name,
295 'post_status' => 'auto-draft',
296 'post_type' => 'wp_template',
297 'post_name' => $post_name,
298 );
299 if ( is_admin() || defined( 'REST_REQUEST' ) ) {
300 $template_query = new WP_Query(
301 array(
302 'post_type' => 'wp_template',
303 'post_status' => 'auto-draft',
304 'name' => $post_name,
305 'posts_per_page' => 1,
306 'no_found_rows' => true,
307 )
308 );
309 $current_template_post = $template_query->have_posts() ? $template_query->next_post() : $current_template_post;
310
311 // Only create auto-draft of block template for editing
312 // in admin screens, when necessary, because the underlying
313 // file has changed.
314 if ( is_array( $current_template_post ) || $current_template_post->post_content !== $file_contents ) {
315 if ( ! is_array( $current_template_post ) ) {
316 $current_template_post->post_content = $file_contents;
317 }
318 $current_template_post = get_post(
319 wp_insert_post( $current_template_post )
320 );
321 }
322 } else {
323 $current_template_post = new WP_Post(
324 (object) $current_template_post
325 );
326 }
327 }
328
329 // If we haven't found any template post by here, it means that this theme doesn't even come with a fallback
330 // `index.html` block template. We create one so that people that are trying to access the editor are greeted
331 // with a blank page rather than an error.
332 if ( ! $current_template_post && ( is_admin() || defined( 'REST_REQUEST' ) ) ) {
333 $current_template_post = array(
334 'post_title' => 'index',
335 'post_status' => 'auto-draft',
336 'post_type' => 'wp_template',
337 'post_name' => 'index',
338 );
339 $current_template_post = get_post(
340 wp_insert_post( $current_template_post )
341 );
342 }
343
344 if ( $current_template_post ) {
345 $template_part_ids = array();
346 if ( is_admin() || defined( 'REST_REQUEST' ) ) {
347 foreach ( parse_blocks( $current_template_post->post_content ) as $block ) {
348 $template_part_ids = array_merge( $template_part_ids, create_auto_draft_for_template_part_block( $block ) );
349 }
350 }
351 return array(
352 'template_post' => $current_template_post,
353 'template_part_ids' => $template_part_ids,
354 );
355 }
356 return null;
357 }
358
359 /**
360 * Displays title tag with content, regardless of whether theme has title-tag support.
361 *
362 * @see _wp_render_title_tag()
363 */
364 function gutenberg_render_title_tag() {
365 echo '<title>' . wp_get_document_title() . '</title>' . "\n";
366 }
367
368 /**
369 * Renders the markup for the current template.
370 */
371 function gutenberg_render_the_template() {
372 global $_wp_current_template_content;
373 global $wp_embed;
374
375 if ( ! $_wp_current_template_content ) {
376 echo '<h1>' . esc_html__( 'No matching template found', 'gutenberg' ) . '</h1>';
377 return;
378 }
379
380 $content = $wp_embed->run_shortcode( $_wp_current_template_content );
381 $content = $wp_embed->autoembed( $content );
382 $content = do_blocks( $content );
383 $content = wptexturize( $content );
384 if ( function_exists( 'wp_filter_content_tags' ) ) {
385 $content = wp_filter_content_tags( $content );
386 } else {
387 $content = wp_make_content_images_responsive( $content );
388 }
389 $content = str_replace( ']]>', ']]&gt;', $content );
390
391 // Wrap block template in .wp-site-blocks to allow for specific descendant styles
392 // (e.g. `.wp-site-blocks > *`).
393 echo '<div class="wp-site-blocks">';
394 echo $content; // phpcs:ignore WordPress.Security.EscapeOutput
395 echo '</div>';
396 }
397
398 /**
399 * Renders a 'viewport' meta tag.
400 *
401 * This is hooked into {@see 'wp_head'} to decouple its output from the default template canvas.
402 */
403 function gutenberg_viewport_meta_tag() {
404 echo '<meta name="viewport" content="width=device-width, initial-scale=1" />' . "\n";
405 }
406
407 /**
408 * Strips .php suffix from template file names.
409 *
410 * @access private
411 *
412 * @param string $template_file Template file name.
413 * @return string Template file name without extension.
414 */
415 function gutenberg_strip_php_suffix( $template_file ) {
416 return preg_replace( '/\.php$/', '', $template_file );
417 }
418
419 /**
420 * Extends default editor settings to enable template and template part editing.
421 *
422 * @param array $settings Default editor settings.
423 *
424 * @return array Filtered editor settings.
425 */
426 function gutenberg_template_loader_filter_block_editor_settings( $settings ) {
427 global $post;
428
429 if ( ! $post || ! post_type_exists( 'wp_template' ) || ! post_type_exists( 'wp_template_part' ) ) {
430 return $settings;
431 }
432
433 // If this is the Site Editor, auto-drafts for template parts have already been generated
434 // through `filter_rest_wp_template_part_query`, when called via the REST API.
435 if ( isset( $settings['editSiteInitialState'] ) ) {
436 return $settings;
437 }
438
439 // Otherwise, create template part auto-drafts for the edited post.
440 $post = get_post();
441 foreach ( parse_blocks( $post->post_content ) as $block ) {
442 create_auto_draft_for_template_part_block( $block );
443 }
444
445 // TODO: Set editing mode and current template ID for editing modes support.
446 return $settings;
447 }
448 add_filter( 'block_editor_settings', 'gutenberg_template_loader_filter_block_editor_settings' );
449
450 /**
451 * Removes post details from block context when rendering a block template.
452 *
453 * @param array $context Default context.
454 *
455 * @return array Filtered context.
456 */
457 function gutenberg_template_render_without_post_block_context( $context ) {
458 /*
459 * When loading a template or template part directly and not through a page
460 * that resolves it, the top-level post ID and type context get set to that
461 * of the template part. Templates are just the structure of a site, and
462 * they should not be available as post context because blocks like Post
463 * Content would recurse infinitely.
464 */
465 if ( isset( $context['postType'] ) &&
466 ( 'wp_template' === $context['postType'] || 'wp_template_part' === $context['postType'] ) ) {
467 unset( $context['postId'] );
468 unset( $context['postType'] );
469 }
470
471 return $context;
472 }
473 add_filter( 'render_block_context', 'gutenberg_template_render_without_post_block_context' );
474