PluginProbe
Code Snippets / 2.14.6
Code Snippets v2.14.6
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 2.14.6, at php/class-list-table.php

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