Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
70.33% covered (warning)
70.33%
147 / 209
60.87% covered (warning)
60.87%
14 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Customize_Feed
70.33% covered (warning)
70.33%
147 / 209
60.87% covered (warning)
60.87%
14 / 23
295.78
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
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
42
 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
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 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        $image = self::show_image_url();
224        if ( '' !== $image ) {
225            echo '<itunes:image href="' . esc_url( $image ) . '" />' . "\n";
226        }
227
228        echo self::category_tag( (string) get_option( 'podcasting_category_1', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
229        echo self::category_tag( (string) get_option( 'podcasting_category_2', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
230        echo self::category_tag( (string) get_option( 'podcasting_category_3', '' ) ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Pre-escaped XML fragment.
231    }
232
233    /**
234     * Item-level podcast tags (rss2_item).
235     */
236    public static function output_item_tags() {
237        global $post;
238
239        if ( ! $post instanceof WP_Post ) {
240            return;
241        }
242
243        $author = get_the_author();
244        if ( '' === $author ) {
245            $author = (string) get_option( 'podcasting_talent_name', '' );
246        }
247        if ( '' !== $author ) {
248            echo '<itunes:author>' . esc_xml( wp_strip_all_tags( $author ) ) . "</itunes:author>\n";
249        }
250
251        // Reuse the string `<description>` just emitted for this item; rebuilding
252        // it costs a second `wp_trim_excerpt()` pass over the whole post body.
253        // The fallback covers a feed template that skips `<description>`.
254        $excerpt = self::$item_summary[0] === (int) $post->ID
255            ? self::$item_summary[1]
256            : (string) apply_filters( 'the_excerpt_rss', get_the_excerpt() );
257        if ( '' !== $excerpt ) {
258            echo '<itunes:summary>' . esc_xml( wp_strip_all_tags( $excerpt ) ) . "</itunes:summary>\n";
259        }
260
261        // Per-item cover art: prefer the block's `coverArt`, fall back to the
262        // post's featured image. Either way, photon-resize to 3000×3000 to
263        // honour Apple's square-cover requirement. When neither is present
264        // the channel-level `<itunes:image>` applies as default per spec.
265        $attrs      = Episode_Block_Tags::get_block_attrs( $post );
266        $cover_url  = isset( $attrs['coverArt']['url'] ) ? trim( (string) $attrs['coverArt']['url'] ) : '';
267        $item_image = '' !== $cover_url ? self::maybe_photon( $cover_url ) : self::episode_image_url( $post->ID );
268        if ( '' !== $item_image ) {
269            echo '<itunes:image href="' . esc_url( $item_image ) . '" />' . "\n";
270        }
271
272        // Block-driven iTunes + Podcasting 2.0 tags. Legacy audio posts
273        // without the block contribute nothing — they keep their pre-block
274        // behavior intact aside from the cover art handled above.
275        if ( ! empty( $attrs ) ) {
276            Episode_Block_Tags::render_from_attrs( $attrs );
277        }
278    }
279
280    /**
281     * Keep the episode, feed-player, and subscribe blocks out of
282     * `<content:encoded>`, leaving the surrounding show-note prose.
283     *
284     * Short-circuits on `pre_render_block` rather than blanking the output on
285     * `render_block`, which runs the callback first and throws the result away.
286     * That callback is expensive per item: the episode block resolves DNS via
287     * `wp_http_validate_url()`, the player block fetches a feed over HTTP.
288     *
289     * @param string|null $pre_render   Short-circuit value; `null` renders normally.
290     * @param array       $parsed_block Parsed block, including its `blockName`.
291     * @return string|null
292     */
293    public static function skip_block_in_feed( $pre_render, $parsed_block ) {
294        if ( isset( $parsed_block['blockName'] ) && in_array(
295            $parsed_block['blockName'],
296            array( 'jetpack/podcast-episode', 'jetpack/podcast-player', 'jetpack/subscriptions' ),
297            true
298        ) ) {
299            return '';
300        }
301        return $pre_render;
302    }
303
304    /**
305     * Stash the item's rendered `<description>` for `<itunes:summary>` to reuse.
306     * Pass-through — the value is never modified.
307     *
308     * @param string $excerpt Filtered item excerpt.
309     * @return string
310     */
311    public static function capture_item_summary( $excerpt ) {
312        self::$item_summary = array( (int) get_the_ID(), (string) $excerpt );
313        return $excerpt;
314    }
315
316    /**
317     * Rewrite the enclosure URL through the WPCOM stats endpoint and append
318     * `<itunes:duration>` when resolvable. Duration is looked up against the
319     * *original* attachment URL — the stats URL is synthetic.
320     *
321     * A podcast item is only valid with a single `<enclosure>`, but core
322     * `rss_enclosure()` emits one per `enclosure` post-meta row and posts
323     * routinely accumulate several (URL drift across re-uploads / CDN hosts
324     * that `do_enclose()`'s dedup treats as distinct). Rewriting keys on
325     * post ID, so those rows all collapse to the same stats URL — we track
326     * emitted URLs per item and drop repeats so the feed carries exactly one.
327     *
328     * @param string $enclosure Generated enclosure markup.
329     * @return string
330     */
331    public static function rewrite_enclosure( $enclosure ) {
332        global $post;
333
334        if ( ! preg_match( '/url="([^"]*)"/i', $enclosure, $match ) ) {
335            return $enclosure;
336        }
337
338        $original_url = $match[1];
339        $final_url    = $original_url;
340        $post_obj     = $post instanceof WP_Post ? $post : null;
341
342        /**
343         * Whether to rewrite the enclosure through the WPCOM stats endpoint.
344         * Token-gated feeds (notably WPCOM's `private-podcasts.php`) opt out
345         * — the stats URL is a deterministic public endpoint that would
346         * bypass any token gating on the feed itself.
347         *
348         * @param bool         $enable Default true.
349         * @param WP_Post|null $post   The post being rendered.
350         */
351        $enable = (bool) apply_filters( 'wpcom_podcasting_enable_play_tracking', true, $post_obj );
352
353        // Skip rewrite for externally hosted enclosures — the stats endpoint 404s anything that isn't a local attachment.
354        $attachment_id = Episode_Media_Cache::attachment_id( $original_url );
355
356        if ( null !== $post_obj && $enable && $attachment_id > 0 ) {
357            // `null` when the site isn't connected; passed through so the filter can still inject a value.
358            $default_blog_id = Connection_Manager::get_site_id( true );
359
360            /**
361             * Override the blog ID baked into the stats URL.
362             *
363             * @param int|null $blog_id Default Jetpack connection site ID, or null when unavailable.
364             * @param WP_Post  $post    The post being rendered.
365             */
366            $blog_id = (int) apply_filters( 'wpcom_podcasting_tracked_blog_id', $default_blog_id, $post_obj );
367
368            // Bail when we can't resolve a real blog ID — emit the original URL rather than a guaranteed-404 stats URL.
369            if ( $blog_id > 0 ) {
370                $final_url = esc_url( self::build_stats_url( $blog_id, (int) $post_obj->ID, $original_url ) );
371                $enclosure = preg_replace_callback(
372                    '/url="[^"]*"/i',
373                    /**
374                     * Replace the matched `url="…"` attribute with the stats URL.
375                     * `$matches` is required by `preg_replace_callback`'s callable
376                     * signature but ignored — we always emit the same value.
377                     *
378                     * @param array $matches Regex matches.
379                     * @return string
380                     */
381                    static function ( array $matches ) use ( $final_url ) {
382                        unset( $matches );
383                        return 'url="' . $final_url . '"';
384                    },
385                    $enclosure,
386                    1
387                );
388            }
389        }
390
391        // Drop repeats: rows keyed per post, by final URL, so distinct enclosures
392        // survive while the duplicate stats URLs collapse to one. Registry is
393        // cleared per render — see `reset_render_state()`.
394        $post_id = null !== $post_obj ? (int) $post_obj->ID : 0;
395        if ( isset( self::$seen_enclosures[ $post_id ][ $final_url ] ) ) {
396            return '';
397        }
398        self::$seen_enclosures[ $post_id ][ $final_url ] = true;
399
400        if ( 0 === $attachment_id ) {
401            return $enclosure;
402        }
403
404        $metadata = wp_get_attachment_metadata( $attachment_id );
405        $duration = is_array( $metadata ) ? absint( $metadata['length'] ?? 0 ) : 0;
406
407        return 0 === $duration
408            ? $enclosure
409            : $enclosure . '<itunes:duration>' . $duration . "</itunes:duration>\n";
410    }
411
412    /**
413     * Clear the per-render statics. Hooked on `rss2_head` (at priority 0, before
414     * any item renders) so re-generating a feed within a single long-lived
415     * process — WP-CLI, a warm worker — starts fresh instead of dropping every
416     * enclosure as already-seen or reusing the last render's summary.
417     */
418    public static function reset_render_state() {
419        self::$seen_enclosures = array();
420        self::$item_summary    = array( 0, '' );
421    }
422
423    /**
424     * Cap the podcast feed at the configured number of episodes. Core reads the
425     * `posts_per_rss` *query var* before the site option of the same name, so the
426     * podcast feed gets its own length and every other feed keeps the site's.
427     *
428     * @param \WP_Query $query Query about to run.
429     */
430    public static function apply_feed_limit( $query ) {
431        if ( ! self::is_podcast_feed_query( $query ) ) {
432            return;
433        }
434
435        $query->set( 'posts_per_rss', Settings::feed_limit() );
436    }
437
438    /**
439     * Constrain the podcast feed's main query to episodes that carry an
440     * `enclosure` meta row, so the SQL `LIMIT`/`OFFSET` paginate over valid
441     * episodes only. Without this the enclosure filter runs on `the_posts` —
442     * after pagination — so a nominal ten-item page could come back short or
443     * empty while older valid episodes sit stranded on later pages.
444     *
445     * A correlated `EXISTS` subquery (semi-join) is used rather than a
446     * `meta_query` clause on purpose: episodes routinely accumulate several
447     * `enclosure` meta rows (see {@see self::rewrite_enclosure()}), and a
448     * single-clause `meta_query` INNER JOIN would multiply those into duplicate
449     * posts, breaking the `LIMIT` count all over again.
450     *
451     * @param string    $where The `WHERE` clause of the query.
452     * @param \WP_Query $query Query about to run.
453     * @return string
454     */
455    public static function constrain_feed_query( $where, $query ) {
456        if ( ! self::is_podcast_feed_query( $query ) ) {
457            return $where;
458        }
459
460        global $wpdb;
461
462        // Table names come from `$wpdb`; `meta_key` runs through `prepare()`.
463        $where .= $wpdb->prepare(
464            " AND EXISTS ( SELECT 1 FROM {$wpdb->postmeta} WHERE {$wpdb->postmeta}.post_id = {$wpdb->posts}.ID AND {$wpdb->postmeta}.meta_key = %s )",
465            'enclosure'
466        );
467
468        return $where;
469    }
470
471    /**
472     * A podcast item without an enclosure is invalid per Apple's spec and can
473     * take down the whole submission. The `enclosure` post meta is what
474     * `rss_enclosure()` reads, so it's the authoritative signal here too.
475     *
476     * The SQL constraint in {@see self::constrain_feed_query()} already excludes
477     * these at query time; this stays as a cheap final guard.
478     *
479     * Doubles as the warm-up point for the render: this is the first hook that
480     * sees the whole page of episodes, so {@see Episode_Media_Cache::prime()}
481     * resolves their media here rather than leaving it to per-item lookups.
482     *
483     * @param WP_Post[] $posts Posts about to be looped over.
484     * @param \WP_Query $query Query that produced them.
485     * @return WP_Post[]
486     */
487    public static function filter_posts_with_enclosure( $posts, $query ) {
488        if ( ! self::is_podcast_feed_query( $query ) ) {
489            return $posts;
490        }
491
492        Episode_Media_Cache::prime( $posts );
493
494        return array_values(
495            array_filter(
496                $posts,
497                static function ( $post ) {
498                    return $post instanceof WP_Post
499                        && ! empty( get_post_meta( $post->ID, 'enclosure', false ) );
500                }
501            )
502        );
503    }
504
505    /**
506     * Whether `$query` is the main podcast category feed query — the shared gate
507     * for the two query-time hooks ({@see self::constrain_feed_query()} and
508     * {@see self::filter_posts_with_enclosure()}), which fire before the `wp`
509     * action and so can't lean on `maybe_register_feed_hooks()`.
510     *
511     * @param \WP_Query $query Query to inspect.
512     * @return bool
513     */
514    private static function is_podcast_feed_query( $query ): bool {
515        if ( ! $query->is_main_query() || ! $query->is_feed() || ! $query->is_category() ) {
516            return false;
517        }
518        $category_id = self::resolve_category_id();
519        if ( 0 === $category_id ) {
520            return false;
521        }
522        $queried = $query->get_queried_object();
523        return $queried && isset( $queried->term_id ) && (int) $queried->term_id === $category_id;
524    }
525
526    /**
527     * Stored explicit value, normalized to the `'true'`/`'false'` strings the
528     * iTunes spec requires. Reuses `Settings::sanitize_explicit`
529     * so legacy `'yes'`/`'no'`/`'clean'` and modern boolean storage both work.
530     *
531     * @return string
532     */
533    public static function explicit_string(): string {
534        return Settings::sanitize_explicit( get_option( 'podcasting_explicit', false ) ) ? 'true' : 'false';
535    }
536
537    /**
538     * Show-level cover image URL — `Settings::raw_show_image_url()` routed
539     * through Photon at 3000×3000 when available.
540     *
541     * @return string
542     */
543    private static function show_image_url(): string {
544        $url = Settings::raw_show_image_url();
545        return '' === $url ? '' : self::maybe_photon( $url );
546    }
547
548    /**
549     * Build the WPCOM stats URL for a given episode. The endpoint redirects
550     * to the audio file after recording the play — the package never serves
551     * it, only points at it. Audio extensions outside the recognized set
552     * fall back to `mp3` to keep the URL shape uniform (matches the Podtrac
553     * / Megaphone / Art19 convention).
554     *
555     * @param int    $blog_id      WPCOM blog ID (Atomic should override via the
556     *                             `wpcom_podcasting_tracked_blog_id` filter).
557     * @param int    $post_id      Episode post ID.
558     * @param string $original_url Original enclosure URL — extension is pulled from here.
559     * @return string
560     */
561    private static function build_stats_url( int $blog_id, int $post_id, string $original_url ): string {
562        $path = (string) wp_parse_url( $original_url, PHP_URL_PATH );
563        $ext  = (string) preg_replace( '/[^a-z0-9]/', '', strtolower( (string) pathinfo( $path, PATHINFO_EXTENSION ) ) );
564        if ( ! in_array( $ext, array( 'mp3', 'm4a', 'm4b', 'aac', 'ogg', 'oga', 'opus', 'wav', 'flac', 'mp4', 'm4v', 'mov' ), true ) ) {
565            $ext = 'mp3';
566        }
567        return sprintf(
568            'https://public-api.wordpress.com/wpcom/v2/sites/%d/podcast-play/%d.%s',
569            $blog_id,
570            $post_id,
571            $ext
572        );
573    }
574
575    /**
576     * Resolve the configured podcast category ID. Prefers the numeric
577     * `podcasting_category_id`, falling back to a slug lookup against the
578     * legacy `podcasting_archive` option — older sites pre-date numeric
579     * storage and only have the slug. Returns 0 when neither resolves.
580     *
581     * A numeric ID whose term was deleted means "not configured" — the slug
582     * is not consulted in that case.
583     *
584     * @return int
585     */
586    public static function resolve_category_id(): int {
587        $category_id = (int) get_option( 'podcasting_category_id', 0 );
588        if ( $category_id > 0 ) {
589            $category = get_category( $category_id );
590            return ( $category && ! is_wp_error( $category ) && isset( $category->term_id ) ) ? (int) $category->term_id : 0;
591        }
592
593        $slug = (string) get_option( 'podcasting_archive', '' );
594        if ( '' === $slug ) {
595            return 0;
596        }
597
598        $term = get_term_by( 'slug', $slug, 'category' );
599        return ( $term && ! is_wp_error( $term ) && isset( $term->term_id ) ) ? (int) $term->term_id : 0;
600    }
601
602    /**
603     * Episode-level image URL — the post's featured image, Photon-resized,
604     * or `''` when no featured image is set. Used as the fallback per-item
605     * cover when the block doesn't supply its own.
606     *
607     * @param int $post_id Episode post ID.
608     * @return string
609     */
610    private static function episode_image_url( int $post_id ): string {
611        if ( ! has_post_thumbnail( $post_id ) ) {
612            return '';
613        }
614        $src = wp_get_attachment_image_src( get_post_thumbnail_id( $post_id ), 'full' );
615        if ( ! is_array( $src ) || empty( $src[0] ) ) {
616            return '';
617        }
618        return self::maybe_photon( $src[0] );
619    }
620
621    /**
622     * Route through Photon at exactly 3000×3000 so the feed always serves a
623     * square cover, regardless of the source aspect ratio. `resize` center-crops
624     * (unlike `fit`, which only constrains within the box); Apple's spec wants
625     * 1400–3000 px square art and rejects non-square covers.
626     *
627     * @param string $url Image URL.
628     * @return string
629     */
630    public static function maybe_photon( string $url ): string {
631        if ( ! function_exists( 'jetpack_photon_url' ) ) {
632            return $url;
633        }
634        // @phan-suppress-next-line PhanUndeclaredFunction -- Provided by Jetpack's Photon module at runtime; guarded by `function_exists` above.
635        return (string) jetpack_photon_url( $url, array( 'resize' => '3000,3000' ), 'https' );
636    }
637
638    /**
639     * Build a single `<itunes:category>` tag from a stored option value. The
640     * stored format is one of:
641     *   - `''` (no category)
642     *   - `'Foo'` → single category
643     *   - `'Foo,Bar'` → category Foo with subcategory Bar
644     *
645     * Includes a back-compat translation pass for a few legacy values that were
646     * stored in non-canonical shapes before validation tightened.
647     *
648     * @param string $stored Raw option value.
649     * @return string Empty string if no category, otherwise an XML fragment.
650     */
651    public static function category_tag( string $stored ): string {
652        static $legacy_aliases = array(
653            'Education,Education'                => 'Education',
654            'Education,Education Technology'     => 'Education,Educational Technology',
655            'Tech News'                          => 'Technology,Tech News',
656            'Sports &amp; Recreation,Technology' => 'Technology',
657            'Sports &amp; Recreation,Gadgets'    => 'Technology,Gadgets',
658            'Sports,Football'                    => 'Sports,American Football',
659            'Sports,Soccer'                      => 'Sports,Football (Soccer)',
660        );
661        $category              = $legacy_aliases[ $stored ] ?? $stored;
662
663        if ( '' === $category ) {
664            return '';
665        }
666
667        // `ent2ncr()` normalises named HTML entities (e.g. `&nbsp;`, `&copy;`) into
668        // numeric character references so an attribute value containing them stays
669        // well-formed XML after esc_attr().
670        $splits = explode( ',', $category );
671        if ( 2 === count( $splits ) ) {
672            return '<itunes:category text="' . ent2ncr( esc_attr( $splits[0] ) ) . '">' . "\n"
673                . "\t" . '<itunes:category text="' . ent2ncr( esc_attr( $splits[1] ) ) . '" />' . "\n"
674                . "</itunes:category>\n";
675        }
676        return '<itunes:category text="' . ent2ncr( esc_attr( $category ) ) . '" />' . "\n";
677    }
678}