Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.18% covered (success)
97.18%
207 / 213
75.00% covered (warning)
75.00%
12 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
Settings
97.18% covered (success)
97.18%
207 / 213
75.00% covered (warning)
75.00%
12 / 16
52
0.00% covered (danger)
0.00%
0 / 1
 register
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 add_to_sync_whitelist
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 register_settings
100.00% covered (success)
100.00%
92 / 92
100.00% covered (success)
100.00%
1 / 1
2
 get_all
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
1
 feed_limit
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 feed_url
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 rest_schema_properties
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
1
 raw_show_image_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 sanitize_explicit
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 sanitize_show_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
3
 show_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_feed_limit
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 feed_limit_max
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 sanitize_show_urls
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
7.01
 sanitize_show_states
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
10.01
 sanitize_show_url
81.25% covered (warning)
81.25%
13 / 16
0.00% covered (danger)
0.00%
0 / 1
10.66
1<?php
2/**
3 * Podcast settings: option schema, sanitizers, and Jetpack Sync opt-in.
4 *
5 * @package automattic/jetpack-podcast
6 */
7
8namespace Automattic\Jetpack\Podcast;
9
10/**
11 * Registers the `podcasting_*` options with their `sanitize_callback`s so writes
12 * through any path stay validated. The dashboard reads and writes them through the
13 * dedicated {@see Podcast_Settings_Endpoint} (`wpcom/v2/podcast/settings`); they
14 * are intentionally not exposed through core `/wp/v2/settings`.
15 *
16 * Array-shaped options merge against stored values on sanitize, not replace —
17 * the SPA can PATCH partial entries without losing the rest.
18 */
19class Settings {
20
21    /**
22     * Per-podcatcher hostname allowlist for `podcasting_show_urls`. `www.` is
23     * stripped before comparison.
24     *
25     * @var array<string, string[]>
26     */
27    const SHOW_URL_HOSTS = array(
28        'pocketcasts'  => array( 'pca.st', 'pocketcasts.com' ),
29        'apple'        => array( 'podcasts.apple.com' ),
30        'spotify'      => array( 'open.spotify.com' ),
31        'youtube'      => array( 'youtube.com', 'm.youtube.com', 'youtu.be', 'music.youtube.com' ),
32        'amazon'       => array(
33            'music.amazon.com',
34            'music.amazon.co.uk',
35            'music.amazon.de',
36            'music.amazon.co.jp',
37            'music.amazon.com.au',
38            'music.amazon.fr',
39            'music.amazon.ca',
40            'music.amazon.es',
41        ),
42        'iheartradio'  => array( 'iheart.com' ),
43        'podcastindex' => array( 'podcastindex.org' ),
44    );
45
46    const SHOW_URL_MAX_LENGTH = 2048;
47
48    /**
49     * Fallback when neither `podcasting_feed_limit` nor `posts_per_rss` is set.
50     */
51    const FEED_LIMIT_DEFAULT = 300;
52
53    /**
54     * Ceiling for `podcasting_feed_limit`. Sized against measured feed generation.
55     */
56    const FEED_LIMIT_MAX = 500;
57
58    /**
59     * Drives `register_settings()` and the sync whitelist.
60     *
61     * @var string[]
62     */
63    const OPTION_NAMES = array(
64        'podcasting_category_id',
65        'podcasting_title',
66        'podcasting_talent_name',
67        'podcasting_summary',
68        'podcasting_copyright',
69        'podcasting_explicit',
70        'podcasting_show_type',
71        'podcasting_image',
72        'podcasting_image_id',
73        'podcasting_category_1',
74        'podcasting_category_2',
75        'podcasting_category_3',
76        'podcasting_email',
77        'podcasting_show_urls',
78        'podcasting_show_states',
79        'podcasting_feed_limit',
80    );
81
82    /**
83     * Wire option registrations + Jetpack Sync opt-in. Idempotent: every
84     * callback is named, so WordPress dedupes repeat calls.
85     */
86    public static function register() {
87        add_action( 'admin_init', array( __CLASS__, 'register_settings' ) );
88        add_action( 'rest_api_init', array( __CLASS__, 'register_settings' ) );
89        add_filter( 'jetpack_sync_options_whitelist', array( __CLASS__, 'add_to_sync_whitelist' ) );
90    }
91
92    /**
93     * Add the podcast options to the Jetpack Sync whitelist.
94     *
95     * @param string[] $options Whitelisted option names.
96     * @return string[]
97     */
98    public static function add_to_sync_whitelist( $options ) {
99        return array_merge( $options, self::OPTION_NAMES );
100    }
101
102    /**
103     * `register_setting()` calls. Hooked on `admin_init` and `rest_api_init`.
104     */
105    public static function register_settings() {
106        $media_settings = array(
107            array( 'podcasting_category_id', 'integer', 0, 'absint' ),
108            array( 'podcasting_title', 'string', '', 'sanitize_text_field' ),
109            array( 'podcasting_talent_name', 'string', '', 'sanitize_text_field' ),
110            array( 'podcasting_summary', 'string', '', 'sanitize_textarea_field' ),
111            array( 'podcasting_copyright', 'string', '', 'sanitize_text_field' ),
112            array( 'podcasting_category_1', 'string', '', 'sanitize_text_field' ),
113            array( 'podcasting_category_2', 'string', '', 'sanitize_text_field' ),
114            array( 'podcasting_category_3', 'string', '', 'sanitize_text_field' ),
115        );
116
117        // Registered under WP core's `media` group to match WPCOM's legacy Media
118        // Settings form, so it keeps accepting these.
119        foreach ( $media_settings as list( $name, $type, $default, $sanitize ) ) {
120            register_setting(
121                'media',
122                $name,
123                array(
124                    'type'              => $type,
125                    'default'           => $default,
126                    'sanitize_callback' => $sanitize,
127                )
128            );
129        }
130
131        register_setting(
132            'media',
133            'podcasting_image',
134            array(
135                'type'              => 'string',
136                'default'           => '',
137                'sanitize_callback' => 'esc_url_raw',
138            )
139        );
140
141        register_setting(
142            'media',
143            'podcasting_explicit',
144            array(
145                'type'              => 'boolean',
146                'default'           => false,
147                'sanitize_callback' => array( __CLASS__, 'sanitize_explicit' ),
148            )
149        );
150
151        register_setting(
152            'media',
153            'podcasting_show_type',
154            array(
155                'type'              => 'string',
156                'default'           => 'episodic',
157                'sanitize_callback' => array( __CLASS__, 'sanitize_show_type' ),
158            )
159        );
160
161        // Registered under WP core's `options` group: settings WPCOM never wired
162        // into a Settings API form.
163        register_setting(
164            'options',
165            'podcasting_email',
166            array(
167                'type'              => 'string',
168                'default'           => '',
169                'sanitize_callback' => 'sanitize_email',
170            )
171        );
172
173        register_setting(
174            'options',
175            'podcasting_image_id',
176            array(
177                'type'              => 'integer',
178                'default'           => 0,
179                'sanitize_callback' => 'absint',
180            )
181        );
182
183        register_setting(
184            'options',
185            'podcasting_show_urls',
186            array(
187                'type'              => 'object',
188                'default'           => array(),
189                'sanitize_callback' => array( __CLASS__, 'sanitize_show_urls' ),
190            )
191        );
192
193        register_setting(
194            'options',
195            'podcasting_show_states',
196            array(
197                'type'              => 'object',
198                'default'           => array(),
199                'sanitize_callback' => array( __CLASS__, 'sanitize_show_states' ),
200            )
201        );
202
203        // Default is the unset sentinel, not `FEED_LIMIT_DEFAULT`: `update_option()`
204        // compares against the default-backed read and bails before creating the
205        // row, so any other default would make that exact value unsavable.
206        register_setting(
207            'options',
208            'podcasting_feed_limit',
209            array(
210                'type'              => 'integer',
211                'default'           => 0,
212                'sanitize_callback' => array( __CLASS__, 'sanitize_feed_limit' ),
213            )
214        );
215    }
216
217    /**
218     * Stable, fully-padded settings payload for the REST endpoint. Every
219     * `OPTION_NAMES` key is present; the two podcatcher maps are padded to all
220     * known directories with empty strings so the SPA always sees a fixed shape.
221     *
222     * @return array<string, mixed>
223     */
224    public static function get_all(): array {
225        $empty_map   = array_fill_keys( array_keys( self::SHOW_URL_HOSTS ), '' );
226        $show_urls   = (array) get_option( 'podcasting_show_urls', array() );
227        $show_states = (array) get_option( 'podcasting_show_states', array() );
228
229        return array(
230            'podcasting_category_id' => (int) get_option( 'podcasting_category_id', 0 ),
231            'podcasting_title'       => (string) get_option( 'podcasting_title', '' ),
232            'podcasting_talent_name' => (string) get_option( 'podcasting_talent_name', '' ),
233            'podcasting_summary'     => (string) get_option( 'podcasting_summary', '' ),
234            'podcasting_copyright'   => (string) get_option( 'podcasting_copyright', '' ),
235            'podcasting_explicit'    => self::sanitize_explicit( get_option( 'podcasting_explicit', false ) ),
236            'podcasting_show_type'   => self::show_type(),
237            'podcasting_image'       => self::raw_show_image_url(),
238            'podcasting_image_id'    => (int) get_option( 'podcasting_image_id', 0 ),
239            'podcasting_category_1'  => (string) get_option( 'podcasting_category_1', '' ),
240            'podcasting_category_2'  => (string) get_option( 'podcasting_category_2', '' ),
241            'podcasting_category_3'  => (string) get_option( 'podcasting_category_3', '' ),
242            'podcasting_email'       => (string) get_option( 'podcasting_email', '' ),
243            'podcasting_show_urls'   => array_merge( $empty_map, array_intersect_key( $show_urls, $empty_map ) ),
244            'podcasting_show_states' => array_merge( $empty_map, array_intersect_key( $show_states, $empty_map ) ),
245            'podcasting_feed_limit'  => self::feed_limit(),
246            'podcasting_feed_url'    => self::feed_url(),
247        );
248    }
249
250    /**
251     * Episodes the podcast feed should carry. Until the site sets one this seeds
252     * from core's `posts_per_rss`, so existing feeds keep their current length.
253     *
254     * Sanitized on read because Sync writes on shadow blogs never hit the
255     * registered `sanitize_callback`.
256     *
257     * @return int
258     */
259    public static function feed_limit(): int {
260        return self::sanitize_feed_limit( get_option( 'podcasting_feed_limit', 0 ) );
261    }
262
263    /**
264     * Canonical RSS feed URL for the configured podcast category. Derived
265     * read-only field on the settings payload — not a stored option.
266     *
267     * Built with WordPress's own {@see get_term_feed_link()} so it stays correct
268     * across every permalink structure (pretty, plain `?cat=N`, no trailing
269     * slash) and is identical on WPCOM and self-hosted. This is the URL the
270     * category feed is actually served at — the SPA must not reconstruct it by
271     * string-appending `feed/` to the archive link.
272     *
273     * @return string Feed URL, or '' when no valid category is configured.
274     */
275    public static function feed_url(): string {
276        $category_id = (int) get_option( 'podcasting_category_id', 0 );
277        if ( $category_id <= 0 ) {
278            return '';
279        }
280        $link = get_term_feed_link( $category_id, 'category' );
281        if ( false === $link ) {
282            return '';
283        }
284        // get_term_feed_link() HTML-escapes the query separator (`&amp;`) in the
285        // plain-permalink form because core builds it for HTML attributes. The
286        // dashboard copies this straight into a directory submission field, so
287        // decode it back to a literal URL — otherwise `?feed=rss2&amp;cat=N` loses
288        // the `cat` filter and serves the whole-site feed instead of the category.
289        return html_entity_decode( $link, ENT_QUOTES );
290    }
291
292    /**
293     * Per-key type map for the endpoint's update args. Type coercion only — the
294     * registered `sanitize_callback`s do the real validation on write, so a single
295     * bad field can't 400 the whole partial patch.
296     *
297     * @return array<string, array<string, mixed>>
298     */
299    public static function rest_schema_properties(): array {
300        return array(
301            'podcasting_category_id' => array( 'type' => 'integer' ),
302            'podcasting_title'       => array( 'type' => 'string' ),
303            'podcasting_talent_name' => array( 'type' => 'string' ),
304            'podcasting_summary'     => array( 'type' => 'string' ),
305            'podcasting_copyright'   => array( 'type' => 'string' ),
306            'podcasting_explicit'    => array( 'type' => array( 'boolean', 'string' ) ),
307            'podcasting_show_type'   => array( 'type' => 'string' ),
308            'podcasting_image'       => array( 'type' => 'string' ),
309            'podcasting_image_id'    => array( 'type' => 'integer' ),
310            'podcasting_category_1'  => array( 'type' => 'string' ),
311            'podcasting_category_2'  => array( 'type' => 'string' ),
312            'podcasting_category_3'  => array( 'type' => 'string' ),
313            'podcasting_email'       => array( 'type' => 'string' ),
314            'podcasting_show_urls'   => array( 'type' => 'object' ),
315            'podcasting_show_states' => array( 'type' => 'object' ),
316            'podcasting_feed_limit'  => array( 'type' => 'integer' ),
317        );
318    }
319
320    /**
321     * Show cover image URL: `podcasting_image_id` resolved to its attachment
322     * URL when it points at an image, otherwise the raw `podcasting_image`
323     * option. Never Photon-routed — feed rendering applies its own resize.
324     *
325     * @return string Image URL, or '' when not configured.
326     */
327    public static function raw_show_image_url(): string {
328        $image_id = (int) get_option( 'podcasting_image_id', 0 );
329        if ( $image_id > 0 && wp_attachment_is_image( $image_id ) ) {
330            $url = wp_get_attachment_url( $image_id );
331            if ( false !== $url ) {
332                return $url;
333            }
334        }
335        return (string) get_option( 'podcasting_image', '' );
336    }
337
338    /**
339     * `'yes'` (any case) or boolean true → true; everything else → false. The
340     * feed only emits true/false; the legacy `'clean'` value collapses to false
341     * because the WPCOM feed builder already treats it that way.
342     *
343     * @param mixed $value Raw input.
344     * @return bool
345     */
346    public static function sanitize_explicit( $value ) {
347        if ( is_string( $value ) ) {
348            return in_array( strtolower( $value ), array( 'yes', 'true', '1' ), true );
349        }
350        return true === $value || 1 === $value;
351    }
352
353    /**
354     * `'serial'` (any case) stays serial; everything else is `'episodic'`.
355     *
356     * @param mixed $value Raw input.
357     * @return string
358     */
359    public static function sanitize_show_type( $value ) {
360        return is_string( $value ) && 'serial' === strtolower( $value ) ? 'serial' : 'episodic';
361    }
362
363    /**
364     * Stored show type, sanitized on read because Sync writes on shadow blogs
365     * never hit the registered `sanitize_callback`.
366     *
367     * @return string
368     */
369    public static function show_type(): string {
370        return self::sanitize_show_type( get_option( 'podcasting_show_type', 'episodic' ) );
371    }
372
373    /**
374     * Clamp the feed episode limit to 1–{@see self::feed_limit_max()}. Cleared and
375     * junk input resolves the way an unset option does — the site's own
376     * `posts_per_rss` — rather than emptying the feed or jumping it to a default
377     * far above whatever the site was already serving.
378     *
379     * @param mixed $value Raw input.
380     * @return int
381     */
382    public static function sanitize_feed_limit( $value ) {
383        $value = (int) $value;
384        if ( $value < 1 ) {
385            $value = (int) get_option( 'posts_per_rss', self::FEED_LIMIT_DEFAULT );
386        }
387
388        return min( $value < 1 ? self::FEED_LIMIT_DEFAULT : $value, self::feed_limit_max() );
389    }
390
391    /**
392     * Most episodes the podcast feed will carry.
393     *
394     * @return int
395     */
396    public static function feed_limit_max(): int {
397        /**
398         * Filters the ceiling for the podcast feed's episode limit. Raising it
399         * renders that many items in one request, so only where the host can
400         * absorb it.
401         *
402         * @since 1.5.0
403         *
404         * @param int $max Maximum episodes a podcast feed may carry.
405         */
406        $max = (int) apply_filters( 'jetpack_podcast_feed_limit_max', self::FEED_LIMIT_MAX );
407
408        return max( 1, $max );
409    }
410
411    /**
412     * Merge a partial show-URLs patch into the stored value. Empty string for a
413     * known key removes that entry; URLs failing the per-podcatcher hostname
414     * allowlist are silently dropped (the SPA validates the same allowlist).
415     *
416     * @param mixed $input Incoming patch.
417     * @return array<string, string>
418     */
419    public static function sanitize_show_urls( $input ) {
420        $current = array_filter(
421            array_intersect_key( (array) get_option( 'podcasting_show_urls', array() ), self::SHOW_URL_HOSTS ),
422            static function ( $value ) {
423                return is_string( $value ) && '' !== $value;
424            }
425        );
426
427        if ( ! is_array( $input ) ) {
428            return $current;
429        }
430
431        foreach ( array_intersect_key( $input, self::SHOW_URL_HOSTS ) as $key => $value ) {
432            $value = is_string( $value ) ? trim( $value ) : '';
433
434            if ( '' === $value ) {
435                unset( $current[ $key ] );
436                continue;
437            }
438
439            $cleaned = self::sanitize_show_url( $key, $value );
440            if ( null !== $cleaned ) {
441                $current[ $key ] = $cleaned;
442            }
443        }
444
445        return $current;
446    }
447
448    /**
449     * Merge a partial show-states patch into the stored value. Values outside
450     * the allowed `'pending'`/`'active'` set are dropped; empty string clears a
451     * stored entry. `'active'` → `'pending'` is
452     * refused so a stale SPA cache can't downgrade a state that `Feed_Detection`
453     * promoted via real UA evidence (explicit `''` clears still work).
454     *
455     * @param mixed $input Incoming patch.
456     * @return array<string, string>
457     */
458    public static function sanitize_show_states( $input ) {
459        $current = array_filter(
460            array_intersect_key( (array) get_option( 'podcasting_show_states', array() ), self::SHOW_URL_HOSTS ),
461            static function ( $value ) {
462                return is_string( $value ) && '' !== $value;
463            }
464        );
465
466        if ( ! is_array( $input ) ) {
467            return $current;
468        }
469
470        foreach ( array_intersect_key( $input, self::SHOW_URL_HOSTS ) as $key => $value ) {
471            $value = is_string( $value ) ? trim( $value ) : '';
472
473            if ( '' === $value ) {
474                unset( $current[ $key ] );
475                continue;
476            }
477
478            if ( ! in_array( $value, array( 'pending', 'active' ), true ) ) {
479                continue;
480            }
481
482            if ( 'pending' === $value && isset( $current[ $key ] ) && 'active' === $current[ $key ] ) {
483                continue;
484            }
485
486            $current[ $key ] = $value;
487        }
488
489        return $current;
490    }
491
492    /**
493     * Validate a URL against the per-podcatcher hostname allowlist.
494     *
495     * @param string $key Podcatcher key.
496     * @param string $url Candidate URL.
497     * @return string|null Cleaned URL, or null if the host isn't in the allowlist.
498     */
499    private static function sanitize_show_url( $key, $url ) {
500        if ( ! isset( self::SHOW_URL_HOSTS[ $key ] ) ) {
501            return null;
502        }
503
504        if ( ! is_string( $url ) || strlen( $url ) > self::SHOW_URL_MAX_LENGTH ) {
505            return null;
506        }
507
508        $cleaned = esc_url_raw( $url, array( 'https' ) );
509        if ( '' === $cleaned ) {
510            return null;
511        }
512
513        if ( ! wp_http_validate_url( $cleaned ) ) {
514            return null;
515        }
516
517        $host = wp_parse_url( $cleaned, PHP_URL_HOST );
518        if ( ! is_string( $host ) || '' === $host ) {
519            return null;
520        }
521
522        $host = strtolower( $host );
523        if ( 0 === strpos( $host, 'www.' ) ) {
524            $host = substr( $host, 4 );
525        }
526
527        return in_array( $host, self::SHOW_URL_HOSTS[ $key ], true ) ? $cleaned : null;
528    }
529}