PluginProbe
Code Snippets / 3.8.1
Code Snippets v3.8.1
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 / snippet-ops.php

snippet-ops.php in Code Snippets 3.8.1, at php/snippet-ops.php

693 lines 19.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Functions to perform snippet operations
4 *
5 * @package Code_Snippets
6 */
7
8 namespace Code_Snippets;
9
10 use ParseError;
11 use function Code_Snippets\Settings\get_self_option;
12 use function Code_Snippets\Settings\update_self_option;
13
14 /**
15 * Clean the cache where active snippets are stored.
16 *
17 * @param string $table_name Snippets table name.
18 * @param array<string>|false $scopes List of scopes. Optional. If not provided, will flush the cache for all scopes.
19 *
20 * @return void
21 */
22 function clean_active_snippets_cache( string $table_name, $scopes = false ) {
23 $scope_groups = $scopes ? [ $scopes ] : [
24 [ 'head-content', 'footer-content' ],
25 [ 'global', 'single-use', 'front-end' ],
26 [ 'global', 'single-use', 'admin' ],
27 ];
28
29 foreach ( $scope_groups as $scopes ) {
30 wp_cache_delete( sprintf( 'active_snippets_%s_%s', sanitize_key( join( '_', $scopes ) ), $table_name ), CACHE_GROUP );
31 }
32 }
33
34 /**
35 * Flush all snippets caches for a given database table.
36 *
37 * @param string $table_name Snippets table name.
38 *
39 * @return void
40 */
41 function clean_snippets_cache( string $table_name ) {
42 wp_cache_delete( "all_snippet_tags_$table_name", CACHE_GROUP );
43 wp_cache_delete( "all_snippets_$table_name", CACHE_GROUP );
44 clean_active_snippets_cache( $table_name );
45 }
46
47 /**
48 * Retrieve a list of snippets from the database.
49 * Read operation.
50 *
51 * @param array<string> $ids The IDs of the snippets to fetch.
52 * @param bool|null $network Retrieve multisite-wide snippets (true) or site-wide snippets (false).
53 *
54 * @return array<Snippet> List of Snippet objects.
55 *
56 * @since 2.0
57 */
58 function get_snippets( array $ids = array(), ?bool $network = null ): array {
59 global $wpdb;
60
61 // If only one ID has been passed in, defer to the get_snippet() function.
62 $ids_count = count( $ids );
63 if ( 1 === $ids_count ) {
64 return array( get_snippet( $ids[0], $network ) );
65 }
66
67 $network = DB::validate_network_param( $network );
68 $table_name = code_snippets()->db->get_table_name( $network );
69
70 $snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
71
72 // Fetch all snippets from the database if none are cached.
73 if ( ! is_array( $snippets ) ) {
74 $results = $wpdb->get_results( "SELECT * FROM $table_name", ARRAY_A );
75
76 $snippets = $results ?
77 array_map(
78 function ( $snippet_data ) use ( $network ) {
79 $snippet_data['network'] = $network;
80 return new Snippet( $snippet_data );
81 },
82 $results
83 ) :
84 array();
85
86 $snippets = apply_filters( 'code_snippets/get_snippets', $snippets, $network );
87
88 if ( 0 === $ids_count ) {
89 wp_cache_set( "all_snippets_$table_name", $snippets, CACHE_GROUP );
90 }
91 }
92
93 // If a list of IDs are provided, narrow down the snippets list.
94 if ( $ids_count > 0 ) {
95 $ids = array_map( 'intval', $ids );
96 return array_values(
97 array_filter(
98 $snippets,
99 function ( Snippet $snippet ) use ( $ids ) {
100 return in_array( $snippet->id, $ids, true );
101 }
102 )
103 );
104 }
105
106 return $snippets;
107 }
108
109 /**
110 * Gets all used tags from the database.
111 * Read operation.
112 *
113 * @since 2.0
114 */
115 function get_all_snippet_tags() {
116 global $wpdb;
117 $table_name = code_snippets()->db->get_table_name();
118 $cache_key = "all_snippet_tags_$table_name";
119
120 $tags = wp_cache_get( $cache_key, CACHE_GROUP );
121 if ( $tags ) {
122 return $tags;
123 }
124
125 // Grab all tags from the database.
126 $tags = array();
127 $all_tags = $wpdb->get_col( "SELECT tags FROM $table_name" );
128
129 // Merge all tags into a single array.
130 foreach ( $all_tags as $snippet_tags ) {
131 $snippet_tags = code_snippets_build_tags_array( $snippet_tags );
132 $tags = array_merge( $snippet_tags, $tags );
133 }
134
135 // Remove duplicate tags.
136 $tags = array_values( array_unique( $tags, SORT_REGULAR ) );
137 wp_cache_set( $cache_key, $tags, CACHE_GROUP );
138 return $tags;
139 }
140
141 /**
142 * Make sure that the tags are a valid array.
143 *
144 * @param array|string $tags The tags to convert into an array.
145 *
146 * @return array<string> The converted tags.
147 *
148 * @since 2.0.0
149 */
150 function code_snippets_build_tags_array( $tags ): array {
151
152 /* If there are no tags set, return an empty array. */
153 if ( empty( $tags ) ) {
154 return array();
155 }
156
157 /* If the tags are set as a string, convert them into an array. */
158 if ( is_string( $tags ) ) {
159 $tags = wp_strip_all_tags( $tags );
160 $tags = str_replace( ', ', ',', $tags );
161 $tags = explode( ',', $tags );
162 }
163
164 /* If we still don't have an array, just convert whatever we do have into one. */
165 return (array) $tags;
166 }
167
168 /**
169 * Retrieve a single snippets from the database.
170 * Will return empty snippet object if no snippet ID is specified.
171 * Read operation.
172 *
173 * @param int $id The ID of the snippet to retrieve. 0 to build a new snippet.
174 * @param bool|null $network Retrieve a multisite-wide snippet (true) or site-wide snippet (false).
175 *
176 * @return Snippet A single snippet object.
177 *
178 * @since 2.0.0
179 */
180 function get_snippet( int $id = 0, ?bool $network = null ): Snippet {
181 global $wpdb;
182
183 $id = absint( $id );
184 $network = DB::validate_network_param( $network );
185 $table_name = code_snippets()->db->get_table_name( $network );
186
187 if ( 0 === $id ) {
188 // If an invalid ID is provided, then return an empty snippet object.
189 $snippet = new Snippet();
190
191 } else {
192 $cached_snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
193
194 // Attempt to fetch snippet from the cached list, if it exists.
195 if ( is_array( $cached_snippets ) ) {
196 foreach ( $cached_snippets as $snippet ) {
197 if ( $snippet->id === $id ) {
198 return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $network );
199 }
200 }
201 }
202
203 // Otherwise, retrieve the snippet from the database.
204 // phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
205 $snippet_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $id ) );
206 $snippet = new Snippet( $snippet_data );
207 }
208
209 $snippet->network = $network;
210 return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $network );
211 }
212
213
214 /**
215 * Ensure the list of shared network snippets is correct if one has been recently activated or deactivated.
216 * Write operation.
217 *
218 * @access private
219 *
220 * @param Snippet[] $snippets Snippets that was recently updated.
221 *
222 * @return boolean Whether an update was performed.
223 */
224 function update_shared_network_snippets( array $snippets ): bool {
225 $shared_ids = [];
226 $unshared_ids = [];
227
228 if ( ! is_multisite() ) {
229 return false;
230 }
231
232 foreach ( $snippets as $snippet ) {
233 if ( $snippet->network ) {
234 if ( $snippet->shared_network ) {
235 $shared_ids[] = $snippet->id;
236 } else {
237 $unshared_ids[] = $snippet->id;
238 }
239 }
240 }
241
242 if ( ! $shared_ids && ! $unshared_ids ) {
243 return false;
244 }
245
246 $existing_shared_ids = get_site_option( 'shared_network_snippets', [] );
247 $updated_shared_ids = array_values( array_diff( array_merge( $existing_shared_ids, $shared_ids ), $unshared_ids ) );
248
249 if ( $existing_shared_ids === $updated_shared_ids ) {
250 return false;
251 }
252
253 update_site_option( 'shared_network_snippets', $updated_shared_ids );
254
255 // Deactivate the snippet on all sites if necessary.
256 if ( $unshared_ids ) {
257 $sites = get_sites( [ 'fields' => 'ids' ] );
258
259 foreach ( $sites as $site ) {
260 switch_to_blog( $site );
261 $active_shared_ids = get_option( 'active_shared_network_snippets' );
262
263 if ( is_array( $active_shared_ids ) ) {
264 $active_shared_ids = array_diff( $active_shared_ids, $unshared_ids );
265 update_option( 'active_shared_network_snippets', $active_shared_ids );
266 }
267
268 clean_active_snippets_cache( code_snippets()->db->ms_table );
269 }
270
271 restore_current_blog();
272 }
273
274 return true;
275 }
276
277 /**
278 * Activates a snippet.
279 * Write operation.
280 *
281 * @param int $id ID of the snippet to activate.
282 * @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
283 *
284 * @return Snippet|string Snippet object on success, error message on failure.
285 * @since 2.0.0
286 */
287 function activate_snippet( int $id, ?bool $network = null ) {
288 global $wpdb;
289 $network = DB::validate_network_param( $network );
290 $table_name = code_snippets()->db->get_table_name( $network );
291
292 // Retrieve the snippet code from the database for validation before activating.
293 $snippet = get_snippet( $id, $network );
294
295 if ( 0 === $snippet->id ) {
296 // translators: %d: snippet identifier.
297 return sprintf( __( 'Could not locate snippet with ID %d.', 'code-snippets' ), $id );
298 }
299
300 if('php' == $snippet->type ){
301 $validator = new Validator( $snippet->code );
302 if ( $validator->validate() ) {
303 return __( 'Could not activate snippet: code did not pass validation.', 'code-snippets' );
304 }
305 }
306
307 $result = $wpdb->update(
308 $table_name,
309 array( 'active' => '1' ),
310 array( 'id' => $id ),
311 array( '%d' ),
312 array( '%d' )
313 );
314
315 if ( ! $result ) {
316 return __( 'Could not activate snippet.', 'code-snippets' );
317 }
318
319 update_shared_network_snippets( [ $snippet ] );
320 do_action( 'code_snippets/activate_snippet', $snippet, $network );
321 clean_snippets_cache( $table_name );
322 return $snippet;
323 }
324
325 /**
326 * Activates multiple snippets.
327 * Write operation.
328 *
329 * @param array<integer> $ids The IDs of the snippets to activate.
330 * @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
331 *
332 * @return Snippet[]|null Snippets which were successfully activated, or null on failure.
333 *
334 * @since 2.0.0
335 */
336 function activate_snippets( array $ids, ?bool $network = null ): ?array {
337 global $wpdb;
338 $network = DB::validate_network_param( $network );
339 $table_name = code_snippets()->db->get_table_name( $network );
340
341 $snippets = get_snippets( $ids, $network );
342
343 if ( ! $snippets ) {
344 return null;
345 }
346
347 // Loop through each snippet code and validate individually.
348 $valid_ids = [];
349 $valid_snippets = [];
350
351 foreach ( $snippets as $snippet ) {
352 $validator = new Validator( $snippet->code );
353 $code_error = $validator->validate();
354
355 if ( ! $code_error ) {
356 $valid_ids[] = $snippet->id;
357 $valid_snippets[] = $snippet;
358 }
359 }
360
361 // If there are no valid snippets, then we're done.
362 if ( ! $valid_ids ) {
363 return null;
364 }
365
366 // Build a SQL query containing all IDs, as wpdb::update does not support OR conditionals.
367 $ids_format = implode( ',', array_fill( 0, count( $valid_ids ), '%d' ) );
368
369 // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
370 $rows_updated = $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET active = 1 WHERE id IN ($ids_format)", $valid_ids ) );
371
372 if ( ! $rows_updated ) {
373 return null;
374 }
375
376 update_shared_network_snippets( $valid_snippets );
377 do_action( 'code_snippets/activate_snippets', $valid_snippets, $table_name );
378 clean_snippets_cache( $table_name );
379 return $valid_ids;
380 }
381
382 /**
383 * Deactivate a snippet.
384 * Write operation.
385 *
386 * @param int $id ID of the snippet to deactivate.
387 * @param bool|null $network Whether the snippets are multisite-wide (true) or site-wide (false).
388 *
389 * @return Snippet|null Snippet that was deactivated on success, or null on failure.
390 *
391 * @since 2.0.0
392 */
393 function deactivate_snippet( int $id, ?bool $network = null ): ?Snippet {
394 global $wpdb;
395 $network = DB::validate_network_param( $network );
396 $table = code_snippets()->db->get_table_name( $network );
397
398 // Set the snippet to inactive.
399 $result = $wpdb->update(
400 $table,
401 array( 'active' => '0' ),
402 array( 'id' => $id ),
403 array( '%d' ),
404 array( '%d' )
405 );
406
407 if ( ! $result ) {
408 return null;
409 }
410
411 // Update the recently active list.
412 $snippet = get_snippet( $id );
413 $recently_active = [ $id => time() ] + get_self_option( $network, 'recently_activated_snippets', [] );
414 update_self_option( $network, 'recently_activated_snippets', $recently_active );
415
416 update_shared_network_snippets( [ $snippet ] );
417 do_action( 'code_snippets/deactivate_snippet', $id, $network );
418 clean_snippets_cache( $table );
419
420 return $snippet;
421 }
422
423 /**
424 * Deletes a snippet from the database.
425 * Write operation.
426 *
427 * @param int $id ID of the snippet to delete.
428 * @param bool|null $network Delete from network-wide (true) or site-wide (false) table.
429 *
430 * @return bool Whether the snippet was deleted successfully.
431 *
432 * @since 2.0.0
433 */
434 function delete_snippet( int $id, ?bool $network = null ): bool {
435 global $wpdb;
436 $network = DB::validate_network_param( $network );
437 $table = code_snippets()->db->get_table_name( $network );
438
439 $snippet = get_snippet( $id, $network );
440
441 $result = $wpdb->delete(
442 $table,
443 array( 'id' => $id ),
444 array( '%d' )
445 );
446
447 if ( $result ) {
448 do_action( 'code_snippets/delete_snippet', $snippet, $network );
449 clean_snippets_cache( $table );
450 code_snippets()->cloud_api->delete_snippet_from_transient_data( $id );
451 }
452
453 return (bool) $result;
454 }
455
456
457 /**
458 * Test snippet code for errors, augmenting the snippet object.
459 *
460 * @param Snippet $snippet Snippet object.
461 */
462 function test_snippet_code( Snippet $snippet ) {
463 $snippet->code_error = null;
464
465 if ( 'php' !== $snippet->type ) {
466 return;
467 }
468
469 $validator = new Validator( $snippet->code );
470 $result = $validator->validate();
471
472 if ( $result ) {
473 $snippet->code_error = [ $result['message'], $result['line'] ];
474 }
475
476 if ( ! $snippet->code_error && 'single-use' !== $snippet->scope ) {
477 $result = execute_snippet( $snippet->code, $snippet->id, true );
478
479 if ( $result instanceof ParseError ) {
480 $snippet->code_error = [
481 ucfirst( rtrim( $result->getMessage(), '.' ) ) . '.',
482 $result->getLine(),
483 ];
484 }
485 }
486 }
487
488 /**
489 * Saves a snippet to the database.
490 * Write operation.
491 *
492 * @param Snippet|array<string, mixed> $snippet The snippet to add/update to the database.
493 *
494 * @return Snippet|null Updated snippet.
495 *
496 * @since 2.0.0
497 */
498 function save_snippet( $snippet ) {
499 global $wpdb;
500 $table = code_snippets()->db->get_table_name( $snippet->network );
501
502 if ( ! $snippet instanceof Snippet ) {
503 $snippet = new Snippet( $snippet );
504 }
505
506 // Update the last modification date if necessary.
507 $snippet->update_modified();
508
509 if ( 'php' === $snippet->type ) {
510 // Remove tags from beginning and end of snippet.
511 $snippet->code = preg_replace( '|^\s*<\?(php)?|', '', $snippet->code );
512 $snippet->code = preg_replace( '|\?>\s*$|', '', $snippet->code );
513
514 // Deactivate snippet if code contains errors.
515 if ( $snippet->active && 'single-use' !== $snippet->scope ) {
516 test_snippet_code( $snippet );
517
518 if ( $snippet->code_error ) {
519 $snippet->active = 0;
520 }
521 }
522 }
523
524 // Increment the revision number unless revision = 1 or revision is not set.
525 if ( $snippet->revision && $snippet->revision > 1 ) {
526 $snippet->increment_revision();
527 }
528
529 // Shared network snippets are always considered inactive.
530 $snippet->active = $snippet->active && ! $snippet->shared_network;
531
532 // Build the list of data to insert.
533 $data = [
534 'name' => $snippet->name,
535 'description' => $snippet->desc,
536 'code' => $snippet->code,
537 'tags' => $snippet->tags_list,
538 'scope' => $snippet->scope,
539 'condition_id' => intval( $snippet->condition_id ),
540 'priority' => $snippet->priority,
541 'active' => intval( $snippet->active ),
542 'modified' => $snippet->modified,
543 'revision' => $snippet->revision,
544 'cloud_id' => $snippet->cloud_id ? $snippet->cloud_id : null,
545 ];
546
547 // Create a new snippet if the ID is not set.
548 if ( 0 === $snippet->id ) {
549 $result = $wpdb->insert( $table, $data, '%s' );
550 if ( false === $result ) {
551 return null;
552 }
553
554 $snippet->id = $wpdb->insert_id;
555 do_action( 'code_snippets/create_snippet', $snippet, $table );
556 } else {
557
558 // Otherwise, update the snippet data.
559 $result = $wpdb->update( $table, $data, [ 'id' => $snippet->id ], null, [ '%d' ] );
560 if ( false === $result ) {
561 return null;
562 }
563
564 do_action( 'code_snippets/update_snippet', $snippet, $table );
565 }
566
567 update_shared_network_snippets( [ $snippet ] );
568 clean_snippets_cache( $table );
569 return $snippet;
570 }
571
572 /**
573 * Execute a snippet.
574 * Execute operation.
575 *
576 * Code must NOT be escaped, as it will be executed directly.
577 *
578 * @param string $code Snippet code to execute.
579 * @param integer $id Snippet ID.
580 * @param boolean $force Force snippet execution, even if save mode is active.
581 *
582 * @return ParseError|mixed Code error if encountered during execution, or result of snippet execution otherwise.
583 *
584 * @since 2.0.0
585 */
586 function execute_snippet( string $code, int $id = 0, bool $force = false ) {
587 /**
588 * Do not continue if safe mode is active.
589 *
590 * @noinspection PhpUndefinedConstantInspection
591 */
592 if ( empty( $code ) || ( ! $force && defined( 'CODE_SNIPPETS_SAFE_MODE' ) && CODE_SNIPPETS_SAFE_MODE ) ) {
593 return false;
594 }
595
596 ob_start();
597
598 try {
599 $result = eval( $code );
600 } catch ( ParseError $parse_error ) {
601 $result = $parse_error;
602 }
603
604 ob_end_clean();
605
606 do_action( 'code_snippets/after_execute_snippet', $code, $id, $result );
607 return $result;
608 }
609
610 /**
611 * Retrieve a single snippets from the database using its cloud ID.
612 *
613 * Read operation.
614 *
615 * @param string $cloud_id The Cloud ID of the snippet to retrieve.
616 * @param boolean|null $multisite Retrieve a multisite-wide snippet (true) or site-wide snippet (false).
617 *
618 * @return Snippet|null A single snippet object or null if no snippet was found.
619 *
620 * @since 3.5.0
621 */
622 function get_snippet_by_cloud_id( string $cloud_id, ?bool $multisite = null ): ?Snippet {
623 global $wpdb;
624
625 $multisite = DB::validate_network_param( $multisite );
626 $table_name = code_snippets()->db->get_table_name( $multisite );
627
628 $cached_snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
629
630 // Attempt to fetch snippet from the cached list, if it exists.
631 if ( is_array( $cached_snippets ) ) {
632 foreach ( $cached_snippets as $snippet ) {
633 if ( $snippet->cloud_id === $cloud_id ) {
634 return apply_filters( 'code_snippets/get_snippet_by_cloud_id', $snippet, $cloud_id, $multisite );
635 }
636 }
637 }
638
639 // Otherwise, search for the snippet from the database.
640 $snippet_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE cloud_id = %s", $cloud_id ) ); // cache pass, db call ok.
641 $snippet = $snippet_data ? new Snippet( $snippet_data ) : null;
642
643 return apply_filters( 'code_snippets/get_snippet_by_cloud_id', $snippet, $cloud_id, $multisite );
644 }
645
646 /**
647 * Update a snippet entry given a list of fields.
648 * Write operation.
649 *
650 * @param int $snippet_id ID of the snippet to update.
651 * @param array<string, mixed> $fields An array of fields mapped to their values.
652 * @param bool|null $network Update in network-wide (true) or site-wide (false) table.
653 */
654 function update_snippet_fields( int $snippet_id, array $fields, ?bool $network = null ) {
655 global $wpdb;
656
657 $table = code_snippets()->db->get_table_name( $network );
658
659 // Build a new snippet object for the validation.
660 $snippet = new Snippet();
661 $snippet->id = $snippet_id;
662
663 // Validate fields through the snippet class and copy them into a clean array.
664 $clean_fields = array();
665
666 foreach ( $fields as $field => $value ) {
667
668 if ( $snippet->set_field( $field, $value ) ) {
669 $clean_fields[ $field ] = $snippet->$field;
670 }
671 }
672
673 // Update the snippet in the database.
674 $wpdb->update( $table, $clean_fields, array( 'id' => $snippet->id ), null, array( '%d' ) );
675
676 do_action( 'code_snippets/update_snippet', $snippet->id, $table );
677 clean_snippets_cache( $table );
678 }
679
680 function execute_snippet_from_flat_file( $code, $file, int $id = 0, bool $force = false ) {
681 if ( ! is_file( $file ) ) {
682 return execute_snippet( $code, $id, $force );
683 }
684
685 if ( ! $force && defined( 'CODE_SNIPPETS_SAFE_MODE' ) && CODE_SNIPPETS_SAFE_MODE ) {
686 return false;
687 }
688
689 require_once $file;
690
691 do_action( 'code_snippets/after_execute_snippet_from_flat_file', $file, $id );
692 }
693