Completed
Push — jetpack/branch-9.4 ( 12b916...516efd )
by Jeremy
33:30 queued 21:54
created

Jetpack_Podcast_Helper::reset_simplepie_cache()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 1
dl 0
loc 9
rs 9.9666
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
	 * @param array $args {
35
	 *    Optional array of arguments.
36
	 *    @type string|int $guid  The ID of a specific episode to return rather than a list.
37
	 * }
38
	 *
39
	 * @return array|WP_Error  The player data or a error object.
40
	 */
41
	public function get_player_data( $args = array() ) {
42
		$guids = isset( $args['guids'] ) && $args['guids'] ? $args['guids'] : array();
43
44
		// Try loading data from the cache.
45
		$transient_key = 'jetpack_podcast_' . md5( $this->feed . implode( ',', $guids ) );
46
		$player_data   = get_transient( $transient_key );
47
48
		// Fetch data if we don't have any cached.
49
		if ( false === $player_data || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
50
			// Load feed.
51
			$rss = $this->load_feed();
52
53
			if ( is_wp_error( $rss ) ) {
54
				return $rss;
55
			}
56
57
			// Get a list of episodes by guid or all tracks in feed.
58
			if ( count( $guids ) ) {
59
				$tracks = array_map( array( $this, 'get_track_data' ), $guids );
60
				$tracks = array_filter(
61
					$tracks,
62
					function ( $track ) {
63
						return ! is_wp_error( $track );
64
					}
65
				);
66
			} else {
67
				$tracks = $this->get_track_list();
68
			}
69
70
			if ( empty( $tracks ) ) {
71
				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...
72
			}
73
74
			// Get podcast meta.
75
			$title = $rss->get_title();
76
			$title = $this->get_plain_text( $title );
77
78
			$cover = $rss->get_image_url();
79
			$cover = ! empty( $cover ) ? esc_url( $cover ) : null;
80
81
			$link = $rss->get_link();
82
			$link = ! empty( $link ) ? esc_url( $link ) : null;
83
84
			$player_data = array(
85
				'title'  => $title,
86
				'link'   => $link,
87
				'cover'  => $cover,
88
				'tracks' => $tracks,
89
			);
90
91
			// Cache for 1 hour.
92
			set_transient( $transient_key, $player_data, HOUR_IN_SECONDS );
93
		}
94
95
		return $player_data;
96
	}
97
98
	/**
99
	 * Gets a specific track from the supplied feed URL.
100
	 *
101
	 * @param string  $guid          The GUID of the track.
102
	 * @param boolean $force_refresh Clear the feed cache.
103
	 * @return array|WP_Error The track object or an error object.
104
	 */
105
	public function get_track_data( $guid, $force_refresh = false ) {
106
		// Get the cache key.
107
		$transient_key = 'jetpack_podcast_' . md5( "$this->feed::$guid" );
108
109
		// Clear the cache if force_refresh param is true.
110
		if ( true === $force_refresh ) {
111
			delete_transient( $transient_key );
112
		}
113
114
		// Try loading track data from the cache.
115
		$track_data = get_transient( $transient_key );
116
117
		// Fetch data if we don't have any cached.
118
		if ( false === $track_data || ( defined( 'WP_DEBUG' ) && WP_DEBUG ) ) {
119
			// Load feed.
120
			$rss = $this->load_feed( $force_refresh );
121
122
			if ( is_wp_error( $rss ) ) {
123
				return $rss;
124
			}
125
126
			// Loop over all tracks to find the one.
127
			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...
128
				if ( $guid === $track->get_id() ) {
129
					$track_data = $this->setup_tracks_callback( $track );
130
					break;
131
				}
132
			}
133
134
			if ( false === $track_data ) {
135
				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...
136
			}
137
138
			// Cache for 1 hour.
139
			set_transient( $transient_key, $track_data, HOUR_IN_SECONDS );
140
		}
141
142
		return $track_data;
143
	}
144
145
	/**
146
	 * Gets a list of tracks for the supplied RSS feed.
147
	 *
148
	 * @return array|WP_Error The feed's tracks or a error object.
149
	 */
150
	public function get_track_list() {
151
		$rss = $this->load_feed();
152
153
		if ( is_wp_error( $rss ) ) {
154
			return $rss;
155
		}
156
157
		// Get first ten items and format them.
158
		$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...
159
160
		// Filter out any tracks that are empty.
161
		// Reset the array indicies.
162
		return array_values( array_filter( $track_list ) );
163
	}
164
165
	/**
166
	 * Formats string as pure plaintext, with no HTML tags or entities present.
167
	 * This is ready to be used in React, innerText but needs to be escaped
168
	 * using standard `esc_html` when generating markup on server.
169
	 *
170
	 * @param string $str Input string.
171
	 * @return string Plain text string.
172
	 */
173
	protected function get_plain_text( $str ) {
174
		return $this->sanitize_and_decode_text( $str, true );
175
	}
176
177
	/**
178
	 * Formats strings as safe HTML.
179
	 *
180
	 * @param string $str Input string.
181
	 * @return string HTML text string safe for post_content.
182
	 */
183
	protected function get_html_text( $str ) {
184
		return $this->sanitize_and_decode_text( $str, false );
185
	}
186
187
	/**
188
	 * Strip unallowed html tags and decode entities.
189
	 *
190
	 * @param string  $str Input string.
191
	 * @param boolean $strip_all_tags Strip all tags, otherwise allow post_content safe tags.
192
	 * @return string Sanitized and decoded text.
193
	 */
194
	protected function sanitize_and_decode_text( $str, $strip_all_tags = true ) {
195
		// Trim string and return if empty.
196
		$str = trim( (string) $str );
197
		if ( empty( $str ) ) {
198
			return '';
199
		}
200
201
		if ( $strip_all_tags ) {
202
			// Make sure there are no tags.
203
			$str = wp_strip_all_tags( $str );
204
		} else {
205
			$str = wp_kses_post( $str );
206
		}
207
208
		// Replace all entities with their characters, including all types of quotes.
209
		$str = html_entity_decode( $str, ENT_QUOTES );
210
211
		return $str;
212
	}
213
214
	/**
215
	 * Loads an RSS feed using `fetch_feed`.
216
	 *
217
	 * @param boolean $force_refresh Clear the feed cache.
218
	 * @return SimplePie|WP_Error The RSS object or error.
219
	 */
220
	public function load_feed( $force_refresh = false ) {
221
		// Add action: clear the SimplePie Cache if $force_refresh param is true.
222
		if ( true === $force_refresh ) {
223
			add_action( 'wp_feed_options', array( __CLASS__, 'reset_simplepie_cache' ) );
224
		}
225
		// Add action: detect the podcast feed from the provided feed URL.
226
		add_action( 'wp_feed_options', array( __CLASS__, 'set_podcast_locator' ) );
227
228
		// Fetch the feed.
229
		$rss = fetch_feed( $this->feed );
230
231
		// Remove added actions from wp_feed_options hook.
232
		remove_action( 'wp_feed_options', array( __CLASS__, 'set_podcast_locator' ) );
233
		if ( true === $force_refresh ) {
234
			remove_action( 'wp_feed_options', array( __CLASS__, 'reset_simplepie_cache' ) );
235
		}
236
237
		if ( is_wp_error( $rss ) ) {
238
			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...
239
		}
240
241
		if ( ! $rss->get_item_quantity() ) {
242
			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...
243
		}
244
245
		return $rss;
246
	}
247
248
	/**
249
	 * Action handler to set our podcast specific feed locator class on the SimplePie object.
250
	 *
251
	 * @param SimplePie $feed The SimplePie object, passed by reference.
252
	 */
253
	public static function set_podcast_locator( &$feed ) {
254
		if ( ! class_exists( 'Jetpack_Podcast_Feed_Locator' ) ) {
255
			jetpack_require_lib( 'class-jetpack-podcast-feed-locator' );
256
		}
257
258
		$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...
259
	}
260
261
	/**
262
	 * Action handler to reset the SimplePie cache for the podcast feed.
263
	 *
264
	 * Note this only resets the cache for the specified url. If the feed locator finds the podcast feed
265
	 * within the markup of the that url, that feed itself may still be cached.
266
	 *
267
	 * @param SimplePie $feed The SimplePie object, passed by reference.
268
	 * @return void
269
	 */
270
	public static function reset_simplepie_cache( &$feed ) {
271
		// Retrieve the cache object for a feed url. Based on:
272
		// https://github.com/WordPress/WordPress/blob/fd1c2cb4011845ceb7244a062b09b2506082b1c9/wp-includes/class-simplepie.php#L1412.
273
		$cache = $feed->registry->call( 'Cache', 'get_handler', array( $feed->cache_location, call_user_func( $feed->cache_name_function, $feed->feed_url ), 'spc' ) );
0 ignored issues
show
Bug introduced by
The property registry does not seem to exist in SimplePie.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property cache_location does not seem to exist in SimplePie.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property cache_name_function does not seem to exist in SimplePie.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The property feed_url does not seem to exist in SimplePie.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
274
275
		if ( method_exists( $cache, 'unlink' ) ) {
276
			$cache->unlink();
277
		}
278
	}
279
280
	/**
281
	 * Prepares Episode data to be used by the Podcast Player block.
282
	 *
283
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
284
	 * @return array
285
	 */
286
	protected function setup_tracks_callback( SimplePie_Item $episode ) {
287
		$enclosure = $this->get_audio_enclosure( $episode );
288
289
		// If the audio enclosure is empty then it is not playable.
290
		// We therefore return an empty array for this track.
291
		// It will be filtered out later.
292
		if ( is_wp_error( $enclosure ) ) {
293
			return array();
294
		}
295
296
		// If there is no link return an empty array. We will filter out later.
297
		if ( empty( $enclosure->link ) ) {
298
			return array();
299
		}
300
301
		// Build track data.
302
		$track = array(
303
			'id'               => wp_unique_id( 'podcast-track-' ),
304
			'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...
305
			'src'              => esc_url( $enclosure->link ),
306
			'type'             => esc_attr( $enclosure->type ),
307
			'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...
308
			'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...
309
			'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...
310
			'image'            => esc_url( $this->get_episode_image_url( $episode ) ),
311
			'guid'             => $this->get_plain_text( $episode->get_id() ),
312
		);
313
314
		if ( empty( $track['title'] ) ) {
315
			$track['title'] = esc_html__( '(no title)', 'jetpack' );
316
		}
317
318
		if ( ! empty( $enclosure->duration ) ) {
319
			$track['duration'] = esc_html( $this->format_track_duration( $enclosure->duration ) );
320
		}
321
322
		return $track;
323
	}
324
325
	/**
326
	 * Retrieves an episode's image URL, if it's available.
327
	 *
328
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
329
	 * @param string         $itunes_ns The itunes namespace, defaulted to the standard 1.0 version.
330
	 * @return string|null The image URL or null if not found.
331
	 */
332
	protected function get_episode_image_url( SimplePie_Item $episode, $itunes_ns = 'http://www.itunes.com/dtds/podcast-1.0.dtd' ) {
333
		$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...
334
		if ( isset( $image[0]['attribs']['']['href'] ) ) {
335
			return $image[0]['attribs']['']['href'];
336
		}
337
		return null;
338
	}
339
340
	/**
341
	 * Retrieves an audio enclosure.
342
	 *
343
	 * @param SimplePie_Item $episode SimplePie_Item object, representing a podcast episode.
344
	 * @return SimplePie_Enclosure|null
345
	 */
346
	protected function get_audio_enclosure( SimplePie_Item $episode ) {
347
		foreach ( (array) $episode->get_enclosures() as $enclosure ) {
348
			if ( 0 === strpos( $enclosure->type, 'audio/' ) ) {
349
				return $enclosure;
350
			}
351
		}
352
353
		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...
354
	}
355
356
	/**
357
	 * Returns the track duration as a formatted string.
358
	 *
359
	 * @param number $duration of the track in seconds.
360
	 * @return string
361
	 */
362
	protected function format_track_duration( $duration ) {
363
		$format = $duration > HOUR_IN_SECONDS ? 'H:i:s' : 'i:s';
364
365
		return date_i18n( $format, $duration );
366
	}
367
368
	/**
369
	 * Gets podcast player data schema.
370
	 *
371
	 * Useful for json schema in REST API endpoints.
372
	 *
373
	 * @return array Player data json schema.
374
	 */
375
	public static function get_player_data_schema() {
376
		return array(
377
			'$schema'    => 'http://json-schema.org/draft-04/schema#',
378
			'title'      => 'jetpack-podcast-player-data',
379
			'type'       => 'object',
380
			'properties' => array(
381
				'title'  => array(
382
					'description' => __( 'The title of the podcast.', 'jetpack' ),
383
					'type'        => 'string',
384
				),
385
				'link'   => array(
386
					'description' => __( 'The URL of the podcast website.', 'jetpack' ),
387
					'type'        => 'string',
388
					'format'      => 'uri',
389
				),
390
				'cover'  => array(
391
					'description' => __( 'The URL of the podcast cover image.', 'jetpack' ),
392
					'type'        => 'string',
393
					'format'      => 'uri',
394
				),
395
				'tracks' => self::get_tracks_schema(),
396
			),
397
		);
398
	}
399
400
	/**
401
	 * Gets tracks data schema.
402
	 *
403
	 * Useful for json schema in REST API endpoints.
404
	 *
405
	 * @return array Tracks json schema.
406
	 */
407
	public static function get_tracks_schema() {
408
		return array(
409
			'description' => __( 'Latest episodes of the podcast.', 'jetpack' ),
410
			'type'        => 'array',
411
			'items'       => array(
412
				'type'       => 'object',
413
				'properties' => array(
414
					'id'               => array(
415
						'description' => __( 'The episode id. Generated per request, not globally unique.', 'jetpack' ),
416
						'type'        => 'string',
417
					),
418
					'link'             => array(
419
						'description' => __( 'The external link for the episode.', 'jetpack' ),
420
						'type'        => 'string',
421
						'format'      => 'uri',
422
					),
423
					'src'              => array(
424
						'description' => __( 'The audio file URL of the episode.', 'jetpack' ),
425
						'type'        => 'string',
426
						'format'      => 'uri',
427
					),
428
					'type'             => array(
429
						'description' => __( 'The mime type of the episode.', 'jetpack' ),
430
						'type'        => 'string',
431
					),
432
					'description'      => array(
433
						'description' => __( 'The episode description, in plaintext.', 'jetpack' ),
434
						'type'        => 'string',
435
					),
436
					'description_html' => array(
437
						'description' => __( 'The episode description with allowed html tags.', 'jetpack' ),
438
						'type'        => 'string',
439
					),
440
					'title'            => array(
441
						'description' => __( 'The episode title.', 'jetpack' ),
442
						'type'        => 'string',
443
					),
444
				),
445
			),
446
		);
447
	}
448
}
449