| 1 |
<?php |
| 2 |
|
| 3 |
/** |
| 4 |
* Subscribers: Get subscriber count |
| 5 |
* |
| 6 |
* @since 6.9 |
| 7 |
*/ |
| 8 |
class WPCOM_REST_API_V2_Endpoint_Subscribers extends WP_REST_Controller { |
| 9 |
function __construct() { |
| 10 |
$this->namespace = 'wpcom/v2'; |
| 11 |
$this->rest_base = 'subscribers'; |
| 12 |
// This endpoint *does not* need to connect directly to Jetpack sites. |
| 13 |
$this->wpcom_is_wpcom_only_endpoint = true; |
| 14 |
add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 15 |
} |
| 16 |
|
| 17 |
public function register_routes() { |
| 18 |
// GET /sites/<blog_id>/subscribers/count - Return number of subscribers for this site. |
| 19 |
register_rest_route( $this->namespace, '/' . $this->rest_base . '/count', array( |
| 20 |
array( |
| 21 |
'methods' => WP_REST_Server::READABLE, |
| 22 |
'callback' => array( $this, 'get_subscriber_count' ), |
| 23 |
'permission_callback' => array( $this, 'readable_permission_check' ), |
| 24 |
) |
| 25 |
) ); |
| 26 |
} |
| 27 |
|
| 28 |
public function readable_permission_check() { |
| 29 |
if ( ! current_user_can_for_blog( get_current_blog_id(), 'edit_posts' ) ) { |
| 30 |
return new WP_Error( 'authorization_required', 'Only users with the permission to edit posts can see the subscriber count.', array( 'status' => 401 ) ); |
| 31 |
} |
| 32 |
|
| 33 |
return true; |
| 34 |
} |
| 35 |
|
| 36 |
/** |
| 37 |
* Retrieves subscriber count |
| 38 |
* |
| 39 |
* @param WP_REST_Request $request incoming API request info |
| 40 |
* @return array data object containing subscriber count |
| 41 |
*/ |
| 42 |
public function get_subscriber_count( $request ) { |
| 43 |
// Get the most up to date subscriber count when request is not a test |
| 44 |
if ( ! Jetpack_Constants::is_defined( 'TESTING_IN_JETPACK' ) ) { |
| 45 |
delete_transient( 'wpcom_subscribers_total' ); |
| 46 |
} |
| 47 |
|
| 48 |
$subscriber_info = Jetpack_Subscriptions_Widget::fetch_subscriber_count(); |
| 49 |
$subscriber_count = $subscriber_info['value']; |
| 50 |
|
| 51 |
return array( |
| 52 |
'count' => $subscriber_count |
| 53 |
); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
if ( |
| 58 |
Jetpack::is_module_active( 'subscriptions' ) || |
| 59 |
( Jetpack_Constants::is_defined( 'TESTING_IN_JETPACK' ) && Jetpack_Constants::get_constant( 'TESTING_IN_JETPACK' ) ) |
| 60 |
) { |
| 61 |
wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Subscribers' ); |
| 62 |
} |
| 63 |
|