Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.00% covered (danger)
50.00%
12 / 24
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Endpoint_Google_Docs
57.14% covered (warning)
57.14%
12 / 21
0.00% covered (danger)
0.00%
0 / 3
8.83
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 register_routes
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
1.00
 check_document_visibility
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2/**
3 * Validate whether a google doc is available for embedding.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Extensions\GoogleDocsEmbed;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/**
15 * Google Docs block endpoint.
16 */
17class WPCOM_REST_API_V2_Endpoint_Google_Docs extends WP_REST_Controller {
18    /**
19     * Constructor.
20     */
21    public function __construct() {
22        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
23    }
24
25    /**
26     * Register endpoint route.
27     */
28    public function register_routes() {
29        register_rest_route(
30            'wpcom/v2',
31            '/checkGoogleDocVisibility',
32            array(
33                array(
34                    'methods'             => WP_REST_Server::READABLE,
35                    'callback'            => array( $this, 'check_document_visibility' ),
36                    'permission_callback' => function () {
37                        return current_user_can( 'edit_posts' );
38                    },
39                ),
40            )
41        );
42    }
43
44    /**
45     * Check URL
46     *
47     * @param \WP_REST_Request $request request object.
48     *
49     * @return \WP_REST_Response|\WP_Error
50     */
51    public function check_document_visibility( $request ) {
52
53        $document_url       = $request->get_param( 'url' );
54        $document_url       = GoogleDocsEmbed\map_gsuite_url( $document_url );
55        $response_head      = wp_safe_remote_head( $document_url );
56        $is_public_document = ! is_wp_error( $response_head ) && ! empty( $response_head['response']['code'] ) && 200 === absint( $response_head['response']['code'] );
57
58        if ( ! $is_public_document ) {
59            return new \WP_Error( 'Unauthorized', esc_html__( 'The document is not publicly accessible', 'jetpack' ), array( 'status' => 401 ) );
60        }
61
62        return new \WP_REST_Response( '', 200 );
63    }
64}
65
66wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V2_Endpoint_Google_Docs' );