PluginProbe
Plugin Groups / trunk
Plugin Groups vtrunk
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 trunk, at classes/class-plugin-groups.php

1,485 lines 37.8 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 use WP_Admin_Bar;
11
12 /**
13 * Plugin_Groups Class.
14 */
15 class Plugin_Groups {
16
17 /**
18 * The single instance of the class.
19 *
20 * @var groups\classes\Plugin_Groups
21 */
22 protected static $instance = null;
23
24 /**
25 * Holds the version of the plugin.
26 *
27 * @var string
28 */
29 protected $version;
30
31 /**
32 * Holds the plugin name.
33 *
34 * @var string
35 */
36 protected $plugin_name;
37
38 /**
39 * Holds the plugin config.
40 *
41 * @var array
42 */
43 protected $config = [];
44
45 /**
46 * Holds the Groups.
47 *
48 * @var array
49 */
50 protected $groups = [];
51
52 /**
53 * Holds the menu slug.
54 *
55 * @var string
56 */
57 public static $slug = 'plugin-groups';
58
59 /**
60 * Holds the current group.
61 *
62 * @var string
63 */
64 protected $current_group;
65
66 /**
67 * Holds the current status.
68 *
69 * @var string
70 */
71 protected $current_status;
72
73 /**
74 * Holds a list of missing plugins.
75 *
76 * @var array
77 */
78 protected $missing = [];
79
80 /**
81 * Holds the current group and status path.
82 *
83 * @var string
84 */
85 protected $current_nav_path;
86
87 /**
88 * Development mode flag.
89 *
90 * @since 3.0.0
91 * @var bool|string
92 */
93 private bool|string $dev_mode = false;
94
95 /**
96 * Hold the record of the plugins current version for upgrade.
97 *
98 * @var string
99 */
100 const VERSION_KEY = '_plugin_groups_version';
101
102 /**
103 * Hold the config storage key.
104 *
105 * @var string
106 */
107 const CONFIG_KEY = '_plugin_groups_config';
108
109 /**
110 * Initiate the plugin_groups object.
111 */
112 public function __construct() {
113
114 require_once ABSPATH . 'wp-admin/includes/plugin.php';
115 $plugin = get_plugin_data( PLGGRP_CORE );
116 $this->plugin_name = $plugin['Name'];
117 $this->version = $plugin['Version'];
118
119 spl_autoload_register( [ $this, 'autoload_class' ], true, false );
120
121 $this->dev_mode = defined( 'PLGGRP_DEV_MODE' ) ? PLGGRP_DEV_MODE : false;
122
123 // Start hooks.
124 $this->setup_hooks();
125
126 // Init the bulk actions.
127 new Bulk_Actions( $this );
128 new Extras( $this );
129 new Rest( $this );
130 }
131
132 /**
133 * Setup and register WordPress hooks.
134 */
135 protected function setup_hooks() {
136
137 // Load plugin text domain
138 add_action( 'init', [ $this, 'plugin_groups_init' ], PHP_INT_MAX ); // Always the last thing to init.
139 add_action( 'admin_init', [ $this, 'admin_init' ] );
140 add_action( 'admin_menu', [ $this, 'admin_menu' ] );
141 add_action( 'network_admin_menu', [ $this, 'admin_menu' ] );
142 add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
143 add_filter( 'views_plugins', [ $this, 'add_groups' ], PHP_INT_MAX );
144 add_filter( 'views_plugins-network', [ $this, 'add_groups' ], PHP_INT_MAX );
145 add_filter( 'all_plugins', [ $this, 'catch_selected_group' ] );
146 add_filter( 'show_advanced_plugins', [ $this, 'filter_shown_status' ], 10, 2 );
147 add_filter( 'site_transient_update_plugins', [ $this, 'alter_update_plugins' ] );
148 add_action( 'pre_current_active_plugins', [ $this, 'render_group_navigation' ] );
149 add_filter( 'bulk_actions-plugins', [ $this, 'bulk_actions' ] );
150 add_action( 'admin_bar_menu', [ $this, 'admin_bar_item' ], 100 );
151 add_filter( 'self_admin_url', [ $this, 'append_group_to_self' ], 10, 3 );
152 add_filter( 'plugin_action_links', [ $this, 'append_group_to_actions' ] );
153 add_action( 'activated_plugin', [ $this, 'auto_assign_by_keywords' ], 10, 0 );
154 add_action( 'upgrader_process_complete', [ $this, 'after_plugin_upgrade' ], 10, 2 );
155 }
156
157 /**
158 * Append the current group id to plugin action links to maintain selection on activation and deactivation of plugins.
159 *
160 * @param array $actions Array of action links.
161 *
162 * @return array
163 */
164 public function append_group_to_actions( $actions ) {
165
166 if ( isset( $this->current_group ) ) {
167 foreach ( $actions as &$tag ) {
168 $parts = shortcode_parse_atts( $tag );
169 if ( isset( $parts['href'] ) ) {
170 $url = html_entity_decode( $parts['href'] );
171 $url = add_query_arg( self::$slug, $this->current_group, $url );
172
173 $tag = str_replace( $parts['href'], htmlentities( $url ), $tag );
174 }
175 }
176 }
177
178 return $actions;
179 }
180
181 /**
182 * Append the group to redirect URLS after activation and deactivation of plugins.
183 *
184 * @param string $url The url to append to.
185 * @param string $path The path location.
186 *
187 * @return string
188 */
189 public function append_group_to_self( $url, $path ) {
190
191 if ( 'plugins.php' === wp_parse_url( $path, PHP_URL_PATH ) ) {
192 if ( ! isset( $this->current_group ) ) {
193 // Init the current group if not set yet.
194 $this->catch_selected_group();
195 }
196 // If we found a group, then append it to the self URL on the plugins page to maintain groups in nav.
197 if ( isset( $this->current_group ) ) {
198 $url = add_query_arg( self::$slug, $this->current_group, $url );
199 }
200 }
201
202 return $url;
203 }
204
205 /**
206 * Remove plugins from the update available.
207 *
208 * @param object $data The data object.
209 *
210 * @return object
211 */
212 public function alter_update_plugins( $data ) {
213
214 if ( $this->current_group ) {
215 $keys = array_keys( $this->groups[ $this->current_group ] );
216 foreach ( $data->response as $key => $plugin ) {
217 if ( ! in_array( $key, $keys, true ) ) {
218 unset( $data->response[ $key ] );
219 }
220 }
221 }
222
223 return $data;
224 }
225
226 /**
227 * Remove status that are not relevant.
228 *
229 * @param bool $show Flag to show.
230 * @param string $status The current status
231 *
232 * @return bool
233 */
234 public function filter_shown_status( $show, $status ) {
235
236 global $plugins;
237
238 static $removes = [
239 'mustuse',
240 'dropins',
241 ];
242 if ( $this->current_group && in_array( $status, $removes, true ) ) {
243 $show = false;
244 }
245 if ( true === $this->config['params']['legacyGrouping'] ) {
246 $plugins += $this->groups;
247 }
248
249 return $show;
250 }
251
252 /**
253 * Render the Group navigation.
254 */
255 public function render_group_navigation() {
256
257 // Use new group system.
258 if ( true !== $this->config['params']['legacyGrouping'] && 'groups-dropdown' !== $this->config['params']['navStyle'] ) {
259 $parts = [];
260 $parts[] = $this->make_all_tag();
261 foreach ( $this->groups as $key => $plugins ) {
262 $parts[] = $this->make_group_tag( $key );
263 }
264
265 $groups = implode( "", $parts );
266 $group_set = Utils::build_tag( 'ul', [ 'class' => [ $this->config['params']['navStyle'] ] ], $groups );
267 $html = Utils::build_tag( 'div', [ 'class' => self::$slug ], $group_set );
268 if ( 1 < count( $parts ) ) {
269 echo wp_kses( $html, wp_kses_allowed_html( 'post' ) );
270 $this->render_group_bulk_actions();
271 }
272 }
273 }
274
275 /**
276 * Add dropdown navigation on bulk actions.
277 *
278 * @param array $actions Unchanged actions.
279 *
280 * @return array
281 */
282 public function bulk_actions( $actions ) {
283
284 if ( true !== $this->config['params']['legacyGrouping'] && 'groups-dropdown' === $this->config['params']['navStyle'] ) {
285 $this->dropdown_navigation();
286 }
287
288 return $actions;
289 }
290
291 /**
292 * Render a dropdown navigation.
293 *
294 * @param bool $echo Optional flag to echo the field or return the string.
295 *
296 * @return void|string
297 */
298 public function dropdown_navigation( $echo = true ) {
299
300 $html = [];
301 $html[] = '<label for="bulk-action-selector-groups" class="screen-reader-text">' . __( 'All groups', self::$slug ) . '</label>';
302 $html[] = '<select id="bulk-action-selector-groups" onChange="window.location = this.value">';
303 $html[] = '<option value="' . esc_url( $this->get_nav_url() ) . '" ' . ( ! empty( $this->current_group ) ? 'selected="selected"' : '' ) . '>' . __( 'All groups', self::$slug ) . '</option>';
304
305 foreach ( $this->groups as $key => $plugins ) {
306 $group = $this->config['groups'][ $key ];
307 $selected = '';
308 if ( $this->current_group === $key ) {
309 $selected = ' selected="selected"';
310 }
311
312 $html[] = "\t" . '<option value="' . esc_url( $this->get_nav_url( $key ) ) . '"' . $selected . '>' . esc_html( $group['name'] ) . ' (' . count( $plugins ) . ')</option>' . "\n";
313 }
314
315 $html[] = "</select>\n";
316 $html = implode( $html );
317 if ( false === $echo ) {
318 return $html;
319 }
320 echo wp_kses(
321 $html,
322 [
323 'label' => [
324 'for' => true,
325 'class' => true,
326 ],
327 'select' => [
328 'id' => true,
329 'onchange' => true,
330 ],
331 'option' => [
332 'value' => true,
333 'selected' => true,
334 ],
335 ]
336 );
337 $this->render_group_bulk_actions();
338 }
339
340 /**
341 * Render bulk activate/deactivate/update controls for the currently selected group.
342 */
343 protected function render_group_bulk_actions() {
344
345 if ( empty( $this->config['params']['groupBulkActions'] ) || true === $this->config['params']['legacyGrouping'] || empty( $this->current_group ) || empty( $this->groups[ $this->current_group ] ) ) {
346 return;
347 }
348
349 $plugin_files = array_keys( $this->groups[ $this->current_group ] );
350 $controls = [];
351 $button_class = $this->config['params']['navStyle'] === 'groups-dropdown' ? 'action' : 'button-small';
352
353 if ( current_user_can( 'activate_plugins' ) ) {
354 $inactive = array_filter(
355 $plugin_files,
356 function ( $plugin ) {
357
358 return ! is_plugin_active( $plugin );
359 }
360 );
361 if ( ! empty( $inactive ) ) {
362 $controls[] = $this->build_bulk_action_form( 'activate-selected', $inactive, __( 'Activate All', self::$slug ) );
363 }
364 }
365
366 if ( current_user_can( 'deactivate_plugins' ) ) {
367 $active = array_filter( $plugin_files, 'is_plugin_active' );
368 if ( ! empty( $active ) ) {
369 $controls[] = $this->build_bulk_action_form( 'deactivate-selected', $active, __( 'Deactivate All', self::$slug ) );
370 }
371 }
372
373 if ( current_user_can( 'update_plugins' ) ) {
374 $updates = get_site_transient( 'update_plugins' );
375 $updatable = ! empty( $updates->response ) ? array_intersect( $plugin_files, array_keys( $updates->response ) ) : [];
376 if ( ! empty( $updatable ) ) {
377 $url = wp_nonce_url(
378 self_admin_url( 'update.php?action=update-selected&plugins=' . rawurlencode( implode( ',', $updatable ) ) ),
379 'bulk-update-plugins'
380 );
381
382 $controls[] = Utils::build_tag(
383 'a',
384 [
385 'href' => $url,
386 'class' => 'button button-secondary ' . $button_class,
387 ],
388 esc_html__( 'Update All', self::$slug )
389 );
390 }
391 }
392
393 if ( empty( $controls ) ) {
394 return;
395 }
396
397 echo wp_kses(
398 Utils::build_tag( 'div', [ 'class' => 'group-bulk-actions' ], implode( ' ', $controls ) ),
399 array_merge(
400 wp_kses_allowed_html( 'post' ),
401 [
402 'form' => [
403 'method' => true,
404 'action' => true,
405 'style' => true,
406 ],
407 'input' => [
408 'type' => true,
409 'name' => true,
410 'value' => true,
411 ],
412 'button' => [
413 'type' => true,
414 'class' => true,
415 ],
416 ]
417 )
418 );
419 }
420
421 /**
422 * Build a small inline POST form for a plugins.php bulk action (activate/deactivate-selected).
423 *
424 * @param string $action The plugins.php bulk action slug.
425 * @param array $plugin_files The plugin files to act on.
426 * @param string $label The button label.
427 *
428 * @return string
429 */
430 protected function build_bulk_action_form( $action, array $plugin_files, $label ) {
431
432 $inputs = '';
433 $button_class = $this->config['params']['navStyle'] === 'groups-dropdown' ? 'action' : 'button-small';
434 foreach ( $plugin_files as $plugin_file ) {
435 $inputs .= Utils::build_tag(
436 'input',
437 [
438 'type' => 'hidden',
439 'name' => 'checked[]',
440 'value' => $plugin_file,
441 ]
442 );
443 }
444 $inputs .= wp_nonce_field( 'bulk-plugins', '_wpnonce', true, false );
445 $inputs .= Utils::build_tag(
446 'input',
447 [
448 'type' => 'hidden',
449 'name' => 'action',
450 'value' => $action,
451 ]
452 );
453 $inputs .= Utils::build_tag( 'button', [
454 'type' => 'submit',
455 'class' => 'button button-secondary ' . $button_class,
456 ], esc_html( $label ) );
457
458 return Utils::build_tag(
459 'form',
460 [
461 'method' => 'post',
462 'action' => self_admin_url( 'plugins.php' ),
463 'style' => 'display:inline-block;',
464 ],
465 $inputs
466 );
467 }
468
469 /**
470 * Catch the selected group.
471 *
472 * @param array $plugins List of plugins.
473 *
474 * @return array
475 */
476 public function catch_selected_group( $plugins = [] ) {
477
478 global $status;
479
480 $this->current_status = $status;
481 $selected_group = Utils::get_sanitized_text( INPUT_GET, self::$slug );
482 if ( $selected_group && isset( $this->groups[ $selected_group ] ) ) {
483 $this->current_group = $selected_group;
484 if ( ! empty( $plugins ) ) {
485 $plugins = $this->groups[ $selected_group ];
486
487 // Add selection path.
488 $this->current_nav_path .= ' | ' . $this->config['groups'][ $selected_group ]['name'];
489 }
490 }
491
492 // Add our styles if we have groups;
493 if ( ! empty( $this->groups ) ) {
494 wp_enqueue_style( self::$slug . '-navbar' );
495 }
496
497 return $plugins;
498 }
499
500 /**
501 * Get a url link for group navigation.
502 *
503 * @param null|string $id The group ID or null for all.
504 *
505 * @return string
506 */
507 protected function get_nav_url( $id = null ) {
508
509 $url = Utils::get_sanitized_text( INPUT_SERVER, 'REQUEST_URI' );
510 if ( ! $url || false === strpos( $url, 'plugins.php' ) ) {
511 // Just in case.
512 $url = self_admin_url( 'plugins.php' );
513 }
514 if ( null === $id ) {
515 // Null id is for the 'All groups'.
516 return remove_query_arg( self::$slug, $url );
517 }
518
519 // If no plugins get a link back to admin.
520 if ( empty( $this->groups[ $id ] ) ) {
521 return add_query_arg( 'page', self::$slug, $url );
522 }
523
524 return add_query_arg(
525 [
526 'plugin_status' => $this->current_status,
527 self::$slug => $id,
528
529 ],
530 $url
531 );
532 }
533
534 /**
535 * Get the current group.
536 *
537 * @return array|null
538 */
539 public function get_current_group() {
540
541 if ( ! isset( $this->current_group ) ) {
542 $this->catch_selected_group();
543 }
544
545 return $this->current_group ? $this->config['groups'][ $this->current_group ] : null;
546 }
547
548 /**
549 * Get the groups.
550 *
551 * @return array
552 */
553 public function get_groups() {
554
555 return array_values( $this->config['groups'] );
556 }
557
558 /**
559 * Make a group tag.
560 *
561 * @param string $id The Group ID.
562 *
563 * @return string
564 */
565 protected function make_group_tag( $id ) {
566
567 $group = $this->config['groups'][ $id ];
568 $total = count( $this->groups[ $id ] );
569 $counter = '';
570
571 if ( ! empty( $total ) ) {
572
573 $counter = Utils::build_tag( 'span', [ 'class' => 'count' ], " ({$total})" );
574 }
575 $li_atts = [
576 'class' => [
577 'group-link',
578 $group['id'],
579 ],
580 ];
581 $link_atts = [
582 'href' => $this->get_nav_url( $id ),
583 ];
584 if ( $group['id'] === $this->current_group ) {
585 $li_atts['class'][] = 'current';
586 $link_atts['class'] = 'current';
587 $link_atts['aria-current'] = 'page';
588 }
589
590 $color_dot = '';
591 if ( ! empty( $group['color'] ) ) {
592 $color_dot = Utils::build_tag(
593 'span',
594 [
595 'class' => 'group-color-dot',
596 'style' => 'background-color: ' . $group['color'],
597 ],
598 ''
599 );
600 }
601
602 $link = Utils::build_tag( 'a', $link_atts, $color_dot . esc_html( $group['name'] ) . $counter );
603
604 return Utils::build_tag( 'li', $li_atts, $link );
605 }
606
607 /**
608 * Load presets into groups for built-in and filtered presets.
609 *
610 * @return array
611 */
612 protected function load_presets() {
613
614 $groups = [
615 'WooCommerce' => [ 'WooCommerce' ],
616 'Easy Digital Downloads' => [ 'Easy Digital Downloads' ],
617 'Ninja Forms' => [ 'Ninja Forms' ],
618 'Gravity Forms' => [ 'Gravity Forms' ],
619 'WPForms' => [ 'WPForms' ],
620 'E-Commerce' => [
621 'WooCommerce',
622 'Easy Digital Downloads',
623 ],
624 'Forms' => [
625 'Ninja Forms',
626 'Gravity Forms',
627 'WPForms',
628 'Formidable Forms',
629 'Contact Form 7',
630 ],
631 'SEO' => [
632 'All in One SEO',
633 'Yoast SEO',
634 ],
635 'Security' => [
636 'Wordfence',
637 'Sucuri',
638 'iThemes Security',
639 ],
640 'Caching' => [
641 'WP Rocket',
642 'W3 Total Cache',
643 'WP Super Cache',
644 'WP Fastest Cache',
645 ],
646 'Backups' => [
647 'UpdraftPlus',
648 'BackWPup',
649 'Duplicator',
650 ],
651 'Page Builders' => [
652 'Elementor',
653 'Beaver Builder',
654 'Divi Builder',
655 ],
656 'Email/SMTP' => [
657 'WP Mail SMTP',
658 'FluentSMTP',
659 'Post SMTP',
660 ],
661 ];
662
663 /**
664 * Filter the presets (legacy)
665 *
666 * @deprecated 2.0.0
667 */
668 $groups = apply_filters( 'plugin-groups-get-presets', $groups );
669
670 /**
671 * Filter preset plugin groups.
672 *
673 * @hook get_preset_plugin_groups
674 *
675 * @param $groups {array} The preset groups.
676 *
677 * @return array
678 * @since 2.0.0
679 *
680 */
681 $presets = apply_filters( 'get_preset_plugin_groups', $groups );
682 $preset_groups = [];
683 foreach ( $presets as $name => $keywords ) {
684 $id = sanitize_title( $name );
685 $preset_groups[ $id ] = [
686 'id' => $id,
687 'name' => $name,
688 'plugins' => [],
689 'keywords' => $keywords,
690 ];
691 }
692
693 return [
694 'preset_groups' => $preset_groups,
695 'presets' => array_keys( $groups ),
696 ];
697 }
698
699 /**
700 * Make all link tag.
701 *
702 * @return string
703 */
704 protected function make_all_tag() {
705
706 $link_atts = [
707 'href' => $this->get_nav_url(),
708 ];
709 if ( empty( $this->current_group ) ) {
710 $link_atts['class'] = 'current';
711 $link_atts['aria-current'] = 'page';
712 }
713 $link = Utils::build_tag( 'a', $link_atts, __( 'All Groups', self::$slug ) );
714
715 return Utils::build_tag( 'li', [ 'class' => [ 'group-link', '__allgroups' ] ], $link );
716 }
717
718 /**
719 * Add new filter view
720 *
721 * @param array $views The list of nav tags for plugin statuses.
722 *
723 * @return array
724 */
725 public function add_groups( $views ) {
726
727 foreach ( $views as &$tag ) {
728 if ( preg_match( '/<a([^>]*?)>{1}/', $tag, $found ) ) {
729 $atts = Utils::get_tag_attributes( $found[1] );
730 $url = add_query_arg( self::$slug, $this->current_group, $atts['href'] );
731 $tag = str_replace( $atts['href'], $url, $tag );
732 wp_parse_str( wp_parse_url( $atts['href'], PHP_URL_QUERY ), $query );
733 if ( isset( $query['plugin_status'] ) && $query['plugin_status'] === $this->current_status ) {
734 $names = explode( ' ', wp_kses( $tag, [] ) );
735 array_pop( $names );
736 $this->current_nav_path .= ' | ' . implode( ' ', $names );
737 }
738 }
739 }
740
741 // Legacy.
742 if ( true === $this->config['params']['legacyGrouping'] ) {
743 foreach ( $this->groups as $key => $plugins ) {
744 $views[ $key ] = $this->make_group_tag( $key );
745 }
746 }
747
748 // @todo: Make method.
749 if ( ! empty( $this->current_nav_path ) ) {
750 $append = [
751 'name' => $this->current_nav_path,
752 ];
753 wp_add_inline_script(
754 'wp-util',
755 'var appendHead = ' . wp_json_encode(
756 $append
757 ) . '; var pluginsHead = document.getElementsByClassName(\'wp-heading-inline\' );if( pluginsHead.length ) {pluginsHead[0].innerText += appendHead.name}'
758 );
759 }
760
761 return $views;
762 }
763
764 /**
765 * Save the current config.
766 *
767 * @param null|int $site_id The site ID to save for.
768 *
769 * @return bool
770 */
771 public function save_config( $site_id = null ) {
772
773 if ( is_multisite() ) {
774 if ( null === $site_id ) {
775 $site_id = get_current_blog_id();
776 }
777 $success = update_blog_option( $site_id, self::CONFIG_KEY, $this->config );
778 } else {
779 $success = update_option( self::CONFIG_KEY, $this->config );
780 }
781
782 return $success;
783 }
784
785 /**
786 * Save the multisite access list on the main site config.
787 *
788 * @param array $site_ids Site IDs allowed to manage their own groups.
789 *
790 * @return bool
791 */
792 public function save_sites_enabled( array $site_ids ) {
793
794 $config = is_multisite() ? $this->get_stored_config( get_main_site_id() ) : get_option( self::CONFIG_KEY, $this->get_default_config() );
795 $config['sitesEnabled'] = array_values( array_map( 'intval', $site_ids ) );
796
797 if ( is_multisite() ) {
798 return update_blog_option( get_main_site_id(), self::CONFIG_KEY, $config );
799 }
800
801 return update_option( self::CONFIG_KEY, $config );
802 }
803
804 /**
805 * Autoloader by Locating and finding classes via folder structure.
806 *
807 * @param string $class class name to be checked and autoloaded.
808 */
809
810 function autoload_class( $class ) {
811
812 $class_location = self::locate_class_file( $class );
813 if ( $class_location ) {
814 include_once $class_location;
815 }
816 }
817
818 /**
819 * Locates the path to a requested class name.
820 *
821 * @param string $class The class name to locate.
822 *
823 * @return string|null
824 */
825 static public function locate_class_file( $class ) {
826
827 $return = null;
828 $parts = explode( '\\', strtolower( str_replace( '_', '-', $class ) ) );
829 $core = array_shift( $parts );
830 $self = strtolower( str_replace( '_', '-', __CLASS__ ) );
831 if ( $core === self::$slug ) {
832 $name = 'class-' . strtolower( array_pop( $parts ) ) . '.php';
833 $parts[] = $name;
834 $path = PLGGRP_PATH . 'classes/' . implode( '/', $parts );
835 if ( file_exists( $path ) ) {
836 $return = $path;
837 }
838 }
839
840 return $return;
841 }
842
843 /**
844 * Get the plugin version
845 */
846 public function version() {
847
848 return $this->version;
849 }
850
851 /**
852 * Check plugin_groups version to allow 3rd party implementations to update or upgrade.
853 */
854 protected function check_version() {
855
856 $previous_version = get_option( self::VERSION_KEY, 0.0 );
857 $new_version = $this->version();
858 if ( version_compare( $previous_version, $new_version, '<' ) ) {
859 if ( version_compare( $previous_version, '2.0.0', '<' ) ) {
860 $data = get_option( 'plugin_groups_plugin_groups', [] );
861 if ( ! empty( $data ) ) {
862 $new_config = $this->convert_legacy_groups( $data );
863 update_option( self::CONFIG_KEY, $new_config );
864 }
865 }
866 // Allow for updating.
867 do_action( "_plugin_groups_version_upgrade", $previous_version, $new_version );
868 // Update version.
869 update_option( self::VERSION_KEY, $new_version, true );
870 }
871 }
872
873 /**
874 * Convert legacy configs.
875 *
876 * @param array $data Array of previous version config.
877 *
878 * @return array
879 */
880 protected function convert_legacy_groups( $data ) {
881
882 $groups = [];
883 foreach ( $data['group'] as $group ) {
884 $keywords = explode( "\n", $group['config']['keywords'] );
885 $new_group = [
886 'id' => $group['_id'],
887 'name' => $group['config']['group_name'],
888 'plugins' => isset( $group['config']['plugins'] ) ? $group['config']['plugins'] : [],
889 'keywords' => array_filter( $keywords ),
890 ];
891 $groups[ $group['_id'] ] = $new_group;
892 }
893
894 // Set up the new config.
895 $config = $this->get_default_config();
896 $config['groups'] = $groups;
897 $config['selectedPresets'] = isset( $data['presets'] ) ? $data['presets'] : [];
898 $config['params']['legacyGrouping'] = true;
899 $config['params']['navStyle'] = 'subsubsub';
900
901 return $config;
902 }
903
904 /**
905 * Initialise plugin_groups.
906 */
907 public function plugin_groups_init() {
908
909 // Check version.
910 $this->check_version();
911
912 // Load config.
913 $config = $this->load_config();
914 $this->set_config( $config );
915
916 /**
917 * Init the settings system
918 *
919 * @param groups\classes\Plugin_Groups ${slug} The core object.
920 */
921 do_action( 'plugin_groups_init' );
922 }
923
924 /**
925 * Hook into admin_init.
926 */
927 public function admin_init() {
928
929 $manifest_path = PLGGRP_PATH . 'build/manifest.json';
930 $navbar_manifest_path = PLGGRP_PATH . 'static/manifest.json';
931 if ( ! file_exists( $manifest_path ) || ! file_exists( $navbar_manifest_path ) ) {
932 wp_die(
933 __( 'The Plugin Groups build is missing. Please run the build process.', 'plugin-groups' )
934 );
935 }
936 $manifest = json_decode( file_get_contents( $manifest_path ), true );
937 $navbar_manifest = json_decode( file_get_contents( $navbar_manifest_path ), true );
938 if ( ! isset( $manifest['src/main.tsx'] ) || ! isset( $navbar_manifest['src/extras.js'] ) ) {
939 wp_die(
940 __( 'The Plugin Groups build is invalid. Please run the build process again.', 'plugin-groups' )
941 );
942 }
943 $js_path = PLGGRP_URL . 'build/' . $manifest['src/main.tsx']['file'];
944 wp_register_script( self::$slug, $js_path, [], PLGGRP_VERSION, [ 'in_footer' => true ] );
945
946 if ( ! empty( $manifest['src/main.tsx']['css'] ) ) {
947 $css_path = PLGGRP_URL . 'build/' . $manifest['src/main.tsx']['css'][0] ?? '';
948 wp_register_style( self::$slug, $css_path, [], PLGGRP_VERSION );
949 }
950 if ( ! empty( $navbar_manifest['src/extras.js']['css'] ) ) {
951 $css_path = PLGGRP_URL . 'static/' . $navbar_manifest['src/extras.js']['css'][0] ?? '';
952 wp_register_style( self::$slug . '-navbar', $css_path, [], PLGGRP_VERSION );
953 }
954 }
955
956 /**
957 * Hook into the admin_menu.
958 */
959 public function admin_menu() {
960
961 if ( ! $this->network_active() || $this->site_enabled() || is_network_admin() ) {
962 add_submenu_page( 'plugins.php', __( 'Plugin Groups', self::$slug ), __( 'Plugin Groups', self::$slug ), 'manage_options', 'plugin-groups', [
963 $this,
964 'render_admin',
965 ], 50 );
966 }
967 }
968
969 /**
970 * Check if the plugin is network activated.
971 *
972 * @return bool
973 */
974 protected function network_active() {
975
976 return is_plugin_active_for_network( PLGGRP_SLUG );
977 }
978
979 /**
980 * Check to see if the site is allowed to use this.
981 *
982 * @return bool
983 */
984 protected function site_enabled() {
985
986 return $this->can_manage_site_config( get_current_blog_id() );
987 }
988
989 /**
990 * Check whether the current user can manage Plugin Groups config for a site.
991 *
992 * @param int|null $site_id Site ID to check. Null uses current site.
993 *
994 * @return bool
995 */
996 public function can_manage_site_config( $site_id = null ) {
997
998 if ( ! is_multisite() ) {
999 return current_user_can( 'manage_options' );
1000 }
1001
1002 if ( null === $site_id ) {
1003 $site_id = get_current_blog_id();
1004 }
1005
1006 $site_id = (int) $site_id;
1007 if ( current_user_can( 'manage_network_options' ) ) {
1008 return true;
1009 }
1010
1011 $main_config = $this->get_stored_config( get_main_site_id() );
1012
1013 return current_user_can_for_site( $site_id, 'manage_options' ) && in_array( $site_id, $main_config['sitesEnabled'], true );
1014 }
1015
1016 /**
1017 * Add Groups to the admin bar.
1018 *
1019 * @param WP_Admin_Bar $admin_bar
1020 */
1021 public function admin_bar_item( $admin_bar ) {
1022
1023 if ( ! $this->config['params']['menuGroups'] || ! current_user_can( 'activate_plugins' ) ) {
1024 return;
1025 }
1026
1027 $groups = [
1028 'parent' => [
1029 'id' => self::$slug,
1030 'title' => $this->plugin_name,
1031 'href' => $this->get_nav_url( 'dashboard' ),
1032 'meta' => [
1033 'title' => $this->plugin_name,
1034 ],
1035 ],
1036 ];
1037
1038 foreach ( $this->groups as $key => $plugins ) {
1039 $group = $this->config['groups'][ $key ];
1040 $groups[ $key ] = [
1041 'id' => $key,
1042 'parent' => self::$slug,
1043 'title' => $group['name'] . ' (' . count( $plugins ) . ')',
1044 'href' => $this->get_nav_url( $key ),
1045 ];
1046 }
1047
1048 foreach ( $groups as $option ) {
1049 $admin_bar->add_menu( $option );
1050 }
1051 }
1052
1053 /**
1054 * Enqueue assets where needed.
1055 */
1056 public function enqueue_assets() {
1057
1058 $page = Utils::get_sanitized_text( INPUT_GET, 'page' );
1059 if ( $page && self::$slug === $page ) {
1060
1061 // In development mode, load from Vite dev server.
1062 if ( $this->dev_mode && file_exists( PLGGRP_PATH . '/dev/dev-server-asset.php' ) ) {
1063 require_once PLGGRP_PATH . '/dev/dev-server-asset.php';
1064 } else {
1065 wp_enqueue_script( self::$slug );
1066 wp_enqueue_style( self::$slug );
1067 wp_set_script_translations( self::$slug, self::$slug );
1068 }
1069 $this->prep_config();
1070 }
1071 }
1072
1073 /**
1074 * Prepare the config data for output to the admin UI.
1075 */
1076 protected function prep_config() {
1077
1078 $data = $this->build_config_object();
1079
1080 // Add config data.
1081 wp_add_inline_script( self::$slug, 'var plgData = ' . $data, 'before' );
1082 }
1083
1084 /**
1085 * Build the json config object.
1086 *
1087 * @param int|null $site_id The site to get config for, ir null for current.
1088 *
1089 * @return string|false
1090 */
1091 public function build_config_object( $site_id = null ) {
1092
1093 if ( null === $site_id ) {
1094 $data = $this->config;
1095 } else {
1096 $data = $this->load_config( $site_id );
1097 }
1098
1099 // Prep config data.
1100 $data['saveURL'] = rest_url( self::$slug . '/save' );
1101 $data['legacyURL'] = add_query_arg( 'reactivate-legacy', true, $this->get_nav_url( 'dashboard' ) );
1102 $data['restNonce'] = wp_create_nonce( 'wp_rest' );
1103 // Multisite.
1104 if ( $this->network_active() && ( is_network_admin() || defined( 'REST_REQUEST' ) && true === REST_REQUEST ) ) {
1105 $data['loadURL'] = rest_url( self::$slug . '/load' );
1106 $data['sites'] = get_sites();
1107 $data['mainSite'] = get_main_site_id();
1108 }
1109
1110 // Add plugins.
1111 $data['plugins'] = get_plugins();
1112
1113 // Remove presets from groups for admin.
1114 $data['groups'] = array_diff_key( $data['groups'], $data['preset_groups'] );
1115
1116 // Remove ungrouped.
1117 unset( $data['groups']['__ungrouped'] );
1118
1119 return wp_json_encode( $data );
1120 }
1121
1122 /**
1123 * Get the default config.
1124 *
1125 * @return array
1126 */
1127 protected function get_default_config() {
1128
1129 return [
1130 'groups' => [],
1131 'selectedPresets' => [],
1132 'params' => [
1133 'legacyGrouping' => false,
1134 'navStyle' => 'subsubsub',
1135 'menuGroups' => false,
1136 'groupBulkActions' => false,
1137 ],
1138
1139 'sitesEnabled' => [], // Used for multisite.
1140 ];
1141 }
1142
1143 /**
1144 * Load the UI config.
1145 *
1146 * @param int|null $site_id The site ID to load. Null for current site.
1147 *
1148 * @return array;
1149 */
1150 public function load_config( $site_id = null ) {
1151
1152 // Load the config.
1153 if ( is_multisite() ) {
1154 if ( ! $site_id ) {
1155 $site_id = get_current_blog_id();
1156 }
1157 $config = $this->get_stored_config( $site_id );
1158 $config['siteID'] = (int) $site_id;
1159 } else {
1160 $config = get_option( self::CONFIG_KEY, $this->get_default_config() );
1161 }
1162 $config['pluginName'] = $this->plugin_name;
1163 $config['version'] = $this->version;
1164 $config['slug'] = self::$slug;
1165
1166 // Flag if network admin vs main site.
1167 if ( is_network_admin() && is_main_site() ) {
1168 $config['networkAdmin'] = true;
1169 }
1170 $presets = $this->load_presets();
1171
1172 $config['presets'] = $presets['presets'];
1173 $config['preset_groups'] = $presets['preset_groups'];
1174
1175 return $config;
1176 }
1177
1178 /**
1179 * Get persisted config for a multisite blog.
1180 *
1181 * Falls back to the legacy network-option storage location used by earlier
1182 * builds before saving back to the blog's own options table.
1183 *
1184 * @param int $site_id Site ID to load.
1185 *
1186 * @return array
1187 */
1188 protected function get_stored_config( $site_id ) {
1189
1190 $config = get_blog_option( (int) $site_id, self::CONFIG_KEY, false );
1191 if ( false === $config ) {
1192 $config = get_network_option( (int) $site_id, self::CONFIG_KEY, $this->get_default_config() );
1193 }
1194
1195 return wp_parse_args( $config, $this->get_default_config() );
1196 }
1197
1198 /**
1199 * Set the config.
1200 *
1201 * @param array $config The config to set.
1202 * @param int|null $site_id The site ID to load. Null for current site.
1203 */
1204 public function set_config( $config, $site_id = null ) {
1205
1206 $this->config = $config;
1207 if ( ! empty( $this->config['params']['showUngrouped'] ) ) {
1208 $ungrouped = $this->create_ungrouped();
1209 if ( ! empty( $ungrouped['plugins'] ) ) {
1210 $this->config['groups']['__ungrouped'] = $ungrouped;
1211 }
1212 }
1213 // Populate groups with plugins.
1214 array_map( [ $this, 'populate_plugins' ], $this->config['groups'] );
1215 // register selected presets.
1216 if ( ! empty( $this->config['selectedPresets'] ) ) {
1217 array_map( [ $this, 'register_preset' ], $this->config['selectedPresets'] );
1218 }
1219 }
1220
1221 /**
1222 * Create the Ungrouped, group.
1223 *
1224 * @return array
1225 */
1226 protected function create_ungrouped() {
1227 $plugins = array_keys( get_plugins() );
1228 $new_group = [
1229 'id' => '__ungrouped',
1230 'name' => __( 'Ungrouped', self::$slug ),
1231 'plugins' => [],
1232 ];
1233 $grouped = [];
1234 foreach ( $this->config['groups'] as $group ) {
1235 $grouped = array_merge( $grouped, $group['plugins'] );
1236 }
1237 $grouped = array_unique( $grouped );
1238 $new_group['plugins'] = array_diff( $plugins, $grouped );
1239
1240 return $new_group;
1241 }
1242
1243 /**
1244 * Register a preset.
1245 *
1246 * @param string $preset The preset name to register.
1247 */
1248 protected function register_preset( $preset ) {
1249
1250 $key = sanitize_title( $preset );
1251 if ( isset( $this->config['preset_groups'][ $key ] ) ) {
1252 $this->config['groups'][ $key ] = $this->config['preset_groups'][ $key ];
1253 }
1254 }
1255
1256 /**
1257 * Populate a group with selected plugins.
1258 *
1259 * @param array $group The group array.
1260 */
1261 protected function populate_plugins( $group ) {
1262
1263 static $plugins;
1264 if ( ! $plugins ) {
1265 $plugins = get_plugins();
1266 }
1267 foreach ( $group['plugins'] as $plugin ) {
1268 if ( ! isset( $plugins[ $plugin ] ) ) {
1269 $this->missing[ $plugin ] = [
1270 'Version' => '0.0',
1271 ];
1272 continue;
1273 }
1274 $this->groups[ $group['id'] ][ $plugin ] = $plugins[ $plugin ];
1275 }
1276 // Populate keywords now to keep ordering.
1277 $this->populate_keywords( $group['id'] );
1278 }
1279
1280 /**
1281 * Populate a group from keywords.
1282 *
1283 * @param string $id The group ID.
1284 */
1285 protected function populate_keywords( $id ) {
1286
1287 if ( ! isset( $this->config['groups'][ $id ] ) || empty( $this->config['groups'][ $id ]['keywords'] ) ) {
1288 return;
1289 }
1290 $matches = $this->match_plugins_by_keywords( $this->config['groups'][ $id ]['keywords'], get_plugins() );
1291 foreach ( $matches as $plugin_key => $plugin_data ) {
1292 if ( ! isset( $this->groups[ $id ][ $plugin_key ] ) ) {
1293 $this->groups[ $id ][ $plugin_key ] = $plugin_data;
1294 }
1295 }
1296 }
1297
1298 /**
1299 * Match plugins against a list of keywords, substring-matched (case-insensitive)
1300 * against each plugin's concatenated header metadata.
1301 *
1302 * @param array $keywords The keywords to match.
1303 * @param array $plugins Plugin file => plugin data map, as returned by get_plugins().
1304 *
1305 * @return array Plugin file => plugin data map of matched plugins.
1306 */
1307 protected function match_plugins_by_keywords( array $keywords, array $plugins ) {
1308
1309 $keywords = array_map( 'strtolower', $keywords );
1310 $matches = [];
1311 foreach ( $plugins as $plugin_key => $plugin_data ) {
1312 $plugin_string = strtolower( implode( ' ', $plugin_data ) );
1313 $matched = array_filter(
1314 $keywords,
1315 function ( $keyword ) use ( $plugin_string ) {
1316
1317 return false !== strpos( $plugin_string, $keyword );
1318 }
1319 );
1320 if ( ! empty( $matched ) ) {
1321 $matches[ $plugin_key ] = $plugin_data;
1322 }
1323 }
1324
1325 return $matches;
1326 }
1327
1328 /**
1329 * Persist keyword-matched plugins into a group's (or all groups') saved plugin list.
1330 *
1331 * Unlike populate_keywords(), which only affects the runtime nav/count state, this
1332 * writes matches into $this->config['groups'][$id]['plugins'] and saves the config.
1333 *
1334 * @param string|null $group_id Optional group ID to limit to; null runs for every group with keywords.
1335 *
1336 * @return bool True if any group was updated and saved.
1337 */
1338 public function auto_assign_by_keywords( $group_id = null ) {
1339
1340 $plugins = get_plugins();
1341 $group_ids = null !== $group_id ? [ $group_id ] : array_keys( $this->config['groups'] );
1342
1343 $claimed = [];
1344 foreach ( $this->config['groups'] as $group ) {
1345 $claimed = array_merge( $claimed, $group['plugins'] );
1346 }
1347
1348 $updated = false;
1349 foreach ( $group_ids as $id ) {
1350 if ( ! isset( $this->config['groups'][ $id ] ) || empty( $this->config['groups'][ $id ]['keywords'] ) ) {
1351 continue;
1352 }
1353 $matches = $this->match_plugins_by_keywords( $this->config['groups'][ $id ]['keywords'], $plugins );
1354 $new_plugins = array_diff( array_keys( $matches ), $claimed );
1355 if ( empty( $new_plugins ) ) {
1356 continue;
1357 }
1358 $this->config['groups'][ $id ]['plugins'] = array_values(
1359 array_unique( array_merge( $this->config['groups'][ $id ]['plugins'], $new_plugins ) )
1360 );
1361 $claimed = array_merge( $claimed, $new_plugins );
1362 $updated = true;
1363 }
1364
1365 if ( $updated ) {
1366 $this->save_config();
1367 }
1368
1369 return $updated;
1370 }
1371
1372 /**
1373 * Re-run keyword auto-assignment for all groups after a plugin is installed or updated.
1374 *
1375 * @param \WP_Upgrader $upgrader The upgrader instance (unused).
1376 * @param array $hook_extra Extra data describing the upgrade action.
1377 */
1378 public function after_plugin_upgrade( $upgrader, $hook_extra ) {
1379
1380 if ( ! isset( $hook_extra['type'] ) || 'plugin' !== $hook_extra['type'] ) {
1381 return;
1382 }
1383 $this->auto_assign_by_keywords();
1384 }
1385
1386 /**
1387 * Create a new Group.
1388 *
1389 * @param string $name The group name to create.
1390 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1391 *
1392 * @return string|bool
1393 */
1394 public function create_group( $name, array $plugin_slugs = [] ) {
1395
1396 $success = false;
1397 $new_id = Utils::generate_id();
1398 $group = [
1399 'id' => $new_id,
1400 'color' => '',
1401 'keywords' => [],
1402 'name' => trim( $name ),
1403 'open' => false,
1404 'plugins' => $plugin_slugs,
1405 ];
1406 $this->config['groups'][ $new_id ] = $group;
1407 if ( $this->save_config() ) {
1408 $success = $new_id;
1409 }
1410
1411 return $success;
1412 }
1413
1414 /**
1415 * Add plugins to a group.
1416 *
1417 * @param string $group_id The group ID to add plugin to.
1418 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1419 *
1420 * @return bool
1421 */
1422 public function add_to_group( $group_id, array $plugin_slugs ) {
1423
1424 $success = false;
1425 if ( isset( $this->config['groups'][ $group_id ] ) ) {
1426 $new_plugins = array_merge( $this->config['groups'][ $group_id ]['plugins'], $plugin_slugs );
1427 $this->config['groups'][ $group_id ]['plugins'] = array_unique( $new_plugins );
1428 $success = $this->save_config();
1429 }
1430
1431 return $success;
1432 }
1433
1434 /**
1435 * Remove Plugins from a group.
1436 *
1437 * @param string $group_id The group ID to add plugin to.
1438 * @param array $plugin_slugs Plugin slug or list of slugs to add to the group.
1439 *
1440 * @return bool
1441 */
1442 public function remove_from_group( $group_id, array $plugin_slugs ) {
1443
1444 $success = false;
1445 if ( isset( $this->config['groups'][ $group_id ] ) ) {
1446 $this->config['groups'][ $group_id ]['plugins'] = array_diff( $this->config['groups'][ $group_id ]['plugins'], $plugin_slugs );
1447 $success = $this->save_config();
1448 }
1449
1450 return $success;
1451 }
1452
1453 /**
1454 * Render the admin page.
1455 */
1456 public function render_admin() {
1457
1458 $bootstrap = [
1459 'loadURL' => rest_url( self::$slug . '/load' ),
1460 'restNonce' => wp_create_nonce( 'wp_rest' ),
1461 'siteID' => get_current_blog_id(),
1462 ];
1463
1464 // Flag if network admin vs main site.
1465 if ( is_network_admin() && is_main_site() ) {
1466 $bootstrap['networkAdmin'] = true;
1467 }
1468 include PLGGRP_PATH . 'includes/main.php';
1469 }
1470
1471 /**
1472 * Get the instance of the class.
1473 *
1474 * @return groups\classes\Plugin_Groups
1475 */
1476 public static function get_instance() {
1477
1478 if ( is_null( self::$instance ) ) {
1479 self::$instance = new self();
1480 }
1481
1482 return self::$instance;
1483 }
1484 }
1485