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