Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
54.86% covered (warning)
54.86%
175 / 319
47.37% covered (danger)
47.37%
9 / 19
CRAP
0.00% covered (danger)
0.00%
0 / 1
Data
54.86% covered (warning)
54.86%
175 / 319
47.37% covered (danger)
47.37%
9 / 19
668.70
0.00% covered (danger)
0.00%
0 / 1
 get_blog_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_videos_private_for_site
50.00% covered (danger)
50.00%
3 / 6
0.00% covered (danger)
0.00%
0 / 1
8.12
 get_videopress_auto_subtitles_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_player_preload_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_inline_player_enabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_download_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_share_menu_disabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_videopress_settings
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
4.18
 get_video_data
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
5
 get_latest_videopress_playlist_entries
96.15% covered (success)
96.15%
25 / 26
0.00% covered (danger)
0.00%
0 / 1
11
 query_latest_videopress_playlist_entries
92.00% covered (success)
92.00%
23 / 25
0.00% covered (danger)
0.00%
0 / 1
15.12
 playlist_entry
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
5
 get_user_data
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
20
 get_storage_used
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 get_connected_initial_state
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 has_connected_owner
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 can_perform_action
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
 get_initial_state
0.00% covered (danger)
0.00%
0 / 87
0.00% covered (danger)
0.00%
0 / 1
30
 prepare_videopress_video_data
100.00% covered (success)
100.00%
53 / 53
100.00% covered (success)
100.00%
1 / 1
6
1<?php
2/**
3 * The Data class.
4 * This class provides methods for data VideoPress access and manipulation.
5 *
6 * @package automattic/jetpack-videopress
7 */
8
9namespace Automattic\Jetpack\VideoPress;
10
11use Automattic\Jetpack\Connection\Manager as Connection_Manager;
12use Automattic\Jetpack\Status\Host;
13use WP_REST_Request;
14/**
15 * The Data class.
16 */
17class Data {
18
19    /**
20     * Gets the Jetpack blog ID
21     *
22     * @return int The blog ID
23     */
24    public static function get_blog_id() {
25        return VideoPressToken::blog_id();
26    }
27
28    /**
29     * Gets the VideoPress site privacy configuration.
30     *
31     * @return boolean If all the videos are private on the site
32     */
33    public static function get_videopress_videos_private_for_site() {
34        /**
35         * If it's a Simple site, returns the site privacy setting.
36         */
37        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
38            return video_is_private_wpcom_blog( get_current_blog_id() );
39        }
40        /**
41         * If it's a private Atomic site, the default setting is private as well.
42         */
43        if ( ( new Host() )->is_woa_site() ) {
44            if ( ( intval( get_option( 'blog_public', '' ) ) === -1 ) ) {
45                return true;
46            }
47        }
48
49        /* If it's a Jetpack site or a public Atomic site, check the settings */
50        return boolval( get_option( 'videopress_private_enabled_for_site', false ) );
51    }
52
53    /**
54     * Gets whether auto-generated subtitles are disabled for the site.
55     *
56     * Subtitles are generated by default, so this opt-out option defaults to false.
57     *
58     * @return boolean If auto-generated subtitles should be skipped for new videos.
59     */
60    public static function get_videopress_auto_subtitles_disabled() {
61        return boolval( get_option( 'videopress_auto_subtitles_disabled', false ) );
62    }
63
64    /**
65     * Gets whether player preloading is turned off for every embed on the site.
66     *
67     * Preloading is on by default, so this opt-out option defaults to false.
68     *
69     * @return boolean If embeds should wait for playback before fetching video data and player assets.
70     */
71    public static function get_videopress_player_preload_disabled() {
72        return boolval( get_option( 'videopress_player_preload_disabled', false ) );
73    }
74
75    /**
76     * Gets whether embeds render an inline player instead of one iframe per video.
77     *
78     * Iframes are the default, so this opt-in option defaults to false.
79     *
80     * @return boolean If embeds should mount players in the page from one shared player script.
81     */
82    public static function get_videopress_inline_player_enabled() {
83        return boolval( get_option( 'videopress_inline_player_enabled', false ) );
84    }
85
86    /**
87     * Gets whether downloads are turned off for every video on the site.
88     *
89     * Downloads follow each video's own setting by default, so this opt-out option defaults to false.
90     *
91     * @return boolean If no video may offer a download, whatever its own setting.
92     */
93    public static function get_videopress_download_disabled() {
94        return boolval( get_option( 'videopress_download_disabled', false ) );
95    }
96
97    /**
98     * Gets whether the share menu is turned off for every video on the site.
99     *
100     * Sharing follows each video's own setting by default, so this opt-out option defaults to false.
101     *
102     * @return boolean If no video may display the share menu, whatever its own setting.
103     */
104    public static function get_videopress_share_menu_disabled() {
105        return boolval( get_option( 'videopress_share_menu_disabled', false ) );
106    }
107
108    /**
109     * Gets the VideoPress Settings.
110     *
111     * @return array The settings as an associative array.
112     */
113    public static function get_videopress_settings() {
114        $site_type       = 'jetpack';
115        $site_is_private = false;
116
117        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
118            $site_type       = 'simple';
119            $site_is_private = video_is_private_wpcom_blog( get_current_blog_id() );
120        } elseif ( ( new Host() )->is_woa_site() ) {
121            $site_type       = 'atomic';
122            $site_is_private = intval( get_option( 'blog_public', '' ) ) === -1;
123        }
124
125        return array(
126            'videopress_videos_private_for_site' => self::get_videopress_videos_private_for_site(),
127            'videopress_auto_subtitles_disabled' => self::get_videopress_auto_subtitles_disabled(),
128            'videopress_player_preload_disabled' => self::get_videopress_player_preload_disabled(),
129            'videopress_inline_player_enabled'   => self::get_videopress_inline_player_enabled(),
130            'videopress_share_menu_disabled'     => self::get_videopress_share_menu_disabled(),
131            'videopress_download_disabled'       => self::get_videopress_download_disabled(),
132            'site_is_private'                    => $site_is_private,
133            'site_type'                          => $site_type,
134        );
135    }
136
137    /**
138     * Gets the video data
139     *
140     * @param boolean $is_videopress - True when getting VideoPress data.
141     * @return array
142     */
143    public static function get_video_data( $is_videopress = true ) {
144        $video_data = array(
145            'videos'     => array(),
146            'total'      => 0,
147            'totalPages' => 0,
148            'query'      => array(
149                'order'        => 'desc',
150                'orderBy'      => 'date',
151                'itemsPerPage' => 6,
152                'page'         => 1,
153            ),
154        );
155
156        $args = array(
157            'order'    => $video_data['query']['order'],
158            'orderby'  => $video_data['query']['orderBy'],
159            'per_page' => $video_data['query']['itemsPerPage'],
160            'page'     => $video_data['query']['page'],
161        );
162
163        if ( $is_videopress ) {
164            $args['mime_type'] = 'video/videopress';
165        } else {
166            $args['media_type']    = 'video';
167            $args['no_videopress'] = true;
168        }
169
170        // Do an internal request for the media list
171        $request = new WP_REST_Request( 'GET', '/wp/v2/media' );
172        $request->set_query_params( $args );
173        $response = rest_do_request( $request );
174
175        if ( $response->is_error() ) {
176            // @todo: error handling
177            return $video_data;
178        }
179
180        // load the real values
181        $video_data['videos'] = $response->get_data();
182        $headers              = $response->get_headers();
183
184        if ( isset( $headers['X-WP-Total'] ) ) {
185            $video_data['total'] = $headers['X-WP-Total'];
186        }
187
188        if ( isset( $headers['X-WP-TotalPages'] ) ) {
189            $video_data['totalPages'] = $headers['X-WP-TotalPages'];
190        }
191
192        return $video_data;
193    }
194
195    /**
196     * Gets the site's newest VideoPress videos as playlist entries, newest first.
197     *
198     * Goes through the media REST endpoint rather than a direct WP_Query so the
199     * package's rest_attachment_query filter resolves VideoPress membership on
200     * every host: by mime off WordPress.com Simple, from wpcom's videos table on it.
201     * The editor's block preview sends the same request.
202     *
203     * @param int $count How many videos to fetch.
204     *
205     * @return array Entries with guid, durationMs and height keys.
206     */
207    public static function get_latest_videopress_playlist_entries( $count ) {
208        $count = max( 1, (int) $count );
209        $args  = array(
210            'per_page'            => $count,
211            'orderby'             => 'date',
212            'order'               => 'desc',
213            'videopress_has_guid' => 1,
214        );
215
216        // Attachments keep their original mime there, so narrow to videos before the ID-set constraint.
217        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
218            $args['videopress_only_videos'] = 1;
219        }
220
221        $request = new WP_REST_Request( 'GET', '/wp/v2/media' );
222        $request->set_query_params( $args );
223        $response = rest_do_request( $request );
224
225        // WordPress.com Simple registers the wp/v2 routes only for REST requests, so on a
226        // page render the media endpoint does not exist: query the attachments directly.
227        if ( $response->is_error() ) {
228            return self::query_latest_videopress_playlist_entries( $count );
229        }
230
231        $entries = array();
232        foreach ( (array) $response->get_data() as $item ) {
233            $item = (array) $item;
234            $guid = $item['jetpack_videopress_guid'] ?? '';
235
236            // The REST field is empty on a site without a connection; the attachment meta still knows.
237            if ( ( ! is_string( $guid ) || '' === $guid ) && ! empty( $item['id'] ) ) {
238                $guid = get_post_meta( (int) $item['id'], 'videopress_guid', true );
239            }
240
241            $details    = isset( $item['media_details'] ) ? (array) $item['media_details'] : array();
242            $videopress = isset( $details['videopress'] ) ? (array) $details['videopress'] : array();
243            $entry      = self::playlist_entry( $guid, $videopress['duration'] ?? 0, $details['height'] ?? $videopress['height'] ?? 0 );
244            if ( $entry ) {
245                $entries[] = $entry;
246            }
247        }
248
249        return $entries;
250    }
251
252    /**
253     * The newest VideoPress videos straight from the posts table, for hosts where the
254     * media endpoint is unavailable. Mirrors what the endpoint does with the package's
255     * query filter: by mime off WordPress.com Simple, from wpcom's videos table on it.
256     *
257     * @param int $count How many videos to fetch.
258     *
259     * @return array Entries with guid, durationMs and height keys.
260     */
261    private static function query_latest_videopress_playlist_entries( $count ) {
262        $is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM;
263        $posts    = get_posts(
264            array(
265                'post_type'      => 'attachment',
266                'post_status'    => 'inherit',
267                'post_mime_type' => $is_wpcom ? 'video' : 'video/videopress',
268                'orderby'        => 'date',
269                'order'          => 'DESC',
270                'posts_per_page' => $count,
271            )
272        );
273
274        $entries = array();
275        foreach ( $posts as $post ) {
276            $guid = get_post_meta( $post->ID, 'videopress_guid', true );
277            if ( ( ! is_string( $guid ) || '' === $guid ) && $is_wpcom && function_exists( 'video_get_info_by_blogpostid' ) ) {
278                $info = video_get_info_by_blogpostid( get_current_blog_id(), $post->ID );
279                $guid = is_object( $info ) && ! empty( $info->guid ) ? (string) $info->guid : '';
280            }
281
282            $meta       = wp_get_attachment_metadata( $post->ID );
283            $meta       = is_array( $meta ) ? $meta : array();
284            $videopress = isset( $meta['videopress'] ) ? (array) $meta['videopress'] : array();
285            $duration   = $videopress['duration'] ?? ( isset( $meta['length'] ) && is_numeric( $meta['length'] ) ? (int) $meta['length'] * 1000 : 0 );
286            $entry      = self::playlist_entry( $guid, $duration, $meta['height'] ?? $videopress['height'] ?? 0 );
287            if ( $entry ) {
288                $entries[] = $entry;
289            }
290        }
291
292        return $entries;
293    }
294
295    /**
296     * One playlist entry, or null when the GUID is unusable.
297     *
298     * @param mixed $guid     VideoPress GUID.
299     * @param mixed $duration Duration in ms.
300     * @param mixed $height   Height in px.
301     *
302     * @return array|null
303     */
304    private static function playlist_entry( $guid, $duration, $height ) {
305        if ( ! is_string( $guid ) || ! preg_match( '/^[a-zA-Z0-9]{8}$/', $guid ) ) {
306            return null;
307        }
308        return array(
309            'guid'       => $guid,
310            'durationMs' => is_numeric( $duration ) ? max( 0, (int) $duration ) : 0,
311            'height'     => is_numeric( $height ) ? max( 0, (int) $height ) : 0,
312        );
313    }
314
315    /**
316     * Gets the user data
317     *
318     * @return array
319     */
320    public static function get_user_data() {
321        $user_data = array(
322            'items'      => array(),
323            'pagination' => array(
324                'total'      => 0,
325                'totalPages' => 1,
326            ),
327            'query'      => array(
328                'order'   => 'asc',
329                'orderBy' => 'name',
330            ),
331            '_meta'      => array(
332                'relyOnInitialState' => true,
333            ),
334        );
335
336        $args = array(
337            'order'   => $user_data['query']['order'],
338            'orderby' => $user_data['query']['orderBy'],
339        );
340
341        // Do an internal request for the user list
342        $request = new WP_REST_Request( 'GET', '/wp/v2/users' );
343        $request->set_query_params( $args );
344        $response = rest_do_request( $request );
345
346        if ( $response->is_error() ) {
347            // @todo: error handling
348            return $user_data;
349        }
350
351        // load the real values
352        $user_data['items'] = $response->get_data();
353        $headers            = $response->get_headers();
354
355        if ( isset( $headers['X-WP-Total'] ) ) {
356            $user_data['pagination']['total'] = $headers['X-WP-Total'];
357        }
358
359        if ( isset( $headers['X-WP-TotalPages'] ) ) {
360            $user_data['pagination']['totalPages'] = $headers['X-WP-TotalPages'];
361        }
362
363        return $user_data;
364    }
365
366    /**
367     * Gets the VideoPress used storage space in bytes
368     *
369     * @return int the used storage space
370     */
371    public static function get_storage_used() {
372        $site_data = Site::get_site_info();
373        if ( is_wp_error( $site_data ) ) {
374            return 0;
375        }
376
377        if ( isset( $site_data['options'] ) && isset( $site_data['options']['videopress_storage_used'] ) ) {
378            return intval( round( $site_data['options']['videopress_storage_used'] * 1024 * 1024 ) );
379        } else {
380            return 0;
381        }
382    }
383
384    /**
385     * Return all the initial state that depends on a valid site connection
386     *
387     * @return array
388     */
389    public static function get_connected_initial_state() {
390        return array(
391            'videos'    => array(
392                'storageUsed' => self::get_storage_used(),
393            ),
394            'purchases' => array(
395                'items'      => Site::get_purchases(),
396                'isFetching' => false,
397            ),
398        );
399    }
400
401    /**
402     * Checks if the site has as connected owner
403     */
404    public static function has_connected_owner() {
405        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
406            return true;
407        }
408
409        if ( ( new Connection_Manager() )->has_connected_owner() ) {
410            return true;
411        }
412
413        return false;
414    }
415
416    /**
417     * Checks if the user is able to perform actions that modify data
418     */
419    public static function can_perform_action() {
420        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
421            return true;
422        }
423
424        $connection = new Connection_Manager();
425
426        return (
427            $connection->is_connected() &&
428            self::has_connected_owner() &&
429            $connection->is_user_connected()
430        );
431    }
432
433    /**
434     * Return the initial state of the VideoPress app,
435     * used to render initially the app in the frontend.
436     *
437     * @return array
438     */
439    public static function get_initial_state() {
440        $videopress_data   = self::get_video_data();
441        $local_videos_data = self::get_video_data( false );
442
443        // Tweak local videos data.
444        $local_videos = array_map(
445            function ( $video ) {
446                $video              = (array) $video;
447                $id                 = $video['id'];
448                $media_details      = $video['media_details'];
449                $jetpack_videopress = $video['jetpack_videopress'];
450                $read_error         = null;
451
452                // In malformed files, the media_details or jetpack_videopress properties are not arrays.
453                if ( ! is_array( $media_details ) || ! is_array( $jetpack_videopress ) ) {
454                    $media_details      = (array) $media_details;
455                    $jetpack_videopress = (array) $jetpack_videopress;
456                    $read_error         = Upload_Exception::ERROR_MALFORMED_FILE;
457                }
458
459                // Check if video is already uploaded to VideoPress or has some error.
460                try {
461                    $uploader                  = new Uploader( $id );
462                    $is_uploaded_to_videopress = $uploader->is_uploaded();
463                } catch ( Upload_Exception $e ) {
464                    $is_uploaded_to_videopress = false;
465                    $read_error                = $e->getCode();
466                }
467
468                $upload_date = $video['date'];
469                $url         = $video['source_url'];
470
471                $title       = $jetpack_videopress['title'];
472                $description = $jetpack_videopress['description'];
473                $caption     = $jetpack_videopress['caption'];
474
475                $width    = $media_details['width'] ?? null;
476                $height   = $media_details['height'] ?? null;
477                $duration = $media_details['length'] ?? null;
478
479                return array(
480                    'id'                     => $id,
481                    'title'                  => $title,
482                    'description'            => $description,
483                    'caption'                => $caption,
484                    'width'                  => $width,
485                    'height'                 => $height,
486                    'url'                    => $url,
487                    'uploadDate'             => $upload_date,
488                    'duration'               => $duration,
489                    'isUploadedToVideoPress' => $is_uploaded_to_videopress,
490                    'readError'              => $read_error,
491                );
492            },
493            $local_videos_data['videos']
494        );
495
496        // Tweak VideoPress videos data.
497        $videos = array_map(
498            array( __CLASS__, 'prepare_videopress_video_data' ),
499            $videopress_data['videos']
500        );
501
502        $site_settings = self::get_videopress_settings();
503
504        $initial_state = array(
505            'users'        => self::get_user_data(),
506            'siteSettings' => array(
507                'videoPressVideosPrivateForSite' => $site_settings['videopress_videos_private_for_site'],
508                'siteIsPrivate'                  => $site_settings['site_is_private'],
509                'siteType'                       => $site_settings['site_type'],
510            ),
511            'videos'       => array(
512                'uploadedVideoCount'           => $videopress_data['total'],
513                'items'                        => $videos,
514                'isFetching'                   => false,
515                'isFetchingUploadedVideoCount' => false,
516                'pagination'                   => array(
517                    'totalPages' => $videopress_data['totalPages'],
518                    'total'      => $videopress_data['total'],
519                ),
520                'query'                        => $videopress_data['query'],
521                '_meta'                        => array(
522                    'processedAllVideosBeingRemoved' => true,
523                    'relyOnInitialState'             => true,
524                ),
525            ),
526            'localVideos'  => array(
527                'uploadedVideoCount'           => $local_videos_data['total'],
528                'items'                        => $local_videos,
529                'isFetching'                   => false,
530                'isFetchingUploadedVideoCount' => false,
531                'pagination'                   => array(
532                    'totalPages' => $local_videos_data['totalPages'],
533                    'total'      => $local_videos_data['total'],
534                ),
535                'query'                        => $local_videos_data['query'],
536                '_meta'                        => array(
537                    'relyOnInitialState' => true,
538                ),
539            ),
540        );
541
542        if ( self::has_connected_owner() ) {
543            return array_merge_recursive( $initial_state, self::get_connected_initial_state() );
544        }
545
546        return $initial_state;
547    }
548
549    /**
550     * Maps a single VideoPress video, as returned by the media REST endpoint, to
551     * the shape consumed by the VideoPress dashboard app.
552     *
553     * Videos that are still processing (or otherwise have partial metadata) come
554     * back without `videopress`, `width` or `height` in their media_details, so
555     * every nested access is coalesced to avoid undefined-key and offset-on-null
556     * warnings.
557     *
558     * @param array|object $video A single video entry from the media REST endpoint.
559     * @return array The video data formatted for the dashboard app.
560     */
561    private static function prepare_videopress_video_data( $video ) {
562        $video              = (array) $video;
563        $id                 = $video['id'];
564        $guid               = $video['jetpack_videopress_guid'];
565        $media_details      = (array) $video['media_details'];
566        $jetpack_videopress = (array) $video['jetpack_videopress'];
567
568        $videopress_media_details = $media_details['videopress'] ?? array();
569        $width                    = $media_details['width'] ?? null;
570        $height                   = $media_details['height'] ?? null;
571
572        $title                = $jetpack_videopress['title'];
573        $description          = $jetpack_videopress['description'];
574        $caption              = $jetpack_videopress['caption'];
575        $rating               = $jetpack_videopress['rating'];
576        $allow_download       = $jetpack_videopress['allow_download'];
577        $display_embed        = $jetpack_videopress['display_embed'];
578        $privacy_setting      = $jetpack_videopress['privacy_setting'];
579        $needs_playback_token = $jetpack_videopress['needs_playback_token'];
580        $is_private           = $jetpack_videopress['is_private'];
581
582        $original      = $videopress_media_details['original'] ?? null;
583        $poster        = ( ! $needs_playback_token ) ? ( $videopress_media_details['poster'] ?? null ) : null;
584        $upload_date   = $videopress_media_details['upload_date'] ?? null;
585        $duration      = $videopress_media_details['duration'] ?? null;
586        $file_url_base = $videopress_media_details['file_url_base'] ?? null;
587        $finished      = $videopress_media_details['finished'] ?? null;
588        $files         = $videopress_media_details['files'] ?? null;
589        $filename      = $original !== null ? basename( $original ) : null;
590
591        if ( isset( $files['dvd']['original_img'] ) && isset( $file_url_base['https'] ) && $privacy_setting !== 1 ) {
592            $thumbnail = $file_url_base['https'] . $files['dvd']['original_img'];
593        } else {
594            $thumbnail = null;
595        }
596
597        return array(
598            'id'                 => $id,
599            'guid'               => $guid,
600            'title'              => $title,
601            'description'        => $description,
602            'caption'            => $caption,
603            'url'                => $original,
604            'uploadDate'         => $upload_date,
605            'duration'           => $duration,
606            'isPrivate'          => $is_private,
607            'posterImage'        => $poster,
608            'allowDownload'      => $allow_download,
609            'displayEmbed'       => $display_embed,
610            'rating'             => $rating,
611            'privacySetting'     => $privacy_setting,
612            'needsPlaybackToken' => $needs_playback_token,
613            'width'              => $width,
614            'height'             => $height,
615            'poster'             => array(
616                'src' => $poster,
617            ),
618            'thumbnail'          => $thumbnail,
619            'finished'           => $finished,
620            'filename'           => $filename,
621        );
622    }
623}