| 1 |
<?php |
| 2 |
/** |
| 3 |
* Get the User ID of a Goodreads account using its Author ID. |
| 4 |
* |
| 5 |
* @package automattic/jetpack |
| 6 |
*/ |
| 7 |
|
| 8 |
if ( ! defined( 'ABSPATH' ) ) { |
| 9 |
exit( 0 ); |
| 10 |
} |
| 11 |
|
| 12 |
/** |
| 13 |
* Goodreads block endpoint. |
| 14 |
*/ |
| 15 |
class WPCOM_REST_API_V2_Endpoint_Goodreads extends WP_REST_Controller { |
| 16 |
/** |
| 17 |
* Constructor. |
| 18 |
*/ |
| 19 |
public function __construct() { |
| 20 |
add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Register endpoint route. |
| 25 |
*/ |
| 26 |
public function register_routes() { |
| 27 |
register_rest_route( |
| 28 |
'wpcom/v2', |
| 29 |
'/goodreads/user-id', |
| 30 |
array( |
| 31 |
array( |
| 32 |
'methods' => WP_REST_Server::READABLE, |
| 33 |
'callback' => array( $this, 'get_goodreads_user_id' ), |
| 34 |
'permission_callback' => function () { |
| 35 |
return current_user_can( 'edit_posts' ); |
| 36 |
}, |
| 37 |
'args' => array( |
| 38 |
'id' => array( |
| 39 |
'description' => __( 'Goodreads user ID', 'jetpack' ), |
| 40 |
'type' => 'integer', |
| 41 |
'required' => true, |
| 42 |
'minimum' => 1, |
| 43 |
'validate_callback' => function ( $param ) { |
| 44 |
return is_numeric( $param ) && (int) $param > 0; |
| 45 |
}, |
| 46 |
), |
| 47 |
), |
| 48 |
), |
| 49 |
) |
| 50 |
); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Get the user ID from the author ID. |
| 55 |
* |
| 56 |
* @param \WP_REST_Request $request request object. |
| 57 |
* |
| 58 |
* @return \WP_Error|int Goodreads user ID (or 404 error if not found). |
| 59 |
*/ |
| 60 |
public function get_goodreads_user_id( $request ) { |
| 61 |
$profile_id = $request->get_param( 'id' ); |
| 62 |
$url = 'https://www.goodreads.com/author/show/' . $profile_id; |
| 63 |
$response = wp_remote_get( esc_url_raw( $url ) ); |
| 64 |
$not_found = new WP_Error( 'not_found', 'Goodreads user not found.', array( 'status' => 404 ) ); |
| 65 |
|
| 66 |
if ( is_wp_error( $response ) ) { |
| 67 |
return $response; |
| 68 |
} |
| 69 |
|
| 70 |
$body = wp_remote_retrieve_body( $response ); |
| 71 |
$pattern = '/goodreads\.com\/user\/updates_rss\/(\d+)/'; |
| 72 |
|
| 73 |
if ( preg_match( $pattern, $body, $matches ) ) { |
| 74 |
$user_id = intval( $matches[1] ); |
| 75 |
return $user_id; |
| 76 |
} |
| 77 |
|
| 78 |
return $not_found; |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Goodreads' ); |
| 83 |
|