Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 115
0.00% covered (danger)
0.00%
0 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Newsletter_Dashboard_Widget
0.00% covered (danger)
0.00%
0 / 108
0.00% covered (danger)
0.00%
0 / 5
812
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_config_data
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
210
 wp_dashboard_setup
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 render
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
2
 load_admin_scripts
0.00% covered (danger)
0.00%
0 / 47
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2/**
3 * Jetpack Newsletter Dashboard Widget.
4 *
5 * @package jetpack
6 */
7
8use Automattic\Jetpack\Modules;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14require_once __DIR__ . '/../class-jetpack-subscriber-data.php';
15
16/**
17 * Class that adds the Jetpack Newsletter Dashboard Widget to the WordPress admin dashboard.
18 */
19class Jetpack_Newsletter_Dashboard_Widget {
20    /**
21     * Indicates whether the class initialized or not.
22     *
23     * @var bool
24     */
25    private static $initialized = false;
26
27    /**
28     * The Widget ID.
29     *
30     * @var string
31     */
32    private static $widget_id = 'jetpack_newsletter_dashboard_widget';
33
34    /**
35     * Initialize the class by calling the setup static function.
36     *
37     * @return void
38     */
39    public static function init() {
40        if ( ! self::$initialized ) {
41            self::$initialized = true;
42            self::wp_dashboard_setup();
43        }
44    }
45
46    /**
47     * Get the config data for the Jetpack Newsletter widget.
48     *
49     * @return array
50     */
51    public static function get_config_data() {
52        $config_data = array(
53            'emailSubscribers'       => 0,
54            'paidSubscribers'        => 0,
55            'allSubscribers'         => 0,
56            'subscriberTotalsByDate' => array(),
57            'isStatsModuleActive'    => false,
58            'showHeader'             => false,
59            'showChart'              => false,
60            'isWidgetVisible'        => false,
61            'newsletterSettingsUrl'  => \Automattic\Jetpack\Newsletter\Urls::get_newsletter_settings_url(),
62        );
63
64        if ( Jetpack::is_connection_ready() ) {
65            $subscriber_counts = Jetpack_Subscriber_Data::get_stats();
66
67            if ( ! is_wp_error( $subscriber_counts ) ) {
68                if ( isset( $subscriber_counts['counts']['email_subscribers'] ) ) {
69                    $config_data['emailSubscribers'] = (int) $subscriber_counts['counts']['email_subscribers'];
70                }
71
72                if ( isset( $subscriber_counts['counts']['paid_subscribers'] ) ) {
73                    $config_data['paidSubscribers'] = (int) $subscriber_counts['counts']['paid_subscribers'];
74                }
75
76                if ( isset( $subscriber_counts['counts']['all_subscribers'] ) ) {
77                    $config_data['allSubscribers'] = (int) $subscriber_counts['counts']['all_subscribers'];
78                }
79
80                if ( isset( $subscriber_counts['aggregate'] ) ) {
81                    $config_data['subscriberTotalsByDate'] = $subscriber_counts['aggregate'];
82                }
83            }
84
85            $config_data['isStatsModuleActive'] = ( new Modules() )->is_active( 'stats' );
86
87            $config_data['showHeader'] = $config_data['isStatsModuleActive'] && ( $config_data['allSubscribers'] > 0 || $config_data['paidSubscribers'] > 0 );
88            foreach ( $config_data['subscriberTotalsByDate'] as $day ) {
89                if ( $day && ( $day['all'] >= 5 || $day['paid'] > 0 ) ) {
90                    $config_data['showChart'] = true;
91                    break;
92                }
93            }
94
95            $config_data['isWidgetVisible'] = $config_data['showHeader'] || $config_data['showChart'];
96        }
97
98        return $config_data;
99    }
100
101    /**
102     * Sets up the Jetpack Newsletter widget in the WordPress admin dashboard.
103     */
104    public static function wp_dashboard_setup() {
105        // Do not show the widget to non-admins.
106        if ( ! current_user_can( 'manage_options' ) ) {
107            return;
108        }
109
110        if ( Jetpack::is_connection_ready() ) {
111            $config_data = static::get_config_data();
112
113            if ( ! $config_data['isWidgetVisible'] ) {
114                return;
115            }
116
117            static::load_admin_scripts(
118                'jp-newsletter-widget',
119                'newsletter-widget',
120                array(
121                    'config_variable_name' => 'jetpackNewsletterWidgetConfigData',
122                    'config_data'          => $config_data,
123                    'load_minified_js'     => false,
124                )
125            );
126
127            wp_add_dashboard_widget(
128                self::$widget_id,
129                /** "Newsletter" is a product name, do not translate. */
130                'Jetpack Newsletter',
131                array( static::class, 'render' ),
132                // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- Core should ideally document null for no-callback arg. https://core.trac.wordpress.org/ticket/52539.
133                null,
134                array(),
135                'side',
136                'high'
137            );
138        }
139    }
140
141    /**
142     * Render the Jetpack Newsletter widget.
143     *
144     * @return void
145     */
146    public static function render() {
147        ?>
148        <div id="wpcom">
149            <div id="newsletter-widget-app"></div>
150        </div>
151        <?php
152    }
153
154    /**
155     * Load the admin scripts for the Jetpack Newsletter widget.
156     *
157     * @param string $asset_handle The handle of the asset.
158     * @param string $asset_name The name of the asset.
159     * @param array  $options The options for the asset.
160     * @return void
161     */
162    public static function load_admin_scripts( $asset_handle, $asset_name, $options = array() ) {
163        $default_options = array(
164            'config_data'          => array(),
165            'config_variable_name' => 'configData',
166            'enqueue_css'          => true,
167            'load_minified_js'     => true,
168        );
169        $options         = wp_parse_args( $options, $default_options );
170
171        /*
172         * Get the asset file path. The widget is built unminified (see tools/webpack.config.js),
173         * so read the matching non-minified asset metadata.
174         */
175        $asset_path = JETPACK__PLUGIN_DIR . '_inc/build/' . $asset_name . '.asset.php';
176
177        // Get dependencies and version from asset file
178        $dependencies = array();
179        $version      = JETPACK__VERSION;
180
181        if ( file_exists( $asset_path ) ) {
182            $asset        = require $asset_path;
183            $dependencies = $asset['dependencies'];
184            $version      = $asset['version'];
185        }
186
187        $file_extension = '.min.js';
188        if ( ! $options['load_minified_js'] ) {
189            $file_extension = '.js';
190        }
191        // Register and enqueue the script
192        wp_register_script(
193            $asset_handle,
194            plugins_url( '_inc/build/' . $asset_name . $file_extension, JETPACK__PLUGIN_FILE ),
195            $dependencies,
196            $version,
197            true
198        );
199        wp_enqueue_script( $asset_handle );
200        if ( in_array( 'wp-i18n', $dependencies, true ) ) {
201            wp_set_script_translations( $asset_handle, 'jetpack' );
202        }
203
204        // Enqueue the CSS if enabled
205        if ( $options['enqueue_css'] ) {
206            wp_enqueue_style(
207                $asset_handle,
208                plugins_url( '_inc/build/' . $asset_name . '.css', JETPACK__PLUGIN_FILE ),
209                array(),
210                $version
211            );
212
213            // Enqueue RTL stylesheet if needed
214            if ( is_rtl() ) {
215                wp_enqueue_style(
216                    $asset_handle . '-rtl',
217                    plugins_url( '_inc/build/' . $asset_name . '.rtl.css', JETPACK__PLUGIN_FILE ),
218                    array( $asset_handle ),
219                    $version
220                );
221            }
222        }
223
224        // Add any configuration data if needed
225        if ( ! empty( $options['config_data'] ) ) {
226            wp_add_inline_script(
227                $asset_handle,
228                "window.{$options['config_variable_name']} = " . wp_json_encode( $options['config_data'], JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';',
229                'before'
230            );
231        }
232    }
233}
234
235add_action(
236    'wp_dashboard_setup',
237    array( 'Jetpack_Newsletter_Dashboard_Widget', 'init' )
238);