Jetpack_Media_Meta_Extractor::get_image_fields()   B
last analyzed

Complexity

Conditions 5
Paths 9

Size

Total Lines 41

Duplication

Lines 8
Ratio 19.51 %

Importance

Changes 0
Metric Value
cc 5
nc 9
nop 2
dl 8
loc 41
rs 8.9528
c 0
b 0
f 0
1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
/**
3
 * Class with methods to extract metadata from a post/page about videos, images, links, mentions embedded
4
 * in or attached to the post/page.
5
 *
6
 * @package automattic/jetpack
7
 */
8
9
/**
10
 * Class with methods to extract metadata from a post/page about videos, images, links, mentions embedded
11
 * in or attached to the post/page.
12
 *
13
 * @todo Additionally, have some filters on number of items in each field
14
 */
15
class Jetpack_Media_Meta_Extractor {
16
17
	// Some consts for what to extract.
18
	const ALL        = 255;
19
	const LINKS      = 1;
20
	const MENTIONS   = 2;
21
	const IMAGES     = 4;
22
	const SHORTCODES = 8; // Only the keeper shortcodes below.
23
	const EMBEDS     = 16;
24
	const HASHTAGS   = 32;
25
26
	/**
27
	 * Shortcodes to keep.
28
	 *
29
	 * For these, we try to extract some data from the shortcode, rather than just recording its presence (which we do for all)
30
	 * There should be a function get_{shortcode}_id( $atts ) or static method SomethingShortcode::get_{shortcode}_id( $atts ) for these.
31
	 *
32
	 * @var string[]
33
	 */
34
	private static $keeper_shortcodes = array(
35
		'youtube',
36
		'vimeo',
37
		'hulu',
38
		'ted',
39
		'wpvideo',
40
		'videopress',
41
	);
42
43
	/**
44
	 * Gets the specified media and meta info from the given post.
45
	 * NOTE: If you have the post's HTML content already and don't need image data, use extract_from_content() instead.
46
	 *
47
	 * @param int $blog_id The ID of the blog.
48
	 * @param int $post_id The ID of the post.
49
	 * @param int $what_to_extract A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS.
50
	 *
51
	 * @return array|WP_Error a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
52
	 */
53
	public static function extract( $blog_id, $post_id, $what_to_extract = self::ALL ) {
54
55
		// multisite?
56
		if ( function_exists( 'switch_to_blog' ) ) {
57
			switch_to_blog( $blog_id );
58
		}
59
60
		$post = get_post( $post_id );
61
		if ( ! $post instanceof WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
62
			if ( function_exists( 'restore_current_blog' ) ) {
63
				restore_current_blog();
64
			}
65
			return array();
66
		}
67
		$content  = $post->post_title . "\n\n" . $post->post_content;
68
		$char_cnt = strlen( $content );
69
70
		// prevent running extraction on really huge amounts of content.
71
		if ( $char_cnt > 100000 ) { // about 20k English words.
72
			$content = substr( $content, 0, 100000 );
73
		}
74
75
		$extracted = array();
76
77
		// Get images first, we need the full post for that.
78
		if ( self::IMAGES & $what_to_extract ) {
79
			$extracted = self::get_image_fields( $post );
80
81
			// Turn off images so we can safely call extract_from_content() below.
82
			$what_to_extract = $what_to_extract - self::IMAGES;
83
		}
84
85
		if ( function_exists( 'restore_current_blog' ) ) {
86
			restore_current_blog();
87
		}
88
89
		// All of the other things besides images can be extracted from just the content.
90
		$extracted = self::extract_from_content( $content, $what_to_extract, $extracted );
91
92
		return $extracted;
93
	}
94
95
	/**
96
	 * Gets the specified meta info from the given post content.
97
	 * NOTE: If you want IMAGES, call extract( $blog_id, $post_id, ...) which will give you more/better image extraction
98
	 * This method will give you an error if you ask for IMAGES.
99
	 *
100
	 * @param string $content The HTML post_content of a post.
101
	 * @param int    $what_to_extract A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS.
102
	 * @param array  $already_extracted Previously extracted things, e.g. images from extract(), which can be used for x-referencing here.
103
	 *
104
	 * @return array a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
105
	 */
106
	public static function extract_from_content( $content, $what_to_extract = self::ALL, $already_extracted = array() ) {
107
		$stripped_content = self::get_stripped_content( $content );
108
109
		// Maybe start with some previously extracted things (e.g. images from extract().
110
		$extracted = $already_extracted;
111
112
		// Embedded media objects will have already been converted to shortcodes by pre_kses hooks on save.
113
114
		if ( self::IMAGES & $what_to_extract ) {
115
			$images    = self::extract_images_from_content( $stripped_content, array() );
116
			$extracted = array_merge( $extracted, $images );
117
		}
118
119
		// ----------------------------------- MENTIONS ------------------------------
120
121 View Code Duplication
		if ( self::MENTIONS & $what_to_extract ) {
122
			if ( preg_match_all( '/(^|\s)@(\w+)/u', $stripped_content, $matches ) ) {
123
				$mentions             = array_values( array_unique( $matches[2] ) ); // array_unique() retains the keys!
124
				$mentions             = array_map( 'strtolower', $mentions );
125
				$extracted['mention'] = array( 'name' => $mentions );
126
				if ( ! isset( $extracted['has'] ) ) {
127
					$extracted['has'] = array();
128
				}
129
				$extracted['has']['mention'] = count( $mentions );
130
			}
131
		}
132
133
		// ----------------------------------- HASHTAGS ------------------------------
134
		/**
135
		 * Some hosts may not compile with --enable-unicode-properties and kick a warning:
136
		 * Warning: preg_match_all() [function.preg-match-all]: Compilation failed: support for \P, \p, and \X has not been compiled
137
		 * Therefore, we only run this code block on wpcom, not in Jetpack.
138
		 */
139
		if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) && ( self::HASHTAGS & $what_to_extract ) ) {
140
			// This regex does not exactly match Twitter's
141
			// if there are problems/complaints we should implement this:
142
			// https://github.com/twitter/twitter-text/blob/master/java/src/com/twitter/Regex.java .
143 View Code Duplication
			if ( preg_match_all( '/(?:^|\s)#(\w*\p{L}+\w*)/u', $stripped_content, $matches ) ) {
144
				$hashtags             = array_values( array_unique( $matches[1] ) ); // array_unique() retains the keys!
145
				$hashtags             = array_map( 'strtolower', $hashtags );
146
				$extracted['hashtag'] = array( 'name' => $hashtags );
147
				if ( ! isset( $extracted['has'] ) ) {
148
					$extracted['has'] = array();
149
				}
150
				$extracted['has']['hashtag'] = count( $hashtags );
151
			}
152
		}
153
154
		// ----------------------------------- SHORTCODES ------------------------------
155
156
		// Always look for shortcodes.
157
		// If we don't want them, we'll just remove them, so we don't grab them as links below.
158
		$shortcode_pattern = '/' . get_shortcode_regex() . '/s';
159
		if ( preg_match_all( $shortcode_pattern, $content, $matches ) ) {
160
161
			$shortcode_total_count = 0;
162
			$shortcode_type_counts = array();
163
			$shortcode_types       = array();
164
			$shortcode_details     = array();
165
166
			if ( self::SHORTCODES & $what_to_extract ) {
167
168
				foreach ( $matches[2] as $key => $shortcode ) {
169
					// Elasticsearch (and probably other things) doesn't deal well with some chars as key names.
170
					$shortcode_name = preg_replace( '/[.,*"\'\/\\\\#+ ]/', '_', $shortcode );
171
172
					$attr = shortcode_parse_atts( $matches[3][ $key ] );
173
174
					$shortcode_total_count++;
175
					if ( ! isset( $shortcode_type_counts[ $shortcode_name ] ) ) {
176
						$shortcode_type_counts[ $shortcode_name ] = 0;
177
					}
178
					$shortcode_type_counts[ $shortcode_name ]++;
179
180
					// Store (uniquely) presence of all shortcode regardless of whether it's a keeper (for those, get ID below)
181
					// @todo Store number of occurrences?
182
					if ( ! in_array( $shortcode_name, $shortcode_types, true ) ) {
183
						$shortcode_types[] = $shortcode_name;
184
					}
185
186
					// For keeper shortcodes, also store the id/url of the object (e.g. youtube video, TED talk, etc.).
187
					if ( in_array( $shortcode, self::$keeper_shortcodes, true ) ) {
188
						// Clear shortcode ID data left from the last shortcode.
189
						$id = null;
190
						// We'll try to get the salient ID from the function jetpack_shortcode_get_xyz_id().
191
						// If the shortcode is a class, we'll call XyzShortcode::get_xyz_id().
192
						$shortcode_get_id_func   = "jetpack_shortcode_get_{$shortcode}_id";
193
						$shortcode_class_name    = ucfirst( $shortcode ) . 'Shortcode';
194
						$shortcode_get_id_method = "get_{$shortcode}_id";
195
						if ( function_exists( $shortcode_get_id_func ) ) {
196
							$id = call_user_func( $shortcode_get_id_func, $attr );
197
						} elseif ( method_exists( $shortcode_class_name, $shortcode_get_id_method ) ) {
198
							$id = call_user_func( array( $shortcode_class_name, $shortcode_get_id_method ), $attr );
199
						}
200
						if ( ! empty( $id )
201
							&& ( ! isset( $shortcode_details[ $shortcode_name ] ) || ! in_array( $id, $shortcode_details[ $shortcode_name ], true ) ) ) {
202
							$shortcode_details[ $shortcode_name ][] = $id;
203
						}
204
					}
205
				}
206
207
				if ( $shortcode_total_count > 0 ) {
208
					// Add the shortcode info to the $extracted array.
209
					if ( ! isset( $extracted['has'] ) ) {
210
						$extracted['has'] = array();
211
					}
212
					$extracted['has']['shortcode'] = $shortcode_total_count;
213
					$extracted['shortcode']        = array();
214
					foreach ( $shortcode_type_counts as $type => $count ) {
215
						$extracted['shortcode'][ $type ] = array( 'count' => $count );
216
					}
217
					if ( ! empty( $shortcode_types ) ) {
218
						$extracted['shortcode_types'] = $shortcode_types;
219
					}
220
					foreach ( $shortcode_details as $type => $id ) {
221
						$extracted['shortcode'][ $type ]['id'] = $id;
222
					}
223
				}
224
			}
225
226
			// Remove the shortcodes form our copy of $content, so we don't count links in them as links below.
227
			$content = preg_replace( $shortcode_pattern, ' ', $content );
228
		}
229
230
		// ----------------------------------- LINKS ------------------------------
231
232
		if ( self::LINKS & $what_to_extract ) {
233
234
			// To hold the extracted stuff we find.
235
			$links = array();
236
237
			// @todo Get the text inside the links?
238
239
			// Grab any links, whether in <a href="..." or not, but subtract those from shortcodes and images.
240
			// (we treat embed links as just another link).
241
			if ( preg_match_all( '#(?:^|\s|"|\')(https?://([^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))))#', $content, $matches ) ) {
242
243
				foreach ( $matches[1] as $link_raw ) {
244
					$url = wp_parse_url( $link_raw );
245
246
					// Data URI links.
247
					if ( ! isset( $url['scheme'] ) || 'data' === $url['scheme'] ) {
248
						continue;
249
					}
250
251
					// Reject invalid URLs.
252
					if ( ! isset( $url['host'] ) ) {
253
						continue;
254
					}
255
256
					// Remove large (and likely invalid) links.
257
					if ( 4096 < strlen( $link_raw ) ) {
258
						continue;
259
					}
260
261
					// Build a simple form of the URL so we can compare it to ones we found in IMAGES or SHORTCODES and exclude those.
262
					$simple_url = $url['scheme'] . '://' . $url['host'] . ( ! empty( $url['path'] ) ? $url['path'] : '' );
263
					if ( isset( $extracted['image']['url'] ) ) {
264
						if ( in_array( $simple_url, (array) $extracted['image']['url'], true ) ) {
265
							continue;
266
						}
267
					}
268
269
					list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
270
271
					// Build a reversed hostname.
272
					$host_parts    = array_reverse( explode( '.', $url['host'] ) );
273
					$host_reversed = '';
274
					foreach ( $host_parts as $part ) {
275
						$host_reversed .= ( ! empty( $host_reversed ) ? '.' : '' ) . $part;
276
					}
277
278
					$link_analyzed = '';
279
					if ( ! empty( $url['path'] ) ) {
280
						// The whole path (no query args or fragments).
281
						$path           = substr( $url['path'], 1 ); // strip the leading '/'.
282
						$link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $path;
283
284
						// The path split by /.
285
						$path_split = explode( '/', $path );
286
						if ( count( $path_split ) > 1 ) {
287
							$link_analyzed .= ' ' . implode( ' ', $path_split );
288
						}
289
290
						// The fragment.
291
						if ( ! empty( $url['fragment'] ) ) {
292
							$link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $url['fragment'];
293
						}
294
					}
295
296
					// @todo Check unique before adding
297
					$links[] = array(
298
						'url'           => $link_all_but_proto,
299
						'host_reversed' => $host_reversed,
300
						'host'          => $url['host'],
301
					);
302
				}
303
			}
304
305
			$link_count = count( $links );
306
			if ( $link_count ) {
307
				$extracted['link'] = $links;
308
				if ( ! isset( $extracted['has'] ) ) {
309
					$extracted['has'] = array();
310
				}
311
				$extracted['has']['link'] = $link_count;
312
			}
313
		}
314
315
		// ----------------------------------- EMBEDS ------------------------------
316
317
		// Embeds are just individual links on their own line.
318
		if ( self::EMBEDS & $what_to_extract ) {
319
320
			if ( ! function_exists( '_wp_oembed_get_object' ) ) {
321
				include ABSPATH . WPINC . '/class-oembed.php';
322
			}
323
324
			// get an oembed object.
325
			$oembed = _wp_oembed_get_object();
326
327
			// Grab any links on their own lines that may be embeds.
328
			if ( preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $content, $matches ) ) {
329
330
				// To hold the extracted stuff we find.
331
				$embeds = array();
332
333
				foreach ( $matches[1] as $link_raw ) {
334
					$url = wp_parse_url( $link_raw );
0 ignored issues
show
Unused Code introduced by
$url is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
335
336
					list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
0 ignored issues
show
Unused Code introduced by
The assignment to $proto is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
337
338
					// Check whether this "link" is really an embed.
339
					foreach ( $oembed->providers as $matchmask => $data ) {
340
						list( $providerurl, $regex ) = $data; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
0 ignored issues
show
Unused Code introduced by
The assignment to $providerurl is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
341
342
						// Turn the asterisk-type provider URLs into regex.
343
						if ( ! $regex ) {
344
							$matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
345
							$matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
346
						}
347
348
						if ( preg_match( $matchmask, $link_raw ) ) {
349
							$embeds[] = $link_all_but_proto; // @todo Check unique before adding
350
351
							// @todo Try to get ID's for the ones we care about (shortcode_keepers)
352
							break;
353
						}
354
					}
355
				}
356
357
				if ( ! empty( $embeds ) ) {
358
					if ( ! isset( $extracted['has'] ) ) {
359
						$extracted['has'] = array();
360
					}
361
					$extracted['has']['embed'] = count( $embeds );
362
					$extracted['embed']        = array( 'url' => array() );
363
					foreach ( $embeds as $e ) {
364
						$extracted['embed']['url'][] = $e;
365
					}
366
				}
367
			}
368
		}
369
370
		return $extracted;
371
	}
372
373
	/**
374
	 * Get image fields for matching images.
375
	 *
376
	 * @uses Jetpack_PostImages
377
	 *
378
	 * @param WP_Post $post A post object.
379
	 * @param array   $args Optional args, see defaults list for details.
380
	 *
381
	 * @return array Returns an array of all images meeting the specified criteria in $args.
382
	 */
383
	private static function get_image_fields( $post, $args = array() ) {
384
385
		if ( ! $post instanceof WP_Post ) {
0 ignored issues
show
Bug introduced by
The class WP_Post does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
386
			return array();
387
		}
388
389
		$defaults = array(
390
			'width'  => 200, // Required minimum width (if possible to determine).
391
			'height' => 200, // Required minimum height (if possible to determine).
392
		);
393
394
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,integer,{"w...r","height":"integer"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
395
396
		$image_list                = array();
397
		$image_booleans            = array();
398
		$image_booleans['gallery'] = 0;
399
400
		$from_featured_image = Jetpack_PostImages::from_thumbnail( $post->ID, $args['width'], $args['height'] );
401 View Code Duplication
		if ( ! empty( $from_featured_image ) ) {
402
			$srcs       = wp_list_pluck( $from_featured_image, 'src' );
403
			$image_list = array_merge( $image_list, $srcs );
404
		}
405
406
		$from_slideshow = Jetpack_PostImages::from_slideshow( $post->ID, $args['width'], $args['height'] );
407 View Code Duplication
		if ( ! empty( $from_slideshow ) ) {
408
			$srcs       = wp_list_pluck( $from_slideshow, 'src' );
409
			$image_list = array_merge( $image_list, $srcs );
410
		}
411
412
		$from_gallery = Jetpack_PostImages::from_gallery( $post->ID );
413
		if ( ! empty( $from_gallery ) ) {
414
			$srcs       = wp_list_pluck( $from_gallery, 'src' );
415
			$image_list = array_merge( $image_list, $srcs );
416
			$image_booleans['gallery']++; // @todo This count isn't correct, will only every count 1
417
		}
418
419
		// @todo Can we check width/height of these efficiently?  Could maybe use query args at least, before we strip them out
420
		$image_list = self::get_images_from_html( $post->post_content, $image_list );
421
422
		return self::build_image_struct( $image_list, $image_booleans );
423
	}
424
425
	/**
426
	 * Helper function to get images from HTML and return it with the set sturcture.
427
	 *
428
	 * @param string $content HTML content.
429
	 * @param array  $image_list Array of already found images.
430
	 *
431
	 * @return array|array[] Array of images.
432
	 */
433
	public static function extract_images_from_content( $content, $image_list ) {
434
		$image_list = self::get_images_from_html( $content, $image_list );
435
		return self::build_image_struct( $image_list, array() );
436
	}
437
438
	/**
439
	 * Produces a set structure for extracted media items.
440
	 *
441
	 * @param array $image_list Array of images.
442
	 * @param array $image_booleans Image booleans.
443
	 *
444
	 * @return array|array[]
445
	 */
446
	public static function build_image_struct( $image_list, $image_booleans ) {
447
		if ( ! empty( $image_list ) ) {
448
			$retval     = array( 'image' => array() );
449
			$image_list = array_unique( $image_list );
450
			foreach ( $image_list as $img ) {
451
				$retval['image'][] = array( 'url' => $img );
452
			}
453
			$image_booleans['image'] = count( $retval['image'] );
454
			if ( ! empty( $image_booleans ) ) {
455
				$retval['has'] = $image_booleans;
456
			}
457
			return $retval;
458
		} else {
459
			return array();
460
		}
461
	}
462
463
	/**
464
	 * Extracts images from html.
465
	 *
466
	 * @param string $html Some markup, possibly containing image tags.
467
	 * @param array  $images_already_extracted (just an array of image URLs without query strings, no special structure), used for de-duplication.
468
	 *
469
	 * @return array Image URLs extracted from the HTML, stripped of query params and de-duped
470
	 */
471
	public static function get_images_from_html( $html, $images_already_extracted ) {
472
		$image_list = $images_already_extracted;
473
		$from_html  = Jetpack_PostImages::from_html( $html );
474
		if ( ! empty( $from_html ) ) {
475
			$srcs = wp_list_pluck( $from_html, 'src' );
476
			foreach ( $srcs as $image_url ) {
477
				$length = strpos( $image_url, '?' );
478
				$src    = wp_parse_url( $image_url );
479
480
				if ( $src && isset( $src['scheme'], $src['host'], $src['path'] ) ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $src of type string|false is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
481
					// Rebuild the URL without the query string.
482
					$queryless = $src['scheme'] . '://' . $src['host'] . $src['path'];
483
				} elseif ( $length ) {
484
					// If wp_parse_url() didn't work, strip off the query string the old fashioned way.
485
					$queryless = substr( $image_url, 0, $length );
486
				} else {
487
					// Failing that, there was no spoon! Err ... query string!
488
					$queryless = $image_url;
489
				}
490
491
				// Discard URLs that are longer then 4KB, these are likely data URIs or malformed HTML.
492
				if ( 4096 < strlen( $queryless ) ) {
493
					continue;
494
				}
495
496
				if ( ! in_array( $queryless, $image_list, true ) ) {
497
					$image_list[] = $queryless;
498
				}
499
			}
500
		}
501
		return $image_list;
502
	}
503
504
	/**
505
	 * Strips concents of all tags, shortcodes, and decodes HTML entities.
506
	 *
507
	 * @param string $content Original content.
508
	 *
509
	 * @return string Cleaned content.
510
	 */
511
	private static function get_stripped_content( $content ) {
512
		$clean_content = wp_strip_all_tags( $content );
513
		$clean_content = html_entity_decode( $clean_content );
514
		// completely strip shortcodes and any content they enclose.
515
		$clean_content = strip_shortcodes( $clean_content );
516
		return $clean_content;
517
	}
518
}
519