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

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

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