Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.75% covered (warning)
78.75%
556 / 706
30.00% covered (danger)
30.00%
6 / 20
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Endpoint_Subscribers_List
79.09% covered (warning)
79.09%
556 / 703
30.00% covered (danger)
30.00%
6 / 20
239.03
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 register_routes
100.00% covered (success)
100.00%
305 / 305
100.00% covered (success)
100.00%
1 / 1
3
 permission_check
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 get_subscribers
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
90
 get_subscriber_totals
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
42
 remove_subscriber
95.24% covered (success)
95.24%
40 / 42
0.00% covered (danger)
0.00%
0 / 1
9
 start_bulk_remove
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
2
 get_bulk_remove_status
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
3
 bulk_remove_response
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
9.08
 send_bounce_confirmation
93.55% covered (success)
93.55%
29 / 31
0.00% covered (danger)
0.00%
0 / 1
11.03
 get_subscriber_individual
62.50% covered (warning)
62.50%
10 / 16
0.00% covered (danger)
0.00%
0 / 1
7.90
 get_subscriber_stats
66.67% covered (warning)
66.67%
10 / 15
0.00% covered (danger)
0.00%
0 / 1
5.93
 add_subscribers
96.00% covered (success)
96.00%
48 / 50
0.00% covered (danger)
0.00%
0 / 1
9
 get_import_jobs
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 reset_import_state
66.67% covered (warning)
66.67%
14 / 21
0.00% covered (danger)
0.00%
0 / 1
4.59
 get_memberships_products
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 add_comp
81.40% covered (warning)
81.40%
35 / 43
0.00% covered (danger)
0.00%
0 / 1
14.09
 remove_comp
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
56
 get_wpcom_error_message
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
8
 wpcom_get
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2/**
3 * Subscribers List REST endpoint.
4 *
5 * Proxies the WP.com `/wpcom/v2/sites/{blog_id}/subscribers` endpoint so the
6 * Subscribers Dashboard wp-admin page can render a live DataViews table on
7 * Jetpack-connected self-hosted sites.
8 *
9 * @package automattic/jetpack
10 */
11
12use Automattic\Jetpack\Connection\Client;
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14
15if ( ! defined( 'ABSPATH' ) ) {
16    exit( 0 );
17}
18
19/**
20 * Class WPCOM_REST_API_V2_Endpoint_Subscribers_List
21 */
22class WPCOM_REST_API_V2_Endpoint_Subscribers_List extends WP_REST_Controller {
23
24    /**
25     * Constructor.
26     */
27    public function __construct() {
28        $this->namespace = 'wpcom/v2';
29        $this->rest_base = 'subscribers/list';
30
31        // On WPCOM the matching endpoint is registered via the wpcom-rest-api-v2 plugin loader,
32        // where it talks to subscriber storage directly.
33        $this->wpcom_is_wpcom_only_endpoint = true;
34
35        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
36    }
37
38    /**
39     * Register routes.
40     *
41     * Gated behind the same `rsm_jetpack_ui_modernization_newsletter` filter the dashboard UI uses
42     * (mirrors `Automattic\Jetpack\Newsletter\Settings::MODERNIZATION_FILTER`). Checked here, on
43     * `rest_api_init`, so theme-added filters have a chance to land before the gate evaluates.
44     *
45     * The filter defaults on for every site; hosts can opt out with
46     * `add_filter( 'rsm_jetpack_ui_modernization_newsletter', '__return_false' )`.
47     */
48    public function register_routes() {
49        if ( ! apply_filters( 'rsm_jetpack_ui_modernization_newsletter', true ) ) {
50            return;
51        }
52
53        register_rest_route(
54            $this->namespace,
55            '/subscribers/add',
56            array(
57                array(
58                    'methods'             => WP_REST_Server::CREATABLE,
59                    'callback'            => array( $this, 'add_subscribers' ),
60                    'permission_callback' => array( $this, 'permission_check' ),
61                    'args'                => array(
62                        'emails'     => array(
63                            'type'              => 'array',
64                            'items'             => array( 'type' => 'string' ),
65                            'required'          => true,
66                            'validate_callback' => function ( $value ) {
67                                return is_array( $value ) && count( $value ) > 0;
68                            },
69                        ),
70                        'categories' => array(
71                            'type'    => 'array',
72                            'items'   => array( 'type' => 'integer' ),
73                            'default' => array(),
74                        ),
75                    ),
76                ),
77            )
78        );
79
80        register_rest_route(
81            $this->namespace,
82            '/subscribers/remove',
83            array(
84                array(
85                    'methods'             => WP_REST_Server::CREATABLE,
86                    'callback'            => array( $this, 'remove_subscriber' ),
87                    'permission_callback' => array( $this, 'permission_check' ),
88                    'args'                => array(
89                        'user_id'               => array(
90                            'type'    => 'integer',
91                            'default' => 0,
92                            'minimum' => 0,
93                        ),
94                        'email_subscription_id' => array(
95                            'type'    => 'integer',
96                            'default' => 0,
97                            'minimum' => 0,
98                        ),
99                        'paid_subscription_ids' => array(
100                            'type'    => 'array',
101                            'items'   => array( 'type' => 'string' ),
102                            'default' => array(),
103                        ),
104                    ),
105                ),
106            )
107        );
108
109        register_rest_route(
110            $this->namespace,
111            '/subscribers/bulk-remove',
112            array(
113                array(
114                    'methods'             => WP_REST_Server::CREATABLE,
115                    'callback'            => array( $this, 'start_bulk_remove' ),
116                    'permission_callback' => array( $this, 'permission_check' ),
117                    'args'                => array(
118                        'filters'        => array(
119                            'type'    => 'array',
120                            'items'   => array( 'type' => 'string' ),
121                            'default' => array( 'all' ),
122                        ),
123                        'search'         => array(
124                            'type'    => 'string',
125                            'default' => '',
126                        ),
127                        'expected_count' => array(
128                            'type'     => 'integer',
129                            'required' => true,
130                            'minimum'  => 1,
131                        ),
132                    ),
133                ),
134            )
135        );
136
137        register_rest_route(
138            $this->namespace,
139            '/subscribers/bulk-remove/status',
140            array(
141                array(
142                    'methods'             => WP_REST_Server::READABLE,
143                    'callback'            => array( $this, 'get_bulk_remove_status' ),
144                    'permission_callback' => array( $this, 'permission_check' ),
145                    'args'                => array(
146                        'job_id' => array(
147                            'type'    => 'integer',
148                            'default' => 0,
149                            'minimum' => 0,
150                        ),
151                    ),
152                ),
153            )
154        );
155
156        register_rest_route(
157            $this->namespace,
158            '/subscribers/send-bounce-confirmation',
159            array(
160                array(
161                    'methods'             => WP_REST_Server::CREATABLE,
162                    'callback'            => array( $this, 'send_bounce_confirmation' ),
163                    'permission_callback' => array( $this, 'permission_check' ),
164                    'args'                => array(
165                        'email_address' => array(
166                            'type'     => 'string',
167                            'format'   => 'email',
168                            'required' => true,
169                        ),
170                    ),
171                ),
172            )
173        );
174
175        register_rest_route(
176            $this->namespace,
177            '/subscribers/individual',
178            array(
179                array(
180                    'methods'             => WP_REST_Server::READABLE,
181                    'callback'            => array( $this, 'get_subscriber_individual' ),
182                    'permission_callback' => array( $this, 'permission_check' ),
183                    'args'                => array(
184                        'subscription_id' => array(
185                            'type'    => 'integer',
186                            'default' => 0,
187                            'minimum' => 0,
188                        ),
189                        'user_id'         => array(
190                            'type'    => 'integer',
191                            'default' => 0,
192                            'minimum' => 0,
193                        ),
194                    ),
195                ),
196            )
197        );
198
199        register_rest_route(
200            $this->namespace,
201            '/subscribers/individual-stats',
202            array(
203                array(
204                    'methods'             => WP_REST_Server::READABLE,
205                    'callback'            => array( $this, 'get_subscriber_stats' ),
206                    'permission_callback' => array( $this, 'permission_check' ),
207                    'args'                => array(
208                        'subscription_id' => array(
209                            'type'    => 'integer',
210                            'default' => 0,
211                            'minimum' => 0,
212                        ),
213                        'user_id'         => array(
214                            'type'    => 'integer',
215                            'default' => 0,
216                            'minimum' => 0,
217                        ),
218                    ),
219                ),
220            )
221        );
222
223        register_rest_route(
224            $this->namespace,
225            '/subscribers/import',
226            array(
227                array(
228                    'methods'             => WP_REST_Server::READABLE,
229                    'callback'            => array( $this, 'get_import_jobs' ),
230                    'permission_callback' => array( $this, 'permission_check' ),
231                ),
232            )
233        );
234
235        register_rest_route(
236            $this->namespace,
237            '/subscribers/import/reset-state',
238            array(
239                array(
240                    'methods'             => WP_REST_Server::CREATABLE,
241                    'callback'            => array( $this, 'reset_import_state' ),
242                    'permission_callback' => array( $this, 'permission_check' ),
243                ),
244            )
245        );
246
247        register_rest_route(
248            $this->namespace,
249            '/subscribers/totals',
250            array(
251                array(
252                    'methods'             => WP_REST_Server::READABLE,
253                    'callback'            => array( $this, 'get_subscriber_totals' ),
254                    'permission_callback' => array( $this, 'permission_check' ),
255                ),
256            )
257        );
258
259        register_rest_route(
260            $this->namespace,
261            '/' . $this->rest_base,
262            array(
263                array(
264                    'methods'             => WP_REST_Server::READABLE,
265                    'callback'            => array( $this, 'get_subscribers' ),
266                    'permission_callback' => array( $this, 'permission_check' ),
267                    'args'                => array(
268                        'page'           => array(
269                            'type'    => 'integer',
270                            'default' => 1,
271                            'minimum' => 1,
272                        ),
273                        'per_page'       => array(
274                            'type'    => 'integer',
275                            'default' => 10,
276                            'minimum' => 1,
277                            'maximum' => 100,
278                        ),
279                        'sort'           => array(
280                            'type'    => 'string',
281                            'default' => 'date_subscribed',
282                            'enum'    => array( 'date_subscribed', 'name', 'plan', 'subscription_status' ),
283                        ),
284                        'sort_order'     => array(
285                            'type'    => 'string',
286                            'default' => 'desc',
287                            'enum'    => array( 'asc', 'desc' ),
288                        ),
289                        'search'         => array(
290                            'type'    => 'string',
291                            'default' => '',
292                        ),
293                        'filters'        => array(
294                            'type'    => 'array',
295                            'items'   => array( 'type' => 'string' ),
296                            'default' => array( 'all' ),
297                        ),
298                        'use_new_helper' => array(
299                            'type'    => 'boolean',
300                            'default' => true,
301                        ),
302                    ),
303                ),
304            )
305        );
306
307        register_rest_route(
308            $this->namespace,
309            '/subscribers/products',
310            array(
311                array(
312                    'methods'             => WP_REST_Server::READABLE,
313                    'callback'            => array( $this, 'get_memberships_products' ),
314                    'permission_callback' => array( $this, 'permission_check' ),
315                ),
316            )
317        );
318
319        register_rest_route(
320            $this->namespace,
321            '/subscribers/comp',
322            array(
323                array(
324                    'methods'             => WP_REST_Server::CREATABLE,
325                    'callback'            => array( $this, 'add_comp' ),
326                    'permission_callback' => array( $this, 'permission_check' ),
327                    'args'                => array(
328                        // Exactly one of user_id / email identifies the subscriber; add_comp()
329                        // enforces that, since the schema can't express "one or the other".
330                        'user_id'       => array(
331                            'type'    => 'integer',
332                            'default' => 0,
333                            'minimum' => 0,
334                        ),
335                        'email'         => array(
336                            'type'   => 'string',
337                            'format' => 'email',
338                        ),
339                        'plan_id'       => array(
340                            'type'     => 'integer',
341                            'required' => true,
342                            'minimum'  => 1,
343                        ),
344                        'no_expiration' => array(
345                            'type'    => 'boolean',
346                            'default' => false,
347                        ),
348                    ),
349                ),
350            )
351        );
352
353        register_rest_route(
354            $this->namespace,
355            '/subscribers/remove-comp',
356            array(
357                array(
358                    'methods'             => WP_REST_Server::CREATABLE,
359                    'callback'            => array( $this, 'remove_comp' ),
360                    'permission_callback' => array( $this, 'permission_check' ),
361                    'args'                => array(
362                        'comp_id' => array(
363                            'type'     => 'integer',
364                            'required' => true,
365                            'minimum'  => 1,
366                        ),
367                    ),
368                ),
369            )
370        );
371    }
372
373    /**
374     * Permission check — manage_options matches the wp-admin Subscribers menu cap.
375     *
376     * @return true|WP_Error
377     */
378    public function permission_check() {
379        if ( ! current_user_can( 'manage_options' ) ) {
380            return new WP_Error(
381                'authorization_required',
382                __( 'You are not allowed to view subscribers for this site.', 'jetpack' ),
383                array( 'status' => rest_authorization_required_code() )
384            );
385        }
386
387        return true;
388    }
389
390    /**
391     * Proxy GET /wpcom/v2/sites/{blog_id}/subscribers.
392     *
393     * @param WP_REST_Request $request Request.
394     * @return WP_REST_Response|WP_Error
395     */
396    public function get_subscribers( $request ) {
397        $blog_id = Connection_Manager::get_site_id();
398
399        if ( is_wp_error( $blog_id ) ) {
400            return $blog_id;
401        }
402
403        $query = array(
404            'page'           => (int) $request->get_param( 'page' ),
405            'per_page'       => (int) $request->get_param( 'per_page' ),
406            'sort'           => (string) $request->get_param( 'sort' ),
407            'sort_order'     => (string) $request->get_param( 'sort_order' ),
408            'use_new_helper' => $request->get_param( 'use_new_helper' ) ? 'true' : 'false',
409        );
410
411        $search = (string) $request->get_param( 'search' );
412        if ( '' !== $search ) {
413            $query['search'] = $search;
414        }
415
416        $query_string = http_build_query( $query );
417
418        $filters = (array) $request->get_param( 'filters' );
419        foreach ( $filters as $filter ) {
420            $query_string .= '&' . rawurlencode( 'filters[]' ) . '=' . rawurlencode( (string) $filter );
421        }
422
423        $path = sprintf( '/sites/%d/subscribers?%s', (int) $blog_id, $query_string );
424
425        $response = Client::wpcom_json_api_request_as_user(
426            $path,
427            '2',
428            array( 'method' => 'GET' ),
429            null,
430            'wpcom'
431        );
432
433        if ( is_wp_error( $response ) ) {
434            return $response;
435        }
436
437        $status = (int) wp_remote_retrieve_response_code( $response );
438        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
439
440        if ( $status >= 400 ) {
441            return new WP_Error(
442                'subscribers_list_failed',
443                is_array( $body ) && isset( $body['message'] ) ? $body['message'] : __( 'Could not fetch subscribers.', 'jetpack' ),
444                array( 'status' => $status )
445            );
446        }
447
448        return rest_ensure_response( $body );
449    }
450
451    /**
452     * Proxy GET /wpcom/v2/sites/{blog_id}/subscribers/counts.
453     *
454     * @return WP_REST_Response|WP_Error
455     */
456    public function get_subscriber_totals() {
457        $blog_id = Connection_Manager::get_site_id();
458
459        if ( is_wp_error( $blog_id ) ) {
460            return $blog_id;
461        }
462
463        $response = Client::wpcom_json_api_request_as_user(
464            sprintf( '/sites/%d/subscribers/counts', (int) $blog_id ),
465            '2',
466            array( 'method' => 'GET' ),
467            null,
468            'wpcom'
469        );
470
471        if ( is_wp_error( $response ) ) {
472            return $response;
473        }
474
475        $status = (int) wp_remote_retrieve_response_code( $response );
476        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
477
478        if ( $status >= 400 ) {
479            return new WP_Error(
480                'subscribers_totals_failed',
481                is_array( $body ) && isset( $body['message'] ) ? $body['message'] : __( 'Could not fetch subscriber totals.', 'jetpack' ),
482                array( 'status' => $status )
483            );
484        }
485
486        return rest_ensure_response( $body );
487    }
488
489    /**
490     * Remove a subscriber by cancelling any paid subscriptions and deleting both the WPCOM
491     * follower and email follower records, mirroring Calypso's `useSubscriberRemoveMutation`.
492     *
493     * Proxies to the consolidated wpcom `/sites/{blog_id}/subscribers/remove` (v2) endpoint, which
494     * runs all three steps in-process after switching to the blog and returns an aggregated
495     * `{ ok, errors }` result. Forwarded as the current user (not the blog token): the wpcom/v2
496     * authorization layer maps the Jetpack user token to the wpcom user, so the endpoint's
497     * `manage_options` gate evaluates against the acting admin — unlike the classic v1.1 `/rest`
498     * API, which left the request with no current user.
499     *
500     * @param WP_REST_Request $request Request.
501     * @return WP_REST_Response|WP_Error
502     */
503    public function remove_subscriber( $request ) {
504        $blog_id = Connection_Manager::get_site_id();
505
506        if ( is_wp_error( $blog_id ) ) {
507            return $blog_id;
508        }
509
510        $user_id               = (int) $request->get_param( 'user_id' );
511        $email_subscription_id = (int) $request->get_param( 'email_subscription_id' );
512        $paid_subscription_ids = array_values(
513            array_filter( array_map( 'strval', (array) $request->get_param( 'paid_subscription_ids' ) ) )
514        );
515
516        if ( ! $user_id && ! $email_subscription_id && empty( $paid_subscription_ids ) ) {
517            return new WP_Error(
518                'subscribers_remove_invalid',
519                __( 'No subscriber identifiers were provided.', 'jetpack' ),
520                array( 'status' => 400 )
521            );
522        }
523
524        $response = Client::wpcom_json_api_request_as_user(
525            sprintf( '/sites/%d/subscribers/remove', (int) $blog_id ),
526            '2',
527            array(
528                'method'  => 'POST',
529                'headers' => array( 'Content-Type' => 'application/json' ),
530            ),
531            wp_json_encode(
532                array(
533                    'user_id'               => $user_id,
534                    'email_subscription_id' => $email_subscription_id,
535                    'paid_subscription_ids' => $paid_subscription_ids,
536                ),
537                JSON_UNESCAPED_SLASHES
538            ),
539            'wpcom'
540        );
541
542        if ( is_wp_error( $response ) ) {
543            return $response;
544        }
545
546        $status = (int) wp_remote_retrieve_response_code( $response );
547        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
548
549        if ( $status >= 400 ) {
550            return new WP_Error(
551                'subscribers_remove_failed',
552                is_array( $body ) && isset( $body['message'] ) ? $body['message'] : __( 'Could not remove the subscriber.', 'jetpack' ),
553                array( 'status' => $status )
554            );
555        }
556
557        return rest_ensure_response( $body );
558    }
559
560    /**
561     * Proxy POST /wpcom/v2/sites/{blog_id}/subscribers/bulk-remove, which starts a background job
562     * on WP.com that saves a backup and then removes every subscriber matching `filters` and
563     * `search` (everyone with the default filter). Paid subscriptions are always cancelled, as
564     * with the single remove route.
565     *
566     * The job refuses to start when the list no longer holds `expected_count` subscribers, or
567     * when another removal is running. Those errors come back with their WP.com code and data
568     * (the new `count`, or the running `job`), so the screen can say what happened.
569     *
570     * @param WP_REST_Request $request Request.
571     * @return WP_REST_Response|WP_Error
572     */
573    public function start_bulk_remove( $request ) {
574        $blog_id = Connection_Manager::get_site_id();
575
576        if ( is_wp_error( $blog_id ) ) {
577            return $blog_id;
578        }
579
580        $response = Client::wpcom_json_api_request_as_user(
581            sprintf( '/sites/%d/subscribers/bulk-remove', (int) $blog_id ),
582            '2',
583            array(
584                'method'  => 'POST',
585                'headers' => array( 'Content-Type' => 'application/json' ),
586            ),
587            wp_json_encode(
588                array(
589                    'filters'        => array_values( array_map( 'strval', (array) $request->get_param( 'filters' ) ) ),
590                    'search'         => (string) $request->get_param( 'search' ),
591                    'expected_count' => (int) $request->get_param( 'expected_count' ),
592                    'cancel_paid'    => true,
593                ),
594                JSON_UNESCAPED_SLASHES
595            ),
596            'wpcom'
597        );
598
599        return $this->bulk_remove_response( $response, __( 'Could not start removing subscribers.', 'jetpack' ) );
600    }
601
602    /**
603     * Proxy GET /wpcom/v2/sites/{blog_id}/subscribers/bulk-remove/status: progress and final
604     * counts of a removal. Without `job_id`, the running removal, or else the latest one; `job`
605     * is null when the site has none. The body passes through unchanged, including `enabled`,
606     * which says whether WP.com lets the site start a removal.
607     *
608     * @param WP_REST_Request $request Request.
609     * @return WP_REST_Response|WP_Error
610     */
611    public function get_bulk_remove_status( $request ) {
612        $blog_id = Connection_Manager::get_site_id();
613
614        if ( is_wp_error( $blog_id ) ) {
615            return $blog_id;
616        }
617
618        $path   = sprintf( '/sites/%d/subscribers/bulk-remove/status', (int) $blog_id );
619        $job_id = (int) $request->get_param( 'job_id' );
620        if ( $job_id ) {
621            $path .= '?job_id=' . $job_id;
622        }
623
624        $response = Client::wpcom_json_api_request_as_user(
625            $path,
626            '2',
627            array( 'method' => 'GET' ),
628            null,
629            'wpcom'
630        );
631
632        return $this->bulk_remove_response( $response, __( 'Could not check the removal.', 'jetpack' ) );
633    }
634
635    /**
636     * Turn a WP.com bulk remove response into a REST response, keeping the WP.com error code and
637     * data on failure.
638     *
639     * @param array|WP_Error $response        Response from Client::wpcom_json_api_request_as_user().
640     * @param string         $default_message Message used when WP.com sends none.
641     * @return WP_REST_Response|WP_Error
642     */
643    private function bulk_remove_response( $response, $default_message ) {
644        if ( is_wp_error( $response ) ) {
645            return $response;
646        }
647
648        $status = (int) wp_remote_retrieve_response_code( $response );
649        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
650
651        if ( $status >= 400 ) {
652            $code = is_array( $body ) && isset( $body['code'] ) && is_string( $body['code'] ) ? $body['code'] : 'subscribers_bulk_remove_failed';
653            $data = is_array( $body ) && isset( $body['data'] ) && is_array( $body['data'] ) ? $body['data'] : array();
654
655            $data['status'] = $status;
656
657            return new WP_Error( $code, $this->get_wpcom_error_message( $body, $default_message ), $data );
658        }
659
660        return rest_ensure_response( $body );
661    }
662
663    /**
664     * Proxy POST /wpcom/v2/sites/{blog_id}/subscribers/send-bounce-confirmation.
665     *
666     * @since 16.4
667     *
668     * @param WP_REST_Request $request Request.
669     * @return WP_REST_Response|WP_Error
670     */
671    public function send_bounce_confirmation( $request ) {
672        $blog_id = Connection_Manager::get_site_id();
673
674        if ( is_wp_error( $blog_id ) ) {
675            return $blog_id;
676        }
677
678        $response = Client::wpcom_json_api_request_as_user(
679            sprintf( '/sites/%d/subscribers/send-bounce-confirmation', (int) $blog_id ),
680            '2',
681            array(
682                'method'  => 'POST',
683                'headers' => array( 'Content-Type' => 'application/json' ),
684            ),
685            wp_json_encode(
686                array(
687                    'email_address' => (string) $request->get_param( 'email_address' ),
688                ),
689                JSON_UNESCAPED_SLASHES
690            ),
691            'wpcom'
692        );
693
694        if ( is_wp_error( $response ) ) {
695            return $response;
696        }
697
698        $status = (int) wp_remote_retrieve_response_code( $response );
699        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
700
701        if ( $status >= 400 ) {
702            // Pass through wpcom's error code and data.
703            $data           = is_array( $body ) && isset( $body['data'] ) && is_array( $body['data'] ) ? $body['data'] : array();
704            $data['status'] = $status;
705
706            return new WP_Error(
707                is_array( $body ) && ! empty( $body['code'] ) ? (string) $body['code'] : 'subscribers_bounce_retry_failed',
708                is_array( $body ) && isset( $body['message'] ) ? $body['message'] : __( 'Could not send the confirmation email.', 'jetpack' ),
709                $data
710            );
711        }
712
713        return rest_ensure_response( $body );
714    }
715
716    /**
717     * Proxy GET /wpcom/v2/sites/{blog_id}/subscribers/individual.
718     *
719     * @param WP_REST_Request $request Request.
720     * @return WP_REST_Response|WP_Error
721     */
722    public function get_subscriber_individual( $request ) {
723        $blog_id         = Connection_Manager::get_site_id();
724        $subscription_id = (int) $request->get_param( 'subscription_id' );
725        $user_id         = (int) $request->get_param( 'user_id' );
726
727        if ( is_wp_error( $blog_id ) ) {
728            return $blog_id;
729        }
730
731        if ( ! $subscription_id && ! $user_id ) {
732            return new WP_Error(
733                'subscriber_individual_missing_id',
734                __( 'Provide either a subscription_id or a user_id.', 'jetpack' ),
735                array( 'status' => 400 )
736            );
737        }
738
739        $type  = $user_id ? 'wpcom' : 'email';
740        $query = $user_id
741            ? sprintf( 'user_id=%d&type=%s', $user_id, rawurlencode( $type ) )
742            : sprintf( 'subscription_id=%d&type=%s', $subscription_id, rawurlencode( $type ) );
743
744        return $this->wpcom_get( sprintf( '/sites/%d/subscribers/individual?%s', (int) $blog_id, $query ) );
745    }
746
747    /**
748     * Proxy GET /wpcom/v2/sites/{blog_id}/individual-subscriber-stats.
749     *
750     * @param WP_REST_Request $request Request.
751     * @return WP_REST_Response|WP_Error
752     */
753    public function get_subscriber_stats( $request ) {
754        $blog_id         = Connection_Manager::get_site_id();
755        $subscription_id = (int) $request->get_param( 'subscription_id' );
756        $user_id         = (int) $request->get_param( 'user_id' );
757
758        if ( is_wp_error( $blog_id ) ) {
759            return $blog_id;
760        }
761
762        if ( ! $subscription_id && ! $user_id ) {
763            return new WP_Error(
764                'subscriber_stats_missing_id',
765                __( 'Provide either a subscription_id or a user_id.', 'jetpack' ),
766                array( 'status' => 400 )
767            );
768        }
769
770        $query = $user_id
771            ? sprintf( 'user_id=%d', $user_id )
772            : sprintf( 'subscription_id=%d', $subscription_id );
773
774        return $this->wpcom_get( sprintf( '/sites/%d/individual-subscriber-stats?%s', (int) $blog_id, $query ) );
775    }
776
777    /**
778     * Add subscribers by email — proxies to `/sites/{blog_id}/subscribers/import` (v2), the same
779     * async import job Calypso's Add Subscribers modal starts. Addresses are imported directly as
780     * subscribers (no invitation email); WP.com processes the job in the background and emails the
781     * importing user a "Subscriber import completed" summary when it finishes.
782     *
783     * When the caller passes `categories` (newsletter category ids selected in the Add Subscribers
784     * picker), they're forwarded so the imported subscribers are opted into those categories — the
785     * same `categories` payload Calypso's `importCsvSubscribers` sends to this endpoint.
786     *
787     * @param WP_REST_Request $request Request.
788     * @return WP_REST_Response|WP_Error
789     */
790    public function add_subscribers( $request ) {
791        $blog_id = Connection_Manager::get_site_id();
792
793        if ( is_wp_error( $blog_id ) ) {
794            return $blog_id;
795        }
796
797        $emails = (array) $request->get_param( 'emails' );
798        $emails = array_values(
799            array_filter(
800                array_map( 'sanitize_email', $emails ),
801                static function ( $email ) {
802                    return is_email( $email );
803                }
804            )
805        );
806
807        if ( empty( $emails ) ) {
808            return new WP_Error(
809                'subscribers_add_no_valid_emails',
810                __( 'Provide at least one valid email address.', 'jetpack' ),
811                array( 'status' => 400 )
812            );
813        }
814
815        // Coerce category ids to positive integers and drop anything else — a category id is always
816        // a term id, so a zero or non-numeric value is noise we shouldn't forward to WP.com.
817        $categories = array_values(
818            array_filter(
819                array_map( 'absint', (array) $request->get_param( 'categories' ) )
820            )
821        );
822
823        $body = array(
824            'emails'     => $emails,
825            'parse_only' => false,
826        );
827        // Only include `categories` when the user actually selected some, so a plain import keeps
828        // the exact payload it sent before this feature existed.
829        if ( ! empty( $categories ) ) {
830            $body['categories'] = $categories;
831        }
832
833        // JSON body, not the form encoding Calypso submits: WP.com's Jetpack signature verifier
834        // canonicalizes `application/x-www-form-urlencoded` bodies differently from the Jetpack
835        // client (it re-encodes the parsed array as JSON before hashing), so a form-encoded POST
836        // fails the body-hash check and arrives unauthenticated (user 0) — surfacing as a 401
837        // `invalid_capabilities`. JSON bodies hash identically on both sides, and the endpoint
838        // reads its params from either encoding. `parse_only => false` runs the import rather
839        // than only validating the payload.
840        $response = Client::wpcom_json_api_request_as_user(
841            sprintf( '/sites/%d/subscribers/import', (int) $blog_id ),
842            '2',
843            array(
844                'method'  => 'POST',
845                'headers' => array( 'Content-Type' => 'application/json' ),
846            ),
847            wp_json_encode( $body, JSON_UNESCAPED_SLASHES ),
848            'wpcom'
849        );
850
851        if ( is_wp_error( $response ) ) {
852            return $response;
853        }
854
855        $status = (int) wp_remote_retrieve_response_code( $response );
856        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
857
858        // A successful import start carries the async job id as `upload_id`. Mirror Calypso, which
859        // treats any response without one as a failure even when the HTTP status is 2xx.
860        if ( $status >= 400 || ! is_array( $body ) || empty( $body['upload_id'] ) ) {
861            return new WP_Error(
862                'subscribers_add_failed',
863                $this->get_wpcom_error_message( $body, __( 'Could not add subscribers.', 'jetpack' ) ),
864                array( 'status' => $status >= 400 ? $status : 400 )
865            );
866        }
867
868        return rest_ensure_response( $body );
869    }
870
871    /**
872     * Proxy GET /wpcom/v2/sites/{blog_id}/subscribers/import — the site's subscriber import jobs,
873     * newest first. The dashboard polls this while the Add Subscribers modal is open so it can
874     * show the "import in progress" / stale-import notices (WP.com runs one import per site at a
875     * time).
876     *
877     * @return WP_REST_Response|WP_Error
878     */
879    public function get_import_jobs() {
880        $blog_id = Connection_Manager::get_site_id();
881
882        if ( is_wp_error( $blog_id ) ) {
883            return $blog_id;
884        }
885
886        return $this->wpcom_get( sprintf( '/sites/%d/subscribers/import', (int) $blog_id ) );
887    }
888
889    /**
890     * POST /wpcom/v2/subscribers/import/reset-state — cancel stuck (pending / importing)
891     * subscriber import jobs, mirroring Calypso's stale-import "Cancel import" action
892     * (`useSubscriberImportStatusReset`). Proxies to the wpcom
893     * `/sites/{blog_id}/subscribers/import/reset_state` endpoint and returns its
894     * `{ reset_count }` body.
895     *
896     * @return WP_REST_Response|WP_Error
897     */
898    public function reset_import_state() {
899        $blog_id = Connection_Manager::get_site_id();
900
901        if ( is_wp_error( $blog_id ) ) {
902            return $blog_id;
903        }
904
905        $response = Client::wpcom_json_api_request_as_user(
906            sprintf( '/sites/%d/subscribers/import/reset_state', (int) $blog_id ),
907            '2',
908            array( 'method' => 'POST' ),
909            null,
910            'wpcom'
911        );
912
913        if ( is_wp_error( $response ) ) {
914            return $response;
915        }
916
917        $status = (int) wp_remote_retrieve_response_code( $response );
918        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
919
920        if ( $status >= 400 ) {
921            return new WP_Error(
922                'subscribers_reset_import_failed',
923                $this->get_wpcom_error_message( $body, __( 'Could not cancel the import.', 'jetpack' ) ),
924                array( 'status' => $status )
925            );
926        }
927
928        return rest_ensure_response( $body );
929    }
930
931    /**
932     * Proxy GET /wpcom/v2/sites/{blog_id}/memberships/products?type=all&is_editable=true — the
933     * paid newsletter / membership tiers configured on this site. Used by the Comp-a-subscription
934     * plan picker so the modal can offer "comp this subscriber on plan X".
935     *
936     * @return WP_REST_Response|WP_Error
937     */
938    public function get_memberships_products() {
939        $blog_id = Connection_Manager::get_site_id();
940
941        if ( is_wp_error( $blog_id ) ) {
942            return $blog_id;
943        }
944
945        return $this->wpcom_get(
946            sprintf(
947                '/sites/%d/memberships/products?type=all&is_editable=true',
948                (int) $blog_id
949            )
950        );
951    }
952
953    /**
954     * POST /wpcom/v2/subscribers/comp — issue a complimentary subscription on a paid membership
955     * product for a single subscriber. Mirrors Calypso's `requestAddComp` thunk, which POSTs to
956     * `/sites/{id}/memberships/comps/{identifier}/{plan_id}`.
957     *
958     * The identifier is a wpcom user id, or an email address for a subscriber with no wpcom
959     * account — WP.com resolves (or creates) an account from the address and links the
960     * subscriber row. See NL-1033.
961     *
962     * @param WP_REST_Request $request Request.
963     * @return WP_REST_Response|WP_Error
964     */
965    public function add_comp( $request ) {
966        $blog_id = Connection_Manager::get_site_id();
967
968        if ( is_wp_error( $blog_id ) ) {
969            return $blog_id;
970        }
971
972        $user_id       = (int) $request->get_param( 'user_id' );
973        $email         = (string) $request->get_param( 'email' );
974        $plan_id       = (int) $request->get_param( 'plan_id' );
975        $no_expiration = (bool) $request->get_param( 'no_expiration' );
976
977        if ( ( $user_id && '' !== $email ) || ( ! $user_id && '' === $email ) ) {
978            return new WP_Error(
979                'subscribers_comp_invalid_subscriber',
980                __( 'Provide either a user ID or an email address for the subscriber.', 'jetpack' ),
981                array( 'status' => 400 )
982            );
983        }
984
985        $body = $no_expiration
986            ? wp_json_encode( array( 'no_expiration' => true ), JSON_UNESCAPED_SLASHES )
987            : null;
988
989        // WP.com rawurldecode()s this segment, so an email has to arrive encoded — `%d` would
990        // flatten it to 0.
991        $identifier = $user_id ? (string) $user_id : rawurlencode( $email );
992
993        $response = Client::wpcom_json_api_request_as_user(
994            sprintf(
995                '/sites/%d/memberships/comps/%s/%d',
996                (int) $blog_id,
997                $identifier,
998                $plan_id
999            ),
1000            '2',
1001            array(
1002                'method'  => 'POST',
1003                'headers' => array( 'Content-Type' => 'application/json' ),
1004            ),
1005            $body,
1006            'wpcom'
1007        );
1008
1009        if ( is_wp_error( $response ) ) {
1010            return $response;
1011        }
1012
1013        $status = (int) wp_remote_retrieve_response_code( $response );
1014        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
1015
1016        // The Memberships API can report a failure either with an HTTP error status or with a 2xx
1017        // response carrying an `error` payload (e.g. "User has already been comped this plan"), so
1018        // treat both as failures and surface the upstream message rather than a generic one.
1019        if ( $status >= 400 || ( is_array( $body ) && ! empty( $body['error'] ) ) ) {
1020            return new WP_Error(
1021                'subscribers_comp_failed',
1022                $this->get_wpcom_error_message( $body, __( 'Could not comp the subscription.', 'jetpack' ) ),
1023                array( 'status' => $status >= 400 ? $status : 400 )
1024            );
1025        }
1026
1027        return rest_ensure_response( $body );
1028    }
1029
1030    /**
1031     * POST /wpcom/v2/subscribers/remove-comp — revoke a complimentary subscription. Mirrors
1032     * Calypso's `requestDeleteComp`, which DELETEs
1033     * `/sites/{id}/memberships/comp/{compId}` (singular `comp`).
1034     *
1035     * @param WP_REST_Request $request Request.
1036     * @return WP_REST_Response|WP_Error
1037     */
1038    public function remove_comp( $request ) {
1039        $blog_id = Connection_Manager::get_site_id();
1040
1041        if ( is_wp_error( $blog_id ) ) {
1042            return $blog_id;
1043        }
1044
1045        $comp_id = (int) $request->get_param( 'comp_id' );
1046
1047        $response = Client::wpcom_json_api_request_as_user(
1048            sprintf(
1049                '/sites/%d/memberships/comp/%d',
1050                (int) $blog_id,
1051                $comp_id
1052            ),
1053            '2',
1054            array( 'method' => 'DELETE' ),
1055            null,
1056            'wpcom'
1057        );
1058
1059        if ( is_wp_error( $response ) ) {
1060            return $response;
1061        }
1062
1063        $status = (int) wp_remote_retrieve_response_code( $response );
1064        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
1065
1066        // Mirror add_comp: the Memberships API can report a failure with an error status or with a
1067        // 2xx response that carries an `error` payload, so treat both as failures.
1068        if ( $status >= 400 || ( is_array( $body ) && ! empty( $body['error'] ) ) ) {
1069            return new WP_Error(
1070                'subscribers_remove_comp_failed',
1071                $this->get_wpcom_error_message( $body, __( 'Could not remove the comp.', 'jetpack' ) ),
1072                array( 'status' => $status >= 400 ? $status : 400 )
1073            );
1074        }
1075
1076        return rest_ensure_response( $body );
1077    }
1078
1079    /**
1080     * Extract the most specific human-readable error message from a wpcom Memberships API response
1081     * body. The Memberships endpoints nest the reason under `error.message` (e.g. "User has already
1082     * been comped this plan"); fall back to a top-level `message`, a string `error`, then the default.
1083     *
1084     * @param mixed  $body            Decoded response body.
1085     * @param string $default_message Fallback used when the body carries no message.
1086     * @return string Error message.
1087     */
1088    private function get_wpcom_error_message( $body, $default_message ) {
1089        if ( is_array( $body ) ) {
1090            if ( isset( $body['error']['message'] ) && is_string( $body['error']['message'] ) ) {
1091                return $body['error']['message'];
1092            }
1093            if ( isset( $body['message'] ) && is_string( $body['message'] ) ) {
1094                return $body['message'];
1095            }
1096            if ( isset( $body['error'] ) && is_string( $body['error'] ) ) {
1097                return $body['error'];
1098            }
1099        }
1100
1101        return $default_message;
1102    }
1103
1104    /**
1105     * Helper: GET a wpcom v2 path on this site as the current user. Returns the parsed JSON
1106     * response or a WP_Error.
1107     *
1108     * @param string $path Path under `/wpcom/v2`, including any query string.
1109     * @return WP_REST_Response|WP_Error
1110     */
1111    private function wpcom_get( $path ) {
1112        $response = Client::wpcom_json_api_request_as_user(
1113            $path,
1114            '2',
1115            array( 'method' => 'GET' ),
1116            null,
1117            'wpcom'
1118        );
1119
1120        if ( is_wp_error( $response ) ) {
1121            return $response;
1122        }
1123
1124        $status = (int) wp_remote_retrieve_response_code( $response );
1125        $body   = json_decode( wp_remote_retrieve_body( $response ), true );
1126
1127        if ( $status >= 400 ) {
1128            return new WP_Error(
1129                'wpcom_call_failed',
1130                is_array( $body ) && isset( $body['message'] ) ? $body['message'] : __( 'WP.com call failed.', 'jetpack' ),
1131                array( 'status' => $status )
1132            );
1133        }
1134
1135        return rest_ensure_response( $body );
1136    }
1137}
1138
1139wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Subscribers_List' );