Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
73.78% covered (warning)
73.78%
197 / 267
26.67% covered (danger)
26.67%
4 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Blaze
73.78% covered (warning)
73.78%
197 / 267
26.67% covered (danger)
26.67%
4 / 15
240.23
0.00% covered (danger)
0.00%
0 / 1
 init
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
7.07
 add_post_links_actions
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_dashboard_enabled
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 enable_blaze_menu
96.67% covered (success)
96.67%
29 / 30
0.00% covered (danger)
0.00%
0 / 1
7
 is_standalone_blaze_ads_active
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 get_menu_parent
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
11.30
 redirect_legacy_advertising_url
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 get_legacy_advertising_redirect_target
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
9.03
 site_supports_blaze
91.67% covered (success)
91.67%
22 / 24
0.00% covered (danger)
0.00%
0 / 1
10.06
 get_active_campaigns_status
97.37% covered (success)
97.37%
37 / 38
0.00% covered (danger)
0.00%
0 / 1
11
 get_unknown_active_campaigns_status
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 should_initialize
45.45% covered (danger)
45.45%
20 / 44
0.00% covered (danger)
0.00%
0 / 1
35.37
 get_campaign_management_url
62.96% covered (warning)
62.96%
17 / 27
0.00% covered (danger)
0.00%
0 / 1
4.81
 jetpack_blaze_row_action
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
42
 enqueue_block_editor_assets
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * Attract high-quality traffic to your site.
4 *
5 * @package automattic/jetpack-blaze
6 */
7
8namespace Automattic\Jetpack;
9
10use Automattic\Jetpack\Admin_UI\Admin_Menu;
11use Automattic\Jetpack\Blaze\Dashboard as Blaze_Dashboard;
12use Automattic\Jetpack\Blaze\Dashboard_REST_Controller as Blaze_Dashboard_REST_Controller;
13use Automattic\Jetpack\Blaze\REST_Controller;
14use Automattic\Jetpack\Connection\Client;
15use Automattic\Jetpack\Connection\Initial_State as Connection_Initial_State;
16use Automattic\Jetpack\Connection\Manager as Jetpack_Connection;
17use Automattic\Jetpack\Status\Host;
18use Automattic\Jetpack\Sync\Settings as Sync_Settings;
19use WP_Post;
20
21/**
22 * Class for promoting posts.
23 */
24class Blaze {
25    /**
26     * Script handle for the JS file we enqueue in the post editor.
27     *
28     * @var string
29     */
30    const SCRIPT_HANDLE = 'jetpack-promote-editor';
31
32    /**
33     * Transient prefix for active campaign status checks.
34     *
35     * @var string
36     */
37    const ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_PREFIX = 'jetpack_blaze_active_campaigns_status_';
38
39    /**
40     * Transient TTL for active campaign status checks that find campaigns.
41     *
42     * @var int
43     */
44    const ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_TTL = HOUR_IN_SECONDS;
45
46    /**
47     * Transient TTL for active campaign status checks that cannot determine campaign status.
48     *
49     * @var int
50     */
51    const UNKNOWN_ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_TTL = 5 * MINUTE_IN_SECONDS;
52
53    /**
54     * Minimum campaign statuses that should trigger a warning.
55     *
56     * @var string[]
57     */
58    const ACTIVE_CAMPAIGN_STATUSES = array( 'active' );
59
60    /**
61     * Path of the JS file we enqueue in the post editor.
62     *
63     * @var string
64     */
65    public static $script_path = '../build/editor.js';
66
67    /**
68     * Initializer.
69     * Used to configure the blaze package, eg when called via the Config package.
70     *
71     * @return void
72     */
73    public static function init() {
74        // On the edit screen, add a row action to promote the post.
75        add_action( 'load-edit.php', array( __CLASS__, 'add_post_links_actions' ) );
76        // After the quick-edit screen is processed, ensure the blaze row action is still present
77        if ( 'edit.php' === $GLOBALS['pagenow'] ||
78            // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verification is not needed here, we're not saving anything.
79            ( 'admin-ajax.php' === $GLOBALS['pagenow'] && ! empty( $_POST['post_view'] ) && 'list' === $_POST['post_view'] && ! empty( $_POST['action'] ) && 'inline-save' === $_POST['action'] ) ) {
80            self::add_post_links_actions();
81        }
82        // In the post editor, add a post-publish panel to allow promoting the post.
83        add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_block_editor_assets' ) );
84        // Add a Blaze Menu.
85        add_action( 'admin_menu', array( __CLASS__, 'enable_blaze_menu' ), 999 );
86        // Redirect legacy/duplicate advertising URLs (the old tools.php location, or the
87        // admin.php?page=advertising slug when the standalone Blaze Ads plugin owns the
88        // menu). Runs late (after WooCommerce and core register their menus, so
89        // get_menu_parent() resolves the real parent) but still before WordPress
90        // validates the page parameter.
91        add_action( 'admin_menu', array( __CLASS__, 'redirect_legacy_advertising_url' ), 999 );
92        // Add Blaze dashboard app REST API endpoints.
93        add_action( 'rest_api_init', array( Blaze_Dashboard_REST_Controller::class, 'register' ) );
94        // Add general Blaze REST API endpoints.
95        add_action( 'rest_api_init', array( REST_Controller::class, 'register' ) );
96    }
97
98    /**
99     * Add links under each published post in the wp-admin post list.
100     *
101     * @return void
102     */
103    public static function add_post_links_actions() {
104        if ( self::should_initialize()['can_init'] ) {
105            add_filter( 'post_row_actions', array( __CLASS__, 'jetpack_blaze_row_action' ), 10, 2 );
106            add_filter( 'page_row_actions', array( __CLASS__, 'jetpack_blaze_row_action' ), 10, 2 );
107        }
108    }
109
110    /**
111     * Is the wp-admin Dashboard enabled?
112     * That dashboard is not available or necessary on WordPress.com sites when the nav redesign is disabled.
113     *
114     * @return bool
115     */
116    public static function is_dashboard_enabled() {
117        $is_dashboard_enabled = true;
118
119        // On WordPress.com sites, the dashboard is not needed if the nav redesign is not enabled.
120        if ( get_option( 'wpcom_admin_interface' ) !== 'wp-admin' && ( new Host() )->is_wpcom_platform() ) {
121            $is_dashboard_enabled = false;
122        }
123
124        /**
125         * Enable a wp-admin dashboard for Blaze campaign management.
126         *
127         * @since 0.7.0
128         *
129         * @param bool $should_enable Should the dashboard be enabled?
130         */
131        return apply_filters( 'jetpack_blaze_dashboard_enable', $is_dashboard_enabled );
132    }
133
134    /**
135     * Enable the Blaze menu.
136     *
137     * @return void
138     */
139    public static function enable_blaze_menu() {
140        if ( ! self::should_initialize()['can_init'] ) {
141            return;
142        }
143
144        /**
145         * Filter the menu page slug used for the Blaze dashboard.
146         *
147         * @since 0.28.0
148         *
149         * @param string $menu_slug The menu page slug. Default 'advertising'.
150         */
151        $menu_slug = apply_filters( 'jetpack_blaze_menu_slug', 'advertising' );
152
153        // Avoid a duplicate Blaze Ads menu when the standalone Blaze Ads plugin
154        // (Automattic/blaze-ads) is also active. Releases <= 0.9.0 register their own
155        // menu and leave our slug at the default 'advertising', so we bail to avoid a
156        // second entry; the standalone owns the menu under 'wp-blaze' and
157        // redirect_legacy_advertising_url() forwards 'advertising' links there. When the
158        // standalone instead delegates registration to us by filtering the slug (e.g. to
159        // 'wp-blaze'), we are the only registrant and must register normally -- the
160        // non-default slug is what tells the two cases apart.
161        if ( 'advertising' === $menu_slug && self::is_standalone_blaze_ads_active() ) {
162            return;
163        }
164
165        /**
166         * Filter the menu label for the Blaze dashboard menu item.
167         *
168         * @since 0.28.0
169         *
170         * @param string $menu_label The menu label. Default 'Blaze Ads'.
171         */
172        $menu_label = apply_filters( 'jetpack_blaze_menu_label', 'Blaze Ads' ); // Product name, do not translate.
173
174        /**
175         * Filter the CSS class prefix for the Blaze dashboard.
176         *
177         * @since 0.28.0
178         *
179         * @param string $css_prefix The CSS class prefix. Default 'jp-blaze'.
180         */
181        $css_prefix = apply_filters( 'jetpack_blaze_dashboard_css_prefix', 'jp-blaze' );
182
183        $parent_slug     = self::get_menu_parent();
184        $blaze_dashboard = new Blaze_Dashboard( 'admin.php', $menu_slug, $css_prefix );
185
186        if ( self::is_dashboard_enabled() || ( new Host() )->is_wpcom_platform() ) {
187            if ( 'jetpack' === $parent_slug ) {
188                // Register through Admin_Menu: on WordPress.com Simple sites the Jetpack
189                // parent menu does not exist yet at this priority, and registering the
190                // submenu before its parent produces a broken menu URL.
191                $page_suffix = Admin_Menu::add_menu(
192                    esc_attr( $menu_label ),
193                    $menu_label,
194                    'manage_options',
195                    $menu_slug,
196                    array( $blaze_dashboard, 'render' ),
197                    null,
198                    // Not $menu_slug: that is filterable, and a host naming it would lose
199                    // the item the moment anything changed it.
200                    array( 'key' => 'jetpack-blaze' )
201                );
202            } else {
203                // Other parents already exist at this priority, so add_submenu_page is safe.
204                $page_suffix = add_submenu_page(
205                    $parent_slug,
206                    esc_attr( $menu_label ),
207                    $menu_label,
208                    'manage_options',
209                    $menu_slug,
210                    array( $blaze_dashboard, 'render' ),
211                    1
212                );
213            }
214            add_action( 'load-' . $page_suffix, array( $blaze_dashboard, 'admin_init' ) );
215        }
216    }
217
218    /**
219     * Detect whether the standalone Blaze Ads plugin (Automattic/blaze-ads) is active.
220     *
221     * Both this package and the standalone plugin can register a Blaze Ads menu, which
222     * would result in a duplicate entry when both are active on the same site (for
223     * example a WooCommerce store running Jetpack alongside the standalone plugin). When
224     * the standalone plugin is present it owns the menu, so this package defers to it.
225     *
226     * Detection relies on a class/constant defined by the standalone plugin rather than
227     * on any cooperation from it, so it works with every released version of the plugin,
228     * including ones that predate the jetpack_blaze_menu_* filters.
229     *
230     * @return bool True if the standalone Blaze Ads plugin is active.
231     */
232    public static function is_standalone_blaze_ads_active() {
233        $is_active = defined( 'BLAZEADS_PLUGIN_FILE' )
234            || defined( 'BLAZE_ADS_VERSION_NUMBER' )
235            || class_exists( 'Blaze_Ads' );
236
237        /**
238         * Filter whether the standalone Blaze Ads plugin (Automattic/blaze-ads) is
239         * considered active. When active and this package is still using the default
240         * menu slug, the package skips registering its own Blaze Ads menu to avoid a
241         * duplicate entry.
242         *
243         * @since 0.28.0
244         *
245         * @param bool $is_active Whether the standalone Blaze Ads plugin is active.
246         */
247        return (bool) apply_filters( 'jetpack_blaze_standalone_active', $is_active );
248    }
249
250    /**
251     * Determine the appropriate parent menu slug based on the installation context.
252     *
253     * - WooCommerce active (Marketing menu registered): parent is 'woocommerce-marketing'
254     * - WordPress.com platform or Jetpack connected: parent is 'jetpack'
255     * - Otherwise: parent is 'tools.php'
256     *
257     * @return string The parent menu slug.
258     */
259    public static function get_menu_parent() {
260        if ( class_exists( 'WooCommerce' ) ) {
261            // Only use woocommerce-marketing if the menu is actually registered.
262            global $menu;
263            foreach ( (array) $menu as $item ) {
264                if ( isset( $item[2] ) && 'woocommerce-marketing' === $item[2] ) {
265                    /**
266                     * Filter the parent menu slug for the Blaze dashboard submenu item.
267                     *
268                     * @since 0.28.0
269                     *
270                     * @param string $parent The parent menu slug.
271                     */
272                    return apply_filters( 'jetpack_blaze_menu_parent', 'woocommerce-marketing' );
273                }
274            }
275        }
276
277        if ( ( new Host() )->is_wpcom_platform() ) {
278            /** This filter is documented above. */
279            return apply_filters( 'jetpack_blaze_menu_parent', 'jetpack' );
280        }
281
282        if ( ( new Jetpack_Connection() )->is_connected() ) {
283            /** This filter is documented above. */
284            return apply_filters( 'jetpack_blaze_menu_parent', 'jetpack' );
285        }
286
287        /** This filter is documented above. */
288        return apply_filters( 'jetpack_blaze_menu_parent', 'tools.php' );
289    }
290
291    /**
292     * Redirect legacy/duplicate Blaze dashboard URLs to wherever the menu actually lives.
293     *
294     * Runs early on admin_menu, before WordPress validates the ?page= parameter against
295     * registered submenus. The target is computed by get_legacy_advertising_redirect_target();
296     * this method only performs the redirect.
297     *
298     * @return void
299     */
300    public static function redirect_legacy_advertising_url() {
301        $target = self::get_legacy_advertising_redirect_target();
302        if ( null !== $target ) {
303            wp_safe_redirect( $target, 302 );
304            exit;
305        }
306    }
307
308    /**
309     * Compute where a legacy/duplicate `page=advertising` request should be redirected, or
310     * null if it should be left alone. Pure (no side effects) so it is unit-testable.
311     *
312     * Two cases produce a redirect:
313     *
314     * - Standard move: `tools.php?page=advertising` -> `admin.php?page=advertising`, once the
315     *   menu has moved away from Tools.
316     * - Standalone Blaze Ads plugin present: this package does not register the 'advertising'
317     *   page (the standalone owns the menu under 'wp-blaze'), so BOTH the tools.php and the
318     *   admin.php `page=advertising` entry points are forwarded to the standalone's page. We
319     *   forward both ourselves rather than relying on the standalone shipping its own
320     *   redirect, so correctness never depends on a particular standalone release.
321     *
322     * @return string|null The redirect URL, or null if no redirect should happen.
323     */
324    public static function get_legacy_advertising_redirect_target() {
325        global $pagenow;
326
327        if (
328            ! isset( $_GET['page'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check to redirect, no data is processed.
329            || 'advertising' !== $_GET['page'] // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only check to redirect, no data is processed.
330        ) {
331            return null;
332        }
333
334        if ( ! self::should_initialize()['can_init'] ) {
335            return null;
336        }
337
338        if ( self::is_standalone_blaze_ads_active() ) {
339            // Only the two URLs that can carry the dashboard page parameter.
340            if ( 'admin.php' !== $pagenow && 'tools.php' !== $pagenow ) {
341                return null;
342            }
343            /**
344             * Filter the standalone Blaze Ads plugin's menu slug used as the redirect
345             * target when this package defers to it.
346             *
347             * @since 0.28.0
348             *
349             * @param string $standalone_slug The standalone menu slug. Default 'wp-blaze'.
350             */
351            $standalone_slug = apply_filters( 'jetpack_blaze_standalone_menu_slug', 'wp-blaze' );
352            return admin_url( 'admin.php?page=' . $standalone_slug );
353        }
354
355        if ( 'tools.php' !== $pagenow || 'tools.php' === self::get_menu_parent() ) {
356            return null;
357        }
358
359        /** This filter is documented in Blaze::enable_blaze_menu() */
360        $menu_slug = apply_filters( 'jetpack_blaze_menu_slug', 'advertising' );
361        return admin_url( 'admin.php?page=' . $menu_slug );
362    }
363
364    /**
365     * Check the WordPress.com REST API
366     * to ensure that the site supports the Blaze feature.
367     *
368     * - If the site is on WordPress.com Simple, we do not query the API.
369     * - Results are cached for a day after getting response from API.
370     * - If the API returns an error, we cache the result for an hour.
371     *
372     * @param int $blog_id The blog ID to check.
373     *
374     * @return bool
375     */
376    public static function site_supports_blaze( $blog_id ) {
377        $transient_name = 'jetpack_blaze_site_supports_blaze_' . $blog_id;
378
379        /*
380         * On WordPress.com, we don't need to make an API request,
381         * we can query directly.
382         */
383        if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'blaze_is_site_eligible' ) ) {
384            return blaze_is_site_eligible( $blog_id );
385        }
386
387        $cached_result = get_transient( $transient_name );
388        if ( false !== $cached_result ) {
389            if ( is_array( $cached_result ) ) {
390                return $cached_result['approved'];
391            }
392
393            return (bool) $cached_result;
394        }
395
396        // Make the API request.
397        $url      = sprintf( '/sites/%d/blaze/status', $blog_id );
398        $response = Client::wpcom_json_api_request_as_blog(
399            $url,
400            '2',
401            array( 'method' => 'GET' ),
402            null,
403            'wpcom'
404        );
405
406        // If there was an error or malformed response, bail and save response for an hour.
407        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
408            set_transient( $transient_name, array( 'approved' => false ), HOUR_IN_SECONDS );
409            return false;
410        }
411
412        // Decode the results.
413        $result = json_decode( wp_remote_retrieve_body( $response ), true );
414
415        // Bail if there were no results returned.
416        if ( ! is_array( $result ) || ! isset( $result['approved'] ) ) {
417            return false;
418        }
419
420        // Cache the result for 24 hours.
421        set_transient( $transient_name, array( 'approved' => (bool) $result['approved'] ), DAY_IN_SECONDS );
422
423        return (bool) $result['approved'];
424    }
425
426    /**
427     * Get the active campaign status for a site.
428     *
429     * @param int $blog_id The blog ID to check.
430     *
431     * @return array Active campaign status.
432     */
433    public static function get_active_campaigns_status( $blog_id ) {
434        $blog_id = absint( $blog_id );
435
436        if ( empty( $blog_id ) ) {
437            return self::get_unknown_active_campaigns_status();
438        }
439
440        $transient_name = self::ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_PREFIX . $blog_id;
441        $cached_result  = get_transient( $transient_name );
442
443        if ( false !== $cached_result ) {
444            return $cached_result;
445        }
446
447        /**
448         * Filter the campaign statuses that should trigger the active campaign warning.
449         *
450         * @since 0.27.23
451         *
452         * @param string[] $statuses Campaign statuses to check.
453         * @param int      $blog_id  The blog ID being checked.
454         */
455        $statuses = apply_filters( 'jetpack_blaze_active_campaign_statuses', self::ACTIVE_CAMPAIGN_STATUSES, $blog_id );
456        $statuses = array_filter( array_map( 'sanitize_key', (array) $statuses ) );
457
458        if ( empty( $statuses ) ) {
459            $statuses = self::ACTIVE_CAMPAIGN_STATUSES;
460        }
461
462        $url = add_query_arg(
463            array(
464                'status' => implode( ',', $statuses ),
465                'limit'  => 1,
466            ),
467            sprintf( '/sites/%d/wordads/dsp/api/v1/search/campaigns/site/%d', $blog_id, $blog_id )
468        );
469
470        $response = Client::wpcom_json_api_request_as_user(
471            $url,
472            '2',
473            array( 'method' => 'GET' ),
474            null,
475            'wpcom'
476        );
477
478        if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
479            return self::get_unknown_active_campaigns_status( $transient_name );
480        }
481
482        $result = json_decode( wp_remote_retrieve_body( $response ), true );
483
484        if ( ! is_array( $result ) || ! isset( $result['campaigns'] ) || ! is_array( $result['campaigns'] ) ) {
485            return self::get_unknown_active_campaigns_status( $transient_name );
486        }
487
488        $has_active_campaigns = ! empty( $result['campaigns'] );
489        $status               = array(
490            'has_active_campaigns' => $has_active_campaigns,
491            'status'               => $has_active_campaigns ? 'active' : 'none',
492        );
493
494        if ( $has_active_campaigns ) {
495            set_transient( $transient_name, $status, self::ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_TTL );
496        }
497
498        return $status;
499    }
500
501    /**
502     * Get the unknown active campaign status response.
503     *
504     * @param string|null $transient_name Optional transient name used to cache the unknown status.
505     * @return array Unknown active campaign status.
506     */
507    private static function get_unknown_active_campaigns_status( $transient_name = null ) {
508        $status = array(
509            'has_active_campaigns' => false,
510            'status'               => 'unknown',
511        );
512
513        if ( $transient_name ) {
514            set_transient( $transient_name, $status, self::UNKNOWN_ACTIVE_CAMPAIGNS_STATUS_TRANSIENT_TTL );
515        }
516
517        return $status;
518    }
519
520    /**
521     * Determines if criteria is met to enable Blaze features.
522     * Keep in mind that this makes remote requests, so we want to avoid calling it when unnecessary, like in the frontend.
523     *
524     * @return array
525     */
526    public static function should_initialize() {
527        $is_wpcom   = defined( 'IS_WPCOM' ) && IS_WPCOM;
528        $connection = new Jetpack_Connection();
529        $site_id    = Jetpack_Connection::get_site_id();
530
531        // Only admins should be able to Blaze posts on a site.
532        if ( ! current_user_can( 'manage_options' ) ) {
533            return array(
534                'can_init' => false,
535                'reason'   => 'user_not_admin',
536            );
537        }
538
539        // Allow short-circuiting the Blaze initialization via a filter.
540        if ( has_filter( 'jetpack_blaze_enabled' ) ) {
541            /**
542             * Filter to disable all Blaze functionality.
543             *
544             * @since 0.3.0
545             *
546             * @param bool $should_initialize Whether Blaze should be enabled. Default to true.
547             */
548            $should_init = apply_filters( 'jetpack_blaze_enabled', true );
549
550            return array(
551                'can_init' => $should_init,
552                'reason'   => $should_init ? null : 'initialization_disabled',
553            );
554        }
555
556        // On self-hosted sites, we must do some additional checks.
557        if ( ! $is_wpcom ) {
558            /*
559            * These features currently only work on WordPress.com,
560            * so the site must be connected to WordPress.com, and the user as well for things to work.
561            */
562            if (
563                is_wp_error( $site_id )
564            ) {
565                return array(
566                    'can_init' => false,
567                    'reason'   => 'wp_error',
568                );
569            }
570
571            if ( ! $connection->is_connected() ) {
572                return array(
573                    'can_init' => false,
574                    'reason'   => 'site_not_connected',
575                );
576            }
577
578            if ( ! $connection->is_user_connected() ) {
579                return array(
580                    'can_init' => false,
581                    'reason'   => 'user_not_connected',
582                );
583            }
584
585            // The whole thing is powered by Sync!
586            if ( ! Sync_Settings::is_sync_enabled() ) {
587                return array(
588                    'can_init' => false,
589                    'reason'   => 'sync_disabled',
590                );
591            }
592        }
593
594        // Check if the site supports Blaze.
595        if ( is_numeric( $site_id ) && ! self::site_supports_blaze( $site_id ) ) {
596            return array(
597                'can_init' => false,
598                'reason'   => 'site_not_eligible',
599            );
600        }
601
602        // Final fallback.
603        return array(
604            'can_init' => true,
605            'reason'   => null,
606        );
607    }
608
609    /**
610     * Get URL to create a Blaze campaign for a specific post.
611     *
612     * This can return 2 different types of URL:
613     * - Calypso Links
614     * - wp-admin Links if access to the wp-admin Blaze Dashboard is enabled.
615     *
616     * @param int|string $post_id Post ID.
617     *
618     * @return array An array with the link, and whether this is a Calypso or a wp-admin link.
619     */
620    public static function get_campaign_management_url( $post_id ) {
621        if ( self::is_dashboard_enabled() ) {
622            /** This filter is documented in Blaze::enable_blaze_menu() */
623            $menu_slug = apply_filters( 'jetpack_blaze_menu_slug', 'advertising' );
624
625            // When the standalone Blaze Ads plugin owns the menu under its own slug and
626            // this package did not register 'advertising', point the link straight at the
627            // standalone's page. Relying on the admin.php?page=advertising redirect would
628            // drop the #! route fragment and land the user on the dashboard home instead
629            // of the specific post's promotion flow.
630            if ( 'advertising' === $menu_slug && self::is_standalone_blaze_ads_active() ) {
631                /** This filter is documented in Blaze::redirect_legacy_advertising_url() */
632                $menu_slug = apply_filters( 'jetpack_blaze_standalone_menu_slug', 'wp-blaze' );
633            }
634
635            $admin_url = admin_url( 'admin.php?page=' . $menu_slug );
636            $hostname  = wp_parse_url( get_site_url(), PHP_URL_HOST );
637            // The dashboard SPA routes under its menu slug (see Dashboard), so the #! path
638            // prefix must match the slug rather than being hardcoded to 'advertising'.
639            $blaze_url = sprintf(
640                '%1$s#!/%2$s/posts/promote/post-%3$s/%4$s',
641                $admin_url,
642                $menu_slug,
643                esc_attr( $post_id ),
644                $hostname
645            );
646
647            return array(
648                'link'     => $blaze_url,
649                'external' => false,
650            );
651        }
652
653        // Default Calypso link.
654        $blaze_url = Redirect::get_url(
655            'jetpack-blaze',
656            array(
657                'query' => 'blazepress-widget=post-' . esc_attr( $post_id ),
658            )
659        );
660        return array(
661            'link'     => $blaze_url,
662            'external' => true,
663        );
664    }
665
666    /**
667     * Adds the Promote link to the posts list row action.
668     *
669     * @param array   $post_actions The current array of post actions.
670     * @param WP_Post $post The current post in the post list table.
671     *
672     * @return array
673     */
674    public static function jetpack_blaze_row_action( $post_actions, $post ) {
675        /**
676         * Allow third-party plugins to disable Blaze row actions.
677         *
678         * @since 0.16.0
679         *
680         * @param bool    $are_quick_links_enabled Should Blaze row actions be enabled.
681         * @param WP_Post $post                    The current post in the post list table.
682         */
683        $are_quick_links_enabled = apply_filters( 'jetpack_blaze_post_row_actions_enable', true, $post );
684
685        // Bail if we are not looking at one of the supported post types (post, page, or product).
686        if (
687            ! $are_quick_links_enabled
688            || ! in_array( $post->post_type, array( 'post', 'page', 'product' ), true )
689        ) {
690            return $post_actions;
691        }
692
693        // Bail if the post is not published.
694        if ( $post->post_status !== 'publish' ) {
695            return $post_actions;
696        }
697
698        // Bail if the post has a password.
699        if ( '' !== $post->post_password ) {
700            return $post_actions;
701        }
702
703        $blaze_url = self::get_campaign_management_url( $post->ID );
704        $text      = __( 'Promote with Blaze', 'jetpack-blaze' );
705        $title     = get_the_title( $post );
706        $label     = sprintf(
707            /* translators: post title */
708            __( 'Blaze &#8220;%s&#8221; to Tumblr and WordPress.com audiences.', 'jetpack-blaze' ),
709            $title
710        );
711
712        $post_actions['blaze'] = sprintf(
713            '<a href="%1$s" title="%2$s" aria-label="%2$s" %4$s>%3$s</a>',
714            esc_url( $blaze_url['link'] ),
715            esc_attr( $label ),
716            esc_html( $text ),
717            ( true === $blaze_url['external'] ? 'target="_blank" rel="noopener noreferrer"' : '' )
718        );
719
720        return $post_actions;
721    }
722
723    /**
724     * Enqueue block editor assets.
725     */
726    public static function enqueue_block_editor_assets() {
727        /*
728         * We do not want (nor need) Blaze in the site editor, or the widget editor, or the classic editor.
729         * We only want it in the post editor.
730         * Enqueueing the script in those editors would cause a fatal error.
731         * See #20357 for more info.
732        */
733        if ( ! function_exists( 'get_current_screen' ) ) { // When Gutenberg is loaded in the frontend.
734            return;
735        }
736        $current_screen = get_current_screen();
737        if (
738            empty( $current_screen )
739            || $current_screen->base !== 'post'
740            || ! $current_screen->is_block_editor()
741        ) {
742            return;
743        }
744        // Bail if criteria is not met to enable Blaze features.
745        if ( ! self::should_initialize()['can_init'] ) {
746            return;
747        }
748
749        Assets::register_script(
750            self::SCRIPT_HANDLE,
751            self::$script_path,
752            __FILE__,
753            array(
754                'enqueue'    => true,
755                'in_footer'  => true,
756                'textdomain' => 'jetpack-blaze',
757            )
758        );
759
760        // Adds Connection package initial state.
761        Connection_Initial_State::render_script( self::SCRIPT_HANDLE );
762
763        // Pass additional data to our script.
764        wp_localize_script(
765            self::SCRIPT_HANDLE,
766            'blazeInitialState',
767            array(
768                'blazeUrlTemplate' => self::get_campaign_management_url( '__POST_ID__' ),
769            )
770        );
771    }
772}