Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.38% covered (success)
94.38%
168 / 178
90.00% covered (success)
90.00%
18 / 20
CRAP
n/a
0 / 0
wpcom_marketplace_register_flag
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_tab_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_add_tab
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
wpcom_marketplace_serve_plugins_api
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
10
wpcom_marketplace_table_args
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
2
wpcom_marketplace_on_plugin_install_screen
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
wpcom_marketplace_is_installed
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
wpcom_marketplace_installed_version
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
wpcom_marketplace_has_update
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
5
wpcom_marketplace_for_core
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
wpcom_marketplace_needs_plan
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
wpcom_marketplace_term_noun
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
wpcom_marketplace_card_description
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
wpcom_marketplace_price_rows
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
11
wpcom_marketplace_card_button
92.68% covered (success)
92.68%
38 / 41
0.00% covered (danger)
0.00%
0 / 1
9.03
wpcom_marketplace_tab_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_render_tab
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_body_class
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_intro
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
wpcom_marketplace_render_table
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Lists the plugins WordPress.com sells as a tab on the core Add Plugins screen.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8use Automattic\Jetpack\Feature_Flags\Feature_Flags;
9use Automattic\Jetpack\Jetpack_Mu_Wpcom\Expiry_Notices\Expiry_Owner;
10use Automattic\Jetpack\Jetpack_Mu_Wpcom\Marketplace_Catalog;
11
12/**
13 * The tab's slug, which is also its `?tab=` value.
14 */
15const WPCOM_MARKETPLACE_TAB = 'wpcom-marketplace';
16
17/**
18 * Feature flag gating the tab.
19 */
20const WPCOM_MARKETPLACE_TAB_FLAG = 'wpcom-plugins-marketplace-tab';
21
22/**
23 * Registers the feature flag.
24 *
25 * Runs as this file loads, so the flag is listed wherever flags are read or toggled.
26 *
27 * @return void
28 */
29function wpcom_marketplace_register_flag() {
30    Feature_Flags::register(
31        WPCOM_MARKETPLACE_TAB_FLAG,
32        array(
33            // On for every site. Kept as an off switch, per site or for all, until the tab has settled.
34            'default'     => true,
35            'description' => 'Show WordPress.com partner and premium plugins as a Marketplace tab on the Add Plugins screen.',
36            'owner'       => 'jetpack-mu-wpcom',
37        )
38    );
39}
40wpcom_marketplace_register_flag();
41
42/**
43 * Whether to show the tab on this site.
44 *
45 * @return bool
46 */
47function wpcom_marketplace_tab_enabled() {
48    return Feature_Flags::is_enabled( WPCOM_MARKETPLACE_TAB_FLAG );
49}
50
51/**
52 * Adds the tab to the Add Plugins screen, ahead of Featured.
53 *
54 * Core lands on whichever tab comes first when none is requested, so this also
55 * makes Marketplace the screen's default view. Placed before Featured rather than
56 * at the very front, which leaves core's own Search Results and Beta Testing tabs
57 * first on the screens that add them.
58 *
59 * @param string[] $tabs Tabs shown on the Add Plugins screen.
60 * @return string[]
61 */
62function wpcom_marketplace_add_tab( $tabs ) {
63    if ( ! wpcom_marketplace_tab_enabled() || ! is_array( $tabs ) ) {
64        return $tabs;
65    }
66
67    $label = _x( 'Marketplace', 'Plugin Installer', 'jetpack-mu-wpcom' );
68
69    $position = array_search( 'featured', array_keys( $tabs ), true );
70    if ( false === $position ) {
71        return array_merge( array( WPCOM_MARKETPLACE_TAB => $label ), $tabs );
72    }
73
74    return array_merge(
75        array_slice( $tabs, 0, $position, true ),
76        array( WPCOM_MARKETPLACE_TAB => $label ),
77        array_slice( $tabs, $position, null, true )
78    );
79}
80add_filter( 'install_plugins_tabs', 'wpcom_marketplace_add_tab' );
81
82/**
83 * Answers the plugin API from the marketplace catalog.
84 *
85 * Serves the tab's listing, asked for by wpcom_marketplace_table_args(), and the details
86 * modal for any of our products.
87 *
88 * @param false|object|WP_Error $result The result object or array. Default false.
89 * @param string                $action The type of information being requested.
90 * @param object                $args   Plugin API arguments.
91 * @return false|object|WP_Error
92 */
93function wpcom_marketplace_serve_plugins_api( $result, $action, $args ) {
94    if ( false !== $result || ! wpcom_marketplace_tab_enabled() ) {
95        return $result;
96    }
97
98    if ( 'query_plugins' === $action && ! empty( $args->wpcom_marketplace ) ) {
99        $products = Marketplace_Catalog::get_products();
100
101        // Core's list table shows this with a Try Again button.
102        if ( empty( $products ) ) {
103            return new WP_Error( 'wpcom_marketplace_unavailable', __( 'These plugins could not be loaded right now. Please try again in a few minutes.', 'jetpack-mu-wpcom' ) );
104        }
105
106        return (object) array(
107            'info'    => array(
108                'page'    => 1,
109                'pages'   => 1,
110                'results' => count( $products ),
111            ),
112            'plugins' => array_map( 'wpcom_marketplace_for_core', array_values( $products ) ),
113        );
114    }
115
116    // Scoped to the plugin screens: plugins_api( 'plugin_information' ) is called from
117    // unrelated admin pages too, and none of those should pay for a catalog fetch.
118    if ( 'plugin_information' === $action && ! empty( $args->slug ) && wpcom_marketplace_on_plugin_install_screen() ) {
119        $product = Marketplace_Catalog::get_product_details( (string) $args->slug );
120
121        if ( null !== $product ) {
122            return (object) $product;
123        }
124    }
125
126    return $result;
127}
128add_filter( 'plugins_api', 'wpcom_marketplace_serve_plugins_api', 10, 3 );
129
130/**
131 * Has core's plugin list table ask for the whole catalog on this tab, on one page.
132 *
133 * Core has no query for a tab it does not know and passes false. The marker is what
134 * wpcom_marketplace_serve_plugins_api() answers.
135 *
136 * @param array|false $args Plugin API arguments core built for this tab.
137 * @return array|false
138 */
139function wpcom_marketplace_table_args( $args ) {
140    if ( ! wpcom_marketplace_tab_enabled() ) {
141        return $args;
142    }
143
144    return array(
145        'page'              => 1,
146        'per_page'          => max( 1, count( Marketplace_Catalog::get_products() ) ),
147        'locale'            => get_user_locale(),
148        'wpcom_marketplace' => true,
149    );
150}
151add_filter( 'install_plugins_table_api_args_' . WPCOM_MARKETPLACE_TAB, 'wpcom_marketplace_table_args' );
152
153/**
154 * Whether this request is the Add Plugins screen, the details modal included.
155 *
156 * Simple sites draw that screen from their own page, which calls itself core's screen.
157 *
158 * @return bool
159 */
160function wpcom_marketplace_on_plugin_install_screen() {
161    if ( isset( $GLOBALS['pagenow'] ) && 'plugin-install.php' === $GLOBALS['pagenow'] ) {
162        return true;
163    }
164
165    $screen = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
166
167    return null !== $screen && 'plugin-install' === $screen->id;
168}
169
170/**
171 * Whether a plugin is on this site already.
172 *
173 * Simple sites draw the Add Plugins screen without core's plugin install functions, and have
174 * nothing installed.
175 *
176 * @param array $plugin Plugin data.
177 * @return bool
178 */
179function wpcom_marketplace_is_installed( array $plugin ) {
180    if ( ! function_exists( 'install_plugin_install_status' ) ) {
181        return false;
182    }
183
184    $slug = (string) ( $plugin['slug'] ?? '' );
185
186    return wpcom_marketplace_has_update( $slug ) || '' !== wpcom_marketplace_installed_version( $slug );
187}
188
189/**
190 * The version of the plugin installed in a slug's directory, as core finds it.
191 *
192 * @param string $slug Plugin slug.
193 * @return string Installed version, or an empty string when nothing is installed there.
194 */
195function wpcom_marketplace_installed_version( $slug ) {
196    if ( '' === $slug || ! function_exists( 'get_plugins' ) || ! is_dir( WP_PLUGIN_DIR . '/' . $slug ) ) {
197        return '';
198    }
199
200    $installed = get_plugins( '/' . $slug );
201
202    return $installed ? (string) ( reset( $installed )['Version'] ?? '' ) : '';
203}
204
205/**
206 * Whether the update_plugins transient has an update waiting for a slug.
207 *
208 * @param string $slug Plugin slug.
209 * @return bool
210 */
211function wpcom_marketplace_has_update( $slug ) {
212    $updates = get_site_transient( 'update_plugins' );
213
214    foreach ( (array) ( $updates->response ?? array() ) as $update ) {
215        if ( is_object( $update ) && isset( $update->slug ) && $update->slug === $slug ) {
216            return true;
217        }
218    }
219
220    return false;
221}
222
223/**
224 * A card as core's install status should see it: no newer than what this site can update to.
225 *
226 * Core takes an older installed copy with no update entry as stale update data and reruns
227 * wp_update_plugins() on every call, once per card; products updated from elsewhere never get one.
228 *
229 * @param array $card Normalized product data.
230 * @return array
231 */
232function wpcom_marketplace_for_core( array $card ) {
233    $slug      = (string) ( $card['slug'] ?? '' );
234    $installed = wpcom_marketplace_installed_version( $slug );
235
236    if ( '' !== $installed && version_compare( (string) ( $card['version'] ?? '' ), $installed, '>' ) && ! wpcom_marketplace_has_update( $slug ) ) {
237        $card['version'] = $installed;
238    }
239
240    return $card;
241}
242
243/**
244 * Whether buying a product here also means buying a plan, as on a free Simple site.
245 *
246 * @return bool
247 */
248function wpcom_marketplace_needs_plan() {
249    return function_exists( 'wpcom_site_has_feature' ) && ! wpcom_site_has_feature( 'install-purchased-plugins' );
250}
251
252/**
253 * The billing term the tab sells at.
254 *
255 * Yearly only. Every product has both variations, but a switcher for the whole
256 * screen was a lot of furniture for a choice that belongs to one purchase, and
257 * checkout lets people change the term there with the product in front of them.
258 */
259const WPCOM_MARKETPLACE_TERM = 'yearly';
260
261/**
262 * The noun a price is read with, as in "$10.00/month".
263 *
264 * @param string $term 'yearly' or 'monthly'.
265 * @return string
266 */
267function wpcom_marketplace_term_noun( $term ) {
268    return 'monthly' === $term
269        ? __( 'month', 'jetpack-mu-wpcom' )
270        : __( 'year', 'jetpack-mu-wpcom' );
271}
272
273/**
274 * A card's description, as plain text cut to fit core's card.
275 *
276 * WordPress.org caps short descriptions at 150 characters, which is what core's card is sized for.
277 *
278 * @param array $card Normalized product data.
279 * @return string
280 */
281function wpcom_marketplace_card_description( array $card ) {
282    $description = wp_strip_all_tags( (string) ( $card['short_description'] ?? '' ) );
283    if ( mb_strlen( $description ) <= 150 ) {
284        return $description;
285    }
286
287    $cut   = mb_substr( $description, 0, 150 );
288    $space = mb_strrpos( $cut, ' ' );
289
290    return rtrim( false === $space ? $cut : mb_substr( $cut, 0, $space ), ' .,;:' ) . '…';
291}
292
293/**
294 * The price as its two rows of markup: the headline, and the line under it.
295 *
296 * The headline is the yearly price, which is what the button charges, with the saving
297 * beside it. The monthly price follows so the saving can be checked rather than taken on
298 * trust. Both are prices a buyer can really be charged: neither is the year divided by twelve.
299 *
300 * @param array $card Normalized product data.
301 * @return array{headline: string, note: string} Escaped markup, empty when there is nothing to show.
302 */
303function wpcom_marketplace_price_rows( array $card ) {
304    // The vendor sets a referral's price, so it gets Calypso's list-card wording, not the store's figures.
305    if ( Marketplace_Catalog::is_referral( $card ) ) {
306        return array(
307            'headline' => '<span class="wpcom-marketplace-card__amount">' . esc_html__( 'Start for free', 'jetpack-mu-wpcom' ) . '</span>',
308            'note'     => '',
309        );
310    }
311
312    $pricing = $card['wpcom_pricing'] ?? array();
313    $yearly  = (string) ( $pricing[ WPCOM_MARKETPLACE_TERM ]['price'] ?? '' );
314    $monthly = (string) ( $pricing['monthly']['price'] ?? '' );
315    $saving  = (int) ( $card['wpcom_saving'] ?? 0 );
316
317    if ( '' === $yearly && '' === $monthly ) {
318        return array(
319            'headline' => '',
320            'note'     => '',
321        );
322    }
323
324    // Only a product we cannot sell by the year falls back to pricing by the month.
325    $has_yearly = '' !== $yearly;
326
327    $headline = sprintf(
328        '<span class="wpcom-marketplace-card__amount">%s</span> <span class="wpcom-marketplace-card__per">/%s</span>',
329        esc_html( $has_yearly ? $yearly : $monthly ),
330        esc_html( wpcom_marketplace_term_noun( $has_yearly ? 'yearly' : 'monthly' ) )
331    );
332    if ( $has_yearly && $saving >= 5 ) {
333        /* translators: %d: Percentage saved, for example 31. */
334        $headline .= ' <span class="wpcom-marketplace-card__saving">' . esc_html( sprintf( __( 'Save %d%%', 'jetpack-mu-wpcom' ), $saving ) ) . '</span>';
335    }
336
337    $note = '';
338    if ( wpcom_marketplace_needs_plan() ) {
339        /**
340         * Filters the line under a card's price on a site that buys a plan along with the product.
341         *
342         * It replaces the monthly price, since the plan is the other thing the buyer pays for.
343         *
344         * @since $$next-version$$
345         *
346         * @param string $note Plain text.
347         */
348        $note = '<span class="wpcom-marketplace-card__note">' . esc_html( (string) apply_filters( 'wpcom_marketplace_plan_note', __( 'Needs a paid plan', 'jetpack-mu-wpcom' ) ) ) . '</span>';
349    } elseif ( $has_yearly && '' !== $monthly ) {
350        // Worded as a condition, not "or": the button buys the year, so this is only what it is measured against.
351        /* translators: %s: Price per month, for example $9.90. */
352        $note = '<span class="wpcom-marketplace-card__note">' . esc_html( sprintf( __( '%s/month if billed monthly', 'jetpack-mu-wpcom' ), $monthly ) ) . '</span>';
353    }
354
355    return array(
356        'headline' => $headline,
357        'note'     => $note,
358    );
359}
360
361/**
362 * The card's action, which is a purchase unless the plugin is already here.
363 *
364 * Installed products keep core's button: Marketplace_Products_Updater already gives
365 * core the right package URL, so Activate, Update and Active all behave.
366 *
367 * @param array  $card     Normalized product data.
368 * @param string $back_url Where checkout's Back link returns to. Defaults to the Marketplace tab.
369 * @return string Button markup.
370 */
371function wpcom_marketplace_card_button( array $card, $back_url = '' ) {
372    $name = (string) ( $card['name'] ?? $card['slug'] ?? '' );
373
374    if ( wpcom_marketplace_is_installed( $card ) ) {
375        return function_exists( 'wp_get_plugin_action_button' )
376            ? wp_get_plugin_action_button( $name, $card, true, true )
377            : '';
378    }
379
380    /*
381     * Checkout cannot complete a referral: the subscription is the vendor's to sell.
382     * Sending someone there would take payment for the wrong thing.
383     */
384    if ( Marketplace_Catalog::is_referral( $card ) ) {
385        if ( '' === (string) ( $card['wpcom_referral_url'] ?? '' ) ) {
386            return '';
387        }
388
389        $referral = Marketplace_Catalog::referral_url( $card, (int) Expiry_Owner::current_user_wpcom_id() );
390        /* translators: %s: Plugin name. */
391        $label = __( 'Get started with %s on the vendor site', 'jetpack-mu-wpcom' );
392
393        // With no WordPress.com account to refer, Calypso's product page can sign them in first.
394        if ( '' === $referral ) {
395            $referral = Marketplace_Catalog::product_url( $card['wpcom_product_slug'] ?? $card['slug'] );
396            /* translators: %s: Plugin name. */
397            $label = __( 'Get started with %s', 'jetpack-mu-wpcom' );
398        }
399
400        // No noreferrer: Calypso's link lets the vendor see where the visit came from, and so does this one.
401        return sprintf(
402            '<a class="button button-compact" href="%s" target="_blank" rel="noopener" data-wpcom-marketplace-track="get_started" aria-label="%s">%s</a>',
403            esc_url( $referral ),
404            esc_attr( sprintf( $label, $name ) ),
405            esc_html__( 'Get started', 'jetpack-mu-wpcom' )
406        );
407    }
408
409    $checkout = Marketplace_Catalog::checkout_url( $card, WPCOM_MARKETPLACE_TERM, '' === $back_url ? wpcom_marketplace_tab_url() : $back_url );
410
411    /**
412     * Filters where a Marketplace card's Purchase button leads.
413     *
414     * Simple sites add the plan the purchase needs, or send it through Calypso when the purchase
415     * cannot go ahead.
416     *
417     * @since 6.11.0
418     *
419     * @param string $checkout Checkout URL, or empty when there is no store product.
420     * @param array  $card     The product's card.
421     */
422    $checkout = (string) apply_filters( 'wpcom_marketplace_checkout_url', $checkout, $card );
423
424    // Without a store product there is nothing to buy, so fall back to the product page.
425    if ( '' === $checkout ) {
426        return sprintf(
427            '<a class="button button-compact" href="%s" data-wpcom-marketplace-track="get_started" aria-label="%s">%s</a>',
428            esc_url( Marketplace_Catalog::product_url( $card['wpcom_product_slug'] ?? $card['slug'] ) ),
429            /* translators: %s: Plugin name. */
430            esc_attr( sprintf( __( 'Get started with %s', 'jetpack-mu-wpcom' ), $name ) ),
431            esc_html__( 'Get started', 'jetpack-mu-wpcom' )
432        );
433    }
434
435    // A site whose plan does not include it buys one in the same checkout, through the filter above.
436    if ( wpcom_marketplace_needs_plan() ) {
437        return sprintf(
438            '<a class="button button-compact wpcom-marketplace-card__upgrade" href="%s" data-wpcom-marketplace-track="purchase" aria-label="%s">%s</a>',
439            esc_url( $checkout ),
440            /* translators: %s: Plugin name. */
441            esc_attr( sprintf( __( 'Upgrade your plan and purchase %s', 'jetpack-mu-wpcom' ), $name ) ),
442            esc_html__( 'Upgrade and purchase', 'jetpack-mu-wpcom' )
443        );
444    }
445
446    return sprintf(
447        '<a class="button button-compact" href="%s" data-wpcom-marketplace-track="purchase" aria-label="%s">%s</a>',
448        esc_url( $checkout ),
449        /* translators: %s: Plugin name. */
450        esc_attr( sprintf( __( 'Purchase and activate %s', 'jetpack-mu-wpcom' ), $name ) ),
451        esc_html__( 'Purchase', 'jetpack-mu-wpcom' )
452    );
453}
454
455/**
456 * The tab's own URL, which is where checkout's Back link should return to.
457 *
458 * @return string
459 */
460function wpcom_marketplace_tab_url() {
461    return add_query_arg( 'tab', WPCOM_MARKETPLACE_TAB, self_admin_url( 'plugin-install.php' ) );
462}
463
464/**
465 * Loads the tab's styles.
466 *
467 * @return void
468 */
469function wpcom_marketplace_render_tab() {
470    add_filter( 'admin_body_class', 'wpcom_marketplace_body_class' );
471
472    wp_enqueue_style(
473        'wpcom-marketplace-tab',
474        plugins_url( 'css/marketplace-tab.css', __FILE__ ),
475        array(),
476        (string) filemtime( __DIR__ . '/css/marketplace-tab.css' )
477    );
478
479    \Automattic\Jetpack\Jetpack_Mu_Wpcom\Common\wpcom_enqueue_tracking_scripts(
480        jetpack_mu_wpcom_enqueue_assets( 'wpcom-marketplace-tab', array( 'js' ) )
481    );
482}
483add_action( 'install_plugins_pre_' . WPCOM_MARKETPLACE_TAB, 'wpcom_marketplace_render_tab' );
484
485/**
486 * Flags the screen so the stylesheet can scope itself to this tab.
487 *
488 * @param string $classes Space-separated admin body classes.
489 * @return string
490 */
491function wpcom_marketplace_body_class( $classes ) {
492    return $classes . ' wpcom-marketplace-tab ';
493}
494
495/**
496 * Says what these plugins are, above the cards.
497 *
498 * @return void
499 */
500function wpcom_marketplace_intro() {
501    printf(
502        '<p class="wpcom-marketplace-intro">%s</p>',
503        esc_html__( 'Premium plugins from WordPress.com and our partners. Each one comes with a subscription, and is installed, updated, and supported for you.', 'jetpack-mu-wpcom' )
504    );
505}
506
507/**
508 * Draws the tab with core's plugin list table, as core draws its own tabs.
509 *
510 * The cards are core's, shaped by the same filters as search results (see
511 * wpcom-marketplace-cards.php). Mirrors display_plugins_table(), except the intro sits
512 * inside #plugin-filter, which core's live search empties before showing its results.
513 *
514 * @return void
515 */
516function wpcom_marketplace_render_table() {
517    global $wp_list_table;
518
519    echo '<form id="plugin-filter" method="post">';
520    wpcom_marketplace_intro();
521    if ( is_object( $wp_list_table ) && method_exists( $wp_list_table, 'display' ) ) {
522        $wp_list_table->display();
523    }
524    echo '</form>';
525}
526add_action( 'install_plugins_' . WPCOM_MARKETPLACE_TAB, 'wpcom_marketplace_render_table' );