PluginProbe
Post Snippets – Custom WordPress Code Snippets Customizer / 4.2.2
Post Snippets – Custom WordPress Code Snippets Customizer v4.2.2
4.2.4 4.2.3 4.2.2 4.2.1 4.2.0 4.1.1 1.7.2 1.7.3 1.8 1.8.1 1.8.2 1.8.3 1.8.5 1.8.6 1.8.7 1.8.8 1.8.9 1.8.9.1 1.8.9.2 1.9 1.9.1 1.9.2 1.9.3 1.9.4 1.9.5 All 115 releases
post-snippets / src / PostSnippets / PSallSnippets.php

PSallSnippets.php in Post Snippets – Custom WordPress Code Snippets Customizer 4.2.2, at src/PostSnippets/PSallSnippets.php

1,231 lines 45.7 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace PostSnippets;
3
4 if ( ! defined( 'ABSPATH' ) ) exit;
5
6 /**
7 * Post Snippets All Snippets Table.
8 *
9 * Class to view list of all Snippets extending WP_List_Table class.
10 *
11 */
12 if (class_exists('PostSnippets')) {
13
14 if (!class_exists('WP_List_Table')) {
15 require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
16 }
17
18 class PSallSnippets extends \WP_List_Table
19 {
20
21 /**
22 * Generates the table navigation above or bellow the table
23 *
24 * @param string $which
25 * @return void
26 */
27
28
29 function display_tablenav($which)
30 {
31 ?>
32 <div class="tablenav <?php echo esc_attr($which); ?>">
33
34 <div class="alignleft actions bulkactions">
35 <?php $this->bulk_actions($which); ?>
36 </div>
37 <?php
38 $this->extra_tablenav($which);
39 $this->pagination($which);
40 ?>
41 <br class="clear" />
42 </div>
43 <?php
44
45 }
46
47
48
49 function column_snippet_title($item)
50 { //function name is array key of the column
51
52 $snippet_status = ($item['snippet_status'] == esc_attr__('Active', 'post-snippets') ? esc_attr__('Deactivate', 'post-snippets') : esc_attr__('Activate', 'post-snippets'));
53
54 $action_nonce = wp_create_nonce('ps-snippets-hover-trigger_' . $item['ID']);
55
56 $page = Edit::get_snippet_page($item['snippet_php']);
57
58 $actions = array(
59 'edit' => sprintf('<a href="?page=%s&action=%s&snippet=%s&_wpnonce=%s">%s</a>', esc_attr($page), 'edit', $item['ID'], $action_nonce, esc_attr__('Edit', 'post-snippets')),
60 'delete' => sprintf('<button class="link_style_button red" type=%s name=%s value=%s>%s</button>', esc_attr('submit'), 'delete', $item['ID'], esc_attr__('Delete', 'post-snippets')),
61 'status' => sprintf('<button class="link_style_button" type=%s name=%s value=%s>%s</button>', esc_attr('submit'), sanitize_title($snippet_status), $item['ID'], $snippet_status),
62 'duplicate' => sprintf('<button class="link_style_button" type=%s name=%s value=%s>%s</button>', esc_attr('submit'), 'duplicate', $item['ID'], esc_attr__('Duplicate', 'post-snippets')),
63 );
64
65 return sprintf('%1$s %2$s', $item['snippet_title'], $this->row_actions($actions));
66 }
67
68
69 function get_bulk_actions()
70 { //Bulk Action Dropdown
71 $actions = array(
72 'enable' => 'Enable',
73 'disable' => 'Disable'
74 );
75 return $actions;
76 }
77
78 function column_cb($item)
79 { //Checkbox column
80 return sprintf(
81 '<input type="checkbox" name="snippets[]" value="%s" class="post-snippet-table-individual-checkbox"/>',
82 $item['ID']
83 );
84 }
85
86 /**This will add vals to table class */
87 function __construct()
88 {
89 parent::__construct(array(
90 'singular' => 'psp_all_snippet', //Singular label
91 'plural' => 'psp_all_snippets', //plural label, also this well be one of the table css class
92 // 'ajax' => false //We won't support Ajax for this table
93 ));
94 }
95
96
97 /**
98 * Add extra markup in the toolbars before or after the list
99 * @param string $which, helps you decide if you add the markup after (bottom) or before (top) the list
100 */
101 function extra_tablenav($which)
102 {
103
104 if ($which == "top") {
105 //The code that goes before the table is here
106 ?>
107
108 <div class="alignleft actions">
109 <label class="screen-reader-text"
110 for="filter_by_status"><?php esc_html_e('Filter by status', 'post-snippets') ?></label>
111 <select name="status" id="filter_by_status" class="postform">
112 <option value="-1"> <?php esc_html_e('Select Status', 'post-snippets') ?></option>
113 <option value="1" <?php echo esc_attr((1 == ($_REQUEST['status'] ?? '')) ? " selected" : ''); ?>>
114 <?php esc_html_e('Active', 'post-snippets') ?></option>
115 <option value="0" <?php echo esc_attr((0 == ($_REQUEST['status'] ?? '')) ? " selected" : ''); ?>>
116 <?php esc_html_e('Inactive', 'post-snippets') ?></option>
117 </select>
118 <input type="submit" name="status_filter_action" id="doaction" class="button action"
119 value="<?php esc_html_e('Filter', 'post-snippets') ?>">
120
121 </div>
122
123
124
125
126 </div>
127
128 <?php
129 }
130 }
131
132
133 /**
134 * Prepare the items for the table to process
135 *
136 * @return Void
137 */
138 public function prepare_items()
139 {
140
141 $this->trigger_hover_action();
142 $this->process_bulk_action();
143 $this->process_bulk_upload();
144 $this->process_bulk_download();
145
146 global $wpdb;
147
148 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
149 $group_table_name = $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME;
150
151 // $snippets_query = $this->process_bulk_filter($table_name);
152
153 // $snippets = $wpdb->get_results($wpdb->prepare($snippets_query, NULL), ARRAY_A );
154
155 $snippets = $this->process_bulk_filter($table_name);
156
157 if (!empty($snippets) && $snippets != NULL) {
158
159 $data = $snippets;
160
161 foreach ($data as $key => $value) { /**Changing group name and status and date*/
162
163 $data[$key]['snippet_status'] = ($data[$key]['snippet_status'] == 1 ? esc_attr__('Active', 'post-snippets') : esc_attr__('InActive', 'post-snippets'));
164 $date = $data[$key]['snippet_date'];
165 $createDate = new \DateTime($date);
166 $data[$key]['snippet_date'] = $createDate->format('d-m-Y');
167
168 unset($data[$key]['snippet_content']); /**No need for Snippet Content */
169 unset($data[$key]['snippet_vars']); /**No need for Snippet Vars on List Table */
170
171 $data[$key]['snippet_desc'] = esc_html(stripslashes($data[$key]['snippet_desc']));
172 }
173
174 usort($data, array(&$this, 'sort_data')); //sort_data is a function, use database related function
175
176 $perPage = $this->get_items_per_page('psp_snippets_per_page', 10);
177 $currentPage = $this->get_pagenum();
178 $totalItems = count($data);
179
180 $this->set_pagination_args(array(
181 'total_items' => $totalItems,
182 'per_page' => $perPage
183 ));
184
185 $data = array_slice($data, (($currentPage - 1) * $perPage), $perPage);
186
187 $this->items = $data;
188
189 }
190
191 $columns = $this->get_columns();
192 $hidden = $this->get_hidden_columns();
193 $sortable = $this->get_sortable_columns();
194
195 $this->_column_headers = array($columns, $hidden, $sortable);
196
197 }
198
199 /**
200 * Override the parent columns method. Defines the columns to use in your listing table
201 *
202 * @return Array
203 */
204 public function get_columns()
205 {
206 $columns = array(
207 'cb' => '<input type="checkbox" />',
208 // 'id' => 'ID',
209 'snippet_title' => esc_attr__('Title', 'post-snippets'),
210 'snippet_desc' => esc_attr__('Description', 'post-snippets'),
211 'snippet_status' => esc_attr__('Status', 'post-snippets'),
212 'snippet_date' => esc_attr__('Date', 'post-snippets'),
213
214 );
215
216 return $columns;
217 }
218
219 /**
220 * Define which columns are hidden
221 *
222 * @return Array
223 */
224 public function get_hidden_columns()
225 {
226 return array();
227 }
228
229 /**
230 * Define the sortable columns
231 *
232 * @return Array
233 */
234 public function get_sortable_columns()
235 {
236 return array('snippet_title' => array('snippet_title', false));
237 }
238
239 /**
240 * Define what data to show on each column of the table
241 *
242 * @param Array $item Data
243 * @param String $column_name - Current column name
244 *
245 * @return Mixed
246 */
247 public function column_default($item, $column_name)
248 {
249 switch ($column_name) {
250 case 'ID':
251 case 'snippet_title':
252 case 'snippet_desc':
253 case 'snippet_status':
254 case 'snippet_group':
255 case 'snippet_date':
256 $content = $this->col_content_short_length($item[$column_name]);
257 return $content;
258
259 default:
260 return print_r($item, true);
261 }
262 }
263
264 /**
265 * @param $col : column content
266 *
267 * @return content Short Content
268 */
269 public function col_content_short_length($col)
270 {
271 $content = str_replace(array("\r\n", "\r", "\n"), "[BR]", htmlspecialchars($col));
272 $content = mb_strimwidth($content, 0, 100, " ...");
273 return $content;
274 }
275
276 /**
277 * Allows you to sort the data by the variables set in the $_GET
278 *
279 * @return Mixed
280 */
281 private function sort_data($a, $b)
282 {
283 // Set defaults
284 $orderby = 'snippet_title';
285 $order = 'asc';
286
287 // If orderby is set, use this as the sort column
288 if (!empty($_GET['orderby'])) {
289 $orderby = $_GET['orderby'];
290 }
291
292 // If order is set use this as the order
293 if (!empty($_GET['order'])) {
294 $order = $_GET['order'];
295 }
296
297
298 $result = strcmp($a[$orderby], $b[$orderby]);
299
300 if ($order === 'asc') {
301 return $result;
302 }
303
304 return -$result;
305 }
306
307
308 /**
309 * Trigger Actions from the Hovering Actions section
310 *
311 * @return NULL
312 */
313 private function trigger_hover_action()
314 {
315
316 if (isset($_REQUEST['delete'])) {
317
318 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
319
320 $snippet_id = intval($_REQUEST['delete']);
321
322 if ($this->delete_snippet($snippet_id)) {
323 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippet Deleted', 'post-snippets'));
324 } else {
325 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
326 }
327
328 } elseif (isset($_REQUEST['deactivate'])) { /**if it needs to be deactivate */
329
330 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
331
332 $snippet_id = intval($_REQUEST['deactivate']);
333
334 if ($this->change_snippet_status($snippet_id, 0)) {
335 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippet Deactivated', 'post-snippets'));
336 } else {
337 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
338 }
339 } elseif (isset($_REQUEST['activate'])) { /**if it needs to be activated */
340
341 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
342
343 $snippet_id = intval($_REQUEST['activate']);
344
345 if ($this->change_snippet_status($snippet_id, 1)) {
346 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippet Activated', 'post-snippets'));
347 } else {
348 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
349 }
350 } elseif (isset($_REQUEST['duplicate'])) { /**If duplicate is clicked */
351
352 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
353
354 $snippet_id = intval($_REQUEST['duplicate']);
355
356 if ($this->duplicate_snippet($snippet_id)) {
357 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippet Duplicated', 'post-snippets'));
358 } else {
359 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
360 }
361 }
362 }
363
364 /**
365 * Delete Snippet from the Hovering Actions section
366 *
367 * @return NULL
368 */
369 private function delete_snippet($snippet_id)
370 {
371
372 global $wpdb;
373 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
374
375 $snippet_groups = maybe_unserialize($wpdb->get_var($wpdb->prepare("SELECT snippet_group FROM $table_name WHERE ID = %d", $snippet_id)));
376
377 if ($wpdb->delete($table_name, array('ID' => $snippet_id), array('%d'))) {
378
379 if (!empty($snippet_groups)) { /**It should have atleast one group, the default group, but just in case */
380
381 Edit::change_group_count($snippet_groups, 'decrement');
382
383 }
384 return true;
385 }
386
387 }
388
389
390
391 /**
392 * Change Snippet Status from the Hovering Actions section
393 *
394 * @param Array|Int $snippet_ids Snippets ID Array or Int
395 * @param Int $action Whether to activate(1) or deactivate(0)
396 *
397 * @return Boolean
398 */
399 private function change_snippet_status($snippet_ids, $action)
400 {
401
402 global $wpdb;
403 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
404
405 if (!is_array($snippet_ids)) {
406
407 $snippet_ids = array($snippet_ids);
408
409 }
410
411 foreach ($snippet_ids as $key => $snippet_id) {
412
413 $snippet_status = $wpdb->get_var($wpdb->prepare("SELECT snippet_status FROM $table_name WHERE ID = %d", $snippet_id)); /**Getting It's Status */
414
415 if ($action == 1 && $snippet_status != 1) { /**If its Already Active, Skip */
416
417 $status_updated = $this->update_snippet_status($snippet_id, $action, $table_name, $wpdb);
418 } elseif ($action == 0 && $snippet_status != 0) { /**If its Already InActive, Skip */
419
420 $status_updated = $this->update_snippet_status($snippet_id, $action, $table_name, $wpdb);
421 } else {
422 $status_updated = true;
423 }
424 }
425
426 if ($status_updated) {
427 return true;
428 }
429 }
430
431
432 /**
433 * Change Snippet Status from the Hovering Actions section
434 *
435 * @param Int $snippet_id Snippets ID
436 * @param Int $action Whether to activate(1) or deactivate(0)
437 *
438 * @return Int|Bool
439 */
440 private function update_snippet_status($snippet_id, $action, $table_name, $wpdb)
441 {
442
443 $status_updated = $wpdb->update(
444 $table_name,
445 array( /**Data to be updated */
446 'snippet_status' => $action,
447 ),
448 array( /**Where Coulum = ? */
449 'ID' => $snippet_id,
450 ),
451 array( /**Data Format, %d or %s */
452 '%d'
453 ),
454 array( /**Where Format, %d or %s */
455 '%d'
456 )
457 );
458
459 return $status_updated;
460
461 }
462
463
464 /**
465 * Duplicate Snippet from the Hovering Actions section
466 *
467 * @return NULL
468 */
469 public static function duplicate_snippet($snippet_id)
470 {
471
472 global $wpdb;
473 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
474
475 $current_time = (current_time('mysql'));
476
477 $snippet_title = $wpdb->get_var($wpdb->prepare("SELECT snippet_title FROM $table_name WHERE ID = %d", $snippet_id));
478 $snippet_title = Edit::number_duplicate_snippet_title($snippet_title);
479 $snippet_title = trim($snippet_title);
480
481 $data = $wpdb->query($wpdb->prepare("INSERT INTO $table_name
482 (snippet_group,
483 snippet_title,
484 snippet_content,
485 snippet_date,
486 snippet_vars,
487 snippet_desc,
488 snippet_status,
489 snippet_shortcode,
490 snippet_php,
491 snippet_wptexturize)
492 SELECT
493 snippet_group,
494 '$snippet_title',
495 snippet_content,
496 '$current_time',
497 snippet_vars,
498 snippet_desc,
499 snippet_status,
500 snippet_shortcode,
501 snippet_php,
502 snippet_wptexturize
503 FROM $table_name WHERE ID = %d", $snippet_id));
504
505
506 if ($data) {
507
508 $snippet_groups = maybe_unserialize($wpdb->get_var($wpdb->prepare("SELECT snippet_group FROM $table_name WHERE ID = %d", $wpdb->insert_id)));
509
510 Edit::change_group_count($snippet_groups, 'increment');
511
512 return true;
513 }
514
515 }
516
517 /**
518 * Process Bulk Action
519 *
520 * @return NULL
521 */
522 private function process_bulk_action()
523 {
524
525 $action = $this->current_action();
526
527 if ($action && !empty($_REQUEST['snippets']) && is_array($_REQUEST['snippets'])) {
528
529 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
530
531 if ($action == 'enable') {
532
533 if ($this->change_snippet_status($_REQUEST['snippets'], 1)) { //$_REQUEST is taken here directly cuz it will be an array
534 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippets Activated', 'post-snippets'));
535 } else {
536 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
537 }
538
539 } elseif ($action == 'disable') {
540
541 if ($this->change_snippet_status($_REQUEST['snippets'], 0)) {
542 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippets Deactivated', 'post-snippets'));
543 } else {
544 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
545 }
546
547 }
548
549 }
550
551 }
552
553 /**
554 * Process Bulk Filter
555 *
556 *
557 * @return NULL
558 */
559 private function process_bulk_filter($table_name)
560 {
561
562 global $wpdb;
563
564 if (isset($_REQUEST['status_filter_action'])) {
565
566 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
567
568 $group_filter = intval($_REQUEST['group'] ?? 0);
569 $status_filter = intval($_REQUEST['status'] ?? 0);
570
571 $wildB = '%\"';
572 $wildE = '\"%';
573 $find = $group_filter;
574 $like = $wildB . $wpdb->esc_like($find) . $wildE;
575
576 if ($group_filter > 0 && $status_filter >= 0) { //if Both group and Status are selected
577
578 // return (sprintf( "SELECT * FROM $table_name WHERE snippet_group LIKE '%s' AND snippet_status = $status_filter", $like ) );
579 return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_group LIKE '%s' AND snippet_status = $status_filter", $like), ARRAY_A);
580
581 } elseif ($status_filter >= 0) {
582
583 // return ( ( "SELECT * FROM $table_name WHERE snippet_status = $status_filter") );
584 return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_status = %d", $status_filter), ARRAY_A);
585
586 } elseif ($group_filter > 0) {
587 // return (sprintf( "SELECT * FROM $table_name WHERE snippet_group LIKE '%s'", $like ) );
588 return $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_group LIKE '%s'", $like), ARRAY_A);
589 } else {
590 // return "SELECT * FROM $table_name";
591 return $wpdb->get_results($wpdb->prepare("SELECT * FROM %1s", $table_name), ARRAY_A);
592 }
593 } else {
594 // return "SELECT * FROM $table_name"; //Get all Snippets
595 return $wpdb->get_results($wpdb->prepare("SELECT * FROM %1s", $table_name), ARRAY_A); //Get all Snippets
596 }
597 }
598
599
600
601 /**
602 * Process Bulk Download
603 *
604 *
605 * @return NULL
606 */
607 private function process_bulk_download()
608 {
609
610 if (isset($_REQUEST['psp_download_selected']) && isset($_REQUEST['snippets']) && is_array($_REQUEST['snippets']) && !empty($_REQUEST['snippets'])) {
611
612 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
613
614 $snippets_ids = $_REQUEST['snippets'];
615
616 $snippets_ids = implode(',', $snippets_ids);
617
618 $snippets_ids = "($snippets_ids)";
619
620 $ie = new ImportExport();
621
622 $download_succeed = $ie->exportSnippets($snippets_ids);
623
624 if ($download_succeed) {
625 printf('<div class="notice notice-success is-dismissible"><p>%s..</p></div>', esc_html__('Snippets Downloaded', 'post-snippets'));
626 } else {
627 printf('<div class="notice notice-error is-dismissible"><p>%s..</p></div>', esc_html__('There has been an Error', 'post-snippets'));
628 }
629 }
630 }
631
632
633 /**
634 * Process Bulk Upload
635 *
636 *
637 * @return NULL
638 */
639 private function process_bulk_upload()
640 {
641
642 if (isset($_REQUEST['psp_upload_selected']) && isset($_REQUEST['snippets']) && is_array($_REQUEST['snippets']) && !empty($_REQUEST['snippets'])) {
643
644 check_admin_referer('pspro_all_snippets', 'pspro_all_snippets_nonce');
645
646 }
647 }
648
649 public static function get_all_snippets_gutenberg()
650 {
651
652 global $wpdb;
653
654 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
655
656 $all_snippets = $wpdb->get_results($wpdb->prepare("SELECT ID, snippet_title, snippet_vars FROM $table_name WHERE snippet_status = %d AND snippet_php != %d AND snippet_php != %d", 1, 2, 3), ARRAY_A);
657
658 if (!empty($all_snippets)) {
659
660 $snippet_list = array();
661 foreach ($all_snippets as $snippet) {
662 if (array_key_exists("ID", $snippet) && array_key_exists("snippet_title", $snippet)) {
663 $snippet_list[$snippet["ID"]] =
664 array(
665 'snippet_title' => $snippet["snippet_title"],
666 'snippet_vars' => Shortcode::filterVars($snippet["snippet_vars"])
667 );
668 }
669 }
670
671 return rest_ensure_response($snippet_list);
672 }
673
674 return rest_ensure_response(array());
675
676 }
677
678 public static function render_block_content($attributes)
679 {
680
681 if (empty($attributes)) {
682 return;
683 }
684
685 global $wpdb;
686 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
687 $atts = array();
688 $snippet = '';
689
690 //Backward Compatibility, getting Snippet ID From Name
691 if (!isset($attributes["snippetID"]) && isset($attributes["snippet"])) {
692
693 $particular_snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_title = %s AND snippet_status = 1", $attributes["snippet"]), ARRAY_A);
694
695 if (!empty($particular_snippets)) {
696
697 $snippet = array();
698 foreach ($particular_snippets as $particular_snippet) { /**Multiple Snippets of Similar Name (Case Sensitive) */
699
700 if (strcmp($particular_snippet['snippet_title'], $attributes["snippet"]) == 0 && !empty($particular_snippet)) {
701 $snippet = $particular_snippet;
702 if (isset($attributes['vars']) && !empty($attributes['vars'])) {
703 //for backward compatibility for variables
704 $atts_value = explode("=", $attributes['vars']);
705 if (isset($atts_value[0]) && isset($atts_value[1])) {
706 $atts[$atts_value[0]] = $atts_value[1];
707 }
708 }
709 break;
710 }
711 }
712 }
713 } elseif (isset($attributes["snippetID"]) && is_numeric($attributes["snippetID"])) {
714
715 $snippet_id = intval($attributes["snippetID"]);
716
717 $snippet = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE ID = %d AND snippet_status = 1", $snippet_id), ARRAY_A);
718
719 if (!empty($snippet)) {
720 $snippet = $snippet[0];
721 }
722
723 $atts = $attributes["snippetVars"] ?? [];
724
725 if (!empty($atts) || is_array($atts)) { /**Removing Empty Arrays, so that they get default Vals(snippet_vars) */
726 foreach ($atts as $key => $att) {
727 if (empty($att)) {
728 unset($atts[$key]);
729 }
730 }
731 }
732
733 } else {
734 return;
735 }
736
737 return Shortcode::evaluateSnippet($snippet, $atts);
738
739 }
740
741 public static function get_all_snippets_rest()
742 {
743
744 global $wpdb;
745
746 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
747
748 $all_snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM %1s", $table_name), ARRAY_A);
749
750 if (!empty($all_snippets)) {
751
752 foreach ($all_snippets as $snippet) {
753
754 $all_snippets_backward[] = array(
755
756 'title' => $snippet['snippet_title'],
757 'vars' => $snippet['snippet_vars'],
758 'description' => $snippet['snippet_desc'],
759 'shortcode' => $snippet['snippet_shortcode'],
760 'php' => $snippet['snippet_php'],
761 'wptexturize' => $snippet['snippet_wptexturize'],
762 'snippet' => $snippet['snippet_content'],
763 'ID' => $snippet['ID'],
764 'status' => $snippet['snippet_status'],
765 'group' => $snippet['snippet_group'],
766 'date' => $snippet['snippet_date'],
767
768 );
769
770 }
771
772 return rest_ensure_response($all_snippets_backward);
773
774 }
775
776 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Not Found.', 'post-snippets')));
777
778 }
779
780
781 public static function get_particular_snippets_rest($snippet_title)
782 {
783
784 if (!empty($snippet_title)) {
785
786 global $wpdb;
787
788 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
789
790 $wild = '%';
791 $find = $snippet_title;
792 $snippet_title_like = $wild . $wpdb->esc_like($find) . $wild;
793
794 $particular_snippets_all = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_title LIKE %s", $snippet_title_like), ARRAY_A);
795
796 foreach ($particular_snippets_all as $particular_snippets) {
797
798 if (strcmp($particular_snippets['snippet_title'], $snippet_title) == 0 && !empty($particular_snippets)) {
799
800 $particular_snippet['title'] = $particular_snippets['snippet_title'];
801 $particular_snippet['vars'] = $particular_snippets['snippet_vars'];
802 $particular_snippet['description'] = $particular_snippets['snippet_desc'];
803 $particular_snippet['shortcode'] = $particular_snippets['snippet_shortcode'];
804 $particular_snippet['php'] = $particular_snippets['snippet_php'];
805 $particular_snippet['wptexturize'] = $particular_snippets['snippet_wptexturize'];
806 $particular_snippet['snippet'] = $particular_snippets['snippet_content'];
807 $particular_snippet['ID'] = $particular_snippets['ID'];
808 $particular_snippet['status'] = $particular_snippets['snippet_status'];
809 $particular_snippet['group'] = $particular_snippets['snippet_group'];
810 $particular_snippet['date'] = $particular_snippets['snippet_date'];
811
812 return rest_ensure_response($particular_snippet);
813
814 }
815 }
816
817 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Not Found.', 'post-snippets')));
818 } else {
819
820 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Title Required.', 'post-snippets')));
821
822 }
823
824 }
825
826
827
828 public static function delete_snippets_rest($snippet_titles)
829 {
830
831 if (!empty($snippet_titles)) {
832
833 global $wpdb;
834 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
835
836 $snippet_titles = explode(",", $snippet_titles);
837
838 $snippet_deleted = false;
839
840 foreach ($snippet_titles as $snippet_title) {
841
842 $wild = '%';
843 $find = $snippet_title;
844 $snippet_title_like = $wild . $wpdb->esc_like($find) . $wild;
845
846 $particular_snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_title LIKE %s", $snippet_title_like), ARRAY_A);
847
848 foreach ($particular_snippets as $particular_snippet) {
849
850 if (strcmp($particular_snippet['snippet_title'], $snippet_title) == 0 && !empty($particular_snippet)) {
851
852 $snippet_groups = maybe_unserialize($particular_snippet['snippet_group']);
853
854 $snippet_deleted = $wpdb->delete($table_name, array('ID' => $particular_snippet['ID']), array('%d'));
855
856 if ($snippet_deleted) {
857
858 if (!empty($snippet_groups)) { /**It should have atleast one group, the default group, but just in case */
859
860 Edit::change_group_count($snippet_groups, 'decrement');
861
862 }
863 }
864 }
865 }
866
867 }
868
869 if ($snippet_deleted) {
870 return rest_ensure_response(array('success' => true, 'message' => __('Snippet Successfully Deleted.', 'post-snippets')));
871 } else {
872 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Not Found.', 'post-snippets')));
873 }
874 } else {
875 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Title Required', 'post-snippets')));
876 }
877
878 }
879
880
881 public static function create_snippet_rest($request)
882 {
883
884 global $wpdb;
885 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
886
887
888 $upgrouped_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM " . $wpdb->prefix . \PostSnippets::GROUP_TABLE_NAME . " WHERE group_slug = %s", __('ungrouped', 'post-snippets')));
889 $group_list = array($upgrouped_id);
890
891
892 $snippet_title = $request['title'];
893 $pattern = '/[\s]/i'; /**remove any WhiteSpaces */
894 $replacement = '';
895 $snippet_title = preg_replace($pattern, $replacement, $snippet_title);
896 $snippet_title = sanitize_text_field($snippet_title);
897
898 $current_snippets_titles = $wpdb->get_results($wpdb->prepare("SELECT snippet_title from %1s", $table_name), ARRAY_A);
899 $current_snippets_titles = array_column($current_snippets_titles, "snippet_title");
900 if (in_array($snippet_title, $current_snippets_titles)) {
901 //duplicate according to settings
902 return rest_ensure_response(array('success' => false, 'message' => __('Duplicate Titles are currently not allowed.', 'post-snippets')));
903
904 $snippet_added = true;
905 }
906
907 $snippet_added = $wpdb->insert(
908 $table_name,
909 array(
910 'snippet_group' => maybe_serialize($group_list),
911 'snippet_title' => $snippet_title,
912 'snippet_content' => addslashes($request['snippet_code']),
913 'snippet_date' => current_time('mysql'),
914 'snippet_vars' => $request['vars'], /**already filtered in rest parameters */
915 'snippet_desc' => sanitize_textarea_field($request['description']),
916 'snippet_status' => 1,
917 'snippet_shortcode' => $request['shortcode'],
918 'snippet_php' => $request['php'],
919 'snippet_wptexturize' => $request['wptexturize'],
920 )
921 );
922
923 if ($snippet_added) {
924
925 return rest_ensure_response(array('success' => true, 'message' => __('Snippet Successfully Added.', 'post-snippets')));
926
927 } else {
928 return rest_ensure_response(array('success' => false, 'message' => __('Could not Add Snippet.', 'post-snippets')));
929 }
930
931
932
933 }
934
935
936 public static function update_snippet_rest($request)
937 {
938
939 global $wpdb;
940 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
941
942 $wild = '%';
943 $find = $request['title'];
944 $snippet_title_like = $wild . $wpdb->esc_like($find) . $wild;
945
946 $particular_snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE snippet_title LIKE %s", $snippet_title_like), ARRAY_A);
947
948 if (empty($particular_snippets)) {
949 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Not Found.', 'post-snippets')));
950 }
951
952 foreach ($particular_snippets as $particular_snippet) {
953
954 if (strcmp($particular_snippet['snippet_title'], $request['title']) == 0 && !empty($particular_snippet)) {
955 $snippet_found = $particular_snippet;
956 } else {
957 return rest_ensure_response(array('success' => false, 'message' => __('Snippet Not Found.', 'post-snippets')));
958 }
959
960 }
961
962 $snippet_updated = $wpdb->update(
963 $table_name,
964 array(
965 // 'snippet_group' => maybe_serialize( $group_list ),
966 // 'snippet_title' => $snippet_title,
967 // 'snippet_status' => $request['snippet_status'] ?? 0, //Disable by default
968 'snippet_content' => addslashes($request['snippet_code']),
969 'snippet_date' => current_time('mysql'),
970 'snippet_vars' => $request['vars'],
971 'snippet_desc' => sanitize_textarea_field($request['description']),
972 'snippet_shortcode' => $request['shortcode'] ?? 0,
973 'snippet_php' => $request['php'] ?? 0,
974 'snippet_wptexturize' => $request['wptexturize'] ?? 0,
975 ),
976 array( /**Where Coulum = ? */
977 'ID' => $snippet_found['ID'],
978 ),
979 array( /**Data Format, %d or %s */
980 /*'%s', '%s', '%d',*/ '%s',
981 '%s',
982 '%s',
983 '%s',
984 '%d',
985 '%d',
986 '%d'
987 ),
988 array( /**Where Format, %d or %s */
989 '%d'
990 )
991 );
992
993
994 if ($snippet_updated) {
995
996 return rest_ensure_response(array('success' => true, 'message' => __('Snippet Successfully Updated.', 'post-snippets')));
997
998 } else {
999 return rest_ensure_response(array('success' => false, 'message' => __('Could not Update Snippet.', 'post-snippets')));
1000 }
1001 }
1002
1003 public static function get_snippet_php($php)
1004 {
1005
1006 if (empty($php)) {
1007 return 0;
1008 }
1009
1010 if (in_array($php, array(0, 1, 2, 3))) {
1011 return $php;
1012 }
1013
1014 return 0;
1015
1016 }
1017
1018
1019
1020 public static function run_snippets($snippets)
1021 {
1022
1023 if (empty($snippets)) {
1024 return;
1025 }
1026
1027 $script_pattern = "/\<script[\w\s]*\>/i";
1028 $style_pattern = "/\<style[\w\s]*\>/i";
1029
1030 foreach ($snippets as $snippet) {
1031
1032 if ($snippet['snippet_php'] == 2 && !empty($snippet['snippet_content'])) {
1033 $snippet_content = stripslashes($snippet['snippet_content']);
1034
1035 $tag_exists = preg_match($script_pattern, $snippet_content);
1036
1037 if (!$tag_exists) {
1038
1039 ?>
1040
1041 <script><?php echo $snippet_content; ?></script>
1042
1043 <?php
1044 } else {
1045 // If script tag already exists, sanitize the entire content
1046 echo wp_kses($snippet_content, array(
1047 'script' => array(
1048 'type' => array(),
1049 'src' => array(),
1050 'async' => array(),
1051 'defer' => array(),
1052 ),
1053 ));
1054 }
1055 } elseif ($snippet['snippet_php'] == 3 && !empty($snippet['snippet_content'])) {
1056 $snippet_content = stripslashes($snippet['snippet_content']);
1057 // Sanitize CSS content to prevent XSS
1058 $snippet_content = wp_kses($snippet_content, array(
1059 'style' => array(
1060 'type' => array(),
1061 'media' => array(),
1062 ),
1063 ));
1064 $tag_exists = preg_match($style_pattern, $snippet_content);
1065
1066 if (!$tag_exists) {
1067
1068 ?>
1069
1070 <style>
1071 <?php echo $snippet_content; ?>
1072 </style>
1073
1074 <?php
1075 } else {
1076 // If style tag already exists, output sanitized content
1077 echo wp_kses($snippet_content, array(
1078 'style' => array(
1079 'type' => array(),
1080 'media' => array(),
1081 ),
1082 ));
1083 }
1084 }
1085
1086 }
1087
1088
1089 }
1090
1091 public static function run_admin_js_css()
1092 {
1093
1094 if (wp_doing_ajax() || isset($_REQUEST['_fs_blog_admin'])) {
1095 return true;
1096 }
1097
1098 global $wpdb;
1099 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
1100
1101 if (is_admin()) {
1102
1103 $wild = '%';
1104 $find = 'admin';
1105 $snippet_var_like = $wild . $wpdb->esc_like($find) . $wild;
1106
1107 $snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE (snippet_php = %d OR snippet_php = %d) AND snippet_vars LIKE %s AND snippet_status = 1", 2, 3, $snippet_var_like), ARRAY_A);
1108
1109 }
1110
1111 if (empty($snippets) || empty(array_filter($snippets))) {
1112 return;
1113 }
1114
1115 self::run_snippets($snippets);
1116
1117
1118 }
1119
1120 public static function run_frontend_header_js()
1121 {
1122
1123 global $wpdb;
1124 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
1125
1126 $wild = '%';
1127 $find = 'frontend';
1128 $snippet_var_like = $wild . $wpdb->esc_like($find) . $wild;
1129 $location_not_like = 'footer';
1130 $snippet_var_not_like = $wild . $wpdb->esc_like($location_not_like) . $wild;
1131
1132 $snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE (snippet_php = %d) AND snippet_status = 1 AND snippet_vars LIKE %s AND snippet_vars NOT LIKE %s", 2, $snippet_var_like, $snippet_var_not_like), ARRAY_A);
1133
1134 $updated_snippets = self::filter_snippets_for_page($snippets, $location_not_like);
1135
1136 // echo "<pre>";
1137 // print_r($updated_snippets);
1138 // echo "</pre>";
1139
1140 // die("Debugging");
1141
1142 self::run_snippets($updated_snippets);
1143
1144 }
1145
1146 public static function run_frontend_footer_js_css()
1147 {
1148
1149 global $wpdb;
1150 $table_name = $wpdb->prefix . \PostSnippets::TABLE_NAME;
1151
1152 $wild = '%';
1153 $find = 'frontend';
1154 $snippet_var_like = $wild . $wpdb->esc_like($find) . $wild;
1155 $location_not_like = 'header';
1156 $snippet_var_not_like = $wild . $wpdb->esc_like($location_not_like) . $wild;
1157
1158 $snippets = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table_name WHERE (snippet_php = %d OR snippet_php = %d) AND snippet_status = 1 AND snippet_vars LIKE %s AND snippet_vars NOT LIKE %s", 2, 3, $snippet_var_like, $snippet_var_not_like), ARRAY_A);
1159
1160 $updated_snippets = self::filter_snippets_for_page($snippets, $location_not_like);
1161
1162 // echo "<pre>";
1163 // print_r($updated_snippets);
1164 // echo "</pre>";
1165
1166 // die("Debugging");
1167
1168 self::run_snippets($updated_snippets);
1169
1170
1171 }
1172
1173
1174 public static function filter_snippets_for_page($snippets, $location = 'header')
1175 {
1176
1177 if (empty($snippets)) {
1178 return;
1179 }
1180
1181 $updated_snippets = array();
1182
1183 foreach ($snippets as $snippet) {
1184
1185 $snippets_vars = Shortcode::filterVars($snippet["snippet_vars"]);
1186 $snippets_vars_keys = array_keys($snippets_vars);
1187
1188 if (in_array($location, $snippets_vars_keys) || !in_array('frontend', $snippets_vars_keys)) {
1189 continue;
1190 }
1191
1192 if (in_array('all_website', $snippets_vars_keys)) {
1193 $updated_snippets[] = $snippet;
1194 }
1195
1196 if (is_front_page() || is_home()) {
1197
1198 if (in_array('homepage', $snippets_vars_keys)) {
1199 $updated_snippets[] = $snippet;
1200 }
1201 }
1202
1203 if (is_page()) {
1204 if (in_array('all_pages', $snippets_vars_keys)) {
1205 $updated_snippets[] = $snippet;
1206 }
1207 }
1208
1209 if (is_single()) {
1210 if (in_array('all_posts', $snippets_vars_keys)) {
1211 $updated_snippets[] = $snippet;
1212 }
1213 }
1214
1215 if (in_array('specific_page', $snippets_vars_keys)) {
1216
1217 $specific_page = $snippets_vars['specific_page'] ?? '';
1218
1219 if (!empty($specific_page) && is_numeric($specific_page) && (is_page($specific_page) || is_single($specific_page))) {
1220
1221 $updated_snippets[] = $snippet;
1222
1223 }
1224 }
1225
1226 }
1227
1228 return $updated_snippets;
1229 }
1230 }
1231 }