PluginProbe
Code Snippets / 3.6.6
Code Snippets v3.6.6
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-front-end.php

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

437 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 Front_End {
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 // Loop through the posts, checking for an existing shortcode, short-circuiting if possible.
135 $found_shortcode = false;
136
137 foreach ( $posts as $post ) {
138 if ( false !== stripos( $post->post_content, '[' . self::SOURCE_SHORTCODE ) ||
139 false !== strpos( $post->post_content, '<!-- wp:code-snippets/source ' ) ) {
140 $found_shortcode = true;
141 break;
142 }
143 }
144
145 // Load assets on the appropriate hook if a matching shortcode was found.
146 if ( $found_shortcode ) {
147 $this->register_prism_assets();
148
149 add_action(
150 'wp_enqueue_scripts',
151 function () {
152 wp_enqueue_style( self::PRISM_HANDLE );
153 wp_enqueue_script( self::PRISM_HANDLE );
154 },
155 100
156 );
157 }
158
159 return $posts;
160 }
161
162 /**
163 * Enqueue the styles and scripts for the Prism syntax highlighter.
164 *
165 * @return void
166 */
167 public static function register_prism_assets() {
168 $plugin = code_snippets();
169
170 wp_register_style(
171 self::PRISM_HANDLE,
172 plugins_url( 'dist/prism.css', $plugin->file ),
173 array(),
174 $plugin->version
175 );
176
177 wp_register_script(
178 self::PRISM_HANDLE,
179 plugins_url( 'dist/prism.js', $plugin->file ),
180 array(),
181 $plugin->version,
182 true
183 );
184 }
185
186 /**
187 * Enqueue all available Prism themes.
188 *
189 * @return void
190 */
191 public static function enqueue_all_prism_themes() {
192 self::register_prism_assets();
193
194 wp_enqueue_style( self::PRISM_HANDLE );
195 wp_enqueue_script( self::PRISM_HANDLE );
196 }
197
198 /**
199 * Print a message to the user if the snippet ID attribute is invalid.
200 *
201 * @param integer $id Snippet ID.
202 *
203 * @return string Warning message.
204 */
205 protected function invalid_id_warning( int $id ): string {
206 // translators: %d: snippet ID.
207 $text = esc_html__( 'Could not load snippet with an invalid ID: %d.', 'code-snippets' );
208 return current_user_can( 'edit_posts' ) ? sprintf( $text, $id ) : '';
209 }
210
211 /**
212 * Allow boolean attributes to be provided without a value, similar to how React works.
213 *
214 * @param array<string|number, mixed> $atts Unfiltered shortcode attributes.
215 * @param array<string> $boolean_flags List of attribute names with boolean values.
216 *
217 * @return array<string|number, mixed> Shortcode attributes with flags converted to attributes.
218 */
219 protected function convert_boolean_attribute_flags( array $atts, array $boolean_flags ): array {
220 foreach ( $atts as $key => $value ) {
221 if ( in_array( $value, $boolean_flags, true ) && ! isset( $atts[ $value ] ) ) {
222 $atts[ $value ] = true;
223 unset( $atts[ $key ] );
224 }
225 }
226
227 return $atts;
228 }
229
230 /**
231 * Evaluate the code from a content shortcode.
232 *
233 * @param Snippet $snippet Snippet.
234 * @param array<string, mixed> $atts Shortcode attributes.
235 *
236 * @return string Evaluated shortcode content.
237 */
238 protected function evaluate_shortcode_content( Snippet $snippet, array $atts ): string {
239 if ( empty( $atts['php'] ) ) {
240 return $snippet->code;
241 }
242
243 /**
244 * Avoiding extract is typically recommended, however in this situation we want to make it easy for snippet
245 * authors to use custom attributes.
246 *
247 * @phpcs:disable WordPress.PHP.DontExtract.extract_extract
248 */
249 extract( $atts );
250
251 ob_start();
252 eval( "?>\n\n" . $snippet->code . "\n\n<?php" );
253
254 return ob_get_clean();
255 }
256
257 /**
258 * Render the value of a content shortcode
259 *
260 * @param array<string, mixed> $atts Shortcode attributes.
261 *
262 * @return string Shortcode content.
263 */
264 public function render_content_shortcode( array $atts ): string {
265 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'php', 'format', 'shortcodes', 'debug' ] );
266 $original_atts = $atts;
267
268 $atts = shortcode_atts(
269 array(
270 'id' => 0,
271 'snippet_id' => 0,
272 'network' => false,
273 'php' => false,
274 'format' => false,
275 'shortcodes' => false,
276 'debug' => false,
277 ),
278 $atts,
279 self::CONTENT_SHORTCODE
280 );
281
282 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
283 if ( ! $id ) {
284 return $this->invalid_id_warning( $id );
285 }
286
287 $snippet = get_snippet( $id, (bool) $atts['network'] );
288
289 // Render the source code if this is not a shortcode snippet.
290 if ( 'content' !== $snippet->scope ) {
291 return $snippet->id ? $this->render_snippet_source( $snippet ) : '';
292 }
293
294 // If the snippet is inactive, either display a message or render nothing.
295 if ( ! $snippet->active ) {
296 if ( ! $atts['debug'] ) {
297 return '';
298 }
299
300 /* translators: 1: snippet name, 2: snippet edit link */
301 $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' );
302
303 $edit_url = add_query_arg( 'id', $snippet->id, code_snippets()->get_menu_url( 'edit' ) );
304 return wp_kses(
305 sprintf( $text, $snippet->name, $edit_url ),
306 [
307 'strong' => [],
308 'a' => [
309 'href' => [],
310 ],
311 ]
312 );
313 }
314
315 $content = $this->evaluate_shortcode_content( $snippet, $original_atts );
316
317 if ( $atts['format'] ) {
318 $functions = [ 'wptexturize', 'convert_smilies', 'convert_chars', 'wpautop', 'capital_P_dangit' ];
319 foreach ( $functions as $function ) {
320 $content = call_user_func( $function, $content );
321 }
322 }
323
324 if ( $atts['shortcodes'] ) {
325 // Remove this shortcode from the list to prevent recursion.
326 remove_shortcode( self::CONTENT_SHORTCODE );
327
328 // Evaluate shortcodes.
329 $content = do_shortcode( $atts['format'] ? shortcode_unautop( $content ) : $content );
330
331 // Add this shortcode back to the list.
332 add_shortcode( self::CONTENT_SHORTCODE, [ $this, 'render_content_shortcode' ] );
333 }
334
335 return apply_filters( 'code_snippets/content_shortcode', $content, $snippet, $atts, $original_atts );
336 }
337
338 /**
339 * Converts a value and key into an HTML attribute pair.
340 *
341 * @param string $value Attribute value.
342 * @param string $key Attribute name.
343 *
344 * @return void
345 */
346 private static function create_attribute_pair( string &$value, string $key ) {
347 $value = sprintf( '%s="%s"', sanitize_key( $key ), esc_attr( $value ) );
348 }
349
350 /**
351 * Render the source code of a given snippet
352 *
353 * @param Snippet $snippet Snippet object.
354 * @param array<string, mixed> $atts Shortcode attributes.
355 *
356 * @return string Shortcode content.
357 */
358 private function render_snippet_source( Snippet $snippet, array $atts = [] ): string {
359 $atts = array_merge(
360 array(
361 'line_numbers' => false,
362 'highlight_lines' => '',
363 ),
364 $atts
365 );
366
367 $language = 'css' === $snippet->type ? 'css' : ( 'js' === $snippet->type ? 'js' : 'php' );
368
369 $pre_attributes = array(
370 'id' => "code-snippet-source-$snippet->id",
371 'class' => 'code-snippet-source',
372 );
373
374 $code_attributes = array(
375 'class' => "language-$language",
376 );
377
378 if ( $atts['line_numbers'] ) {
379 $code_attributes['class'] .= ' line-numbers';
380 $pre_attributes['class'] .= ' linkable-line-numbers';
381 }
382
383 if ( $atts['highlight_lines'] ) {
384 $pre_attributes['data-line'] = $atts['highlight_lines'];
385 }
386
387 $pre_attributes = apply_filters( 'code_snippets/prism_pre_attributes', $pre_attributes, $snippet, $atts );
388 $code_attributes = apply_filters( 'code_snippets/prism_code_attributes', $code_attributes, $snippet, $atts );
389
390 array_walk( $code_attributes, array( $this, 'create_attribute_pair' ) );
391 array_walk( $pre_attributes, array( $this, 'create_attribute_pair' ) );
392
393 $code = 'php' === $snippet->type ? "<?php\n\n$snippet->code" : $snippet->code;
394
395 $output = sprintf(
396 '<pre %s><code %s>%s</code></pre>',
397 implode( ' ', $pre_attributes ),
398 implode( ' ', $code_attributes ),
399 esc_html( $code )
400 );
401
402 return apply_filters( 'code_snippets/render_source_shortcode', $output, $snippet, $atts );
403 }
404
405 /**
406 * Render the value of a source shortcode
407 *
408 * @param array<string, mixed> $atts Shortcode attributes.
409 *
410 * @return string Shortcode content.
411 */
412 public function render_source_shortcode( array $atts ): string {
413 $atts = $this->convert_boolean_attribute_flags( $atts, [ 'network', 'line_numbers' ] );
414
415 $atts = shortcode_atts(
416 array(
417 'id' => 0,
418 'snippet_id' => 0,
419 'network' => false,
420 'line_numbers' => false,
421 'highlight_lines' => '',
422 ),
423 $atts,
424 self::SOURCE_SHORTCODE
425 );
426
427 $id = 0 !== intval( $atts['snippet_id'] ) ? intval( $atts['snippet_id'] ) : intval( $atts['id'] );
428 if ( ! $id ) {
429 return $this->invalid_id_warning( $id );
430 }
431
432 $snippet = get_snippet( $id, (bool) $atts['network'] );
433
434 return $this->render_snippet_source( $snippet, $atts );
435 }
436 }
437