PluginProbe
Code Snippets / 3.5.0
Code Snippets v3.5.0
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 3.0.1 All 64 releases
code-snippets / php / front-end / class-frontend.php

class-frontend.php in Code Snippets 3.5.0, at php/front-end/class-frontend.php

433 lines 11.5 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;
4
5 use WP_Post;
6 use WP_REST_Response;
7 use WP_REST_Server;
8
9 /**
10 * This class manages the shortcodes included with the plugin
11 *
12 * @package Code_Snippets
13 */
14 class Frontend {
15
16 /**
17 * Name of the shortcode tag for rendering the code source
18 */
19 const SOURCE_SHORTCODE = 'code_snippet_source';
20
21 /**
22 * Name of the shortcode tag for rendering content snippets
23 */
24 const CONTENT_SHORTCODE = 'code_snippet';
25
26 /**
27 * Handle to use for front-end scripts and styles.
28 */
29 const PRISM_HANDLE = 'code-snippets-prism';
30
31 /**
32 * Class constructor
33 */
34 public function __construct() {
35 add_action( 'the_posts', [ $this, 'enqueue_highlighting' ] );
36 add_action( 'init', [ $this, 'setup_mce_plugin' ] );
37
38 add_shortcode( self::CONTENT_SHORTCODE, [ $this, 'render_content_shortcode' ] );
39 add_shortcode( self::SOURCE_SHORTCODE, [ $this, 'render_source_shortcode' ] );
40
41 add_filter( 'code_snippets/render_content_shortcode', 'trim' );
42 }
43
44 /**
45 * Register REST API routes for use in front-end plugins.
46 *
47 * @return void
48 */
49 public function register_rest_routes() {
50 register_rest_route(
51 'v1/snippets',
52 '/snippets-info',
53 array(
54 'methods' => WP_REST_Server::READABLE,
55 'callback' => [ $this, 'get_snippets_info' ],
56 'permission_callback' => function () {
57 return current_user_can( 'edit_posts' );
58 },
59 )
60 );
61 }
62
63 /**
64 * Fetch snippets data in response to a request.
65 *
66 * @return WP_REST_Response
67 */
68 public function get_snippets_info(): WP_REST_Response {
69 $snippets = get_snippets();
70 $data = [];
71
72 foreach ( $snippets as $snippet ) {
73 $data[] = [
74 'id' => $snippet->id,
75 'name' => $snippet->name,
76 'type' => $snippet->type,
77 'active' => $snippet->active,
78 ];
79 }
80
81 return new WP_REST_Response( $data, 200 );
82 }
83
84 /**
85 * Perform the necessary actions to add a button to the TinyMCE editor
86 */
87 public function setup_mce_plugin() {
88 if ( ! code_snippets()->current_user_can() ) {
89 return;
90 }
91
92 /* Register the TinyMCE plugin */
93 add_filter(
94 'mce_external_plugins',
95 function ( $plugins ) {
96 $plugins['code_snippets'] = plugins_url( 'dist/mce.js', PLUGIN_FILE );
97 return $plugins;
98 }
99 );
100
101 /* Add the button to the editor toolbar */
102 add_filter(
103 'mce_buttons',
104 function ( $buttons ) {
105 $buttons[] = 'code_snippets';
106 return $buttons;
107 }
108 );
109
110 /* Add the translation strings to the TinyMCE editor */
111 add_filter(
112 'mce_external_languages',
113 function ( $languages ) {
114 $languages['code_snippets'] = __DIR__ . '/mce-strings.php';
115 return $languages;
116 }
117 );
118 }
119
120 /**
121 * Enqueue the syntax highlighting assets if they are required for the current posts
122 *
123 * @param array<WP_Post|int>|null|false $posts List of currently visible posts.
124 *
125 * @return array<WP_Post|int>|null|false Unchanged list of posts.
126 */
127 public function enqueue_highlighting( $posts ) {
128
129 // Exit early if there are no posts to check or if the highlighter has been disabled.
130 if ( empty( $posts ) || Settings\get_setting( 'general', 'disable_prism' ) ) {
131 return $posts;
132 }
133
134 // Concatenate all provided content together, so we can check it all in one go.
135 $content = implode( ' ', wp_list_pluck( $posts, 'post_content' ) );
136
137 // Bail now if the provided post don't contain the source shortcode or block editor block.
138 if ( false === stripos( $content, '[' . self::SOURCE_SHORTCODE ) &&
139 false === strpos( $content, '<!-- wp:code-snippets/source ' ) ) {
140 return $posts;
141 }
142
143 // Load Prism assets on the appropriate hook.
144 $this->register_prism_assets();
145
146 add_action(
147 'wp_enqueue_scripts',
148 function () {
149 wp_enqueue_style( self::PRISM_HANDLE );
150 wp_enqueue_script( self::PRISM_HANDLE );
151 },
152 100
153 );
154
155 return $posts;
156 }
157
158 /**
159 * Enqueue the styles and scripts for the Prism syntax highlighter.
160 *
161 * @return void
162 */
163 public static function register_prism_assets() {
164 $plugin = code_snippets();
165
166 wp_register_style(
167 self::PRISM_HANDLE,
168 plugins_url( 'dist/prism.css', $plugin->file ),
169 array(),
170 $plugin->version
171 );
172
173 wp_register_script(
174 self::PRISM_HANDLE,
175 plugins_url( 'dist/prism.js', $plugin->file ),
176 array(),
177 $plugin->version,
178 true
179 );
180 }
181
182 /**
183 * Enqueue all available Prism themes.
184 *
185 * @return void
186 */
187 public static function enqueue_all_prism_themes() {
188 self::register_prism_assets();
189
190 wp_enqueue_style( self::PRISM_HANDLE );
191 wp_enqueue_script( self::PRISM_HANDLE );
192 }
193
194 /**
195 * Print a message to the user if the snippet ID attribute is invalid.
196 *
197 * @param integer $id Snippet ID.
198 *
199 * @return string Warning message.
200 */
201 protected function invalid_id_warning( int $id ): string {
202 // translators: %d: snippet ID.
203 $text = esc_html__( 'Could not load snippet with an invalid ID: %d.', 'code-snippets' );
204 return current_user_can( 'edit_posts' ) ? sprintf( $text, $id ) : '';
205 }
206
207 /**
208 * Allow boolean attributes to be provided without a value, similar to how React works.
209 *
210 * @param array<string|number, mixed> $atts Unfiltered shortcode attributes.
211 * @param array<string> $boolean_flags List of attribute names with boolean values.
212 *
213 * @return array<string|number, mixed> Shortcode attributes with flags converted to attributes.
214 */
215 protected function convert_boolean_attribute_flags( array $atts, array $boolean_flags ): array {
216 foreach ( $atts as $key => $value ) {
217 if ( in_array( $value, $boolean_flags, true ) && ! isset( $atts[ $value ] ) ) {
218 $atts[ $value ] = true;
219 unset( $atts[ $key ] );
220 }
221 }
222
223 return $atts;
224 }
225
226 /**
227 * Evaluate the code from a content shortcode.
228 *
229 * @param Snippet $snippet Snippet.
230 * @param array<string, mixed> $atts Shortcode attributes.
231 *
232 * @return string Evaluated shortcode content.
233 */
234 protected function evaluate_shortcode_content( Snippet $snippet, array $atts ): string {
235 if ( empty( $atts['php'] ) ) {
236 return $snippet->code;
237 }
238
239 /**
240 * Avoiding extract is typically recommended, however in this situation we want to make it easy for snippet
241 * authors to use custom attributes.
242 *
243 * @phpcs:disable WordPress.PHP.DontExtract.extract_extract
244 */
245 extract( $atts );
246
247 ob_start();
248 eval( "?>\n\n" . $snippet->code . "\n\n<?php" );
249
250 return ob_get_clean();
251 }
252
253 /**
254 * Render the value of a content shortcode
255 *
256 * @param array<string, mixed> $atts Shortcode attributes.
257 *
258 * @return string Shortcode content.
259 */
260 public function render_content_shortcode( array $atts ): string {
261 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'php', 'format', 'shortcodes', 'debug' ] );
262 $original_atts = $atts;
263
264 $atts = shortcode_atts(
265 array(
266 'id' => 0,
267 'snippet_id' => 0,
268 'network' => false,
269 'php' => false,
270 'format' => false,
271 'shortcodes' => false,
272 'debug' => false,
273 ),
274 $atts,
275 self::CONTENT_SHORTCODE
276 );
277
278 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
279 if ( ! $id ) {
280 return $this->invalid_id_warning( $id );
281 }
282
283 $snippet = get_snippet( $id, (bool) $atts['network'] );
284
285 // Render the source code if this is not a shortcode snippet.
286 if ( 'content' !== $snippet->scope ) {
287 return $snippet->id ? $this->render_snippet_source( $snippet ) : '';
288 }
289
290 // If the snippet is inactive, either display a message or render nothing.
291 if ( ! $snippet->active ) {
292 if ( ! $atts['debug'] ) {
293 return '';
294 }
295
296 /* translators: 1: snippet name, 2: snippet edit link */
297 $text = __( '<strong>%1$s</strong> 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' );
298
299 $edit_url = add_query_arg( 'id', $snippet->id, code_snippets()->get_menu_url( 'edit' ) );
300 return wp_kses(
301 sprintf( $text, $snippet->name, $edit_url ),
302 [
303 'strong' => [],
304 'a' => [
305 'href' => [],
306 ],
307 ]
308 );
309 }
310
311 $content = $this->evaluate_shortcode_content( $snippet, $original_atts );
312
313 if ( $atts['format'] ) {
314 $functions = [ 'wptexturize', 'convert_smilies', 'convert_chars', 'wpautop', 'capital_P_dangit' ];
315 foreach ( $functions as $function ) {
316 $content = call_user_func( $function, $content );
317 }
318 }
319
320 if ( $atts['shortcodes'] ) {
321 // Remove this shortcode from the list to prevent recursion.
322 remove_shortcode( self::CONTENT_SHORTCODE );
323
324 // Evaluate shortcodes.
325 $content = do_shortcode( $atts['format'] ? shortcode_unautop( $content ) : $content );
326
327 // Add this shortcode back to the list.
328 add_shortcode( self::CONTENT_SHORTCODE, [ $this, 'render_content_shortcode' ] );
329 }
330
331 return apply_filters( 'code_snippets/content_shortcode', $content, $snippet, $atts, $original_atts );
332 }
333
334 /**
335 * Converts a value and key into an HTML attribute pair.
336 *
337 * @param string $value Attribute value.
338 * @param string $key Attribute name.
339 *
340 * @return void
341 */
342 private static function create_attribute_pair( string &$value, string $key ) {
343 $value = sprintf( '%s="%s"', sanitize_key( $key ), esc_attr( $value ) );
344 }
345
346 /**
347 * Render the source code of a given snippet
348 *
349 * @param Snippet $snippet Snippet object.
350 * @param array<string, mixed> $atts Shortcode attributes.
351 *
352 * @return string Shortcode content.
353 */
354 private function render_snippet_source( Snippet $snippet, array $atts = [] ): string {
355 $atts = array_merge(
356 array(
357 'line_numbers' => false,
358 'highlight_lines' => '',
359 ),
360 $atts
361 );
362
363 $language = 'css' === $snippet->type ? 'css' : ( 'js' === $snippet->type ? 'js' : 'php' );
364
365 $pre_attributes = array(
366 'id' => "code-snippet-source-$snippet->id",
367 'class' => 'code-snippet-source',
368 );
369
370 $code_attributes = array(
371 'class' => "language-$language",
372 );
373
374 if ( $atts['line_numbers'] ) {
375 $code_attributes['class'] .= ' line-numbers';
376 $pre_attributes['class'] .= ' linkable-line-numbers';
377 }
378
379 if ( $atts['highlight_lines'] ) {
380 $pre_attributes['data-line'] = $atts['highlight_lines'];
381 }
382
383 $pre_attributes = apply_filters( 'code_snippets/prism_pre_attributes', $pre_attributes, $snippet, $atts );
384 $code_attributes = apply_filters( 'code_snippets/prism_code_attributes', $code_attributes, $snippet, $atts );
385
386 array_walk( $code_attributes, array( $this, 'create_attribute_pair' ) );
387 array_walk( $pre_attributes, array( $this, 'create_attribute_pair' ) );
388
389 $code = 'php' === $snippet->type ? "<?php\n\n$snippet->code" : $snippet->code;
390
391 $output = sprintf(
392 '<pre %s><code %s>%s</code></pre>',
393 implode( ' ', $pre_attributes ),
394 implode( ' ', $code_attributes ),
395 esc_html( $code )
396 );
397
398 return apply_filters( 'code_snippets/render_source_shortcode', $output, $snippet, $atts );
399 }
400
401 /**
402 * Render the value of a source shortcode
403 *
404 * @param array<string, mixed> $atts Shortcode attributes.
405 *
406 * @return string Shortcode content.
407 */
408 public function render_source_shortcode( array $atts ): string {
409 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'line_numbers' ] );
410
411 $atts = shortcode_atts(
412 array(
413 'id' => 0,
414 'snippet_id' => 0,
415 'network' => false,
416 'line_numbers' => false,
417 'highlight_lines' => '',
418 ),
419 $atts,
420 self::SOURCE_SHORTCODE
421 );
422
423 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
424 if ( ! $id ) {
425 return $this->invalid_id_warning( $id );
426 }
427
428 $snippet = get_snippet( $id, (bool) $atts['network'] );
429
430 return $this->render_snippet_source( $snippet, $atts );
431 }
432 }
433