Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.80% covered (warning)
64.80%
81 / 125
70.00% covered (warning)
70.00%
7 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
XMLRPC
64.80% covered (warning)
64.80%
81 / 125
70.00% covered (warning)
70.00%
7 / 10
198.70
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
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
 xmlrpc_methods
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 authorize_videopress_copy
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
8
 create_videopress_copy
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
6
 create_media_item
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
12
 create_copy_attachment
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
14
 update_videopress_media_item
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
42
 update_poster_image
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 authenticate_user
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
1<?php
2/**
3 * The VIdeoPress XMLRPC class
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use WP_Error;
11use WP_User;
12
13/**
14 * VideoPress playback module markup generator.
15 *
16 * @since 0.1.1
17 */
18class XMLRPC {
19
20    /**
21     * Singleton XMLRPC instance.
22     *
23     * @var XMLRPC
24     **/
25    private static $instance = null;
26
27    /**
28     * The current user object.
29     *
30     * @var WP_User
31     */
32    private $current_user;
33
34    /**
35     * Private VideoPress_XMLRPC constructor.
36     *
37     * Use the VideoPress_XMLRPC::init() method to get an instance.
38     */
39    private function __construct() {
40        add_filter( 'jetpack_xmlrpc_methods', array( $this, 'xmlrpc_methods' ), 10, 3 );
41    }
42
43    /**
44     * Initialize the VideoPress_XMLRPC and get back a singleton instance.
45     *
46     * @return XMLRPC
47     */
48    public static function init() {
49        if ( self::$instance === null ) {
50            self::$instance = new XMLRPC();
51        }
52
53        return self::$instance;
54    }
55
56    /**
57     * Adds additional methods the WordPress xmlrpc API for handling VideoPress specific features
58     *
59     * @param array   $methods The Jetpack API methods.
60     * @param array   $core_methods The WordPress Core API methods (ignored).
61     * @param WP_User $user The user object the API request is signed by.
62     *
63     * @return array
64     */
65    public function xmlrpc_methods( $methods, $core_methods, $user ) {
66        if ( $user && $user instanceof WP_User ) {
67            $this->current_user = $user;
68        }
69
70        $methods['jetpack.createMediaItem']             = array( $this, 'create_media_item' );
71        $methods['jetpack.createVideoPressCopy']        = array( $this, 'create_videopress_copy' );
72        $methods['jetpack.authorizeVideoPressCopy']     = array( $this, 'authorize_videopress_copy' );
73        $methods['jetpack.updateVideoPressMediaItem']   = array( $this, 'update_videopress_media_item' );
74        $methods['jetpack.updateVideoPressPosterImage'] = array( $this, 'update_poster_image' );
75
76        return $methods;
77    }
78
79    /**
80     * Check permissions on the real attachment before WordPress.com copies its retained master.
81     *
82     * @since $$next-version$$
83     * @param string $guid The source VideoPress GUID.
84     * @return array Permission acknowledgement or an error response.
85     */
86    public function authorize_videopress_copy( $guid ) {
87        $this->authenticate_user();
88        if ( ! is_string( $guid ) || ! preg_match( '/^[A-Za-z0-9]{8}$/D', $guid )
89            || ! $this->current_user || ! $this->current_user->exists() || ! current_user_can( 'upload_files' ) ) {
90            return array( 'errors' => array( 'videopress_copy_forbidden' => __( 'You cannot copy this video.', 'jetpack-videopress-pkg' ) ) );
91        }
92        $post_id = WPCOM_REST_API_V2_Endpoint_VideoPress::get_video_attachment_id( $guid );
93        if ( ! $post_id || ! current_user_can( 'edit_post', $post_id ) ) {
94            return array( 'errors' => array( 'videopress_copy_forbidden' => __( 'You cannot copy this video.', 'jetpack-videopress-pkg' ) ) );
95        }
96        return array(
97            'authorized' => true,
98            'guid'       => $guid,
99        );
100    }
101
102    /**
103     * Create one idempotent copy attachment; older clients reject this method before inserting a row.
104     *
105     * @since $$next-version$$
106     * @param array $media A single media item carrying its copy request identifier.
107     * @return array The attachment or an error response.
108     */
109    public function create_videopress_copy( $media ) {
110        if ( ! is_array( $media ) || count( $media ) !== 1 || ! isset( $media[0] ) || ! is_array( $media[0] ) || ! array_key_exists( 'videopress_copy_request_id', $media[0] ) ) {
111            return array( 'errors' => array( 'videopress_copy_invalid_request' => __( 'Invalid video copy request.', 'jetpack-videopress-pkg' ) ) );
112        }
113        return $this->create_media_item( $media );
114    }
115
116    /**
117     * This is used by the WPCOM VideoPress uploader in order to create a media item with
118     * specific meta data about an uploaded file. After this, the transcoding session will
119     * update the meta information via the update_videopress_media_item() method.
120     *
121     * Note: This method technically handles the creation of multiple media objects, though
122     * in practice this is never done.
123     *
124     * @param array $media Media items being uploaded.
125     * @return array
126     */
127    public function create_media_item( $media ) {
128        $this->authenticate_user();
129
130        foreach ( $media as & $media_item ) {
131            $url   = is_string( $media_item['url'] ?? null ) ? $media_item['url'] : '';
132            $title = isset( $media_item['title'] ) && '' !== $media_item['title']
133                ? sanitize_text_field( $media_item['title'] )
134                : sanitize_title( basename( $url ) );
135            $guid  = $media['guid'] ?? null;
136
137            if ( array_key_exists( 'videopress_copy_request_id', $media_item ) ) {
138                $media_id = $this->create_copy_attachment( $title, $media_item['videopress_copy_request_id'] );
139                if ( is_wp_error( $media_id ) ) {
140                    return array( 'errors' => array( $media_id->get_error_code() => $media_id->get_error_message() ) );
141                }
142                $media_item['post']                           = get_post( $media_id );
143                $media_item['videopress_copy_request_id_ack'] = $media_item['videopress_copy_request_id'];
144                continue;
145            }
146
147            $media_id = videopress_create_new_media_item( $title, $guid );
148
149            $post_update = array();
150            if ( isset( $media_item['description'] ) && '' !== $media_item['description'] ) {
151                $post_update['post_content'] = sanitize_textarea_field( $media_item['description'] );
152            }
153            if ( isset( $media_item['caption'] ) && '' !== $media_item['caption'] ) {
154                $post_update['post_excerpt'] = sanitize_textarea_field( $media_item['caption'] );
155            }
156            if ( $post_update ) {
157                $post_update['ID'] = $media_id;
158                wp_update_post( $post_update );
159            }
160
161            wp_update_attachment_metadata(
162                $media_id,
163                array(
164                    'original' => array(
165                        'url' => $media_item['url'],
166                    ),
167                )
168            );
169
170            $media_item['post'] = get_post( $media_id );
171        }
172
173        return array( 'media' => $media );
174    }
175
176    /**
177     * Reserve a copy request before inserting its attachment so retries cannot create duplicates.
178     *
179     * @param string $title Attachment title.
180     * @param mixed  $request_id Source GUID and copy request UUID.
181     * @return int|WP_Error The existing or newly created attachment ID.
182     */
183    private function create_copy_attachment( $title, $request_id ) {
184        if ( ! is_string( $request_id ) || ! preg_match( '/^[A-Za-z0-9]{8}:[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/D', $request_id ) ) {
185            return new WP_Error( 'videopress_copy_invalid_request', __( 'Invalid video copy request identifier.', 'jetpack-videopress-pkg' ) );
186        }
187        if ( ! $this->current_user || ! $this->current_user->exists() || ! current_user_can( 'upload_files' ) ) {
188            return new WP_Error( 'videopress_copy_forbidden', __( 'You cannot create a video copy.', 'jetpack-videopress-pkg' ) );
189        }
190
191        $option = 'videopress_copy_attachment_' . hash( 'sha256', $request_id );
192        if ( ! add_option( $option, 0, '', false ) ) {
193            $attachment_id = (int) get_option( $option, 0 );
194            if ( ! $attachment_id ) {
195                return new WP_Error( 'videopress_copy_attachment_pending', __( 'The video copy attachment is still being created.', 'jetpack-videopress-pkg' ) );
196            }
197            if ( 'attachment' !== get_post_type( $attachment_id ) || get_post_meta( $attachment_id, '_videopress_copy_request_id', true ) !== $request_id ) {
198                return new WP_Error( 'videopress_copy_attachment_unavailable', __( 'The video copy attachment is unavailable.', 'jetpack-videopress-pkg' ) );
199            }
200            return $attachment_id;
201        }
202
203        // A pending reservation never expires: a timed-out insert may already have created the attachment.
204        $attachment_id = videopress_create_new_media_item( $title );
205        if ( is_wp_error( $attachment_id ) || ! $attachment_id ) {
206            return new WP_Error( 'videopress_copy_attachment_failed', __( 'The video copy attachment could not be created.', 'jetpack-videopress-pkg' ) );
207        }
208        wp_update_attachment_metadata( $attachment_id, array( 'original' => array( 'url' => '' ) ) );
209        if ( ! add_post_meta( $attachment_id, '_videopress_copy_request_id', $request_id, true ) || ! update_option( $option, $attachment_id, false ) ) {
210            return new WP_Error( 'videopress_copy_attachment_failed', __( 'The video copy attachment could not be recorded.', 'jetpack-videopress-pkg' ) );
211        }
212        return $attachment_id;
213    }
214
215    /**
216     * Update VideoPress metadata for a media item.
217     *
218     * @param array $request Media item to update.
219     *
220     * @return bool
221     */
222    public function update_videopress_media_item( $request ) {
223        $this->authenticate_user();
224
225        $id     = $request['post_id'];
226        $status = $request['status'];
227        $format = $request['format'];
228        $info   = $request['info'];
229
230        $attachment = get_post( $id );
231        if ( ! $attachment ) {
232            return false;
233        }
234
235        $attachment->guid           = $info['original'];
236        $attachment->post_mime_type = 'video/videopress';
237
238        wp_update_post( $attachment );
239
240        // Update the vp guid and set it to a direct meta property.
241        update_post_meta( $id, 'videopress_guid', $info['guid'] );
242
243        $meta = wp_get_attachment_metadata( $id );
244
245        $meta['width']             = $info['width'];
246        $meta['height']            = $info['height'];
247        $meta['original']['url']   = $info['original'];
248        $meta['videopress']        = $info;
249        $meta['videopress']['url'] = 'https://videopress.com/v/' . $info['guid'];
250
251        // Update file statuses
252        if ( ! empty( $format ) ) {
253            $meta['file_statuses'][ $format ] = $status;
254        }
255
256        if ( ! get_post_meta( $id, '_thumbnail_id', true ) ) {
257            // Update the poster in the VideoPress info.
258            $thumbnail_id = videopress_download_poster_image( $info['poster'], $id );
259
260            if ( is_int( $thumbnail_id ) ) {
261                update_post_meta( $id, '_thumbnail_id', $thumbnail_id );
262            }
263        }
264
265        wp_update_attachment_metadata( $id, $meta );
266
267        videopress_update_meta_data( $id );
268
269        // update the meta to tell us that we're processing or complete
270        update_post_meta( $id, 'videopress_status', videopress_is_finished_processing( $id ) ? 'complete' : 'processing' );
271
272        return true;
273    }
274
275    /**
276     * Update poster image for a VideoPress media item.
277     *
278     * @param array $request The media item to update.
279     * @return bool
280     */
281    public function update_poster_image( $request ) {
282        $this->authenticate_user();
283
284        $post_id = $request['post_id'];
285        $poster  = $request['poster'];
286
287        $attachment = get_post( $post_id );
288        if ( ! $attachment ) {
289            return false;
290        }
291
292        $poster = apply_filters( 'jetpack_photon_url', $poster );
293
294        $meta                         = wp_get_attachment_metadata( $post_id );
295        $meta['videopress']['poster'] = $poster;
296        wp_update_attachment_metadata( $post_id, $meta );
297
298        // Update the poster in the VideoPress info.
299        $thumbnail_id = videopress_download_poster_image( $poster, $post_id );
300
301        if ( ! is_int( $thumbnail_id ) ) {
302            return false;
303        }
304
305        update_post_meta( $post_id, '_thumbnail_id', $thumbnail_id );
306
307        return true;
308    }
309
310    /**
311     * Check if the XML-RPC request is signed by a user token, and authenticate the user in WordPress.
312     *
313     * @return bool
314     */
315    private function authenticate_user() {
316        if ( $this->current_user ) {
317            wp_set_current_user( $this->current_user->ID );
318
319            return true;
320        }
321
322        return false;
323    }
324}