Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
29.61% covered (danger)
29.61%
45 / 152
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_JSON_API_Upload_Media_v1_1_Endpoint
39.47% covered (danger)
39.47%
45 / 114
0.00% covered (danger)
0.00%
0 / 4
972.22
0.00% covered (danger)
0.00%
0 / 1
 callback
56.96% covered (warning)
56.96%
45 / 79
0.00% covered (danger)
0.00%
0 / 1
175.01
 rewrite_generic_upload_error
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 check_upload_size
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
156
 force_wpcom_request
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
56
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * Upload media item API endpoint v1.1
4 *
5 * Endpoint: /sites/%s/media/new
6 */
7
8if ( ! defined( 'ABSPATH' ) ) {
9    exit( 0 );
10}
11
12new WPCOM_JSON_API_Upload_Media_v1_1_Endpoint(
13    array(
14        'description'                => 'Upload a new piece of media.',
15        'allow_cross_origin_request' => true,
16        'allow_upload_token_auth'    => true,
17        'group'                      => 'media',
18        'stat'                       => 'media:new',
19        'min_version'                => '1.1',
20        'max_version'                => '1.1',
21        'method'                     => 'POST',
22        'path'                       => '/sites/%s/media/new',
23        'path_labels'                => array(
24            '$site' => '(int|string) Site ID or domain',
25        ),
26
27        'request_format'             => array(
28            'media'      => '(media) An array of media to attach to the post. To upload media, the entire request should be multipart/form-data encoded. Accepts  jpg, jpeg, png, gif, pdf, doc, ppt, odt, pptx, docx, pps, ppsx, xls, xlsx, key. Audio and Video may also be available. See <code>allowed_file_types</code> in the options response of the site endpoint.<br /><br /><strong>Example</strong>:<br />' .
29                            "<code>curl \<br />--form 'media[]=@/path/to/file.jpg' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/media/new'</code>",
30            'media_urls' => '(array) An array of URLs to upload to the post. Errors produced by media uploads, if any, will be in `media_errors` in the response.',
31            'attrs'      => '(array) An array of attributes (`title`, `description`, `caption` `alt` for images, `artist` for audio, `album` for audio, and `parent_id`) are supported to assign to the media uploaded via the `media` or `media_urls` properties. You must use a numeric index for the keys of `attrs` which follows the same sequence as `media` and `media_urls`. <br /><br /><strong>Example</strong>:<br />' .
32                            "<code>curl \<br />--form 'media[]=@/path/to/file1.jpg' \<br />--form 'media_urls[]=http://example.com/file2.jpg' \<br /> \<br />--form 'attrs[0][caption]=This will be the caption for file1.jpg' \<br />--form 'attrs[1][title]=This will be the title for file2.jpg' \<br />-H 'Authorization: BEARER your-token' \<br />'https://public-api.wordpress.com/rest/v1/sites/123/media/new'</code>",
33        ),
34
35        'response_format'            => array(
36            'media'  => '(array) Array of uploaded media objects',
37            'errors' => '(array) Array of error messages of uploading media failures',
38        ),
39
40        'example_request'            => 'https://public-api.wordpress.com/rest/v1.1/sites/82974409/media/new',
41        'example_request_data'       => array(
42            'headers' => array(
43                'authorization' => 'Bearer YOUR_API_TOKEN',
44            ),
45            'body'    => array(
46                'media_urls' => 'https://s.w.org/about/images/logos/codeispoetry-rgb.png',
47            ),
48        ),
49    )
50);
51
52// phpcs:disable PEAR.NamingConventions.ValidClassName.Invalid
53/**
54 * Upload media item API class v1.1
55 *
56 * @phan-constructor-used-for-side-effects
57 */
58class WPCOM_JSON_API_Upload_Media_v1_1_Endpoint extends WPCOM_JSON_API_Endpoint {
59    /**
60     * Upload media item API endpoint callback v1.1
61     *
62     * @param string $path API path.
63     * @param int    $blog_id Blog ID.
64     *
65     * @return array|int|WP_Error|void
66     */
67    public function callback( $path = '', $blog_id = 0 ) {
68        $blog_id = $this->api->switch_to_blog_and_validate_user( $this->api->get_blog_id( $blog_id ) );
69        if ( is_wp_error( $blog_id ) ) {
70            return $blog_id;
71        }
72
73        if ( ! current_user_can( 'upload_files' ) && ! $this->api->is_authorized_with_upload_token() ) {
74            return new WP_Error( 'unauthorized', 'User cannot upload media.', 403 );
75        }
76
77        $input = $this->input( true );
78
79        $media_files = ! empty( $input['media'] ) ? $input['media'] : array();
80        $media_urls  = ! empty( $input['media_urls'] ) ? $input['media_urls'] : array();
81        $media_attrs = ! empty( $input['attrs'] ) ? $input['attrs'] : array();
82
83        if ( empty( $media_files ) && empty( $media_urls ) ) {
84            return new WP_Error( 'invalid_input', 'No media provided in input.' );
85        }
86
87        /*
88         * Attaching an upload to a post is an edit of that post, so a caller-supplied
89         * `parent_id` takes `edit_post` on the target. `upload_files` above says only that
90         * the caller may upload something, never where they may put it.
91         *
92         * Every target is checked here, before the first file is written. Refusing from
93         * inside `handle_media_creation_v1_1()` would leave the items it already created
94         * on disk and in the database, and a retry would upload them again.
95         *
96         * An upload-token request drops `parent_id` instead of being refused. Such a request
97         * runs with no logged-in user by construction -- `is_authorized_with_upload_token()`
98         * fails as soon as `get_current_user_id()` is non-zero -- so it can never
99         * demonstrate `edit_post` on any target, and refusing would break any client that
100         * pairs a token with `parent_id` for no security gain. Dropping lands the item at
101         * `post_parent` 0, the same place `absint()` already puts unusable input. The token
102         * is not treated as trusted here: it is an opaque bearer credential mintable by any
103         * logged-in user via `/sites/%s/media/token`, so it must not buy an attach.
104         *
105         * Zero is exempt: it names no target, and `edit_post` fails closed on 0.
106         */
107        if ( $this->api->is_authorized_with_upload_token() ) {
108            foreach ( $media_attrs as $i => $media_attr ) {
109                $media_attr = (array) $media_attr;
110                unset( $media_attr['parent_id'] );
111                $media_attrs[ $i ] = $media_attr;
112            }
113        } else {
114            foreach ( $media_attrs as $media_attr ) {
115                // An entry may arrive as an object or as something that is neither; casting
116                // keeps a string entry from being indexed as an array.
117                $media_attr = (array) $media_attr;
118
119                if ( empty( $media_attr['parent_id'] ) ) {
120                    continue;
121                }
122
123                $parent_id = absint( $media_attr['parent_id'] );
124
125                if ( $parent_id && ! current_user_can( 'edit_post', $parent_id ) ) {
126                    return new WP_Error( 'unauthorized', 'User cannot edit the parent post', 403 );
127                }
128            }
129        }
130
131        $jetpack_sync    = null;
132        $is_jetpack_site = false;
133        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
134            // For jetpack sites, we send the media via a different method, because the sync is very different.
135            $jetpack_sync    = Jetpack_Media_Sync::summon( $blog_id );
136            $is_jetpack_site = $jetpack_sync->is_jetpack_site();
137        }
138
139        $jetpack_media_files = array();
140        $other_media_files   = array();
141        $media_items         = array();
142        $errors              = array();
143
144        // We're splitting out videos for Jetpack sites.
145        foreach ( $media_files as $media_item ) {
146            if ( isset( $media_item['type'] ) && preg_match( '@^video/@', $media_item['type'] ) && $is_jetpack_site ) {
147                if ( defined( 'IS_WPCOM' ) && IS_WPCOM &&
148                    defined( 'VIDEOPRESS_JETPACK_VIDEO_ENABLED' ) && VIDEOPRESS_JETPACK_VIDEO_ENABLED
149                ) {
150                    // Check that video upload space is available for a Jetpack site (skipped if site is Atomic).
151                    $result = videopress_check_space_available_for_jetpack( $blog_id, $media_item['name'], $media_item['size'] );
152
153                    if ( true !== $result ) {
154                        $this->api->output_early( 400, array( 'errors' => $this->rewrite_generic_upload_error( array( $result ) ) ) );
155                        continue;
156                    }
157                }
158                $jetpack_media_files[] = $media_item;
159            } else {
160                $other_media_files[] = $media_item;
161            }
162        }
163
164        // New Jetpack / VideoPress media upload processing.
165        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
166            if ( count( $jetpack_media_files ) > 0 ) {
167                add_filter( 'upload_mimes', array( $this, 'allow_video_uploads' ) );
168
169                // get_space_used() checks blog upload directory storage,
170                // so filter it temporarily to return only video storage used.
171                add_filter( 'pre_get_space_used', 'videopress_filter_jetpack_get_space_used' );
172
173                $media_items = $jetpack_sync->upload_media( $jetpack_media_files, $this->api );
174
175                $errors = $jetpack_sync->get_errors();
176
177                foreach ( $media_items as & $media_item ) {
178                    // More than likely a post has not been created yet, so we pass in the media item we
179                    // got back from the Jetpack site.
180                    $post       = (object) $media_item['post'];
181                    $media_item = $this->get_media_item_v1_1( $post->ID, $post, $media_item['file'] );
182                }
183                // Remove get_space_used filter after upload.
184                remove_filter( 'pre_get_space_used', 'videopress_filter_jetpack_get_space_used' );
185            }
186        }
187
188        // Normal WPCOM upload processing.
189        if ( count( $other_media_files ) > 0 || count( $media_urls ) > 0 ) {
190            if ( is_multisite() ) { // Do not check for available space in non multisites.
191                add_filter( 'wp_handle_upload_prefilter', array( $this, 'check_upload_size' ), 9 ); // used for direct media uploads.
192                add_filter( 'wp_handle_sideload_prefilter', array( $this, 'check_upload_size' ), 9 ); // used for uploading media via url.
193            }
194
195            if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
196                require_lib( 'tos-acceptance-tracking' );
197                add_filter( 'wp_handle_upload_prefilter', '\\A8C\\TOS_Acceptance_Tracking\\handle_uploads_wpcomtos_blog' );
198            }
199
200            $create_media = $this->handle_media_creation_v1_1( $other_media_files, $media_urls, $media_attrs );
201            $media_ids    = $create_media['media_ids'];
202            $errors       = $create_media['errors'];
203
204            $media_items = array();
205            foreach ( $media_ids as $media_id ) {
206                $media_items[] = $this->get_media_item_v1_1( $media_id );
207            }
208        }
209
210        if ( array() === $media_items ) {
211            return $this->api->output_early( 400, array( 'errors' => $this->rewrite_generic_upload_error( $errors ) ) );
212        }
213
214        $results = array();
215        foreach ( $media_items as $media_item ) {
216            if ( is_wp_error( $media_item ) ) {
217                $errors[] = array(
218                    'error'   => $media_item->get_error_code(),
219                    'message' => $media_item->get_error_message(),
220                );
221
222            } else {
223                $results[] = $media_item;
224            }
225        }
226
227        $response = array( 'media' => $results );
228
229        if ( is_countable( $errors ) && count( $errors ) > 0 ) {
230            $response['errors'] = $this->rewrite_generic_upload_error( $errors );
231        }
232
233        return $response;
234    }
235
236    /**
237     * This changes the generic "upload_error" code to something more meaningful if possible
238     *
239     * @param  array $errors Errors for the uploaded file.
240     * @return array         The same array with an improved error message.
241     */
242    public function rewrite_generic_upload_error( $errors ) {
243        foreach ( $errors as $k => $error ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
244            if ( 'upload_error' === $error['error'] && str_contains( $error['message'], '|' ) ) {
245                list( $errors[ $k ]['error'], $errors[ $k ]['message'] ) = explode( '|', $error['message'], 2 ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
246            }
247        }
248        return $errors;
249    }
250
251    /**
252     * Determine if uploaded file exceeds space quota on multisite.
253     *
254     * This is a copy of the core function with added functionality, synced
255     * with this with WP_REST_Attachments_Controller::check_upload_size()
256     * to allow for specifying a better error message.
257     *
258     * @param array $file $_FILES array for a given file.
259     * @return array Maybe extended with an error message.
260     */
261    public function check_upload_size( $file ) {
262        if ( get_site_option( 'upload_space_check_disabled' ) ) {
263            return $file;
264        }
265
266        if ( isset( $file['error'] ) && $file['error'] > 0 ) { // There's already an error. Error Codes Reference: https://www.php.net/manual/en/features.file-upload.errors.php .
267            return $file;
268        }
269
270        // We don't know if this is an upload or a sideload, but in either case the tmp_name should be a path, not a URL.
271        if ( wp_parse_url( $file['tmp_name'], PHP_URL_SCHEME ) !== null ) {
272            $file['error'] = 'rest_upload_invalid|' . __( 'Specified file failed upload test.', 'default' ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
273            return $file;
274        }
275
276        if ( defined( 'WP_IMPORTING' ) ) {
277            return $file;
278        }
279
280        $space_left = get_upload_space_available();
281
282        $file_size = filesize( $file['tmp_name'] );
283        if ( $space_left < $file_size ) {
284            /* translators: %s: Required disk space in kilobytes. */
285            $file['error'] = 'rest_upload_limited_space|' . sprintf( __( 'Not enough space to upload. %s KB needed.', 'default' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
286        }
287
288        $max_upload_size = KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 );
289        if ( defined( 'IS_WPCOM' ) && IS_WPCOM && defined( 'WPCOM_MAX_UPLOAD_FILE_SIZE' ) ) {
290            $max_upload_size = WPCOM_MAX_UPLOAD_FILE_SIZE;
291        }
292
293        if ( $file_size > $max_upload_size ) {
294            /* translators: %s: Maximum allowed file size in kilobytes. */
295            $file['error'] = 'rest_upload_file_too_big|' . sprintf( __( 'This file is too big. Files must be less than %s KB in size.', 'jetpack' ), $max_upload_size / KB_IN_BYTES );
296        }
297
298        if ( upload_is_user_over_quota( false ) ) {
299            $file['error'] = 'rest_upload_user_quota_exceeded|' . __( 'You have used your space quota. Please delete files before uploading.', 'default' ); // phpcs:ignore WordPress.WP.I18n.TextDomainMismatch
300        }
301
302        return $file;
303    }
304    /**
305     * Force to use the WPCOM API instead of proxy back to the Jetpack API if the blog is a paid Jetpack
306     * blog w/ the VideoPress module enabled AND the uploaded file is a video.
307     *
308     * @param int $blog_id Blog ID.
309     * @return bool
310     */
311    public function force_wpcom_request( $blog_id ) {
312
313        // We don't need to do anything if VideoPress is not enabled for the blog.
314        if ( ! is_videopress_enabled_on_jetpack_blog( $blog_id ) ) {
315            return false;
316        }
317
318        // Check to see if the upload is not a video type, if not then return false.
319        $input       = $this->input( true );
320        $media_files = ! empty( $input['media'] ) ? $input['media'] : array();
321
322        if ( empty( $media_files ) ) {
323            return false;
324        }
325
326        foreach ( $media_files as $media_item ) {
327            if ( ! isset( $media_item['type'] ) || ! preg_match( '@^video/@', $media_item['type'] ) ) {
328                return false;
329            }
330        }
331
332        // The API request should be for a blog w/ Jetpack, A valid plan, has VideoPress enabled,
333        // and is a video file. Let's let it through.
334        return true;
335    }
336}