Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
73.76% covered (warning)
73.76%
163 / 221
64.71% covered (warning)
64.71%
11 / 17
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Connector
73.76% covered (warning)
73.76%
163 / 221
64.71% covered (warning)
64.71%
11 / 17
184.17
0.00% covered (danger)
0.00%
0 / 1
 init
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 register_connector
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_script_module
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 1
20
 get_connector_data
93.94% covered (success)
93.94%
31 / 33
0.00% covered (danger)
0.00%
0 / 1
7.01
 add_identity_crisis_data
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
7.02
 get_current_user_data
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 get_connection_owner_data
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 resolve_user_fields
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
10
 is_connectors_screen
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 get_connectors_page_path
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 store_auth_error
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 consume_auth_error
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 get_connected_plugins_data
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
5
 get_connected_plugin_families
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
5
 get_connector_logo_url
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 get_inline_connector_logo_url
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
30
 get_plugin_logo_url
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
7.05
1<?php
2/**
3 * Jetpack connector card for the WP core Connectors screen.
4 *
5 * Registers a connector in the WP 7.0+ Connectors registry and enqueues
6 * a script module that provides a custom render function with connection
7 * details (owner, connected plugins, disconnect).
8 *
9 * @package automattic/jetpack-connection
10 */
11
12namespace Automattic\Jetpack\Connection;
13
14use Automattic\Jetpack\Identity_Crisis;
15use Automattic\Jetpack\Modules;
16use Automattic\Jetpack\Status;
17use Automattic\Jetpack\Status\Host;
18
19/**
20 * Jetpack connector card handler.
21 *
22 * @since 8.2.0
23 */
24class Jetpack_Connector {
25
26    /**
27     * Whether the connector has been initialized.
28     *
29     * @var bool
30     */
31    private static $initialized = false;
32
33    /**
34     * Script module identifier.
35     *
36     * @var string
37     */
38    const MODULE_ID = '@automattic/jetpack-connection-connectors';
39
40    /**
41     * Screen ID assigned by WordPress to the Gutenberg plugin's connectors submenu page.
42     *
43     * @var string
44     */
45    const GUTENBERG_CONNECTORS_SCREEN_ID = 'settings_page_options-connectors-wp-admin';
46
47    /**
48     * Page slug registered by the Gutenberg plugin for the connectors submenu page.
49     *
50     * @var string
51     */
52    const GUTENBERG_CONNECTORS_PAGE_SLUG = 'options-connectors-wp-admin';
53
54    /**
55     * Initialize the connector.
56     */
57    public static function init() {
58        if ( static::$initialized ) {
59            return;
60        }
61        static::$initialized = true;
62
63        add_action( 'wp_connectors_init', array( static::class, 'register_connector' ), 20 );
64        add_action( 'admin_enqueue_scripts', array( static::class, 'enqueue_script_module' ) );
65        add_action( 'jetpack_client_authorize_error', array( static::class, 'store_auth_error' ) );
66    }
67
68    /**
69     * Register Jetpack as a connector in the WP core Connectors screen.
70     *
71     * The wp_connectors_init action is available in WordPress 7.0+.
72     * On older versions this action never fires, so the hook is safely a no-op.
73     *
74     * @since 8.2.0
75     *
76     * @param \WP_Connector_Registry $registry Connector registry instance.
77     */
78    public static function register_connector( $registry ) {
79        $registry->register(
80            'wordpress_com',
81            array(
82                'name'           => 'Jetpack Connection',
83                'description'    => __( 'Enhanced functionality for Jetpack and WooCommerce with WordPress.com.', 'jetpack-connection' ),
84                'type'           => 'cloud_service',
85                'logo_url'       => static::get_connector_logo_url(),
86                'authentication' => array(
87                    'method' => 'none',
88                ),
89            )
90        );
91    }
92
93    /**
94     * Enqueue the connectors card script module on the Settings > Connectors page.
95     *
96     * @since 8.2.0
97     */
98    public static function enqueue_script_module() {
99        $screen = get_current_screen();
100
101        if ( ! $screen || ! static::is_connectors_screen( $screen ) ) {
102            return;
103        }
104
105        if ( ! class_exists( 'WP_Connector_Registry' ) ) {
106            return;
107        }
108
109        $css_path = __DIR__ . '/css/connectors-card.css';
110        wp_enqueue_style(
111            'jetpack-connector-card',
112            plugins_url( 'css/connectors-card.css', __FILE__ ),
113            array(),
114            (string) @filemtime( $css_path ) // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- fallback to empty string if file is missing.
115        );
116
117        $js_path = __DIR__ . '/js/connectors-card.js';
118        wp_register_script_module(
119            static::MODULE_ID,
120            plugins_url( 'js/connectors-card.js', __FILE__ ),
121            array(
122                array(
123                    'id'     => '@wordpress/connectors',
124                    'import' => 'static',
125                ),
126            ),
127            (string) @filemtime( $js_path ) // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- fallback to empty string if file is missing.
128        );
129        wp_enqueue_script_module( static::MODULE_ID );
130
131        add_filter(
132            'script_module_data_' . static::MODULE_ID,
133            array( static::class, 'get_connector_data' )
134        );
135    }
136
137    /**
138     * Build the data passed to the script module via the script_module_data_ filter.
139     *
140     * @since 8.2.0
141     *
142     * @param array $data Existing script module data.
143     * @return array Filtered script module data.
144     */
145    public static function get_connector_data( $data ) {
146        $manager       = new Manager();
147        $is_registered = $manager->is_connected();
148        $is_connected  = $is_registered && $manager->has_connected_owner();
149
150        $data['isConnected']          = $is_connected;
151        $data['isRegistered']         = $is_registered;
152        $data['isOfflineMode']        = ( new Status() )->is_offline_mode();
153        $data['isFirstConnection']    = ! $is_registered && ! (bool) \Jetpack_Options::get_option( 'id' );
154        $data['apiRoot']              = esc_url_raw( rest_url() );
155        $data['apiNonce']             = wp_create_nonce( 'wp_rest' );
156        $data['redirectUri']          = static::get_connectors_page_path();
157        $data['connectorName']        = 'Jetpack Connection';
158        $data['connectorDescription'] = __( 'Enhanced functionality for Jetpack and WooCommerce with WordPress.com.', 'jetpack-connection' );
159        $data['connectorLogoUrl']     = static::get_connector_logo_url();
160
161        $data['connectedPlugins'] = static::get_connected_plugins_data( $manager );
162
163        if ( $is_registered ) {
164            $data['siteDetails'] = array(
165                'blogId'  => (int) \Jetpack_Options::get_option( 'id' ),
166                'siteUrl' => site_url(),
167                'homeUrl' => home_url(),
168            );
169
170            if ( in_array( 'jetpack', array_column( $data['connectedPlugins'], 'slug' ), true ) ) {
171                $data['ssoStatus'] = ( new Modules() )->is_active( 'sso', false );
172            }
173
174            static::add_identity_crisis_data( $data );
175        }
176
177        if ( $is_connected ) {
178            $data['currentUser']     = static::get_current_user_data( $manager );
179            $data['connectionOwner'] = static::get_connection_owner_data( $manager );
180        }
181
182        $host              = new Host();
183        $data['isWoaSite'] = $host->is_woa_site();
184        $data['isVipSite'] = $host->is_vip_site();
185
186        $auth_error = static::consume_auth_error();
187        if ( $auth_error ) {
188            $data['authError'] = $auth_error;
189        }
190
191        return $data;
192    }
193
194    /**
195     * Add Jetpack Identity Crisis (Safe Mode) data to the script module data.
196     *
197     * The connector card uses this to swap the status badge to "Safe Mode" and
198     * to render IDC resolution options (migrate / start fresh / stay in safe
199     * mode) in the expanded details. Mirrors the data assembled by
200     * \Automattic\Jetpack\IdentityCrisis\UI::get_initial_state_data().
201     *
202     * @since 8.7.0
203     *
204     * @param array $data Script module data passed by reference.
205     */
206    private static function add_identity_crisis_data( &$data ) {
207        if ( ! class_exists( Identity_Crisis::class ) ) {
208            return;
209        }
210
211        $in_safe_mode = ( new Status() )->in_safe_mode();
212
213        $data['isInSafeMode'] = $in_safe_mode;
214
215        if ( ! $in_safe_mode ) {
216            return;
217        }
218
219        $idc_urls = Identity_Crisis::get_mismatched_urls();
220
221        $data['isSafeModeConfirmed'] = (bool) Identity_Crisis::$is_safe_mode_confirmed;
222        $data['idc']                 = array(
223            'currentUrl'                     => ( is_array( $idc_urls ) && array_key_exists( 'current_url', $idc_urls ) ) ? $idc_urls['current_url'] : home_url(),
224            'wpcomHomeUrl'                   => ( is_array( $idc_urls ) && array_key_exists( 'wpcom_url', $idc_urls ) ) ? $idc_urls['wpcom_url'] : '',
225            'isDevelopmentSite'              => (bool) Status::is_development_site(),
226            'possibleDynamicSiteUrlDetected' => (bool) Identity_Crisis::detect_possible_dynamic_site_url(),
227        );
228    }
229
230    /**
231     * Get the current (logged-in) user's connection details.
232     *
233     * @param Manager $manager Connection manager instance.
234     * @return array|null Current user data or null if not connected.
235     */
236    private static function get_current_user_data( $manager ) {
237        $user_id = get_current_user_id();
238
239        if ( ! $user_id || ! $manager->is_user_connected( $user_id ) ) {
240            return null;
241        }
242
243        $user      = get_userdata( $user_id );
244        $user_info = static::resolve_user_fields( $user, $manager->get_connected_user_data( $user_id ) );
245        $is_owner  = $manager->is_connection_owner( $user_id );
246
247        $has_other_connected_users = false;
248        if ( $is_owner ) {
249            $connected_users           = $manager->get_connected_users( 'any', 2 );
250            $has_other_connected_users = count( $connected_users ) > 1;
251        }
252
253        return array_merge(
254            $user_info,
255            array(
256                'isOwner'                => $is_owner,
257                'hasOtherConnectedUsers' => $has_other_connected_users,
258            )
259        );
260    }
261
262    /**
263     * Get the connection owner details for the script module.
264     *
265     * @param Manager $manager Connection manager instance.
266     * @return array|null Owner data or null if unavailable.
267     */
268    private static function get_connection_owner_data( $manager ) {
269        $owner = $manager->get_connection_owner();
270
271        if ( false === $owner ) {
272            return null;
273        }
274
275        $fields = static::resolve_user_fields( $owner, $manager->get_connected_user_data( $owner->ID ) );
276
277        $fields['localLogin'] = $owner->user_login;
278
279        return $fields;
280    }
281
282    /**
283     * Merge local WP user fields with WordPress.com user data.
284     *
285     * WPCOM values take precedence when available. Returns the common
286     * user shape used by both currentUser and connectionOwner.
287     *
288     * @param \WP_User|false $wp_user        Local WordPress user object (false if unavailable).
289     * @param array|false    $wpcom_user_data WPCOM user data from the connection manager.
290     * @return array User data with displayName, login, email, and avatar.
291     */
292    private static function resolve_user_fields( $wp_user, $wpcom_user_data ) {
293        $display_name = $wp_user ? $wp_user->display_name : '';
294        $login        = $wp_user ? $wp_user->user_login : '';
295        $email        = $wp_user ? $wp_user->user_email : '';
296
297        if ( is_array( $wpcom_user_data ) ) {
298            if ( ! empty( $wpcom_user_data['display_name'] ) ) {
299                $display_name = $wpcom_user_data['display_name'];
300            }
301            if ( ! empty( $wpcom_user_data['login'] ) ) {
302                $login = $wpcom_user_data['login'];
303            }
304            if ( ! empty( $wpcom_user_data['email'] ) ) {
305                $email = $wpcom_user_data['email'];
306            }
307        }
308
309        $user_id = $wp_user ? $wp_user->ID : 0;
310
311        return array(
312            'displayName' => $display_name,
313            'login'       => $login,
314            'email'       => $email,
315            'avatar'      => $user_id
316                ? get_avatar_url(
317                    $user_id,
318                    array(
319                        'size'    => 48,
320                        'default' => 'mysteryman',
321                    )
322                )
323                : '',
324        );
325    }
326
327    /**
328     * Check whether the given screen is the Connectors settings page.
329     *
330     * Handles both WP 7.0 core (`options-connectors`) and the Gutenberg
331     * plugin (`settings_page_options-connectors-wp-admin`).
332     *
333     * @param \WP_Screen $screen Current admin screen.
334     * @return bool
335     */
336    private static function is_connectors_screen( $screen ) {
337        return 'options-connectors' === $screen->id
338            || static::GUTENBERG_CONNECTORS_SCREEN_ID === $screen->id;
339    }
340
341    /**
342     * Return the admin-relative path for the Connectors page.
343     *
344     * WP 7.0 core uses the standalone `options-connectors.php` file while
345     * the Gutenberg plugin registers a submenu page under options-general.php
346     * with slug `options-connectors-wp-admin`. Both set parent_file to
347     * `options-general.php` for menu highlighting, so we distinguish them by
348     * checking the actual script filename being served.
349     *
350     * Note: for the Gutenberg case we use the registered page slug directly,
351     * not `$screen->id`. WordPress auto-prefixes screen IDs for submenu pages
352     * (e.g. `settings_page_options-connectors-wp-admin`), so using `$screen->id`
353     * as the `page=` parameter produces an invalid URL.
354     *
355     * The result is suitable for the `redirect_uri` parameter accepted by the
356     * `jetpack/v4/connection/register` REST endpoint (which wraps it in `admin_url()`).
357     *
358     * @return string Admin-relative path, e.g. 'options-connectors.php'.
359     */
360    private static function get_connectors_page_path() {
361        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- only compared against a hardcoded string.
362        $script = isset( $_SERVER['SCRIPT_NAME'] ) ? wp_basename( wp_unslash( $_SERVER['SCRIPT_NAME'] ) ) : '';
363
364        if ( 'options-connectors.php' === $script ) {
365            return 'options-connectors.php';
366        }
367
368        // Gutenberg plugin registers the page under options-general.php.
369        $screen = get_current_screen();
370        if ( $screen && static::GUTENBERG_CONNECTORS_SCREEN_ID === $screen->id ) {
371            return 'options-general.php?page=' . static::GUTENBERG_CONNECTORS_PAGE_SLUG;
372        }
373
374        return 'options-connectors.php';
375    }
376
377    /**
378     * Store an authorization error in a short-lived transient.
379     *
380     * Hooked to `jetpack_client_authorize_error` which fires when
381     * the auth webhook fails. The transient is read on the next
382     * Connectors page load so the JS card can display the error.
383     *
384     * @since 8.2.0
385     *
386     * @param \WP_Error $error Authorization error.
387     */
388    public static function store_auth_error( $error ) {
389        if ( is_wp_error( $error ) ) {
390            $user_id = get_current_user_id();
391            if ( $user_id ) {
392                set_transient(
393                    'jetpack_connector_auth_error_' . $user_id,
394                    $error->get_error_message(),
395                    60
396                );
397            }
398        }
399    }
400
401    /**
402     * Read and delete a stored authorization error for the current user.
403     *
404     * @return string|false Error message or false if none.
405     */
406    private static function consume_auth_error() {
407        $user_id = get_current_user_id();
408        if ( ! $user_id ) {
409            return false;
410        }
411
412        $key   = 'jetpack_connector_auth_error_' . $user_id;
413        $error = get_transient( $key );
414        if ( false !== $error ) {
415            delete_transient( $key );
416        }
417
418        return $error;
419    }
420
421    /**
422     * Get connected plugins data for the script module.
423     *
424     * @param Manager $manager Connection manager instance.
425     * @return array List of connected plugin data.
426     */
427    private static function get_connected_plugins_data( $manager ) {
428        $plugins = $manager->get_connected_plugins();
429
430        if ( is_wp_error( $plugins ) || ! is_array( $plugins ) ) {
431            return array();
432        }
433
434        $result = array();
435
436        foreach ( $plugins as $slug => $plugin_data ) {
437            $name = $plugin_data['name'] ?? $slug;
438
439            $entry = array(
440                'name' => $name,
441                'slug' => $slug,
442            );
443
444            $logo_url = static::get_plugin_logo_url( $slug );
445            if ( $logo_url ) {
446                $entry['logoUrl'] = $logo_url;
447            }
448
449            $result[] = $entry;
450        }
451
452        return $result;
453    }
454
455    /**
456     * Detect which plugin families are using the connection.
457     *
458     * @since 8.5.0
459     *
460     * @return array{has_woo: bool, has_a4a: bool}
461     */
462    public static function get_connected_plugin_families() {
463        $plugins = Plugin_Storage::get_all();
464
465        $has_woo = false;
466        $has_a4a = false;
467
468        if ( is_array( $plugins ) ) {
469            foreach ( array_keys( $plugins ) as $slug ) {
470                if ( str_starts_with( $slug, 'woocommerce' ) ) {
471                    $has_woo = true;
472                }
473                if ( str_starts_with( $slug, 'automattic' ) ) {
474                    $has_a4a = true;
475                }
476            }
477        }
478
479        return array(
480            'has_woo' => $has_woo,
481            'has_a4a' => $has_a4a,
482        );
483    }
484
485    /**
486     * Determine the connector card logo based on which plugin families are connected.
487     *
488     * Priority:
489     * 1. Both Woo-family and A4A plugins → jetpack-connect-all.svg
490     * 2. Woo-family only                 → jetpack-connect-woo.svg
491     * 3. A4A only                        → jetpack-connect-a8c.svg
492     * 4. Default (Jetpack only or other) → jetpack-connect.svg
493     *
494     * @since 8.3.2
495     *
496     * @return string Logo URL.
497     */
498    public static function get_connector_logo_url() {
499        $families = self::get_connected_plugin_families();
500
501        if ( $families['has_woo'] && $families['has_a4a'] ) {
502            return plugins_url( 'images/jetpack-connect-all.svg', __FILE__ );
503        }
504
505        if ( $families['has_woo'] ) {
506            return plugins_url( 'images/jetpack-connect-woo.svg', __FILE__ );
507        }
508
509        if ( $families['has_a4a'] ) {
510            return plugins_url( 'images/jetpack-connect-a8c.svg', __FILE__ );
511        }
512
513        return plugins_url( 'images/jetpack-connect.svg', __FILE__ );
514    }
515
516    /**
517     * Get the inline (single-row) connector logo for use in compact contexts like table cells.
518     *
519     * All circles are arranged horizontally in a single row, unlike the card
520     * logos which stack circles vertically for 3+ plugins.
521     *
522     * @since 8.5.0
523     *
524     * @return string Logo URL.
525     */
526    public static function get_inline_connector_logo_url() {
527        $families = self::get_connected_plugin_families();
528
529        if ( $families['has_woo'] && $families['has_a4a'] ) {
530            return plugins_url( 'images/jetpack-connect-all-inline.svg', __FILE__ );
531        }
532
533        if ( $families['has_woo'] ) {
534            return plugins_url( 'images/jetpack-connect-woo-inline.svg', __FILE__ );
535        }
536
537        if ( $families['has_a4a'] ) {
538            return plugins_url( 'images/jetpack-connect-a8c-inline.svg', __FILE__ );
539        }
540
541        return plugins_url( 'images/jetpack-connect.svg', __FILE__ );
542    }
543
544    /**
545     * Map a plugin slug to a brand logo URL.
546     *
547     * Jetpack-family plugins get the Jetpack mark, WooCommerce-family
548     * plugins get the Woo mark, and Automattic for Agencies gets the
549     * Automattic mark. Unknown slugs fall through to the
550     * `jetpack_connection_plugin_logo_url` filter so that third-party
551     * plugins can register their own logo. Only SVG URLs are accepted
552     * to keep the icons sharp at every display density.
553     *
554     * @since 8.3.2
555     *
556     * @param string $slug Plugin slug.
557     * @return string|null Logo URL or null.
558     */
559    private static function get_plugin_logo_url( $slug ) {
560        if ( str_starts_with( $slug, 'jetpack' ) ) {
561            return plugins_url( 'images/jetpack-icon.svg', __FILE__ ); // str_starts_with() is polyfilled by WP since 5.9; this code only runs on WP 7.0+.
562        }
563
564        if ( str_starts_with( $slug, 'woocommerce' ) ) {
565            return plugins_url( 'images/woo-icon.svg', __FILE__ );
566        }
567
568        if ( str_starts_with( $slug, 'automattic' ) ) {
569            return plugins_url( 'images/automattic-icon.svg', __FILE__ );
570        }
571
572        /**
573         * Filters a map of plugin slugs to custom logo URLs for the
574         * Settings → Connectors card.
575         *
576         * Add entries as `$slug => $url` pairs. URLs must point to an
577         * SVG file (`.svg` extension required); non-SVG values are
578         * silently ignored and the generic fallback icon is shown.
579         *
580         * Example:
581         *
582         *     add_filter( 'jetpack_connection_plugin_logos', function ( $logos ) {
583         *         $logos['my-plugin'] = plugins_url( 'assets/logo.svg', __FILE__ );
584         *         return $logos;
585         *     } );
586         *
587         * @since 8.3.2
588         *
589         * @param array<string,string> $logos Map of plugin slug to SVG URL.
590         */
591        $logos = apply_filters( 'jetpack_connection_plugin_logos', array() );
592
593        if ( isset( $logos[ $slug ] ) && is_string( $logos[ $slug ] ) && str_ends_with( strtolower( $logos[ $slug ] ), '.svg' ) ) {
594            return esc_url( $logos[ $slug ] );
595        }
596
597        return null;
598    }
599}