Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.42% covered (warning)
86.42%
70 / 81
76.92% covered (warning)
76.92%
10 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
Menu_Visibility
86.42% covered (warning)
86.42%
70 / 81
76.92% covered (warning)
76.92%
10 / 13
69.02
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 forget_resolved_gates
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 resolve
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 activate
84.21% covered (warning)
84.21%
16 / 19
0.00% covered (danger)
0.00%
0 / 1
11.48
 can_activate
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
42
 get_targets
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
5
 is_module_on_offer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 is_module_activated
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 is_product_activated
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 can_offer
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
7
 offers
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
8
 is_module_held_off
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 is_module_removed
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
5.20
1<?php
2/**
3 * Resolves whether a Jetpack admin menu item's feature is active.
4 *
5 * @package automattic/my-jetpack
6 */
7
8namespace Automattic\Jetpack\My_Jetpack;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Modules;
12use WP_Error;
13
14/**
15 * The activation half of the sidebar visibility contract.
16 *
17 * Admin_Menu owns when the question is asked and what a host may do with the answer; this
18 * class owns the answer itself, because the product classes it reads live here. A menu item
19 * declares its gate at registration and this resolves it from the same product class its
20 * My Jetpack card reads.
21 */
22class Menu_Visibility {
23
24    /**
25     * Gates already resolved this registration pass, keyed by type and slug.
26     *
27     * @var array<string, bool|null>
28     */
29    private static $resolved = array();
30
31    /**
32     * Registers this class as Admin_Menu's visibility resolver.
33     *
34     * @return void
35     */
36    public static function init() {
37        // An older admin-ui, loaded first by another plugin, may predate the resolver; items then stay visible.
38        if ( ! method_exists( Admin_Menu::class, 'set_visibility_resolver' ) ) {
39            return;
40        }
41
42        Admin_Menu::set_visibility_resolver( array( __CLASS__, 'resolve' ) );
43        if ( method_exists( Admin_Menu::class, 'set_feature_activator' ) ) {
44            Admin_Menu::set_feature_activator( array( __CLASS__, 'activate' ), array( __CLASS__, 'offers' ) );
45        }
46
47        // Memoized answers last one registration pass, which is as long as they can stay true.
48        add_action( 'admin_menu', array( __CLASS__, 'forget_resolved_gates' ), 0 );
49        add_action( 'network_admin_menu', array( __CLASS__, 'forget_resolved_gates' ), 0 );
50    }
51
52    /**
53     * Drops the gates resolved during the previous registration pass.
54     *
55     * @return void
56     */
57    public static function forget_resolved_gates() {
58        self::$resolved = array();
59    }
60
61    /**
62     * Answers whether a menu item's declared gate is satisfied.
63     *
64     * Answers are memoized for one registration pass: resolving a product rebuilds the product
65     * class map and rescans the installed plugins, and the sidebar asks once per gated item.
66     *
67     * @param array $args The item's visibility declaration, as passed to Admin_Menu::add_menu().
68     * @return bool|null True or false, or null when the gate cannot be resolved here.
69     */
70    public static function resolve( $args ) {
71        if ( ! empty( $args['product'] ) ) {
72            $key = 'product:' . $args['product'];
73
74            if ( ! array_key_exists( $key, self::$resolved ) ) {
75                self::$resolved[ $key ] = self::is_product_activated( $args['product'] );
76            }
77
78            return self::$resolved[ $key ];
79        }
80
81        if ( ! empty( $args['module'] ) ) {
82            $key = 'module:' . $args['module'];
83
84            if ( ! array_key_exists( $key, self::$resolved ) ) {
85                self::$resolved[ $key ] = self::is_module_activated( $args['module'] );
86            }
87
88            return self::$resolved[ $key ];
89        }
90
91        return null;
92    }
93
94    /**
95     * Switch a gated feature on the way the Features tab does: its module, when Jetpack runs one, before its plugin.
96     *
97     * Never installs a plugin; a feature that needs one is set up from My Jetpack.
98     *
99     * @param array $args The item's visibility declaration.
100     * @return true|WP_Error
101     */
102    public static function activate( $args ) {
103        list( $product_class, $module ) = self::get_targets( $args );
104
105        // Else the product fallback below would install a plugin for a module the site filtered away or holds off.
106        if ( ! self::can_offer( $args ) ) {
107            return new WP_Error( 'not_available', __( 'This feature is not available on this site.', 'jetpack-my-jetpack' ) );
108        }
109
110        if ( self::is_module_on_offer( $module ) ) {
111            if ( isset( Products\Protect::get_protect_page_module_urls()[ $module ] ) ) {
112                return REST_Main_Features::managed_in_protect_error();
113            }
114            $result = REST_Main_Features::switch_module( $module, true );
115            // A product whose standalone plugin is off stays off with its module on: activate the plugin below.
116            if ( is_wp_error( $result ) || ! $product_class || $product_class::is_activated() ) {
117                self::forget_resolved_gates();
118                return $result;
119            }
120        }
121
122        if ( ! $product_class ) {
123            return new WP_Error( 'not_found', __( 'That feature was not found.', 'jetpack-my-jetpack' ) );
124        }
125        // Not is_plugin_installed(): a hybrid product counts the Jetpack plugin, and activation would install its own.
126        if ( ! $product_class::get_installed_plugin_filename() ) {
127            return new WP_Error( 'not_available', __( 'This feature needs a plugin installed from My Jetpack.', 'jetpack-my-jetpack' ) );
128        }
129        if ( ! REST_Products::edit_permissions_callback() ) {
130            return new WP_Error( 'not_allowed', __( 'Your account can’t activate plugins on this site.', 'jetpack-my-jetpack' ) );
131        }
132
133        $result = $product_class::activate();
134        self::forget_resolved_gates();
135
136        return is_wp_error( $result ) ? $result : true;
137    }
138
139    /**
140     * Whether the current user has the capabilities activate() needs for this gate.
141     *
142     * @param array $args The item's visibility declaration.
143     * @return bool
144     */
145    public static function can_activate( $args ) {
146        list( $product_class, $module ) = self::get_targets( $args );
147        $module_on_offer                = self::is_module_on_offer( $module );
148
149        if ( $module_on_offer && ! current_user_can( 'jetpack_manage_modules' ) ) {
150            return false;
151        }
152        // activate() goes on to the plugin when Jetpack runs no module for it, or the plugin is off.
153        if ( $product_class && ( ! $module_on_offer || ! $product_class::is_plugin_active() ) ) {
154            return REST_Products::edit_permissions_callback();
155        }
156
157        return $module_on_offer;
158    }
159
160    /**
161     * The product class and module a gate switches.
162     *
163     * @param array $args The item's visibility declaration.
164     * @return array{0: class-string<Product>|null, 1: string|null}
165     */
166    private static function get_targets( $args ) {
167        $product_class = empty( $args['product'] ) ? null : Products::get_product_class( $args['product'] );
168        $module        = empty( $args['module'] ) ? ( $product_class ? $product_class::get_module_name() : null ) : $args['module'];
169
170        return array( $product_class, $module ? $module : null );
171    }
172
173    /**
174     * Whether this site runs the module, so switching it on needs no plugin.
175     *
176     * @param string|null $module_name A Jetpack module name.
177     * @return bool
178     */
179    private static function is_module_on_offer( $module_name ) {
180        return $module_name && in_array( $module_name, ( new Modules() )->get_available(), true );
181    }
182
183    /**
184     * Whether a Jetpack module gating an item is switched on.
185     *
186     * A name this site has no module for is unanswerable rather than off, so a typo in a gate
187     * fails open like an unknown product slug does instead of silently removing the item. Off
188     * the Jetpack plugin that covers any module a standalone plugin did not declare through
189     * `jetpack_get_available_standalone_modules`.
190     *
191     * @param string $module_name A Jetpack module name.
192     * @return bool|null Null when this site has no such module.
193     */
194    private static function is_module_activated( $module_name ) {
195        $modules = new Modules();
196
197        if ( ! in_array( $module_name, $modules->get_available(), true ) ) {
198            return null;
199        }
200
201        return $modules->is_active( $module_name );
202    }
203
204    /**
205     * Whether the site has switched a My Jetpack product on.
206     *
207     * Reads is_activated(), not is_active(): a lapsed plan is not "off", and resolving plans
208     * costs WordPress.com requests on every admin page load. No connection check is added.
209     *
210     * @param string $product_slug A My Jetpack product slug.
211     * @return bool|null Null when no product class is registered under that slug.
212     */
213    private static function is_product_activated( $product_slug ) {
214        $product_class = Products::get_product_class( $product_slug );
215
216        if ( ! $product_class ) {
217            return null;
218        }
219
220        return (bool) $product_class::is_activated();
221    }
222
223    /**
224     * Whether activate() can switch a gate's feature on: it needs no install, and nothing removed its module or holds it off.
225     *
226     * Separate from resolve(), which also decides the sidebar: a feature held off is still off there.
227     *
228     * @param array $args The item's visibility declaration.
229     * @return bool
230     */
231    public static function can_offer( $args ) {
232        list( $product_class, $module ) = self::get_targets( $args );
233
234        // A site without the plugin never had the feature on, say Stats on a Boost-only site.
235        if ( ! self::is_module_on_offer( $module ) && ! ( $product_class && $product_class::get_installed_plugin_filename() ) ) {
236            return false;
237        }
238
239        return ! self::is_module_removed( $module )
240            && ! self::is_module_held_off( $module )
241            && ! ( $product_class && $product_class::is_held_off() );
242    }
243
244    /**
245     * Whether the admin shell should offer to turn a gate's feature on: it can, and the Features tab lists it, so My Jetpack has its card.
246     *
247     * A page with no card, such as SEO's, keeps its own way to turn its feature back on.
248     *
249     * @param array $args The item's visibility declaration.
250     * @return bool
251     */
252    public static function offers( $args ) {
253        $listed = false;
254        foreach ( Main_Features::get_feature_definitions() as $definition ) {
255            if ( ( ! empty( $args['product'] ) && ( $definition['product'] ?? '' ) === $args['product'] )
256                || ( empty( $args['product'] ) && ! empty( $args['module'] ) && ( $definition['module'] ?? '' ) === $args['module'] ) ) {
257                $listed = true;
258                break;
259            }
260        }
261
262        return $listed && self::can_offer( $args );
263    }
264
265    /**
266     * Whether a `jetpack_active_modules` callback, such as a host's, would keep this module off once it is saved on.
267     *
268     * @param string|null $module_name A Jetpack module name.
269     * @return bool
270     */
271    private static function is_module_held_off( $module_name ) {
272        if ( ! self::is_module_on_offer( $module_name ) ) {
273            return false;
274        }
275        $active = ( new Modules() )->get_active();
276        if ( in_array( $module_name, $active, true ) ) {
277            return false;
278        }
279
280        /** This filter is documented in projects/packages/status/src/class-modules.php */
281        return ! in_array( $module_name, (array) apply_filters( 'jetpack_active_modules', array_merge( $active, array( $module_name ) ) ), true );
282    }
283
284    /**
285     * Whether the Jetpack plugin ships this module but no longer offers it, as when a
286     * `jetpack_get_available_modules` filter removes it.
287     *
288     * Bundles and Scan name modules Jetpack has no file for, which are not removed.
289     *
290     * @param string|null $module_name A Jetpack module name.
291     * @return bool
292     */
293    private static function is_module_removed( $module_name ) {
294        if ( ! $module_name || ! class_exists( 'Jetpack' ) ) {
295            return false;
296        }
297        $modules = new Modules();
298        $path    = $modules->get_path( $module_name );
299
300        return $path && file_exists( $path ) && ! in_array( $module_name, $modules->get_available(), true );
301    }
302}