Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
86.35% covered (warning)
86.35%
253 / 293
80.00% covered (warning)
80.00%
12 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Newsletter_Abilities
87.24% covered (warning)
87.24%
253 / 290
80.00% covered (warning)
80.00%
12 / 15
61.28
0.00% covered (danger)
0.00%
0 / 1
 enabled_by_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
129 / 129
100.00% covered (success)
100.00%
1 / 1
1
 can_view_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_manage_settings
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_settings
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 get_subscriber_stats
20.93% covered (danger)
20.93%
9 / 43
0.00% covered (danger)
0.00%
0 / 1
96.54
 update_settings
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
9
 settings_map
100.00% covered (success)
100.00%
29 / 29
100.00% covered (success)
100.00%
1 / 1
1
 current_settings
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 read_option
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 normalize_input_value
93.75% covered (success)
93.75%
30 / 32
0.00% covered (danger)
0.00%
0 / 1
15.05
 cast_to_response
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
6.10
 invalid_field
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Jetpack Newsletter Abilities Registration
4 *
5 * Registers Jetpack Newsletter (subscriptions) abilities with the WordPress
6 * Abilities API.
7 *
8 * @package automattic/jetpack
9 */
10
11namespace Automattic\Jetpack\Plugin\Abilities;
12
13use Automattic\Jetpack\Connection\Client;
14use Automattic\Jetpack\Modules\Subscriptions\Settings as Subscriptions_Settings;
15use Automattic\Jetpack\WP_Abilities\Registrar;
16use Jetpack;
17use Jetpack_Options;
18
19if ( ! defined( 'ABSPATH' ) ) {
20    exit( 0 );
21}
22
23// The Subscriptions module doesn't load its Settings helpers eagerly. Pull it
24// in here so `Subscriptions_Settings::$default_reply_to` and
25// `is_valid_reply_to()` are resolvable when the abilities run.
26require_once __DIR__ . '/../class-settings.php';
27
28/**
29 * Registers Jetpack Newsletter abilities with the WordPress Abilities API.
30 *
31 * Exposes a consolidated read of the site's newsletter (subscriptions) settings
32 * and a partial-update writer so AI agents can configure the Newsletter module
33 * through the standard `wp-abilities/v1` REST surface.
34 */
35class Newsletter_Abilities extends Registrar {
36
37    // Field type tags used in `settings_map()`. Constants (not strings) so a
38    // typo in a `case` label fails fast instead of silently falling through.
39    private const TYPE_BOOL   = 'bool';
40    private const TYPE_ON_OFF = 'on_off';
41    private const TYPE_ENUM   = 'enum';
42    private const TYPE_STRING = 'string';
43
44    /**
45     * Allowed values for the `reply_to` setting. Mirror of
46     * `Subscriptions_Settings::is_valid_reply_to()` — kept here so it can be
47     * referenced from the JSON Schema enum without loading the Settings class
48     * at file-parse time.
49     */
50    private const REPLY_TO_VALUES = array( 'comment', 'author', 'no-reply' );
51
52    /**
53     * {@inheritDoc}
54     */
55    protected static function enabled_by_default(): bool {
56        return true;
57    }
58
59    /**
60     * Returns the abilities category, definition, or registered abilities.
61     *
62     * @inheritDoc
63     */
64    public static function get_category_slug(): string {
65        return 'jetpack-newsletter';
66    }
67
68    /**
69     * Returns the abilities category, definition, or registered abilities.
70     *
71     * @inheritDoc
72     */
73    public static function get_category_definition(): array {
74        return array(
75            // "Jetpack" and "Newsletter" are product names and should not be translated.
76            'label'       => 'Jetpack Newsletter',
77            'description' => __( 'Abilities for reading and updating Jetpack Newsletter settings.', 'jetpack' ),
78        );
79    }
80
81    /**
82     * Returns the abilities category, definition, or registered abilities.
83     *
84     * @inheritDoc
85     */
86    public static function get_abilities(): array {
87        $settings_object_schema = array(
88            'type'                 => 'object',
89            'additionalProperties' => false,
90            'properties'           => array(
91                'subscribe_post_end_enabled' => array(
92                    'type'        => 'boolean',
93                    'description' => __( 'Add a Subscribe block at the end of every post. Default false.', 'jetpack' ),
94                ),
95                'subscribe_comments_enabled' => array(
96                    'type'        => 'boolean',
97                    'description' => __( 'Show a "notify me of new comments" checkbox in the comment form. Default true.', 'jetpack' ),
98                ),
99                'notify_admin_on_subscribe'  => array(
100                    'type'        => 'boolean',
101                    'description' => __( 'Email the site admin whenever a new subscriber signs up. Default true.', 'jetpack' ),
102                ),
103                'reply_to'                   => array(
104                    'type'        => 'string',
105                    'enum'        => self::REPLY_TO_VALUES,
106                    'description' => __( 'Reply-to address for newsletter emails. "comment" routes to the post comment author, "author" to the post author, "no-reply" disables replies. Default "comment".', 'jetpack' ),
107                ),
108                'from_name'                  => array(
109                    'type'        => 'string',
110                    'description' => __( 'Sender name shown on newsletter emails. Empty string falls back to the site name.', 'jetpack' ),
111                    'maxLength'   => 200,
112                ),
113            ),
114        );
115
116        return array(
117            'jetpack-newsletter/get-settings'         => array(
118                'label'               => __( 'Get Newsletter settings', 'jetpack' ),
119                'description'         => __(
120                    'Return the current Jetpack Newsletter settings as a flat object. Always returns the same five fields: subscribe_post_end_enabled (bool), subscribe_comments_enabled (bool), notify_admin_on_subscribe (bool), reply_to ("comment"|"author"|"no-reply"), and from_name (string). Read-only and idempotent. To change any value, call jetpack-newsletter/update-settings.',
121                    'jetpack'
122                ),
123                'input_schema'        => array(
124                    'type'                 => 'object',
125                    'default'              => array(),
126                    'properties'           => array(),
127                    'additionalProperties' => false,
128                ),
129                'output_schema'       => $settings_object_schema,
130                'execute_callback'    => array( __CLASS__, 'get_settings' ),
131                'permission_callback' => array( __CLASS__, 'can_view_settings' ),
132                'meta'                => array(
133                    'annotations'  => array(
134                        'readonly'    => true,
135                        'destructive' => false,
136                        'idempotent'  => true,
137                    ),
138                    'public'       => true,
139                    'show_in_rest' => true,
140                    'mcp'          => array(
141                        'public' => true,
142                        'type'   => 'tool', // default is already "tool", but can be explicit.
143                    ),
144                ),
145            ),
146
147            'jetpack-newsletter/update-settings'      => array(
148                'label'               => __( 'Update Newsletter settings', 'jetpack' ),
149                'description'         => __(
150                    'Update one or more Jetpack Newsletter settings. Any subset of the five fields may be supplied; omitted fields are left untouched. Idempotent — fields whose desired value already matches the current value are not rewritten. Returns { settings: <full current state after the update>, changed: <array of field names that actually transitioned> }. An empty input or input matching the current state returns changed = [].',
151                    'jetpack'
152                ),
153                'input_schema'        => $settings_object_schema,
154                'output_schema'       => array(
155                    'type'       => 'object',
156                    'properties' => array(
157                        'settings' => $settings_object_schema,
158                        'changed'  => array(
159                            'type'        => 'array',
160                            'items'       => array( 'type' => 'string' ),
161                            'description' => __( 'Names of the fields that actually changed during this call. Empty when the call was a no-op.', 'jetpack' ),
162                        ),
163                    ),
164                ),
165                'execute_callback'    => array( __CLASS__, 'update_settings' ),
166                'permission_callback' => array( __CLASS__, 'can_manage_settings' ),
167                'meta'                => array(
168                    'annotations'  => array(
169                        'readonly'    => false,
170                        'destructive' => false,
171                        'idempotent'  => true,
172                    ),
173                    'public'       => true,
174                    'show_in_rest' => true,
175                    'mcp'          => array(
176                        'public' => true,
177                        'type'   => 'tool', // default is already "tool", but can be explicit.
178                    ),
179                ),
180            ),
181
182            'jetpack-newsletter/get-subscriber-stats' => array(
183                'label'               => __( 'Get Newsletter subscriber stats', 'jetpack' ),
184                'description'         => __(
185                    'Return aggregate subscriber counts for the site. Always returns { all: int, email: int, paid: int }: all is the total subscriber count (email + WordPress.com followers); email is the subset that receives email; paid is the subset on a paid newsletter plan. Numbers are fetched from WordPress.com and cached locally for one hour, so transient network errors yield a stale-but-non-zero response when one is available. Requires an active Jetpack connection — sites without one return jetpack_newsletter_not_connected.',
186                    'jetpack'
187                ),
188                'input_schema'        => array(
189                    'type'                 => 'object',
190                    'default'              => array(),
191                    'properties'           => array(),
192                    'additionalProperties' => false,
193                ),
194                'output_schema'       => array(
195                    'type'       => 'object',
196                    'properties' => array(
197                        'all'   => array( 'type' => 'integer' ),
198                        'email' => array( 'type' => 'integer' ),
199                        'paid'  => array( 'type' => 'integer' ),
200                    ),
201                ),
202                'execute_callback'    => array( __CLASS__, 'get_subscriber_stats' ),
203                'permission_callback' => array( __CLASS__, 'can_view_settings' ),
204                'meta'                => array(
205                    'annotations'  => array(
206                        'readonly'    => true,
207                        'destructive' => false,
208                        'idempotent'  => true,
209                    ),
210                    'public'       => true,
211                    'show_in_rest' => true,
212                    'mcp'          => array(
213                        'public' => true,
214                        'type'   => 'tool', // default is already "tool", but can be explicit.
215                    ),
216                ),
217            ),
218        );
219    }
220
221    /**
222     * Permission check for read abilities. Newsletter settings live on the WP
223     * Newsletter settings screen, which is itself gated on `manage_options`.
224     */
225    public static function can_view_settings(): bool {
226        return current_user_can( 'manage_options' );
227    }
228
229    /**
230     * Permission check for write abilities. Mirrors the gating on the
231     * Newsletter settings screen.
232     */
233    public static function can_manage_settings(): bool {
234        return current_user_can( 'manage_options' );
235    }
236
237    /**
238     * Execute: return the current newsletter settings.
239     *
240     * @param array|null $input Unused — input schema accepts no parameters.
241     * @return array
242     */
243    public static function get_settings( $input = null ): array {
244        unset( $input );
245        return self::current_settings();
246    }
247
248    /**
249     * Transient key for the wpcom subscriber-stats response.
250     */
251    private const SUBSCRIBER_STATS_CACHE_KEY = 'jetpack_newsletter_subscriber_stats';
252
253    /**
254     * Transient TTL for subscriber-stats responses, in seconds.
255     *
256     * Matches the existing legacy widget pattern of an hour-long cache so
257     * agents calling this ability repeatedly don't fan out to wpcom.
258     */
259    private const SUBSCRIBER_STATS_CACHE_TTL = HOUR_IN_SECONDS;
260
261    /**
262     * Execute: fetch (and cache) aggregate subscriber counts from WordPress.com.
263     *
264     * @param array|null $input Unused — input schema accepts no parameters.
265     * @return array|\WP_Error
266     */
267    public static function get_subscriber_stats( $input = null ) {
268        unset( $input );
269
270        $cached = get_transient( self::SUBSCRIBER_STATS_CACHE_KEY );
271        if ( is_array( $cached ) ) {
272            return $cached;
273        }
274
275        if ( ! class_exists( 'Jetpack' ) || ! Jetpack::is_connection_ready() ) {
276            return new \WP_Error(
277                'jetpack_newsletter_not_connected',
278                __( 'Subscriber stats are only available on Jetpack-connected sites. Connect Jetpack and retry.', 'jetpack' )
279            );
280        }
281
282        $site_id = (int) Jetpack_Options::get_option( 'id' );
283        if ( $site_id <= 0 ) {
284            return new \WP_Error(
285                'jetpack_newsletter_not_connected',
286                __( 'No Jetpack site ID is registered. Connect Jetpack and retry.', 'jetpack' )
287            );
288        }
289
290        $response = Client::wpcom_json_api_request_as_blog(
291            sprintf( '/sites/%d/subscribers/stats', $site_id ),
292            '2',
293            array(),
294            null,
295            'wpcom'
296        );
297
298        if ( is_wp_error( $response ) ) {
299            return new \WP_Error(
300                'jetpack_newsletter_subscriber_stats_unavailable',
301                $response->get_error_message()
302            );
303        }
304
305        if ( 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
306            return new \WP_Error(
307                'jetpack_newsletter_subscriber_stats_unavailable',
308                __( 'WordPress.com did not return subscriber stats. Retry shortly.', 'jetpack' )
309            );
310        }
311
312        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
313        $counts = is_array( $body ) && isset( $body['counts'] ) && is_array( $body['counts'] )
314            ? $body['counts']
315            : array();
316
317        $stats = array(
318            'all'   => isset( $counts['all_subscribers'] ) ? (int) $counts['all_subscribers'] : 0,
319            'email' => isset( $counts['email_subscribers'] ) ? (int) $counts['email_subscribers'] : 0,
320            'paid'  => isset( $counts['paid_subscribers'] ) ? (int) $counts['paid_subscribers'] : 0,
321        );
322
323        set_transient( self::SUBSCRIBER_STATS_CACHE_KEY, $stats, self::SUBSCRIBER_STATS_CACHE_TTL );
324
325        return $stats;
326    }
327
328    /**
329     * Execute: idempotent partial update of newsletter settings.
330     *
331     * Validates every supplied field before writing anything, so a malformed
332     * field cannot leave the option set in a partially-updated state.
333     *
334     * @param array|null $input Input matching the ability's input_schema.
335     * @return array|\WP_Error
336     */
337    public static function update_settings( $input = null ) {
338        $input = is_array( $input ) ? $input : array();
339        $map   = self::settings_map();
340
341        // Validate + normalize every supplied field up-front. Any failure
342        // short-circuits the call with no writes, so a bad field can't leave
343        // earlier fields in a partially-updated state.
344        $normalized = array();
345        foreach ( $map as $field => $config ) {
346            if ( ! array_key_exists( $field, $input ) ) {
347                continue;
348            }
349
350            $result = self::normalize_input_value( $field, $config, $input[ $field ] );
351            if ( $result instanceof \WP_Error ) {
352                return $result;
353            }
354            $normalized[ $field ] = $result;
355        }
356
357        // Read every field's current value once. This pass also feeds the
358        // post-update response, avoiding a second `get_option` sweep.
359        $current_storage = array();
360        foreach ( $map as $field => $config ) {
361            $current_storage[ $field ] = self::read_option( $config );
362        }
363
364        $changed = array();
365        foreach ( $normalized as $field => $desired ) {
366            // String-cast on both sides because every field's storage form is
367            // scalar (`0`/`1` for BOOL, `'on'`/`'off'` for ON_OFF, plain strings
368            // for ENUM/STRING). New field types added later must keep that
369            // invariant or this comparison will misfire.
370            if ( (string) $desired === (string) $current_storage[ $field ] ) {
371                continue;
372            }
373            update_option( $map[ $field ]['option'], $desired );
374            $current_storage[ $field ] = $desired;
375            $changed[]                 = $field;
376        }
377
378        $settings = array();
379        foreach ( $map as $field => $config ) {
380            $settings[ $field ] = self::cast_to_response( $config, $current_storage[ $field ] );
381        }
382
383        return array(
384            'settings' => $settings,
385            'changed'  => $changed,
386        );
387    }
388
389    /**
390     * Map of public ability field name → backing option config.
391     *
392     * Storage shape (option key, type tag, default, enum). The agent-facing
393     * descriptions and JSON Schema live in `get_abilities()`; this map drives
394     * the storage-side validation, normalization, and casting.
395     *
396     * Kept as a method (not a class constant) so the description strings
397     * referenced from `cast_to_response()` and `normalize_input_value()` can
398     * resolve through `__()` at call time rather than file load time.
399     */
400    private static function settings_map(): array {
401        return array(
402            'subscribe_post_end_enabled' => array(
403                'option'  => 'jetpack_subscriptions_subscribe_post_end_enabled',
404                'type'    => self::TYPE_BOOL,
405                'default' => 0,
406            ),
407            'subscribe_comments_enabled' => array(
408                'option'  => 'stc_enabled',
409                'type'    => self::TYPE_BOOL,
410                'default' => 1,
411            ),
412            'notify_admin_on_subscribe'  => array(
413                'option'  => 'social_notifications_subscribe',
414                'type'    => self::TYPE_ON_OFF,
415                'default' => 'on',
416            ),
417            'reply_to'                   => array(
418                'option'  => 'jetpack_subscriptions_reply_to',
419                'type'    => self::TYPE_ENUM,
420                'default' => Subscriptions_Settings::$default_reply_to,
421                'enum'    => self::REPLY_TO_VALUES,
422            ),
423            'from_name'                  => array(
424                'option'     => 'jetpack_subscriptions_from_name',
425                'type'       => self::TYPE_STRING,
426                'default'    => '',
427                'max_length' => 200,
428            ),
429        );
430    }
431
432    /**
433     * Read all settings as the public response shape.
434     */
435    private static function current_settings(): array {
436        $out = array();
437        foreach ( self::settings_map() as $field => $config ) {
438            $out[ $field ] = self::cast_to_response( $config, self::read_option( $config ) );
439        }
440        return $out;
441    }
442
443    /**
444     * Read the raw option for a field config, falling back to its default.
445     *
446     * @param array $config Field config from `settings_map()`.
447     * @return mixed
448     */
449    private static function read_option( array $config ) {
450        return get_option( $config['option'], $config['default'] );
451    }
452
453    /**
454     * Validate + normalize a single input value to the storage form.
455     *
456     * @param string $field  Public field name (used in error messages).
457     * @param array  $config Field config from `settings_map()`.
458     * @param mixed  $value  Raw input value.
459     * @return mixed|\WP_Error Storage-form value, or WP_Error when invalid.
460     */
461    private static function normalize_input_value( string $field, array $config, $value ) {
462        switch ( $config['type'] ) {
463            case self::TYPE_BOOL:
464                if ( ! is_bool( $value ) ) {
465                    return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
466                }
467                return $value ? 1 : 0;
468
469            case self::TYPE_ON_OFF:
470                if ( ! is_bool( $value ) ) {
471                    return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
472                }
473                return $value ? 'on' : 'off';
474
475            case self::TYPE_ENUM:
476                // reply_to is the only enum today and shares its allowed-values
477                // list with `Subscriptions_Settings::is_valid_reply_to()`. Defer
478                // to that validator so the two surfaces can't drift.
479                $valid = 'reply_to' === $field
480                    ? Subscriptions_Settings::is_valid_reply_to( $value )
481                    : ( is_string( $value ) && in_array( $value, $config['enum'], true ) );
482                if ( ! $valid ) {
483                    return self::invalid_field(
484                        $field,
485                        sprintf(
486                            /* translators: %s: comma-separated list of allowed values. */
487                            __( 'allowed values are %s.', 'jetpack' ),
488                            implode( ', ', $config['enum'] )
489                        )
490                    );
491                }
492                return $value;
493
494            case self::TYPE_STRING:
495                if ( ! is_string( $value ) ) {
496                    return self::invalid_field( $field, __( 'expected a string.', 'jetpack' ) );
497                }
498                $sanitized = sanitize_text_field( $value );
499                if ( isset( $config['max_length'] ) && mb_strlen( $sanitized ) > (int) $config['max_length'] ) {
500                    return self::invalid_field(
501                        $field,
502                        sprintf(
503                            /* translators: %d: maximum number of characters. */
504                            __( 'must be %d characters or fewer.', 'jetpack' ),
505                            (int) $config['max_length']
506                        )
507                    );
508                }
509                return $sanitized;
510        }
511
512        return self::invalid_field( $field, __( 'unsupported field type.', 'jetpack' ) );
513    }
514
515    /**
516     * Cast a stored option value to the public response shape.
517     *
518     * @param array $config Field config from `settings_map()`.
519     * @param mixed $value  Raw stored value.
520     * @return mixed
521     */
522    private static function cast_to_response( array $config, $value ) {
523        switch ( $config['type'] ) {
524            case self::TYPE_BOOL:
525                return 1 === (int) $value;
526            case self::TYPE_ON_OFF:
527                return 'on' === (string) $value;
528            case self::TYPE_ENUM:
529                $value = (string) $value;
530                return in_array( $value, $config['enum'], true ) ? $value : (string) $config['default'];
531            case self::TYPE_STRING:
532                return (string) $value;
533        }
534        return $value;
535    }
536
537    /**
538     * Build a `jetpack_newsletter_invalid_<field>` WP_Error with a message
539     * that names the field and tells the agent how to fix the input.
540     *
541     * @param string $field  Public field name; appears in the error code and message.
542     * @param string $reason Translated explanation of the expected value.
543     * @return \WP_Error
544     */
545    private static function invalid_field( string $field, string $reason ): \WP_Error {
546        return new \WP_Error(
547            'jetpack_newsletter_invalid_' . $field,
548            sprintf(
549                /* translators: 1: field name, 2: explanation of the expected value. */
550                __( 'Invalid value for "%1$s": %2$s', 'jetpack' ),
551                $field,
552                $reason
553            )
554        );
555    }
556}