| 1 |
<?php |
| 2 |
/** |
| 3 |
* Get blog stats. |
| 4 |
* |
| 5 |
* @package automattic/jetpack |
| 6 |
*/ |
| 7 |
|
| 8 |
if ( ! defined( 'ABSPATH' ) ) { |
| 9 |
exit( 0 ); |
| 10 |
} |
| 11 |
|
| 12 |
if ( ! class_exists( 'Jetpack_Blog_Stats_Helper' ) ) { |
| 13 |
require_once JETPACK__PLUGIN_DIR . '/_inc/lib/class-jetpack-blog-stats-helper.php'; |
| 14 |
} |
| 15 |
|
| 16 |
/** |
| 17 |
* Blog Stats block endpoint. |
| 18 |
*/ |
| 19 |
class WPCOM_REST_API_V2_Endpoint_Blog_Stats extends WP_REST_Controller { |
| 20 |
/** |
| 21 |
* Constructor. |
| 22 |
*/ |
| 23 |
public function __construct() { |
| 24 |
add_action( 'rest_api_init', array( $this, 'register_routes' ) ); |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Register endpoint routes. |
| 29 |
*/ |
| 30 |
public function register_routes() { |
| 31 |
register_rest_route( |
| 32 |
'wpcom/v2', |
| 33 |
'/blog-stats', |
| 34 |
array( |
| 35 |
array( |
| 36 |
'methods' => WP_REST_Server::READABLE, |
| 37 |
'callback' => array( $this, 'get_blog_stats' ), |
| 38 |
'permission_callback' => function () { |
| 39 |
return current_user_can( 'edit_posts' ); |
| 40 |
}, |
| 41 |
'args' => array( |
| 42 |
'post_id' => array( |
| 43 |
'description' => __( 'Post ID to obtain stats for.', 'jetpack' ), |
| 44 |
'type' => array( 'string', 'integer' ), |
| 45 |
'required' => false, |
| 46 |
'validate_callback' => function ( $param ) { |
| 47 |
return is_numeric( $param ); |
| 48 |
}, |
| 49 |
), |
| 50 |
), |
| 51 |
), |
| 52 |
) |
| 53 |
); |
| 54 |
} |
| 55 |
|
| 56 |
/** |
| 57 |
* Get the blog stats. |
| 58 |
* |
| 59 |
* @param \WP_REST_Request $request Request object. |
| 60 |
* |
| 61 |
* @return array Blog stats. |
| 62 |
*/ |
| 63 |
public function get_blog_stats( $request ) { |
| 64 |
$post_id = $request->get_param( 'post_id' ); |
| 65 |
|
| 66 |
return array( |
| 67 |
'post-views' => Jetpack_Blog_Stats_Helper::get_stats( |
| 68 |
array( |
| 69 |
'statsOption' => 'post', |
| 70 |
'postId' => $post_id, |
| 71 |
) |
| 72 |
), |
| 73 |
'blog-visitors' => Jetpack_Blog_Stats_Helper::get_stats( |
| 74 |
array( |
| 75 |
'statsOption' => 'blog', |
| 76 |
'statsData' => 'visitors', |
| 77 |
) |
| 78 |
), |
| 79 |
'blog-views' => Jetpack_Blog_Stats_Helper::get_stats( |
| 80 |
array( |
| 81 |
'statsOption' => 'blog', |
| 82 |
'statsData' => 'views', |
| 83 |
) |
| 84 |
), |
| 85 |
); |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Blog_Stats' ); |
| 90 |
|