Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
70.37% covered (warning)
70.37%
247 / 351
22.73% covered (danger)
22.73%
5 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Endpoint_Memberships
71.18% covered (warning)
71.18%
247 / 347
22.73% covered (danger)
22.73%
5 / 22
238.03
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 register_routes
100.00% covered (success)
100.00%
173 / 173
100.00% covered (success)
100.00%
1 / 1
1
 get_status_permission_check
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 can_modify_products_permission_check
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 create_products
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
13.57
 list_products
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
9.29
 create_product
55.56% covered (warning)
55.56%
5 / 9
0.00% covered (danger)
0.00%
0 / 1
5.40
 update_product
60.00% covered (warning)
60.00%
6 / 10
0.00% covered (danger)
0.00%
0 / 1
5.02
 delete_product
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
4.54
 get_status
30.43% covered (danger)
30.43%
7 / 23
0.00% covered (danger)
0.00%
0 / 1
23.50
 prevent_running_outside_of_wpcom
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 list_products_from_wpcom
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
 find_product_from_wpcom
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
20
 create_product_from_wpcom
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 update_product_from_wpcom
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 delete_product_from_wpcom
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 get_payload_for_product
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
7
 validate_tier_field
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
5.07
 validate_yearly_tier
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 validate_tier_references
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 check_duplicate_tier_references
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
110
 is_wpcom
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
1<?php // phpcs:disable WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Memberships: API to communicate with "product" database.
4 *
5 * @package    Jetpack
6 * @since      7.3.0
7 */
8
9use Automattic\Jetpack\Connection\Traits\WPCOM_REST_API_Proxy_Request;
10
11if ( ! defined( 'ABSPATH' ) ) {
12    exit( 0 );
13}
14
15/**
16 * Class WPCOM_REST_API_V2_Endpoint_Memberships
17 * This introduces V2 endpoints.
18 *
19 * @phan-constructor-used-for-side-effects
20 */
21class WPCOM_REST_API_V2_Endpoint_Memberships extends WP_REST_Controller {
22
23    use WPCOM_REST_API_Proxy_Request;
24
25    /**
26     * WPCOM_REST_API_V2_Endpoint_Memberships constructor.
27     */
28    public function __construct() {
29        $this->base_api_path                   = 'wpcom';
30        $this->version                         = 'v2';
31        $this->namespace                       = $this->base_api_path . '/' . $this->version;
32        $this->rest_base                       = 'memberships';
33        $this->wpcom_is_wpcom_only_endpoint    = true;
34        $this->wpcom_is_site_specific_endpoint = true;
35        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
36    }
37
38    /**
39     * Called automatically on `rest_api_init()`.
40     */
41    public function register_routes() {
42        register_rest_route(
43            $this->namespace,
44            $this->rest_base . '/status/?',
45            array(
46                array(
47                    'methods'             => WP_REST_Server::READABLE,
48                    'callback'            => array( $this, 'get_status' ),
49                    'permission_callback' => array( $this, 'get_status_permission_check' ),
50                    'args'                => array(
51                        'type'        => array(
52                            'type'              => 'string',
53                            'required'          => false,
54                            'validate_callback' => function ( $param ) {
55                                return in_array( $param, array( 'donation', 'all' ), true );
56                            },
57                        ),
58                        'source'      => array(
59                            'type'              => 'string',
60                            'required'          => false,
61                            'validate_callback' => function ( $param ) {
62                                return in_array(
63                                    $param,
64                                    array(
65                                        'calypso',
66                                        'earn',
67                                        'earn-newsletter',
68                                        'gutenberg',
69                                        'gutenberg-wpcom',
70                                        'launchpad',
71                                        'import-paid-subscribers',
72                                        'jetpack-monetize',
73                                    ),
74                                    true
75                                );
76                            },
77                        ),
78                        'is_editable' => array(
79                            'type'     => 'boolean',
80                            'required' => false,
81                        ),
82                    ),
83                ),
84            )
85        );
86        register_rest_route(
87            $this->namespace,
88            $this->rest_base . '/product/?',
89            array(
90                array(
91                    'methods'             => WP_REST_Server::CREATABLE,
92                    'callback'            => array( $this, 'create_product' ),
93                    'permission_callback' => array( $this, 'get_status_permission_check' ),
94                    'args'                => array(
95                        'title'                   => array(
96                            'type'     => 'string',
97                            'required' => true,
98                        ),
99                        'price'                   => array(
100                            'type'     => 'number',
101                            'required' => true,
102                        ),
103                        'currency'                => array(
104                            'type'     => 'string',
105                            'required' => true,
106                        ),
107                        'interval'                => array(
108                            'type'     => 'string',
109                            'required' => true,
110                        ),
111                        'is_editable'             => array(
112                            'type'     => 'boolean',
113                            'required' => false,
114                        ),
115                        'buyer_can_change_amount' => array(
116                            'type' => 'boolean',
117                        ),
118                        'tier'                    => array(
119                            'type'     => 'integer',
120                            'required' => false,
121                        ),
122                        'description'             => array(
123                            'type'     => 'string',
124                            'required' => false,
125                        ),
126                    ),
127                ),
128            )
129        );
130        register_rest_route(
131            $this->namespace,
132            $this->rest_base . '/products/?',
133            array(
134                array(
135                    'methods'             => WP_REST_Server::CREATABLE,
136                    'callback'            => array( $this, 'create_products' ),
137                    'permission_callback' => array( $this, 'can_modify_products_permission_check' ),
138                    'args'                => array(
139                        'currency'    => array(
140                            'type'     => 'string',
141                            'required' => true,
142                        ),
143                        'type'        => array(
144                            'type'     => 'string',
145                            'required' => true,
146                        ),
147                        'is_editable' => array(
148                            'type'     => 'boolean',
149                            'required' => false,
150                        ),
151                    ),
152                ),
153                array(
154                    'methods'             => WP_REST_Server::READABLE,
155                    'callback'            => array( $this, 'list_products' ),
156                    'permission_callback' => array( $this, 'get_status_permission_check' ),
157                ),
158            )
159        );
160        register_rest_route(
161            $this->namespace,
162            $this->rest_base . '/product/(?P<product_id>[0-9]+)/?',
163            array(
164                array(
165                    'methods'             => WP_REST_Server::EDITABLE,
166                    'callback'            => array( $this, 'update_product' ),
167                    'permission_callback' => array( $this, 'can_modify_products_permission_check' ),
168                    'args'                => array(
169                        'title'                   => array(
170                            'type'     => 'string',
171                            'required' => true,
172                        ),
173                        'price'                   => array(
174                            'type'     => 'number',
175                            'required' => true,
176                        ),
177                        'currency'                => array(
178                            'type'     => 'string',
179                            'required' => true,
180                        ),
181                        'interval'                => array(
182                            'type'     => 'string',
183                            'required' => true,
184                        ),
185                        'is_editable'             => array(
186                            'type'     => 'boolean',
187                            'required' => false,
188                        ),
189                        'buyer_can_change_amount' => array(
190                            'type' => 'boolean',
191                        ),
192                        'tier'                    => array(
193                            'type'     => 'integer',
194                            'required' => false,
195                        ),
196                        'description'             => array(
197                            'type'     => 'string',
198                            'required' => false,
199                        ),
200                    ),
201                ),
202                array(
203                    'methods'             => WP_REST_Server::DELETABLE,
204                    'callback'            => array( $this, 'delete_product' ),
205                    'permission_callback' => array( $this, 'can_modify_products_permission_check' ),
206                    'args'                => array(
207                        'cancel_subscriptions' => array(
208                            'type'     => 'boolean',
209                            'required' => false,
210                        ),
211                    ),
212                ),
213            )
214        );
215    }
216
217    /**
218     * Ensure the user has proper permissions for getting status and listing products
219     *
220     * @return boolean
221     */
222    public function get_status_permission_check() {
223        return current_user_can( 'edit_posts' );
224    }
225
226    /**
227     * Ensure the user has proper permissions to modify products
228     *
229     * @return boolean
230     */
231    public function can_modify_products_permission_check() {
232        return current_user_can( 'manage_options' );
233    }
234
235    /**
236     * Automatically generate products according to type.
237     *
238     * @param object $request - request passed from WP.
239     *
240     * @return array|WP_Error
241     */
242    public function create_products( $request ) {
243        $is_editable = isset( $request['is_editable'] ) ? (bool) $request['is_editable'] : null;
244
245        if ( $this->is_wpcom() ) {
246            require_lib( 'memberships' );
247            Memberships_Store_Sandbox::get_instance()->init( true );
248
249            $result = Memberships_Product::generate_default_products( get_current_blog_id(), $request['type'], $request['currency'], $is_editable );
250
251            if ( is_wp_error( $result ) ) {
252                $status = 'invalid_param' === $result->get_error_code() ? 400 : 500;
253                return new WP_Error( $result->get_error_code(), $result->get_error_message(), array( 'status' => $status ) );
254            }
255            return $result;
256        } else {
257            return $this->proxy_request_to_wpcom_as_user( $request, 'products' );
258        }
259
260        return $request;
261    }
262
263    /**
264     * List already-created products.
265     *
266     * @param \WP_REST_Request $request - request passed from WP.
267     *
268     * @return WP_Error|array ['products']
269     */
270    public function list_products( WP_REST_Request $request ) {
271        $is_editable = isset( $request['is_editable'] ) ? (bool) $request['is_editable'] : null;
272        $type        = $request['type'] ?? null;
273
274        if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ) {
275            require_lib( 'memberships' );
276            require_once JETPACK__PLUGIN_DIR . '/modules/memberships/class-jetpack-memberships.php';
277            try {
278                return array( 'products' => $this->list_products_from_wpcom( $request, $type, $is_editable ) );
279            } catch ( \Exception $e ) {
280                return array( 'error' => $e->getMessage() );
281            }
282        } else {
283
284            return $this->proxy_request_to_wpcom_as_user( $request, 'products' );
285        }
286    }
287
288    /**
289     * Do create a product based on data, or pass request to wpcom.
290     *
291     * @param WP_REST_Request $request - request passed from WP.
292     *
293     * @return array|WP_Error
294     */
295    public function create_product( WP_REST_Request $request ) {
296        $payload = $this->get_payload_for_product( $request );
297
298        if ( is_wp_error( $payload ) ) {
299            return $payload;
300        }
301
302        if ( $this->is_wpcom() ) {
303            require_lib( 'memberships' );
304            try {
305                return $this->create_product_from_wpcom( $payload );
306            } catch ( \Exception $e ) {
307                return array( 'error' => $e->getMessage() );
308            }
309        } else {
310            return $this->proxy_request_to_wpcom_as_user( $request, 'product' );
311        }
312    }
313
314    /**
315     * Update an existing memberships product
316     *
317     * @param \WP_REST_Request $request The request passed from WP.
318     *
319     * @return array|WP_Error
320     */
321    public function update_product( \WP_REST_Request $request ) {
322        $product_id = $request->get_param( 'product_id' );
323        $payload    = $this->get_payload_for_product( $request );
324
325        if ( is_wp_error( $payload ) ) {
326            return $payload;
327        }
328
329        if ( $this->is_wpcom() ) {
330            require_lib( 'memberships' );
331            try {
332                return array( 'product' => $this->update_product_from_wpcom( $product_id, $payload ) );
333            } catch ( \Exception $e ) {
334                return array( 'error' => $e->getMessage() );
335            }
336        } else {
337            return $this->proxy_request_to_wpcom_as_user( $request, "product/$product_id" );
338        }
339    }
340
341    /**
342     * Delete an existing memberships product
343     *
344     * @param \WP_REST_Request $request The request passed from WP.
345     *
346     * @return array|WP_Error
347     */
348    public function delete_product( \WP_REST_Request $request ) {
349        $product_id           = $request->get_param( 'product_id' );
350        $cancel_subscriptions = $request->get_param( 'cancel_subscriptions' );
351        if ( $this->is_wpcom() ) {
352            require_lib( 'memberships' );
353            try {
354                $this->delete_product_from_wpcom( $product_id, $cancel_subscriptions );
355                return array( 'deleted' => true );
356            } catch ( \Exception $e ) {
357                return array( 'error' => $e->getMessage() );
358            }
359        } else {
360            return $this->proxy_request_to_wpcom_as_user( $request, "product/$product_id" );
361        }
362    }
363
364    /**
365     * Get a status of connection for the site. If this is Jetpack, pass the request to wpcom.
366     *
367     * @param \WP_REST_Request $request - request passed from WP.
368     *
369     * @return WP_Error|array ['products','connected_account_id','connect_url']
370     */
371    public function get_status( \WP_REST_Request $request ) {
372        $product_type = $request['type'];
373
374        if ( ! empty( $request['source'] ) ) {
375            $source = sanitize_text_field( wp_unslash( $request['source'] ) );
376        } else {
377            $source = 'gutenberg';
378        }
379
380        $is_editable = ! isset( $request['is_editable'] ) ? null : (bool) $request['is_editable'];
381
382        if ( $this->is_wpcom() ) {
383            require_lib( 'memberships' );
384            Memberships_Store_Sandbox::get_instance()->init( true );
385            $blog_id             = get_current_blog_id();
386            $membership_settings = get_memberships_settings_for_site( $blog_id, $product_type, $is_editable, $source );
387
388            if ( is_wp_error( $membership_settings ) ) {
389                // Get error messages from the $membership_settings.
390                $error_codes    = $membership_settings->get_error_codes();
391                $error_messages = array();
392
393                foreach ( $error_codes as $code ) {
394                    $messages = $membership_settings->get_error_messages( $code );
395                    foreach ( $messages as $message ) {
396                        // Sanitize error message
397                        $error_messages[] = esc_html( $message );
398                    }
399                }
400
401                $error_messages_string = implode( ' ', $error_messages );
402                // translators: %s is a list of error messages.
403                $base_message = __( 'Could not get the membership settings due to the following error(s): %s', 'jetpack' );
404                $full_message = sprintf( $base_message, $error_messages_string );
405
406                return new WP_Error( 'membership_settings_error', $full_message, array( 'status' => 404 ) );
407            }
408
409            return (array) $membership_settings;
410        } else {
411            return $this->proxy_request_to_wpcom_as_user( $request, 'status' );
412        }
413    }
414
415    /**
416     * This function throws an exception if it is run outside of wpcom.
417     *
418     * @return void
419     * @throws \Exception If the function is run outside of WPCOM.
420     */
421    private function prevent_running_outside_of_wpcom() {
422        if ( ! $this->is_wpcom() || ! class_exists( 'Memberships_Product' ) ) {
423            throw new \Exception( 'This function is intended to be run from WPCOM' );
424        }
425    }
426
427    /**
428     * List products via the WPCOM-specific Memberships_Product class.
429     *
430     * @param WP_REST_Request $request The request for this endpoint.
431     * @param ?string         $type The type of the products to list.
432     * @param ?bool           $is_editable If we are looking for editable or non-editable products.
433     * @throws \Exception If blog is not known or if there is an error getting products.
434     * @return array List of products.
435     */
436    private function list_products_from_wpcom( WP_REST_Request $request, $type, $is_editable ) {
437        $this->prevent_running_outside_of_wpcom();
438        Memberships_Store_Sandbox::get_instance()->init( true );
439        $blog_id = $request->get_param( 'blog_id' );
440        if ( is_wp_error( $blog_id ) ) {
441            throw new \Exception( 'Unknown blog' );
442        }
443        $list = Memberships_Product::get_product_list( get_current_blog_id(), $type, $is_editable );
444        if ( is_wp_error( $list ) ) {
445            throw new \Exception( $list->get_error_message() );
446        }
447        return $list;
448    }
449
450    /**
451     * Find a product by product id via the WPCOM-specific Memberships_Product class.
452     *
453     * @param string|int $product_id The ID of the product to be found.
454     * @throws \Exception If there is an error getting the product or if the product was not found.
455     * @return object The found product.
456     */
457    private function find_product_from_wpcom( $product_id ) {
458        $this->prevent_running_outside_of_wpcom();
459        Memberships_Store_Sandbox::get_instance()->init( true );
460        $product = Memberships_Product::get_from_post( get_current_blog_id(), $product_id );
461        if ( is_wp_error( $product ) ) {
462            throw new \Exception( $product->get_error_message() );
463        }
464        if ( ! $product || ! $product instanceof Memberships_Product ) {
465            throw new \Exception( __( 'Product not found.', 'jetpack' ) );
466        }
467        return $product;
468    }
469
470    /**
471     * Create a product via the WPCOM-specific Memberships_Product class.
472     *
473     * @param array $payload The request payload which contains details about the product.
474     * @throws \Exception When the product failed to be created.
475     * @return array The newly created product.
476     */
477    private function create_product_from_wpcom( $payload ) {
478        $this->prevent_running_outside_of_wpcom();
479        Memberships_Store_Sandbox::get_instance()->init( true );
480        $product = Memberships_Product::create( get_current_blog_id(), $payload );
481        if ( is_wp_error( $product ) ) {
482            throw new \Exception( __( 'Creating product has failed.', 'jetpack' ) );
483        }
484        return $product->to_array();
485    }
486
487    /**
488     * Update a product via the WPCOM-specific Memberships_Product class.
489     *
490     * @param string|int $product_id The ID of the product being updated.
491     * @param array      $payload The request payload which contains details about the product.
492     * @throws \Exception When there is a problem updating the product.
493     * @return object The newly updated product.
494     */
495    private function update_product_from_wpcom( $product_id, $payload ) {
496        Memberships_Store_Sandbox::get_instance()->init( true );
497        $product         = $this->find_product_from_wpcom( $product_id ); // prevents running outside of wpcom
498        $updated_product = $product->update( $payload );
499        if ( is_wp_error( $updated_product ) ) {
500            throw new \Exception( $updated_product->get_error_message() );
501        }
502        return $updated_product->to_array();
503    }
504
505    /**
506     * Delete a product via the WPCOM-specific Memberships_Product class.
507     *
508     * @param string|int $product_id The ID of the product being deleted.
509     * @param bool       $cancel_subscriptions Whether to cancel subscriptions to the product as well.
510     * @throws \Exception When there is a problem deleting the product.
511     * @return void
512     */
513    private function delete_product_from_wpcom( $product_id, $cancel_subscriptions = false ) {
514        Memberships_Store_Sandbox::get_instance()->init( true );
515        $product = $this->find_product_from_wpcom( $product_id ); // prevents running outside of wpcom
516        $result  = $product->delete( $cancel_subscriptions ? Memberships_Product::CANCEL_SUBSCRIPTIONS : Memberships_Product::KEEP_SUBSCRIPTIONS );
517        if ( is_wp_error( $result ) ) {
518            throw new \Exception( $result->get_error_message() );
519        }
520    }
521
522    /**
523     * Get a payload for creating or updating products by parsing the request.
524     *
525     * @param WP_REST_Request $request The request for this endpoint, containing the details needed to build the payload.
526     * @return array|WP_Error The built payload or WP_Error on validation failure.
527     */
528    private function get_payload_for_product( WP_REST_Request $request ) {
529        $is_editable             = isset( $request['is_editable'] ) ? (bool) $request['is_editable'] : null;
530        $type                    = $request['type'] ?? null;
531        $tier                    = $request['tier'] ?? null;
532        $buyer_can_change_amount = isset( $request['buyer_can_change_amount'] ) && (bool) $request['buyer_can_change_amount'];
533        $interval                = $request['interval'];
534
535        // Validate tier field usage.
536        $tier_validation = $this->validate_tier_field( $request, $tier, $type, $interval );
537        if ( is_wp_error( $tier_validation ) ) {
538            return $tier_validation;
539        }
540
541        $payload = array(
542            'title'                        => $request['title'],
543            'price'                        => $request['price'],
544            'currency'                     => $request['currency'],
545            'buyer_can_change_amount'      => $buyer_can_change_amount,
546            'interval'                     => $interval,
547            'type'                         => $type,
548            'welcome_email_content'        => $request['welcome_email_content'],
549            'subscribe_as_site_subscriber' => $request['subscribe_as_site_subscriber'],
550            'multiple_per_user'            => $request['multiple_per_user'],
551        );
552
553        if ( null !== $tier ) {
554            $payload['tier'] = $tier;
555        }
556
557        // If we pass directly the value "null", it will break the argument validation.
558        if ( null !== $is_editable ) {
559            $payload['is_editable'] = $is_editable;
560        }
561
562        if ( isset( $request['description'] ) ) {
563            $payload['description'] = $request['description'];
564        }
565
566        return $payload;
567    }
568
569    /**
570     * Validate tier field usage for newsletter plans.
571     *
572     * @param WP_REST_Request $request  The request object.
573     * @param string|null     $tier     The tier value to validate.
574     * @param string|null     $type     The product type.
575     * @param string          $interval The product interval.
576     * @return WP_Error|null  Error object if validation fails, null if successful.
577     */
578    private function validate_tier_field( WP_REST_Request $request, $tier, $type, $interval ) {
579        // Only apply tier validation for newsletter plans with type 'tier'.
580        if ( null === $tier || 'tier' !== $type ) {
581            return null;
582        }
583
584        // Monthly plans should not have a tier field.
585        if ( '1 month' === $interval ) {
586            return new WP_Error( 'invalid_tier_usage', __( 'Monthly plans should not have a tier field. The tier field is only used to link yearly plans to their corresponding monthly plans.', 'jetpack' ), array( 'status' => 400 ) );
587        }
588
589        // Yearly plans must have a valid tier that points to a monthly plan.
590        if ( '1 year' === $interval ) {
591            return $this->validate_yearly_tier( $request, $tier );
592        }
593
594        return null;
595    }
596
597    /**
598     * Validate yearly tier requirements.
599     *
600     * @param WP_REST_Request $request The request object.
601     * @param string|int      $tier    The tier value to validate.
602     * @return WP_Error|null  Error object if validation fails, null if successful.
603     */
604    private function validate_yearly_tier( WP_REST_Request $request, $tier ) {
605        if ( ! is_numeric( $tier ) || $tier <= 0 ) {
606            return new WP_Error( 'invalid_tier_id', __( 'Yearly plans must have a valid tier ID that points to an existing monthly plan.', 'jetpack' ), array( 'status' => 400 ) );
607        }
608
609        if ( ! $this->is_wpcom() ) {
610            return null; // Validation will happen on WPCOM side.
611        }
612
613        return $this->validate_tier_references( $request, $tier );
614    }
615
616    /**
617     * Validate that the tier references a valid monthly plan and check for duplicates.
618     *
619     * @param WP_REST_Request $request The request object.
620     * @param string|int      $tier    The tier value to validate.
621     * @return WP_Error|null  Error object if validation fails, null if successful.
622     */
623    private function validate_tier_references( WP_REST_Request $request, $tier ) {
624        require_lib( 'memberships' );
625        Memberships_Store_Sandbox::get_instance()->init( true );
626
627        // Check if the referenced monthly plan exists and is actually a monthly plan.
628        $monthly_plan = Memberships_Product::get_from_post( get_current_blog_id(), $tier );
629        if ( is_wp_error( $monthly_plan ) || ! $monthly_plan ) {
630            return new WP_Error( 'tier_not_found', __( 'The specified tier ID does not correspond to an existing monthly plan.', 'jetpack' ), array( 'status' => 400 ) );
631        }
632
633        $monthly_plan_data = $monthly_plan->to_array();
634        if ( '1 month' !== $monthly_plan_data['interval'] ) {
635            return new WP_Error( 'invalid_tier_interval', __( 'The specified tier ID must point to a monthly plan (1 month interval).', 'jetpack' ), array( 'status' => 400 ) );
636        }
637
638        return $this->check_duplicate_tier_references( $request, $tier );
639    }
640
641    /**
642     * Check for duplicate tier references.
643     *
644     * @param WP_REST_Request $request The request object.
645     * @param string|int      $tier    The tier value to check.
646     * @return WP_Error|null  Error object if duplicate found, null if successful.
647     */
648    private function check_duplicate_tier_references( WP_REST_Request $request, $tier ) {
649        $existing_yearly_plans = Memberships_Product::get_product_list( get_current_blog_id(), 'tier', null, false );
650        if ( is_wp_error( $existing_yearly_plans ) ) {
651            return new WP_Error( 'product_list_error', __( 'Could not retrieve existing products to check for duplicate tier references.', 'jetpack' ), array( 'status' => 500 ) );
652        }
653
654        // Ensure the result is iterable before foreach.
655        if ( ! is_array( $existing_yearly_plans ) && ! $existing_yearly_plans instanceof Traversable ) {
656            return new WP_Error( 'invalid_product_list', __( 'Unexpected error: product list is not iterable.', 'jetpack' ), array( 'status' => 500 ) );
657        }
658
659        foreach ( $existing_yearly_plans as $existing_plan ) {
660            if ( isset( $existing_plan['tier'] ) && (string) $existing_plan['tier'] === (string) $tier && '1 year' === $existing_plan['interval'] ) {
661                // If this is an update, allow it to reference itself.
662                $product_id = $request->get_param( 'product_id' );
663                if ( ! $product_id || (string) $existing_plan['id'] !== (string) $product_id ) {
664                    return new WP_Error( 'duplicate_tier_reference', __( 'Another yearly plan already references this monthly plan. Each monthly plan can only have one corresponding yearly plan.', 'jetpack' ), array( 'status' => 400 ) );
665                }
666            }
667        }
668
669        return null;
670    }
671
672    /**
673     * Returns true if run from WPCOM.
674     *
675     * @return boolean true if run from wpcom, otherwise false.
676     */
677    private function is_wpcom() {
678        return defined( 'IS_WPCOM' ) && IS_WPCOM;
679    }
680}
681
682if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) || Jetpack::is_connection_ready() ) {
683    wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Memberships' );
684}