PluginProbe
Code Snippets / 3.5.0
Code Snippets v3.5.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.5.0, at php/class-list-table.php

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