Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
85.60% covered (warning)
85.60%
214 / 250
37.50% covered (danger)
37.50%
3 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Jetpack_Media_Meta_Extractor
85.60% covered (warning)
85.60%
214 / 250
37.50% covered (danger)
37.50%
3 / 8
137.92
0.00% covered (danger)
0.00%
0 / 1
 extract
78.95% covered (warning)
78.95%
15 / 19
0.00% covered (danger)
0.00%
0 / 1
7.46
 extract_from_content
86.43% covered (warning)
86.43%
121 / 140
0.00% covered (danger)
0.00%
0 / 1
74.24
 get_image_fields
70.97% covered (warning)
70.97%
22 / 31
0.00% covered (danger)
0.00%
0 / 1
9.57
 reduce_extracted_images
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
6.09
 extract_images_from_content
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 build_image_struct
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
4
 get_images_from_html
92.86% covered (success)
92.86%
26 / 28
0.00% covered (danger)
0.00%
0 / 1
14.07
 get_stripped_content
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
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
9use Automattic\Jetpack\Post_Media\Images;
10
11/**
12 * Class with methods to extract metadata from a post/page about videos, images, links, mentions embedded
13 * in or attached to the post/page.
14 *
15 * @todo Additionally, have some filters on number of items in each field
16 */
17class Jetpack_Media_Meta_Extractor {
18
19    // Some consts for what to extract.
20    const ALL        = 255;
21    const LINKS      = 1;
22    const MENTIONS   = 2;
23    const IMAGES     = 4;
24    const SHORTCODES = 8; // Only the keeper shortcodes below.
25    const EMBEDS     = 16;
26    const HASHTAGS   = 32;
27
28    /**
29     * Shortcodes to keep.
30     *
31     * For these, we try to extract some data from the shortcode, rather than just recording its presence (which we do for all)
32     * There should be a function get_{shortcode}_id( $atts ) or static method SomethingShortcode::get_{shortcode}_id( $atts ) for these.
33     *
34     * @var string[]
35     */
36    private static $keeper_shortcodes = array(
37        'audio',
38        'youtube',
39        'vimeo',
40        'hulu',
41        'ted',
42        'video',
43        'wpvideo',
44        'videopress',
45    );
46
47    /**
48     * Gets the specified media and meta info from the given post.
49     * NOTE: If you have the post's HTML content already and don't need image data, use extract_from_content() instead.
50     *
51     * @param int     $blog_id The ID of the blog.
52     * @param int     $post_id The ID of the post.
53     * @param int     $what_to_extract A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS.
54     * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
55     *
56     * @return array|WP_Error a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
57     */
58    public static function extract( $blog_id, $post_id, $what_to_extract = self::ALL, $extract_alt_text = false ) {
59
60        // multisite?
61        if ( function_exists( 'switch_to_blog' ) ) {
62            switch_to_blog( $blog_id );
63        }
64
65        $post = get_post( $post_id );
66        if ( ! $post instanceof WP_Post ) {
67            if ( function_exists( 'restore_current_blog' ) ) {
68                restore_current_blog();
69            }
70            return array();
71        }
72        $content  = $post->post_title . "\n\n" . $post->post_content;
73        $char_cnt = strlen( $content );
74
75        // prevent running extraction on really huge amounts of content.
76        if ( $char_cnt > 100000 ) { // about 20k English words.
77            $content = substr( $content, 0, 100000 );
78        }
79
80        $extracted = array();
81
82        // Get images first, we need the full post for that.
83        if ( self::IMAGES & $what_to_extract ) {
84            $extracted = self::get_image_fields( $post, array(), $extract_alt_text );
85
86            // Turn off images so we can safely call extract_from_content() below.
87            $what_to_extract -= self::IMAGES;
88        }
89
90        if ( function_exists( 'restore_current_blog' ) ) {
91            restore_current_blog();
92        }
93
94        // All of the other things besides images can be extracted from just the content.
95        $extracted = self::extract_from_content( $content, $what_to_extract, $extracted );
96
97        return $extracted;
98    }
99
100    /**
101     * Gets the specified meta info from the given post content.
102     * NOTE: If you want IMAGES, call extract( $blog_id, $post_id, ...) which will give you more/better image extraction
103     * This method will give you an error if you ask for IMAGES.
104     *
105     * @param string $content The HTML post_content of a post.
106     * @param int    $what_to_extract A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS.
107     * @param array  $already_extracted Previously extracted things, e.g. images from extract(), which can be used for x-referencing here.
108     *
109     * @return array a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
110     */
111    public static function extract_from_content( $content, $what_to_extract = self::ALL, $already_extracted = array() ) {
112        $stripped_content = self::get_stripped_content( $content );
113
114        // Maybe start with some previously extracted things (e.g. images from extract().
115        $extracted = $already_extracted;
116
117        // Embedded media objects will have already been converted to shortcodes by pre_kses hooks on save.
118
119        if ( self::IMAGES & $what_to_extract ) {
120            $images    = self::extract_images_from_content( $stripped_content, array() );
121            $extracted = array_merge( $extracted, $images );
122        }
123
124        // ----------------------------------- MENTIONS ------------------------------
125
126        if ( self::MENTIONS & $what_to_extract ) {
127            if ( preg_match_all( '/(^|\s)@(\w+)/u', $stripped_content, $matches ) ) {
128                $mentions             = array_values( array_unique( $matches[2] ) ); // array_unique() retains the keys!
129                $mentions             = array_map( 'strtolower', $mentions );
130                $extracted['mention'] = array( 'name' => $mentions );
131                if ( ! isset( $extracted['has'] ) ) {
132                    $extracted['has'] = array();
133                }
134                $extracted['has']['mention'] = count( $mentions );
135            }
136        }
137
138        // ----------------------------------- HASHTAGS ------------------------------
139        /**
140         * Some hosts may not compile with --enable-unicode-properties and kick a warning:
141         * Warning: preg_match_all() [function.preg-match-all]: Compilation failed: support for \P, \p, and \X has not been compiled
142         * Therefore, we only run this code block on wpcom, not in Jetpack.
143         */
144        if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) && ( self::HASHTAGS & $what_to_extract ) ) {
145            // This regex does not exactly match Twitter's
146            // if there are problems/complaints we should implement this:
147            // https://github.com/twitter/twitter-text/blob/master/java/src/com/twitter/Regex.java .
148            if ( preg_match_all( '/(?:^|\s)#(\w*\p{L}+\w*)/u', $stripped_content, $matches ) ) {
149                $hashtags             = array_values( array_unique( $matches[1] ) ); // array_unique() retains the keys!
150                $hashtags             = array_map( 'strtolower', $hashtags );
151                $extracted['hashtag'] = array( 'name' => $hashtags );
152                if ( ! isset( $extracted['has'] ) ) {
153                    $extracted['has'] = array();
154                }
155                $extracted['has']['hashtag'] = count( $hashtags );
156            }
157        }
158
159        // ----------------------------------- SHORTCODES ------------------------------
160
161        // Always look for shortcodes.
162        // If we don't want them, we'll just remove them, so we don't grab them as links below.
163        // Limit the regex to tags in the content as `do_shortcode()` does; otherwise the regex can get too big.
164        // See also: https://github.com/WordPress/wordpress-develop/blob/7.1.3/src/wp-includes/shortcodes.php#L255-L272
165        global $shortcode_tags;
166        $shortcode_pattern = null;
167        if ( str_contains( $content, '[' ) && ! empty( $shortcode_tags ) && is_array( $shortcode_tags ) ) {
168            // Find all registered tag names in $content.
169            preg_match_all( '@\[([^<>&/\[\]\x00-\x20=]++)@', $content, $matches );
170            $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
171
172            if ( ! empty( $tagnames ) ) {
173                $shortcode_pattern = '/' . get_shortcode_regex( $tagnames ) . '/s';
174            }
175        }
176        if ( $shortcode_pattern && preg_match_all( $shortcode_pattern, $content, $matches ) ) {
177
178            $shortcode_total_count = 0;
179            $shortcode_type_counts = array();
180            $shortcode_types       = array();
181            $shortcode_details     = array();
182
183            if ( self::SHORTCODES & $what_to_extract ) {
184
185                foreach ( $matches[2] as $key => $shortcode ) {
186                    // Elasticsearch (and probably other things) doesn't deal well with some chars as key names.
187                    $shortcode_name = preg_replace( '/[.,*"\'\/\\\\#+ ]/', '_', $shortcode );
188
189                    $attr = shortcode_parse_atts( $matches[3][ $key ] );
190
191                    ++$shortcode_total_count;
192                    if ( ! isset( $shortcode_type_counts[ $shortcode_name ] ) ) {
193                        $shortcode_type_counts[ $shortcode_name ] = 0;
194                    }
195                    ++$shortcode_type_counts[ $shortcode_name ];
196
197                    // Store (uniquely) presence of all shortcode regardless of whether it's a keeper (for those, get ID below)
198                    // @todo Store number of occurrences?
199                    if ( ! in_array( $shortcode_name, $shortcode_types, true ) ) {
200                        $shortcode_types[] = $shortcode_name;
201                    }
202
203                    // For keeper shortcodes, also store the id/url of the object (e.g. youtube video, TED talk, etc.).
204                    if ( in_array( $shortcode, self::$keeper_shortcodes, true ) ) {
205                        // Clear shortcode ID data left from the last shortcode.
206                        $id = null;
207                        // We'll try to get the salient ID from the function jetpack_shortcode_get_xyz_id().
208                        // If the shortcode is a class, we'll call XyzShortcode::get_xyz_id().
209                        $shortcode_get_id_func   = "jetpack_shortcode_get_{$shortcode}_id";
210                        $shortcode_class_name    = ucfirst( $shortcode ) . 'Shortcode';
211                        $shortcode_get_id_method = "get_{$shortcode}_id";
212                        if ( function_exists( $shortcode_get_id_func ) ) {
213                            $id = call_user_func( $shortcode_get_id_func, $attr );
214                        } elseif ( method_exists( $shortcode_class_name, $shortcode_get_id_method ) ) {
215                            $id = call_user_func( array( $shortcode_class_name, $shortcode_get_id_method ), $attr );
216                        } elseif ( 'video' === $shortcode ) {
217                            $id = $attr['src'] ?? $attr['url'] ?? $attr['mp4'] ?? $attr['m4v'] ?? $attr['webm'] ?? $attr['ogv'] ?? $attr['wmv'] ?? $attr['flv'] ?? null;
218                        } elseif ( 'audio' === $shortcode ) {
219                            preg_match( '#(https?://(?:[^\s"|\']+)\.(?:mp3|ogg|flac|m4a|wav))([ "\'|]|$)#', implode( ' ', $attr ), $audio_matches );
220                            $id = $audio_matches[1] ?? null;
221                        }
222                        if ( ! empty( $id )
223                            && ( ! isset( $shortcode_details[ $shortcode_name ] ) || ! in_array( $id, $shortcode_details[ $shortcode_name ], true ) ) ) {
224                            $shortcode_details[ $shortcode_name ][] = $id;
225                        }
226                    }
227                }
228
229                if ( $shortcode_total_count > 0 ) {
230                    // Add the shortcode info to the $extracted array.
231                    if ( ! isset( $extracted['has'] ) ) {
232                        $extracted['has'] = array();
233                    }
234                    $extracted['has']['shortcode'] = $shortcode_total_count;
235                    $extracted['shortcode']        = array();
236                    foreach ( $shortcode_type_counts as $type => $count ) {
237                        $extracted['shortcode'][ $type ] = array( 'count' => $count );
238                    }
239                    if ( ! empty( $shortcode_types ) ) {
240                        $extracted['shortcode_types'] = $shortcode_types;
241                    }
242                    foreach ( $shortcode_details as $type => $id ) {
243                        $extracted['shortcode'][ $type ]['id'] = $id;
244                    }
245                }
246            }
247
248            // Remove the shortcodes form our copy of $content, so we don't count links in them as links below.
249            $content = preg_replace( $shortcode_pattern, ' ', $content );
250        }
251
252        // ----------------------------------- LINKS ------------------------------
253
254        if ( self::LINKS & $what_to_extract ) {
255
256            // To hold the extracted stuff we find.
257            $links = array();
258
259            // @todo Get the text inside the links?
260
261            // Grab any links, whether in <a href="..." or not, but subtract those from shortcodes and images.
262            // (we treat embed links as just another link).
263            if ( preg_match_all( '#(?:^|\s|"|\')(https?://([^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))))#', $content, $matches ) ) {
264
265                foreach ( $matches[1] as $link_raw ) {
266                    $url = wp_parse_url( $link_raw );
267
268                    // Data URI links.
269                    if ( ! isset( $url['scheme'] ) || 'data' === $url['scheme'] ) {
270                        continue;
271                    }
272
273                    // Reject invalid URLs.
274                    if ( ! isset( $url['host'] ) ) {
275                        continue;
276                    }
277
278                    // Remove large (and likely invalid) links.
279                    if ( 4096 < strlen( $link_raw ) ) {
280                        continue;
281                    }
282
283                    // Build a simple form of the URL so we can compare it to ones we found in IMAGES or SHORTCODES and exclude those.
284                    $simple_url = $url['scheme'] . '://' . $url['host'] . ( ! empty( $url['path'] ) ? $url['path'] : '' );
285                    if ( isset( $extracted['image']['url'] ) ) {
286                        if ( in_array( $simple_url, (array) $extracted['image']['url'], true ) ) {
287                            continue;
288                        }
289                    }
290
291                    list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
292
293                    // Build a reversed hostname.
294                    $host_parts    = array_reverse( explode( '.', $url['host'] ) );
295                    $host_reversed = '';
296                    foreach ( $host_parts as $part ) {
297                        $host_reversed .= ( ! empty( $host_reversed ) ? '.' : '' ) . $part;
298                    }
299
300                    $link_analyzed = '';
301                    if ( ! empty( $url['path'] ) ) {
302                        // The whole path (no query args or fragments).
303                        $path           = substr( $url['path'], 1 ); // strip the leading '/'.
304                        $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $path;
305
306                        // The path split by /.
307                        $path_split = explode( '/', $path );
308                        if ( count( $path_split ) > 1 ) {
309                            $link_analyzed .= ' ' . implode( ' ', $path_split );
310                        }
311
312                        // The fragment.
313                        if ( ! empty( $url['fragment'] ) ) {
314                            $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $url['fragment'];
315                        }
316                    }
317
318                    $link = array(
319                        'url'           => $link_all_but_proto,
320                        'host_reversed' => $host_reversed,
321                        'host'          => $url['host'],
322                    );
323                    if ( ! in_array( $link, $links, true ) ) {
324                        $links[] = $link;
325                    }
326                }
327            }
328
329            $link_count = count( $links );
330            if ( $link_count ) {
331                $extracted['link'] = $links;
332                if ( ! isset( $extracted['has'] ) ) {
333                    $extracted['has'] = array();
334                }
335                $extracted['has']['link'] = $link_count;
336            }
337        }
338
339        // ----------------------------------- EMBEDS ------------------------------
340
341        // Embeds are just individual links on their own line.
342        if ( self::EMBEDS & $what_to_extract ) {
343
344            if ( ! function_exists( '_wp_oembed_get_object' ) ) {
345                include ABSPATH . WPINC . '/class-oembed.php';
346            }
347
348            // get an oembed object.
349            $oembed = _wp_oembed_get_object();
350
351            // Grab any links on their own lines that may be embeds.
352            if ( preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $content, $matches ) ) {
353
354                // To hold the extracted stuff we find.
355                $embeds = array();
356
357                foreach ( $matches[1] as $link_raw ) {
358                    $url = wp_parse_url( $link_raw );
359
360                    list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
361
362                    // Check whether this "link" is really an embed.
363                    foreach ( $oembed->providers as $matchmask => $data ) {
364                        // Guard against malformed oEmbed providers.
365                        if ( ! isset( $data[0] ) ) {
366                            continue;
367                        }
368                        $regex = $data[1] ?? false;
369
370                        // Turn the asterisk-type provider URLs into regex.
371                        if ( ! $regex ) {
372                            $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
373                            $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
374                        }
375
376                        if ( preg_match( $matchmask, $link_raw ) ) {
377                            $embeds[] = $link_all_but_proto; // @todo Check unique before adding
378
379                            // @todo Try to get ID's for the ones we care about (shortcode_keepers)
380                            break;
381                        }
382                    }
383                }
384
385                if ( ! empty( $embeds ) ) {
386                    if ( ! isset( $extracted['has'] ) ) {
387                        $extracted['has'] = array();
388                    }
389                    $extracted['has']['embed'] = count( $embeds );
390                    $extracted['embed']        = array( 'url' => array() );
391                    foreach ( $embeds as $e ) {
392                        $extracted['embed']['url'][] = $e;
393                    }
394                }
395            }
396        }
397
398        return $extracted;
399    }
400
401    /**
402     * Get image fields for matching images.
403     *
404     * @uses Images
405     *
406     * @param WP_Post $post A post object.
407     * @param array   $args Optional args, see defaults list for details.
408     * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
409     *
410     * @return array Returns an array of all images meeting the specified criteria in $args.
411     */
412    private static function get_image_fields( $post, $args = array(), $extract_alt_text = false ) {
413
414        if ( ! $post instanceof WP_Post ) {
415            return array();
416        }
417
418        $defaults = array(
419            'width'  => 200, // Required minimum width (if possible to determine).
420            'height' => 200, // Required minimum height (if possible to determine).
421        );
422
423        $args = wp_parse_args( $args, $defaults );
424
425        $image_list                = array();
426        $image_booleans            = array();
427        $image_booleans['gallery'] = 0;
428
429        $from_featured_image = Images::from_thumbnail( $post->ID, $args['width'], $args['height'] );
430        if ( ! empty( $from_featured_image ) ) {
431            if ( $extract_alt_text ) {
432                $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_featured_image ) );
433            } else {
434                $srcs       = wp_list_pluck( $from_featured_image, 'src' );
435                $image_list = array_merge( $image_list, $srcs );
436            }
437        }
438
439        $from_slideshow = Images::from_slideshow( $post->ID, $args['width'], $args['height'] );
440        if ( ! empty( $from_slideshow ) ) {
441            if ( $extract_alt_text ) {
442                $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_slideshow ) );
443            } else {
444                $srcs       = wp_list_pluck( $from_slideshow, 'src' );
445                $image_list = array_merge( $image_list, $srcs );
446            }
447        }
448
449        $from_gallery = Images::from_gallery( $post->ID );
450        if ( ! empty( $from_gallery ) ) {
451            if ( $extract_alt_text ) {
452                $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_gallery ) );
453            } else {
454                $srcs       = wp_list_pluck( $from_gallery, 'src' );
455                $image_list = array_merge( $image_list, $srcs );
456            }
457            ++$image_booleans['gallery']; // @todo This count isn't correct, will only every count 1
458        }
459
460        // @todo Can we check width/height of these efficiently?  Could maybe use query args at least, before we strip them out
461        $image_list = self::get_images_from_html( $post->post_content, $image_list, $extract_alt_text );
462
463        return self::build_image_struct( $image_list, $image_booleans );
464    }
465
466    /**
467     * Given an extracted image array reduce to src,  alt_text, src_width, and src_height.
468     *
469     * @param array $images extracted image array.
470     *
471     * @return array reduced image array
472     */
473    protected static function reduce_extracted_images( $images ) {
474        $ret_images = array();
475        foreach ( $images as $image ) {
476            // skip if src isn't set.
477            if ( empty( $image['src'] ) ) {
478                continue;
479            }
480            $ret_image = array(
481                'url' => $image['src'],
482            );
483            if ( ! empty( $image['src_height'] ) || ! empty( $image['src_width'] ) ) {
484                $ret_image['src_width']  = $image['src_width'] ?? '';
485                $ret_image['src_height'] = $image['src_height'] ?? '';
486            }
487            if ( ! empty( $image['alt_text'] ) ) {
488                $ret_image['alt_text'] = $image['alt_text'];
489            } else {
490                $ret_image = $image['src'];
491            }
492            $ret_images[] = $ret_image;
493        }
494        return $ret_images;
495    }
496
497    /**
498     * Helper function to get images from HTML and return it with the set sturcture.
499     *
500     * @param string $content HTML content.
501     * @param array  $image_list Array of already found images.
502     * @param string $extract_alt_text Whether or not to extract the alt text.
503     *
504     * @return array|array[] Array of images.
505     */
506    public static function extract_images_from_content( $content, $image_list, $extract_alt_text = false ) {
507        $image_list = self::get_images_from_html( $content, $image_list, $extract_alt_text );
508        return self::build_image_struct( $image_list, array() );
509    }
510
511    /**
512     * Produces a set structure for extracted media items.
513     *
514     * @param array $image_list Array of images.
515     * @param array $image_booleans Image booleans.
516     *
517     * @return array|array[]
518     */
519    public static function build_image_struct( $image_list, $image_booleans ) {
520        if ( ! empty( $image_list ) ) {
521            $retval     = array( 'image' => array() );
522            $image_list = array_unique( $image_list, SORT_REGULAR );
523            foreach ( $image_list as $img ) {
524                if ( is_string( $img ) ) {
525                    $retval['image'][] = array( 'url' => $img );
526                } else {
527                    $retval['image'][] = $img;
528                }
529            }
530            $image_booleans['image'] = count( $retval['image'] );
531            $retval['has']           = $image_booleans;
532            return $retval;
533        } else {
534            return array();
535        }
536    }
537
538    /**
539     * Extracts images from html.
540     *
541     * @param string  $html Some markup, possibly containing image tags.
542     * @param array   $images_already_extracted (just an array of image URLs without query strings, no special structure), used for de-duplication.
543     * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
544     *
545     * @return array Image URLs extracted from the HTML, stripped of query params and de-duped
546     */
547    public static function get_images_from_html( $html, $images_already_extracted, $extract_alt_text = false ) {
548        $image_list = $images_already_extracted;
549        $from_html  = Images::from_html( $html );
550        // early return if no image in html.
551        if ( empty( $from_html ) ) {
552            return $image_list;
553        }
554        // process images.
555        foreach ( $from_html as $extracted_image ) {
556            $image_url = $extracted_image['src'];
557            $length    = strpos( $image_url, '?' );
558            $src       = wp_parse_url( $image_url );
559
560            if ( $src && isset( $src['scheme'] ) && isset( $src['host'] ) && isset( $src['path'] ) ) {
561                // Rebuild the URL without the query string.
562                $queryless = $src['scheme'] . '://' . $src['host'] . $src['path'];
563            } elseif ( $length ) {
564                // If wp_parse_url() didn't work, strip off the query string the old fashioned way.
565                $queryless = substr( $image_url, 0, $length );
566            } else {
567                // Failing that, there was no spoon! Err ... query string!
568                $queryless = $image_url;
569            }
570
571            // Discard URLs that are longer then 4KB, these are likely data URIs or malformed HTML.
572            if ( 4096 < strlen( $queryless ) ) {
573                continue;
574            }
575
576            if ( ! in_array( $queryless, $image_list, true ) ) {
577                $image_to_add = array(
578                    'url' => $queryless,
579                );
580                if ( $extract_alt_text ) {
581                    if ( ! empty( $extracted_image['alt_text'] ) ) {
582                        $image_to_add['alt_text'] = $extracted_image['alt_text'];
583                    }
584                    if ( ! empty( $extracted_image['src_width'] ) || ! empty( $extracted_image['src_height'] ) ) {
585                            $image_to_add['src_width']  = $extracted_image['src_width'];
586                            $image_to_add['src_height'] = $extracted_image['src_height'];
587                    }
588                } else {
589                    $image_to_add = $queryless;
590                }
591                $image_list[] = $image_to_add;
592            }
593        }
594        return $image_list;
595    }
596
597    /**
598     * Strips concents of all tags, shortcodes, and decodes HTML entities.
599     *
600     * @param string $content Original content.
601     *
602     * @return string Cleaned content.
603     */
604    private static function get_stripped_content( $content ) {
605        $clean_content = wp_strip_all_tags( $content );
606        $clean_content = html_entity_decode( $clean_content, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
607        // completely strip shortcodes and any content they enclose.
608        $clean_content = strip_shortcodes( $clean_content );
609        return $clean_content;
610    }
611}