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