-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy paththeme-patterns.php
More file actions
256 lines (225 loc) · 9.28 KB
/
Copy paththeme-patterns.php
File metadata and controls
256 lines (225 loc) · 9.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
<?php
class CBT_Theme_Patterns {
/**
* Strip PHP execution tags from user-supplied pattern body content.
*
* Block patterns are HTML/block markup, not PHP. Any `<?php` (or short/
* legacy variants) in user content is treated as malicious and removed
* before the body is interpolated into the exported `.php` pattern file.
*
* This helper is `public static` because it is invoked from two pipelines:
* 1. `pattern_from_wp_block()` in this class (wp_block patterns), where
* sanitisation happens BEFORE `prepare_pattern_for_export()` injects
* trusted `<?php esc_*_e(...);?>` markers.
* 2. `CBT_Theme_Templates::prepare_template_for_export()` (templates and
* template parts), where sanitisation must happen at the very start —
* BEFORE `escape_text_in_template()` injects the same trusted markers.
*
* In both cases the rule is: sanitise first, inject trusted PHP second,
* build the heredoc third. Calling this AFTER the trusted-PHP injection
* would strip the plugin's own localization helpers and break the
* "Make text translation-ready" feature.
*
* @param mixed $content User-supplied body content.
* @return mixed Same content with PHP open tags removed (when input is a non-empty string).
*/
public static function strip_php_tags( $content ) {
if ( ! is_string( $content ) || '' === $content ) {
return $content;
}
// Strip ANY `<?` open tag. On hosts with `short_open_tag=1`, PHP parses
// `<?` followed by `$`, `(`, `"`, `//`, `/*`, `;`, or `xml` as an open
// tag — preserving any of them would either re-execute as PHP or
// produce a fatal parse error when the exported `.php` file is loaded.
// Block patterns are HTML/block markup, so there's no legitimate
// `<?xml` content to preserve.
$content = preg_replace( '/<\?/', '', $content );
// Strip legacy `<script language="php">…</script>` blocks. PHP 7+
// removed this parser, but custom SAPIs / polyfills could still
// honour it. Match the entire block (opening tag → closing tag,
// inclusive of inner content).
$content = preg_replace( '#<script\s+language\s*=\s*["\']?php["\']?[^>]*>.*?</script>#is', '', $content );
return $content;
}
/**
* Build a pattern .php file from a template stdClass.
*
* IMPORTANT: this function expects `$template->content` to be already
* sanitised by the caller. The pipeline entry point is
* `CBT_Theme_Templates::prepare_template_for_export`, which strips PHP
* tags from `$template->content` BEFORE the trusted-PHP injection done
* by `escape_text_in_template`. Calling `pattern_from_template` with
* un-sanitised user content would re-introduce the PHP injection bug.
*/
public static function pattern_from_template( $template, $new_slug = null ) {
$theme_slug = $new_slug ? $new_slug : wp_get_theme()->get( 'TextDomain' );
$template_slug = str_replace( '*/', '*/', $template->slug );
$pattern_slug = $theme_slug . '/' . $template_slug;
$pattern_content = <<<PHP
<?php
/**
* Title: {$template_slug}
* Slug: {$pattern_slug}
* Inserter: no
*/
?>
{$template->content}
PHP;
return array(
'slug' => $pattern_slug,
'content' => $pattern_content,
);
}
public static function pattern_from_wp_block( $pattern_post ) {
$pattern = new stdClass();
$pattern->id = $pattern_post->ID;
$pattern->title = $pattern_post->post_title;
$pattern->name = sanitize_title_with_dashes( $pattern_post->post_title );
$pattern->slug = wp_get_theme()->get( 'TextDomain' ) . '/' . $pattern->name;
$pattern_category_list = get_the_terms( $pattern->id, 'wp_pattern_category' );
$pattern->categories = ! empty( $pattern_category_list ) ? join( ', ', wp_list_pluck( $pattern_category_list, 'name' ) ) : '';
$pattern_title = str_replace( '*/', '*/', $pattern->title );
$pattern_categories = str_replace( '*/', '*/', $pattern->categories );
$safe_body = self::strip_php_tags( $pattern_post->post_content );
$pattern->content = <<<PHP
<?php
/**
* Title: {$pattern_title}
* Slug: {$pattern->slug}
* Categories: {$pattern_categories}
*/
?>
{$safe_body}
PHP;
return $pattern;
}
public static function escape_alt_for_pattern( $html ) {
if ( empty( $html ) ) {
return $html;
}
$html = new WP_HTML_Tag_Processor( $html );
while ( $html->next_tag( 'img' ) ) {
$alt_attribute = $html->get_attribute( 'alt' );
if ( ! empty( $alt_attribute ) ) {
$html->set_attribute( 'alt', self::escape_text_for_pattern( $alt_attribute ) );
}
}
return $html->__toString();
}
public static function escape_text_for_pattern( $text ) {
if ( $text && trim( $text ) !== '' ) {
$escaped_text = addslashes( $text );
return "<?php esc_attr_e('" . $escaped_text . "', '" . wp_get_theme()->get( 'Name' ) . "');?>";
}
}
public static function create_pattern_link( $attributes ) {
$block_attributes = array_filter( $attributes );
$attributes_json = json_encode( $block_attributes, JSON_UNESCAPED_SLASHES );
return '<!-- wp:pattern ' . $attributes_json . ' /-->';
}
public static function replace_local_pattern_references( $pattern, $options = null ) {
// Find any references to pattern in templates
$templates_to_update = array();
$args = array(
'post_type' => array( 'wp_template', 'wp_template_part' ),
'posts_per_page' => -1,
's' => 'wp:block {"ref":' . $pattern->id . '}',
);
$find_pattern_refs = new WP_Query( $args );
if ( $find_pattern_refs->have_posts() ) {
foreach ( $find_pattern_refs->posts as $post ) {
$slug = $post->post_name;
array_push( $templates_to_update, $slug );
}
}
$templates_to_update = array_unique( $templates_to_update );
// Only update templates that reference the pattern
CBT_Theme_Templates::add_templates_to_local( 'all', null, null, $options, $templates_to_update );
// List all template and pattern files in the theme
$base_dir = get_stylesheet_directory();
$patterns = glob( $base_dir . DIRECTORY_SEPARATOR . 'patterns' . DIRECTORY_SEPARATOR . '*.php' );
$templates = glob( $base_dir . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . '*.html' );
$template_parts = glob( $base_dir . DIRECTORY_SEPARATOR . 'template-parts' . DIRECTORY_SEPARATOR . '*.html' );
// Replace references to the local patterns in the theme
foreach ( array_merge( $patterns, $templates, $template_parts ) as $file ) {
$file_content = file_get_contents( $file );
$file_content = str_replace( 'wp:block {"ref":' . $pattern->id . '}', 'wp:pattern {"slug":"' . $pattern->slug . '"}', $file_content );
file_put_contents( $file, $file_content );
}
CBT_Theme_Templates::clear_user_templates_customizations();
CBT_Theme_Templates::clear_user_template_parts_customizations();
}
public static function prepare_pattern_for_export( $pattern, $options = null ) {
if ( ! $options ) {
$options = array(
'localizeText' => false,
'removeNavRefs' => true,
'localizeImages' => true,
);
}
$pattern = CBT_Theme_Templates::eliminate_environment_specific_content( $pattern, $options );
if ( array_key_exists( 'localizeText', $options ) && $options['localizeText'] ) {
$pattern = CBT_Theme_Templates::escape_text_in_template( $pattern );
}
if ( array_key_exists( 'localizeImages', $options ) && $options['localizeImages'] ) {
$pattern = CBT_Theme_Media::make_template_images_local( $pattern );
// Write the media assets if there are any
if ( $pattern->media ) {
CBT_Theme_Media::add_media_to_local( $pattern->media );
}
}
return $pattern;
}
/**
* Copy the local patterns as well as any media to the theme filesystem.
*/
public static function add_patterns_to_theme( $options = null ) {
$base_dir = get_stylesheet_directory();
$patterns_dir = $base_dir . DIRECTORY_SEPARATOR . 'patterns';
$pattern_query = new WP_Query(
array(
'post_type' => 'wp_block',
'posts_per_page' => -1,
)
);
if ( $pattern_query->have_posts() ) {
// If there is no patterns folder, create it.
if ( ! is_dir( $patterns_dir ) ) {
wp_mkdir_p( $patterns_dir );
}
foreach ( $pattern_query->posts as $pattern ) {
$pattern = self::pattern_from_wp_block( $pattern );
$pattern = self::prepare_pattern_for_export( $pattern, $options );
$pattern_exists = false;
// Check pattern name doesn't already exist before creating the file.
$existing_patterns = glob( $patterns_dir . DIRECTORY_SEPARATOR . '*.php' );
foreach ( $existing_patterns as $existing_pattern ) {
if ( strpos( $existing_pattern, $pattern->name . '.php' ) !== false ) {
$pattern_exists = true;
}
}
if ( $pattern_exists ) {
return new WP_Error(
'pattern_already_exists',
sprintf(
/* Translators: Pattern name. */
__(
'A pattern with this name already exists: "%s".',
'create-block-theme'
),
$pattern->name
)
);
}
// Create the pattern file.
file_put_contents(
$patterns_dir . DIRECTORY_SEPARATOR . $pattern->name . '.php',
$pattern->content
);
self::replace_local_pattern_references( $pattern, $options );
// Remove it from the database to ensure that these patterns are loaded from the theme.
wp_delete_post( $pattern->id, true );
}
}
}
}