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

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