Completed
Push — update/anchor.fm--episode-summ... ( 6f2b2f )
by
unknown
225:19 queued 216:25
created

Jetpack_Podcast_Helper::sanitize_and_decode_text()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php
2
/**
3
 * Helper to massage Podcast data to be used in the Podcast block.
4
 *
5
 * @package jetpack
6
 */
7
8
/**
9
 * Class Jetpack_Podcast_Helper
10
 */
11
class Jetpack_Podcast_Helper {
12
	/**
13
	 * The RSS feed of the podcast.
14
	 *
15
	 * @var string
16
	 */
17
	protected $feed = null;
18
19
	/**
20
	 * Initialize class.
21
	 *
22
	 * @param string $feed The RSS feed of the podcast.
23
	 */
24
	public function __construct( $feed ) {
25
		$this->feed = esc_url_raw( $feed );
26
	}
27
28
	/**
29
	 * Gets podcast data formatted to be used by the Podcast Player block in both server-side
30
	 * block rendering and in API `WPCOM_REST_API_V2_Endpoint_Podcast_Player`.
31
	 *
32
	 * The result is cached for one hour.
33
	 *
34
	 * @return array|WP_Error  The player data or a error object.
35
	 */
36
	public function get_player_data() {
37
		// Try loading data from the cache.
38
		$transient_key = 'jetpack_podcast_' . md5( $this->feed );
39
		$player_data   = get_transient( $transient_key );
40
41
		// Fetch data if we don't have any cached.
42
		if ( false === $player_data || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
43
			// Load feed.
44
			$rss = $this->load_feed();
45
46
			if ( is_wp_error( $rss ) ) {
47
				return $rss;
48
			}
49
50
			// Get tracks.
51
			$tracks = $this->get_track_list();
52
53
			if ( empty( $tracks ) ) {
54
				return new WP_Error( 'no_tracks', __( 'Your Podcast couldn\'t be embedded as it doesn\'t contain any tracks. Please double check your URL.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_tracks'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
55
			}
56
57
			// Get podcast meta.
58
			$title = $rss->get_title();
59
			$title = $this->get_plain_text( $title );
60
61
			$cover = $rss->get_image_url();
62
			$cover = ! empty( $cover ) ? esc_url( $cover ) : null;
63
64
			$link = $rss->get_link();
65
			$link = ! empty( $link ) ? esc_url( $link ) : null;
66
67
			$player_data = array(
68
				'title'  => $title,
69
				'link'   => $link,
70
				'cover'  => $cover,
71
				'tracks' => $tracks,
72
			);
73
74
			// Cache for 1 hour.
75
			set_transient( $transient_key, $player_data, HOUR_IN_SECONDS );
76
		}
77
78
		return $player_data;
79
	}
80
81
	/**
82
	 * Gets a specific track from the supplied feed URL.
83
	 *
84
	 * @param string $guid     The GUID of the track.
85
	 * @return array|WP_Error  The track object or an error object.
86
	 */
87
	public function get_track_data( $guid ) {
88
		// Try loading track data from the cache.
89
		$transient_key = 'jetpack_podcast_' . md5( "$this->feed::$guid" );
90
		$track_data    = get_transient( $transient_key );
91
92
		// Fetch data if we don't have any cached.
93
		if ( false === $track_data || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
94
			// Load feed.
95
			$rss = $this->load_feed();
96
97
			if ( is_wp_error( $rss ) ) {
98
				return $rss;
99
			}
100
101
			// Loop over all tracks to find the one.
102
			foreach ( $rss->get_items() as $track ) {
0 ignored issues
show
Bug introduced by
The method get_items does only exist in SimplePie, but not in WP_Error.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
103
				if ( $guid === $track->get_id() ) {
104
					$track_data = $this->setup_tracks_callback( $track );
105
					break;
106
				}
107
			}
108
109
			if ( false === $track_data ) {
110
				return new WP_Error( 'no_track', __( 'The track was not found.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_track'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
111
			}
112
113
			// Cache for 1 hour.
114
			set_transient( $transient_key, $track_data, HOUR_IN_SECONDS );
115
		}
116
117
		return $track_data;
118
	}
119
120
	/**
121
	 * Gets a list of tracks for the supplied RSS feed.
122
	 *
123
	 * @return array|WP_Error The feed's tracks or a error object.
124
	 */
125
	public function get_track_list() {
126
		$rss = $this->load_feed();
127
128
		if ( is_wp_error( $rss ) ) {
129
			return $rss;
130
		}
131
132
		// Get first ten items and format them.
133
		$track_list = array_map( array( __CLASS__, 'setup_tracks_callback' ), $rss->get_items( 0, 10 ) );
0 ignored issues
show
Unused Code introduced by
The call to SimplePie::get_items() has too many arguments starting with 0.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Bug introduced by
The method get_items does only exist in SimplePie, but not in WP_Error.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
134
135
		// Filter out any tracks that are empty.
136
		// Reset the array indicies.
137
		return array_values( array_filter( $track_list ) );
138
	}
139
140
	/**
141
	 * Formats string as pure plaintext, with no HTML tags or entities present.
142
	 * This is ready to be used in React, innerText but needs to be escaped
143
	 * using standard `esc_html` when generating markup on server.
144
	 *
145
	 * @param string $str Input string.
146
	 * @return string Plain text string.
147
	 */
148
	protected function get_plain_text( $str ) {
149
		return $this->sanitize_and_decode_text( $str, true );
150
	}
151
152
	/**
153
	 * Formats strings as safe HTML.
154
	 *
155
	 * @param string $str Input string.
156
	 * @return string HTML text string safe for post_content.
157
	 */
158
	protected function get_html_text( $str ) {
159
		return $this->sanitize_and_decode_text( $str, false );
160
	}
161
162
	/**
163
	 * Strip unallowed html tags and decode entities.
164
	 *
165
	 * @param string  $str Input string.
166
	 * @param boolean $strip_all_tags Strip all tags, otherwise allow post_content safe tags.
167
	 * @return string Sanitized and decoded text.
168
	 */
169
	protected function sanitize_and_decode_text( $str, $strip_all_tags = true ) {
170
		// Trim string and return if empty.
171
		$str = trim( (string) $str );
172
		if ( empty( $str ) ) {
173
			return '';
174
		}
175
176
		if ( $strip_all_tags ) {
177
			// Make sure there are no tags.
178
			$str = wp_strip_all_tags( $str );
179
		} else {
180
			$str = wp_kses_post( $str );
181
		}
182
183
		// Replace all entities with their characters, including all types of quotes.
184
		$str = html_entity_decode( $str, ENT_QUOTES );
185
186
		return $str;
187
	}
188
189
	/**
190
	 * Loads an RSS feed using `fetch_feed`.
191
	 *
192
	 * @return SimplePie|WP_Error The RSS object or error.
193
	 */
194
	public function load_feed() {
195
		add_action( 'wp_feed_options', array( __CLASS__, 'set_podcast_locator' ) );
196
		$rss = fetch_feed( $this->feed );
197
		remove_action( 'wp_feed_options', array( __CLASS__, 'set_podcast_locator' ) );
198
		if ( is_wp_error( $rss ) ) {
199
			return new WP_Error( 'invalid_url', __( 'Your podcast couldn\'t be embedded. Please double check your URL.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_url'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
200
		}
201
202
		if ( ! $rss->get_item_quantity() ) {
203
			return new WP_Error( 'no_tracks', __( 'Podcast audio RSS feed has no tracks.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'no_tracks'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
204
		}
205
206
		return $rss;
207
	}
208
209
	/**
210
	 * Action handler to set our podcast specific feed locator class on the SimplePie object.
211
	 *
212
	 * @param SimplePie $feed The SimplePie object, passed by reference.
213
	 */
214
	public static function set_podcast_locator( &$feed ) {
215
		if ( ! class_exists( 'Jetpack_Podcast_Feed_Locator' ) ) {
216
			jetpack_require_lib( 'class-jetpack-podcast-feed-locator' );
217
		}
218
219
		$feed->set_locator_class( 'Jetpack_Podcast_Feed_Locator' );
0 ignored issues
show
Bug introduced by
The method set_locator_class() does not seem to exist on object<SimplePie>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
220
	}
221
222
	/**
223
	 * Prepares Episode data to be used by the Podcast Player block.
224
	 *
225
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
226
	 * @return array
227
	 */
228
	protected function setup_tracks_callback( SimplePie_Item $episode ) {
229
		$enclosure = $this->get_audio_enclosure( $episode );
230
231
		// If the audio enclosure is empty then it is not playable.
232
		// We therefore return an empty array for this track.
233
		// It will be filtered out later.
234
		if ( is_wp_error( $enclosure ) ) {
235
			return array();
236
		}
237
238
		// If there is no link return an empty array. We will filter out later.
239
		if ( empty( $enclosure->link ) ) {
240
			return array();
241
		}
242
243
		// Build track data.
244
		$track = array(
245
			'id'               => wp_unique_id( 'podcast-track-' ),
246
			'link'             => esc_url( $episode->get_link() ),
0 ignored issues
show
Bug introduced by
The method get_link() does not seem to exist on object<SimplePie_Item>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
247
			'src'              => esc_url( $enclosure->link ),
248
			'type'             => esc_attr( $enclosure->type ),
249
			'description'      => $this->get_plain_text( $episode->get_description() ),
0 ignored issues
show
Bug introduced by
The method get_description() does not seem to exist on object<SimplePie_Item>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
250
			'description_html' => $this->get_html_text( $episode->get_description() ),
0 ignored issues
show
Bug introduced by
The method get_description() does not seem to exist on object<SimplePie_Item>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
251
			'title'            => $this->get_plain_text( $episode->get_title() ),
0 ignored issues
show
Bug introduced by
The method get_title() does not seem to exist on object<SimplePie_Item>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
252
			'image'            => esc_url( $this->get_episode_image_url( $episode ) ),
253
			'guid'             => $this->get_plain_text( $episode->get_id() ),
254
		);
255
256
		if ( empty( $track['title'] ) ) {
257
			$track['title'] = esc_html__( '(no title)', 'jetpack' );
258
		}
259
260
		if ( ! empty( $enclosure->duration ) ) {
261
			$track['duration'] = esc_html( $this->format_track_duration( $enclosure->duration ) );
262
		}
263
264
		return $track;
265
	}
266
267
	/**
268
	 * Retrieves an episode's image URL, if it's available.
269
	 *
270
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
271
	 * @param string         $itunes_ns The itunes namespace, defaulted to the standard 1.0 version.
272
	 * @return string|null The image URL or null if not found.
273
	 */
274
	protected function get_episode_image_url( SimplePie_Item $episode, $itunes_ns = 'http://www.itunes.com/dtds/podcast-1.0.dtd' ) {
275
		$image = $episode->get_item_tags( $itunes_ns, 'image' );
0 ignored issues
show
Bug introduced by
The method get_item_tags() does not seem to exist on object<SimplePie_Item>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
276
		if ( isset( $image[0]['attribs']['']['href'] ) ) {
277
			return $image[0]['attribs']['']['href'];
278
		}
279
		return null;
280
	}
281
282
	/**
283
	 * Retrieves an audio enclosure.
284
	 *
285
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
286
	 * @return SimplePie_Enclosure|null
287
	 */
288
	protected function get_audio_enclosure( SimplePie_Item $episode ) {
289
		foreach ( (array) $episode->get_enclosures() as $enclosure ) {
290
			if ( 0 === strpos( $enclosure->type, 'audio/' ) ) {
291
				return $enclosure;
292
			}
293
		}
294
295
		return new WP_Error( 'invalid_audio', __( 'Podcast audio is an invalid type.', 'jetpack' ) );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_audio'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
296
	}
297
298
	/**
299
	 * Returns the track duration as a formatted string.
300
	 *
301
	 * @param number $duration of the track in seconds.
302
	 * @return string
303
	 */
304
	protected function format_track_duration( $duration ) {
305
		$format = $duration > HOUR_IN_SECONDS ? 'H:i:s' : 'i:s';
306
307
		return date_i18n( $format, $duration );
308
	}
309
310
	/**
311
	 * Gets podcast player data schema.
312
	 *
313
	 * Useful for json schema in REST API endpoints.
314
	 *
315
	 * @return array Player data json schema.
316
	 */
317
	public static function get_player_data_schema() {
318
		return array(
319
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
320
			'title'      => 'jetpack-podcast-player-data',
321
			'type'       => 'object',
322
			'properties' => array(
323
				'title'  => array(
324
					'description' => __( 'The title of the podcast.', 'jetpack' ),
325
					'type'        => 'string',
326
				),
327
				'link'   => array(
328
					'description' => __( 'The URL of the podcast website.', 'jetpack' ),
329
					'type'        => 'string',
330
					'format'      => 'uri',
331
				),
332
				'cover'  => array(
333
					'description' => __( 'The URL of the podcast cover image.', 'jetpack' ),
334
					'type'        => 'string',
335
					'format'      => 'uri',
336
				),
337
				'tracks' => self::get_tracks_schema(),
338
			),
339
		);
340
	}
341
342
	/**
343
	 * Gets tracks data schema.
344
	 *
345
	 * Useful for json schema in REST API endpoints.
346
	 *
347
	 * @return array Tracks json schema.
348
	 */
349
	public static function get_tracks_schema() {
350
		return array(
351
			'description' => __( 'Latest episodes of the podcast.', 'jetpack' ),
352
			'type'        => 'array',
353
			'items'       => array(
354
				'type'       => 'object',
355
				'properties' => array(
356
					'id'               => array(
357
						'description' => __( 'The episode id. Generated per request, not globally unique.', 'jetpack' ),
358
						'type'        => 'string',
359
					),
360
					'link'             => array(
361
						'description' => __( 'The external link for the episode.', 'jetpack' ),
362
						'type'        => 'string',
363
						'format'      => 'uri',
364
					),
365
					'src'              => array(
366
						'description' => __( 'The audio file URL of the episode.', 'jetpack' ),
367
						'type'        => 'string',
368
						'format'      => 'uri',
369
					),
370
					'type'             => array(
371
						'description' => __( 'The mime type of the episode.', 'jetpack' ),
372
						'type'        => 'string',
373
					),
374
					'description'      => array(
375
						'description' => __( 'The episode description, in plaintext.', 'jetpack' ),
376
						'type'        => 'string',
377
					),
378
					'description_html' => array(
379
						'description' => __( 'The episode description, with allowed html tags.', 'jetpack' ),
380
						'type'        => 'string',
381
					),
382
					'title'            => array(
383
						'description' => __( 'The episode title.', 'jetpack' ),
384
						'type'        => 'string',
385
					),
386
				),
387
			),
388
		);
389
	}
390
}
391