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

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