Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.22% covered (success)
97.22%
245 / 252
86.67% covered (warning)
86.67%
13 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
Newsletter_Abilities
98.79% covered (success)
98.79%
245 / 248
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%
120 / 120
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.',
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.',
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.',
97                ),
98                'notify_admin_on_subscribe'  => array(
99                    'type'        => 'boolean',
100                    'description' => 'Email the site admin whenever a new subscriber signs up. Default true.',
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".',
106                ),
107                'from_name'                  => array(
108                    'type'        => 'string',
109                    'description' => 'Sender name shown on newsletter emails. Empty string falls back to the site name.',
110                    'maxLength'   => 200,
111                ),
112            ),
113        );
114
115        return array(
116            'jetpack-newsletter/get-settings'         => array(
117                'label'               => __( 'Get Newsletter settings', 'jetpack' ),
118                'description'         => '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.',
119                'input_schema'        => array(
120                    'type'                 => 'object',
121                    'default'              => array(),
122                    'properties'           => array(),
123                    'additionalProperties' => false,
124                ),
125                'output_schema'       => $settings_object_schema,
126                'execute_callback'    => array( __CLASS__, 'get_settings' ),
127                'permission_callback' => array( __CLASS__, 'can_view_settings' ),
128                'meta'                => array(
129                    'annotations'  => array(
130                        'readonly'    => true,
131                        'destructive' => false,
132                        'idempotent'  => true,
133                    ),
134                    'public'       => true,
135                    'show_in_rest' => true,
136                    'mcp'          => array(
137                        'public' => true,
138                        'type'   => 'tool', // default is already "tool", but can be explicit.
139                    ),
140                ),
141            ),
142
143            'jetpack-newsletter/update-settings'      => array(
144                'label'               => __( 'Update Newsletter settings', 'jetpack' ),
145                'description'         => '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 = [].',
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.',
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'         => '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.',
178                'input_schema'        => array(
179                    'type'                 => 'object',
180                    'default'              => array(),
181                    'properties'           => array(),
182                    'additionalProperties' => false,
183                ),
184                'output_schema'       => array(
185                    'type'       => 'object',
186                    'properties' => array(
187                        'all'   => array( 'type' => 'integer' ),
188                        'email' => array( 'type' => 'integer' ),
189                        'paid'  => array( 'type' => 'integer' ),
190                    ),
191                ),
192                'execute_callback'    => array( __CLASS__, 'get_subscriber_stats' ),
193                'permission_callback' => array( __CLASS__, 'can_view_settings' ),
194                'meta'                => array(
195                    'annotations'  => array(
196                        'readonly'    => true,
197                        'destructive' => false,
198                        'idempotent'  => true,
199                    ),
200                    'public'       => true,
201                    'show_in_rest' => true,
202                    'mcp'          => array(
203                        'public' => true,
204                        'type'   => 'tool', // default is already "tool", but can be explicit.
205                    ),
206                ),
207            ),
208        );
209    }
210
211    /**
212     * Permission check for read abilities. Newsletter settings live on the WP
213     * Newsletter settings screen, which is itself gated on `manage_options`.
214     */
215    public static function can_view_settings(): bool {
216        return current_user_can( 'manage_options' );
217    }
218
219    /**
220     * Permission check for write abilities. Mirrors the gating on the
221     * Newsletter settings screen.
222     */
223    public static function can_manage_settings(): bool {
224        return current_user_can( 'manage_options' );
225    }
226
227    /**
228     * Execute: return the current newsletter settings.
229     *
230     * @param array|null $input Unused — input schema accepts no parameters.
231     * @return array
232     */
233    public static function get_settings( $input = null ): array {
234        unset( $input );
235        return self::current_settings();
236    }
237
238    /**
239     * Execute: fetch (and cache) aggregate subscriber counts from WordPress.com.
240     *
241     * @param array|null $input Unused — input schema accepts no parameters.
242     * @return array|\WP_Error
243     */
244    public static function get_subscriber_stats( $input = null ) {
245        unset( $input );
246
247        $data = Jetpack_Subscriber_Data::get_stats();
248        if ( is_wp_error( $data ) ) {
249            return $data;
250        }
251
252        $counts = $data['counts'];
253        return array(
254            'all'   => isset( $counts['all_subscribers'] ) ? (int) $counts['all_subscribers'] : 0,
255            'email' => isset( $counts['email_subscribers'] ) ? (int) $counts['email_subscribers'] : 0,
256            'paid'  => isset( $counts['paid_subscribers'] ) ? (int) $counts['paid_subscribers'] : 0,
257        );
258    }
259
260    /**
261     * Execute: idempotent partial update of newsletter settings.
262     *
263     * Validates every supplied field before writing anything, so a malformed
264     * field cannot leave the option set in a partially-updated state.
265     *
266     * @param array|null $input Input matching the ability's input_schema.
267     * @return array|\WP_Error
268     */
269    public static function update_settings( $input = null ) {
270        $input = is_array( $input ) ? $input : array();
271        $map   = self::settings_map();
272
273        // Validate + normalize every supplied field up-front. Any failure
274        // short-circuits the call with no writes, so a bad field can't leave
275        // earlier fields in a partially-updated state.
276        $normalized = array();
277        foreach ( $map as $field => $config ) {
278            if ( ! array_key_exists( $field, $input ) ) {
279                continue;
280            }
281
282            $result = self::normalize_input_value( $field, $config, $input[ $field ] );
283            if ( $result instanceof \WP_Error ) {
284                return $result;
285            }
286            $normalized[ $field ] = $result;
287        }
288
289        // Read every field's current value once. This pass also feeds the
290        // post-update response, avoiding a second `get_option` sweep.
291        $current_storage = array();
292        foreach ( $map as $field => $config ) {
293            $current_storage[ $field ] = self::read_option( $config );
294        }
295
296        $changed = array();
297        foreach ( $normalized as $field => $desired ) {
298            // String-cast on both sides because every field's storage form is
299            // scalar (`0`/`1` for BOOL, `'on'`/`'off'` for ON_OFF, plain strings
300            // for ENUM/STRING). New field types added later must keep that
301            // invariant or this comparison will misfire.
302            if ( (string) $desired === (string) $current_storage[ $field ] ) {
303                continue;
304            }
305            update_option( $map[ $field ]['option'], $desired );
306            $current_storage[ $field ] = $desired;
307            $changed[]                 = $field;
308        }
309
310        $settings = array();
311        foreach ( $map as $field => $config ) {
312            $settings[ $field ] = self::cast_to_response( $config, $current_storage[ $field ] );
313        }
314
315        return array(
316            'settings' => $settings,
317            'changed'  => $changed,
318        );
319    }
320
321    /**
322     * Map of public ability field name → backing option config.
323     *
324     * Storage shape (option key, type tag, default, enum). The agent-facing
325     * descriptions and JSON Schema live in `get_abilities()`; this map drives
326     * the storage-side validation, normalization, and casting.
327     *
328     * Kept as a method (not a class constant) so the description strings
329     * referenced from `cast_to_response()` and `normalize_input_value()` can
330     * resolve through `__()` at call time rather than file load time.
331     */
332    private static function settings_map(): array {
333        return array(
334            'subscribe_post_end_enabled' => array(
335                'option'  => 'jetpack_subscriptions_subscribe_post_end_enabled',
336                'type'    => self::TYPE_BOOL,
337                'default' => 0,
338            ),
339            'subscribe_comments_enabled' => array(
340                'option'  => 'stc_enabled',
341                'type'    => self::TYPE_BOOL,
342                'default' => 1,
343            ),
344            'notify_admin_on_subscribe'  => array(
345                'option'  => 'social_notifications_subscribe',
346                'type'    => self::TYPE_ON_OFF,
347                'default' => 'on',
348            ),
349            'reply_to'                   => array(
350                'option'  => 'jetpack_subscriptions_reply_to',
351                'type'    => self::TYPE_ENUM,
352                'default' => Subscriptions_Settings::$default_reply_to,
353                'enum'    => self::REPLY_TO_VALUES,
354            ),
355            'from_name'                  => array(
356                'option'     => 'jetpack_subscriptions_from_name',
357                'type'       => self::TYPE_STRING,
358                'default'    => '',
359                'max_length' => 200,
360            ),
361        );
362    }
363
364    /**
365     * Read all settings as the public response shape.
366     */
367    private static function current_settings(): array {
368        $out = array();
369        foreach ( self::settings_map() as $field => $config ) {
370            $out[ $field ] = self::cast_to_response( $config, self::read_option( $config ) );
371        }
372        return $out;
373    }
374
375    /**
376     * Read the raw option for a field config, falling back to its default.
377     *
378     * @param array $config Field config from `settings_map()`.
379     * @return mixed
380     */
381    private static function read_option( array $config ) {
382        return get_option( $config['option'], $config['default'] );
383    }
384
385    /**
386     * Validate + normalize a single input value to the storage form.
387     *
388     * @param string $field  Public field name (used in error messages).
389     * @param array  $config Field config from `settings_map()`.
390     * @param mixed  $value  Raw input value.
391     * @return mixed|\WP_Error Storage-form value, or WP_Error when invalid.
392     */
393    private static function normalize_input_value( string $field, array $config, $value ) {
394        switch ( $config['type'] ) {
395            case self::TYPE_BOOL:
396                if ( ! is_bool( $value ) ) {
397                    return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
398                }
399                return $value ? 1 : 0;
400
401            case self::TYPE_ON_OFF:
402                if ( ! is_bool( $value ) ) {
403                    return self::invalid_field( $field, __( 'expected a boolean (true or false).', 'jetpack' ) );
404                }
405                return $value ? 'on' : 'off';
406
407            case self::TYPE_ENUM:
408                // reply_to is the only enum today and shares its allowed-values
409                // list with `Subscriptions_Settings::is_valid_reply_to()`. Defer
410                // to that validator so the two surfaces can't drift.
411                $valid = 'reply_to' === $field
412                    ? Subscriptions_Settings::is_valid_reply_to( $value )
413                    : ( is_string( $value ) && in_array( $value, $config['enum'], true ) );
414                if ( ! $valid ) {
415                    return self::invalid_field(
416                        $field,
417                        sprintf(
418                            /* translators: %s: comma-separated list of allowed values. */
419                            __( 'allowed values are %s.', 'jetpack' ),
420                            implode( ', ', $config['enum'] )
421                        )
422                    );
423                }
424                return $value;
425
426            case self::TYPE_STRING:
427                if ( ! is_string( $value ) ) {
428                    return self::invalid_field( $field, __( 'expected a string.', 'jetpack' ) );
429                }
430                $sanitized = sanitize_text_field( $value );
431                if ( isset( $config['max_length'] ) && mb_strlen( $sanitized ) > (int) $config['max_length'] ) {
432                    return self::invalid_field(
433                        $field,
434                        sprintf(
435                            /* translators: %d: maximum number of characters. */
436                            __( 'must be %d characters or fewer.', 'jetpack' ),
437                            (int) $config['max_length']
438                        )
439                    );
440                }
441                return $sanitized;
442        }
443
444        return self::invalid_field( $field, __( 'unsupported field type.', 'jetpack' ) );
445    }
446
447    /**
448     * Cast a stored option value to the public response shape.
449     *
450     * @param array $config Field config from `settings_map()`.
451     * @param mixed $value  Raw stored value.
452     * @return mixed
453     */
454    private static function cast_to_response( array $config, $value ) {
455        switch ( $config['type'] ) {
456            case self::TYPE_BOOL:
457                return 1 === (int) $value;
458            case self::TYPE_ON_OFF:
459                return 'on' === (string) $value;
460            case self::TYPE_ENUM:
461                $value = (string) $value;
462                return in_array( $value, $config['enum'], true ) ? $value : (string) $config['default'];
463            case self::TYPE_STRING:
464                return (string) $value;
465        }
466        return $value;
467    }
468
469    /**
470     * Build a `jetpack_newsletter_invalid_<field>` WP_Error with a message
471     * that names the field and tells the agent how to fix the input.
472     *
473     * @param string $field  Public field name; appears in the error code and message.
474     * @param string $reason Translated explanation of the expected value.
475     * @return \WP_Error
476     */
477    private static function invalid_field( string $field, string $reason ): \WP_Error {
478        return new \WP_Error(
479            'jetpack_newsletter_invalid_' . $field,
480            sprintf(
481                /* translators: 1: field name, 2: explanation of the expected value. */
482                __( 'Invalid value for "%1$s": %2$s', 'jetpack' ),
483                $field,
484                $reason
485            )
486        );
487    }
488}