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