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

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