Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
41.67% covered (danger)
41.67%
90 / 216
46.67% covered (danger)
46.67%
7 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V2_Attachment_VideoPress_Data
41.59% covered (danger)
41.59%
89 / 214
46.67% covered (danger)
46.67%
7 / 15
1524.88
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 register_fields
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 add_jetpack_videopress_custom_query_filters
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 filter_attachments_by_jetpack_videopress_fields
35.90% covered (danger)
35.90%
14 / 39
0.00% covered (danger)
0.00%
0 / 1
57.52
 filter_attachments_by_jetpack_videopress_fields_wpcom
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
 apply_wpcom_id_constraint
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
14
 wpcom_privacy_type_plan
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
10
 get_wpcom_videopress_post_ids
0.00% covered (danger)
0.00%
0 / 36
0.00% covered (danger)
0.00%
0 / 1
90
 wpcom_privacy_value_set
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
 get_schema
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 get
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 get_videopress_data
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
90
 is_video
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
 remove_field_for_non_videos
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 video_is_private
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * Extend the REST API functionality for VideoPress users.
4 *
5 * @package automattic/jetpack-videopress
6 * @since-jetpack 7.1.0
7 * @since 0.3.1
8 */
9
10namespace Automattic\Jetpack\VideoPress;
11
12use Automattic\Jetpack\Connection\Manager as Jetpack_Connection;
13use WP_Post;
14use WP_REST_Request;
15use WP_REST_Response;
16
17/**
18 * Add per-attachment VideoPress data.
19 *
20 * { # Attachment Object
21 *   ...
22 *   jetpack_videopress: (object) VideoPress data
23 *   ...
24 * }
25 *
26 * @since 7.1.0
27 *
28 * @phan-constructor-used-for-side-effects
29 */
30class WPCOM_REST_API_V2_Attachment_VideoPress_Data {
31    /**
32     * The REST Object Type to which the jetpack_videopress field will be added.
33     *
34     * @var string
35     */
36    protected $object_type = 'attachment';
37
38    /**
39     * The name of the REST API field to add.
40     *
41     * @var string $field_name
42     */
43    protected $field_name = 'jetpack_videopress';
44
45    /**
46     * Constructor.
47     */
48    public function __construct() {
49        add_action( 'rest_api_init', array( $this, 'register_fields' ) );
50
51        add_action( 'rest_api_init', array( $this, 'add_jetpack_videopress_custom_query_filters' ) );
52
53        // do this again later to collect any CPTs that get registered later.
54        add_action( 'restapi_theme_init', array( $this, 'register_fields' ), 20 );
55    }
56
57    /**
58     * Registers the jetpack_videopress field and adds a filter to remove it for attachments that are not videos.
59     */
60    public function register_fields() {
61        global $wp_rest_additional_fields;
62
63        if ( ! empty( $wp_rest_additional_fields[ $this->object_type ][ $this->field_name ] ) ) {
64            return;
65        }
66
67        register_rest_field(
68            $this->object_type,
69            $this->field_name,
70            array(
71                'get_callback'    => array( $this, 'get' ),
72                'update_callback' => null,
73                'schema'          => $this->get_schema(),
74            )
75        );
76
77        add_filter( 'rest_prepare_attachment', array( $this, 'remove_field_for_non_videos' ), 10, 2 );
78    }
79
80    /**
81     * Adds the custom query filters
82     */
83    public function add_jetpack_videopress_custom_query_filters() {
84        add_filter( 'rest_attachment_query', array( $this, 'filter_attachments_by_jetpack_videopress_fields' ), 999, 2 );
85    }
86
87    /**
88     * Filter request args to handle the custom VideoPress query filters
89     *
90     * Possible filters:
91     *
92     * `no_videopress`: the returned attachments should not be VideoPress videos
93     *                  (off-Simple: no videopress_guid meta; on Simple: not a
94     *                  member of wpcom's videos table)
95     * `videopress_has_guid`: restrict results to VideoPress videos (off-Simple:
96     *                        the video/videopress mime; on Simple: members of
97     *                        wpcom's videos table)
98     * `videopress_only_videos`: (WPCOM only) restrict results to video attachments
99     * `videopress_privacy_setting`: restrict by privacy (0/1/2). Off-Simple this
100     *                               is a comma list; on Simple it's a single
101     *                               DataViews `is` code, resolved via the videos table
102     *
103     * @param array           $args The original list of args before the filtering.
104     * @param WP_REST_Request $request The original request data.
105     */
106    public function filter_attachments_by_jetpack_videopress_fields( $args, $request ) {
107
108        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
109            return $this->filter_attachments_by_jetpack_videopress_fields_wpcom( $args, $request );
110        }
111
112        if ( ! isset( $args['meta_query'] ) || ! is_array( $args['meta_query'] ) ) {
113            $args['meta_query'] = array();
114        }
115
116        /*
117         * Unlike the `mime_type` param, this doesn't depend on video/videopress
118         * being an allowed upload mime, which the media endpoint silently
119         * requires before it narrows by mime at all.
120         */
121        if ( isset( $request['videopress_has_guid'] ) ) {
122            $args['post_mime_type'] = 'video/videopress';
123        }
124
125        /* To ignore all VideoPress videos, select only attachments without videopress_guid meta field */
126        if ( isset( $request['no_videopress'] ) ) {
127            $args['meta_query'][] = array(
128                'key'     => 'videopress_guid',
129                'compare' => 'NOT EXISTS',
130            );
131        }
132
133        /*
134         * Hide local attachments that have already been uploaded to VideoPress.
135         * Such "zombie" locals carry a `_videopress_uploaded_id` meta pointing
136         * at their VideoPress sibling attachment; the sibling is the row the
137         * dashboard should surface.
138         */
139        if ( isset( $request['videopress_hide_already_uploaded'] ) ) {
140            $args['meta_query'][] = array(
141                'key'     => Uploader::UPLOADED_KEY,
142                'compare' => 'NOT EXISTS',
143            );
144        }
145
146        /* Filter using privacy setting meta key */
147        if ( isset( $request['videopress_privacy_setting'] ) ) {
148            $videopress_privacy_setting = sanitize_text_field( $request['videopress_privacy_setting'] );
149
150            /* Allows the filtering to happens using a list of privacy settings separated by comma */
151            $videopress_privacy_setting_list = explode( ',', $videopress_privacy_setting );
152
153            $site_default_is_private = Data::get_videopress_videos_private_for_site();
154
155            if ( $site_default_is_private ) {
156                /**
157                 * If the search is looking for private videos and the site default is private,
158                 * the site default setting should be included on the search.
159                 */
160                if ( in_array( strval( \VIDEOPRESS_PRIVACY::IS_PRIVATE ), $videopress_privacy_setting_list, true ) ) {
161                    $videopress_privacy_setting_list[] = \VIDEOPRESS_PRIVACY::SITE_DEFAULT;
162                }
163            } else { // phpcs:ignore Universal.ControlStructures.DisallowLonelyIf.Found
164                /**
165                 * If the search is looking for public videos and the site default is public,
166                 * the site default setting should be included on the search.
167                 */
168                if ( in_array( strval( \VIDEOPRESS_PRIVACY::IS_PUBLIC ), $videopress_privacy_setting_list, true ) ) {
169                    $videopress_privacy_setting_list[] = \VIDEOPRESS_PRIVACY::SITE_DEFAULT;
170                }
171            }
172
173            $args['meta_query'][] = array(
174                'key'     => 'videopress_privacy_setting',
175                'value'   => $videopress_privacy_setting_list,
176                'compare' => 'IN',
177            );
178        }
179
180        /* Filter using rating meta key */
181        if ( isset( $request['videopress_rating'] ) ) {
182            $videopress_rating = sanitize_text_field( $request['videopress_rating'] );
183
184            /* Allows the filtering to happens using a list of ratings separated by comma */
185            $videopress_rating_list = explode( ',', $videopress_rating );
186
187            $args['meta_query'][] = array(
188                'key'     => 'videopress_rating',
189                'value'   => $videopress_rating_list,
190                'compare' => 'IN',
191            );
192        }
193
194        return $args;
195    }
196
197    /**
198     * WordPress.com Simple variant of the VideoPress query filters.
199     *
200     * On Simple a VideoPress attachment keeps its ORIGINAL mime (video/mp4, â€¦),
201     * never video/videopress, and its privacy/type data live in wpcom's global
202     * `videos`/`video_meta` tables rather than postmeta. So every filter here is
203     * expressed as a WP_Query ID-set constraint (post__in / post__not_in) resolved
204     * from those tables, which keeps found_posts â€” and therefore the X-WP-Total /
205     * X-WP-TotalPages headers â€” exact (no client-side truncation).
206     *
207     * Only reached when IS_WPCOM is defined and true, where the `videos` tables
208     * and video_is_private_wpcom_blog() exist.
209     *
210     * @param array           $args    The original WP_Query args.
211     * @param WP_REST_Request $request The REST request.
212     * @return array The filtered WP_Query args.
213     */
214    private function filter_attachments_by_jetpack_videopress_fields_wpcom( $args, $request ) {
215        /*
216         * Browse default: the `media_type` param is rejected on WPCOM and
217         * `mime_type=video/*` doesn't narrow the query, so the dashboard sends
218         * `videopress_only_videos`. The bare major type makes WP_Query match
219         * `post_mime_type LIKE 'video/%'`. Always sent so the grid shows every
220         * video; the ID-set constraints below narrow it further when a type or
221         * privacy filter is active.
222         */
223        if ( isset( $request['videopress_only_videos'] ) ) {
224            $args['post_mime_type'] = 'video';
225        }
226
227        /*
228         * Normalize the privacy filter to a single code. The dashboard's DataViews
229         * control uses the `is` operator, so it sends one value: 0 = public,
230         * 1 = private, 2 = site-default. Anything else (empty, malformed, a stray
231         * comma list) means "no privacy filter".
232         */
233        $privacy = null;
234        if ( isset( $request['videopress_privacy_setting'] ) ) {
235            $raw = trim( (string) $request['videopress_privacy_setting'] );
236            if ( '0' === $raw || '1' === $raw || '2' === $raw ) {
237                $privacy = (int) $raw;
238            }
239        }
240
241        /*
242         * Resolve the (type, privacy) pair into a single WP_Query ID-set
243         * constraint. This reproduces the old client-side matchesClientSideFilters
244         * exactly â€” including its treatment of a "local" (non-VideoPress) video as
245         * public + site-default: locals carry no videos-table privacy row, so they
246         * surface under the Public and Site-default filters and never under
247         * Private. See wpcom_privacy_type_plan().
248         */
249        list( $mode, $set ) = $this->wpcom_privacy_type_plan(
250            isset( $request['videopress_has_guid'] ),
251            isset( $request['no_videopress'] ),
252            $privacy
253        );
254
255        $ids = in_array( $mode, array( 'in', 'not_in' ), true )
256            ? $this->get_wpcom_videopress_post_ids( $set )
257            : array();
258
259        return $this->apply_wpcom_id_constraint( $args, $mode, $ids );
260    }
261
262    /**
263     * Apply a resolved (mode, ids) constraint to WP_Query args, composing with
264     * any include/exclude constraints core already mapped onto post__in /
265     * post__not_in (the REST `include`/`exclude` params) rather than clobbering
266     * them. WP_Query ignores post__not_in whenever post__in is present, so
267     * whenever this method *introduces* a post__in where none existed, a
268     * pre-existing exclusion (which WOULD have been honored) is folded into it
269     * by subtraction. A request carrying both include and exclude keeps core's
270     * own precedence (include wins, exclude is dropped), matching what the
271     * off-Simple meta_query path yields.
272     *
273     * Pure (args in, args out) so the composition rules are unit-testable
274     * off-platform; only the resolution of $ids touches wpcom.
275     *
276     * @param array  $args The WP_Query args.
277     * @param string $mode How to apply the set: 'in' | 'not_in' | 'empty' | 'none'.
278     * @param int[]  $ids  The resolved ID set for 'in'/'not_in'.
279     * @return array The args with the constraint applied.
280     */
281    private function apply_wpcom_id_constraint( $args, $mode, $ids ) {
282        // WP_Query normalizes these lists with absint; mirror it so the
283        // composition operates on the values that would actually be queried.
284        $existing_in     = isset( $args['post__in'] ) ? array_map( 'absint', (array) $args['post__in'] ) : array();
285        $existing_not_in = isset( $args['post__not_in'] ) ? array_map( 'absint', (array) $args['post__not_in'] ) : array();
286
287        switch ( $mode ) {
288            case 'in':
289                // Intersect with a pre-existing include list rather than clobber
290                // it. WP_Query silently skips an empty post__in, so an empty
291                // result must fall back to a sentinel that matches no attachment
292                // (post ID 0 never exists) â€” otherwise it would leak the library.
293                if ( array() !== $existing_in ) {
294                    // Include + exclude together: core drops the exclude, keep
295                    // that precedence and intersect the include list only.
296                    $ids = array_values( array_intersect( $existing_in, $ids ) );
297                } elseif ( array() !== $existing_not_in ) {
298                    // A lone exclude WOULD have been honored by WP_Query, but the
299                    // post__in set here would make it ignored â€” fold it in by
300                    // subtraction and drop the now-dead arg.
301                    $ids = array_values( array_diff( $ids, $existing_not_in ) );
302                    unset( $args['post__not_in'] );
303                }
304                $args['post__in'] = array() === $ids ? array( 0 ) : $ids;
305                break;
306
307            case 'not_in':
308                // An empty exclude-set excludes nothing; leave the args untouched.
309                if ( array() === $ids ) {
310                    break;
311                }
312                if ( array() !== $existing_in ) {
313                    // post__not_in would be ignored next to post__in â€” express the
314                    // exclusion by subtracting from the include list instead.
315                    $kept             = array_values( array_diff( $existing_in, $ids ) );
316                    $args['post__in'] = array() === $kept ? array( 0 ) : $kept;
317                    break;
318                }
319                $args['post__not_in'] = array_values( array_unique( array_merge( $existing_not_in, $ids ) ) );
320                break;
321
322            case 'empty':
323                // The requested combination can't match anything (e.g. local +
324                // private). A pre-existing include intersected with the empty set
325                // is still empty, so the match-nothing sentinel stands either way.
326                $args['post__in'] = array( 0 );
327                break;
328
329            case 'none':
330            default:
331                // No type or privacy narrowing â€” the browse default stands.
332                break;
333        }
334
335        return $args;
336    }
337
338    /**
339     * Map a (type, privacy) filter pair to a single WP_Query ID-set constraint,
340     * reproducing the old client-side matchesClientSideFilters exactly.
341     *
342     * The library holds two kinds of video attachment: L = local (not a member of
343     * wpcom's `videos` table) and V = VideoPress (a member). The old client filter
344     * treated every local video as public + site-default (is_private defaulted to
345     * false, privacy to 'site-default'), so locals appeared under the Public and
346     * Site-default privacy views and never under Private. This mapping preserves
347     * that parity: privacy is resolved across the whole video library, not just V.
348     *
349     * Over the site's video/* attachments, the V sub-sets are:
350     *   Vall  â€” all (non-soft-deleted) videos-table members.
351     *   Vpriv â€” effectively private: setting 1, or (setting 2 / absent) on a private site.
352     *   Vpub  â€” effectively public: setting 0, or (setting 2 / absent) on a public site.
353     *   Vsd   â€” stored site-default: setting 2 or absent.
354     *   Vexpl â€” an explicit setting: setting IN (0,1).
355     *
356     * Returns [ $mode, $set ], where $mode is how to apply the set and $set names it:
357     *   'none'   / null  â€” no constraint (show everything).
358     *   'in'     / <set> â€” post__in     = <set>.
359     *   'not_in' / <set> â€” post__not_in = <set>.
360     *   'empty'  / null  â€” match nothing.
361     *
362     * Pure and independent of the resolved site privacy â€” only the *contents* of
363     * each named set depend on it (see get_wpcom_videopress_post_ids()) â€” so this
364     * is exhaustively unit-testable off-platform.
365     *
366     * @param bool     $has_guid Type filter = VideoPress (videos-table members only).
367     * @param bool     $no_vp    Type filter = local (exclude videos-table members).
368     * @param int|null $privacy  Single privacy code (0/1/2), or null for no privacy filter.
369     * @return array{0:string,1:string|null} [ $mode, $set ].
370     */
371    private function wpcom_privacy_type_plan( $has_guid, $no_vp, $privacy ) {
372        // Strict comparisons throughout: a switch would match `case 0` for a null
373        // $privacy (PHP's loose null == 0), collapsing "no privacy filter" into
374        // the Public view.
375        if ( $has_guid ) {
376            // Type = VideoPress: always restrict to videos-table members, then
377            // narrow to the effective/stored privacy set when asked.
378            if ( 1 === $privacy ) {
379                return array( 'in', 'priv' );
380            }
381            if ( 0 === $privacy ) {
382                return array( 'in', 'pub' );
383            }
384            if ( 2 === $privacy ) {
385                return array( 'in', 'sd' );
386            }
387            return array( 'in', 'all' );
388        }
389
390        if ( $no_vp ) {
391            // Type = local: exclude every videos-table member. Locals are all
392            // public + site-default and never private, so only the Private view is
393            // empty; the rest just return L.
394            if ( 1 === $privacy ) {
395                return array( 'empty', null );
396            }
397            return array( 'not_in', 'all' );
398        }
399
400        // No type filter: privacy applies across the whole video library.
401        if ( 1 === $privacy ) {
402            // Vpriv only â€” locals are never private.
403            return array( 'in', 'priv' );
404        }
405        if ( 0 === $privacy ) {
406            // L âˆª Vpub â€” everything except the effectively-private videos.
407            return array( 'not_in', 'priv' );
408        }
409        if ( 2 === $privacy ) {
410            // L âˆª Vsd â€” everything except videos with an explicit setting.
411            return array( 'not_in', 'expl' );
412        }
413        return array( 'none', null );
414    }
415
416    /**
417     * List this blog's VideoPress attachment post IDs from wpcom's global
418     * `videos` table, optionally narrowed to a named privacy set.
419     *
420     * Membership in the `videos` table â€” not postmeta or the mime type â€” is what
421     * distinguishes a VideoPress video from a local one on Simple. Soft-deleted
422     * rows (a `video_meta` row with meta_key 'deleted_at') are always excluded,
423     * matching every canonical wpcom query over these tables
424     * (e.g. helpers.php:videopress_get_jetpack_storage_used()).
425     *
426     * The named sets mirror wpcom_privacy_type_plan():
427     *   'all'  â€” every member, no privacy predicate (Vall).
428     *   'priv' â€” effectively private (Vpriv).
429     *   'pub'  â€” effectively public (Vpub).
430     *   'sd'   â€” stored site-default (Vsd).
431     *   'expl' â€” an explicit privacy_setting IN (0,1) (Vexpl); absent meta does
432     *            NOT qualify, since a missing row is stored site-default.
433     *
434     * The literal meta_key strings map to wpcom's VIDEOPRESS_META_KEYS constants:
435     * 'deleted_at' = DELETED_AT, 'privacy_setting' = PRIVACY_SETTING. The privacy
436     * integers map to VIDEOPRESS_PRIVACY: 0 = IS_PUBLIC, 1 = IS_PRIVATE,
437     * 2 = SITE_DEFAULT. They're inlined as literals rather than referencing those
438     * classes, which aren't present off-platform; this method is only ever called
439     * from the IS_WPCOM-guarded branch above.
440     *
441     * @param string $set Named privacy set: 'all'|'priv'|'pub'|'sd'|'expl'.
442     * @return int[] Attachment post IDs.
443     */
444    private function get_wpcom_videopress_post_ids( $set = 'all' ) {
445        global $wpdb;
446
447        $privacy_join  = '';
448        $privacy_where = '';
449        $prepare_args  = array( get_current_blog_id() );
450
451        if ( 'all' !== $set ) {
452            if ( 'expl' === $set ) {
453                // Videos with an explicit setting only. A missing privacy_setting
454                // row is stored site-default, so absent meta does NOT qualify.
455                $values   = array( 0, 1 );
456                $inc_null = false;
457            } else {
458                $site_is_private = Data::get_videopress_videos_private_for_site();
459                switch ( $set ) {
460                    case 'priv':
461                        $code = 1;
462                        break;
463                    case 'pub':
464                        $code = 0;
465                        break;
466                    case 'sd':
467                    default:
468                        $code = 2;
469                        break;
470                }
471                list( $values, $inc_null ) = $this->wpcom_privacy_value_set( $code, $site_is_private );
472            }
473
474            $privacy_join = 'LEFT OUTER JOIN video_meta AS privacy ON privacy.guid = videos.guid AND privacy.meta_key = \'privacy_setting\'';
475
476            $clauses = array();
477            if ( array() !== $values ) {
478                $placeholders = implode( ', ', array_fill( 0, count( $values ), '%d' ) );
479                $clauses[]    = "privacy.meta_value IN ( {$placeholders} )";
480                $prepare_args = array_merge( $prepare_args, $values );
481            }
482            if ( $inc_null ) {
483                // No stored privacy_setting row â†’ the video defaults to SITE_DEFAULT.
484                $clauses[] = 'ISNULL( privacy.meta_value )';
485            }
486            $privacy_where = 'AND ( ' . implode( ' OR ', $clauses ) . ' )';
487        }
488
489        /*
490         * $privacy_join / $privacy_where are assembled above from literal SQL
491         * fragments and %d placeholders only â€” never from request input â€” and every
492         * value is bound through $wpdb->prepare() via $prepare_args. The
493         * InterpolatedNotPrepared sniff can't see that the interpolated pieces are
494         * constant, so disable it (with the direct-query / no-caching sniffs â€” this
495         * is a short-lived, per-request video-id lookup) across the multi-line query.
496         */
497        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
498        $ids = $wpdb->get_col(
499            $wpdb->prepare(
500                "SELECT videos.post_id
501                FROM videos
502                LEFT OUTER JOIN video_meta AS delete_key ON delete_key.guid = videos.guid AND delete_key.meta_key = 'deleted_at'
503                {$privacy_join}
504                WHERE videos.blog_id = %d
505                    AND ISNULL( delete_key.meta_value )
506                    {$privacy_where}",
507                $prepare_args
508            )
509        );
510        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber
511
512        return array_map( 'intval', (array) $ids );
513    }
514
515    /**
516     * Translate a requested privacy code into the concrete set of stored
517     * `privacy_setting` values â€” plus whether an absent meta row qualifies â€”
518     * that reproduce, for VideoPress videos, the same effective visibility the
519     * client's old matchesClientSideFilters computed for them.
520     *
521     * Effective visibility is private when the stored setting is 1 (IS_PRIVATE),
522     * or when the setting is 2 (SITE_DEFAULT) or the meta row is absent AND the
523     * site default is private. A missing privacy_setting row defaults to
524     * SITE_DEFAULT. The 'site-default' request (2) matches the *stored* setting
525     * (2 or absent) regardless of the resolved site privacy, mirroring the
526     * client's `site-default` branch on item.privacy.
527     *
528     * This resolves the Vpriv (code 1), Vpub (code 0) and Vsd (code 2) sets used
529     * by get_wpcom_videopress_post_ids(). Local (non-videos-table) videos carry no
530     * row here; the caller folds them back into the Public and Site-default views
531     * via post__not_in, restoring the old client filter's parity.
532     *
533     * Pure (no wpcom globals) so it's unit-testable off-platform.
534     *
535     * @param int  $code            Requested privacy code: 0 public, 1 private, 2 site-default.
536     * @param bool $site_is_private Whether the site default resolves to private.
537     * @return array{0:int[],1:bool} [ acceptable stored privacy_setting values, whether absent meta qualifies ].
538     */
539    private function wpcom_privacy_value_set( $code, $site_is_private ) {
540        switch ( (int) $code ) {
541            case 1: // Private -- wpcom constant IS_PRIVATE. Site-default and
542                // absent-meta videos resolve to private on a private site.
543                return $site_is_private ? array( array( 1, 2 ), true ) : array( array( 1 ), false );
544            case 0: // Public -- wpcom constant IS_PUBLIC. Site-default and
545                // absent-meta videos resolve to public on a public site.
546                return $site_is_private ? array( array( 0 ), false ) : array( array( 0, 2 ), true );
547            case 2: // Site default (SITE_DEFAULT) â€” match the stored setting,
548            default: // not the resolved visibility.
549                return array( array( 2 ), true );
550        }
551    }
552
553    /**
554     * Defines data structure and what elements are visible in which contexts
555     */
556    public function get_schema() {
557        return array(
558            '$schema'     => 'http://json-schema.org/draft-04/schema#',
559            'title'       => $this->field_name,
560            'type'        => 'object',
561            'context'     => array( 'view', 'edit' ),
562            'readonly'    => true,
563            'description' => __( 'VideoPress Data', 'jetpack-videopress-pkg' ),
564        );
565    }
566
567    /**
568     * Getter: Retrieve current VideoPress data for a given attachment.
569     *
570     * @param array           $attachment Response from the attachment endpoint.
571     * @param WP_REST_Request $request Request to the attachment endpoint.
572     *
573     * @return array
574     */
575    public function get( $attachment, $request ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
576        if ( ! isset( $attachment['id'] ) ) {
577            return array();
578        }
579
580        $blog_id = Jetpack_Connection::get_site_id();
581        if ( ! is_int( $blog_id ) ) {
582            return array();
583        }
584
585        $videopress = $this->get_videopress_data( (int) $attachment['id'], $blog_id );
586
587        if ( ! $videopress ) {
588            return array();
589        }
590
591        return $videopress;
592    }
593
594    /**
595     * Gets the VideoPress GUID for a given attachment.
596     *
597     * This is pulled out into a separate method to support unit test mocking.
598     *
599     * @param int $attachment_id Attachment ID.
600     * @param int $blog_id Blog ID.
601     *
602     * @return array
603     */
604    public function get_videopress_data( $attachment_id, $blog_id ) {
605        $info = video_get_info_by_blogpostid( $blog_id, $attachment_id );
606        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
607            $title       = video_get_title( $blog_id, $attachment_id );
608            $description = video_get_description( $blog_id, $attachment_id );
609
610            $video_attachment = get_blog_post( $blog_id, $attachment_id );
611            if ( null === $video_attachment ) {
612                $caption = '';
613            } else {
614                $caption = $video_attachment->post_excerpt;
615            }
616        } else {
617            $title       = $info->title;
618            $description = $info->description;
619            $caption     = $info->caption;
620        }
621
622        $video_privacy_setting    = ! isset( $info->privacy_setting ) ? \VIDEOPRESS_PRIVACY::SITE_DEFAULT : intval( $info->privacy_setting );
623        $private_enabled_for_site = Data::get_videopress_videos_private_for_site();
624        $is_private               = $this->video_is_private( $video_privacy_setting, $private_enabled_for_site );
625
626        // The video needs a playback token if it's private for any reason (video privacy setting or site default privacy setting)
627        $video_needs_playback_token = $is_private;
628
629        return array(
630            'title'                    => $title,
631            'description'              => $description,
632            'caption'                  => $caption,
633            'guid'                     => $info->guid ?? null,
634            'rating'                   => $info->rating ?? null,
635            'allow_download'           =>
636                isset( $info->allow_download ) && $info->allow_download ? 1 : 0,
637            'display_embed'            =>
638                isset( $info->display_embed ) && $info->display_embed ? 1 : 0,
639            'privacy_setting'          => $video_privacy_setting,
640            'needs_playback_token'     => $video_needs_playback_token,
641            'is_private'               => $is_private,
642            'private_enabled_for_site' => $private_enabled_for_site,
643        );
644    }
645
646    /**
647     * Checks if the given attachment is a video.
648     *
649     * @param object $attachment The attachment object.
650     *
651     * @return false|int
652     */
653    public function is_video( $attachment ) {
654        return isset( $attachment->post_mime_type ) && wp_startswith( $attachment->post_mime_type, 'video/' );
655    }
656
657    /**
658     * Removes the jetpack_videopress field from the response if the
659     * given attachment is not a video.
660     *
661     * @param WP_REST_Response $response Response from the attachment endpoint.
662     * @param WP_Post          $attachment The original attachment object.
663     *
664     * @return mixed
665     */
666    public function remove_field_for_non_videos( $response, $attachment ) {
667        if ( ! $this->is_video( $attachment ) ) {
668            unset( $response->data[ $this->field_name ] );
669        }
670
671        return $response;
672    }
673
674    /**
675     * Determines if a video is private based on the video privacy
676     * setting and the site default privacy setting.
677     *
678     * @param int  $video_privacy_setting The privacy setting for the video.
679     * @param bool $private_enabled_for_site Flag stating if the default video privacy is private.
680     *
681     * @return bool
682     */
683    private function video_is_private( $video_privacy_setting, $private_enabled_for_site ) {
684        if ( $video_privacy_setting === \VIDEOPRESS_PRIVACY::IS_PUBLIC ) {
685            return false;
686        }
687        if ( $video_privacy_setting === \VIDEOPRESS_PRIVACY::IS_PRIVATE ) {
688            return true;
689        }
690
691        return $private_enabled_for_site;
692    }
693}
694
695if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
696    wpcom_rest_api_v2_load_plugin( 'Automattic\Jetpack\VideoPress\WPCOM_REST_API_V2_Attachment_VideoPress_Data' );
697}