PluginProbe
Plugin Groups / 2.0.3
Plugin Groups v2.0.3
trunk 1.0.3 1.1.0 1.2.1 1.2.2 2.0.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.0.9 3.0.0
plugin-groups / classes / class-plugin-groups.php

class-plugin-groups.php in Plugin Groups 2.0.3, at classes/class-plugin-groups.php

1,157 lines 29.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Core class for Plugin Groups.
4 *
5 * @package plugin_groups
6 */
7
8 namespace Plugin_Groups;
9
10 /**
11 * Plugin_Groups Class.
12 */
13 class Plugin_Groups {
14
15 /**
16 * The single instance of the class.
17 *
18 * @var Plugin_Groups
19 */
20 protected static $instance = null;
21
22 /**
23 * Holds the version of the plugin.
24 *
25 * @var string
26 */
27 protected $version;
28
29 /**
30 * Holds the plugin name.
31 *
32 * @var string
33 */
34 protected $plugin_name;
35
36 /**
37 * Holds the plugin config.
38 *
39 * @var array
40 */
41 protected $config = array();
42
43 /**
44 * Holds the Groups.
45 *
46 * @var array
47 */
48 protected $groups = array();
49
50 /**
51 * Holds the menu slug.
52 *
53 * @var string
54 */
55 public static $slug = 'plugin-groups';
56
57 /**
58 * Holds the current group.
59 *
60 * @var string
61 */
62 protected $current_group;
63
64 /**
65 * Holds the current status.
66 *
67 * @var string
68 */
69 protected $current_status;
70
71 /**
72 * Holds the current group and status path.
73 *
74 * @var string
75 */
76 protected $current_nav_path;
77
78 /**
79 * Hold the record of the plugins current version for upgrade.
80 *
81 * @var string
82 */
83 const VERSION_KEY = '_plugin_groups_version';
84
85 /**
86 * Hold the config storage key.
87 *
88 * @var string
89 */
90 const CONFIG_KEY = '_plugin_groups_config';
91
92 /**
93 * Initiate the plugin_groups object.
94 */
95 public function __construct() {
96
97 require_once ABSPATH . 'wp-admin/includes/plugin.php';
98 $plugin = get_plugin_data( PLGGRP_CORE );
99 $this->plugin_name = $plugin['Name'];
100 $this->version = $plugin['Version'];
101
102 spl_autoload_register( array( $this, 'autoload_class' ), true, false );
103
104 // Start hooks.
105 $this->setup_hooks();
106
107 // Init the bulk actions.
108 new Bulk_Actions( $this );
109 }
110
111 /**
112 * Setup and register WordPress hooks.
113 */
114 protected function setup_hooks() {
115
116 // Load plugin text domain
117 add_action( 'init', array( $this, 'load_text_domain' ) );
118 add_action( 'init', array( $this, 'plugin_groups_init' ), PHP_INT_MAX ); // Always the last thing to init.
119 add_action( 'admin_init', array( $this, 'admin_init' ) );
120 add_action( 'admin_menu', array( $this, 'admin_menu' ) );
121 add_action( 'network_admin_menu', array( $this, 'admin_menu' ) );
122 add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_assets' ) );
123 add_action( 'rest_api_init', array( $this, 'register_routes' ) );
124 add_filter( 'views_plugins', array( $this, 'add_groups' ), PHP_INT_MAX );
125 add_filter( 'views_plugins-network', array( $this, 'add_groups' ), PHP_INT_MAX );
126 add_filter( 'all_plugins', array( $this, 'catch_selected_group' ) );
127 add_filter( 'show_advanced_plugins', array( $this, 'filter_shown_status' ), 10, 2 );
128 add_filter( 'site_transient_update_plugins', array( $this, 'alter_update_plugins' ) );
129 add_action( 'pre_current_active_plugins', array( $this, 'render_group_navigation' ) );
130 add_filter( 'bulk_actions-plugins', array( $this, 'bulk_actions' ) );
131 add_action( 'admin_bar_menu', array( $this, 'admin_bar_item' ), 100 );
132 add_filter( 'self_admin_url', array( $this, 'append_group_to_self' ), 10, 3 );
133 add_filter( 'plugin_action_links', array( $this, 'append_group_to_actions' ) );
134 }
135
136 /**
137 * Append the current group id to plugin action links to maintain selection on activation and deactivation of plugins.
138 *
139 * @param array $actions Array of action links.
140 *
141 * @return array
142 */
143 public function append_group_to_actions( $actions ) {
144
145 if ( isset( $this->current_group ) ) {
146 foreach ( $actions as &$tag ) {
147 $parts = shortcode_parse_atts( $tag );
148 if ( isset( $parts['href'] ) ) {
149 $url = html_entity_decode( $parts['href'] );
150 $url = add_query_arg( self::$slug, $this->current_group, $url );
151
152 $tag = str_replace( $parts['href'], htmlentities( $url ), $tag );
153 }
154 }
155 }
156
157 return $actions;
158 }
159
160 /**
161 * Append the group to redirect URLS after activation and deactivation of plugins.
162 *
163 * @param string $url The url to append to.
164 * @param string $path The path location.
165 *
166 * @return string
167 */
168 public function append_group_to_self( $url, $path ) {
169
170 if ( 'plugins.php' === wp_parse_url( $path, PHP_URL_PATH ) ) {
171 if ( ! isset( $this->current_group ) ) {
172 // Init the current group if not set yet.
173 $this->catch_selected_group();
174 }
175 // If we found a group, then append it to the self URL on the plugins page to maintain groups in nav.
176 if ( isset( $this->current_group ) ) {
177 $url = add_query_arg( self::$slug, $this->current_group, $url );
178 }
179 }
180
181 return $url;
182 }
183
184 /**
185 * Load the plugin text domain for translation.
186 */
187 public function load_text_domain() {
188
189 load_plugin_textdomain( self::$slug, false, basename( PLGGRP_PATH ) . '/languages' );
190 }
191
192 /**
193 * Remove plugins from the update available.
194 *
195 * @param object $data The data object.
196 *
197 * @return object
198 */
199 public function alter_update_plugins( $data ) {
200
201 if ( $this->current_group ) {
202 $keys = array_keys( $this->groups[ $this->current_group ] );
203 foreach ( $data->response as $key => $plugin ) {
204 if ( ! in_array( $key, $keys, true ) ) {
205 unset( $data->response[ $key ] );
206 }
207 }
208 }
209
210 return $data;
211 }
212
213 /**
214 * Remove status that are not relevant.
215 *
216 * @param bool $show Flag to show.
217 * @param string $status The current status
218 *
219 * @return bool
220 */
221 public function filter_shown_status( $show, $status ) {
222
223 global $plugins;
224
225 static $removes = array(
226 'mustuse',
227 'dropins',
228 );
229 if ( $this->current_group && in_array( $status, $removes, true ) ) {
230 $show = false;
231 }
232 if ( true === $this->config['params']['legacyGrouping'] ) {
233 $plugins += $this->groups;
234 }
235
236 return $show;
237 }
238
239 /**
240 * Render the Group navigation.
241 */
242 public function render_group_navigation() {
243
244 // Use new group system.
245 if ( true !== $this->config['params']['legacyGrouping'] && 'groups-dropdown' !== $this->config['params']['navStyle'] ) {
246 $parts = array();
247 $parts[] = $this->make_all_tag();
248 foreach ( $this->groups as $key => $plugins ) {
249 $parts[] = $this->make_group_tag( $key );
250 }
251
252 $groups = implode( "", $parts );
253 $group_set = Utils::build_tag( 'ul', array( 'class' => array( $this->config['params']['navStyle'] ) ), $groups );
254 $html = Utils::build_tag( 'div', array( 'class' => self::$slug ), $group_set );
255 if ( 1 < count( $parts ) ) {
256 echo wp_kses( $html, wp_kses_allowed_html( 'post' ) );
257 }
258 }
259 }
260
261 /**
262 * Add dropdown navigation on bulk actions.
263 *
264 * @param array $actions Unchanged actions.
265 *
266 * @return array
267 */
268 public function bulk_actions( $actions ) {
269
270 if ( true !== $this->config['params']['legacyGrouping'] && 'groups-dropdown' === $this->config['params']['navStyle'] ) {
271 $this->dropdown_navigation();
272 }
273
274 return $actions;
275 }
276
277 /**
278 * Render a dropdown navigation.
279 *
280 * @param bool $echo Optional flag to echo the field or return the string.
281 *
282 * @return void|string
283 */
284 public function dropdown_navigation( $echo = true ) {
285
286 $html = array();
287 $html[] = '<label for="bulk-action-selector-groups" class="screen-reader-text">' . __( 'All groups', self::$slug ) . '</label>';
288 $html[] = '<select id="bulk-action-selector-groups" onChange="window.location = this.value">';
289 $html[] = '<option value="' . esc_url( $this->get_nav_url() ) . '" ' . ( ! empty( $this->current_group ) ? 'selected="selected"' : '' ) . '>' . __( 'All groups', self::$slug ) . '</option>';
290
291 foreach ( $this->groups as $key => $plugins ) {
292 $group = $this->config['groups'][ $key ];
293 $selected = '';
294 if ( $this->current_group === $key ) {
295 $selected = ' selected="selected"';
296 }
297
298 $html[] = "\t" . '<option value="' . esc_url( $this->get_nav_url( $key ) ) . '"' . $selected . '>' . $group['name'] . ' (' . count( $plugins ) . ')</option>' . "\n";
299 }
300
301 $html[] = "</select>\n";
302 $html = implode( $html );
303 if ( false === $echo ) {
304 return $html;
305 }
306 echo $html;
307 }
308
309 /**
310 * Catch the selected group.
311 *
312 * @param array $plugins List of plugins.
313 *
314 * @return array
315 */
316 public function catch_selected_group( $plugins = array() ) {
317
318 global $status;
319
320 $this->current_status = $status;
321 $selected_group = filter_input( INPUT_GET, self::$slug, FILTER_SANITIZE_STRING );
322 if ( $selected_group && isset( $this->groups[ $selected_group ] ) ) {
323 $this->current_group = $selected_group;
324 if ( ! empty( $plugins ) ) {
325 $plugins = $this->groups[ $selected_group ];
326
327 // Add selection path.
328 $this->current_nav_path .= ' | ' . $this->config['groups'][ $selected_group ]['name'];
329 }
330 }
331
332 // Add our styles if we have groups;
333 if ( ! empty( $this->groups ) ) {
334 wp_enqueue_style( self::$slug . '-navbar' );
335 }
336
337 return $plugins;
338 }
339
340 /**
341 * Get a url link for group navigation.
342 *
343 * @param null|string $id The group ID or null for all.
344 *
345 * @return string
346 */
347 protected function get_nav_url( $id = null ) {
348
349 $url = filter_input( INPUT_SERVER, 'REQUEST_URI', FILTER_SANITIZE_URL );
350 if ( ! $url || false === strpos( 'plugins.php', $url ) ) {
351 // Just in case.
352 $url = self_admin_url( 'plugins.php' );
353 }
354 if ( null === $id ) {
355 // Null id is for the 'All groups'.
356 return remove_query_arg( self::$slug, $url );
357 }
358
359 // If no plugins get a link back to admin.
360 if ( empty( $this->groups[ $id ] ) ) {
361 return add_query_arg( 'page', self::$slug, $url );
362 }
363
364 return add_query_arg(
365 array(
366 'plugin_status' => $this->current_status,
367 self::$slug => $id,
368
369 ),
370 $url
371 );
372 }
373
374 /**
375 * Get the current group.
376 *
377 * @return array|null
378 */
379 public function get_current_group() {
380
381 if ( ! isset( $this->current_group ) ) {
382 $this->catch_selected_group();
383 }
384
385 return $this->current_group ? $this->config['groups'][ $this->current_group ] : null;
386 }
387
388 /**
389 * Get the groups.
390 *
391 * @return array
392 */
393 public function get_groups() {
394
395 return array_values( $this->config['groups'] );
396 }
397
398 /**
399 * Make a group tag.
400 *
401 * @param string $id The Group ID.
402 *
403 * @return string
404 */
405 protected function make_group_tag( $id ) {
406
407 $group = $this->config['groups'][ $id ];
408 $total = count( $this->groups[ $id ] );
409 $counter = '';
410
411 if ( ! empty( $total ) ) {
412
413 $counter = Utils::build_tag( 'span', array( 'class' => 'count' ), " ({$total})" );
414 }
415 $li_atts = array(
416 'class' => array(
417 'group-link',
418 $group['id'],
419 ),
420 );
421 $link_atts = array(
422 'href' => $this->get_nav_url( $id ),
423 );
424 if ( $group['id'] === $this->current_group ) {
425 $li_atts['class'][] = 'current';
426 $link_atts['class'] = 'current';
427 $link_atts['aria-current'] = 'page';
428 }
429
430 $link = Utils::build_tag( 'a', $link_atts, $group['name'] . $counter );
431
432 return Utils::build_tag( 'li', $li_atts, $link );
433 }
434
435 /**
436 * Load presets into groups for built-in and filtered presets.
437 *
438 * @return array
439 */
440 protected function load_presets() {
441
442 $groups = array(
443 'WooCommerce' => array( 'WooCommerce' ),
444 'Easy Digital Downloads' => array( 'Easy Digital Downloads' ),
445 'Ninja Forms' => array( 'Ninja Forms' ),
446 'Gravity Forms' => array( 'Gravity Forms' ),
447 'WPForms' => array( 'WPForms' ),
448 'E-Commerce' => array(
449 'WooCommerce',
450 'Easy Digital Downloads',
451 ),
452 'Forms' => array(
453 'Ninja Forms',
454 'Gravity Forms',
455 'WPForms',
456 'Formidable Forms',
457 ),
458 'SEO' => array(
459 'All in One SEO',
460 'Yoast SEO',
461 ),
462 // @todo: Add more categories for presets.
463 );
464
465 /**
466 * Filter the presets (legacy)
467 *
468 * @deprecated 2.0.0
469 */
470 $groups = apply_filters( 'plugin-groups-get-presets', $groups );
471
472 /**
473 * Filter preset plugin groups.
474 *
475 * @hook get_preset_plugin_groups
476 * @since 2.0.0
477 *
478 * @param $groups {array} The preset groups.
479 *
480 * @return array
481 */
482 $presets = apply_filters( 'get_preset_plugin_groups', $groups );
483 $preset_groups = array();
484 foreach ( $presets as $name => $keywords ) {
485 $id = sanitize_title( $name );
486 $preset_groups[ $id ] = array(
487 'id' => $id,
488 'name' => $name,
489 'plugins' => array(),
490 'keywords' => $keywords,
491 );
492 }
493
494 return array(
495 'preset_groups' => $preset_groups,
496 'presets' => array_keys( $groups ),
497 );
498 }
499
500 /**
501 * Make all link tag.
502 *
503 * @return string
504 */
505 protected function make_all_tag() {
506
507 $link_atts = array(
508 'href' => $this->get_nav_url(),
509 );
510 if ( empty( $this->current_group ) ) {
511 $link_atts['class'] = 'current';
512 $link_atts['aria-current'] = 'page';
513 }
514 $link = Utils::build_tag( 'a', $link_atts, __( 'All Groups', self::$slug ) );
515
516 return Utils::build_tag( 'li', array( 'class' => array( 'group-link', '__allgroups' ) ), $link );
517 }
518
519 /**
520 * Add new filter view
521 *
522 * @param array $views The list of nav tags for plugin statuses.
523 *
524 * @return array
525 */
526 public function add_groups( $views ) {
527
528 foreach ( $views as &$tag ) {
529 if ( preg_match( '/<a([^>]*?)>{1}/', $tag, $found ) ) {
530 $atts = Utils::get_tag_attributes( $found[1] );
531 $url = add_query_arg( self::$slug, $this->current_group, $atts['href'] );
532 $tag = str_replace( $atts['href'], $url, $tag );
533 wp_parse_str( wp_parse_url( $atts['href'], PHP_URL_QUERY ), $query );
534 if ( isset( $query['plugin_status'] ) && $query['plugin_status'] === $this->current_status ) {
535 $names = explode( ' ', wp_kses( $tag, array() ) );
536 array_pop( $names );
537 $this->current_nav_path .= ' | ' . implode( ' ', $names );
538 }
539 }
540 }
541
542 // Legacy.
543 if ( true === $this->config['params']['legacyGrouping'] ) {
544 foreach ( $this->groups as $key => $plugins ) {
545 $views[ $key ] = $this->make_group_tag( $key );
546 }
547 }
548
549 // @todo: Make method.
550 if ( ! empty( $this->current_nav_path ) ) {
551 $append = array(
552 'name' => $this->current_nav_path,
553 );
554 wp_add_inline_script(
555 'wp-util',
556 'var appendHead = ' . wp_json_encode(
557 $append
558 ) . '; var pluginsHead = document.getElementsByClassName(\'wp-heading-inline\' );if( pluginsHead.length ) {pluginsHead[0].innerText += appendHead.name}'
559 );
560 }
561
562 return $views;
563 }
564
565 /**
566 * Register REST Endpoint for saving config.
567 */
568 public function register_routes() {
569
570 register_rest_route(
571 self::$slug,
572 'save',
573 array(
574 'methods' => \WP_REST_Server::CREATABLE,
575 'args' => array(),
576 'callback' => array( $this, 'rest_save_config' ),
577 'permission_callback' => function( \WP_REST_Request $request ) {
578
579 if ( is_multisite() ) {
580 $data = $request->get_json_params();
581 $can = current_user_can_for_blog( $data['siteID'], 'manage_options' );
582 } else {
583 $can = current_user_can( 'manage_options' );
584 }
585
586 return $can;
587 },
588 )
589 );
590
591 register_rest_route(
592 self::$slug,
593 'load',
594 array(
595 'methods' => \WP_REST_Server::READABLE,
596 'args' => array(),
597 'callback' => array( $this, 'rest_load_config' ),
598 'permission_callback' => function( \WP_REST_Request $request ) {
599
600 $id = $request->get_param( 'siteID' );
601
602 return current_user_can_for_blog( $id, 'manage_options' );
603 },
604 )
605 );
606 }
607
608 /**
609 * Load a config for a specific site.
610 *
611 * @param \WP_REST_Request $request
612 *
613 * @return \WP_Error|\WP_HTTP_Response|\WP_REST_Response
614 */
615 public function rest_load_config( \WP_REST_Request $request ) {
616
617 $id = $request->get_param( 'siteID' );
618 $json = $this->build_config_object( $id );
619
620 return rest_ensure_response( json_decode( $json ) );
621 }
622
623 /**
624 * Save endpoint.
625 *
626 * @param \WP_REST_Request $request The request.
627 *
628 * @return \WP_Error|\WP_HTTP_Response|\WP_REST_Response
629 */
630 public function rest_save_config( \WP_REST_Request $request ) {
631
632 $data = $request->get_json_params();
633 $site_id = get_current_blog_id();
634 if ( is_multisite() ) {
635 if ( ! empty( $data['siteID'] ) ) {
636 $site_id = $data['siteID'];
637 unset( $data['siteID'] );
638 }
639 if ( ! empty( $data['sitesEnabled'] ) ) {
640 // Ensure we have the same types.
641 $data['sitesEnabled'] = array_map( 'intval', $data['sitesEnabled'] );
642 }
643 }
644
645 $this->config = wp_parse_args( $data, $this->config );
646 $success = $this->save_config( $site_id );
647
648 return rest_ensure_response( array( 'success' => $success ) );
649 }
650
651 /**
652 * Save the current config.
653 *
654 * @param null|int $site_id The site ID to save for.
655 *
656 * @return bool
657 */
658 protected function save_config( $site_id = null ) {
659
660 if ( is_multisite() ) {
661 if ( null === $site_id ) {
662 $site_id = get_current_blog_id();
663 }
664 $success = update_network_option( $site_id, self::CONFIG_KEY, $this->config );
665 } else {
666 $success = update_option( self::CONFIG_KEY, $this->config );
667 }
668
669 return $success;
670 }
671
672 /**
673 * Autoloader by Locating and finding classes via folder structure.
674 *
675 * @param string $class class name to be checked and autoloaded.
676 */
677
678 function autoload_class( $class ) {
679
680 $class_location = self::locate_class_file( $class );
681 if ( $class_location ) {
682 include_once $class_location;
683 }
684 }
685
686 /**
687 * Locates the path to a requested class name.
688 *
689 * @param string $class The class name to locate.
690 *
691 * @return string|null
692 */
693 static public function locate_class_file( $class ) {
694
695 $return = null;
696 $parts = explode( '\\', strtolower( str_replace( '_', '-', $class ) ) );
697 $core = array_shift( $parts );
698 $self = strtolower( str_replace( '_', '-', __CLASS__ ) );
699 if ( $core === self::$slug ) {
700 $name = 'class-' . strtolower( array_pop( $parts ) ) . '.php';
701 $parts[] = $name;
702 $path = PLGGRP_PATH . 'classes/' . implode( '/', $parts );
703 if ( file_exists( $path ) ) {
704 $return = $path;
705 }
706 }
707
708 return $return;
709 }
710
711 /**
712 * Get the plugin version
713 */
714 public function version() {
715
716 return $this->version;
717 }
718
719 /**
720 * Check plugin_groups version to allow 3rd party implementations to update or upgrade.
721 */
722 protected function check_version() {
723
724 $previous_version = get_option( self::VERSION_KEY, 0.0 );
725 $new_version = $this->version();
726 if ( version_compare( $previous_version, $new_version, '<' ) ) {
727 if ( version_compare( $previous_version, '2.0.0', '<' ) ) {
728 $data = get_option( 'plugin_groups_plugin_groups', array() );
729 if ( ! empty( $data ) ) {
730 $new_config = $this->convert_legacy_groups( $data );
731 update_option( self::CONFIG_KEY, $new_config );
732 }
733 }
734 // Allow for updating.
735 do_action( "_plugin_groups_version_upgrade", $previous_version, $new_version );
736 // Update version.
737 update_option( self::VERSION_KEY, $new_version, true );
738 }
739 }
740
741 /**
742 * Convert legacy configs.
743 *
744 * @param array $data Array of previous version config.
745 *
746 * @return array
747 */
748 protected function convert_legacy_groups( $data ) {
749
750 $groups = array();
751 foreach ( $data['group'] as $group ) {
752 $keywords = explode( "\n", $group['config']['keywords'] );
753 $new_group = array(
754 'id' => $group['_id'],
755 'name' => $group['config']['group_name'],
756 'plugins' => isset( $group['config']['plugins'] ) ? $group['config']['plugins'] : array(),
757 'keywords' => array_filter( $keywords ),
758 );
759 $groups[ $group['_id'] ] = $new_group;
760 }
761
762 // Set up the new config.
763 $config = $this->get_default_config();
764 $config['groups'] = $groups;
765 $config['selectedPresets'] = isset( $data['presets'] ) ? $data['presets'] : array();
766 $config['params']['legacyGrouping'] = true;
767 $config['params']['navStyle'] = 'subsubsub';
768
769 return $config;
770 }
771
772 /**
773 * Initialise plugin_groups.
774 */
775 public function plugin_groups_init() {
776
777 // Check version.
778 $this->check_version();
779
780 // Load config.
781 $this->set_config();
782
783 /**
784 * Init the settings system
785 *
786 * @param Plugin_Groups ${slug} The core object.
787 */
788 do_action( 'plugin_groups_init' );
789 }
790
791 /**
792 * Hook into admin_init.
793 */
794 public function admin_init() {
795
796 if ( ! empty( $_POST['plugin-group-config'] ) ) {
797 $data = stripslashes( $_POST['plugin-group-config'] );
798 $data = json_decode( $data, true );
799 update_option( Plugin_Groups::CONFIG_KEY, $data );
800 wp_safe_redirect( admin_url( 'plugins.php?page=plugin-groups' ) );
801 }
802 $asset = include PLGGRP_PATH . 'js/' . self::$slug . '.asset.php';
803 wp_register_script( self::$slug, PLGGRP_URL . 'js/' . self::$slug . '.js', $asset['dependencies'], $asset['version'], true );
804 wp_register_style( self::$slug, PLGGRP_URL . 'css/' . self::$slug . '.css', array(), $asset['version'] );
805 wp_register_style( self::$slug . '-navbar', PLGGRP_URL . 'css/' . self::$slug . '-navbar.css', array(), $asset['version'] );
806 }
807
808 /**
809 * Hook into the admin_menu.
810 */
811 public function admin_menu() {
812
813 if ( ! $this->network_active() || $this->site_enabled() || is_main_site() ) {
814 add_submenu_page( 'plugins.php', __( 'Plugin Groups', self::$slug ), __( 'Plugin Groups', self::$slug ), 'manage_options', 'plugin-groups', array( $this, 'render_admin' ), 50 );
815 }
816 }
817
818 /**
819 * Check if the plugin is network activated.
820 *
821 * @return bool
822 */
823 protected function network_active() {
824
825 return is_plugin_active_for_network( PLGGRP_SLUG );
826 }
827
828 /**
829 * Check to see if the site is allowed to use this.
830 *
831 * @return bool
832 */
833 protected function site_enabled() {
834
835 $site_id = get_current_blog_id();
836 $main_config = get_network_option( get_main_site_id(), self::CONFIG_KEY, $this->get_default_config() );
837
838 return in_array( $site_id, $main_config['sitesEnabled'], true );
839 }
840
841 /**
842 * Add Groups to the admin bar.
843 *
844 * @param WP_Admin_Bar $admin_bar
845 */
846 public function admin_bar_item( $admin_bar ) {
847
848 if ( ! $this->config['params']['menuGroups'] || ! current_user_can( 'activate_plugins' ) ) {
849 return;
850 }
851
852 $groups = array(
853 'parent' => array(
854 'id' => self::$slug,
855 'title' => $this->plugin_name,
856 'href' => $this->get_nav_url( 'dashboard' ),
857 'meta' => array(
858 'title' => $this->plugin_name,
859 ),
860 ),
861 );
862
863 foreach ( $this->groups as $key => $plugins ) {
864 $group = $this->config['groups'][ $key ];
865 $groups[ $key ] = array(
866 'id' => $key,
867 'parent' => self::$slug,
868 'title' => $group['name'] . ' (' . count( $plugins ) . ')',
869 'href' => $this->get_nav_url( $key ),
870 );
871 }
872
873 foreach ( $groups as $option ) {
874 $admin_bar->add_menu( $option );
875 }
876 }
877
878 /**
879 * Enqueue assets where needed.
880 */
881 public function enqueue_assets() {
882
883 $page = filter_input( INPUT_GET, 'page', FILTER_SANITIZE_STRING );
884 if ( $page && self::$slug === $page ) {
885 wp_enqueue_script( self::$slug );
886 wp_enqueue_style( self::$slug );
887
888 $this->prep_config();
889 }
890 }
891
892 /**
893 * Prepare the config data for output to the admin UI.
894 */
895 protected function prep_config() {
896
897 $data = $this->build_config_object();
898
899 // Add config data.
900 wp_add_inline_script( self::$slug, 'var plgData = ' . $data, 'before' );
901 }
902
903 /**
904 * Build the json config object.
905 *
906 * @param int|null $site_id The site to get config for, ir null for current.
907 *
908 * @return string
909 */
910 protected function build_config_object( $site_id = null ) {
911
912 if ( null === $site_id ) {
913 $data = $this->config;
914 } else {
915 $data = $this->load_config( $site_id );
916 }
917 // Prep config data.
918 $data['saveURL'] = rest_url( self::$slug . '/save' );
919 $data['legacyURL'] = add_query_arg( 'reactivate-legacy', true, $this->get_nav_url( 'dashboard' ) );
920 $data['restNonce'] = wp_create_nonce( 'wp_rest' );
921 // Multisite.
922 if ( $this->network_active() && ( is_network_admin() || defined( 'REST_REQUEST' ) && true === REST_REQUEST ) ) {
923 $data['loadURL'] = rest_url( self::$slug . '/load' );
924 $data['sites'] = get_sites();
925 $data['mainSite'] = get_main_site_id();
926 if ( ! in_array( $data['mainSite'], $data['sitesEnabled'], true ) ) {
927 $data['sitesEnabled'][] = get_main_site_id();
928 }
929 }
930
931 // Add plugins.
932 $data['plugins'] = get_plugins();
933
934 // Remove presets from groups for admin.
935 $data['groups'] = array_diff_key( $data['groups'], $data['preset_groups'] );
936
937 return wp_json_encode( $data );
938 }
939
940 /**
941 * Get the default config.
942 *
943 * @return array
944 */
945 protected function get_default_config() {
946
947 return array(
948 'groups' => array(),
949 'selectedPresets' => array(),
950 'params' => array(
951 'legacyGrouping' => false,
952 'navStyle' => 'subsubsub',
953 'menuGroups' => false,
954 ),
955
956 'sitesEnabled' => array(), // Used for multisite.
957 );
958 }
959
960 /**
961 * Load the UI config.
962 *
963 * @param int|null $site_id The site ID to load. Null for current site.
964 *
965 * @return array;
966 */
967 protected function load_config( $site_id = null ) {
968
969 // Load the config.
970 if ( is_multisite() ) {
971 if ( ! $site_id ) {
972 $site_id = get_current_blog_id();
973 }
974 $config = get_network_option( $site_id, self::CONFIG_KEY, $this->get_default_config() );
975 $config['siteID'] = (int) $site_id;
976 } else {
977 $config = get_option( self::CONFIG_KEY, $this->get_default_config() );
978 }
979 $config['pluginName'] = $this->plugin_name;
980 $config['version'] = $this->version;
981 $config['slug'] = self::$slug;
982
983 // Load the presets.
984 $config += $this->load_presets();
985
986 return $config;
987 }
988
989 /**
990 * Set the config.
991 *
992 * @param int|null $site_id The site ID to load. Null for current site.
993 */
994 protected function set_config( $site_id = null ) {
995
996 $this->config = $this->load_config( $site_id );
997 // Populate groups with plugins.
998 array_map( array( $this, 'populate_plugins' ), $this->config['groups'] );
999 // register selected presets.
1000
1001 if ( ! empty( $this->config['selectedPresets'] ) ) {
1002 array_map( array( $this, 'register_preset' ), $this->config['selectedPresets'] );
1003 }
1004 }
1005
1006 /**
1007 * Register a preset.
1008 *
1009 * @param string $preset The preset name to register.
1010 */
1011 protected function register_preset( $preset ) {
1012
1013 $key = sanitize_title( $preset );
1014 if ( isset( $this->config['preset_groups'][ $key ] ) ) {
1015 $this->config['groups'][ $key ] = $this->config['preset_groups'][ $key ];
1016 }
1017 }
1018
1019 /**
1020 * Populate a group with selected plugins.
1021 *
1022 * @param array $group The group array.
1023 */
1024 protected function populate_plugins( $group ) {
1025
1026 static $plugins;
1027 if ( ! $plugins ) {
1028 $plugins = get_plugins();
1029 }
1030 foreach ( $group['plugins'] as $plugin ) {
1031 if ( isset( $plugins[ $plugin ] ) ) {
1032 $this->groups[ $group['id'] ][ $plugin ] = $plugins[ $plugin ];
1033 }
1034 }
1035 // Populate keywords now to keep ordering.
1036 $this->populate_keywords( $group['id'] );
1037 }
1038
1039 /**
1040 * Populate a group from keywords.
1041 *
1042 * @param string $id The group ID.
1043 */
1044 protected function populate_keywords( $id ) {
1045
1046 if ( ! isset( $this->config['groups'][ $id ] ) || empty( $this->config['groups'][ $id ]['keywords'] ) ) {
1047 return;
1048 }
1049 $keywords = array_map( 'strtolower', $this->config['groups'][ $id ]['keywords'] );
1050 $plugins = get_plugins();
1051 foreach ( $plugins as $plugin_key => $plugin_data ) {
1052 if ( isset( $this->groups[ $id ][ $plugin_key ] ) ) {
1053 continue;
1054 }
1055 $plugin_string = strtolower( implode( ' ', $plugin_data ) );
1056 $matched = array_filter(
1057 $keywords,
1058 function( $keyword ) use ( $plugin_string ) {
1059
1060 return false !== strpos( $plugin_string, $keyword );
1061 }
1062 );
1063 if ( ! empty( $matched ) ) {
1064 $this->groups[ $id ][ $plugin_key ] = $plugin_data;
1065 }
1066 }
1067 }
1068
1069 /**
1070 * Create a new Group.
1071 *
1072 * @param string $name The group name to create.
1073 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1074 *
1075 * @return string|bool
1076 */
1077 public function create_group( $name, array $plugin_slugs = array() ) {
1078
1079 $success = false;
1080 $new_id = Utils::generate_id();
1081 $group = array(
1082 'id' => $new_id,
1083 'keywords' => array(),
1084 'name' => trim( $name ),
1085 'open' => false,
1086 'plugins' => $plugin_slugs,
1087 );
1088 $this->config['groups'][ $new_id ] = $group;
1089 if ( $this->save_config() ) {
1090 $success = $new_id;
1091 }
1092
1093 return $success;
1094 }
1095
1096 /**
1097 * Add plugins to a group.
1098 *
1099 * @param string $group_id The group ID to add plugin to.
1100 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1101 *
1102 * @return bool
1103 */
1104 public function add_to_group( $group_id, array $plugin_slugs ) {
1105
1106 $success = false;
1107 if ( isset( $this->config['groups'][ $group_id ] ) ) {
1108 $new_plugins = array_merge( $this->config['groups'][ $group_id ]['plugins'], $plugin_slugs );
1109 $this->config['groups'][ $group_id ]['plugins'] = array_unique( $new_plugins );
1110 $success = $this->save_config();
1111 }
1112
1113 return $success;
1114 }
1115
1116 /**
1117 * Remove Plugins from a group.
1118 *
1119 * @param string $group_id The group ID to add plugin to.
1120 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1121 *
1122 * @return bool
1123 */
1124 public function remove_from_group( $group_id, array $plugin_slugs ) {
1125
1126 $success = false;
1127 if ( isset( $this->config['groups'][ $group_id ] ) ) {
1128 $this->config['groups'][ $group_id ]['plugins'] = array_diff( $this->config['groups'][ $group_id ]['plugins'], $plugin_slugs );
1129 $success = $this->save_config();
1130 }
1131
1132 return $success;
1133 }
1134
1135 /**
1136 * Render the admin page.
1137 */
1138 public function render_admin() {
1139
1140 include PLGGRP_PATH . 'includes/main.php';
1141 }
1142
1143 /**
1144 * Get the instance of the class.
1145 *
1146 * @return Plugin_Groups
1147 */
1148 public static function get_instance() {
1149
1150 if ( is_null( self::$instance ) ) {
1151 self::$instance = new self();
1152 }
1153
1154 return self::$instance;
1155 }
1156 }
1157