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 / php / class-list-table.php

class-list-table.php in Code Snippets 3.0.0, at php/class-list-table.php

1,293 lines 36.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace Code_Snippets;
4
5 use function Code_Snippets\Settings\get_setting;
6 use WP_List_Table;
7
8 /**
9 * Contains the class for handling the snippets table
10 *
11 * @package Code_Snippets
12 *
13 * phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
14 */
15
16 /* The WP_List_Table base class is not included by default, so we need to load it */
17 if ( ! class_exists( 'WP_List_Table' ) ) {
18 require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
19 }
20
21 /**
22 * This class handles the table for the manage snippets menu
23 *
24 * @since 1.5
25 * @package Code_Snippets
26 */
27 class List_Table extends WP_List_Table {
28
29 /**
30 * Whether the current screen is in the network admin
31 *
32 * @var bool
33 */
34 public $is_network;
35
36 /**
37 * A list of statuses (views)
38 *
39 * @var array
40 */
41 public $statuses = array( 'all', 'active', 'inactive', 'recently_activated' );
42
43 /**
44 * Column name to use when ordering the snippets list.
45 *
46 * @var string
47 */
48 protected $order_by;
49
50 /**
51 * Direction to use when ordering the snippets list. Either 'asc' or 'desc'.
52 *
53 * @var string
54 */
55 protected $order_dir;
56
57 /**
58 * The constructor function for our class.
59 * Adds hooks, initializes variables, setups class.
60 *
61 * @phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
62 */
63 public function __construct() {
64 global $status, $page;
65 $this->is_network = is_network_admin();
66
67 /* Determine the status */
68 $status = apply_filters( 'code_snippets/list_table/default_view', 'all' );
69 if ( isset( $_REQUEST['status'] ) && in_array( sanitize_key( $_REQUEST['status'] ), $this->statuses, true ) ) {
70 $status = sanitize_key( $_REQUEST['status'] );
71 }
72
73 /* Add the search query to the URL */
74 if ( isset( $_REQUEST['s'] ) ) {
75 $_SERVER['REQUEST_URI'] = add_query_arg( 's', sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) );
76 }
77
78 /* Add a snippets per page screen option */
79 $page = $this->get_pagenum();
80
81 add_screen_option(
82 'per_page',
83 array(
84 'label' => __( 'Snippets per page', 'code-snippets' ),
85 'default' => 999,
86 'option' => 'snippets_per_page',
87 )
88 );
89
90 add_filter( 'default_hidden_columns', array( $this, 'default_hidden_columns' ) );
91
92 /* Strip the result query arg from the URL */
93 $_SERVER['REQUEST_URI'] = remove_query_arg( 'result' );
94
95 /* Add filters to format the snippet description in the same way the post content is formatted */
96 $filters = [ 'wptexturize', 'convert_smilies', 'convert_chars', 'wpautop', 'shortcode_unautop', 'capital_P_dangit', 'wp_kses_post' ];
97 foreach ( $filters as $filter ) {
98 add_filter( 'code_snippets/list_table/column_description', $filter );
99 }
100
101 /* Set up the class */
102 parent::__construct(
103 array(
104 'ajax' => true,
105 'plural' => 'snippets',
106 'singular' => 'snippet',
107 )
108 );
109 }
110
111 /**
112 * Set the 'id' column as hidden by default.
113 *
114 * @param array $hidden List of hidden columns.
115 *
116 * @return array
117 */
118 public function default_hidden_columns( $hidden ) {
119 $hidden[] = 'id';
120 return $hidden;
121 }
122
123 /**
124 * Set the 'name' column as the primary column.
125 *
126 * @return string
127 */
128 protected function get_default_primary_column_name() {
129 return 'name';
130 }
131
132 /**
133 * Define the output of all columns that have no callback function
134 *
135 * @param Snippet $item The snippet used for the current row.
136 * @param string $column_name The name of the column being printed.
137 *
138 * @return string The content of the column to output.
139 */
140 protected function column_default( $item, $column_name ) {
141
142 switch ( $column_name ) {
143 case 'id':
144 return $item->id;
145
146 case 'description':
147 return apply_filters( 'code_snippets/list_table/column_description', $item->desc );
148
149 case 'type':
150 $type = $item->type;
151 return sprintf(
152 '<a class="snippet-type-badge" href="%s" data-type="%s">%s</a>',
153 esc_url( add_query_arg( 'type', $type ) ),
154 esc_attr( $type ),
155 esc_html( $type )
156 );
157
158 case 'modified':
159 return $item->modified ? $item->format_modified() : '&#8212;';
160
161 default:
162 return apply_filters( "code_snippets/list_table/column_$column_name", '&#8212;', $item );
163 }
164 }
165
166 /**
167 * Retrieve a URL to perform an action on a snippet
168 *
169 * @param string $action Name of action to produce a link for.
170 * @param Snippet $snippet Snippet object to produce link for.
171 *
172 * @return string URL to perform action.
173 */
174 public function get_action_link( $action, $snippet ) {
175
176 // redirect actions to the network dashboard for shared network snippets
177 $local_actions = array( 'activate', 'activate-shared', 'run-once', 'run-once-shared' );
178 $network_redirect = $snippet->shared_network && ! $this->is_network && ! in_array( $action, $local_actions, true );
179
180 // edit links go to a different menu
181 if ( 'edit' === $action ) {
182 return code_snippets()->get_snippet_edit_url( $snippet->id, $network_redirect ? 'network' : 'self' );
183 }
184
185 $query_args = array(
186 'action' => $action,
187 'id' => $snippet->id,
188 'scope' => $snippet->scope,
189 );
190
191 $url = $network_redirect ?
192 add_query_arg( $query_args, code_snippets()->get_menu_url( 'manage', 'network' ) ) :
193 add_query_arg( $query_args );
194
195 // add a nonce to the URL for security purposes
196 return wp_nonce_url( $url, 'code_snippets_manage_snippet_' . $snippet->id );
197 }
198
199 /**
200 * Build a list of action links for individual snippets
201 *
202 * @param Snippet $snippet The current snippet.
203 *
204 * @return array The action links HTML.
205 */
206 private function get_snippet_action_links( Snippet $snippet ) {
207 $actions = array();
208
209 if ( ! $this->is_network && $snippet->network && ! $snippet->shared_network ) {
210 // display special links if on a subsite and dealing with a network-active snippet
211 if ( $snippet->active ) {
212 $actions['network_active'] = esc_html__( 'Network Active', 'code-snippets' );
213 } else {
214 $actions['network_only'] = esc_html__( 'Network Only', 'code-snippets' );
215 }
216 } elseif ( ! $snippet->shared_network || current_user_can( code_snippets()->get_network_cap_name() ) ) {
217
218 // if the snippet is a shared network snippet, only display extra actions if the user has network permissions
219 $simple_actions = array(
220 'edit' => esc_html__( 'Edit', 'code-snippets' ),
221 'clone' => esc_html__( 'Clone', 'code-snippets' ),
222 'export' => esc_html__( 'Export', 'code-snippets' ),
223 );
224
225 foreach ( $simple_actions as $action => $label ) {
226 $actions[ $action ] = sprintf( '<a href="%s">%s</a>', esc_url( $this->get_action_link( $action, $snippet ) ), $label );
227 }
228
229 $actions['delete'] = sprintf(
230 '<a href="%2$s" class="delete" onclick="%3$s">%1$s</a>',
231 esc_html__( 'Delete', 'code-snippets' ),
232 esc_url( $this->get_action_link( 'delete', $snippet ) ),
233 esc_js(
234 sprintf(
235 'return confirm("%s");',
236 esc_html__( 'You are about to permanently delete the selected item.', 'code-snippets' ) . "\n" .
237 esc_html__( "'Cancel' to stop, 'OK' to delete.", 'code-snippets' )
238 )
239 )
240 );
241 }
242
243 return apply_filters( 'code_snippets/list_table/row_actions', $actions );
244 }
245
246 /**
247 * Retrieve the code for a snippet activation switch
248 *
249 * @param Snippet $snippet Snippet object.
250 *
251 * @return string Output for activation switch.
252 */
253 protected function column_activate( $snippet ) {
254
255 if ( $this->is_network && $snippet->shared_network || ( ! $this->is_network && $snippet->network && ! $snippet ) ) {
256 return '';
257 }
258
259 if ( 'single-use' === $snippet->scope ) {
260 $class = 'snippet-execution-button';
261 $action = 'run-once';
262 $label = esc_html__( 'Run Once', 'code-snippets' );
263 } else {
264 $class = 'snippet-activation-switch';
265 $action = $snippet->active ? 'deactivate' : 'activate';
266 $label = $snippet->network && ! $snippet->shared_network ?
267 ( $snippet->active ? __( 'Network Deactivate', 'code-snippets' ) : __( 'Network Activate', 'code-snippets' ) ) :
268 ( $snippet->active ? __( 'Deactivate', 'code-snippets' ) : __( 'Activate', 'code-snippets' ) );
269 }
270
271 if ( $snippet->shared_network ) {
272 $action .= '-shared';
273 }
274
275 return sprintf(
276 '<a class="%s" href="%s" title="%s">&nbsp;</a> ',
277 esc_attr( $class ),
278 esc_url( $this->get_action_link( $action, $snippet ) ),
279 esc_attr( $label )
280 );
281 }
282
283 /**
284 * Build the content of the snippet name column
285 *
286 * @param Snippet $snippet The snippet being used for the current row.
287 *
288 * @return string The content of the column to output.
289 */
290 protected function column_name( $snippet ) {
291 $row_actions = $this->row_actions(
292 $this->get_snippet_action_links( $snippet ),
293 apply_filters( 'code_snippets/list_table/row_actions_always_visible', true )
294 );
295
296 $out = esc_html( $snippet->display_name );
297
298 if ( 'global' !== $snippet->scope ) {
299 $out .= ' <span class="dashicons dashicons-' . $snippet->scope_icon . '"></span>';
300 }
301
302 /* Add a link to the snippet if it isn't an unreadable network-only snippet */
303 if ( $this->is_network || ! $snippet->network || current_user_can( code_snippets()->get_network_cap_name() ) ) {
304
305 $out = sprintf(
306 '<a href="%s" class="snippet-name">%s</a>',
307 esc_attr( code_snippets()->get_snippet_edit_url( $snippet->id, $snippet->network ? 'network' : 'admin' ) ),
308 $out
309 );
310 }
311
312 if ( $snippet->shared_network ) {
313 $out .= ' <span class="badge">' . esc_html__( 'Shared on Network', 'code-snippets' ) . '</span>';
314 }
315
316 /* Return the name contents */
317
318 $out = apply_filters( 'code_snippets/list_table/column_name', $out, $snippet );
319
320 return $out . $row_actions;
321 }
322
323 /**
324 * Handles the checkbox column output.
325 *
326 * @param Snippet $item The snippet being used for the current row.
327 *
328 * @return string The column content to be printed.
329 */
330 protected function column_cb( $item ) {
331
332 $out = sprintf(
333 '<input type="checkbox" name="%s[]" value="%s">',
334 $item->shared_network ? 'shared_ids' : 'ids',
335 intval( $item->id )
336 );
337
338 return apply_filters( 'code_snippets/list_table/column_cb', $out, $item );
339 }
340
341 /**
342 * Handles the tags column output.
343 *
344 * @param Snippet $snippet The snippet being used for the current row.
345 *
346 * @return string The column output.
347 */
348 protected function column_tags( $snippet ) {
349
350 /* Return now if there are no tags */
351 if ( empty( $snippet->tags ) ) {
352 return '';
353 }
354
355 $out = array();
356
357 /* Loop through the tags and create a link for each one */
358 foreach ( $snippet->tags as $tag ) {
359 $out[] = sprintf( '<a href="%s">%s</a>',
360 esc_url( add_query_arg( 'tag', esc_attr( $tag ) ) ),
361 esc_html( $tag )
362 );
363 }
364
365 return join( ', ', $out );
366 }
367
368 /**
369 * Handles the priority column output.
370 *
371 * @param Snippet $snippet The snippet being used for the current row.
372 *
373 * @return string The column output.
374 */
375 protected function column_priority( $snippet ) {
376 return sprintf( '<input type="number" class="snippet-priority" value="%d" step="1" disabled>', $snippet->priority );
377 }
378
379 /**
380 * Define the column headers for the table
381 *
382 * @return array The column headers, ID paired with label
383 */
384 public function get_columns() {
385 $columns = array(
386 'cb' => '<input type="checkbox">',
387 'activate' => '',
388 'name' => __( 'Name', 'code-snippets' ),
389 'type' => __( 'Type', 'code-snippets' ),
390 'description' => __( 'Description', 'code-snippets' ),
391 'tags' => __( 'Tags', 'code-snippets' ),
392 'date' => __( 'Modified', 'code-snippets' ),
393 'priority' => __( 'Priority', 'code-snippets' ),
394 'id' => __( 'ID', 'code-snippets' ),
395 );
396
397 if ( isset( $_GET['type'] ) && 'all' !== $_GET['type'] ) {
398 unset( $columns['type'] );
399 }
400
401 if ( ! get_setting( 'general', 'enable_description' ) ) {
402 unset( $columns['description'] );
403 }
404
405 if ( ! get_setting( 'general', 'enable_tags' ) ) {
406 unset( $columns['tags'] );
407 }
408
409 return apply_filters( 'code_snippets/list_table/columns', $columns );
410 }
411
412 /**
413 * Define the columns that can be sorted. The format is:
414 * 'internal-name' => 'orderby'
415 * or
416 * 'internal-name' => array( 'orderby', true )
417 *
418 * The second format will make the initial sorting order be descending.
419 *
420 * @return array The IDs of the columns that can be sorted
421 */
422 public function get_sortable_columns() {
423
424 $sortable_columns = array(
425 'id' => array( 'id', true ),
426 'name' => 'name',
427 'type' => array( 'type', true ),
428 'date' => array( 'modified', true ),
429 'priority' => array( 'priority', true ),
430 );
431
432 return apply_filters( 'code_snippets/list_table/sortable_columns', $sortable_columns );
433 }
434
435 /**
436 * Define the bulk actions to include in the drop-down menus
437 *
438 * @return array An array of menu items with the ID paired to the label
439 */
440 public function get_bulk_actions() {
441 $actions = array(
442 'activate-selected' => $this->is_network ? __( 'Network Activate', 'code-snippets' ) : __( 'Activate', 'code-snippets' ),
443 'deactivate-selected' => $this->is_network ? __( 'Network Deactivate', 'code-snippets' ) : __( 'Deactivate', 'code-snippets' ),
444 'clone-selected' => __( 'Clone', 'code-snippets' ),
445 'download-selected' => __( 'Download', 'code-snippets' ),
446 'export-selected' => __( 'Export', 'code-snippets' ),
447 'delete-selected' => __( 'Delete', 'code-snippets' ),
448 );
449
450 return apply_filters( 'code_snippets/list_table/bulk_actions', $actions );
451 }
452
453 /**
454 * Retrieve the classes for the table
455 *
456 * We override this in order to add 'snippets' as a class for custom styling
457 *
458 * @return array The classes to include on the table element
459 */
460 public function get_table_classes() {
461 $classes = array( 'widefat', $this->_args['plural'] );
462
463 return apply_filters( 'code_snippets/list_table/table_classes', $classes );
464 }
465
466 /**
467 * Retrieve the 'views' of the table
468 *
469 * Example: active, inactive, recently active
470 *
471 * @return array A list of the view labels linked to the view
472 */
473 public function get_views() {
474 global $totals, $status;
475 $status_links = array();
476
477 /* Loop through the view counts */
478 foreach ( $totals as $type => $count ) {
479
480 /* Don't show the view if there is no count */
481 if ( ! $count ) {
482 continue;
483 }
484
485 /* Define the labels for each view */
486 $labels = array();
487
488 /* translators: %s: total number of snippets */
489 $labels['all'] = _n(
490 'All <span class="count">(%s)</span>',
491 'All <span class="count">(%s)</span>',
492 $count,
493 'code-snippets'
494 );
495
496 /* translators: %s: total number of active snippets */
497 $labels['active'] = _n(
498 'Active <span class="count">(%s)</span>',
499 'Active <span class="count">(%s)</span>',
500 $count,
501 'code-snippets'
502 );
503
504 /* translators: %s: total number of inactive snippets */
505 $labels['inactive'] = _n(
506 'Inactive <span class="count">(%s)</span>',
507 'Inactive <span class="count">(%s)</span>',
508 $count,
509 'code-snippets'
510 );
511
512 /* translators: %s: total number of recently activated snippets */
513 $labels['recently_activated'] = _n(
514 'Recently Active <span class="count">(%s)</span>',
515 'Recently Active <span class="count">(%s)</span>',
516 $count,
517 'code-snippets'
518 );
519
520 /* The page URL with the status parameter */
521 $url = esc_url( add_query_arg( 'status', $type ) );
522
523 /* Add a class if this view is currently being viewed */
524 $class = $type === $status ? ' class="current"' : '';
525
526 /* Add the view count to the label */
527 $text = sprintf( $labels[ $type ], number_format_i18n( $count ) );
528
529 /* Construct the link */
530 $status_links[ $type ] = sprintf( '<a href="%s"%s>%s</a>', $url, $class, $text );
531 }
532
533 /* Filter and return the list of views */
534
535 return apply_filters( 'code_snippets/list_table/views', $status_links );
536 }
537
538 /**
539 * Gets the tags of the snippets currently being viewed in the table
540 *
541 * @since 2.0
542 */
543 public function get_current_tags() {
544 global $snippets, $status;
545
546 /* If we're not viewing a snippets table, get all used tags instead */
547 if ( ! isset( $snippets, $status ) ) {
548 $tags = get_all_snippet_tags();
549 } else {
550 $tags = array();
551
552 /* Merge all tags into a single array */
553 foreach ( $snippets[ $status ] as $snippet ) {
554 $tags = array_merge( $snippet->tags, $tags );
555 }
556
557 /* Remove duplicate tags */
558 $tags = array_unique( $tags );
559 }
560
561 sort( $tags );
562
563 return $tags;
564 }
565
566 /**
567 * Add filters and extra actions above and below the table
568 *
569 * @param string $which Whether the actions are displayed on the before (true) or after (false) the table.
570 */
571 public function extra_tablenav( $which ) {
572 global $status;
573
574 if ( 'top' === $which ) {
575
576 /* Tags dropdown filter */
577 $tags = $this->get_current_tags();
578
579 if ( count( $tags ) ) {
580 $query = isset( $_GET['tag'] ) ? sanitize_text_field( wp_unslash( $_GET['tag'] ) ) : '';
581
582 echo '<div class="alignleft actions">';
583 echo '<select name="tag">';
584
585 printf( "<option %s value=''>%s</option>\n",
586 selected( $query, '', false ),
587 esc_html__( 'Show all tags', 'code-snippets' )
588 );
589
590 foreach ( $tags as $tag ) {
591
592 printf(
593 "<option %s value='%s'>%s</option>\n",
594 selected( $query, $tag, false ),
595 esc_attr( $tag ),
596 esc_html( $tag )
597 );
598 }
599
600 echo '</select>';
601
602 submit_button( __( 'Filter', 'code-snippets' ), 'button', 'filter_action', false );
603 echo '</div>';
604 }
605 }
606
607 echo '<div class="alignleft actions">';
608
609 if ( 'recently_activated' === $status ) {
610 submit_button( __( 'Clear List', 'code-snippets' ), 'secondary', 'clear-recent-list', false );
611 }
612
613 do_action( 'code_snippets/list_table/actions', $which );
614
615 echo '</div>';
616 }
617
618 /**
619 * Output form fields needed to preserve important
620 * query vars over form submissions
621 *
622 * @param string $context The context in which the fields are being outputted.
623 */
624 public function required_form_fields( $context = 'main' ) {
625
626 $vars = apply_filters(
627 'code_snippets/list_table/required_form_fields',
628 array( 'page', 's', 'status', 'paged', 'tag' ),
629 $context
630 );
631
632 if ( 'search_box' === $context ) {
633 /* Remove the 's' var if we're doing this for the search box */
634 $vars = array_diff( $vars, array( 's' ) );
635 }
636
637 foreach ( $vars as $var ) {
638 if ( ! empty( $_REQUEST[ $var ] ) ) {
639 $value = sanitize_text_field( wp_unslash( $_REQUEST[ $var ] ) );
640 printf( '<input type="hidden" name="%s" value="%s" />', esc_attr( $var ), esc_attr( $value ) );
641 print "\n";
642 }
643 }
644
645 do_action( 'code_snippets/list_table/print_required_form_fields', $context );
646 }
647
648 /**
649 * Perform an action on a single snippet.
650 *
651 * @param int $id Snippet ID.
652 * @param string $action Action to perform.
653 * @param string $scope Snippet scope; used for cache busting CSS and JS snippets.
654 *
655 * @return bool|string Result of performing action
656 * @uses activate_snippet() to activate snippets
657 * @uses deactivate_snippet() to deactivate snippets
658 * @uses delete_snippet() to delete snippets
659 */
660 private function perform_action( $id, $action, $scope = '' ) {
661
662 switch ( $action ) {
663
664 case 'activate':
665 activate_snippet( $id, $this->is_network );
666 return 'activated';
667
668 case 'deactivate':
669 deactivate_snippet( $id, $this->is_network );
670 return 'deactivated';
671
672 case 'run-once':
673 $this->perform_action( $id, 'activate' );
674 return 'executed';
675
676 case 'run-once-shared':
677 $this->perform_action( $id, 'activate-shared' );
678 return 'executed';
679
680 case 'activate-shared':
681 $active_shared_snippets = get_option( 'active_shared_network_snippets', array() );
682
683 if ( ! in_array( $id, $active_shared_snippets, true ) ) {
684 $active_shared_snippets[] = $id;
685 update_option( 'active_shared_network_snippets', $active_shared_snippets );
686 }
687
688 return 'activated';
689
690 case 'deactivate-shared':
691 $active_shared_snippets = get_option( 'active_shared_network_snippets', array() );
692 update_option( 'active_shared_network_snippets', array_diff( $active_shared_snippets, array( $id ) ) );
693 return 'deactivated';
694
695 case 'clone':
696 $this->clone_snippets( array( $id ) );
697 return 'cloned';
698
699 case 'delete':
700 delete_snippet( $id, $this->is_network );
701 return 'deleted';
702
703 case 'export':
704 $export = new Export( $id );
705 $export->export_snippets();
706 break;
707
708 case 'download':
709 $export = new Export( $id );
710 $export->download_snippets();
711 break;
712 }
713
714 return false;
715 }
716
717 /**
718 * Processes actions requested by the user.
719 *
720 * @uses wp_redirect() to pass the results to the current page
721 * @uses add_query_arg() to append the results to the current URI
722 */
723 public function process_requested_actions() {
724
725 /* Clear the recent snippets list if requested to do so */
726 if ( isset( $_POST['clear-recent-list'] ) ) {
727 check_admin_referer( 'bulk-' . $this->_args['plural'] );
728
729 if ( $this->is_network ) {
730 update_site_option( 'recently_activated_snippets', array() );
731 } else {
732 update_option( 'recently_activated_snippets', array() );
733 }
734 }
735
736 /* Check if there are any single snippet actions to perform */
737 if ( isset( $_GET['action'], $_GET['id'] ) ) {
738 $id = absint( $_GET['id'] );
739 $scope = isset( $_GET['scope'] ) ? sanitize_key( wp_unslash( $_GET['scope'] ) ) : '';
740
741 /* Verify they were sent from a trusted source */
742 $nonce_action = 'code_snippets_manage_snippet_' . $id;
743 if ( ! isset( $_GET['_wpnonce'] ) || ! wp_verify_nonce( sanitize_key( wp_unslash( $_GET['_wpnonce'] ) ), $nonce_action ) ) {
744 wp_nonce_ays( $nonce_action );
745 }
746
747 $_SERVER['REQUEST_URI'] = remove_query_arg( array( 'action', 'id', 'scope', '_wpnonce' ) );
748
749 /* If so, then perform the requested action and inform the user of the result */
750 $result = $this->perform_action( $id, sanitize_key( $_GET['action'] ), $scope );
751
752 if ( $result ) {
753 wp_redirect( esc_url_raw( add_query_arg( 'result', $result ) ) );
754 exit;
755 }
756 }
757
758 /* Only continue from this point if there are bulk actions to process */
759 if ( ! isset( $_POST['ids'] ) && ! isset( $_POST['shared_ids'] ) ) {
760 return;
761 }
762
763 check_admin_referer( 'bulk-' . $this->_args['plural'] );
764
765 $ids = isset( $_POST['ids'] ) ? array_map( 'intval', $_POST['ids'] ) : array();
766 $_SERVER['REQUEST_URI'] = remove_query_arg( 'action' );
767
768 switch ( $this->current_action() ) {
769
770 case 'activate-selected':
771 activate_snippets( $ids );
772
773 /* Process the shared network snippets */
774 if ( isset( $_POST['shared_ids'] ) && is_multisite() && ! $this->is_network ) {
775 $active_shared_snippets = get_option( 'active_shared_network_snippets', array() );
776
777 foreach ( array_map( 'intval', $_POST['shared_ids'] ) as $id ) {
778 if ( ! in_array( $id, $active_shared_snippets, true ) ) {
779 $active_shared_snippets[] = $id;
780 }
781 }
782
783 update_option( 'active_shared_network_snippets', $active_shared_snippets );
784 }
785
786 $result = 'activated-multi';
787 break;
788
789 case 'deactivate-selected':
790 foreach ( $ids as $id ) {
791 deactivate_snippet( $id, $this->is_network );
792 }
793
794 /* Process the shared network snippets */
795 if ( isset( $_POST['shared_ids'] ) && is_multisite() && ! $this->is_network ) {
796 $active_shared_snippets = get_option( 'active_shared_network_snippets', array() );
797 $active_shared_snippets = ( '' === $active_shared_snippets ) ? array() : $active_shared_snippets;
798 $active_shared_snippets = array_diff( $active_shared_snippets, array_map( 'intval', $_POST['shared_ids'] ) );
799 update_option( 'active_shared_network_snippets', $active_shared_snippets );
800 }
801
802 $result = 'deactivated-multi';
803 break;
804
805 case 'export-selected':
806 $export = new Export( $ids );
807 $export->export_snippets();
808 break;
809
810 case 'download-selected':
811 $export = new Export( $ids );
812 $export->download_snippets();
813 break;
814
815 case 'clone-selected':
816 $this->clone_snippets( $ids );
817 $result = 'cloned-multi';
818 break;
819
820 case 'delete-selected':
821 foreach ( $ids as $id ) {
822 delete_snippet( $id, $this->is_network );
823 }
824 $result = 'deleted-multi';
825 break;
826 }
827
828 if ( isset( $result ) ) {
829 wp_redirect( esc_url_raw( add_query_arg( 'result', $result ) ) );
830 exit;
831 }
832 }
833
834 /**
835 * Message to display if no snippets are found
836 */
837 public function no_items() {
838
839 if ( ! empty( $GLOBALS['s'] ) || ! empty( $_GET['tag'] ) ) {
840 esc_html_e( 'No snippets were found matching the current search query. Please enter a new query or use the "Clear Filters" button above.', 'code-snippets' );
841
842 } else {
843 $add_url = code_snippets()->get_menu_url( 'add' );
844
845 if ( empty( $_GET['type'] ) ) {
846 esc_html_e( "It looks like you don't have any snippets.", 'code-snippets' );
847 } else {
848 esc_html_e( "It looks like you don't have any snippets of this type.", 'code-snippets' );
849 $add_url = add_query_arg( 'type', sanitize_key( wp_unslash( $_GET['type'] ) ), $add_url );
850 }
851
852 printf(
853 ' <a href="%s">%s</a>',
854 esc_url( $add_url ),
855 esc_html__( 'Perhaps you would like to add a new one?', 'code-snippets' )
856 );
857 }
858 }
859
860 /**
861 * Fetch all shared network snippets for the current site
862 */
863 private function fetch_shared_network_snippets() {
864 global $snippets, $wpdb;
865 $db = code_snippets()->db;
866 $ids = get_site_option( 'shared_network_snippets', false );
867
868 if ( ! is_multisite() || ! $ids ) {
869 return;
870 }
871
872 if ( $this->is_network ) {
873 $limit = count( $snippets['all'] );
874
875 for ( $i = 0; $i < $limit; $i++ ) {
876 /** Snippet @var Snippet $snippet */
877 $snippet = &$snippets['all'][ $i ];
878
879 if ( in_array( $snippet->id, $ids, true ) ) {
880 $snippet->shared_network = true;
881 $snippet->tags = array_merge( $snippet->tags, array( 'shared on network' ) );
882 $snippet->active = false;
883 }
884 }
885 } else {
886 $active_shared_snippets = get_option( 'active_shared_network_snippets', array() );
887 $active_shared_snippet_format = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
888
889 /* phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching */
890 $shared_snippets = $wpdb->get_results(
891 $wpdb->prepare( "
892 SELECT * FROM $db->ms_table
893 WHERE id IN ($active_shared_snippet_format)",
894 $ids
895 ),
896 ARRAY_A
897 );
898
899 foreach ( $shared_snippets as $index => $snippet ) {
900 $snippet = new Snippet( $snippet );
901 $snippet->network = true;
902 $snippet->shared_network = true;
903 $snippet->tags = array_merge( $snippet->tags, array( 'shared on network' ) );
904 $snippet->active = in_array( $snippet->id, $active_shared_snippets, true );
905
906 $shared_snippets[ $index ] = $snippet;
907 }
908
909 $snippets['all'] = array_merge( $snippets['all'], $shared_snippets );
910 }
911 }
912
913 /**
914 * Prepares the items to later display in the table.
915 * Should run before any headers are sent.
916 *
917 * @phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
918 */
919 public function prepare_items() {
920 global $status, $snippets, $totals, $s;
921
922 wp_reset_vars( array( 'orderby', 'order', 's' ) );
923
924 /* Redirect tag filter from POST to GET */
925 if ( isset( $_POST['filter_action'] ) ) {
926 $location = empty( $_POST['tag'] ) ?
927 remove_query_arg( 'tag' ) :
928 add_query_arg( 'tag', sanitize_text_field( wp_unslash( $_POST['tag'] ) ) );
929 wp_redirect( esc_url_raw( $location ) );
930 exit;
931 }
932
933 /* First, lets process the submitted actions */
934 $this->process_requested_actions();
935
936 /* Initialize the $snippets array */
937 $snippets = array_fill_keys( $this->statuses, array() );
938
939 /* Fetch all snippets */
940 $snippets['all'] = apply_filters( 'code_snippets/list_table/get_snippets', get_snippets( array() ) );
941 $this->fetch_shared_network_snippets();
942
943 /* Filter snippets by type */
944 if ( isset( $_GET['type'] ) && 'all' !== $_GET['type'] ) {
945 $snippets['all'] = array_filter(
946 $snippets['all'],
947 function ( Snippet $snippet ) {
948 return $_GET['type'] === $snippet->type;
949 }
950 );
951 }
952
953 /* Add scope tags */
954 /** Snippet @var Snippet $snippet */
955 foreach ( $snippets['all'] as $snippet ) {
956 if ( 'global' !== $snippet->scope ) {
957 $snippet->add_tag( $snippet->scope );
958 }
959 }
960
961 /* Filter snippets by tag */
962 if ( ! empty( $_GET['tag'] ) ) {
963 $snippets['all'] = array_filter( $snippets['all'], array( $this, 'tags_filter_callback' ) );
964 }
965
966 /* Filter snippets based on search query */
967 if ( $s ) {
968 $snippets['all'] = array_filter( $snippets['all'], array( $this, 'search_by_line_callback' ) );
969 }
970
971 /* Clear recently activated snippets older than a week */
972 $recently_activated = $this->is_network ?
973 get_site_option( 'recently_activated_snippets', array() ) :
974 get_option( 'recently_activated_snippets', array() );
975
976 foreach ( $recently_activated as $key => $time ) {
977
978 if ( $time + WEEK_IN_SECONDS < time() ) {
979 unset( $recently_activated[ $key ] );
980 }
981 }
982
983 $this->is_network ?
984 update_site_option( 'recently_activated_snippets', $recently_activated ) :
985 update_option( 'recently_activated_snippets', $recently_activated );
986
987 /**
988 * Filter snippets into individual sections
989 *
990 * @var Snippet $snippet
991 */
992 foreach ( $snippets['all'] as $snippet ) {
993
994 if ( $snippet->active ) {
995 $snippets['active'][] = $snippet;
996 } else {
997 $snippets['inactive'][] = $snippet;
998
999 /* Was the snippet recently deactivated? */
1000 if ( isset( $recently_activated[ $snippet->id ] ) ) {
1001 $snippets['recently_activated'][] = $snippet;
1002 }
1003 }
1004 }
1005
1006 /* Count the totals for each section */
1007 $totals = array();
1008 foreach ( $snippets as $type => $list ) {
1009 $totals[ $type ] = count( $list );
1010 }
1011
1012 /* If the current status is empty, default tp all */
1013 if ( empty( $snippets[ $status ] ) ) {
1014 $status = 'all';
1015 }
1016
1017 /* Get the current data */
1018 $data = $snippets[ $status ];
1019
1020 /* Decide how many records per page to show by getting the user's setting in the Screen Options panel */
1021 $sort_by = $this->screen->get_option( 'per_page', 'option' );
1022 $per_page = get_user_meta( get_current_user_id(), $sort_by, true );
1023
1024 if ( empty( $per_page ) || $per_page < 1 ) {
1025 $per_page = $this->screen->get_option( 'per_page', 'default' );
1026 }
1027
1028 $per_page = (int) $per_page;
1029
1030 $this->set_order_vars();
1031 usort( $data, array( $this, 'usort_reorder_callback' ) );
1032
1033 /* Determine what page the user is currently looking at */
1034 $current_page = $this->get_pagenum();
1035
1036 /* Check how many items are in the data array */
1037 $total_items = count( $data );
1038
1039 /* The WP_List_Table class does not handle pagination for us, so we need to ensure that the data is trimmed to only the current page. */
1040 $data = array_slice( $data, ( ( $current_page - 1 ) * $per_page ), $per_page );
1041
1042 /* Now we can add our *sorted* data to the items property, where it can be used by the rest of the class. */
1043 $this->items = $data;
1044
1045 /* We register our pagination options and calculations */
1046 $this->set_pagination_args(
1047 array(
1048 'total_items' => $total_items, // Calculate the total number of items
1049 'per_page' => $per_page, // Determine how many items to show on a page
1050 'total_pages' => ceil( $total_items / $per_page ), // Calculate the total number of pages
1051 )
1052 );
1053 }
1054
1055 /**
1056 * Determine the sort ordering for two pieces of data.
1057 *
1058 * @param string|integer $a_data First piece of data.
1059 * @param string|integer $b_data Second piece of data.
1060 *
1061 * @return int Returns -1 if $a_data is less than $b_data; 0 if they are equal; 1 otherwise
1062 * @ignore
1063 */
1064 private function get_sort_direction( $a_data, $b_data ) {
1065
1066 // if the data is numeric, then calculate the ordering directly
1067 if ( is_numeric( $a_data ) ) {
1068 return $a_data - $b_data;
1069 }
1070
1071 // if only one of the data points is empty, then place it before the one which is not
1072 if ( '' === $a_data xor '' === $b_data ) {
1073 return '' === $a_data ? 1 : -1;
1074 }
1075
1076 // sort using the default string sort order if possible
1077 if ( is_string( $a_data ) ) {
1078 return strcasecmp( $a_data, $b_data );
1079 }
1080
1081 // otherwise, use basic comparison operators
1082 return $a_data === $b_data ? 0 : ( $a_data < $b_data ? -1 : 1 );
1083 }
1084
1085 /**
1086 * Set the $order_by and $order_dir class variables.
1087 */
1088 private function set_order_vars() {
1089 $order = Settings\get_setting( 'general', 'list_order' );
1090
1091 // set the order by based on the query variable, if set.
1092 if ( ! empty( $_REQUEST['orderby'] ) ) {
1093 $this->order_by = sanitize_key( wp_unslash( $_REQUEST['orderby'] ) );
1094 } else {
1095 // otherwise, fetch the order from the setting, ensuring it is valid.
1096 $valid_fields = [ 'id', 'name', 'type', 'modified', 'priority' ];
1097 $order_parts = explode( '-', $order, 2 );
1098
1099 $this->order_by = in_array( $order_parts[0], $valid_fields, true ) ? $order_parts[0] :
1100 apply_filters( 'code_snippets/list_table/default_orderby', 'priority' );
1101 }
1102
1103 // set the order dir based on the query variable, if set.
1104 if ( ! empty( $_REQUEST['order'] ) ) {
1105 $this->order_dir = sanitize_key( wp_unslash( $_REQUEST['order'] ) );
1106 } elseif ( '-desc' === substr( $order, -5 ) ) {
1107 $this->order_dir = 'desc';
1108 } elseif ( '-asc' === substr( $order, -4 ) ) {
1109 $this->order_dir = 'asc';
1110 } else {
1111 $this->order_dir = apply_filters( 'code_snippets/list_table/default_order', 'asc' );
1112 }
1113 }
1114
1115 /**
1116 * Callback for usort() used to sort snippets
1117 *
1118 * @param Snippet $a The first snippet to compare.
1119 * @param Snippet $b The second snippet to compare.
1120 *
1121 * @return int The sort order.
1122 * @ignore
1123 */
1124 private function usort_reorder_callback( Snippet $a, Snippet $b ) {
1125 $orderby = $this->order_by;
1126 $result = $this->get_sort_direction( $a->$orderby, $b->$orderby );
1127
1128 if ( 0 === $result && 'id' !== $orderby ) {
1129 $result = $this->get_sort_direction( $a->id, $b->id );
1130 }
1131
1132 // apply the sort direction to the calculated order
1133 return ( 'asc' === $this->order_dir ) ? $result : -$result;
1134 }
1135
1136 /**
1137 * Callback for search function
1138 *
1139 * @param Snippet $snippet The snippet being filtered.
1140 *
1141 * @return bool The result of the filter
1142 * @ignore
1143 */
1144 private function search_callback( Snippet $snippet ): bool {
1145 global $s;
1146
1147 $fields = array( 'name', 'desc', 'code', 'tags_list' );
1148
1149 foreach ( $fields as $field ) {
1150 if ( false !== stripos( $snippet->$field, $s ) ) {
1151 return true;
1152 }
1153 }
1154 return false;
1155 }
1156
1157 /**
1158 * Callback for search function
1159 *
1160 * @param Snippet $snippet The snippet being filtered.
1161 *
1162 * @return bool The result of the filter
1163 * @ignore
1164 */
1165 private function search_by_line_callback( Snippet $snippet ): bool {
1166 global $s;
1167 static $line_num;
1168
1169 if ( is_null( $line_num ) ) {
1170
1171 if ( preg_match( '/@line:(?P<line>\d+)/', $s, $matches ) ) {
1172 $s = trim( str_replace( $matches[0], '', $s ) );
1173 $line_num = (int) $matches['line'] - 1;
1174 } else {
1175 $line_num = -1;
1176 }
1177 }
1178
1179 if ( $line_num < 0 ) {
1180 return $this->search_callback( $snippet );
1181 }
1182
1183 $code_lines = explode( "\n", $snippet->code );
1184
1185 return isset( $code_lines[ $line_num ] ) && false !== stripos( $code_lines[ $line_num ], $s );
1186 }
1187
1188 /**
1189 * Callback for filtering snippets by tag.
1190 *
1191 * @param Snippet $snippet The snippet being filtered.
1192 *
1193 * @return bool The result of the filter.
1194 * @ignore
1195 */
1196 private function tags_filter_callback( Snippet $snippet ): bool {
1197 $tags = isset( $_GET['tag'] ) ?
1198 explode( ',', sanitize_text_field( wp_unslash( $_GET['tag'] ) ) ) :
1199 array();
1200
1201 foreach ( $tags as $tag ) {
1202 if ( in_array( $tag, $snippet->tags, true ) ) {
1203 return true;
1204 }
1205 }
1206
1207 return false;
1208 }
1209
1210 /**
1211 * Display a notice showing the current search terms
1212 *
1213 * @since 1.7
1214 */
1215 public function search_notice() {
1216 if ( ! empty( $_REQUEST['s'] ) || ! empty( $_GET['tag'] ) ) {
1217
1218 echo '<span class="subtitle">' . esc_html__( 'Search results', 'code-snippets' );
1219
1220 if ( ! empty( $_REQUEST['s'] ) ) {
1221 $s = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) );
1222
1223 if ( preg_match( '/@line:(?P<line>\d+)/', $s, $matches ) ) {
1224
1225 /* translators: 1: search query, 2: line number */
1226 echo sprintf( esc_html__( ' for &ldquo;%1$s&rdquo; on line %2$d', 'code-snippets' ),
1227 esc_html( trim( str_replace( $matches[0], '', $s ) ) ),
1228 intval( $matches['line'] )
1229 );
1230
1231 } else {
1232 /* translators: %s: search query */
1233 echo esc_html( sprintf( __( ' for &ldquo;%s&rdquo;', 'code-snippets' ), $s ) );
1234 }
1235 }
1236
1237 if ( ! empty( $_GET['tag'] ) ) {
1238 $tag = sanitize_text_field( wp_unslash( $_GET['tag'] ) );
1239 /* translators: %s: tag name */
1240 echo esc_html( sprintf( __( ' in tag &ldquo;%s&rdquo;', 'code-snippets' ), $tag ) );
1241 }
1242
1243 echo '</span>';
1244
1245 /* translators: 1: link URL, 2: link text */
1246 printf( '&nbsp;<a class="button clear-filters" href="%s">%s</a>',
1247 esc_url( remove_query_arg( array( 's', 'tag' ) ) ),
1248 esc_html__( 'Clear Filters', 'code-snippets' )
1249 );
1250 }
1251 }
1252
1253 /**
1254 * Outputs content for a single row of the table
1255 *
1256 * @param Snippet $item The snippet being used for the current row.
1257 */
1258 public function single_row( $item ) {
1259 $status = $item->active ? 'active' : 'inactive';
1260
1261 $row_class = "snippet $status-snippet $item->type-snippet $item->scope-scope";
1262
1263 if ( $item->shared_network ) {
1264 $row_class .= ' shared-network-snippet';
1265 }
1266
1267 printf( '<tr class="%s" data-snippet-scope="%s">', esc_attr( $row_class ), esc_attr( $item->scope ) );
1268 $this->single_row_columns( $item );
1269 echo '</tr>';
1270 }
1271
1272 /**
1273 * Clone a selection of snippets
1274 *
1275 * @param array $ids List of snippet IDs.
1276 */
1277 private function clone_snippets( $ids ) {
1278 $snippets = get_snippets( $ids, $this->is_network );
1279
1280 /** Snippet @var Snippet $snippet */
1281 foreach ( $snippets as $snippet ) {
1282 // copy all data from the previous snippet aside from the ID and active status
1283 $snippet->id = 0;
1284 $snippet->active = false;
1285
1286 /* translators: %s: snippet title */
1287 $snippet->name = sprintf( __( '%s [CLONE]', 'code-snippets' ), $snippet->name );
1288
1289 save_snippet( $snippet );
1290 }
1291 }
1292 }
1293