Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
78.10% covered (warning)
78.10%
164 / 210
65.22% covered (warning)
65.22%
15 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Customize_Feed
78.10% covered (warning)
78.10%
164 / 210
65.22% covered (warning)
65.22%
15 / 23
172.25
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 touch_episode_on_enclosure
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
5
 maybe_register_feed_hooks
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
20
 output_namespaces
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 feed_title
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
4.05
 feed_description
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 output_channel_tags
75.00% covered (warning)
75.00%
15 / 20
0.00% covered (danger)
0.00%
0 / 1
6.56
 output_item_tags
89.47% covered (warning)
89.47%
17 / 19
0.00% covered (danger)
0.00%
0 / 1
10.12
 skip_block_in_feed
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 capture_item_summary
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 rewrite_enclosure
96.88% covered (success)
96.88%
31 / 32
0.00% covered (danger)
0.00%
0 / 1
12
 reset_render_state
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 apply_feed_limit
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 constrain_feed_query
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 filter_posts_with_enclosure
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
3
 is_podcast_feed_query
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
7
 explicit_string
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 show_image_url
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 build_stats_url
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
2
 resolve_category_id
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
9
 episode_image_url
33.33% covered (danger)
33.33%
2 / 6
0.00% covered (danger)
0.00%
0 / 1
8.74
 maybe_photon
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 category_tag
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Adds podcast tags + tracked enclosure URLs to the RSS feed for the
4 * configured podcast category.
5 *
6 * @package automattic/jetpack-podcast
7 */
8
9declare( strict_types = 1 );
10
11namespace Automattic\Jetpack\Podcast\Feed;
12
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14use Automattic\Jetpack\Podcast\Settings;
15use WP_Post;
16
17/**
18 * Hooks into RSS2 rendering when the current request is the podcast category
19 * feed, adding `<itunes:*>` + `<podcast:*>` tags at channel and item level
20 * and rewriting `<enclosure>` URLs through the WPCOM stats endpoint.
21 */
22class Customize_Feed {
23
24    /**
25     * Whether `init()` has wired its hooks.
26     *
27     * @var bool
28     */
29    private static $registered = false;
30
31    /**
32     * Enclosure URLs already emitted in the current feed render, keyed by post
33     * ID then URL. Reset on `rss2_head` so each feed starts clean — see
34     * {@see self::reset_render_state()}.
35     *
36     * @var array<int, array<string, true>>
37     */
38    private static $seen_enclosures = array();
39
40    /**
41     * The `<description>` most recently rendered, as `[ post ID, value ]`, for
42     * {@see self::output_item_tags()} to reuse. One slot: the template emits
43     * `<description>` immediately before `rss2_item` fires for the same item.
44     * Reset per render — see {@see self::reset_render_state()} — so a template
45     * that skips `<description>` can't match a previous render's post ID.
46     *
47     * @var array{0: int, 1: string}
48     */
49    private static $item_summary = array( 0, '' );
50
51    /**
52     * Wire the late-binding `wp` action that decides whether to register the
53     * feed-modification hooks for this request. Idempotent.
54     */
55    public static function init() {
56        if ( self::$registered ) {
57            return;
58        }
59        self::$registered = true;
60
61        add_action( 'wp', array( __CLASS__, 'maybe_register_feed_hooks' ) );
62
63        // These hooks fire during query execution — before the `wp` action — so
64        // they're registered up-front and self-gated to the podcast feed query,
65        // rather than wired conditionally in `maybe_register_feed_hooks`.
66        //
67        // `posts_where` constrains the SQL itself so LIMIT/OFFSET paginate over
68        // episodes that actually have an enclosure; `the_posts` is a cheap final
69        // guard for the rare row the SQL constraint can't reach.
70        //
71        // `pre_get_posts` runs last so the gate reads the category every other
72        // callback has finished rewriting — and so `get_queried_object()` doesn't
73        // memoize a term ahead of them, which `posts_where` would then inherit.
74        add_action( 'pre_get_posts', array( __CLASS__, 'apply_feed_limit' ), PHP_INT_MAX );
75        add_filter( 'posts_where', array( __CLASS__, 'constrain_feed_query' ), 10, 2 );
76        add_filter( 'the_posts', array( __CLASS__, 'filter_posts_with_enclosure' ), 10, 2 );
77
78        add_action( 'added_post_meta', array( __CLASS__, 'touch_episode_on_enclosure' ), 10, 3 );
79    }
80
81    /**
82     * Bump an episode's modified time when cron adds its enclosure. The feed
83     * leaves the episode out until then, and its `Last-Modified` would otherwise
84     * stay put, so podcast apps that fetched in between get 304s indefinitely.
85     *
86     * @param int    $meta_id  Meta ID.
87     * @param int    $post_id  Post ID.
88     * @param string $meta_key Meta key.
89     */
90    public static function touch_episode_on_enclosure( $meta_id, $post_id, $meta_key ) {
91        if ( 'enclosure' !== $meta_key || 'publish' !== get_post_status( $post_id ) ) {
92            return;
93        }
94        $category_id = self::resolve_category_id();
95        if ( 0 === $category_id || ! has_category( $category_id, $post_id ) ) {
96            return;
97        }
98
99        wp_update_post( array( 'ID' => $post_id ) );
100    }
101
102    /**
103     * Register the RSS2 hooks if this request is the configured podcast feed.
104     * Also fires `Feed_Detection` while we're here — same gating, no need to
105     * walk the post query twice.
106     */
107    public static function maybe_register_feed_hooks() {
108        if ( ! is_feed() ) {
109            return;
110        }
111        $category_id = self::resolve_category_id();
112        if ( 0 === $category_id || ! is_category( $category_id ) ) {
113            return;
114        }
115
116        // Strip channel-level tags that conflict with the iTunes-compliant
117        // header: blavatar / site-icon `<image>` duplicates `<itunes:image>`,
118        // and `<cloud …/>` from rsscloud isn't part of the podcast spec.
119        remove_action( 'rss2_head', 'rss2_blavatar' );
120        remove_action( 'rss2_head', 'rss2_site_icon' );
121        remove_action( 'rss2_head', 'rsscloud_add_rss_cloud_element' );
122
123        add_action( 'rss2_ns', array( __CLASS__, 'output_namespaces' ) );
124        add_filter( 'wp_title_rss', array( __CLASS__, 'feed_title' ) );
125        add_filter( 'bloginfo_rss', array( __CLASS__, 'feed_description' ), 10, 2 );
126        add_action( 'rss2_head', array( __CLASS__, 'reset_render_state' ), 0 );
127        add_action( 'rss2_head', array( __CLASS__, 'output_channel_tags' ) );
128        add_action( 'rss2_item', array( __CLASS__, 'output_item_tags' ) );
129        add_filter( 'rss_enclosure', array( __CLASS__, 'rewrite_enclosure' ) );
130        // Last, so the captured value is what `<description>` actually printed —
131        // a filter above priority 10 would otherwise leave us caching an
132        // intermediate string and `<itunes:summary>` disagreeing with it.
133        add_filter( 'the_excerpt_rss', array( __CLASS__, 'capture_item_summary' ), PHP_INT_MAX );
134
135        add_filter( 'option_rss_use_excerpt', '__return_false' );
136        // Request-scoped to the feed: only the queried episodes render here, so
137        // this never touches block output outside the podcast feed response.
138        add_filter( 'pre_render_block', array( __CLASS__, 'skip_block_in_feed' ), 10, 2 );
139        add_filter( 'comments_open', '__return_false' );
140        add_filter( 'get_comments_number', '__return_zero' );
141        add_filter( 'the_category_rss', '__return_empty_string' );
142        remove_action( 'rss2_item', 'mrss_item', 10 );
143        remove_action( 'rss2_item', 'mrss_news_item' );
144
145        Feed_Detection::detect_and_record();
146    }
147
148    /**
149     * Add iTunes and Podcasting 2.0 XML namespaces to the `<rss>` open tag.
150     */
151    public static function output_namespaces() {
152        echo "\n\t" . 'xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"' . "\n";
153        echo "\t" . 'xmlns:podcast="https://podcastindex.org/namespace/1.0"' . "\n";
154    }
155
156    /**
157     * Override the feed title with `podcasting_title`, falling back to
158     * `Blog Name » Category Name`.
159     *
160     * @param string $title Existing title.
161     * @return string
162     */
163    public static function feed_title( $title ) {
164        $override = (string) get_option( 'podcasting_title', '' );
165        if ( '' !== $override ) {
166            return esc_xml( $override );
167        }
168
169        $category = get_category( self::resolve_category_id() );
170        if ( $category && ! is_wp_error( $category ) ) {
171            return esc_xml( get_bloginfo( 'name' ) ) . ' &#187; ' . esc_xml( $category->name );
172        }
173        return esc_xml( $title );
174    }
175
176    /**
177     * Replace the `bloginfo_rss('description')` value with `podcasting_summary`.
178     *
179     * `bloginfo_rss()` echoes the filter return value directly, so we strip and
180     * escape here — matches the channel-level `<itunes:summary>` treatment and
181     * keeps stray markup in the option from leaking into `<description>`.
182     *
183     * @param string $value Existing value.
184     * @param string $field Field being requested.
185     * @return string
186     */
187    public static function feed_description( $value, $field ) {
188        if ( 'description' !== $field ) {
189            return $value;
190        }
191        return esc_xml( wp_strip_all_tags( (string) get_option( 'podcasting_summary', '' ) ) );
192    }
193
194    /**
195     * Channel-level podcast tags (rss2_head).
196     */
197    public static function output_channel_tags() {
198        $summary = (string) get_option( 'podcasting_summary', '' );
199        if ( '' !== $summary ) {
200            echo '<itunes:summary>' . esc_xml( wp_strip_all_tags( $summary ) ) . "</itunes:summary>\n";
201        }
202
203        $author = (string) get_option( 'podcasting_talent_name', '' );
204        if ( '' !== $author ) {
205            echo '<itunes:author>' . esc_xml( wp_strip_all_tags( $author ) ) . "</itunes:author>\n";
206        }
207
208        $email = wp_strip_all_tags( (string) get_option( 'podcasting_email', '' ) );
209        if ( '' !== $email ) {
210            echo '<itunes:owner><itunes:email>' . esc_xml( $email ) . "</itunes:email></itunes:owner>\n";
211        }
212
213        $copyright = (string) get_option( 'podcasting_copyright', '' );
214        if ( '' !== $copyright ) {
215            echo '<copyright>' . esc_xml( wp_strip_all_tags( $copyright ) ) . "</copyright>\n";
216        }
217
218        /**
219         * Explicit content flag
220         */
221        echo '<itunes:explicit>' . esc_html( self::explicit_string() ) . "</itunes:explicit>\n";
222
223        echo '<itunes:type>' . esc_html( Settings::show_type() ) . "</itunes:type>\n";
224
225        $image = self::show_image_url();
226        if ( '' !== $image ) {
227            echo '<itunes:image href="' . esc_url( $image ) . '" />' . "\n";
228        }
229
230        echo self::category_tag( (string) get_option( 'podcasting_category_1', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
231        echo self::category_tag( (string) get_option( 'podcasting_category_2', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
232        echo self::category_tag( (string) get_option( 'podcasting_category_3', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
233    }
234
235    /**
236     * Item-level podcast tags (rss2_item).
237     */
238    public static function output_item_tags() {
239        global $post;
240
241        if ( ! $post instanceof WP_Post ) {
242            return;
243        }
244
245        $author = get_the_author();
246        if ( '' === $author ) {
247            $author = (string) get_option( 'podcasting_talent_name', '' );
248        }
249        if ( '' !== $author ) {
250            echo '<itunes:author>' . esc_xml( wp_strip_all_tags( $author ) ) . "</itunes:author>\n";
251        }
252
253        // Reuse the string `<description>` just emitted for this item; rebuilding
254        // it costs a second `wp_trim_excerpt()` pass over the whole post body.
255        // The fallback covers a feed template that skips `<description>`.
256        $excerpt = self::$item_summary[0] === (int) $post->ID
257            ? self::$item_summary[1]
258            : (string) apply_filters( 'the_excerpt_rss', get_the_excerpt() );
259        if ( '' !== $excerpt ) {
260            echo '<itunes:summary>' . esc_xml( wp_strip_all_tags( $excerpt ) ) . "</itunes:summary>\n";
261        }
262
263        // Per-item cover art: prefer the block's `coverArt`, fall back to the
264        // post's featured image. Either way, photon-resize to 3000×3000 to
265        // honour Apple's square-cover requirement. When neither is present
266        // the channel-level `<itunes:image>` applies as default per spec.
267        $attrs      = Episode_Block_Tags::get_block_attrs( $post );
268        $cover_url  = isset( $attrs['coverArt']['url'] ) ? trim( (string) $attrs['coverArt']['url'] ) : '';
269        $item_image = '' !== $cover_url ? self::maybe_photon( $cover_url ) : self::episode_image_url( $post->ID );
270        if ( '' !== $item_image ) {
271            echo '<itunes:image href="' . esc_url( $item_image ) . '" />' . "\n";
272        }
273
274        // Block-driven iTunes + Podcasting 2.0 tags. Legacy audio posts
275        // without the block contribute nothing — they keep their pre-block
276        // behavior intact aside from the cover art handled above.
277        if ( ! empty( $attrs ) ) {
278            Episode_Block_Tags::render_from_attrs( $attrs );
279        }
280    }
281
282    /**
283     * Keep the episode, feed-player, and subscribe blocks out of
284     * `<content:encoded>`, leaving the surrounding show-note prose.
285     *
286     * Short-circuits on `pre_render_block` rather than blanking the output on
287     * `render_block`, which runs the callback first and throws the result away.
288     * That callback is expensive per item: the episode block resolves DNS via
289     * `wp_http_validate_url()`, the player block fetches a feed over HTTP.
290     *
291     * @param string|null $pre_render   Short-circuit value; `null` renders normally.
292     * @param array       $parsed_block Parsed block, including its `blockName`.
293     * @return string|null
294     */
295    public static function skip_block_in_feed( $pre_render, $parsed_block ) {
296        if ( isset( $parsed_block['blockName'] ) && in_array(
297            $parsed_block['blockName'],
298            array( 'jetpack/podcast-episode', 'jetpack/podcast-player', 'jetpack/subscriptions' ),
299            true
300        ) ) {
301            return '';
302        }
303        return $pre_render;
304    }
305
306    /**
307     * Stash the item's rendered `<description>` for `<itunes:summary>` to reuse.
308     * Pass-through — the value is never modified.
309     *
310     * @param string $excerpt Filtered item excerpt.
311     * @return string
312     */
313    public static function capture_item_summary( $excerpt ) {
314        self::$item_summary = array( (int) get_the_ID(), (string) $excerpt );
315        return $excerpt;
316    }
317
318    /**
319     * Rewrite the enclosure URL through the WPCOM stats endpoint and append
320     * `<itunes:duration>` when resolvable. Duration is looked up against the
321     * *original* attachment URL — the stats URL is synthetic.
322     *
323     * A podcast item is only valid with a single `<enclosure>`, but core
324     * `rss_enclosure()` emits one per `enclosure` post-meta row and posts
325     * routinely accumulate several (URL drift across re-uploads / CDN hosts
326     * that `do_enclose()`'s dedup treats as distinct). Rewriting keys on
327     * post ID, so those rows all collapse to the same stats URL — we track
328     * emitted URLs per item and drop repeats so the feed carries exactly one.
329     *
330     * @param string $enclosure Generated enclosure markup.
331     * @return string
332     */
333    public static function rewrite_enclosure( $enclosure ) {
334        global $post;
335
336        if ( ! preg_match( '/url="([^"]*)"/i', $enclosure, $match ) ) {
337            return $enclosure;
338        }
339
340        $original_url = $match[1];
341        $final_url    = $original_url;
342        $post_obj     = $post instanceof WP_Post ? $post : null;
343
344        /**
345         * Whether to rewrite the enclosure through the WPCOM stats endpoint.
346         * Token-gated feeds (notably WPCOM's `private-podcasts.php`) opt out
347         * — the stats URL is a deterministic public endpoint that would
348         * bypass any token gating on the feed itself.
349         *
350         * @param bool         $enable Default true.
351         * @param WP_Post|null $post   The post being rendered.
352         */
353        $enable = (bool) apply_filters( 'wpcom_podcasting_enable_play_tracking', true, $post_obj );
354
355        // Skip rewrite for externally hosted enclosures — the stats endpoint 404s anything that isn't a local attachment.
356        $attachment_id = Episode_Media_Cache::attachment_id( $original_url );
357
358        if ( null !== $post_obj && $enable && $attachment_id > 0 ) {
359            // `null` when the site isn't connected; passed through so the filter can still inject a value.
360            $default_blog_id = Connection_Manager::get_site_id( true );
361
362            /**
363             * Override the blog ID baked into the stats URL.
364             *
365             * @param int|null $blog_id Default Jetpack connection site ID, or null when unavailable.
366             * @param WP_Post  $post    The post being rendered.
367             */
368            $blog_id = (int) apply_filters( 'wpcom_podcasting_tracked_blog_id', $default_blog_id, $post_obj );
369
370            // Bail when we can't resolve a real blog ID — emit the original URL rather than a guaranteed-404 stats URL.
371            if ( $blog_id > 0 ) {
372                $final_url = esc_url( self::build_stats_url( $blog_id, (int) $post_obj->ID, $original_url ) );
373                $enclosure = preg_replace_callback(
374                    '/url="[^"]*"/i',
375                    /**
376                     * Replace the matched `url="…"` attribute with the stats URL.
377                     * `$matches` is required by `preg_replace_callback`'s callable
378                     * signature but ignored — we always emit the same value.
379                     *
380                     * @param array $matches Regex matches.
381                     * @return string
382                     */
383                    static function ( array $matches ) use ( $final_url ) {
384                        unset( $matches );
385                        return 'url="' . $final_url . '"';
386                    },
387                    $enclosure,
388                    1
389                );
390            }
391        }
392
393        // Drop repeats: rows keyed per post, by final URL, so distinct enclosures
394        // survive while the duplicate stats URLs collapse to one. Registry is
395        // cleared per render — see `reset_render_state()`.
396        $post_id = null !== $post_obj ? (int) $post_obj->ID : 0;
397        if ( isset( self::$seen_enclosures[ $post_id ][ $final_url ] ) ) {
398            return '';
399        }
400        self::$seen_enclosures[ $post_id ][ $final_url ] = true;
401
402        if ( 0 === $attachment_id ) {
403            return $enclosure;
404        }
405
406        $metadata = wp_get_attachment_metadata( $attachment_id );
407        $duration = is_array( $metadata ) ? absint( $metadata['length'] ?? 0 ) : 0;
408
409        return 0 === $duration
410            ? $enclosure
411            : $enclosure . '<itunes:duration>' . $duration . "</itunes:duration>\n";
412    }
413
414    /**
415     * Clear the per-render statics. Hooked on `rss2_head` (at priority 0, before
416     * any item renders) so re-generating a feed within a single long-lived
417     * process — WP-CLI, a warm worker — starts fresh instead of dropping every
418     * enclosure as already-seen or reusing the last render's summary.
419     */
420    public static function reset_render_state() {
421        self::$seen_enclosures = array();
422        self::$item_summary    = array( 0, '' );
423    }
424
425    /**
426     * Cap the podcast feed at the configured number of episodes. Core reads the
427     * `posts_per_rss` *query var* before the site option of the same name, so the
428     * podcast feed gets its own length and every other feed keeps the site's.
429     *
430     * @param \WP_Query $query Query about to run.
431     */
432    public static function apply_feed_limit( $query ) {
433        if ( ! self::is_podcast_feed_query( $query ) ) {
434            return;
435        }
436
437        $query->set( 'posts_per_rss', Settings::feed_limit() );
438    }
439
440    /**
441     * Constrain the podcast feed's main query to episodes that carry an
442     * `enclosure` meta row, so the SQL `LIMIT`/`OFFSET` paginate over valid
443     * episodes only. Without this the enclosure filter runs on `the_posts` —
444     * after pagination — so a nominal ten-item page could come back short or
445     * empty while older valid episodes sit stranded on later pages.
446     *
447     * A correlated `EXISTS` subquery (semi-join) is used rather than a
448     * `meta_query` clause on purpose: episodes routinely accumulate several
449     * `enclosure` meta rows (see {@see self::rewrite_enclosure()}), and a
450     * single-clause `meta_query` INNER JOIN would multiply those into duplicate
451     * posts, breaking the `LIMIT` count all over again.
452     *
453     * @param string    $where The `WHERE` clause of the query.
454     * @param \WP_Query $query Query about to run.
455     * @return string
456     */
457    public static function constrain_feed_query( $where, $query ) {
458        if ( ! self::is_podcast_feed_query( $query ) ) {
459            return $where;
460        }
461
462        global $wpdb;
463
464        // Table names come from `$wpdb`; `meta_key` runs through `prepare()`.
465        $where .= $wpdb->prepare(
466            " AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} WHERE {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID AND {$wpdb->postmeta}.meta_key = %s )",
467            'enclosure'
468        );
469
470        return $where;
471    }
472
473    /**
474     * A podcast item without an enclosure is invalid per Apple's spec and can
475     * take down the whole submission. The `enclosure` post meta is what
476     * `rss_enclosure()` reads, so it's the authoritative signal here too.
477     *
478     * The SQL constraint in {@see self::constrain_feed_query()} already excludes
479     * these at query time; this stays as a cheap final guard.
480     *
481     * Doubles as the warm-up point for the render: this is the first hook that
482     * sees the whole page of episodes, so {@see Episode_Media_Cache::prime()}
483     * resolves their media here rather than leaving it to per-item lookups.
484     *
485     * @param WP_Post[] $posts Posts about to be looped over.
486     * @param \WP_Query $query Query that produced them.
487     * @return WP_Post[]
488     */
489    public static function filter_posts_with_enclosure( $posts, $query ) {
490        if ( ! self::is_podcast_feed_query( $query ) ) {
491            return $posts;
492        }
493
494        Episode_Media_Cache::prime( $posts );
495
496        return array_values(
497            array_filter(
498                $posts,
499                static function ( $post ) {
500                    return $post instanceof WP_Post
501                        && ! empty( get_post_meta( $post->ID, 'enclosure', false ) );
502                }
503            )
504        );
505    }
506
507    /**
508     * Whether `$query` is the main podcast category feed query — the shared gate
509     * for the two query-time hooks ({@see self::constrain_feed_query()} and
510     * {@see self::filter_posts_with_enclosure()}), which fire before the `wp`
511     * action and so can't lean on `maybe_register_feed_hooks()`.
512     *
513     * @param \WP_Query $query Query to inspect.
514     * @return bool
515     */
516    private static function is_podcast_feed_query( $query ): bool {
517        if ( ! $query->is_main_query() || ! $query->is_feed() || ! $query->is_category() ) {
518            return false;
519        }
520        $category_id = self::resolve_category_id();
521        if ( 0 === $category_id ) {
522            return false;
523        }
524        $queried = $query->get_queried_object();
525        return $queried && isset( $queried->term_id ) && (int) $queried->term_id === $category_id;
526    }
527
528    /**
529     * Stored explicit value, normalized to the `'true'`/`'false'` strings the
530     * iTunes spec requires. Reuses `Settings::sanitize_explicit`
531     * so legacy `'yes'`/`'no'`/`'clean'` and modern boolean storage both work.
532     *
533     * @return string
534     */
535    public static function explicit_string(): string {
536        return Settings::sanitize_explicit( get_option( 'podcasting_explicit', false ) ) ? 'true' : 'false';
537    }
538
539    /**
540     * Show-level cover image URL — `Settings::raw_show_image_url()` routed
541     * through Photon at 3000×3000 when available.
542     *
543     * @return string
544     */
545    private static function show_image_url(): string {
546        $url = Settings::raw_show_image_url();
547        return '' === $url ? '' : self::maybe_photon( $url );
548    }
549
550    /**
551     * Build the WPCOM stats URL for a given episode. The endpoint redirects
552     * to the audio file after recording the play — the package never serves
553     * it, only points at it. Audio extensions outside the recognized set
554     * fall back to `mp3` to keep the URL shape uniform (matches the Podtrac
555     * / Megaphone / Art19 convention).
556     *
557     * @param int    $blog_id      WPCOM blog ID (Atomic should override via the
558     *                             `wpcom_podcasting_tracked_blog_id` filter).
559     * @param int    $post_id      Episode post ID.
560     * @param string $original_url Original enclosure URL — extension is pulled from here.
561     * @return string
562     */
563    private static function build_stats_url( int $blog_id, int $post_id, string $original_url ): string {
564        $path = (string) wp_parse_url( $original_url, PHP_URL_PATH );
565        $ext  = (string) preg_replace( '/[^a-z0-9]/', '', strtolower( (string) pathinfo( $path, PATHINFO_EXTENSION ) ) );
566        if ( ! in_array( $ext, array( 'mp3', 'm4a', 'm4b', 'aac', 'ogg', 'oga', 'opus', 'wav', 'flac', 'mp4', 'm4v', 'mov' ), true ) ) {
567            $ext = 'mp3';
568        }
569        return sprintf(
570            'https://public-api.wordpress.com/wpcom/v2/sites/%d/podcast-play/%d.%s',
571            $blog_id,
572            $post_id,
573            $ext
574        );
575    }
576
577    /**
578     * Resolve the configured podcast category ID. Prefers the numeric
579     * `podcasting_category_id`, falling back to a slug lookup against the
580     * legacy `podcasting_archive` option — older sites pre-date numeric
581     * storage and only have the slug. Returns 0 when neither resolves.
582     *
583     * A numeric ID whose term was deleted means "not configured" — the slug
584     * is not consulted in that case.
585     *
586     * @return int
587     */
588    public static function resolve_category_id(): int {
589        $category_id = (int) get_option( 'podcasting_category_id', 0 );
590        if ( $category_id > 0 ) {
591            $category = get_category( $category_id );
592            return ( $category && ! is_wp_error( $category ) && isset( $category->term_id ) ) ? (int) $category->term_id : 0;
593        }
594
595        $slug = (string) get_option( 'podcasting_archive', '' );
596        if ( '' === $slug ) {
597            return 0;
598        }
599
600        $term = get_term_by( 'slug', $slug, 'category' );
601        return ( $term && ! is_wp_error( $term ) && isset( $term->term_id ) ) ? (int) $term->term_id : 0;
602    }
603
604    /**
605     * Episode-level image URL — the post's featured image, Photon-resized,
606     * or `''` when no featured image is set. Used as the fallback per-item
607     * cover when the block doesn't supply its own.
608     *
609     * @param int $post_id Episode post ID.
610     * @return string
611     */
612    private static function episode_image_url( int $post_id ): string {
613        if ( ! has_post_thumbnail( $post_id ) ) {
614            return '';
615        }
616        $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'full' );
617        if ( ! is_array( $src ) || empty( $src[0] ) ) {
618            return '';
619        }
620        return self::maybe_photon( $src[0] );
621    }
622
623    /**
624     * Route through Photon at exactly 3000×3000 so the feed always serves a
625     * square cover, regardless of the source aspect ratio. `resize` center-crops
626     * (unlike `fit`, which only constrains within the box); Apple's spec wants
627     * 1400–3000 px square art and rejects non-square covers.
628     *
629     * @param string $url Image URL.
630     * @return string
631     */
632    public static function maybe_photon( string $url ): string {
633        if ( ! function_exists( 'jetpack_photon_url' ) ) {
634            return $url;
635        }
636        // @phan-suppress-next-line PhanUndeclaredFunction -- Provided by Jetpack's Photon module at runtime; guarded by `function_exists` above.
637        return (string) jetpack_photon_url( $url, array( 'resize' => '3000,3000' ), 'https' );
638    }
639
640    /**
641     * Build a single `<itunes:category>` tag from a stored option value. The
642     * stored format is one of:
643     *   - `''` (no category)
644     *   - `'Foo'` → single category
645     *   - `'Foo,Bar'` → category Foo with subcategory Bar
646     *
647     * Includes a back-compat translation pass for a few legacy values that were
648     * stored in non-canonical shapes before validation tightened.
649     *
650     * @param string $stored Raw option value.
651     * @return string Empty string if no category, otherwise an XML fragment.
652     */
653    public static function category_tag( string $stored ): string {
654        static $legacy_aliases = array(
655            'Education,Education'                => 'Education',
656            'Education,Education Technology'     => 'Education,Educational Technology',
657            'Tech News'                          => 'Technology,Tech News',
658            'Sports &amp; Recreation,Technology' => 'Technology',
659            'Sports &amp; Recreation,Gadgets'    => 'Technology,Gadgets',
660            'Sports,Football'                    => 'Sports,American Football',
661            'Sports,Soccer'                      => 'Sports,Football (Soccer)',
662        );
663        $category              = $legacy_aliases[ $stored ] ?? $stored;
664
665        if ( '' === $category ) {
666            return '';
667        }
668
669        // `ent2ncr()` normalises named HTML entities (e.g. `&nbsp;`, `&copy;`) into
670        // numeric character references so an attribute value containing them stays
671        // well-formed XML after esc_attr().
672        $splits = explode( ',', $category );
673        if ( 2 === count( $splits ) ) {
674            return '<itunes:category text="' . ent2ncr( esc_attr( $splits[0] ) ) . '">' . "\n"
675                . "\t" . '<itunes:category text="' . ent2ncr( esc_attr( $splits[1] ) ) . '" />' . "\n"
676                . "</itunes:category>\n";
677        }
678        return '<itunes:category text="' . ent2ncr( esc_attr( $category ) ) . '" />' . "\n";
679    }
680}