Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.18% covered (success)
94.18%
340 / 361
73.33% covered (warning)
73.33%
22 / 30
CRAP
0.00% covered (danger)
0.00%
0 / 1
Channel_Data
94.18% covered (success)
94.18%
340 / 361
73.33% covered (warning)
73.33%
22 / 30
188.52
0.00% covered (danger)
0.00%
0 / 1
 reset
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 videos
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 cache_key
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 search_scope
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 has_full_list
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 query_args
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
4
 query_page
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
3
 video_count
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 query_videos
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
3
 record
88.89% covered (warning)
88.89%
16 / 18
0.00% covered (danger)
0.00%
0 / 1
11.17
 latest_video
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 video_views
100.00% covered (success)
100.00%
15 / 15
100.00% covered (success)
100.00%
1 / 1
9
 fetch_video_views
87.50% covered (warning)
87.50%
14 / 16
0.00% covered (danger)
0.00%
0 / 1
4.03
 parse_video_plays
80.95% covered (warning)
80.95%
17 / 21
0.00% covered (danger)
0.00%
0 / 1
17.77
 with_views
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 browse_request
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
10
 browse
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
6
 browse_results
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
9
 browse_page
91.67% covered (success)
91.67%
33 / 36
0.00% covered (danger)
0.00%
0 / 1
13.10
 matches_length
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
7.29
 video_details
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
17
 handle
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 subscriber_count
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
 fetch_subscriber_count
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
6.73
 parse_subscriber_counts
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
12
 total_views
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 joined
77.78% covered (warning)
77.78%
14 / 18
0.00% covered (danger)
0.00%
0 / 1
9.89
 compact_number
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
 ago
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 views_and_age
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * VideoPress Channel data: the site's videos, their views and the channel's numbers.
4 *
5 * @package automattic/jetpack-videopress
6 */
7
8namespace Automattic\Jetpack\VideoPress;
9
10use Automattic\Jetpack\Connection\Client;
11use WP_Post;
12
13/**
14 * Reads what the channel blocks show: the VideoPress videos in the media
15 * library ( straight from the posts table, as WordPress.com Simple has no
16 * wp/v2 routes on page renders ), their play counts from Jetpack Stats, and
17 * the channel's totals. Nothing is written to the blog except short-lived
18 * caches of the play and subscriber counts.
19 */
20class Channel_Data {
21
22    /**
23     * Most videos read for one listing; browsing, sorting and counting work on these.
24     *
25     * @var int
26     */
27    const MAX_VIDEOS = 1000;
28
29    /**
30     * Object-cache group and lifetime of the full video list. Keys carry the blog
31     * ID and the posts' last-changed stamp, so an upload or edit makes a new key.
32     */
33    const CACHE_GROUP = 'videopress_channel';
34    const CACHE_TTL   = DAY_IN_SECONDS;
35
36    /**
37     * Transient caching the play counts, and how long.
38     */
39    const VIEWS_TRANSIENT       = 'videopress_channel_video_views';
40    const VIEWS_TTL             = HOUR_IN_SECONDS;
41    const VIEWS_ERROR_TTL       = 10 * MINUTE_IN_SECONDS;
42    const SUBSCRIBERS_TRANSIENT = 'videopress_channel_subscribers';
43    const SUBSCRIBERS_TTL       = HOUR_IN_SECONDS;
44    const SUBSCRIBERS_ERROR_TTL = 10 * MINUTE_IN_SECONDS;
45    const SHORT_MAX_MS          = 1200000; // Under 20 minutes.
46    const LONG_MIN_MS           = 2700000; // Over 45 minutes.
47    const BROWSE_SORTS          = array( 'newest', 'popular', 'oldest' );
48    const BROWSE_LENGTHS        = array( 'any', 'short', 'mid', 'long' );
49    const SEARCH_MAX_LENGTH     = 100;
50    const QUERY_ARG_SEARCH      = 'videos-q';
51    const QUERY_ARG_SORT        = 'videos-sort';
52    const QUERY_ARG_LENGTH      = 'videos-length';
53    const QUERY_ARG_PAGE        = 'videos-page';
54    const DEFAULT_BROWSE_PAGE   = 1;
55    const COMPACT_THOUSAND      = 1000;
56    const COMPACT_TEN_THOUSAND  = 10000;
57    const COMPACT_MILLION       = 1000000;
58    const DEFAULT_HANDLE_PREFIX = '@';
59
60    /**
61     * Per-request cache of the video lists, keyed by blog ID, search scope and search term.
62     *
63     * @var array<int, array<string, array<string, array[]>>>
64     */
65    private static $videos = array();
66
67    /**
68     * Per-request cache of the play counts, keyed by blog ID.
69     *
70     * @var array<int, array<int, int>>
71     */
72    private static $views = array();
73
74    /**
75     * Forget the per-request caches ( tests, and after uploads in long requests ).
76     *
77     * @return void
78     */
79    public static function reset() {
80        self::$videos = array();
81        self::$views  = array();
82    }
83
84    /**
85     * The site's VideoPress videos, newest first.
86     *
87     * @param string $search Optional search term, matched against the attachments.
88     *
89     * @return array[] Records with id, guid, durationMs, height and publishedAt ( unix time ).
90     */
91    public static function videos( $search = '' ) {
92        $search  = is_string( $search ) ? trim( $search ) : '';
93        $blog_id = get_current_blog_id();
94        $scope   = self::search_scope( $search );
95        if ( isset( self::$videos[ $blog_id ][ $scope ][ $search ] ) ) {
96            return self::$videos[ $blog_id ][ $scope ][ $search ];
97        }
98
99        /**
100         * Short-circuits the channel's video list.
101         *
102         * @since 0.58.0
103         *
104         * @param array[]|null $videos Records with id, guid, durationMs, height and publishedAt, newest first; null to query.
105         * @param string       $search The search term, if any.
106         */
107        $videos = apply_filters( 'videopress_channel_videos', null, $search );
108        if ( ! is_array( $videos ) ) {
109            $key    = self::cache_key( 'videos', $search );
110            $videos = wp_cache_get( $key, self::CACHE_GROUP );
111            if ( ! is_array( $videos ) ) {
112                $videos = self::query_videos( $search );
113                wp_cache_set( $key, $videos, self::CACHE_GROUP, self::CACHE_TTL );
114            }
115        }
116
117        self::$videos[ $blog_id ][ $scope ][ $search ] = $videos;
118        return $videos;
119    }
120
121    /**
122     * Object-cache key for this blog's data, invalidated whenever a post changes.
123     *
124     * @param string $what   What is cached.
125     * @param string $search Search term, if any.
126     *
127     * @return string
128     */
129    public static function cache_key( $what, $search = '' ) {
130        return implode( ':', array( $what, get_current_blog_id(), wp_cache_get_last_changed( 'posts' ), self::search_scope( $search ), md5( (string) $search ) ) );
131    }
132
133    /**
134     * Who a search's matches are for, since members also match private videos' transcripts.
135     *
136     * @param string $search Search term.
137     *
138     * @return string
139     */
140    private static function search_scope( $search ) {
141        return '' !== (string) $search && current_user_can( 'read' ) ? 'member' : 'public';
142    }
143
144    /**
145     * Whether the full list for a search is already at hand ( this request or the
146     * object cache ), or is replaced by a filter, so reading it costs no query.
147     *
148     * @param string $search Search term.
149     *
150     * @return bool
151     */
152    private static function has_full_list( $search ) {
153        return isset( self::$videos[ get_current_blog_id() ][ $search ] )
154            || has_filter( 'videopress_channel_videos' )
155            || is_array( wp_cache_get( self::cache_key( 'videos', $search ), self::CACHE_GROUP ) );
156    }
157
158    /**
159     * The query arguments shared by the full list and the paged queries.
160     *
161     * @param string $search Search term.
162     * @param string $order  DESC ( newest first ) or ASC.
163     *
164     * @return array
165     */
166    private static function query_args( $search, $order = 'DESC' ) {
167        $is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM;
168        $args     = array(
169            'post_type'        => 'attachment',
170            'post_status'      => 'inherit',
171            'post_mime_type'   => $is_wpcom ? 'video' : Channel::MIME_TYPE,
172            // The ID breaks date ties, so ASC is exactly the reverse of DESC.
173            'orderby'          => array(
174                'date' => $order,
175                'ID'   => $order,
176            ),
177            'suppress_filters' => false,
178        );
179        if ( '' !== $search ) {
180            $args['s']                            = $search;
181            $args['videopress_transcript_search'] = Transcript_Index::is_search_enabled();
182        }
183        return $args;
184    }
185
186    /**
187     * One page of videos straight from SQL, for listings that need no full list.
188     *
189     * @param string $search   Search term.
190     * @param string $order    DESC or ASC.
191     * @param int    $per_page Page size.
192     * @param int    $page     1-based page.
193     *
194     * @return array{records: array[], total: int}|null Null when an attachment on the page is
195     *                                                   not a VideoPress video, so the SQL total cannot be trusted.
196     */
197    private static function query_page( $search, $order, $per_page, $page ) {
198        $query = new \WP_Query(
199            array_merge(
200                self::query_args( $search, $order ),
201                array(
202                    'posts_per_page'      => $per_page,
203                    'paged'               => $page,
204                    'ignore_sticky_posts' => true,
205                )
206            )
207        );
208
209        $records = array();
210        foreach ( $query->posts as $post ) {
211            $record = self::record( $post );
212            if ( ! $record ) {
213                return null;
214            }
215            $records[] = $record;
216        }
217        return array(
218            'records' => $records,
219            'total'   => (int) $query->found_posts,
220        );
221    }
222
223    /**
224     * How many videos the channel has, without reading the full list unless it is at hand.
225     *
226     * @return int
227     */
228    public static function video_count() {
229        if ( self::has_full_list( '' ) ) {
230            return count( self::videos() );
231        }
232        $page = self::query_page( '', 'DESC', 1, 1 );
233        return null === $page ? count( self::videos() ) : $page['total'];
234    }
235
236    /**
237     * Query the VideoPress attachments: by mime off WordPress.com Simple, and
238     * every video with a GUID in the platform's videos table on it.
239     *
240     * @param string $search Search term.
241     *
242     * @return array[]
243     */
244    private static function query_videos( $search ) {
245        $args                   = self::query_args( $search );
246        $args['posts_per_page'] = self::MAX_VIDEOS;
247
248        $videos = array();
249        foreach ( get_posts( $args ) as $post ) {
250            $record = self::record( $post );
251            if ( $record ) {
252                $videos[] = $record;
253            }
254        }
255        return $videos;
256    }
257
258    /**
259     * The listing record of one attachment, or null when it is not a VideoPress video.
260     *
261     * @param WP_Post|null $post The attachment.
262     *
263     * @return array|null
264     */
265    public static function record( $post ) {
266        if ( ! $post instanceof WP_Post ) {
267            return null;
268        }
269        $guid = Channel::guid( $post );
270        if ( '' === $guid ) {
271            return null;
272        }
273
274        $meta       = wp_get_attachment_metadata( $post->ID );
275        $meta       = is_array( $meta ) ? $meta : array();
276        $videopress = isset( $meta['videopress'] ) && is_array( $meta['videopress'] ) ? $meta['videopress'] : array();
277        $duration   = $videopress['duration'] ?? ( isset( $meta['length'] ) && is_numeric( $meta['length'] ) ? (int) $meta['length'] * 1000 : 0 );
278        $height     = $meta['height'] ?? $videopress['height'] ?? 0;
279        $published  = strtotime( $post->post_date_gmt . ' UTC' );
280
281        return array(
282            'id'          => (int) $post->ID,
283            'guid'        => $guid,
284            'durationMs'  => is_numeric( $duration ) ? max( 0, (int) $duration ) : 0,
285            'height'      => is_numeric( $height ) ? max( 0, (int) $height ) : 0,
286            'publishedAt' => false === $published ? 0 : (int) $published,
287        );
288    }
289
290    /**
291     * The newest video's attachment, or null.
292     *
293     * @return WP_Post|null
294     */
295    public static function latest_video() {
296        $page   = self::has_full_list( '' ) ? null : self::query_page( '', 'DESC', 1, 1 );
297        $videos = null === $page ? self::videos() : $page['records'];
298        $post   = $videos ? get_post( $videos[0]['id'] ) : null;
299        return $post instanceof WP_Post ? $post : null;
300    }
301
302    /**
303     * Play counts per attachment ID.
304     *
305     * @return array<int, int>
306     */
307    public static function video_views() {
308        $blog_id = get_current_blog_id();
309        if ( isset( self::$views[ $blog_id ] ) ) {
310            return self::$views[ $blog_id ];
311        }
312
313        $views = get_transient( self::VIEWS_TRANSIENT );
314        if ( ! is_array( $views ) ) {
315            $fetched = self::fetch_video_views();
316            $views   = is_array( $fetched ) ? $fetched : array();
317            // A failed fetch is cached as no plays for a short while, so it is not retried on every render.
318            set_transient( self::VIEWS_TRANSIENT, $views, null === $fetched ? self::VIEWS_ERROR_TTL : self::VIEWS_TTL );
319        }
320
321        /**
322         * Filters the play counts the channel shows and sorts by.
323         *
324         * @since 0.58.0
325         *
326         * @param array<int, int> $views Plays keyed by attachment ID.
327         */
328        $views = apply_filters( 'videopress_channel_video_views', $views );
329
330        $clean = array();
331        foreach ( is_array( $views ) ? $views : array() as $id => $count ) {
332            if ( is_numeric( $id ) && is_numeric( $count ) ) {
333                $clean[ (int) $id ] = max( 0, (int) $count );
334            }
335        }
336
337        self::$views[ $blog_id ] = $clean;
338        return $clean;
339    }
340
341    /**
342     * Ask Jetpack Stats for the video plays, when the Stats package is present.
343     *
344     * @return array<int, int>|null Plays keyed by post ID; null on failure.
345     */
346    private static function fetch_video_views() {
347        $stats_class = '\Automattic\Jetpack\Stats\WPCOM_Stats';
348        if ( ! class_exists( $stats_class ) ) {
349            return array();
350        }
351
352        /**
353         * Filters the query the channel sends to the video plays stats endpoint.
354         *
355         * @since 0.58.0
356         *
357         * @param array $args Endpoint query arguments.
358         */
359        $args = apply_filters(
360            'videopress_channel_video_plays_args',
361            array(
362                // With `summarize` the endpoint ignores `period` and reads `num` as days; it has no all-time option.
363                'period'    => 'day',
364                'num'       => 3650,
365                'max'       => 0,
366                'summarize' => 1,
367            )
368        );
369
370        $response = ( new $stats_class() )->get_video_plays( $args );
371        if ( is_wp_error( $response ) || ! is_array( $response ) ) {
372            return null;
373        }
374
375        return self::parse_video_plays( $response );
376    }
377
378    /**
379     * Collect attachment ID → plays from a `stats/video-plays` response. With `summarize`
380     * the rows sit in `days.summary.plays` ( `data` rows counting `views` with `complete_stats` );
381     * without it each day has its own `plays` rows, which are added up.
382     *
383     * @param mixed $response Decoded response.
384     *
385     * @return array<int, int>
386     */
387    public static function parse_video_plays( $response ) {
388        $response = json_decode( (string) wp_json_encode( $response, JSON_UNESCAPED_SLASHES ), true );
389        if ( ! is_array( $response ) ) {
390            return array();
391        }
392        $days = isset( $response['days'] ) && is_array( $response['days'] ) ? $response['days'] : array();
393        if ( isset( $response['summary'] ) && is_array( $response['summary'] ) ) {
394            $periods = array( $response['summary'] );
395        } elseif ( isset( $days['summary'] ) && is_array( $days['summary'] ) ) {
396            $periods = array( $days['summary'] );
397        } else {
398            $periods = $days;
399        }
400
401        $plays = array();
402        foreach ( $periods as $period ) {
403            if ( ! is_array( $period ) ) {
404                continue;
405            }
406            $rows = $period['plays'] ?? $period['data'] ?? array();
407            foreach ( is_array( $rows ) ? $rows : array() as $row ) {
408                $count = is_array( $row ) ? ( $row['plays'] ?? $row['views'] ?? null ) : null;
409                if ( ! isset( $row['post_id'] ) || ! is_numeric( $row['post_id'] ) || ! is_numeric( $count ) ) {
410                    continue;
411                }
412                $id           = (int) $row['post_id'];
413                $plays[ $id ] = ( $plays[ $id ] ?? 0 ) + max( 0, (int) $count );
414            }
415        }
416
417        return $plays;
418    }
419
420    /**
421     * Add the play count to listing records.
422     *
423     * @param array[] $records Records with an id.
424     *
425     * @return array[]
426     */
427    public static function with_views( array $records ) {
428        $views = self::video_views();
429        foreach ( $records as &$record ) {
430            $record['views'] = $views[ (int) ( $record['id'] ?? 0 ) ] ?? 0;
431        }
432        unset( $record );
433        return $records;
434    }
435
436    /**
437     * The browsing state a request asks for.
438     *
439     * @param bool   $read_filters Whether search, sort and length come from the request ( browse controls shown ).
440     * @param bool   $read_page    Whether the page comes from the request ( numbered pagination ).
441     * @param string $default_sort The block's own order.
442     *
443     * @return array{search: string, sort: string, length: string, page: int}
444     */
445    public static function browse_request( $read_filters, $read_page, $default_sort = 'newest' ) {
446        // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only listing arguments, like core's paged and s.
447        $get   = function ( $key ) {
448            return isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ? sanitize_text_field( wp_unslash( $_GET[ $key ] ) ) : '';
449        };
450        $state = array(
451            'search' => '',
452            'sort'   => in_array( $default_sort, self::BROWSE_SORTS, true ) ? $default_sort : 'newest',
453            'length' => 'any',
454            'page'   => self::DEFAULT_BROWSE_PAGE,
455        );
456
457        if ( $read_filters ) {
458            $state['search'] = function_exists( 'mb_substr' ) ? mb_substr( $get( self::QUERY_ARG_SEARCH ), 0, self::SEARCH_MAX_LENGTH ) : substr( $get( self::QUERY_ARG_SEARCH ), 0, self::SEARCH_MAX_LENGTH );
459            $sort            = $get( self::QUERY_ARG_SORT );
460            $sort            = 'latest' === $sort ? 'newest' : $sort;
461            if ( in_array( $sort, self::BROWSE_SORTS, true ) ) {
462                $state['sort'] = $sort;
463            }
464            $length = $get( self::QUERY_ARG_LENGTH );
465            if ( in_array( $length, self::BROWSE_LENGTHS, true ) ) {
466                $state['length'] = $length;
467            }
468        }
469        if ( $read_page ) {
470            $state['page'] = max( 1, absint( $get( self::QUERY_ARG_PAGE ) ) );
471        }
472        // phpcs:enable WordPress.Security.NonceVerification.Recommended
473
474        return $state;
475    }
476
477    /**
478     * One page of the channel's videos for a browsing state.
479     *
480     * @param array    $state       From browse_request().
481     * @param int      $per_page    Page size.
482     * @param string[] $exclude     GUIDs to leave out.
483     * @param bool     $with_views  Whether records need play counts.
484     *
485     * @return array{entries: array[], total: int, page: int, pages: int, start: int}
486     */
487    public static function browse( array $state, $per_page, array $exclude = array(), $with_views = false ) {
488        $result = self::browse_results( $state, $per_page, $exclude, $with_views );
489        $search = trim( (string) ( $state['search'] ?? '' ) );
490        if ( '' !== $search && Transcript_Index::is_search_enabled() ) {
491            foreach ( $result['entries'] as &$entry ) {
492                $match = Transcript_Index::can_read_transcript( (int) $entry['id'] ) ? Transcript_Index::match( (int) $entry['id'], $search ) : null;
493                if ( $match ) {
494                    $entry['snippet']      = $match['text'];
495                    $entry['snippetMatch'] = $match['needle'];
496                    $entry['startMs']      = $match['start'];
497                }
498            }
499            unset( $entry );
500        }
501        return $result;
502    }
503
504    /**
505     * One page of browse() before transcript snippets are added.
506     *
507     * @param array    $state      From browse_request().
508     * @param int      $per_page   Page size.
509     * @param string[] $exclude    GUIDs to leave out.
510     * @param bool     $with_views Whether records need play counts.
511     *
512     * @return array{entries: array[], total: int, page: int, pages: int, start: int}
513     */
514    private static function browse_results( array $state, $per_page, array $exclude, $with_views ) {
515        $per_page = max( 1, (int) $per_page );
516        $fast     = self::browse_page( $state, $per_page, $exclude, $with_views );
517        if ( null !== $fast ) {
518            return $fast;
519        }
520        $videos = self::videos( $state['search'] ?? '' );
521
522        if ( $exclude ) {
523            $videos = array_values(
524                array_filter(
525                    $videos,
526                    function ( $video ) use ( $exclude ) {
527                        return ! in_array( $video['guid'], $exclude, true );
528                    }
529                )
530            );
531        }
532
533        $length = $state['length'] ?? 'any';
534        if ( 'any' !== $length ) {
535            $videos = array_values(
536                array_filter(
537                    $videos,
538                    function ( $video ) use ( $length ) {
539                        return self::matches_length( (int) $video['durationMs'], $length );
540                    }
541                )
542            );
543        }
544
545        $sort = $state['sort'] ?? 'newest';
546        if ( $with_views || 'popular' === $sort ) {
547            $videos = self::with_views( $videos );
548        }
549        if ( 'popular' === $sort ) {
550            // Most viewed first; equal counts keep upload order ( newest first ).
551            $position = array_flip( array_keys( $videos ) );
552            uksort(
553                $videos,
554                function ( $a, $b ) use ( $videos, $position ) {
555                    $diff = $videos[ $b ]['views'] - $videos[ $a ]['views'];
556                    return 0 !== $diff ? $diff : $position[ $a ] - $position[ $b ];
557                }
558            );
559            $videos = array_values( $videos );
560        } elseif ( 'oldest' === $sort ) {
561            $videos = array_reverse( $videos );
562        }
563
564        $total = count( $videos );
565        $pages = max( 1, (int) ceil( $total / $per_page ) );
566        $page  = min( $pages, max( 1, (int) ( $state['page'] ?? 1 ) ) );
567        $start = ( $page - 1 ) * $per_page;
568
569        return array(
570            'entries' => array_slice( $videos, $start, $per_page ),
571            'total'   => $total,
572            'page'    => $page,
573            'pages'   => $pages,
574            'start'   => $start,
575        );
576    }
577
578    /**
579     * A browse() page straight from SQL: newest or oldest first, any length, and at
580     * most a few excluded videos on the first page. Null when the full list is
581     * needed ( popular, a length filter, exclusions elsewhere ) or already at hand.
582     *
583     * @param array    $state      From browse_request().
584     * @param int      $per_page   Page size.
585     * @param string[] $exclude    GUIDs to leave out.
586     * @param bool     $with_views Whether records need play counts.
587     *
588     * @return array|null Same shape as browse().
589     */
590    private static function browse_page( array $state, $per_page, array $exclude, $with_views ) {
591        $search = trim( (string) ( $state['search'] ?? '' ) );
592        $sort   = $state['sort'] ?? 'newest';
593        $page   = max( 1, (int) ( $state['page'] ?? 1 ) );
594        if ( ! in_array( $sort, array( 'newest', 'oldest' ), true )
595            || 'any' !== ( $state['length'] ?? 'any' )
596            || ( $exclude && 1 !== $page )
597            || self::has_full_list( $search )
598        ) {
599            return null;
600        }
601
602        $result = self::query_page( $search, 'oldest' === $sort ? 'ASC' : 'DESC', $per_page + count( $exclude ), $page );
603        if ( null === $result ) {
604            return null;
605        }
606
607        $records = $result['records'];
608        $total   = $result['total'];
609        if ( $exclude ) {
610            $kept = array_values(
611                array_filter(
612                    $records,
613                    function ( $video ) use ( $exclude ) {
614                        return ! in_array( $video['guid'], $exclude, true );
615                    }
616                )
617            );
618            // An excluded video beyond this window would make the total wrong.
619            if ( count( $records ) - count( $kept ) !== count( array_unique( $exclude ) ) && count( $records ) < $total ) {
620                return null;
621            }
622            $total  -= count( $records ) - count( $kept );
623            $records = array_slice( $kept, 0, $per_page );
624        }
625
626        $pages = max( 1, (int) ceil( $total / $per_page ) );
627        if ( $page > $pages ) {
628            return null;
629        }
630
631        return array(
632            'entries' => $with_views ? self::with_views( $records ) : $records,
633            'total'   => $total,
634            'page'    => $page,
635            'pages'   => $pages,
636            'start'   => ( $page - 1 ) * $per_page,
637        );
638    }
639
640    /**
641     * Whether a duration falls in a length bucket. Unknown durations match only "any".
642     *
643     * @param int    $duration_ms Duration.
644     * @param string $length      One of BROWSE_LENGTHS.
645     *
646     * @return bool
647     */
648    public static function matches_length( $duration_ms, $length ) {
649        if ( 'any' === $length ) {
650            return true;
651        }
652        if ( $duration_ms <= 0 ) {
653            return false;
654        }
655        switch ( $length ) {
656            case 'short':
657                return $duration_ms < self::SHORT_MAX_MS;
658            case 'mid':
659                return $duration_ms >= self::SHORT_MAX_MS && $duration_ms <= self::LONG_MIN_MS;
660            case 'long':
661                return $duration_ms > self::LONG_MIN_MS;
662        }
663        return true;
664    }
665
666    /**
667     * A video's display details from VideoPress, with the attachment as fallback.
668     *
669     * @param string           $guid       VideoPress GUID.
670     * @param int|WP_Post|null $attachment The attachment, when known.
671     *
672     * @return array{title: string, description: string, poster: string}
673     */
674    public static function video_details( $guid, $attachment = null ) {
675        $details = function_exists( 'videopress_get_video_details' ) && is_string( $guid ) && '' !== $guid ? videopress_get_video_details( $guid ) : null;
676        $details = is_object( $details ) && ! is_wp_error( $details ) ? $details : null;
677        $post    = null !== $attachment ? get_post( $attachment ) : ( $guid ? get_post( Channel::attachment_id( $guid ) ) : null );
678        $post    = $post instanceof WP_Post ? $post : null;
679
680        $title       = $details && ! empty( $details->title ) ? (string) $details->title : ( $post ? get_the_title( $post ) : '' );
681        $description = $details && ! empty( $details->description ) ? (string) $details->description : ( $post ? (string) $post->post_content : '' );
682        $poster      = $details && ! empty( $details->poster ) ? (string) $details->poster : '';
683
684        return array(
685            'title'       => $title,
686            'description' => $description,
687            'poster'      => $poster,
688        );
689    }
690
691    /**
692     * The channel's handle, e.g. "@journeythroughforever".
693     *
694     * @return string
695     */
696    public static function handle() {
697        $host  = (string) wp_parse_url( home_url(), PHP_URL_HOST );
698        $label = $host ? strtok( preg_replace( '/^www\./', '', $host ), '.' ) : '';
699
700        /**
701         * Filters the channel handle shown in the channel details.
702         *
703         * @since 0.58.0
704         *
705         * @param string $handle "@" plus the first label of the site's host; empty for none.
706         */
707        return (string) apply_filters( 'videopress_channel_handle', $label ? self::DEFAULT_HANDLE_PREFIX . $label : '' );
708    }
709
710    /**
711     * Subscriber count, or null when unknown.
712     *
713     * @return int|null
714     */
715    public static function subscriber_count() {
716        $count = function_exists( 'wpcom_subs_total_for_blog' ) ? wpcom_subs_total_for_blog() : self::fetch_subscriber_count();
717
718        /**
719         * Filters the subscriber count shown in the channel details: WordPress.com's count, read
720         * directly on WordPress.com and through the site's connection elsewhere.
721         *
722         * @since 0.58.0
723         *
724         * @param int|null $count Subscribers, or null when unknown.
725         */
726        $count = apply_filters( 'videopress_channel_subscriber_count', is_numeric( $count ) ? (int) $count : null );
727
728        return is_numeric( $count ) ? max( 0, (int) $count ) : null;
729    }
730
731    /**
732     * Subscribers ( email subscribers plus social followers, like the Subscribe block counts them )
733     * from WordPress.com through the site's connection, cached for an hour.
734     *
735     * @return int|null Null when the site is not connected or the request failed.
736     */
737    private static function fetch_subscriber_count() {
738        $cached = get_transient( self::SUBSCRIBERS_TRANSIENT );
739        if ( is_array( $cached ) && array_key_exists( 'count', $cached ) ) {
740            return is_numeric( $cached['count'] ) ? (int) $cached['count'] : null;
741        }
742
743        $blog_id = (int) VideoPressToken::blog_id();
744        $count   = $blog_id
745            ? self::parse_subscriber_counts(
746                Client::wpcom_json_api_request_as_blog( sprintf( '/sites/%d/subscribers/counts', $blog_id ), '2', array( 'timeout' => 5 ), null, 'wpcom' )
747            )
748            : null;
749
750        set_transient( self::SUBSCRIBERS_TRANSIENT, array( 'count' => $count ), null === $count ? self::SUBSCRIBERS_ERROR_TTL : self::SUBSCRIBERS_TTL );
751        return $count;
752    }
753
754    /**
755     * The subscriber total in a `/sites/%d/subscribers/counts` response:
756     * `{ "counts": { "total_subscribers": 42, "social_followers": 9, … } }`.
757     *
758     * @param mixed $response HTTP response array or WP_Error.
759     *
760     * @return int|null
761     */
762    public static function parse_subscriber_counts( $response ) {
763        if ( is_wp_error( $response ) || ! is_array( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
764            return null;
765        }
766        $body   = json_decode( (string) wp_remote_retrieve_body( $response ), true );
767        $counts = is_array( $body ) && isset( $body['counts'] ) && is_array( $body['counts'] ) ? $body['counts'] : null;
768        if ( ! $counts || ! isset( $counts['total_subscribers'] ) || ! is_numeric( $counts['total_subscribers'] ) ) {
769            return null;
770        }
771        $followers = isset( $counts['social_followers'] ) && is_numeric( $counts['social_followers'] ) ? (int) $counts['social_followers'] : 0;
772        return max( 0, (int) $counts['total_subscribers'] + $followers );
773    }
774
775    /**
776     * Total plays of the channel's videos.
777     *
778     * @return int
779     */
780    public static function total_views() {
781        $ids   = array_flip( array_column( self::videos(), 'id' ) );
782        $total = 0;
783        foreach ( self::video_views() as $id => $count ) {
784            if ( isset( $ids[ $id ] ) ) {
785                $total += $count;
786            }
787        }
788        return $total;
789    }
790
791    /**
792     * When the channel started: the site's registration date on a network,
793     * else its oldest published post. Unix time, 0 when unknown.
794     *
795     * @return int
796     */
797    public static function joined() {
798        $time = 0;
799        if ( is_multisite() && function_exists( 'get_site' ) ) {
800            $site = get_site();
801            if ( $site && ! empty( $site->registered ) && '0000-00-00 00:00:00' !== $site->registered ) {
802                $time = (int) strtotime( $site->registered . ' UTC' );
803            }
804        }
805        if ( ! $time ) {
806            $oldest = get_posts(
807                array(
808                    'post_type'      => 'any',
809                    'post_status'    => 'publish',
810                    'orderby'        => 'date',
811                    'order'          => 'ASC',
812                    'posts_per_page' => 1,
813                )
814            );
815            if ( $oldest && $oldest[0] instanceof WP_Post ) {
816                $time = (int) strtotime( $oldest[0]->post_date_gmt . ' UTC' );
817            }
818        }
819
820        /**
821         * Filters when the channel started, shown as "Joined".
822         *
823         * @since 0.58.0
824         *
825         * @param int $time Unix time, 0 when unknown.
826         */
827        return max( 0, (int) apply_filters( 'videopress_channel_joined', $time ) );
828    }
829
830    /**
831     * A compact count: 950, 1.2K, 48K, 1.2M.
832     *
833     * @param int $count The number.
834     *
835     * @return string
836     */
837    public static function compact_number( $count ) {
838        $count = max( 0, (int) $count );
839        if ( $count >= self::COMPACT_MILLION ) {
840            /* translators: %s: a number of millions, e.g. 1.2 */
841            return sprintf( __( '%sM', 'jetpack-videopress-pkg' ), number_format_i18n( $count / self::COMPACT_MILLION, 1 ) );
842        }
843        if ( $count >= self::COMPACT_TEN_THOUSAND ) {
844            /* translators: %s: a number of thousands, e.g. 48 */
845            return sprintf( __( '%sK', 'jetpack-videopress-pkg' ), number_format_i18n( floor( $count / self::COMPACT_THOUSAND ) ) );
846        }
847        if ( $count >= self::COMPACT_THOUSAND ) {
848            /* translators: %s: a number of thousands, e.g. 1.2 */
849            return sprintf( __( '%sK', 'jetpack-videopress-pkg' ), number_format_i18n( $count / self::COMPACT_THOUSAND, 1 ) );
850        }
851        return number_format_i18n( $count );
852    }
853
854    /**
855     * "3 days ago" for a unix time.
856     *
857     * @param int $time Unix time.
858     *
859     * @return string Empty when unknown.
860     */
861    public static function ago( $time ) {
862        $time = (int) $time;
863        if ( $time <= 0 ) {
864            return '';
865        }
866        /* translators: %s: a time span, e.g. "3 days". */
867        return sprintf( __( '%s ago', 'jetpack-videopress-pkg' ), human_time_diff( $time, time() ) );
868    }
869
870    /**
871     * "12K views · 3 days ago", from a listing record.
872     *
873     * @param array $record     Record with views and publishedAt.
874     * @param bool  $full_count Whether to print the full view count ( 12,345 ) instead of the compact one.
875     *
876     * @return string
877     */
878    public static function views_and_age( array $record, $full_count = false ) {
879        $parts = array();
880        if ( isset( $record['views'] ) ) {
881            $views   = (int) $record['views'];
882            $number  = $full_count ? number_format_i18n( $views ) : self::compact_number( $views );
883            $parts[] = sprintf(
884                /* translators: %s: number of views, e.g. "12K". */
885                _n( '%s view', '%s views', $views, 'jetpack-videopress-pkg' ),
886                $number
887            );
888        }
889        $ago = self::ago( (int) ( $record['publishedAt'] ?? 0 ) );
890        if ( '' !== $ago ) {
891            $parts[] = $ago;
892        }
893        return implode( ' · ', $parts );
894    }
895}