Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.69% covered (success)
90.69%
224 / 247
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%
18 / 18
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 the store does not sell, or that a failed lookup hides, is not ours to sell.
273    if ( array() === $subscription ) {
274        return $theme;
275    }
276
277    // A theme already paid for is core's to install. wpcom reads the flag to offer Install, because
278    // a missing purchase_url alone cannot tell owned from unsold. DOTCOM-18722.
279    if ( $subscription['owned'] ) {
280        $theme->wpcom_owned = true;
281
282        return $theme;
283    }
284
285    // Every paid plan grants the tier, so this is only ever the cheapest one.
286    $plan = WPCom_Themes_Tiers::site_can_use( WPCom_Themes_Tiers::PARTNER )
287        ? ''
288        : WPCom_Themes_Tiers::plan_for( WPCom_Themes_Tiers::PARTNER );
289
290    $theme->price_product = $subscription['product'];
291    $theme->price_plan    = '' === $plan ? '' : WPCom_Themes_Tiers::plan_name_for( WPCom_Themes_Tiers::PARTNER );
292    $theme->required_plan = $plan;
293    // Checkout charges for the plan and the theme together, so one purchase is enough to install.
294    $theme->purchase_url = wpcom_themes_tab_checkout_url(
295        '' === $plan ? $subscription['product'] : array( $plan, $subscription['product'] ),
296        $slug
297    );
298
299    return $theme;
300}
301
302/**
303 * How a partner theme is sold, and whether this site has already bought it.
304 *
305 * @param string $slug Theme slug.
306 * @return array{product: string, owned: bool}|array{} Empty when the store does not sell it.
307 */
308function wpcom_themes_tab_subscription( string $slug ) {
309    if ( '' === $slug ) {
310        return array();
311    }
312
313    $store    = wpcom_themes_tab_store();
314    $products = $store->products();
315
316    foreach ( wpcom_themes_tab_api()->fetch_partner_products()[ $slug ] ?? array() as $sold_as ) {
317        $product_slug = (string) ( $sold_as->product_slug ?? '' );
318        $product      = $products[ $product_slug ] ?? null;
319
320        if ( null === $product || WPCom_Themes_Store::TERM !== $product['term'] ) {
321            continue;
322        }
323
324        return array(
325            'product' => $product_slug,
326            'owned'   => in_array( $product['billing_slug'], $store->subscriptions(), true ),
327        );
328    }
329
330    return array();
331}
332
333/**
334 * The shared WordPress.com themes reader, which wpcomsh also uses for core's own tabs.
335 *
336 * @return WPCom_Themes_Api
337 */
338function wpcom_themes_tab_api() {
339    static $api;
340    if ( ! $api ) {
341        $api = new WPCom_Themes_Api( new WPCom_Themes_Cache() );
342    }
343
344    return $api;
345}
346
347/**
348 * The store reader, which prices the themes no plan includes.
349 *
350 * @return WPCom_Themes_Store
351 */
352function wpcom_themes_tab_store() {
353    static $store;
354    if ( ! $store ) {
355        $store = new WPCom_Themes_Store( new WPCom_Themes_Cache() );
356    }
357
358    return $store;
359}
360
361/**
362 * The shared mapper, which shapes a WordPress.com theme the way core's grid reads it.
363 *
364 * @return WPCom_Themes_Mapper
365 */
366function wpcom_themes_tab_mapper() {
367    static $mapper;
368    if ( ! $mapper ) {
369        $mapper = new WPCom_Themes_Mapper();
370    }
371
372    return $mapper;
373}
374
375/**
376 * Every theme the tab lists, in the order WordPress.com returns them.
377 *
378 * The shared reader fetches and caches the whole catalog, so the tab pages through it here rather
379 * than asking for a page at a time.
380 *
381 * @return array<stdClass>
382 */
383function wpcom_themes_tab_catalog() {
384    return array_values(
385        array_filter(
386            wpcom_themes_tab_api()->fetch_all_non_delisted_themes(),
387            static function ( $theme ) {
388                return is_object( $theme ) && ! empty( $theme->id ) && is_string( $theme->id );
389            }
390        )
391    );
392}
393
394/**
395 * Answers the tab's query in place of the WordPress.org themes API.
396 *
397 * @param false|object|array $result The result object or array. Default false.
398 * @param string             $action The type of information being requested.
399 * @param object             $args   Theme API arguments.
400 * @return false|object|array
401 */
402function wpcom_themes_tab_serve_themes_api( $result, $action, $args ) {
403    if ( false !== $result || 'query_themes' !== $action || ! wpcom_themes_tab_enabled() ) {
404        return $result;
405    }
406
407    // A `?theme=<slug>` preview link, loaded directly, looks its theme up by slug rather than by tab.
408    if ( ! isset( $args->browse ) && isset( $args->theme ) && is_string( $args->theme ) ) {
409        $theme = wpcom_themes_tab_api()->fetch_theme( $args->theme );
410
411        return null === $theme ? $result : (object) array(
412            'info'   => array(
413                'page'    => 1,
414                'pages'   => 1,
415                'results' => 1,
416            ),
417            'themes' => array( wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $theme ) ) ),
418        );
419    }
420
421    if ( ! isset( $args->browse ) || WPCOM_THEMES_TAB !== $args->browse ) {
422        return $result;
423    }
424
425    $themes = wpcom_themes_tab_catalog();
426
427    // Filtered before paging, so the count and the pages match what the grid shows.
428    if ( isset( $args->wpcom_pricing ) && WPCOM_THEMES_TAB_INCLUDED === $args->wpcom_pricing ) {
429        $themes = array_values(
430            array_filter(
431                $themes,
432                static function ( $theme ) {
433                    // Read as the mapper reads it, so the filter agrees with the card's badge.
434                    return wpcom_themes_tab_is_included( (string) ( $theme->theme_tier->slug ?? '' ), $theme->id );
435                }
436            )
437        );
438    }
439
440    $mapper = wpcom_themes_tab_mapper();
441
442    // Core's Feature Filter: as on WordPress.org, a theme has to carry every tag asked for.
443    $tags = isset( $args->tag ) ? array_filter( (array) $args->tag, 'is_string' ) : array();
444    if ( array() !== $tags ) {
445        $themes = array_values(
446            array_filter(
447                $themes,
448                static function ( $theme ) use ( $mapper, $tags ) {
449                    return array() === array_diff( $tags, $mapper->build_theme_tags( $theme ) );
450                }
451            )
452        );
453    }
454
455    $page = isset( $args->page ) ? max( 1, (int) $args->page ) : 1;
456
457    // Only the page core asked for is mapped: mapping reads each theme from disk to say whether it
458    // is installed.
459    $shown = array_slice( $themes, ( $page - 1 ) * WPCOM_THEMES_TAB_PER_PAGE, WPCOM_THEMES_TAB_PER_PAGE );
460
461    return (object) array(
462        'info'   => array(
463            'page'    => $page,
464            'pages'   => (int) ceil( count( $themes ) / WPCOM_THEMES_TAB_PER_PAGE ),
465            'results' => count( $themes ),
466        ),
467        'themes' => array_values( array_map( 'wpcom_themes_tab_add_plan', array_map( array( $mapper, 'map_wpcom_to_wporg' ), $shown ) ) ),
468    );
469}
470add_filter( 'themes_api', 'wpcom_themes_tab_serve_themes_api', 10, 3 );
471
472/**
473 * How many partner themes a search can bring to the top, as on the plugins Marketplace tab.
474 */
475const WPCOM_THEMES_TAB_SEARCH_PARTNERS = 2;
476
477/**
478 * Partner themes that match a search term, best matches first.
479 *
480 * A match in the name ranks above one WordPress.com found elsewhere in the theme. Only themes the
481 * store sells are offered.
482 *
483 * @param string $term What was searched for.
484 * @return array<stdClass> Themes in the WordPress.com shape.
485 */
486function wpcom_themes_tab_search_partners( string $term ) {
487    $needle = mb_strtolower( trim( $term ) );
488
489    // Anything shorter matches half the catalog.
490    if ( mb_strlen( $needle ) < 3 ) {
491        return array();
492    }
493
494    $in_name   = array();
495    $elsewhere = array();
496    foreach ( wpcom_themes_tab_api()->search_themes( $term ) as $theme ) {
497        $slug = $theme->id ?? null;
498
499        if (
500            ! is_string( $slug )
501            || WPCom_Themes_Tiers::PARTNER !== ( $theme->theme_tier->slug ?? '' )
502            || array() === wpcom_themes_tab_subscription( $slug )
503        ) {
504            continue;
505        }
506
507        if ( false !== mb_strpos( mb_strtolower( (string) ( $theme->name ?? '' ) ), $needle ) ) {
508            $in_name[] = $theme;
509        } else {
510            $elsewhere[] = $theme;
511        }
512    }
513
514    return array_slice( array_merge( $in_name, $elsewhere ), 0, WPCOM_THEMES_TAB_SEARCH_PARTNERS );
515}
516
517/**
518 * Adds matching partner themes to the top of a keyword search's first page.
519 *
520 * Runs after wpcomsh merges in the WordPress.com themes a plan includes, which leaves partner
521 * themes out because they are sold rather than included.
522 *
523 * @param object|WP_Error $result Themes API response.
524 * @param string          $action Themes API action.
525 * @param object          $args   Themes API arguments.
526 * @return object|WP_Error
527 */
528function wpcom_themes_tab_splice_search_partners( $result, $action, $args ) {
529    $term = is_object( $args ) && isset( $args->search ) && is_string( $args->search ) ? $args->search : '';
530    $page = is_object( $args ) && isset( $args->page ) ? (int) $args->page : 1;
531
532    if (
533        'query_themes' !== $action
534        || '' === $term
535        || $page > 1
536        || ! is_object( $result )
537        || ! isset( $result->themes )
538        || ! is_array( $result->themes )
539        || ! wpcom_themes_tab_enabled()
540    ) {
541        return $result;
542    }
543
544    $back     = admin_url( 'theme-install.php?search=' . rawurlencode( $term ) );
545    $partners = array();
546    foreach ( wpcom_themes_tab_search_partners( $term ) as $theme ) {
547        $theme = wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $theme ) );
548
549        // Listed by the search, which installs and purchase clicks are attributed to.
550        $theme->wpcom_marketplace_tab = false;
551        $theme->wpcom_search_slot     = true;
552
553        if ( isset( $theme->purchase_url ) ) {
554            $theme->purchase_url = add_query_arg( 'checkoutBackUrl', rawurlencode( $back ), $theme->purchase_url );
555        }
556
557        $partners[] = $theme;
558    }
559
560    if ( array() === $partners ) {
561        return $result;
562    }
563
564    // A WordPress.org theme with a partner theme's slug is another author's theme, so both stay listed.
565    $result->themes = array_merge( $partners, $result->themes );
566
567    if ( isset( $result->info['results'] ) ) {
568        $result->info['results'] += count( $partners );
569    }
570
571    return $result;
572}
573add_filter( 'themes_api_result', 'wpcom_themes_tab_splice_search_partners', 10, 3 );
574
575/**
576 * Shows WordPress.com's copy of a theme both directories list, on Simple.
577 *
578 * A Simple site can activate ours without moving to Atomic, so it takes the WordPress.org card's
579 * place. Not a partner theme's slug, which WordPress.org uses for another author's theme.
580 *
581 * @param object|WP_Error $result Themes API response.
582 * @param string          $action Themes API action.
583 * @return object|WP_Error
584 */
585function wpcom_themes_tab_prefer_wpcom_copies( $result, $action ) {
586    if (
587        'query_themes' !== $action
588        || ! is_object( $result )
589        || ! isset( $result->themes )
590        || ! is_array( $result->themes )
591        || ! ( new Host() )->is_wpcom_simple()
592        || ! wpcom_themes_tab_enabled()
593    ) {
594        return $result;
595    }
596
597    $ours = array();
598    foreach ( wpcom_themes_tab_catalog() as $theme ) {
599        if ( WPCom_Themes_Tiers::PARTNER !== WPCom_Themes_Tiers::tier_of( $theme ) ) {
600            $ours[ $theme->id ] = $theme;
601        }
602    }
603
604    foreach ( $result->themes as $i => $theme ) {
605        $slug = is_object( $theme ) && empty( $theme->is_wpcom_theme ) ? ( $theme->slug ?? null ) : null;
606
607        if ( ! is_string( $slug ) || ! isset( $ours[ $slug ] ) ) {
608            continue;
609        }
610
611        $copy = wpcom_themes_tab_add_plan( wpcom_themes_tab_mapper()->map_wpcom_to_wporg( $ours[ $slug ] ) );
612
613        // Listed by core's tab, which installs and purchase clicks are attributed to.
614        $copy->wpcom_marketplace_tab = false;
615
616        $result->themes[ $i ] = $copy;
617    }
618
619    return $result;
620}
621add_filter( 'themes_api_result', 'wpcom_themes_tab_prefer_wpcom_copies', 10, 2 );