PluginProbe
Code Snippets / 2.14.6
Code Snippets v2.14.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 / snippet-ops.php

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

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