PluginProbe
Code Snippets / 4.0.0-beta.2
Code Snippets v4.0.0-beta.2
4.0.0-beta.2 3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 All 65 releases
code-snippets / php / Integration / Shortcodes.php

Shortcodes.php in Code Snippets 4.0.0-beta.2, at php/Integration/Shortcodes.php

424 lines 13.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Code_Snippets\Integration;
4
5 use WP_Post;
6 use Code_Snippets\Flat_Files\Snippet_Files;
7 use Code_Snippets\Model\Snippet;
8 use Code_Snippets\Utils\Code_Highlighter;
9 use function Code_Snippets\code_snippets;
10 use function Code_Snippets\get_snippet;
11 use function Code_Snippets\Settings\get_setting;
12 use function Code_Snippets\Utils\validate_network_param;
13
14 /**
15 * This class manages the shortcodes included with the plugin,
16 *
17 * @package Code_Snippets
18 */
19 class Shortcodes {
20
21 /**
22 * Name of the shortcode tag for rendering the code source
23 */
24 public const SOURCE_SHORTCODE = 'code_snippet_source';
25
26 /**
27 * Name of the shortcode tag for rendering content snippets
28 */
29 public const CONTENT_SHORTCODE = 'code_snippet';
30
31 /**
32 * Class constructor
33 */
34 public function __construct() {
35 add_action( 'the_posts', [ $this, 'enqueue_highlighting' ] );
36
37 add_shortcode( self::CONTENT_SHORTCODE, [ $this, 'render_content_shortcode' ] );
38 add_shortcode( self::SOURCE_SHORTCODE, [ $this, 'render_source_shortcode' ] );
39
40 add_filter( 'code_snippets/render_content_shortcode', 'trim' );
41 }
42
43 /**
44 * Enqueue the syntax highlighting assets if they are required for the current posts
45 *
46 * @param array<WP_Post|int>|null|false $posts List of currently visible posts.
47 *
48 * @return array<WP_Post|int>|null|false Unchanged list of posts.
49 */
50 public function enqueue_highlighting( $posts ) {
51 if ( empty( $posts ) || get_setting( 'general', 'disable_prism' ) ) {
52 return $posts;
53 }
54
55 // Loop through the posts, checking for an existing shortcode, short-circuiting if possible.
56 $found_shortcode_content = null;
57
58 foreach ( $posts as $post ) {
59 if ( false !== stripos( $post->post_content, '[' . self::SOURCE_SHORTCODE ) ||
60 false !== strpos( $post->post_content, '<!-- wp:code-snippets/source ' ) ) {
61 $found_shortcode_content = $post->post_content;
62 break;
63 }
64 }
65
66 // Load assets on the appropriate hook if a matching shortcode was found.
67 if ( null !== $found_shortcode_content ) {
68 Code_Highlighter::register_prism_assets();
69
70 add_action(
71 'wp_enqueue_scripts',
72 function () {
73 wp_enqueue_style( Code_Highlighter::PRISM_HANDLE );
74 wp_enqueue_script( Code_Highlighter::PRISM_HANDLE );
75 },
76 100
77 );
78 }
79
80 return $posts;
81 }
82
83 /**
84 * Print a message to the user if the snippet ID attribute is invalid.
85 *
86 * @param int $id Snippet ID.
87 *
88 * @return string Warning message.
89 */
90 protected function invalid_id_warning( int $id ): string {
91 // translators: %d: snippet ID.
92 $text = esc_html__( 'Could not load snippet with an invalid ID: %d.', 'code-snippets' );
93 return current_user_can( 'edit_posts' ) ? sprintf( $text, $id ) : '';
94 }
95
96 /**
97 * Allow boolean attributes to be provided without a value, similar to how React works.
98 *
99 * @param array<string|number, mixed> $atts Unfiltered shortcode attributes.
100 * @param array<string> $boolean_flags List of attribute names with boolean values.
101 *
102 * @return array<string|number, mixed> Shortcode attributes with flags converted to attributes.
103 */
104 protected function convert_boolean_attribute_flags( array $atts, array $boolean_flags ): array {
105 foreach ( $atts as $key => $value ) {
106 if ( in_array( $value, $boolean_flags, true ) && ! isset( $atts[ $value ] ) ) {
107 $atts[ $value ] = true;
108 unset( $atts[ $key ] );
109 }
110 }
111
112 return $atts;
113 }
114
115 /**
116 * Build the file path for a snippet's flat file.
117 *
118 * @param string $table_name Table name for the snippet.
119 * @param Snippet $snippet Snippet object.
120 *
121 * @return string Full file path for the snippet.
122 */
123 private function build_snippet_flat_file_path( string $table_name, Snippet $snippet ): string {
124 $handler = code_snippets()->snippet_handler_registry->get_handler( $snippet->get_type() );
125
126 return Snippet_Files::get_base_dir( $table_name, $handler->get_dir_name() ) . '/' . $snippet->id . '.' . $handler->get_file_extension();
127 }
128
129 /**
130 * Evaluate the code from a content shortcode.
131 *
132 * @param Snippet $snippet Snippet.
133 * @param array<string, mixed> $atts Shortcode attributes.
134 *
135 * @return string Evaluated shortcode content.
136 */
137 protected function evaluate_shortcode_content( Snippet $snippet, array $atts ): string {
138 if ( empty( $atts['php'] ) ) {
139 return $snippet->code;
140 }
141
142 if ( ! Snippet_Files::is_active() ) {
143 return $this->evaluate_shortcode_from_db( $snippet, $atts );
144 }
145
146 $network = validate_network_param( $snippet->network );
147 $table_name = Snippet_Files::get_hashed_table_name( code_snippets()->db->get_table_name( $network ) );
148 $filepath = $this->build_snippet_flat_file_path( $table_name, $snippet );
149
150 return file_exists( $filepath )
151 ? $this->evaluate_shortcode_from_flat_file( $filepath, $atts )
152 : $this->evaluate_shortcode_from_db( $snippet, $atts );
153 }
154
155 /**
156 * Evaluate a snippet by evaluating its code as a string.
157 *
158 * @param Snippet $snippet Snippet to execute.
159 * @param array $atts Shortcode attributes.
160 *
161 * @return string Snippet output.
162 *
163 * phpcs:disable Squiz.PHP.Eval.Discouraged
164 */
165 private function evaluate_shortcode_from_db( Snippet $snippet, array $atts ): string {
166 /**
167 * Avoiding extract is typically recommended, however in this situation we want to make it easy for snippet
168 * authors to use custom attributes.
169 *
170 * phpcs:disable WordPress.PHP.DontExtract.extract_extract
171 */
172 extract( $atts, EXTR_SKIP );
173
174 ob_start();
175 eval( "?>\n\n" . $snippet->code );
176
177 return ob_get_clean();
178 }
179
180 /**
181 * Check if being rendered within the block editor.
182 *
183 * @return bool True if in the block editor, false otherwise.
184 */
185 private function is_block_editor(): bool {
186 $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
187 return $screen && method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor();
188 }
189
190 /**
191 * Evaluate a snippet by loading its code from the filesystem.
192 *
193 * @param string $filepath Path to file to evaluate.
194 * @param array $atts Shortcode attributes.
195 *
196 * @return string Snippet output.
197 */
198 private function evaluate_shortcode_from_flat_file( string $filepath, array $atts ): string {
199 ob_start();
200
201 ( function ( $atts ) use ( $filepath ) {
202 /**
203 * Avoiding extract is typically recommended, however in this situation we want to make it easy for snippet
204 * authors to use custom attributes.
205 *
206 * phpcs:ignore WordPress.PHP.DontExtract.extract_extract
207 */
208 extract( $atts, EXTR_SKIP );
209 require_once $filepath;
210 } )( $atts );
211
212 return ob_get_clean();
213 }
214
215 /**
216 * Retrieve a content snippet from the filesystem or the database.
217 *
218 * @param int $id Snippet identifier.
219 * @param bool $network Whether the snippet is network-wide.
220 *
221 * @return Snippet|null
222 */
223 private function get_snippet( int $id, bool $network ): ?Snippet {
224 if ( ! Snippet_Files::is_active() ) {
225 return get_snippet( $id, $network );
226 }
227
228 $validated_network = validate_network_param( $network );
229 $table_name = Snippet_Files::get_hashed_table_name( code_snippets()->db->get_table_name( $validated_network ) );
230 $handler = code_snippets()->snippet_handler_registry->get_handler( 'html' );
231 $config_filepath = Snippet_Files::get_base_dir( $table_name, $handler->get_dir_name() ) . '/index.php';
232
233 if ( file_exists( $config_filepath ) ) {
234 $config = require_once $config_filepath;
235 $snippet_data = $config[ $id ] ?? null;
236
237 if ( $snippet_data ) {
238 $snippet = new Snippet( $snippet_data );
239 return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $network );
240 }
241 }
242
243 return get_snippet( $id, $network );
244 }
245
246 /**
247 * Render the value of a content shortcode
248 *
249 * @param array<string, mixed> $atts Shortcode attributes.
250 *
251 * @return string Shortcode content.
252 */
253 public function render_content_shortcode( array $atts ): string {
254 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'php', 'format', 'shortcodes', 'debug' ] );
255 $original_atts = $atts;
256
257 $atts = shortcode_atts(
258 [
259 'id' => 0,
260 'snippet_id' => 0,
261 'network' => false,
262 'php' => false,
263 'format' => false,
264 'shortcodes' => false,
265 'debug' => $this->is_block_editor(),
266 ],
267 $atts,
268 self::CONTENT_SHORTCODE
269 );
270
271 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
272 if ( ! $id ) {
273 return $this->invalid_id_warning( $id );
274 }
275
276 $snippet = $this->get_snippet( $id, (bool) $atts['network'] );
277
278 // Render the source code if this is not a shortcode snippet.
279 if ( 'content' !== $snippet->scope ) {
280 return $snippet->id ? $this->render_snippet_source( $snippet ) : $this->invalid_id_warning( $snippet->id );
281 }
282
283 // If the snippet is inactive, either display a message or render nothing.
284 if ( ! $snippet->active ) {
285 if ( $atts['debug'] ) {
286 /* translators: 1: snippet name, 2: snippet edit link */
287 $text = __( '%1$s is currently inactive. You can <a href="%2$s">edit this snippet</a> to activate it and make it visible. This message will not appear in the published post.', 'code-snippets' );
288 $snippet_name = '<strong>' . $snippet->name . '</strong>';
289 $edit_url = add_query_arg( 'id', $snippet->id, code_snippets()->get_menu_url( 'edit' ) );
290
291 $message = wp_kses(
292 sprintf( $text, $snippet_name, $edit_url ),
293 [
294 'strong' => [],
295 'a' => [
296 'href' => [],
297 ],
298 ]
299 );
300
301 return "<p>$message</p><p>" . esc_html__( 'This message will not appear in the published post.', 'code-snippets' ) . '</p>';
302 } else {
303 return '';
304 }
305 }
306
307 $content = $this->evaluate_shortcode_content( $snippet, $original_atts );
308
309 if ( $atts['format'] ) {
310 $functions = [ 'wptexturize', 'convert_smilies', 'convert_chars', 'wpautop', 'capital_P_dangit' ];
311 foreach ( $functions as $function ) {
312 $content = call_user_func( $function, $content );
313 }
314 }
315
316 if ( $atts['shortcodes'] ) {
317 // Temporarily remove this shortcode from the list to prevent recursion while executing do_shortcode.
318 remove_shortcode( self::CONTENT_SHORTCODE );
319 $content = do_shortcode( $atts['format'] ? shortcode_unautop( $content ) : $content );
320 add_shortcode( self::CONTENT_SHORTCODE, [ $this, 'render_content_shortcode' ] );
321 }
322
323 return apply_filters( 'code_snippets/content_shortcode', $content, $snippet, $atts, $original_atts );
324 }
325
326 /**
327 * Converts a value and key into an HTML attribute pair.
328 *
329 * @param string $value Attribute value.
330 * @param string $key Attribute name.
331 *
332 * @return void
333 */
334 private static function create_attribute_pair( string &$value, string $key ) {
335 $value = sprintf( '%s="%s"', sanitize_key( $key ), esc_attr( $value ) );
336 }
337
338 /**
339 * Render the source code of a given snippet
340 *
341 * @param Snippet $snippet Snippet object.
342 * @param array<string, mixed> $atts Shortcode attributes.
343 *
344 * @return string Shortcode content.
345 */
346 private function render_snippet_source( Snippet $snippet, array $atts = [] ): string {
347 $atts = array_merge(
348 array(
349 'line_numbers' => false,
350 'highlight_lines' => '',
351 ),
352 $atts
353 );
354
355 $language = 'css' === $snippet->type ? 'css' : ( 'js' === $snippet->type ? 'js' : 'php' );
356
357 $pre_attributes = array(
358 'id' => "code-snippet-source-$snippet->id",
359 'class' => 'code-snippet-source',
360 );
361
362 $code_attributes = array(
363 'class' => "language-$language",
364 );
365
366 if ( $atts['line_numbers'] ) {
367 $code_attributes['class'] .= ' line-numbers';
368 $pre_attributes['class'] .= ' linkable-line-numbers';
369 }
370
371 if ( $atts['highlight_lines'] ) {
372 $pre_attributes['data-line'] = $atts['highlight_lines'];
373 }
374
375 $pre_attributes = apply_filters( 'code_snippets/prism_pre_attributes', $pre_attributes, $snippet, $atts );
376 $code_attributes = apply_filters( 'code_snippets/prism_code_attributes', $code_attributes, $snippet, $atts );
377
378 array_walk( $code_attributes, array( $this, 'create_attribute_pair' ) );
379 array_walk( $pre_attributes, array( $this, 'create_attribute_pair' ) );
380
381 $code = 'php' === $snippet->type ? "<?php\n\n$snippet->code" : $snippet->code;
382
383 $output = sprintf(
384 '<pre %s><code %s>%s</code></pre>',
385 implode( ' ', $pre_attributes ),
386 implode( ' ', $code_attributes ),
387 esc_html( $code )
388 );
389
390 return apply_filters( 'code_snippets/render_source_shortcode', $output, $snippet, $atts );
391 }
392
393 /**
394 * Render the value of a source shortcode
395 *
396 * @param array<string, mixed> $atts Shortcode attributes.
397 *
398 * @return string Shortcode content.
399 */
400 public function render_source_shortcode( array $atts ): string {
401 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'line_numbers' ] );
402
403 $atts = shortcode_atts(
404 array(
405 'id' => 0,
406 'snippet_id' => 0,
407 'network' => false,
408 'line_numbers' => false,
409 'highlight_lines' => '',
410 ),
411 $atts,
412 self::SOURCE_SHORTCODE
413 );
414
415 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
416 if ( ! $id ) {
417 return $this->invalid_id_warning( $id );
418 }
419
420 $snippet = $this->get_snippet( $id, (bool) $atts['network'] );
421 return $this->render_snippet_source( $snippet, $atts );
422 }
423 }
424