Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
89.81% covered (warning)
89.81%
564 / 628
56.41% covered (warning)
56.41%
22 / 39
CRAP
0.00% covered (danger)
0.00%
0 / 1
Playlist_Manager
89.81% covered (warning)
89.81%
564 / 628
56.41% covered (warning)
56.41%
22 / 39
204.68
0.00% covered (danger)
0.00%
0 / 1
 register_rest_routes
100.00% covered (success)
100.00%
96 / 96
100.00% covered (success)
100.00%
1 / 1
1
 playlist_args
100.00% covered (success)
100.00%
40 / 40
100.00% covered (success)
100.00%
1 / 1
2
 edit_permissions_callback
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 update_permissions_callback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 rest_list_playlists
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
1
 rest_get_playlist
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 rest_create_playlist
92.86% covered (success)
92.86%
13 / 14
0.00% covered (danger)
0.00%
0 / 1
2.00
 rest_update_playlist
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 rest_delete_playlist
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 changes_from_request
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 query
89.36% covered (warning)
89.36%
42 / 47
0.00% covered (danger)
0.00%
0 / 1
11.15
 create
82.50% covered (warning)
82.50%
33 / 40
0.00% covered (danger)
0.00%
0 / 1
12.77
 update
91.30% covered (success)
91.30%
21 / 23
0.00% covered (danger)
0.00%
0 / 1
15.15
 delete
70.73% covered (warning)
70.73%
29 / 41
0.00% covered (danger)
0.00%
0 / 1
9.60
 locate
57.89% covered (warning)
57.89%
11 / 19
0.00% covered (danger)
0.00%
0 / 1
8.69
 change_block_at
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 remove_block_at
53.33% covered (warning)
53.33%
8 / 15
0.00% covered (danger)
0.00%
0 / 1
9.66
 is_whitespace_block
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 without_inner_slot
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 apply_changes
100.00% covered (success)
100.00%
25 / 25
100.00% covered (success)
100.00%
1 / 1
13
 sanitize_settings
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
8.01
 settings_from_attrs
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 sync_heading
100.00% covered (success)
100.00%
26 / 26
100.00% covered (success)
100.00%
1 / 1
8
 heading_text
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 with_heading_text
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
2
 find_block_path
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 block_at
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 block_key
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
4
 playlist_block_paths
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
7
 records
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
6.04
 unpublished_posts
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
1
 post_types
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 modified_time
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 find_record
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 record_for_block
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
5.39
 block_attrs
77.78% covered (warning)
77.78%
7 / 9
0.00% covered (danger)
0.00%
0 / 1
4.18
 prepare_item
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
14
 cannot_publish
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 not_found
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Playlist management for the VideoPress dashboard.
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use WP_Error;
11use WP_Post;
12use WP_Query;
13use WP_REST_Request;
14use WP_REST_Response;
15use WP_REST_Server;
16
17/**
18 * Lists, creates, edits and deletes the site's playlists.
19 *
20 * A playlist is a Video Playlist block in a post, so every change rewrites
21 * that block in its post: Playlist_Index picks published changes up from the
22 * post save. Playlists in unpublished posts ( drafts, pending, scheduled,
23 * private ) aren't indexed; they are read straight from their posts so the
24 * dashboard can list the ones it creates before they go live.
25 */
26class Playlist_Manager {
27
28    /**
29     * REST namespace for the playlist routes.
30     *
31     * The wpcom namespaces are the ones WordPress.com's public API serves for
32     * Simple sites ( jetpack/v4 is only proxied to Jetpack-connected sites ), and
33     * they resolve locally on Jetpack and Atomic sites.
34     *
35     * @var string
36     */
37    const REST_NAMESPACE = 'wpcom/v3';
38
39    /**
40     * Route base under REST_NAMESPACE.
41     *
42     * @var string
43     */
44    const ROUTE = '/videopress/playlists';
45
46    /**
47     * Accepted playlist keys, as sanitize_key() leaves them.
48     *
49     * @var string
50     */
51    const KEY_PATTERN = '[a-z0-9_\-]+';
52
53    /**
54     * Fields the list can be sorted by.
55     *
56     * @var string[]
57     */
58    const ORDERBY = array( 'updated', 'title', 'videos' );
59
60    /**
61     * Post statuses a listed playlist can have, `publish` first.
62     *
63     * @var string[]
64     */
65    const STATUSES = array( 'publish', 'future', 'draft', 'pending', 'private' );
66
67    /**
68     * Statuses a playlist can be switched to from the dashboard.
69     *
70     * @var string[]
71     */
72    const SETTABLE_STATUSES = array( 'publish', 'draft' );
73
74    /**
75     * Post types a new playlist can be created in.
76     *
77     * @var string[]
78     */
79    const CREATABLE_POST_TYPES = array( 'page', 'post' );
80
81    /**
82     * Most unpublished posts read per request.
83     *
84     * @var int
85     */
86    const UNPUBLISHED_LIMIT = 200;
87
88    /**
89     * The block's display and playback attributes the dashboard edits, as
90     * block.json declares them ( Playlist_Manager_Test keeps the two in step ).
91     *
92     * @var array[]
93     */
94    const SETTINGS = array(
95        'showPlaylistTitle'    => array(
96            'type'    => 'boolean',
97            'default' => true,
98        ),
99        'layout'               => array(
100            'type'    => 'string',
101            'enum'    => array( 'side-rail', 'grid', 'strip' ),
102            'default' => 'side-rail',
103        ),
104        'darkPlayer'           => array(
105            'type'    => 'boolean',
106            'default' => false,
107        ),
108        'showPlayer'           => array(
109            'type'    => 'boolean',
110            'default' => true,
111        ),
112        'entryClickAction'     => array(
113            'type'    => 'string',
114            'enum'    => array( 'new-tab', 'show-player' ),
115            'default' => 'new-tab',
116        ),
117        'autoplayNext'         => array(
118            'type'    => 'boolean',
119            'default' => false,
120        ),
121        'muteByDefault'        => array(
122            'type'    => 'boolean',
123            'default' => false,
124        ),
125        'loopPlaylist'         => array(
126            'type'    => 'boolean',
127            'default' => false,
128        ),
129        'showThumbnail'        => array(
130            'type'    => 'boolean',
131            'default' => true,
132        ),
133        'showTitle'            => array(
134            'type'    => 'boolean',
135            'default' => true,
136        ),
137        'showResolution'       => array(
138            'type'    => 'boolean',
139            'default' => true,
140        ),
141        'showDuration'         => array(
142            'type'    => 'boolean',
143            'default' => true,
144        ),
145        'showPositionNumber'   => array(
146            'type'    => 'boolean',
147            'default' => false,
148        ),
149        'showTotalRuntime'     => array(
150            'type'    => 'boolean',
151            'default' => true,
152        ),
153        'entryTitleFontFamily' => array(
154            'type'    => 'string',
155            'default' => '',
156        ),
157    );
158
159    /**
160     * Register the playlist routes.
161     *
162     * @return void
163     */
164    public static function register_rest_routes() {
165        register_rest_route(
166            self::REST_NAMESPACE,
167            self::ROUTE,
168            array(
169                array(
170                    'methods'             => WP_REST_Server::READABLE,
171                    'callback'            => array( __CLASS__, 'rest_list_playlists' ),
172                    'permission_callback' => array( Rest_Controller::class, 'permissions_callback' ),
173                    'args'                => array(
174                        'page'     => array(
175                            'type'    => 'integer',
176                            'default' => 1,
177                            'minimum' => 1,
178                        ),
179                        'per_page' => array(
180                            'type'    => 'integer',
181                            'default' => 12,
182                            'minimum' => 1,
183                            'maximum' => 100,
184                        ),
185                        'search'   => array(
186                            'type'    => 'string',
187                            'default' => '',
188                        ),
189                        'orderby'  => array(
190                            'type'    => 'string',
191                            'default' => 'updated',
192                            'enum'    => self::ORDERBY,
193                        ),
194                        'order'    => array(
195                            'type'    => 'string',
196                            'default' => 'desc',
197                            'enum'    => array( 'asc', 'desc' ),
198                        ),
199                        'status'   => array(
200                            'type'    => 'array',
201                            'items'   => array(
202                                'type' => 'string',
203                                'enum' => self::STATUSES,
204                            ),
205                            'default' => array(),
206                        ),
207                    ),
208                ),
209                array(
210                    'methods'             => WP_REST_Server::CREATABLE,
211                    'callback'            => array( __CLASS__, 'rest_create_playlist' ),
212                    'permission_callback' => array( Rest_Controller::class, 'permissions_callback' ),
213                    'args'                => array_merge(
214                        self::playlist_args(),
215                        array(
216                            'postType' => array(
217                                'type'    => 'string',
218                                'enum'    => self::CREATABLE_POST_TYPES,
219                                'default' => 'page',
220                            ),
221                            'status'   => array(
222                                'type'    => 'string',
223                                'enum'    => self::SETTABLE_STATUSES,
224                                'default' => 'draft',
225                            ),
226                        )
227                    ),
228                ),
229            )
230        );
231
232        register_rest_route(
233            self::REST_NAMESPACE,
234            self::ROUTE . '/(?P<key>' . self::KEY_PATTERN . ')',
235            array(
236                array(
237                    'methods'             => WP_REST_Server::READABLE,
238                    'callback'            => array( __CLASS__, 'rest_get_playlist' ),
239                    'permission_callback' => array( Rest_Controller::class, 'permissions_callback' ),
240                ),
241                array(
242                    'methods'             => WP_REST_Server::EDITABLE,
243                    'callback'            => array( __CLASS__, 'rest_update_playlist' ),
244                    'permission_callback' => array( __CLASS__, 'edit_permissions_callback' ),
245                    'args'                => array_merge(
246                        self::playlist_args(),
247                        array(
248                            'status' => array(
249                                'type' => 'string',
250                                'enum' => self::SETTABLE_STATUSES,
251                            ),
252                        )
253                    ),
254                ),
255                array(
256                    'methods'             => WP_REST_Server::DELETABLE,
257                    'callback'            => array( __CLASS__, 'rest_delete_playlist' ),
258                    'permission_callback' => array( __CLASS__, 'edit_permissions_callback' ),
259                ),
260            )
261        );
262    }
263
264    /**
265     * Arguments shared by the create and update routes.
266     *
267     * @return array
268     */
269    private static function playlist_args() {
270        $settings = array();
271        foreach ( self::SETTINGS as $name => $schema ) {
272            unset( $schema['default'] );
273            $settings[ $name ] = $schema;
274        }
275
276        return array(
277            'title'       => array(
278                'type'              => 'string',
279                'sanitize_callback' => 'sanitize_text_field',
280            ),
281            'description' => array(
282                'type'              => 'string',
283                'sanitize_callback' => 'sanitize_textarea_field',
284            ),
285            'videos'      => array(
286                'type'  => 'array',
287                'items' => array(
288                    'type'       => 'object',
289                    'properties' => array(
290                        'guid'       => array(
291                            'type'     => 'string',
292                            'pattern'  => '^[a-zA-Z0-9]{8}$',
293                            'required' => true,
294                        ),
295                        'durationMs' => array(
296                            'type'    => 'integer',
297                            'minimum' => 0,
298                        ),
299                        'height'     => array(
300                            'type'    => 'integer',
301                            'minimum' => 0,
302                        ),
303                    ),
304                ),
305            ),
306            'settings'    => array(
307                'type'                 => 'object',
308                'properties'           => $settings,
309                'additionalProperties' => false,
310            ),
311        );
312    }
313
314    /**
315     * Changing a playlist needs the dashboard capability and the right to edit its post.
316     *
317     * @param WP_REST_Request $request Incoming request.
318     * @return bool
319     */
320    public static function edit_permissions_callback( WP_REST_Request $request ) {
321        if ( ! Rest_Controller::permissions_callback() ) {
322            return false;
323        }
324
325        $record = self::find_record( (string) $request['key'] );
326
327        // Unknown keys fall through to the callback, which answers 404.
328        return null === $record || current_user_can( 'edit_post', $record['post_id'] );
329    }
330
331    /**
332     * Kept for callers of the first version of the routes.
333     *
334     * @param WP_REST_Request $request Incoming request.
335     * @return bool
336     */
337    public static function update_permissions_callback( WP_REST_Request $request ) {
338        return self::edit_permissions_callback( $request );
339    }
340
341    /**
342     * List the site's playlists, a page at a time.
343     *
344     * @param WP_REST_Request $request Incoming request.
345     * @return WP_REST_Response
346     */
347    public static function rest_list_playlists( WP_REST_Request $request ) {
348        $result = self::query(
349            array(
350                'page'     => (int) $request['page'],
351                'per_page' => (int) $request['per_page'],
352                'search'   => (string) $request['search'],
353                'orderby'  => (string) $request['orderby'],
354                'order'    => (string) $request['order'],
355                'status'   => (array) $request['status'],
356            )
357        );
358
359        $response = rest_ensure_response( array_map( array( __CLASS__, 'prepare_item' ), $result['items'] ) );
360        $response->header( 'X-WP-Total', (string) $result['total'] );
361        $response->header( 'X-WP-TotalPages', (string) $result['total_pages'] );
362
363        return $response;
364    }
365
366    /**
367     * Get one playlist.
368     *
369     * @param WP_REST_Request $request Incoming request.
370     * @return WP_REST_Response|WP_Error
371     */
372    public static function rest_get_playlist( WP_REST_Request $request ) {
373        $record = self::find_record( (string) $request['key'] );
374        if ( ! $record ) {
375            return self::not_found();
376        }
377
378        return rest_ensure_response( self::prepare_item( $record ) );
379    }
380
381    /**
382     * Create a playlist in a new post.
383     *
384     * @param WP_REST_Request $request Incoming request.
385     * @return WP_REST_Response|WP_Error
386     */
387    public static function rest_create_playlist( WP_REST_Request $request ) {
388        $record = self::create(
389            array_merge(
390                self::changes_from_request( $request ),
391                array(
392                    'post_type' => (string) $request['postType'],
393                    'status'    => (string) $request['status'],
394                )
395            )
396        );
397        if ( is_wp_error( $record ) ) {
398            return $record;
399        }
400
401        $response = rest_ensure_response( self::prepare_item( $record ) );
402        $response->set_status( 201 );
403
404        return $response;
405    }
406
407    /**
408     * Update a playlist's details, videos, settings or post status.
409     *
410     * @param WP_REST_Request $request Incoming request.
411     * @return WP_REST_Response|WP_Error
412     */
413    public static function rest_update_playlist( WP_REST_Request $request ) {
414        $changes = self::changes_from_request( $request );
415        if ( $request->has_param( 'status' ) ) {
416            $changes['status'] = (string) $request->get_param( 'status' );
417        }
418
419        $record = self::update( (string) $request['key'], $changes );
420        if ( is_wp_error( $record ) ) {
421            return $record;
422        }
423
424        return rest_ensure_response( self::prepare_item( $record ) );
425    }
426
427    /**
428     * Delete a playlist.
429     *
430     * @param WP_REST_Request $request Incoming request.
431     * @return WP_REST_Response|WP_Error
432     */
433    public static function rest_delete_playlist( WP_REST_Request $request ) {
434        $result = self::delete( (string) $request['key'] );
435        if ( is_wp_error( $result ) ) {
436            return $result;
437        }
438
439        return rest_ensure_response( $result );
440    }
441
442    /**
443     * The playlist changes a request carries.
444     *
445     * @param WP_REST_Request $request Incoming request.
446     * @return array Any of `title`, `description`, `videos` and `settings`.
447     */
448    private static function changes_from_request( WP_REST_Request $request ) {
449        $changes = array();
450        foreach ( array( 'title', 'description', 'videos', 'settings' ) as $field ) {
451            if ( $request->has_param( $field ) ) {
452                $changes[ $field ] = $request->get_param( $field );
453            }
454        }
455
456        return $changes;
457    }
458
459    /**
460     * Filter, sort and paginate the playlists.
461     *
462     * @param array $args {
463     *     Query arguments.
464     *
465     *     @type int      $page     1-based page.
466     *     @type int      $per_page Playlists per page.
467     *     @type string   $search   Text matched against titles and descriptions.
468     *     @type string   $orderby  One of ORDERBY.
469     *     @type string   $order    `asc` or `desc`.
470     *     @type string[] $status   Post statuses to keep; empty keeps all.
471     * }
472     * @return array{items: array[], total: int, total_pages: int}
473     */
474    public static function query( array $args ) {
475        $page     = max( 1, (int) ( $args['page'] ?? 1 ) );
476        $per_page = max( 1, (int) ( $args['per_page'] ?? 12 ) );
477        $search   = trim( (string) ( $args['search'] ?? '' ) );
478        $orderby  = in_array( $args['orderby'] ?? '', self::ORDERBY, true ) ? $args['orderby'] : 'updated';
479        $order    = 'asc' === ( $args['order'] ?? 'desc' ) ? 'asc' : 'desc';
480        $statuses = array_values( array_intersect( (array) ( $args['status'] ?? array() ), self::STATUSES ) );
481
482        $playlists = array_values( self::records() );
483
484        if ( $statuses ) {
485            $playlists = array_values(
486                array_filter(
487                    $playlists,
488                    function ( $playlist ) use ( $statuses ) {
489                        return in_array( $playlist['status'], $statuses, true );
490                    }
491                )
492            );
493        }
494
495        if ( '' !== $search ) {
496            $playlists = array_values(
497                array_filter(
498                    $playlists,
499                    function ( $playlist ) use ( $search ) {
500                        return false !== stripos( $playlist['title'], $search )
501                            || false !== stripos( $playlist['description'], $search );
502                    }
503                )
504            );
505        }
506
507        usort(
508            $playlists,
509            function ( $a, $b ) use ( $orderby, $order ) {
510                switch ( $orderby ) {
511                    case 'title':
512                        $cmp = strcasecmp( $a['title'], $b['title'] );
513                        break;
514                    case 'videos':
515                        $cmp = count( $a['videos'] ) - count( $b['videos'] );
516                        break;
517                    default:
518                        $cmp = $a['updated'] - $b['updated'];
519                }
520                if ( 0 === $cmp ) {
521                    return strcmp( $a['key'], $b['key'] );
522                }
523                return 'asc' === $order ? $cmp : -$cmp;
524            }
525        );
526
527        $total = count( $playlists );
528
529        return array(
530            'items'       => array_slice( $playlists, ( $page - 1 ) * $per_page, $per_page ),
531            'total'       => $total,
532            'total_pages' => (int) ceil( $total / $per_page ),
533        );
534    }
535
536    /**
537     * Create a playlist: a new post holding one Video Playlist block.
538     *
539     * @param array $args Any of `title`, `description`, `videos` and `settings`,
540     *                    plus the new post's `post_type` and `status`.
541     * @return array|WP_Error The new record.
542     */
543    public static function create( array $args ) {
544        $post_type = in_array( $args['post_type'] ?? '', self::CREATABLE_POST_TYPES, true ) ? $args['post_type'] : 'page';
545        $status    = in_array( $args['status'] ?? '', self::SETTABLE_STATUSES, true ) ? $args['status'] : 'draft';
546        $type      = get_post_type_object( $post_type );
547
548        if ( ! $type || ! current_user_can( $type->cap->create_posts ) ) {
549            return new WP_Error(
550                'videopress_playlist_cannot_create',
551                __( 'You aren’t allowed to create playlists.', 'jetpack-videopress-pkg' ),
552                array( 'status' => rest_authorization_required_code() )
553            );
554        }
555        if ( 'publish' === $status && ! current_user_can( $type->cap->publish_posts ) ) {
556            return self::cannot_publish();
557        }
558
559        $title = isset( $args['title'] ) && is_string( $args['title'] ) ? $args['title'] : '';
560        $block = self::apply_changes(
561            array(
562                'blockName'    => Playlist_Index::BLOCK_NAME,
563                'attrs'        => array( 'playlistId' => wp_generate_uuid4() ),
564                'innerBlocks'  => array(),
565                'innerHTML'    => '',
566                'innerContent' => array(),
567            ),
568            array_merge(
569                array( 'title' => $title ),
570                array_intersect_key( $args, array_flip( array( 'description', 'videos', 'settings' ) ) )
571            )
572        );
573
574        $post_id = wp_insert_post(
575            wp_slash(
576                array(
577                    'post_type'    => $post_type,
578                    'post_status'  => $status,
579                    'post_title'   => '' !== $title ? $title : __( 'Untitled playlist', 'jetpack-videopress-pkg' ),
580                    'post_content' => serialize_block( $block ),
581                )
582            ),
583            true
584        );
585        if ( is_wp_error( $post_id ) ) {
586            return $post_id;
587        }
588
589        $record = self::record_for_block( $post_id, array( 0 ) );
590
591        return $record ? $record : self::not_found();
592    }
593
594    /**
595     * Rewrite a playlist's block in its post, and optionally its post's status.
596     *
597     * @param string $key     Playlist key.
598     * @param array  $changes Any of `title`, `description`, `videos`, `settings` and `status`.
599     * @return array|WP_Error The updated record.
600     */
601    public static function update( $key, array $changes ) {
602        $target = self::locate( $key );
603        if ( is_wp_error( $target ) ) {
604            return $target;
605        }
606        list( $post, $blocks, $path ) = $target;
607
608        $postarr = array(
609            'ID'           => $post->ID,
610            'post_content' => serialize_blocks( self::change_block_at( $blocks, $path, $changes ) ),
611        );
612
613        // A post named after its playlist, as the ones the dashboard creates are, follows a rename.
614        $old_title = self::block_at( $blocks, $path )['attrs']['playlistTitle'] ?? '';
615        if ( isset( $changes['title'] ) && is_string( $changes['title'] ) && '' !== trim( $changes['title'] )
616            && $changes['title'] !== $old_title && $post->post_title === $old_title ) {
617            $postarr['post_title'] = $changes['title'];
618        }
619
620        $status = $changes['status'] ?? null;
621        if ( is_string( $status ) && in_array( $status, self::SETTABLE_STATUSES, true ) && $status !== $post->post_status ) {
622            $type = get_post_type_object( $post->post_type );
623            if ( 'publish' === $status && ( ! $type || ! current_user_can( $type->cap->publish_posts ) ) ) {
624                return self::cannot_publish();
625            }
626            $postarr['post_status'] = $status;
627        }
628
629        $updated = wp_update_post( wp_slash( $postarr ), true );
630        if ( is_wp_error( $updated ) ) {
631            return $updated;
632        }
633
634        $saved = self::record_for_block( $post->ID, $path );
635
636        return $saved ? $saved : self::not_found();
637    }
638
639    /**
640     * Delete a playlist: remove its block, and trash the post when nothing else is left in it.
641     *
642     * @param string $key Playlist key.
643     * @return array|WP_Error `deleted`, whether the post went to the trash, and the playlist as it was.
644     */
645    public static function delete( $key ) {
646        $record = self::find_record( $key );
647        $target = self::locate( $key );
648        if ( ! $record || is_wp_error( $target ) ) {
649            return $record ? $target : self::not_found();
650        }
651        list( $post, $blocks, $path ) = $target;
652
653        $previous = self::prepare_item( $record );
654        $content  = serialize_blocks( self::remove_block_at( $blocks, $path ) );
655
656        if ( '' === trim( $content ) ) {
657            if ( ! current_user_can( 'delete_post', $post->ID ) ) {
658                return new WP_Error(
659                    'videopress_playlist_cannot_delete',
660                    __( 'You aren’t allowed to delete the post this playlist is in.', 'jetpack-videopress-pkg' ),
661                    array( 'status' => rest_authorization_required_code() )
662                );
663            }
664            if ( ! wp_trash_post( $post->ID ) ) {
665                return new WP_Error(
666                    'videopress_playlist_delete_failed',
667                    __( 'The playlist could not be deleted.', 'jetpack-videopress-pkg' ),
668                    array( 'status' => 500 )
669                );
670            }
671
672            return array(
673                'deleted'     => true,
674                'postTrashed' => true,
675                'previous'    => $previous,
676            );
677        }
678
679        $updated = wp_update_post(
680            wp_slash(
681                array(
682                    'ID'           => $post->ID,
683                    'post_content' => $content,
684                )
685            ),
686            true
687        );
688        if ( is_wp_error( $updated ) ) {
689            return $updated;
690        }
691
692        return array(
693            'deleted'     => true,
694            'postTrashed' => false,
695            'previous'    => $previous,
696        );
697    }
698
699    /**
700     * Find a playlist's post, its parsed blocks and the path to its block.
701     *
702     * @param string $key Playlist key.
703     * @return array|WP_Error [ WP_Post, blocks, path ].
704     */
705    private static function locate( $key ) {
706        $record = self::find_record( $key );
707        if ( ! $record ) {
708            return self::not_found();
709        }
710
711        $post = get_post( $record['post_id'] );
712        if ( ! $post instanceof WP_Post ) {
713            return self::not_found();
714        }
715
716        if ( ! function_exists( 'wp_check_post_lock' ) ) {
717            require_once ABSPATH . 'wp-admin/includes/post.php';
718        }
719        if ( wp_check_post_lock( $post->ID ) ) {
720            return new WP_Error(
721                'videopress_playlist_post_locked',
722                __( 'Someone is editing the post this playlist is in. Try again once they are done.', 'jetpack-videopress-pkg' ),
723                array( 'status' => 409 )
724            );
725        }
726
727        $blocks = parse_blocks( $post->post_content );
728        $path   = self::find_block_path( $blocks, $record['key'], $post->ID );
729        if ( null === $path ) {
730            return self::not_found();
731        }
732
733        return array( $post, $blocks, $path );
734    }
735
736    /**
737     * Apply playlist changes to the block a path leads to.
738     *
739     * @param array $blocks  Parsed blocks.
740     * @param int[] $path    Indexes leading to the block through `innerBlocks`.
741     * @param array $changes Any of `title`, `description`, `videos` and `settings`.
742     * @return array The blocks, with that one changed.
743     */
744    private static function change_block_at( array $blocks, array $path, array $changes ) {
745        $index = array_shift( $path );
746
747        if ( $path ) {
748            $blocks[ $index ]['innerBlocks'] = self::change_block_at( $blocks[ $index ]['innerBlocks'], $path, $changes );
749        } else {
750            $blocks[ $index ] = self::apply_changes( $blocks[ $index ], $changes );
751        }
752
753        return $blocks;
754    }
755
756    /**
757     * Remove the block a path leads to, with its slot in the parent's inner content.
758     *
759     * @param array $blocks Parsed blocks.
760     * @param int[] $path   Indexes leading to the block through `innerBlocks`.
761     * @return array The blocks without that one.
762     */
763    private static function remove_block_at( array $blocks, array $path ) {
764        $index = array_shift( $path );
765
766        if ( $path ) {
767            $parent      = $blocks[ $index ];
768            $child_index = $path[0];
769            if ( 1 === count( $path ) ) {
770                $parent['innerContent'] = self::without_inner_slot( $parent['innerContent'] ?? array(), $child_index );
771            }
772            $parent['innerBlocks'] = self::remove_block_at( $parent['innerBlocks'], $path );
773            $blocks[ $index ]      = $parent;
774
775            return $blocks;
776        }
777
778        array_splice( $blocks, $index, 1 );
779
780        // Drop the whitespace that separated the block from its neighbour, so no blank gap is left.
781        foreach ( array( $index - 1, $index ) as $neighbour ) {
782            if ( isset( $blocks[ $neighbour ] ) && self::is_whitespace_block( $blocks[ $neighbour ] ) ) {
783                array_splice( $blocks, $neighbour, 1 );
784                break;
785            }
786        }
787
788        return array_values( $blocks );
789    }
790
791    /**
792     * Whether a parsed block is the whitespace parse_blocks() keeps between blocks.
793     *
794     * @param array $block Parsed block.
795     * @return bool
796     */
797    private static function is_whitespace_block( array $block ) {
798        return null === ( $block['blockName'] ?? null ) && '' === trim( (string) ( $block['innerHTML'] ?? '' ) );
799    }
800
801    /**
802     * Drop the n-th inner block placeholder from a block's inner content.
803     *
804     * @param array $inner_content Inner content: strings and null placeholders.
805     * @param int   $n             Index of the inner block.
806     * @return array
807     */
808    private static function without_inner_slot( array $inner_content, $n ) {
809        $seen = -1;
810        foreach ( $inner_content as $i => $chunk ) {
811            if ( null === $chunk && ++$seen === $n ) {
812                array_splice( $inner_content, $i, 1 );
813                break;
814            }
815        }
816
817        return $inner_content;
818    }
819
820    /**
821     * Apply playlist changes to a parsed Video Playlist block.
822     *
823     * The heading inner block mirrors the title, so it is kept in step with
824     * `playlistTitle` and `showPlaylistTitle` the way the block editor does.
825     *
826     * @param array $block   Parsed block.
827     * @param array $changes Any of `title`, `description`, `videos` and `settings`.
828     * @return array The block with the changes applied.
829     */
830    public static function apply_changes( array $block, array $changes ) {
831        $attrs = isset( $block['attrs'] ) && is_array( $block['attrs'] ) ? $block['attrs'] : array();
832
833        if ( isset( $changes['title'] ) && is_string( $changes['title'] ) ) {
834            $attrs['playlistTitle'] = $changes['title'];
835        }
836
837        if ( isset( $changes['description'] ) && is_string( $changes['description'] ) ) {
838            $attrs['playlistDescription'] = $changes['description'];
839        }
840
841        if ( isset( $changes['videos'] ) && is_array( $changes['videos'] ) ) {
842            // Stored the way the block editor stores them: unknown metadata is left out.
843            $attrs['videos'] = array_map(
844                function ( $entry ) {
845                    return array_filter(
846                        array(
847                            'guid'       => $entry['guid'],
848                            'durationMs' => $entry['durationMs'],
849                            'height'     => $entry['height'],
850                        )
851                    );
852                },
853                Initializer::sanitize_playlist_entries( $changes['videos'] )
854            );
855        }
856
857        if ( isset( $changes['settings'] ) && is_array( $changes['settings'] ) ) {
858            foreach ( self::sanitize_settings( $changes['settings'] ) as $name => $value ) {
859                // The block editor leaves defaults out of the markup; so does this.
860                if ( self::SETTINGS[ $name ]['default'] === $value ) {
861                    unset( $attrs[ $name ] );
862                } else {
863                    $attrs[ $name ] = $value;
864                }
865            }
866        }
867
868        $block['attrs'] = $attrs;
869
870        return self::sync_heading( $block );
871    }
872
873    /**
874     * Keep only known settings with valid values.
875     *
876     * @param array $settings Raw settings.
877     * @return array
878     */
879    public static function sanitize_settings( array $settings ) {
880        $clean = array();
881
882        foreach ( self::SETTINGS as $name => $schema ) {
883            if ( ! array_key_exists( $name, $settings ) ) {
884                continue;
885            }
886            $value = $settings[ $name ];
887
888            if ( 'boolean' === $schema['type'] ) {
889                if ( is_bool( $value ) ) {
890                    $clean[ $name ] = $value;
891                }
892                continue;
893            }
894
895            if ( ! is_string( $value ) ) {
896                continue;
897            }
898            if ( isset( $schema['enum'] ) ) {
899                if ( in_array( $value, $schema['enum'], true ) ) {
900                    $clean[ $name ] = $value;
901                }
902                continue;
903            }
904            // The only free-form setting is a font-family preset slug.
905            $clean[ $name ] = sanitize_key( $value );
906        }
907
908        return $clean;
909    }
910
911    /**
912     * A playlist block's settings, defaults filled in.
913     *
914     * @param array $attrs Block attributes.
915     * @return array
916     */
917    public static function settings_from_attrs( array $attrs ) {
918        $settings = array();
919        foreach ( self::SETTINGS as $name => $schema ) {
920            $settings[ $name ] = $schema['default'];
921        }
922
923        return array_merge( $settings, self::sanitize_settings( $attrs ) );
924    }
925
926    /**
927     * Keep the heading inner block in step with the title, as the block editor's template does:
928     * a level-2 heading holding the title while `showPlaylistTitle` is on, none otherwise.
929     *
930     * @param array $block Parsed Video Playlist block.
931     * @return array
932     */
933    private static function sync_heading( array $block ) {
934        $attrs    = $block['attrs'];
935        $show     = ! isset( $attrs['showPlaylistTitle'] ) || false !== $attrs['showPlaylistTitle'];
936        $title    = isset( $attrs['playlistTitle'] ) && is_string( $attrs['playlistTitle'] ) ? $attrs['playlistTitle'] : '';
937        $existing = $block['innerBlocks'][0] ?? null;
938
939        if ( ! $show ) {
940            $block['innerBlocks']  = array();
941            $block['innerHTML']    = '';
942            $block['innerContent'] = array();
943
944            return $block;
945        }
946
947        if ( is_array( $existing ) && 'core/heading' === ( $existing['blockName'] ?? null ) ) {
948            if ( self::heading_text( $existing ) !== $title ) {
949                $block['innerBlocks'][0] = self::with_heading_text( $existing, $title );
950            }
951
952            return $block;
953        }
954
955        $html                  = '<h2 class="wp-block-heading">' . esc_html( $title ) . '</h2>';
956        $block['innerBlocks']  = array(
957            array(
958                'blockName'    => 'core/heading',
959                'attrs'        => array(),
960                'innerBlocks'  => array(),
961                'innerHTML'    => $html,
962                'innerContent' => array( $html ),
963            ),
964        );
965        $block['innerHTML']    = "\n\n";
966        $block['innerContent'] = array( "\n", null, "\n" );
967
968        return $block;
969    }
970
971    /**
972     * The plain text of a parsed core/heading block.
973     *
974     * @param array $heading Parsed heading block.
975     * @return string
976     */
977    private static function heading_text( array $heading ) {
978        return html_entity_decode( wp_strip_all_tags( (string) ( $heading['innerHTML'] ?? '' ) ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
979    }
980
981    /**
982     * Replace the text of a parsed core/heading block.
983     *
984     * @param array  $heading Parsed heading block.
985     * @param string $text    New plain-text heading.
986     * @return array
987     */
988    private static function with_heading_text( array $heading, $text ) {
989        $replace = function ( $html ) use ( $text ) {
990            return is_string( $html )
991                ? preg_replace_callback(
992                    '/^(\s*<h[1-6]\b[^>]*>).*(<\/h[1-6]>\s*)$/s',
993                    function ( $matches ) use ( $text ) {
994                        return $matches[1] . esc_html( $text ) . $matches[2];
995                    },
996                    $html
997                )
998                : $html;
999        };
1000
1001        $heading['innerHTML']    = $replace( $heading['innerHTML'] ?? '' );
1002        $heading['innerContent'] = array_map( $replace, $heading['innerContent'] ?? array() );
1003
1004        return $heading;
1005    }
1006
1007    /**
1008     * Locate the Video Playlist block a key names, mirroring how Playlist_Index keys them.
1009     *
1010     * @param array  $blocks  Parsed blocks of the post.
1011     * @param string $key     Playlist key.
1012     * @param int    $post_id Post the blocks belong to.
1013     * @return int[]|null Indexes leading to the block through `innerBlocks`, or null.
1014     */
1015    public static function find_block_path( array $blocks, $key, $post_id ) {
1016        $found = null;
1017
1018        foreach ( self::playlist_block_paths( $blocks ) as $ordinal => $path ) {
1019            $own_key = self::block_key( self::block_at( $blocks, $path ), $post_id, $ordinal );
1020
1021            // The index suffixes a key another post already owns with this post's id.
1022            // When a key repeats within the post, the index keeps the last block.
1023            if ( $own_key === $key || $own_key . '-' . $post_id === $key ) {
1024                $found = $path;
1025            }
1026        }
1027
1028        return $found;
1029    }
1030
1031    /**
1032     * The block a path leads to.
1033     *
1034     * @param array $blocks Parsed blocks.
1035     * @param int[] $path   Indexes leading to the block through `innerBlocks`.
1036     * @return array
1037     */
1038    private static function block_at( array $blocks, array $path ) {
1039        $block = $blocks[ $path[0] ];
1040        foreach ( array_slice( $path, 1 ) as $index ) {
1041            $block = $block['innerBlocks'][ $index ];
1042        }
1043
1044        return $block;
1045    }
1046
1047    /**
1048     * A playlist block's key before collisions with other posts are resolved.
1049     *
1050     * @param array $block   Parsed block.
1051     * @param int   $post_id Post the block belongs to.
1052     * @param int   $ordinal 0-based position among the post's playlist blocks.
1053     * @return string
1054     */
1055    private static function block_key( array $block, $post_id, $ordinal ) {
1056        $key = isset( $block['attrs']['playlistId'] ) && is_string( $block['attrs']['playlistId'] )
1057            ? sanitize_key( $block['attrs']['playlistId'] )
1058            : '';
1059
1060        return '' !== $key ? $key : $post_id . '-' . ( $ordinal + 1 );
1061    }
1062
1063    /**
1064     * Paths to every standalone Video Playlist block, in document order.
1065     *
1066     * @param array $blocks Parsed blocks.
1067     * @param int[] $prefix Path of the parent block.
1068     * @return int[][]
1069     */
1070    private static function playlist_block_paths( array $blocks, array $prefix = array() ) {
1071        $paths = array();
1072
1073        foreach ( $blocks as $index => $block ) {
1074            $name = $block['blockName'] ?? null;
1075            if ( in_array( $name, Playlist_Index::DYNAMIC_PLAYLIST_BLOCKS, true ) ) {
1076                continue;
1077            }
1078
1079            $path = array_merge( $prefix, array( $index ) );
1080            if ( Playlist_Index::BLOCK_NAME === $name ) {
1081                $source = $block['attrs']['source'] ?? 'own';
1082                if ( 'own' === $source ) {
1083                    $paths[] = $path;
1084                }
1085            }
1086
1087            if ( ! empty( $block['innerBlocks'] ) && is_array( $block['innerBlocks'] ) ) {
1088                $paths = array_merge( $paths, self::playlist_block_paths( $block['innerBlocks'], $path ) );
1089            }
1090        }
1091
1092        return $paths;
1093    }
1094
1095    /**
1096     * Every playlist the dashboard lists, keyed by playlist key: the published
1097     * ones from the index, then those in unpublished posts the user can edit.
1098     *
1099     * @return array[] Records as Channel::playlists() lists them, plus `status`.
1100     */
1101    public static function records() {
1102        $records = array();
1103        foreach ( Channel::playlists() as $playlist ) {
1104            $playlist['status']          = 'publish';
1105            $records[ $playlist['key'] ] = $playlist;
1106        }
1107
1108        foreach ( self::unpublished_posts() as $post ) {
1109            if ( ! current_user_can( 'edit_post', $post->ID ) ) {
1110                continue;
1111            }
1112            foreach ( Playlist_Index::extract_records( $post ) as $key => $record ) {
1113                $key = (string) $key;
1114                if ( isset( $records[ $key ] ) ) {
1115                    $key .= '-' . $post->ID;
1116                }
1117                $records[ $key ] = array_merge(
1118                    $record,
1119                    array(
1120                        'key'     => $key,
1121                        'status'  => $post->post_status,
1122                        'updated' => self::modified_time( $post ),
1123                    )
1124                );
1125            }
1126        }
1127
1128        return $records;
1129    }
1130
1131    /**
1132     * Unpublished posts that hold a Video Playlist block, most recently modified first.
1133     *
1134     * @return WP_Post[]
1135     */
1136    private static function unpublished_posts() {
1137        $add_content_clause = function ( $where ) {
1138            global $wpdb;
1139
1140            return $where . $wpdb->prepare(
1141                " AND {$wpdb->posts}.post_content LIKE %s",
1142                '%' . $wpdb->esc_like( '<!-- wp:' . Playlist_Index::BLOCK_NAME ) . '%'
1143            );
1144        };
1145
1146        add_filter( 'posts_where', $add_content_clause );
1147        $query = new WP_Query(
1148            array(
1149                'post_type'              => self::post_types(),
1150                'post_status'            => array_values( array_diff( self::STATUSES, array( 'publish' ) ) ),
1151                'posts_per_page'         => self::UNPUBLISHED_LIMIT,
1152                'orderby'                => 'modified',
1153                'order'                  => 'DESC',
1154                'no_found_rows'          => true,
1155                'ignore_sticky_posts'    => true,
1156                'suppress_filters'       => false,
1157                'update_post_meta_cache' => false,
1158                'update_post_term_cache' => false,
1159            )
1160        );
1161        remove_filter( 'posts_where', $add_content_clause );
1162
1163        return array_values(
1164            array_filter(
1165                $query->posts,
1166                function ( $post ) {
1167                    return $post instanceof WP_Post;
1168                }
1169            )
1170        );
1171    }
1172
1173    /**
1174     * Post types that hold playlists, as Playlist_Index indexes them.
1175     *
1176     * @return string[]
1177     */
1178    private static function post_types() {
1179        return array_values(
1180            array_filter(
1181                get_post_types( array( 'public' => true ) ),
1182                function ( $post_type ) {
1183                    return 'attachment' !== $post_type;
1184                }
1185            )
1186        );
1187    }
1188
1189    /**
1190     * When a post was last modified, as a Unix timestamp.
1191     *
1192     * A draft that was never updated has no GMT modified time, so fall back to the local one.
1193     *
1194     * @param WP_Post $post Post.
1195     * @return int
1196     */
1197    private static function modified_time( WP_Post $post ) {
1198        if ( '0000-00-00 00:00:00' !== $post->post_modified_gmt ) {
1199            return (int) strtotime( $post->post_modified_gmt . ' UTC' );
1200        }
1201
1202        return (int) strtotime( get_gmt_from_date( $post->post_modified ) . ' UTC' );
1203    }
1204
1205    /**
1206     * Look a playlist up by key.
1207     *
1208     * @param string $key Playlist key.
1209     * @return array|null
1210     */
1211    public static function find_record( $key ) {
1212        $records = self::records();
1213
1214        return $records[ $key ] ?? null;
1215    }
1216
1217    /**
1218     * The record of the playlist block at a path in a post, whatever its key turned out to be.
1219     *
1220     * @param int   $post_id Post id.
1221     * @param int[] $path    Indexes leading to the block through `innerBlocks`.
1222     * @return array|null
1223     */
1224    private static function record_for_block( $post_id, array $path ) {
1225        $post = get_post( $post_id );
1226        if ( ! $post instanceof WP_Post ) {
1227            return null;
1228        }
1229        $blocks = parse_blocks( $post->post_content );
1230
1231        foreach ( self::records() as $record ) {
1232            if ( (int) $record['post_id'] === (int) $post_id && self::find_block_path( $blocks, $record['key'], $post_id ) === $path ) {
1233                return $record;
1234            }
1235        }
1236
1237        return null;
1238    }
1239
1240    /**
1241     * The attributes of a record's block, read from its post.
1242     *
1243     * @param array $record Playlist record.
1244     * @return array
1245     */
1246    private static function block_attrs( array $record ) {
1247        $post = get_post( $record['post_id'] );
1248        if ( ! $post instanceof WP_Post ) {
1249            return array();
1250        }
1251
1252        $blocks = parse_blocks( $post->post_content );
1253        $path   = self::find_block_path( $blocks, $record['key'], $post->ID );
1254        if ( null === $path ) {
1255            return array();
1256        }
1257        $attrs = self::block_at( $blocks, $path )['attrs'] ?? array();
1258
1259        return is_array( $attrs ) ? $attrs : array();
1260    }
1261
1262    /**
1263     * Shape a playlist record for the REST response.
1264     *
1265     * @param array $record Record as records() lists it.
1266     * @return array
1267     */
1268    public static function prepare_item( array $record ) {
1269        $post    = get_post( $record['post_id'] );
1270        $videos  = array_map(
1271            function ( $entry ) {
1272                return array(
1273                    'guid'       => $entry['guid'],
1274                    'durationMs' => $entry['durationMs'],
1275                    'height'     => $entry['height'],
1276                );
1277            },
1278            $record['videos']
1279        );
1280        $is_post = $post instanceof WP_Post;
1281        $status  = $record['status'] ?? ( $is_post ? $post->post_status : 'publish' );
1282        $type    = $is_post ? get_post_type_object( $post->post_type ) : null;
1283
1284        if ( 'publish' === $status ) {
1285            $url = Channel::is_enabled() ? Channel::playlist_url( $record['key'] ) : ( $is_post ? (string) get_permalink( $post ) : '' );
1286        } else {
1287            $url = $is_post ? (string) get_preview_post_link( $post ) : '';
1288        }
1289
1290        return array(
1291            'key'         => $record['key'],
1292            'title'       => $record['title'],
1293            'description' => $record['description'],
1294            'videos'      => $videos,
1295            'videoCount'  => count( $videos ),
1296            'durationMs'  => array_sum( array_column( $videos, 'durationMs' ) ),
1297            'updated'     => gmdate( 'c', $record['updated'] ?? ( $is_post ? self::modified_time( $post ) : 0 ) ),
1298            'status'      => $status,
1299            'settings'    => self::settings_from_attrs( self::block_attrs( $record ) ),
1300            'post'        => array(
1301                'id'        => (int) $record['post_id'],
1302                'title'     => $is_post ? html_entity_decode( get_the_title( $post ), ENT_QUOTES, get_bloginfo( 'charset' ) ) : '',
1303                'type'      => $is_post ? $post->post_type : '',
1304                'typeLabel' => $type ? $type->labels->singular_name : '',
1305                'editUrl'   => $is_post ? (string) get_edit_post_link( $post, 'raw' ) : '',
1306            ),
1307            'url'         => $url,
1308            'canEdit'     => $is_post && current_user_can( 'edit_post', $post->ID ),
1309            'canPublish'  => $type && current_user_can( $type->cap->publish_posts ),
1310        );
1311    }
1312
1313    /**
1314     * The error for publishing without the capability.
1315     *
1316     * @return WP_Error
1317     */
1318    private static function cannot_publish() {
1319        return new WP_Error(
1320            'videopress_playlist_cannot_publish',
1321            __( 'You aren’t allowed to publish this playlist.', 'jetpack-videopress-pkg' ),
1322            array( 'status' => rest_authorization_required_code() )
1323        );
1324    }
1325
1326    /**
1327     * The not-found error shared by every playlist route.
1328     *
1329     * @return WP_Error
1330     */
1331    private static function not_found() {
1332        return new WP_Error(
1333            'videopress_playlist_not_found',
1334            __( 'Playlist not found.', 'jetpack-videopress-pkg' ),
1335            array( 'status' => 404 )
1336        );
1337    }
1338}