PluginProbe
Code Snippets / 3.2.1
Code Snippets v3.2.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.2.1, at php/snippet-ops.php

572 lines 16.0 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 wpdb;
11
12 /**
13 * Clean the cache where active snippets are stored.
14 *
15 * @param string $table_name Snippets table name.
16 * @param array|false $scopes List of scopes. Optional. If not provided, will flush the cache for all scopes.
17 *
18 * @return void
19 */
20 function clean_active_snippets_cache( $table_name, $scopes = false ) {
21 $scope_groups = $scopes ? [ $scopes ] : [
22 [ 'head-content', 'footer-content' ],
23 [ 'global', 'single-use', 'front-end' ],
24 [ 'global', 'single-use', 'admin' ],
25 ];
26
27 foreach ( $scope_groups as $scopes ) {
28 wp_cache_delete( sprintf( 'active_snippets_%s_%s', sanitize_key( join( '_', $scopes ) ), $table_name ), CACHE_GROUP );
29 }
30 }
31
32 /**
33 * Flush all snippets caches for a given database table.
34 *
35 * @param string $table_name Snippets table name.
36 *
37 * @return void
38 */
39 function clean_snippets_cache( $table_name ) {
40 wp_cache_delete( "all_snippet_tags_$table_name", CACHE_GROUP );
41 wp_cache_delete( "all_snippets_$table_name", CACHE_GROUP );
42 clean_active_snippets_cache( $table_name );
43 }
44
45 /**
46 * Retrieve a list of snippets from the database.
47 * Read operation.
48 *
49 * @param array $ids The IDs of the snippets to fetch.
50 * @param bool|null|string $multisite Retrieve multisite-wide snippets (true) or site-wide snippets (false).
51 *
52 * @return array List of Snippet objects.
53 *
54 * @since 2.0
55 */
56 function get_snippets( array $ids = array(), $multisite = null ) {
57 global $wpdb;
58
59 // If only one ID has been passed in, defer to the get_snippet() function.
60 $ids_count = count( $ids );
61 if ( 1 === $ids_count ) {
62 return array( get_snippet( $ids[0], $multisite ) );
63 }
64
65 $db = code_snippets()->db;
66 $multisite = $db->validate_network_param( $multisite );
67 $table_name = $db->get_table_name( $multisite );
68 $snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
69
70 // Fetch all snippets from the database if none are cached.
71 if ( ! is_array( $snippets ) ) {
72 $results = $wpdb->get_results( "SELECT * FROM $table_name", ARRAY_A ); // db call ok.
73
74 $snippets = $results ?
75 array_map(
76 function ( $snippet_data ) use ( $multisite ) {
77 $snippet_data['network'] = $multisite;
78 return new Snippet( $snippet_data );
79 },
80 $results
81 ) :
82 array();
83
84 $snippets = apply_filters( 'code_snippets/get_snippets', $snippets, $multisite );
85
86 if ( 0 === $ids_count ) {
87 wp_cache_set( "all_snippets_$table_name", $snippets, CACHE_GROUP );
88 }
89 }
90
91 // If a list of IDs are provided, narrow down the snippets list.
92 if ( $ids_count > 0 ) {
93 $ids = array_map( 'intval', $ids );
94 return array_filter(
95 $snippets,
96 function ( Snippet $snippet ) use ( $ids ) {
97 return in_array( $snippet->id, $ids, true );
98 }
99 );
100 }
101
102 return $snippets;
103 }
104
105 /**
106 * Gets all used tags from the database.
107 * Read operation.
108 *
109 * @since 2.0
110 */
111 function get_all_snippet_tags() {
112 global $wpdb;
113 $table_name = code_snippets()->db->get_table_name();
114 $cache_key = "all_snippet_tags_$table_name";
115
116 $tags = wp_cache_get( $cache_key, CACHE_GROUP );
117 if ( $tags ) {
118 return $tags;
119 }
120
121 // Grab all tags from the database.
122 $tags = array();
123 $all_tags = $wpdb->get_col( "SELECT tags FROM $table_name" ); // db call ok.
124
125 // Merge all tags into a single array.
126 foreach ( $all_tags as $snippet_tags ) {
127 $snippet_tags = code_snippets_build_tags_array( $snippet_tags );
128 $tags = array_merge( $snippet_tags, $tags );
129 }
130
131 // Remove duplicate tags.
132 $tags = array_values( array_unique( $tags, SORT_REGULAR ) );
133 wp_cache_set( $cache_key, $tags, CACHE_GROUP );
134 return $tags;
135 }
136
137 /**
138 * Make sure that the tags are a valid array.
139 *
140 * @param mixed $tags The tags to convert into an array.
141 *
142 * @return array The converted tags.
143 *
144 * @since 2.0.0
145 */
146 function code_snippets_build_tags_array( $tags ) {
147
148 /* If there are no tags set, return an empty array. */
149 if ( empty( $tags ) ) {
150 return array();
151 }
152
153 /* If the tags are set as a string, convert them into an array. */
154 if ( is_string( $tags ) ) {
155 $tags = wp_strip_all_tags( $tags );
156 $tags = str_replace( ', ', ',', $tags );
157 $tags = explode( ',', $tags );
158 }
159
160 /* If we still don't have an array, just convert whatever we do have into one. */
161 return (array) $tags;
162 }
163
164 /**
165 * Retrieve a single snippets from the database.
166 * Will return empty snippet object if no snippet ID is specified.
167 * Read operation.
168 *
169 * @param int $id The ID of the snippet to retrieve. 0 to build a new snippet.
170 * @param boolean|null $multisite Retrieve a multisite-wide snippet (true) or site-wide snippet (false).
171 *
172 * @return Snippet A single snippet object.
173 * @since 2.0.0
174 */
175 function get_snippet( $id = 0, $multisite = null ) {
176 global $wpdb;
177
178 $id = absint( $id );
179 $multisite = DB::validate_network_param( $multisite );
180 $table_name = code_snippets()->db->get_table_name( $multisite );
181
182 if ( 0 === $id ) {
183 // If an invalid ID is provided, then return an empty snippet object.
184 $snippet = new Snippet();
185
186 } else {
187 $cached_snippets = wp_cache_get( "all_snippets_$table_name", CACHE_GROUP );
188
189 // Attempt to fetch snippet from the cached list, if it exists.
190 if ( is_array( $cached_snippets ) ) {
191 foreach ( $cached_snippets as $snippet ) {
192 if ( $snippet->id === $id ) {
193 return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $multisite );
194 }
195 }
196 }
197
198 // Otherwise, retrieve the snippet from the database.
199 $snippet_data = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table_name WHERE id = %d", $id ) ); // cache pass, db call ok.
200 $snippet = new Snippet( $snippet_data );
201 }
202
203 $snippet->network = $multisite;
204 return apply_filters( 'code_snippets/get_snippet', $snippet, $id, $multisite );
205 }
206
207 /**
208 * Activates a snippet.
209 * Write operation.
210 *
211 * @param int $id ID of the snippet to activate.
212 * @param bool|null $multisite Whether the snippets are multisite-wide (true) or site-wide (false).
213 *
214 * @return Snippet|string Snippet object on success, error message on failure.
215 * @since 2.0.0
216 */
217 function activate_snippet( $id, $multisite = null ) {
218 global $wpdb;
219 $db = code_snippets()->db;
220 $table_name = $db->get_table_name( $multisite );
221
222 // Retrieve the snippet code from the database for validation before activating.
223 $snippet = get_snippet( $id, $multisite );
224 if ( ! $snippet || 0 === $snippet->id ) {
225 /* translators: %d: snippet ID */
226 return sprintf( __( 'Could not locate snippet with ID %d.', 'code-snippets' ), $id );
227 }
228
229 $validator = new Validator( $snippet->code );
230 if ( $validator->validate() ) {
231 return __( 'Could not activate snippet: code did not pass validation.', 'code-snippets' );
232 }
233
234 $result = $wpdb->update(
235 $table_name,
236 array( 'active' => '1' ),
237 array( 'id' => $id ),
238 array( '%d' ),
239 array( '%d' )
240 ); // db call ok.
241
242 if ( ! $result ) {
243 return __( 'Could not activate snippet.', 'code-snippets' );
244 }
245
246 /* Remove snippet from shared network snippet list if it was Network Activated */
247 if ( $table_name === $db->ms_table ) {
248 $shared_network_snippets = get_site_option( 'shared_network_snippets' );
249 if ( $shared_network_snippets ) {
250 $shared_network_snippets = array_diff( $shared_network_snippets, array( $id ) );
251 update_site_option( 'shared_network_snippets', $shared_network_snippets );
252 }
253 }
254
255 do_action( 'code_snippets/activate_snippet', $id, $multisite );
256 clean_snippets_cache( $table_name );
257 return $snippet;
258 }
259
260 /**
261 * Activates multiple snippets.
262 * Write operation.
263 *
264 * @param array $ids The IDs of the snippets to activate.
265 * @param bool|null $multisite Whether the snippets are multisite-wide (true) or site-wide (false).
266 *
267 * @return array The IDs of the snippets which were successfully activated.
268 *
269 * @since 2.0.0
270 */
271 function activate_snippets( array $ids, $multisite = null ) {
272 global $wpdb;
273 $db = code_snippets()->db;
274 $multisite = DB::validate_network_param( $multisite );
275 $table_name = $db->get_table_name( $multisite );
276 $snippets = get_snippets( $ids, $multisite );
277
278 if ( ! $snippets ) {
279 return array();
280 }
281
282 // Loop through each snippet code and validate individually.
283 $valid_ids = array();
284
285 foreach ( $snippets as $snippet ) {
286 $validator = new Validator( $snippet->code );
287 $code_error = $validator->validate();
288
289 if ( ! $code_error ) {
290 $valid_ids[] = $snippet->id;
291 }
292 }
293
294 // If there are no valid snippets, then we're done.
295 if ( ! $valid_ids ) {
296 return $valid_ids;
297 }
298
299 // Build a SQL query containing all IDs, as wpdb::update does not support OR conditionals.
300 $ids_format = implode( ',', array_fill( 0, count( $valid_ids ), '%d' ) );
301 // phpcs:disable WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
302 $wpdb->query( $wpdb->prepare( "UPDATE $table_name SET active = 1 WHERE id IN ($ids_format)", $valid_ids ) ); // db call ok.
303
304 // Remove any snippets from shared network snippet list if they were Network Activated.
305 if ( $table_name === $db->ms_table ) {
306 $shared_network_snippets = get_site_option( 'shared_network_snippets' );
307
308 if ( $shared_network_snippets ) {
309 $shared_network_snippets = array_diff( $shared_network_snippets, $valid_ids );
310 update_site_option( 'shared_network_snippets', $shared_network_snippets );
311 clean_active_snippets_cache( $db->ms_table );
312 }
313 }
314
315 do_action( 'code_snippets/activate_snippets', $valid_ids, $multisite );
316 clean_snippets_cache( $table_name );
317 return $valid_ids;
318 }
319
320 /**
321 * Deactivate a snippet.
322 * Write operation.
323 *
324 * @param int $id ID of the snippet to deactivate.
325 * @param bool|null $multisite Whether the snippets are multisite-wide (true) or site-wide (false).
326 *
327 * @return bool Whether the deactivation was successful.
328 *
329 * @uses $wpdb to set the snippets' active status.
330 * @since 2.0.0
331 */
332 function deactivate_snippet( $id, $multisite = null ) {
333 global $wpdb;
334 $db = code_snippets()->db;
335 $table = $db->get_table_name( $multisite );
336
337 // Set the snippet to active.
338 $result = $wpdb->update(
339 $table,
340 array( 'active' => '0' ),
341 array( 'id' => $id ),
342 array( '%d' ),
343 array( '%d' )
344 ); // db call ok.
345
346 if ( ! $result ) {
347 return false;
348 }
349
350 // Update the recently active list.
351 $recently_active = array( $id => time() );
352
353 if ( $table === $db->table ) {
354
355 update_option(
356 'recently_activated_snippets',
357 $recently_active + (array) get_option( 'recently_activated_snippets', array() )
358 );
359 } elseif ( $table === $db->ms_table ) {
360
361 update_site_option(
362 'recently_activated_snippets',
363 $recently_active + (array) get_site_option( 'recently_activated_snippets', array() )
364 );
365 }
366
367 do_action( 'code_snippets/deactivate_snippet', $id, $multisite );
368 clean_snippets_cache( $table );
369 return true;
370 }
371
372 /**
373 * Deletes a snippet from the database.
374 * Write operation.
375 *
376 * @param int $id ID of the snippet to delete.
377 * @param bool|null $multisite Delete from network-wide (true) or site-wide (false) table.
378 *
379 * @since 2.0.0
380 */
381 function delete_snippet( $id, $multisite = null ) {
382 global $wpdb;
383 $table = code_snippets()->db->get_table_name( $multisite );
384
385 $wpdb->delete(
386 $table,
387 array( 'id' => $id ),
388 array( '%d' )
389 ); // db call ok.
390
391 do_action( 'code_snippets/delete_snippet', $id, $multisite );
392 clean_snippets_cache( $table );
393 }
394
395 /**
396 * Saves a snippet to the database.
397 * Write operation.
398 *
399 * @param Snippet $snippet The snippet to add/update to the database.
400 *
401 * @return int ID of the snippet
402 *
403 * @since 2.0.0
404 */
405 function save_snippet( Snippet $snippet ) {
406 global $wpdb;
407 $table = code_snippets()->db->get_table_name( $snippet->network );
408
409 // Update the last modification date if necessary.
410 $snippet->update_modified();
411
412 // Build array of data to insert.
413 $data = array(
414 'name' => $snippet->name,
415 'description' => $snippet->desc,
416 'code' => $snippet->code,
417 'tags' => $snippet->tags_list,
418 'scope' => $snippet->scope,
419 'priority' => $snippet->priority,
420 'active' => intval( $snippet->active ),
421 'modified' => $snippet->modified,
422 );
423
424 // Create a new snippet if the ID is not set.
425 if ( 0 === $snippet->id ) {
426 $result = $wpdb->insert( $table, $data, '%s' ); // db call ok.
427 if ( false === $result ) {
428 return 0;
429 }
430
431 $snippet->id = $wpdb->insert_id;
432 do_action( 'code_snippets/create_snippet', $snippet, $table );
433 } else {
434
435 // Otherwise, update the snippet data.
436 $result = $wpdb->update( $table, $data, array( 'id' => $snippet->id ), null, array( '%d' ) ); // db call ok.
437 if ( false === $result ) {
438 return 0;
439 }
440
441 do_action( 'code_snippets/update_snippet', $snippet, $table );
442 }
443
444 clean_snippets_cache( $table );
445 return $snippet->id;
446 }
447
448 /**
449 * Update a snippet entry given a list of fields.
450 * Write operation.
451 *
452 * @param int $snippet_id ID of the snippet to update.
453 * @param array $fields An array of fields mapped to their values.
454 * @param bool|null $network Update in network-wide (true) or site-wide (false) table.
455 */
456 function update_snippet_fields( $snippet_id, $fields, $network = null ) {
457 global $wpdb;
458
459 $table = code_snippets()->db->get_table_name( $network );
460
461 // Build a new snippet object for the validation.
462 $snippet = new Snippet();
463 $snippet->id = $snippet_id;
464
465 // Validate fields through the snippet class and copy them into a clean array.
466 $clean_fields = array();
467
468 foreach ( $fields as $field => $value ) {
469
470 if ( $snippet->set_field( $field, $value ) ) {
471 $clean_fields[ $field ] = $snippet->$field;
472 }
473 }
474
475 // Update the snippet in the database.
476 $wpdb->update( $table, $clean_fields, array( 'id' => $snippet->id ), null, array( '%d' ) ); // db call ok.
477
478 do_action( 'code_snippets/update_snippet', $snippet->id, $table );
479 clean_snippets_cache( $table );
480 }
481
482 /**
483 * Execute a snippet.
484 * Execute operation.
485 *
486 * Code must NOT be escaped, as it will be executed directly.
487 *
488 * @param string $code Snippet code to execute.
489 * @param int $id Snippet ID.
490 * @param bool $catch_output Whether to attempt to suppress the output of execution using buffers.
491 *
492 * @return mixed Result of the code execution
493 * @since 2.0.0
494 */
495 function execute_snippet( $code, $id = 0, $catch_output = true ) {
496
497 if ( empty( $code ) || defined( 'CODE_SNIPPETS_SAFE_MODE' ) && CODE_SNIPPETS_SAFE_MODE ) {
498 return false;
499 }
500
501 if ( $catch_output ) {
502 ob_start();
503 }
504
505 $result = eval( $code );
506
507 if ( $catch_output ) {
508 ob_end_clean();
509 }
510
511 do_action( 'code_snippets/after_execute_snippet', $id, $code, $result );
512
513 return $result;
514 }
515
516 /**
517 * Run the active snippets.
518 * Read-write-execute operation.
519 *
520 * @return bool true on success, false on failure.
521 *
522 * @since 2.0.0
523 */
524 function execute_active_snippets() {
525 global $wpdb;
526
527 // Bail early if safe mode is active.
528 if ( defined( 'CODE_SNIPPETS_SAFE_MODE' ) && CODE_SNIPPETS_SAFE_MODE || ! apply_filters( 'code_snippets/execute_snippets', true ) ) {
529 return false;
530 }
531
532 $db = code_snippets()->db;
533 $scopes = array( 'global', 'single-use', is_admin() ? 'admin' : 'front-end' );
534 $data = $db->fetch_active_snippets( $scopes );
535
536 foreach ( $data as $table_name => $active_snippets ) {
537
538 // Loop through the returned snippets and execute the PHP code.
539 foreach ( $active_snippets as $snippet ) {
540 $snippet_id = intval( $snippet['id'] );
541 $code = $snippet['code'];
542
543 // If the snippet is a single-use snippet, deactivate it before execution to ensure that the process always happens.
544 if ( 'single-use' === $snippet['scope'] ) {
545 $active_shared_ids = get_option( 'active_shared_network_snippets', array() );
546
547 if ( $table_name === $db->ms_table && is_array( $active_shared_ids ) && in_array( $snippet_id, $active_shared_ids, true ) ) {
548 unset( $active_shared_ids[ array_search( $snippet_id, $active_shared_ids, true ) ] );
549 $active_shared_ids = array_values( $active_shared_ids );
550 update_option( 'active_shared_network_snippets', $active_shared_ids );
551 clean_active_snippets_cache( $table_name );
552 } else {
553 $wpdb->update(
554 $table_name,
555 array( 'active' => '0' ),
556 array( 'id' => $snippet_id ),
557 array( '%d' ),
558 array( '%d' )
559 ); // db call ok.
560 clean_snippets_cache( $table_name );
561 }
562 }
563
564 if ( apply_filters( 'code_snippets/allow_execute_snippet', true, $snippet_id, $table_name ) ) {
565 execute_snippet( $code, $snippet_id );
566 }
567 }
568 }
569
570 return true;
571 }
572