Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.57% covered (success)
90.57%
221 / 244
80.00% covered (warning)
80.00%
16 / 20
CRAP
n/a
0 / 0
wpcom_themes_get_purchases
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
wpcom_themes_tab_register_flag
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
wpcom_themes_tab_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_enqueue_script
100.00% covered (success)
100.00%
36 / 36
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_is_default_view
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_redirect_to_default_view
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
wpcom_themes_tab_url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
wpcom_themes_tab_checkout_url
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
wpcom_themes_tab_add_plan
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
wpcom_themes_tab_is_included
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
wpcom_themes_tab_add_subscription
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
6
wpcom_themes_tab_subscription
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
5.01
wpcom_themes_tab_api
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_store
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_mapper
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
wpcom_themes_tab_catalog
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
wpcom_themes_tab_serve_themes_api
100.00% covered (success)
100.00%
45 / 45
100.00% covered (success)
100.00%
1 / 1
15
wpcom_themes_tab_search_partners
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
7
wpcom_themes_tab_splice_search_partners
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
17
wpcom_themes_tab_prefer_wpcom_copies
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
14
1<?php
2/**
3 * Lists WordPress.com themes as a tab on the core Add Themes screen.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8use Automattic\Jetpack\Feature_Flags\Feature_Flags;
9use Automattic\Jetpack\Jetpack_Mu_Wpcom\Common;
10use Automattic\Jetpack\Status\Host;
11
12// @codeCoverageIgnoreStart -- shadowed by the test stub in tests/lib/functions-wordpress.php.
13if ( ! function_exists( 'wpcom_themes_get_purchases' ) ) {
14    /**
15     * Source of purchase data for the themes tab, pre-definable by a test as
16     * wpcom_expiry_get_purchases() is, and for the reason given there.
17     *
18     * @return array
19     *
20     * @phan-suppress PhanRedefineFunction -- phan sees both this and the test stub as definitions even though only one loads at runtime.
21     */
22    function wpcom_themes_get_purchases() {
23        if ( function_exists( 'wpcom_get_site_purchases' ) ) {
24            return wpcom_get_site_purchases();
25        }
26
27        return array();
28    }
29}
30// @codeCoverageIgnoreEnd
31
32/**
33 * The tab's `data-sort` value, which core's theme.js sends to themes_api() as `browse`.
34 */
35const WPCOM_THEMES_TAB = 'wpcom';
36
37/**
38 * Feature flag gating the tab.
39 */
40const WPCOM_THEMES_TAB_FLAG = 'wpcom-themes-marketplace-tab';
41
42/**
43 * Themes per request, which is also the grid's page size.
44 */
45const WPCOM_THEMES_TAB_PER_PAGE = 100;
46
47/**
48 * The `wpcom_pricing` value that lists only the themes this site can install with nothing to buy.
49 */
50const WPCOM_THEMES_TAB_INCLUDED = 'included';
51
52/**
53 * Registers the feature flag.
54 *
55 * @return void
56 */
57function wpcom_themes_tab_register_flag() {
58    Feature_Flags::register(
59        WPCOM_THEMES_TAB_FLAG,
60        array(
61            'default'     => false,
62            'description' => 'Show WordPress.com themes as a tab on the Add Themes screen.',
63            'owner'       => 'jetpack-mu-wpcom',
64        )
65    );
66}
67wpcom_themes_tab_register_flag();
68
69/**
70 * Whether to show the tab on this site.
71 *
72 * Core's Add Themes screen can't be reached on Simple, so there the tab goes on WordPress.com's
73 * own copy of it, which asks this before it draws.
74 *
75 * @return bool
76 */
77function wpcom_themes_tab_enabled() {
78    return ( new Host() )->is_wpcom_platform() && Feature_Flags::is_enabled( WPCOM_THEMES_TAB_FLAG );
79}
80
81/**
82 * Loads the script that adds the tab.
83 *
84 * Core hard-codes this screen's tabs with no filter (trac #65979), so the script inserts ours
85 * into the markup before core's theme.js reads it on DOM ready.
86 *
87 * @return void
88 */
89function wpcom_themes_tab_enqueue_script() {
90    if ( ! wpcom_themes_tab_enabled() ) {
91        return;
92    }
93
94    // Core's theme.js owns the views this decorates, and routes on DOM ready rather than on load.
95    wp_enqueue_script(
96        'wpcom-themes-tab',
97        plugins_url( 'js/themes-tab.js', __FILE__ ),
98        array( 'theme' ),
99        // The package version does not change between builds of it, and these are served for a year.
100        (string) filemtime( __DIR__ . '/js/themes-tab.js' ),
101        array( 'in_footer' => true )
102    );
103    wp_localize_script(
104        'wpcom-themes-tab',
105        'wpcomThemesTab',
106        array(
107            'sort'           => WPCOM_THEMES_TAB,
108            'label'          => _x( 'Marketplace', 'Theme Installer', 'jetpack-mu-wpcom' ),
109            'upgrade'        => __( 'Upgrade', 'jetpack-mu-wpcom' ),
110            /* translators: %s: Theme name. */
111            'upgradeLabel'   => __( 'Upgrade for %s', 'jetpack-mu-wpcom' ),
112            'subscribe'      => __( 'Subscribe', 'jetpack-mu-wpcom' ),
113            /* translators: %s: Theme name. */
114            'subscribeLabel' => __( 'Subscribe to %s', 'jetpack-mu-wpcom' ),
115            'pricingLabel'   => __( 'Filter themes by plan', 'jetpack-mu-wpcom' ),
116            'allPlans'       => __( 'All plans', 'jetpack-mu-wpcom' ),
117            'included'       => WPCOM_THEMES_TAB_INCLUDED,
118            'includedLabel'  => __( 'Included with my plan', 'jetpack-mu-wpcom' ),
119            'searchLabel'    => __( 'Search Themes', 'jetpack-mu-wpcom' ),
120            'products'       => WPCom_Themes_Store::PRODUCTS_URL,
121            /* translators: %s: Price per month, for example $7.20. */
122            'price'          => __( '%s/mo, billed annually', 'jetpack-mu-wpcom' ),
123            /* translators: 1: Price per month, for example $7.20. 2: Plan name, for example Personal plan. */
124            'priceWithPlan'  => __( '%1$s/mo, billed annually + %2$s', 'jetpack-mu-wpcom' ),
125        )
126    );
127    wp_enqueue_style(
128        'wpcom-themes-tab',
129        plugins_url( 'css/themes-tab.css', __FILE__ ),
130        array( 'wp-admin' ),
131        (string) filemtime( __DIR__ . '/css/themes-tab.css' )
132    );
133
134    Common\wpcom_enqueue_tracking_scripts( jetpack_mu_wpcom_enqueue_assets( 'wpcom-themes-tab-tracks', array( 'js' ) ) );
135}
136add_action( 'load-theme-install.php', 'wpcom_themes_tab_enqueue_script' );
137
138/**
139 * Whether a request to the Add Themes screen should land on this tab.
140 *
141 * @param array $query The request's query args.
142 * @return bool
143 */
144function wpcom_themes_tab_is_default_view( array $query ) {
145    if ( ! wpcom_themes_tab_enabled() ) {
146        return false;
147    }
148
149    // An explicit view, a search, an upload or a preview is left as asked for.
150    return ! array_intersect( array( 'browse', 'theme', 'search', 'upload' ), array_keys( $query ) );
151}
152
153/**
154 * Sends a bare Add Themes request to this tab.
155 *
156 * Core's theme.js routes a bare `theme-install.php` to `popular` and rewrites the URL to match, so
157 * the view has to be chosen before that runs rather than by ordering the tabs.
158 *
159 * @return void
160 */
161function wpcom_themes_tab_redirect_to_default_view() {
162    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reads which view was asked for, nothing more.
163    if ( ! wpcom_themes_tab_is_default_view( $_GET ) ) {
164        return;
165    }
166
167    wp_safe_redirect( wpcom_themes_tab_url() );
168    exit;
169}
170add_action( 'load-theme-install.php', 'wpcom_themes_tab_redirect_to_default_view' );
171/**
172 * This tab's own URL.
173 *
174 * @return string
175 */
176function wpcom_themes_tab_url() {
177    return admin_url( 'theme-install.php?browse=' . WPCOM_THEMES_TAB );
178}
179
180/**
181 * Where to buy the plan a theme needs.
182 *
183 * Checkout returns to the theme itself, where the plan now allows an install, and back out to
184 * the tab if it is abandoned instead.
185 *
186 * @param string|array $products One product slug, or the several checkout should charge for at once.
187 * @param string       $slug     Theme slug.
188 * @return string
189 */
190function wpcom_themes_tab_checkout_url( $products, string $slug ) {
191    $url = sprintf(
192        'https://wordpress.com/checkout/%s/%s',
193        rawurlencode( (string) wp_parse_url( home_url(), PHP_URL_HOST ) ),
194        // Checkout splits this segment on commas, so each slug is encoded but the separator is not.
195        implode( ',', array_map( 'rawurlencode', (array) $products ) )
196    );
197
198    // Checkout honours these on the site's own host, and add_query_arg() does not encode values.
199    return add_query_arg(
200        array(
201            'checkoutBackUrl' => rawurlencode( wpcom_themes_tab_url() ),
202            'redirect_to'     => rawurlencode( admin_url( 'theme-install.php?theme=' . rawurlencode( $slug ) ) ),
203        ),
204        $url
205    );
206}
207
208/**
209 * Says what a theme costs this site, for the badge every card carries.
210 *
211 * Core's grid offers Install for whatever it is given, so a theme the plan excludes also has to
212 * carry the upgrade that belongs in its place.
213 *
214 * @param stdClass $theme A theme in the themes API shape.
215 * @return stdClass The theme, carrying its badge and, when the plan excludes it, an upgrade.
216 */
217function wpcom_themes_tab_add_plan( $theme ) {
218    $theme->wpcom_marketplace_tab = true;
219
220    $tier = isset( $theme->theme_tier ) ? (string) $theme->theme_tier : '';
221
222    // A partner theme is sold rather than granted, so its badge is a price and not a plan.
223    if ( WPCom_Themes_Tiers::PARTNER === $tier ) {
224        return wpcom_themes_tab_add_subscription( $theme );
225    }
226
227    if ( wpcom_themes_tab_is_included( $tier, (string) ( $theme->slug ?? '' ) ) ) {
228        $theme->plan_badge = __( 'Included with plan', 'jetpack-mu-wpcom' );
229
230        return $theme;
231    }
232
233    $plan                 = WPCom_Themes_Tiers::plan_for( $tier );
234    $theme->plan_badge    = WPCom_Themes_Tiers::plan_name_for( $tier );
235    $theme->required_plan = $plan;
236    $theme->upgrade_url   = wpcom_themes_tab_checkout_url( $plan, (string) ( $theme->slug ?? '' ) );
237
238    return $theme;
239}
240
241/**
242 * Whether this site can install a theme with nothing more to buy.
243 *
244 * @param string $tier Tier slug.
245 * @param string $slug Theme slug.
246 * @return bool
247 */
248function wpcom_themes_tab_is_included( string $tier, string $slug ) {
249    // No plan includes a partner theme, so one counts only once its own subscription is paid for.
250    if ( WPCom_Themes_Tiers::PARTNER === $tier ) {
251        $subscription = wpcom_themes_tab_subscription( $slug );
252
253        return array() !== $subscription && $subscription['owned'];
254    }
255
256    return '' === WPCom_Themes_Tiers::plan_for( $tier ) || WPCom_Themes_Tiers::site_can_use( $tier );
257}
258
259/**
260 * Offers the subscription a partner theme needs, which no plan includes.
261 *
262 * The badge is left for the browser to write, because the store prices a request where it comes
263 * from: read here it would quote the web server's currency rather than the reader's.
264 *
265 * @param stdClass $theme A theme in the themes API shape.
266 * @return stdClass The theme, carrying what to price and where to buy it.
267 */
268function wpcom_themes_tab_add_subscription( $theme ) {
269    $slug         = (string) ( $theme->slug ?? '' );
270    $subscription = wpcom_themes_tab_subscription( $slug );
271
272    // A theme already paid for is core's to install, and one the store does not sell is not ours
273    // to sell. Both are left to core's own button, which a partner theme still defeats. DOTCOM-18722.
274    if ( array() === $subscription || $subscription['owned'] ) {
275        return $theme;
276    }
277
278    // Every paid plan grants the tier, so this is only ever the cheapest one.
279    $plan = WPCom_Themes_Tiers::site_can_use( WPCom_Themes_Tiers::PARTNER )
280        ? ''
281        : WPCom_Themes_Tiers::plan_for( WPCom_Themes_Tiers::PARTNER );
282
283    $theme->price_product = $subscription['product'];
284    $theme->price_plan    = '' === $plan ? '' : WPCom_Themes_Tiers::plan_name_for( WPCom_Themes_Tiers::PARTNER );
285    $theme->required_plan = $plan;
286    // Checkout charges for the plan and the theme together, so one purchase is enough to install.
287    $theme->purchase_url = wpcom_themes_tab_checkout_url(
288        '' === $plan ? $subscription['product'] : array( $plan, $subscription['product'] ),
289        $slug
290    );
291
292    return $theme;
293}
294
295/**
296 * How a partner theme is sold, and whether this site has already bought it.
297 *
298 * @param string $slug Theme slug.
299 * @return array{product: string, owned: bool}|array{} Empty when the store does not sell it.
300 */
301function wpcom_themes_tab_subscription( string $slug ) {
302    if ( '' === $slug ) {
303        return array();
304    }
305
306    $store    = wpcom_themes_tab_store();
307    $products = $store->products();
308
309    foreach ( wpcom_themes_tab_api()->fetch_partner_products()[ $slug ] ?? array() as $sold_as ) {
310        $product_slug = (string) ( $sold_as->product_slug ?? '' );
311        $product      = $products[ $product_slug ] ?? null;
312
313        if ( null === $product || WPCom_Themes_Store::TERM !== $product['term'] ) {
314            continue;
315        }
316
317        return array(
318            'product' => $product_slug,
319            'owned'   => in_array( $product['billing_slug'], $store->subscriptions(), true ),
320        );
321    }
322
323    return array();
324}
325
326/**
327 * The shared WordPress.com themes reader, which wpcomsh also uses for core's own tabs.
328 *
329 * @return WPCom_Themes_Api
330 */
331function wpcom_themes_tab_api() {
332    static $api;
333    if ( ! $api ) {
334        $api = new WPCom_Themes_Api( new WPCom_Themes_Cache() );
335    }
336
337    return $api;
338}
339
340/**
341 * The store reader, which prices the themes no plan includes.
342 *
343 * @return WPCom_Themes_Store
344 */
345function wpcom_themes_tab_store() {
346    static $store;
347    if ( ! $store ) {
348        $store = new WPCom_Themes_Store( new WPCom_Themes_Cache() );
349    }
350
351    return $store;
352}
353
354/**
355 * The shared mapper, which shapes a WordPress.com theme the way core's grid reads it.
356 *
357 * @return WPCom_Themes_Mapper
358 */
359function wpcom_themes_tab_mapper() {
360    static $mapper;
361    if ( ! $mapper ) {
362        $mapper = new WPCom_Themes_Mapper();
363    }
364
365    return $mapper;
366}
367
368/**
369 * Every theme the tab lists, in the order WordPress.com returns them.
370 *
371 * The shared reader fetches and caches the whole catalog, so the tab pages through it here rather
372 * than asking for a page at a time.
373 *
374 * @return array<stdClass>
375 */
376function wpcom_themes_tab_catalog() {
377    return array_values(
378        array_filter(
379            wpcom_themes_tab_api()->fetch_all_non_delisted_themes(),
380            static function ( $theme ) {
381                return is_object( $theme ) && ! empty( $theme->id ) && is_string( $theme->id );
382            }
383        )
384    );
385}
386
387/**
388 * Answers the tab's query in place of the WordPress.org themes API.
389 *
390 * @param false|object|array $result The result object or array. Default false.
391 * @param string             $action The type of information being requested.
392 * @param object             $args   Theme API arguments.
393 * @return false|object|array
394 */
395function wpcom_themes_tab_serve_themes_api( $result, $action, $args ) {
396    if ( false !== $result || 'query_themes' !== $action || ! wpcom_themes_tab_enabled() ) {
397        return $result;
398    }
399
400    // A `?theme=<slug>` preview link, loaded directly, looks its theme up by slug rather than by tab.
401    if ( ! isset( $args->browse ) && isset( $args->theme ) && is_string( $args->theme ) ) {
402        $theme = wpcom_themes_tab_api()->fetch_theme( $args->theme );
403
404        return null === $theme ? $result : (object) array(
405            'info'   => array(
406                'page'    => 1,
407                'pages'   => 1,
408                'results' => 1,
409            ),
410            'themes' => array( wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $theme ) ) ),
411        );
412    }
413
414    if ( ! isset( $args->browse ) || WPCOM_THEMES_TAB !== $args->browse ) {
415        return $result;
416    }
417
418    $themes = wpcom_themes_tab_catalog();
419
420    // Filtered before paging, so the count and the pages match what the grid shows.
421    if ( isset( $args->wpcom_pricing ) && WPCOM_THEMES_TAB_INCLUDED === $args->wpcom_pricing ) {
422        $themes = array_values(
423            array_filter(
424                $themes,
425                static function ( $theme ) {
426                    // Read as the mapper reads it, so the filter agrees with the card's badge.
427                    return wpcom_themes_tab_is_included( (string) ( $theme->theme_tier->slug ?? '' ), $theme->id );
428                }
429            )
430        );
431    }
432
433    $mapper = wpcom_themes_tab_mapper();
434
435    // Core's Feature Filter: as on WordPress.org, a theme has to carry every tag asked for.
436    $tags = isset( $args->tag ) ? array_filter( (array) $args->tag, 'is_string' ) : array();
437    if ( array() !== $tags ) {
438        $themes = array_values(
439            array_filter(
440                $themes,
441                static function ( $theme ) use ( $mapper, $tags ) {
442                    return array() === array_diff( $tags, $mapper->build_theme_tags( $theme ) );
443                }
444            )
445        );
446    }
447
448    $page = isset( $args->page ) ? max( 1, (int) $args->page ) : 1;
449
450    // Only the page core asked for is mapped: mapping reads each theme from disk to say whether it
451    // is installed.
452    $shown = array_slice( $themes, ( $page - 1 ) * WPCOM_THEMES_TAB_PER_PAGE, WPCOM_THEMES_TAB_PER_PAGE );
453
454    return (object) array(
455        'info'   => array(
456            'page'    => $page,
457            'pages'   => (int) ceil( count( $themes ) / WPCOM_THEMES_TAB_PER_PAGE ),
458            'results' => count( $themes ),
459        ),
460        'themes' => array_values( array_map( 'wpcom_themes_tab_add_plan', array_map( array( $mapper, 'map_wpcom_to_wporg' ), $shown ) ) ),
461    );
462}
463add_filter( 'themes_api', 'wpcom_themes_tab_serve_themes_api', 10, 3 );
464
465/**
466 * How many partner themes a search can bring to the top, as on the plugins Marketplace tab.
467 */
468const WPCOM_THEMES_TAB_SEARCH_PARTNERS = 2;
469
470/**
471 * Partner themes that match a search term, best matches first.
472 *
473 * A match in the name ranks above one WordPress.com found elsewhere in the theme. Only themes the
474 * store sells are offered.
475 *
476 * @param string $term What was searched for.
477 * @return array<stdClass> Themes in the WordPress.com shape.
478 */
479function wpcom_themes_tab_search_partners( string $term ) {
480    $needle = mb_strtolower( trim( $term ) );
481
482    // Anything shorter matches half the catalog.
483    if ( mb_strlen( $needle ) < 3 ) {
484        return array();
485    }
486
487    $in_name   = array();
488    $elsewhere = array();
489    foreach ( wpcom_themes_tab_api()->search_themes( $term ) as $theme ) {
490        $slug = $theme->id ?? null;
491
492        if (
493            ! is_string( $slug )
494            || WPCom_Themes_Tiers::PARTNER !== ( $theme->theme_tier->slug ?? '' )
495            || array() === wpcom_themes_tab_subscription( $slug )
496        ) {
497            continue;
498        }
499
500        if ( false !== mb_strpos( mb_strtolower( (string) ( $theme->name ?? '' ) ), $needle ) ) {
501            $in_name[] = $theme;
502        } else {
503            $elsewhere[] = $theme;
504        }
505    }
506
507    return array_slice( array_merge( $in_name, $elsewhere ), 0, WPCOM_THEMES_TAB_SEARCH_PARTNERS );
508}
509
510/**
511 * Adds matching partner themes to the top of a keyword search's first page.
512 *
513 * Runs after wpcomsh merges in the WordPress.com themes a plan includes, which leaves partner
514 * themes out because they are sold rather than included.
515 *
516 * @param object|WP_Error $result Themes API response.
517 * @param string          $action Themes API action.
518 * @param object          $args   Themes API arguments.
519 * @return object|WP_Error
520 */
521function wpcom_themes_tab_splice_search_partners( $result, $action, $args ) {
522    $term = is_object( $args ) && isset( $args->search ) && is_string( $args->search ) ? $args->search : '';
523    $page = is_object( $args ) && isset( $args->page ) ? (int) $args->page : 1;
524
525    if (
526        'query_themes' !== $action
527        || '' === $term
528        || $page > 1
529        || ! is_object( $result )
530        || ! isset( $result->themes )
531        || ! is_array( $result->themes )
532        || ! wpcom_themes_tab_enabled()
533    ) {
534        return $result;
535    }
536
537    $back     = admin_url( 'theme-install.php?search=' . rawurlencode( $term ) );
538    $partners = array();
539    foreach ( wpcom_themes_tab_search_partners( $term ) as $theme ) {
540        $theme = wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $theme ) );
541
542        // Listed by the search, which installs and purchase clicks are attributed to.
543        $theme->wpcom_marketplace_tab = false;
544        $theme->wpcom_search_slot     = true;
545
546        if ( isset( $theme->purchase_url ) ) {
547            $theme->purchase_url = add_query_arg( 'checkoutBackUrl', rawurlencode( $back ), $theme->purchase_url );
548        }
549
550        $partners[] = $theme;
551    }
552
553    if ( array() === $partners ) {
554        return $result;
555    }
556
557    // A WordPress.org theme with a partner theme's slug is another author's theme, so both stay listed.
558    $result->themes = array_merge( $partners, $result->themes );
559
560    if ( isset( $result->info['results'] ) ) {
561        $result->info['results'] += count( $partners );
562    }
563
564    return $result;
565}
566add_filter( 'themes_api_result', 'wpcom_themes_tab_splice_search_partners', 10, 3 );
567
568/**
569 * Shows WordPress.com's copy of a theme both directories list, on Simple.
570 *
571 * A Simple site can activate ours without moving to Atomic, so it takes the WordPress.org card's
572 * place. Not a partner theme's slug, which WordPress.org uses for another author's theme.
573 *
574 * @param object|WP_Error $result Themes API response.
575 * @param string          $action Themes API action.
576 * @return object|WP_Error
577 */
578function wpcom_themes_tab_prefer_wpcom_copies( $result, $action ) {
579    if (
580        'query_themes' !== $action
581        || ! is_object( $result )
582        || ! isset( $result->themes )
583        || ! is_array( $result->themes )
584        || ! ( new Host() )->is_wpcom_simple()
585        || ! wpcom_themes_tab_enabled()
586    ) {
587        return $result;
588    }
589
590    $ours = array();
591    foreach ( wpcom_themes_tab_catalog() as $theme ) {
592        if ( WPCom_Themes_Tiers::PARTNER !== WPCom_Themes_Tiers::tier_of( $theme ) ) {
593            $ours[ $theme->id ] = $theme;
594        }
595    }
596
597    foreach ( $result->themes as $i => $theme ) {
598        $slug = is_object( $theme ) && empty( $theme->is_wpcom_theme ) ? ( $theme->slug ?? null ) : null;
599
600        if ( ! is_string( $slug ) || ! isset( $ours[ $slug ] ) ) {
601            continue;
602        }
603
604        $copy = wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $ours[ $slug ] ) );
605
606        // Listed by core's tab, which installs and purchase clicks are attributed to.
607        $copy->wpcom_marketplace_tab = false;
608
609        $result->themes[ $i ] = $copy;
610    }
611
612    return $result;
613}
614add_filter( 'themes_api_result', 'wpcom_themes_tab_prefer_wpcom_copies', 10, 2 );