Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
52.11% covered (warning)
52.11%
74 / 142
27.27% covered (danger)
27.27%
3 / 11
CRAP
0.00% covered (danger)
0.00%
0 / 1
AJAX
52.11% covered (warning)
52.11%
74 / 142
27.27% covered (danger)
27.27%
3 / 11
387.19
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 init
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 is_valid_guid
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
3.33
 wp_ajax_videopress_get_playback_jwt
73.33% covered (warning)
73.33%
11 / 15
0.00% covered (danger)
0.00%
0 / 1
7.93
 is_current_user_authed_for_video
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 request_jwt_from_wpcom
64.71% covered (warning)
64.71%
11 / 17
0.00% covered (danger)
0.00%
0 / 1
9.15
 wp_ajax_videopress_get_upload_jwt
40.00% covered (danger)
40.00%
14 / 35
0.00% covered (danger)
0.00%
0 / 1
63.60
 wp_ajax_complete_upload
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
 wp_ajax_videopress_get_upload_token
51.85% covered (warning)
51.85%
14 / 27
0.00% covered (danger)
0.00%
0 / 1
12.47
 wp_ajax_update_transcoding_status
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 get_videopress_blog_id
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3namespace Automattic\Jetpack\VideoPress;
4
5use Automattic\Jetpack\Connection\Client;
6
7/**
8 * VideoPress AJAX action handlers and utilities.
9 *
10 * Note: this is also being used on WordPress.com.
11 * Use IS_WPCOM checks for functionality that is specific to WPCOM/Jetpack.
12 */
13class AJAX {
14
15    /**
16     * Singleton AJAX instance.
17     *
18     * @var AJAX
19     **/
20    private static $instance = null;
21
22    /**
23     * Private AJAX constructor.
24     *
25     * Use the AJAX::init() method to get an instance.
26     */
27    private function __construct() {
28        add_action( 'wp_ajax_videopress-get-upload-token', array( $this, 'wp_ajax_videopress_get_upload_token' ) );
29        add_action( 'wp_ajax_videopress-complete-upload', array( $this, 'wp_ajax_complete_upload' ) );
30        add_action( 'wp_ajax_videopress-get-upload-jwt', array( $this, 'wp_ajax_videopress_get_upload_jwt' ) );
31        add_action( 'wp_ajax_nopriv_videopress-get-playback-jwt', array( $this, 'wp_ajax_videopress_get_playback_jwt' ) );
32        add_action( 'wp_ajax_videopress-get-playback-jwt', array( $this, 'wp_ajax_videopress_get_playback_jwt' ) );
33
34        add_action(
35            'wp_ajax_videopress-update-transcoding-status',
36            array(
37                $this,
38                'wp_ajax_update_transcoding_status',
39            ),
40            -1
41        );
42    }
43
44    /**
45     * Initialize the AJAX and get back a singleton instance.
46     *
47     * @return AJAX
48     */
49    public static function init() {
50        if ( self::$instance === null ) {
51            self::$instance = new AJAX();
52        }
53
54        return self::$instance;
55    }
56
57    /**
58     * Validate a guid.
59     *
60     * @param string $guid The guid to validate.
61     *
62     * @return bool
63     **/
64    private function is_valid_guid( $guid ) {
65        if ( empty( $guid ) ) {
66            return false;
67        }
68
69        preg_match( '/^[a-z0-9]{8}$/i', $guid, $matches );
70
71        if ( empty( $matches ) ) {
72            return false;
73        }
74
75        return true;
76    }
77
78    /**
79     * Ajax method that is used by the VideoPress player to get a token to play a video.
80     *
81     * This is used for both logged in and logged out users.
82     *
83     * @return never
84     */
85    public function wp_ajax_videopress_get_playback_jwt() {
86        $guid             = filter_input( INPUT_POST, 'guid' );
87        $embedded_post_id = filter_input( INPUT_POST, 'post_id', FILTER_VALIDATE_INT );
88        $selected_plan_id = filter_input( INPUT_POST, 'subscription_plan_id' );
89
90        if ( empty( $embedded_post_id ) ) {
91            $embedded_post_id = 0;
92        }
93
94        if ( empty( $guid ) || ! $this->is_valid_guid( $guid ) ) {
95            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
96            wp_send_json_error( array( 'message' => __( 'need a guid', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
97        }
98
99        if ( ! $this->is_current_user_authed_for_video( $guid, $embedded_post_id, $selected_plan_id ) ) {
100            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
101            wp_send_json_error( array( 'message' => __( 'You cannot view this video.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
102        }
103
104        $token = $this->request_jwt_from_wpcom( $guid );
105
106        if ( empty( $token ) ) {
107            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
108            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress playback JWT. Please try again later. (empty upload token)', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
109        }
110
111        if ( is_wp_error( $token ) ) {
112            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
113            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress upload JWT. Please try again later.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
114        }
115
116        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
117        wp_send_json_success( array( 'jwt' => $token ), null, JSON_UNESCAPED_SLASHES );
118    }
119
120    /**
121     * Determines if the current user can view the provided video. Only ever gets fired if site-wide private videos are enabled.
122     *
123     * Filterable for 3rd party plugins.
124     *
125     * @param string $guid             The video id being checked.
126     * @param int    $embedded_post_id The post id the video is embedded in or 0.
127     * @param int    $selected_plan_id The plan id the earn block this video is embedded in has.
128     */
129    private function is_current_user_authed_for_video( $guid, $embedded_post_id, $selected_plan_id = 0 ) {
130        return Access_Control::instance()->is_current_user_authed_for_video( $guid, $embedded_post_id, $selected_plan_id );
131    }
132
133    /**
134     * Requests JWT from wpcom.
135     *
136     * @param string $guid The video id being checked.
137     */
138    private function request_jwt_from_wpcom( $guid ) {
139        if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'video_wpcom_get_playback_jwt_for_guid' ) ) {
140            $jwt_data = video_wpcom_get_playback_jwt_for_guid( $guid );
141            if ( is_wp_error( $jwt_data ) ) {
142                return false;
143            }
144            return $jwt_data->metadata_token;
145        }
146
147        $video_blog_id = $this->get_videopress_blog_id();
148        $args          = array(
149            'method' => 'POST',
150        );
151
152        $endpoint = "sites/{$video_blog_id}/media/videopress-playback-jwt/{$guid}";
153        $result   = Client::wpcom_json_api_request_as_blog( $endpoint, 'v2', $args, null, 'wpcom' );
154        if ( is_wp_error( $result ) ) {
155            return $result;
156        }
157
158        $response = json_decode( $result['body'], true );
159
160        if ( empty( $response['metadata_token'] ) ) {
161            return false;
162        }
163
164        return $response['metadata_token'];
165    }
166
167    /**
168     * Ajax method that is used by the VideoPress uploader to get a token to upload a file to the wpcom api.
169     *
170     * @return never
171     */
172    public function wp_ajax_videopress_get_upload_jwt() {
173        if ( ! current_user_can( 'upload_files' ) ) {
174            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
175            wp_send_json_error( array( 'message' => __( 'You do not have permission to upload files.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
176        }
177
178        if ( ! ( defined( 'IS_WPCOM' ) && IS_WPCOM ) && isset( $_POST['filename'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Verified before allocation below.
179            check_ajax_referer( 'videopress-upload', 'nonce' );
180            $post_id = isset( $_POST['attachment_id'] ) && is_scalar( $_POST['attachment_id'] ) ? absint( $_POST['attachment_id'] ) : 0;
181            if ( $post_id && ! current_user_can( 'edit_post', $post_id ) ) {
182                wp_send_json_error( array( 'message' => __( 'You cannot edit this attachment.', 'jetpack-videopress-pkg' ) ), 403, JSON_UNESCAPED_SLASHES );
183            }
184            $response = $post_id ? Upload_Session::token( $post_id ) : Upload_Session::start( sanitize_text_field( wp_unslash( is_string( $_POST['filename'] ) ? $_POST['filename'] : '' ) ) );
185            if ( is_wp_error( $response ) ) {
186                $data = $response->get_error_data();
187                $data = is_array( $data ) ? $data : array();
188                wp_send_json_error(
189                    array(
190                        'message'       => $response->get_error_message(),
191                        'code'          => $response->get_error_code(),
192                        'attachment_id' => $data['attachment_id'] ?? 0,
193                    ),
194                    503,
195                    JSON_UNESCAPED_SLASHES
196                );
197            }
198            $response['upload_action_url'] = videopress_make_resumable_upload_path( (int) VideoPressToken::blog_id() );
199            wp_send_json_success( $response, 200, JSON_UNESCAPED_SLASHES );
200        }
201
202        $video_blog_id = $this->get_videopress_blog_id();
203        $args          = array(
204            'method' => 'POST',
205        );
206
207        $endpoint = "sites/{$video_blog_id}/media/videopress-upload-jwt";
208        $result   = Client::wpcom_json_api_request_as_blog( $endpoint, 'v2', $args, null, 'wpcom' );
209        if ( is_wp_error( $result ) ) {
210            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
211            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress upload JWT. Please try again later.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
212        }
213
214        $response = json_decode( $result['body'], true );
215
216        if ( empty( $response['upload_token'] ) ) {
217            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
218            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress upload JWT. Please try again later. (empty upload token)', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
219        }
220
221        $response['upload_action_url'] = videopress_make_resumable_upload_path( $video_blog_id );
222
223        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
224        wp_send_json_success( $response, null, JSON_UNESCAPED_SLASHES );
225    }
226
227    /**
228     * Finalize only an editable attachment whose server-side reservation completed.
229     *
230     * @return never
231     */
232    public function wp_ajax_complete_upload() {
233        check_ajax_referer( 'videopress-upload', 'nonce' );
234        $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0;
235        if ( ! current_user_can( 'upload_files' ) || ! current_user_can( 'edit_post', $post_id ) ) {
236            wp_send_json_error( array( 'message' => __( 'You cannot edit this attachment.', 'jetpack-videopress-pkg' ) ), 403, JSON_UNESCAPED_SLASHES );
237        }
238        $result = Upload_Session::get( $post_id ) ? Upload_Session::complete( $post_id ) : true;
239        if ( is_wp_error( $result ) ) {
240            wp_send_json_error( array( 'message' => $result->get_error_message() ), (int) ( $result->get_error_data()['status'] ?? 503 ), JSON_UNESCAPED_SLASHES );
241        }
242        wp_send_json_success( true, 200, JSON_UNESCAPED_SLASHES );
243    }
244
245    /**
246     * Ajax method that is used by the VideoPress uploader to get a token to upload a file to the wpcom api.
247     *
248     * @return never
249     */
250    public function wp_ajax_videopress_get_upload_token() {
251        if ( ! current_user_can( 'upload_files' ) ) {
252            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
253            wp_send_json_error( array( 'message' => __( 'You do not have permission to upload files.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
254        }
255
256        $video_blog_id = $this->get_videopress_blog_id();
257
258        // On WordPress.com the classic `sites/{id}/media/token` (rest/v1.1) endpoint
259        // isn't reachable in-process (WPCOM_API_Direct only dispatches WP-REST routes),
260        // so mint the token via VideoPressToken, which has its own IS_WPCOM branch that
261        // mints locally. `get_videopress_blog_id()` is the current blog on Simple, matching
262        // the minted token. The self-hosted remote path below is left unchanged.
263        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
264            try {
265                $upload_token = VideoPressToken::videopress_onetime_upload_token();
266            } catch ( Upload_Exception $e ) {
267                // Explicit 200: identical to the null default (admin-ajax errors
268                // ride the success:false envelope), but typed as the phpdoc wants.
269                wp_send_json_error( array( 'message' => $e->getMessage() ), 200, JSON_UNESCAPED_SLASHES );
270            }
271
272            // `upload_action_url` (from `videopress_make_media_upload_path()`) is omitted:
273            // that helper isn't loaded in the Simple admin-ajax context, and only the
274            // legacy upload-form flow reads it — the track/poster consumers use the token
275            // and blog id, not the URL.
276            wp_send_json_success(
277                array(
278                    'upload_token'   => $upload_token,
279                    'upload_blog_id' => $video_blog_id,
280                ),
281                200,
282                JSON_UNESCAPED_SLASHES
283            );
284        }
285
286        $args = array(
287            'method' => 'POST',
288        );
289
290        $endpoint = "sites/{$video_blog_id}/media/token";
291        $result   = Client::wpcom_json_api_request_as_blog( $endpoint, Client::WPCOM_JSON_API_VERSION, $args );
292
293        if ( is_wp_error( $result ) ) {
294            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
295            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress upload token. Please try again later.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
296        }
297
298        $response = json_decode( $result['body'], true );
299
300        if ( empty( $response['upload_token'] ) ) {
301            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
302            wp_send_json_error( array( 'message' => __( 'Could not obtain a VideoPress upload token. Please try again later.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
303        }
304
305        $response['upload_action_url'] = videopress_make_media_upload_path( $video_blog_id );
306
307        // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
308        wp_send_json_success( $response, null, JSON_UNESCAPED_SLASHES );
309    }
310
311    /**
312     * Ajax action to update the video transcoding status from the WPCOM API.
313     *
314     * @return never
315     */
316    public function wp_ajax_update_transcoding_status() {
317        if ( ! isset( $_POST['post_id'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Informational AJAX response.
318            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
319            wp_send_json_error( array( 'message' => __( 'A valid post_id is required.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
320        }
321
322        $post_id = (int) $_POST['post_id']; // phpcs:ignore WordPress.Security.NonceVerification.Missing
323
324        if ( ! videopress_update_meta_data( $post_id ) ) {
325            // @phan-suppress-next-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
326            wp_send_json_error( array( 'message' => __( 'That post does not have a VideoPress video associated to it.', 'jetpack-videopress-pkg' ) ), null, JSON_UNESCAPED_SLASHES );
327        }
328
329        wp_send_json_success(
330            array(
331                'message' => __( 'Status updated', 'jetpack-videopress-pkg' ),
332                'status'  => videopress_get_transcoding_status( $post_id ),
333            ),
334            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
335            JSON_UNESCAPED_SLASHES
336        );
337    }
338
339    /**
340     * Returns the proper blog id depending on Jetpack or WP.com
341     *
342     * @return int the blog id
343     */
344    public function get_videopress_blog_id() {
345        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
346            return get_current_blog_id();
347        }
348
349        $options = Options::get_options();
350        return $options['shadow_blog_id'];
351    }
352}