PluginProbe
Code Snippets / 3.0.0
Code Snippets v3.0.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 / trunk / php / snippet-ops.php

snippet-ops.php in Code Snippets 3.0.0, at trunk/php/snippet-ops.php

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