Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
72.16% covered (warning)
72.16%
127 / 176
47.37% covered (danger)
47.37%
9 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Attachment_Handler
72.16% covered (warning)
72.16%
127 / 176
47.37% covered (danger)
47.37%
9 / 19
152.39
0.00% covered (danger)
0.00%
0 / 1
 init
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
3.00
 maybe_get_attached_url_for_videopress
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 add_video_upload_mimes
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 filter_video_mimes
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 delete_video_wpcom
59.26% covered (warning)
59.26%
16 / 27
0.00% covered (danger)
0.00%
0 / 1
8.43
 explain_rest_delete_failure
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 delete_video_poster_attachment
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 wp_mime_type_icon
66.67% covered (warning)
66.67%
4 / 6
0.00% covered (danger)
0.00%
0 / 1
4.59
 add_videopress_extenstion
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 prepare_attachment_for_js
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 conversion_failure_field
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 ajax_query_attachments_args
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 media_list_table_query
21.43% covered (danger)
21.43%
3 / 14
0.00% covered (danger)
0.00%
0 / 1
30.77
 disable_delete_if_disconnected
57.14% covered (warning)
57.14%
4 / 7
0.00% covered (danger)
0.00%
0 / 1
8.83
 enqueue_media_library_poll
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 enqueue_media_library_bulk_delete
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
7
 enqueue_media_library_styles
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 heartbeat_settings
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 heartbeat_received
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
1<?php
2/**
3 * VideoPress Attachment_Handler
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use Automattic\Jetpack\Connection\Client;
11use Automattic\Jetpack\Current_Plan;
12use WP_Error;
13use WP_Post;
14
15/**
16 * VideoPress Attachment_Handler class.
17 */
18class Attachment_Handler {
19
20    /**
21     * Seconds to wait for WordPress.com to delete a video; it often takes close to 10, the Connection client's default.
22     */
23    const DELETE_TIMEOUT = 60;
24
25    /**
26     * Why the last VideoPress delete in this request was blocked, if it was.
27     *
28     * @var string|null
29     */
30    private static $delete_error = null;
31
32    /**
33     * Initializer
34     *
35     * This method should be called only once by the Initializer class. Do not call this method again.
36     */
37    public static function init() {
38
39        if ( ! Status::is_active() ) {
40            return;
41        }
42
43        add_filter( 'wp_get_attachment_url', array( __CLASS__, 'maybe_get_attached_url_for_videopress' ), 10, 2 );
44        add_filter( 'get_attached_file', array( __CLASS__, 'maybe_get_attached_url_for_videopress' ), 10, 2 );
45
46        if ( Current_Plan::supports( 'videopress' ) ) {
47            add_filter( 'upload_mimes', array( __CLASS__, 'add_video_upload_mimes' ), 999 );
48        }
49
50        add_filter( 'pre_delete_attachment', array( __CLASS__, 'delete_video_wpcom' ), 10, 2 );
51        add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'explain_rest_delete_failure' ) );
52        add_filter( 'wp_mime_type_icon', array( __CLASS__, 'wp_mime_type_icon' ), 10, 3 );
53        add_filter( 'wp_video_extensions', array( __CLASS__, 'add_videopress_extenstion' ) );
54
55        add_filter( 'attachment_fields_to_edit', array( __CLASS__, 'conversion_failure_field' ), 10, 2 );
56        add_filter( 'wp_prepare_attachment_for_js', array( __CLASS__, 'prepare_attachment_for_js' ) );
57        add_filter( 'ajax_query_attachments_args', array( __CLASS__, 'ajax_query_attachments_args' ) );
58        add_action( 'pre_get_posts', array( __CLASS__, 'media_list_table_query' ) );
59
60        add_filter( 'user_has_cap', array( __CLASS__, 'disable_delete_if_disconnected' ), 10, 3 );
61
62        add_action( 'admin_print_scripts-upload.php', array( __CLASS__, 'enqueue_media_library_poll' ) );
63        add_action( 'admin_print_scripts-upload.php', array( __CLASS__, 'enqueue_media_library_bulk_delete' ) );
64        add_action( 'admin_print_styles-upload.php', array( __CLASS__, 'enqueue_media_library_styles' ) );
65        add_filter( 'heartbeat_received', array( __CLASS__, 'heartbeat_received' ), 10, 2 );
66    }
67
68    /**
69     * Returns the VideoPress URL for the give post id, otherwise returns the provided default.
70     *
71     * This is an attachment-based filter handler.
72     *
73     * @param string $default The default return value if post id is not a VideoPress video.
74     * @param int    $post_id The post id for the current attachment.
75     */
76    public static function maybe_get_attached_url_for_videopress( $default, $post_id ) {
77        $videopress_url = videopress_get_attachment_url( $post_id );
78
79        if ( null !== $videopress_url ) {
80            return $videopress_url;
81        }
82
83        return $default;
84    }
85
86    /**
87     * Makes sure that all video mimes are added in, as multi site installs can remove them.
88     *
89     * @param array $existing_mimes Mime types to extend/filter.
90     * @return array
91     */
92    public static function add_video_upload_mimes( $existing_mimes = array() ) {
93        $mime_types  = wp_get_mime_types();
94        $video_types = array_filter( $mime_types, array( __CLASS__, 'filter_video_mimes' ) );
95
96        foreach ( $video_types as $key => $value ) {
97            $existing_mimes[ $key ] = $value;
98        }
99
100        // Make sure that videopress mimes are considered videos.
101        $existing_mimes['videopress'] = 'video/videopress';
102
103        return $existing_mimes;
104    }
105
106    /**
107     * Filter designed to get rid of non video mime types.
108     *
109     * @param string $value Mime type to filter.
110     * @return int
111     */
112    public static function filter_video_mimes( $value ) {
113        return preg_match( '@^video/@', $value );
114    }
115
116    /**
117     * Attempts to delete a VideoPress video from wp.com.
118     * Will block the deletion from continuing if certain errors return from the wp.com API.
119     *
120     * @param bool|null $delete Short-circuit value from earlier filters; null by default (unused).
121     * @param WP_Post   $post   The post object.
122     *
123     * @return null|false null if deletion should continue, false to block it.
124     */
125    public static function delete_video_wpcom( $delete, $post ) {
126        if ( ! is_videopress_attachment( $post->ID ) ) {
127            return null;
128        }
129        self::$delete_error = null;
130
131        $guid = get_post_meta( $post->ID, 'videopress_guid', true );
132        if ( empty( $guid ) ) {
133            self::delete_video_poster_attachment( $post->ID );
134            return null;
135        }
136
137        // Phone home and have wp.com delete the VideoPress entry and files.
138        $wpcom_response = Client::wpcom_json_api_request_as_blog(
139            sprintf( '/videos/%s/delete', $guid ),
140            '1.1',
141            array(
142                'method'  => 'POST',
143                'timeout' => self::DELETE_TIMEOUT,
144            ),
145            array( 'user_id' => get_current_user_id() )
146        );
147
148        // Return false, not the WP_Error: core treats any truthy value as a successful delete.
149        if ( is_wp_error( $wpcom_response ) ) {
150            self::$delete_error = __( 'WordPress.com did not confirm that the video was deleted, so it was kept. Try again.', 'jetpack-videopress-pkg' );
151            return false;
152        }
153
154        // Upon success or a 404 (video already deleted on wp.com), return null to allow the deletion to continue.
155        if ( 200 === $wpcom_response['response']['code'] || 404 === $wpcom_response['response']['code'] ) {
156            self::delete_video_poster_attachment( $post->ID );
157            return null;
158        }
159
160        // Otherwise we stop the deletion from proceeding.
161        self::$delete_error = sprintf(
162            /* translators: %d: HTTP status code. */
163            __( 'WordPress.com could not delete this video (error %d).', 'jetpack-videopress-pkg' ),
164            (int) $wpcom_response['response']['code']
165        );
166        return false;
167    }
168
169    /**
170     * Replaces the REST API's generic "cannot be deleted" error with the reason a VideoPress delete was blocked.
171     *
172     * @since $$next-version$$
173     *
174     * @param mixed $response Result of the endpoint callback.
175     * @return mixed
176     */
177    public static function explain_rest_delete_failure( $response ) {
178        if ( null === self::$delete_error || ! is_wp_error( $response ) || 'rest_cannot_delete' !== $response->get_error_code() ) {
179            return $response;
180        }
181        $message            = self::$delete_error;
182        self::$delete_error = null;
183        return new WP_Error( 'videopress_delete_failed', $message, array( 'status' => 502 ) );
184    }
185
186    /**
187     * Deletes a video poster attachment if it exists.
188     *
189     * @param int $attachment_id the WP attachment id.
190     */
191    private static function delete_video_poster_attachment( $attachment_id ) {
192        $thumbnail_id = get_post_meta( $attachment_id, '_thumbnail_id', true );
193        if ( ! empty( $thumbnail_id ) ) {
194            // Let's ensure this is a VP poster image before we delete it.
195            if ( '1' === get_post_meta( $thumbnail_id, 'videopress_poster_image', true ) ) {
196                // This call triggers the `delete_video_wpcom` filter again but it bails early at the is_videopress_attachment() check.
197                wp_delete_attachment( $thumbnail_id );
198            }
199        }
200    }
201
202    /**
203     * Filter the mime type icon.
204     *
205     * @param string $icon Icon path.
206     * @param string $mime Mime type.
207     * @param int    $post_id Post ID.
208     *
209     * @return string
210     */
211    public static function wp_mime_type_icon( $icon, $mime, $post_id ) {
212
213        if ( $mime !== 'video/videopress' ) {
214            return $icon;
215        }
216
217        $status = get_post_meta( $post_id, 'videopress_status', true );
218
219        if ( $status === 'complete' || $status === 'failed' ) {
220            return $icon;
221        }
222
223        return 'https://wordpress.com/wp-content/mu-plugins/videopress/images/media-video-processing-icon.png';
224    }
225
226    /**
227     * Filter the list of supported video formats.
228     *
229     * @param array $extensions Supported video formats.
230     *
231     * @return array
232     */
233    public static function add_videopress_extenstion( $extensions ) {
234        $extensions[] = 'videopress';
235        return $extensions;
236    }
237
238    /**
239     * Make sure that any Video that has a VideoPress GUID passes that data back.
240     *
241     * @param array $post Attachment data array.
242     * @return array
243     */
244    public static function prepare_attachment_for_js( $post ) {
245        if ( 'video' === $post['type'] ) {
246            $guid = get_post_meta( $post['id'], 'videopress_guid', true );
247            if ( $guid ) {
248                $post['videopress_guid'] = $guid;
249            }
250            $status = get_post_meta( $post['id'], 'videopress_status', true );
251            if ( $status ) {
252                $post['videopress_status'] = $status;
253            }
254        }
255        return $post;
256    }
257
258    /**
259     * Explain a terminal conversion failure in the Media Library details.
260     *
261     * @since 0.58.0
262     *
263     * @param array   $fields Attachment fields.
264     * @param WP_Post $post Attachment.
265     * @return array
266     */
267    public static function conversion_failure_field( $fields, $post ) {
268        if ( 'failed' === get_post_meta( $post->ID, 'videopress_status', true ) ) {
269            $fields['videopress_conversion_error'] = array(
270                'label' => __( 'VideoPress', 'jetpack-videopress-pkg' ),
271                'input' => 'html',
272                'html'  => esc_html__( 'Conversion failed. Delete this video and upload it again.', 'jetpack-videopress-pkg' ),
273            );
274        }
275        return $fields;
276    }
277
278    /**
279     * Media Grid:
280     * Filter out any videopress video posters that we've downloaded,
281     * so that they don't seem to display twice.
282     *
283     * @param array $args Query variables.
284     */
285    public static function ajax_query_attachments_args( $args ) {
286        $meta_query = array(
287            array(
288                'key'     => 'videopress_poster_image',
289                'compare' => 'NOT EXISTS',
290            ),
291        );
292
293        // If there was already a meta query, let's AND it via
294        // nesting it with our new one. No need to specify the
295        // relation, as it defaults to AND.
296        if ( ! empty( $args['meta_query'] ) ) {
297            $meta_query[] = $args['meta_query'];
298        }
299        $args['meta_query'] = $meta_query;
300
301        return $args;
302    }
303
304    /**
305     * Media List:
306     * Do the same as `videopress_ajax_query_attachments_args()` but for the list view.
307     *
308     * @param array $query WP_Query instance.
309     */
310    public static function media_list_table_query( $query ) {
311
312        if (
313            ! function_exists( 'get_current_screen' )
314            || get_current_screen() === null
315        ) {
316            return;
317        }
318
319        if ( is_admin() && $query->is_main_query() && ( 'upload' === get_current_screen()->id ) ) {
320            $meta_query = array(
321                array(
322                    'key'     => 'videopress_poster_image',
323                    'compare' => 'NOT EXISTS',
324                ),
325            );
326
327            $old_meta_query = $query->get( 'meta_query' );
328            if ( $old_meta_query ) {
329                $meta_query[] = $old_meta_query;
330            }
331
332            $query->set( 'meta_query', $meta_query );
333        }
334    }
335
336    /**
337     * Filter to disable the `delete_post` capability
338     * for VideoPress attachments if the current user is
339     * not connected.
340     *
341     * @param array $allcaps All the capabilities of the user.
342     * @param array $cap     [0] Required capability.
343     * @param array $args    [0] Requested capability.
344     *                       [1] User ID.
345     *                       [2] Associated object ID.
346     * @return array the filtered array of capabilities.
347     */
348    public static function disable_delete_if_disconnected( $allcaps, $cap, $args ) {
349
350        // Only apply this filter to `delete_post` checks
351        if ( ! isset( $args[0] ) || 'delete_post' !== $args[0] ) {
352            return $allcaps;
353        }
354
355        // Only apply this filter to VideoPress attachments
356        if ( ! isset( $args[2] ) || ! is_videopress_attachment( $args[2] ) ) {
357            return $allcaps;
358        }
359
360        // Set the capability to false if the user can't perform the actions
361        if ( ! Data::can_perform_action() ) {
362            $allcaps[ $cap[0] ] = false;
363        }
364
365        return $allcaps;
366    }
367
368    /**
369     * Enqueues the script that hooks into WP Heartbeat to refresh
370     * processing VideoPress video data in the media library grid.
371     *
372     * @since 0.35.4
373     *
374     * @return void
375     */
376    public static function enqueue_media_library_poll() {
377        wp_enqueue_script(
378            'videopress-media-library-poll',
379            plugins_url( 'js/media-library-poll.js', __FILE__ ),
380            array( 'jquery', 'heartbeat', 'media-grid' ),
381            Package_Version::PACKAGE_VERSION,
382            true
383        );
384
385        add_filter( 'heartbeat_settings', array( __CLASS__, 'heartbeat_settings' ) );
386    }
387
388    /**
389     * Replaces the Media Library list view's single-request bulk delete with per-item requests
390     * when VideoPress videos are selected, since each one waits on WordPress.com.
391     *
392     * @since $$next-version$$
393     *
394     * @return void
395     */
396    public static function enqueue_media_library_bulk_delete() {
397        global $wp_list_table, $wp_query;
398
399        if ( ! $wp_list_table instanceof \WP_Media_List_Table || ! $wp_query instanceof \WP_Query ) {
400            return;
401        }
402
403        $videopress_ids = array();
404        foreach ( $wp_query->posts as $post ) {
405            if ( $post instanceof WP_Post && 'video/videopress' === $post->post_mime_type ) {
406                $videopress_ids[] = $post->ID;
407            }
408        }
409        if ( empty( $videopress_ids ) ) {
410            return;
411        }
412
413        wp_enqueue_script(
414            'videopress-media-library-bulk-delete',
415            plugins_url( 'js/media-library-bulk-delete.js', __FILE__ ),
416            array( 'jquery', 'wp-api-fetch' ),
417            Package_Version::PACKAGE_VERSION,
418            true
419        );
420        wp_localize_script(
421            'videopress-media-library-bulk-delete',
422            'videopressMediaBulkDelete',
423            array(
424                'videoPressIds' => $videopress_ids,
425                'strings'       => array(
426                    /* translators: %1$s: number of items processed so far, %2$s: number of items selected. */
427                    'progress'     => __( 'Deleting media: %1$s of %2$s done. Keep this page open until it finishes.', 'jetpack-videopress-pkg' ),
428                    /* translators: %1$s: number of items deleted, %2$s: number of items selected. */
429                    'done'         => __( 'Deleted %1$s of %2$s selected items.', 'jetpack-videopress-pkg' ),
430                    /* translators: %1$s: number of items deleted, %2$s: number of items selected, %3$s: number of items that failed. */
431                    'partial'      => __( 'Deleted %1$s of %2$s selected items. %3$s could not be deleted and are still selected, so you can try again:', 'jetpack-videopress-pkg' ),
432                    /* translators: %1$s: media title, %2$s: error message. */
433                    'failure'      => __( '%1$s: %2$s', 'jetpack-videopress-pkg' ),
434                    'unknownError' => __( 'The item could not be deleted.', 'jetpack-videopress-pkg' ),
435                ),
436            )
437        );
438    }
439
440    /**
441     * Adds inline styles for the media library grid on the upload page.
442     *
443     * @since 0.35.4
444     *
445     * @return void
446     */
447    public static function enqueue_media_library_styles() {
448        // Constrain poster images so they fit within the media library grid cell.
449        wp_add_inline_style(
450            'media-views',
451            '.attachment-preview.type-video .thumbnail .centered img.thumbnail { max-width: 100%; max-height: 100%; }'
452        );
453    }
454
455    /**
456     * Lowers the Heartbeat minimum interval on the media library page
457     * so the polling script can request a faster tick rate.
458     *
459     * @since 0.35.4
460     *
461     * @param array $settings Heartbeat settings.
462     * @return array
463     */
464    public static function heartbeat_settings( $settings ) {
465        $settings['minimalInterval'] = 5;
466
467        return $settings;
468    }
469
470    /**
471     * Heartbeat API handler that checks the processing status of VideoPress videos.
472     *
473     * @since 0.35.4
474     *
475     * @param array $response The Heartbeat response.
476     * @param array $data     The data sent with the Heartbeat request.
477     * @return array
478     */
479    public static function heartbeat_received( $response, $data ) {
480        if ( empty( $data['videopress_processing_ids'] ) || ! is_array( $data['videopress_processing_ids'] ) ) {
481            return $response;
482        }
483
484        $statuses = array();
485        foreach ( $data['videopress_processing_ids'] as $id ) {
486            $id = (int) $id;
487
488            if ( ! current_user_can( 'edit_post', $id ) ) {
489                continue;
490            }
491
492            $status = get_post_meta( $id, 'videopress_status', true );
493            if ( $status ) {
494                $statuses[ $id ] = $status;
495            }
496        }
497
498        if ( ! empty( $statuses ) ) {
499            $response['videopress_processing_status'] = $statuses;
500        }
501
502        return $response;
503    }
504}