PluginProbe
Code Snippets / 3.1.0
Code Snippets v3.1.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.1.0, at php/class-list-table.php

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