PluginProbe ʕ •ᴥ•ʔ
Jetpack – WP Security, Backup, Speed, & Growth / 13.2.4
Jetpack – WP Security, Backup, Speed, & Growth v13.2.4
12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 14.4.2 14.5.1 14.6.1 14.7.1 14.8.1 14.9.2 15.0.3 15.1.2 15.2.1 15.3.2 15.4.1 15.5.1 15.6.1 15.7.2 15.8.1 15.9.2 16.0.2 16.1.3 16.2-a.5 16.2-a.3 16.1.2 16.2-a.1 16.1.1 16.1 16.1-beta 16.1-beta.2 16.1-beta.3 16.1-a.5 16.1-a.3 16.0.1 16.1-a.1 16.0 16.0-beta 16.0-a.7 16.0-a.5 15.9.1 16.0-a.3 16.0-a.1 15.9 15.9-beta 15.9-a.7 15.9-a.5 15.9-a.3 15.9-a.1 15.8 15.8-beta 15.8-a.7 15.8-a.5 5.2.5 5.3.4 5.4.4 5.5.5 5.6.5 5.7.5 5.8.4 5.9.4 6.0.4 6.1 6.1.1 6.1.2 6.1.3 6.1.4 6.1.5 6.2 6.2.1 6.2.2 6.2.3 6.2.4 6.2.5 6.3 6.3.1 6.3.2 6.3.3 6.3.4 6.3.5 6.3.6 6.3.7 6.4 6.4.1 6.4.2 6.4.3 6.4.4 6.4.5 6.4.6 6.5 6.5.1 6.5.2 6.5.3 6.5.4 6.6 6.6.1 6.6.2 6.6.3 6.6.4 6.6.5 6.7 6.7.1 6.7.2 6.7.3 6.7.4 6.8 6.8.1 6.8.2 6.8.3 6.8.4 6.8.5 6.9 6.9.1 6.9.2 6.9.3 6.9.4 7.0 7.0.1 7.0.2 7.0.3 7.0.4 7.0.5 7.1 7.1.1 7.1.2 7.1.3 7.1.4 7.1.5 7.2 7.2.1 7.2.1.1 7.2.2 7.2.3 7.2.4 7.2.5 7.3 7.3.0.1 7.3.1 7.3.1.1 7.3.2 7.3.3 7.3.4 7.3.5 7.4 7.4.1 7.4.2 7.4.3 7.4.4 7.4.5 7.5 7.5.0.1 7.5.1 7.5.2 7.5.3 7.5.4 7.5.5 7.5.6 7.5.7 7.6 7.6.1 7.6.2 7.6.3 7.6.4 7.7 7.7.1 7.7.2 7.7.3 7.7.4 7.7.5 7.7.6 7.8 7.8.1 7.8.2 7.8.3 7.8.4 7.9 7.9.1 7.9.2 7.9.3 7.9.4 8.0 8.0.1 8.0.2 8.0.3 8.1 8.1.1 8.1.2 8.1.3 8.1.4 8.2 8.2.0.1 8.2.1 8.2.2 8.2.3 8.2.4 8.2.5 8.2.6 8.3 8.3.1 8.3.2 8.3.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.5 8.5.1 8.5.2 8.5.3 8.6 8.6.1 8.6.2 8.6.3 8.6.4 8.7 8.7.0.1 8.7.1 8.7.2 8.7.3 8.7.4 8.8 8.8.1 8.8.2 8.8.3 8.8.4 8.8.5 8.9 8.9.1 8.9.2 8.9.3 8.9.4 9.0 9.0.1 9.0.2 9.0.3 9.0.4 9.0.5 9.1 9.1.1 9.1.2 9.1.3 9.2 9.2.1 9.2.2 9.2.3 9.2.4 9.3 9.3.1 9.3.2 9.3.3 9.3.4 9.3.5 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.5 9.5.1 9.5.2 9.5.3 9.5.4 9.5.5 9.6 9.6.1 9.6.2 9.6.3 9.6.4 9.7 9.7.1 9.7.2 15.7-beta.2 9.7.3 15.7.1 9.8 15.8-a.1 9.8.1 15.8-a.3 9.8.2 2.0.9 9.8.3 2.1.7 9.9 2.2.10 9.9.1 2.3.10 9.9.2 2.4.7 9.9.3 2.5.5 2.6.6 2.7.5 2.8.5 2.9.6 3.0.6 3.1.5 3.2.5 3.3.6 3.4.6 3.5.6 3.6.4 3.7.5 3.8.5 3.9.10 4.0.7 4.1.4 4.2.5 4.3.5 4.4.5 4.5.3 4.6.3 4.7.4 4.8.5 4.9.3 5.0.3 5.1.4 trunk 10.0 10.0.1 10.0.2 10.1 10.1.1 10.1.2 10.2 10.2.1 10.2.2 10.2.3 10.3 10.3.1 10.3.2 10.4 10.4.1 10.4.2 10.5 10.5.1 10.5.2 10.5.3 10.6 10.6.1 10.6.2 10.7 10.7.1 10.7.2 10.8 10.8.1 10.8.2 10.9 10.9.1 10.9.2 10.9.3 11.0 11.0.1 11.0.2 11.1 11.1.1 11.1.2 11.1.3 11.1.4 11.2 11.2.1 11.2.2 11.3 11.3.1 11.3.2 11.3.3 11.3.4 11.4 11.4.1 11.4.2 11.5 11.5.1 11.5.2 11.5.3 11.6 11.6.1 11.6.2 11.7 11.7.1 11.7.2 11.7.3 11.8 11.8.3 11.8.4 11.8.5 11.8.6 11.9 11.9.1 11.9.2 11.9.3 12.0 12.0.1 12.0.2 12.1 12.1.1 12.1.2 12.2 12.2.1 12.2.2 12.3 12.3.1 12.4 12.4.1 12.5 12.5.1 12.6 12.6.1 12.6.2 12.6.3 12.7 12.7.1 12.7.2 12.8 12.8.1 12.8.2 12.9 12.9.1 12.9.2 12.9.3 12.9.4 13.0 13.0.1 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 13.2.2 13.2.3 13.3 13.3.1 13.3.2 13.4 13.4.1 13.4.2 13.4.3 13.4.4 13.5 13.5.1 13.6 13.6.1 13.7 13.7.1 13.8 13.8.1 13.8.2 13.9 13.9.1 14.0 14.1 14.2 14.2.1 14.3 14.4 14.4.1 14.5 14.6 14.7 14.8 14.9 14.9.1 15.0 15.0.1 15.0.2 15.1 15.1.1 15.2 15.3 15.3.1 15.4 15.5 15.6 15.7 15.7-a.1 15.7-a.3 15.7-a.5 15.7-a.7 15.7-beta
jetpack / _inc / lib / class.media-extractor.php
jetpack / _inc / lib Last commit date
admin-pages 2 years ago core-api 2 years ago debugger 2 years ago markdown 2 years ago class-jetpack-ai-helper.php 2 years ago class-jetpack-currencies.php 5 years ago class-jetpack-google-drive-helper.php 3 years ago class-jetpack-instagram-gallery-helper.php 3 years ago class-jetpack-mapbox-helper.php 3 years ago class-jetpack-podcast-feed-locator.php 2 years ago class-jetpack-podcast-helper.php 2 years ago class-jetpack-recommendations.php 2 years ago class-jetpack-top-posts-helper.php 2 years ago class-jetpack-wizard.php 5 years ago class.color.php 2 years ago class.core-rest-api-endpoints.php 2 years ago class.jetpack-automatic-install-skin.php 2 years ago class.jetpack-iframe-embed.php 3 years ago class.jetpack-keyring-service-helper.php 3 years ago class.jetpack-password-checker.php 3 years ago class.jetpack-search-performance-logger.php 4 years ago class.media-extractor.php 2 years ago class.media-summary.php 2 years ago class.media.php 2 years ago components.php 3 years ago debugger.php 2 years ago functions.wp-notify.php 3 years ago icalendar-reader.php 2 years ago markdown.php 3 years ago plans.php 4 years ago plugins.php 4 years ago tonesque.php 2 years ago widgets.php 2 years ago
class.media-extractor.php
589 lines
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 * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
51 *
52 * @return array|WP_Error a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
53 */
54 public static function extract( $blog_id, $post_id, $what_to_extract = self::ALL, $extract_alt_text = false ) {
55
56 // multisite?
57 if ( function_exists( 'switch_to_blog' ) ) {
58 switch_to_blog( $blog_id );
59 }
60
61 $post = get_post( $post_id );
62 if ( ! $post instanceof WP_Post ) {
63 if ( function_exists( 'restore_current_blog' ) ) {
64 restore_current_blog();
65 }
66 return array();
67 }
68 $content = $post->post_title . "\n\n" . $post->post_content;
69 $char_cnt = strlen( $content );
70
71 // prevent running extraction on really huge amounts of content.
72 if ( $char_cnt > 100000 ) { // about 20k English words.
73 $content = substr( $content, 0, 100000 );
74 }
75
76 $extracted = array();
77
78 // Get images first, we need the full post for that.
79 if ( self::IMAGES & $what_to_extract ) {
80 $extracted = self::get_image_fields( $post, array(), $extract_alt_text );
81
82 // Turn off images so we can safely call extract_from_content() below.
83 $what_to_extract = $what_to_extract - self::IMAGES;
84 }
85
86 if ( function_exists( 'restore_current_blog' ) ) {
87 restore_current_blog();
88 }
89
90 // All of the other things besides images can be extracted from just the content.
91 $extracted = self::extract_from_content( $content, $what_to_extract, $extracted );
92
93 return $extracted;
94 }
95
96 /**
97 * Gets the specified meta info from the given post content.
98 * NOTE: If you want IMAGES, call extract( $blog_id, $post_id, ...) which will give you more/better image extraction
99 * This method will give you an error if you ask for IMAGES.
100 *
101 * @param string $content The HTML post_content of a post.
102 * @param int $what_to_extract A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS.
103 * @param array $already_extracted Previously extracted things, e.g. images from extract(), which can be used for x-referencing here.
104 *
105 * @return array a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error.
106 */
107 public static function extract_from_content( $content, $what_to_extract = self::ALL, $already_extracted = array() ) {
108 $stripped_content = self::get_stripped_content( $content );
109
110 // Maybe start with some previously extracted things (e.g. images from extract().
111 $extracted = $already_extracted;
112
113 // Embedded media objects will have already been converted to shortcodes by pre_kses hooks on save.
114
115 if ( self::IMAGES & $what_to_extract ) {
116 $images = self::extract_images_from_content( $stripped_content, array() );
117 $extracted = array_merge( $extracted, $images );
118 }
119
120 // ----------------------------------- MENTIONS ------------------------------
121
122 if ( self::MENTIONS & $what_to_extract ) {
123 if ( preg_match_all( '/(^|\s)@(\w+)/u', $stripped_content, $matches ) ) {
124 $mentions = array_values( array_unique( $matches[2] ) ); // array_unique() retains the keys!
125 $mentions = array_map( 'strtolower', $mentions );
126 $extracted['mention'] = array( 'name' => $mentions );
127 if ( ! isset( $extracted['has'] ) ) {
128 $extracted['has'] = array();
129 }
130 $extracted['has']['mention'] = count( $mentions );
131 }
132 }
133
134 // ----------------------------------- HASHTAGS ------------------------------
135 /**
136 * Some hosts may not compile with --enable-unicode-properties and kick a warning:
137 * Warning: preg_match_all() [function.preg-match-all]: Compilation failed: support for \P, \p, and \X has not been compiled
138 * Therefore, we only run this code block on wpcom, not in Jetpack.
139 */
140 if ( ( defined( 'IS_WPCOM' ) && IS_WPCOM ) && ( self::HASHTAGS & $what_to_extract ) ) {
141 // This regex does not exactly match Twitter's
142 // if there are problems/complaints we should implement this:
143 // https://github.com/twitter/twitter-text/blob/master/java/src/com/twitter/Regex.java .
144 if ( preg_match_all( '/(?:^|\s)#(\w*\p{L}+\w*)/u', $stripped_content, $matches ) ) {
145 $hashtags = array_values( array_unique( $matches[1] ) ); // array_unique() retains the keys!
146 $hashtags = array_map( 'strtolower', $hashtags );
147 $extracted['hashtag'] = array( 'name' => $hashtags );
148 if ( ! isset( $extracted['has'] ) ) {
149 $extracted['has'] = array();
150 }
151 $extracted['has']['hashtag'] = count( $hashtags );
152 }
153 }
154
155 // ----------------------------------- SHORTCODES ------------------------------
156
157 // Always look for shortcodes.
158 // If we don't want them, we'll just remove them, so we don't grab them as links below.
159 $shortcode_pattern = '/' . get_shortcode_regex() . '/s';
160 if ( preg_match_all( $shortcode_pattern, $content, $matches ) ) {
161
162 $shortcode_total_count = 0;
163 $shortcode_type_counts = array();
164 $shortcode_types = array();
165 $shortcode_details = array();
166
167 if ( self::SHORTCODES & $what_to_extract ) {
168
169 foreach ( $matches[2] as $key => $shortcode ) {
170 // Elasticsearch (and probably other things) doesn't deal well with some chars as key names.
171 $shortcode_name = preg_replace( '/[.,*"\'\/\\\\#+ ]/', '_', $shortcode );
172
173 $attr = shortcode_parse_atts( $matches[3][ $key ] );
174
175 ++$shortcode_total_count;
176 if ( ! isset( $shortcode_type_counts[ $shortcode_name ] ) ) {
177 $shortcode_type_counts[ $shortcode_name ] = 0;
178 }
179 ++$shortcode_type_counts[ $shortcode_name ];
180
181 // Store (uniquely) presence of all shortcode regardless of whether it's a keeper (for those, get ID below)
182 // @todo Store number of occurrences?
183 if ( ! in_array( $shortcode_name, $shortcode_types, true ) ) {
184 $shortcode_types[] = $shortcode_name;
185 }
186
187 // For keeper shortcodes, also store the id/url of the object (e.g. youtube video, TED talk, etc.).
188 if ( in_array( $shortcode, self::$keeper_shortcodes, true ) ) {
189 // Clear shortcode ID data left from the last shortcode.
190 $id = null;
191 // We'll try to get the salient ID from the function jetpack_shortcode_get_xyz_id().
192 // If the shortcode is a class, we'll call XyzShortcode::get_xyz_id().
193 $shortcode_get_id_func = "jetpack_shortcode_get_{$shortcode}_id";
194 $shortcode_class_name = ucfirst( $shortcode ) . 'Shortcode';
195 $shortcode_get_id_method = "get_{$shortcode}_id";
196 if ( function_exists( $shortcode_get_id_func ) ) {
197 $id = call_user_func( $shortcode_get_id_func, $attr );
198 } elseif ( method_exists( $shortcode_class_name, $shortcode_get_id_method ) ) {
199 $id = call_user_func( array( $shortcode_class_name, $shortcode_get_id_method ), $attr );
200 }
201 if ( ! empty( $id )
202 && ( ! isset( $shortcode_details[ $shortcode_name ] ) || ! in_array( $id, $shortcode_details[ $shortcode_name ], true ) ) ) {
203 $shortcode_details[ $shortcode_name ][] = $id;
204 }
205 }
206 }
207
208 if ( $shortcode_total_count > 0 ) {
209 // Add the shortcode info to the $extracted array.
210 if ( ! isset( $extracted['has'] ) ) {
211 $extracted['has'] = array();
212 }
213 $extracted['has']['shortcode'] = $shortcode_total_count;
214 $extracted['shortcode'] = array();
215 foreach ( $shortcode_type_counts as $type => $count ) {
216 $extracted['shortcode'][ $type ] = array( 'count' => $count );
217 }
218 if ( ! empty( $shortcode_types ) ) {
219 $extracted['shortcode_types'] = $shortcode_types;
220 }
221 foreach ( $shortcode_details as $type => $id ) {
222 $extracted['shortcode'][ $type ]['id'] = $id;
223 }
224 }
225 }
226
227 // Remove the shortcodes form our copy of $content, so we don't count links in them as links below.
228 $content = preg_replace( $shortcode_pattern, ' ', $content );
229 }
230
231 // ----------------------------------- LINKS ------------------------------
232
233 if ( self::LINKS & $what_to_extract ) {
234
235 // To hold the extracted stuff we find.
236 $links = array();
237
238 // @todo Get the text inside the links?
239
240 // Grab any links, whether in <a href="..." or not, but subtract those from shortcodes and images.
241 // (we treat embed links as just another link).
242 if ( preg_match_all( '#(?:^|\s|"|\')(https?://([^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))))#', $content, $matches ) ) {
243
244 foreach ( $matches[1] as $link_raw ) {
245 $url = wp_parse_url( $link_raw );
246
247 // Data URI links.
248 if ( ! isset( $url['scheme'] ) || 'data' === $url['scheme'] ) {
249 continue;
250 }
251
252 // Reject invalid URLs.
253 if ( ! isset( $url['host'] ) ) {
254 continue;
255 }
256
257 // Remove large (and likely invalid) links.
258 if ( 4096 < strlen( $link_raw ) ) {
259 continue;
260 }
261
262 // Build a simple form of the URL so we can compare it to ones we found in IMAGES or SHORTCODES and exclude those.
263 $simple_url = $url['scheme'] . '://' . $url['host'] . ( ! empty( $url['path'] ) ? $url['path'] : '' );
264 if ( isset( $extracted['image']['url'] ) ) {
265 if ( in_array( $simple_url, (array) $extracted['image']['url'], true ) ) {
266 continue;
267 }
268 }
269
270 list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
271
272 // Build a reversed hostname.
273 $host_parts = array_reverse( explode( '.', $url['host'] ) );
274 $host_reversed = '';
275 foreach ( $host_parts as $part ) {
276 $host_reversed .= ( ! empty( $host_reversed ) ? '.' : '' ) . $part;
277 }
278
279 $link_analyzed = '';
280 if ( ! empty( $url['path'] ) ) {
281 // The whole path (no query args or fragments).
282 $path = substr( $url['path'], 1 ); // strip the leading '/'.
283 $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $path;
284
285 // The path split by /.
286 $path_split = explode( '/', $path );
287 if ( count( $path_split ) > 1 ) {
288 $link_analyzed .= ' ' . implode( ' ', $path_split );
289 }
290
291 // The fragment.
292 if ( ! empty( $url['fragment'] ) ) {
293 $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $url['fragment'];
294 }
295 }
296
297 $link = array(
298 'url' => $link_all_but_proto,
299 'host_reversed' => $host_reversed,
300 'host' => $url['host'],
301 );
302 if ( ! in_array( $link, $links, true ) ) {
303 $links[] = $link;
304 }
305 }
306 }
307
308 $link_count = count( $links );
309 if ( $link_count ) {
310 $extracted['link'] = $links;
311 if ( ! isset( $extracted['has'] ) ) {
312 $extracted['has'] = array();
313 }
314 $extracted['has']['link'] = $link_count;
315 }
316 }
317
318 // ----------------------------------- EMBEDS ------------------------------
319
320 // Embeds are just individual links on their own line.
321 if ( self::EMBEDS & $what_to_extract ) {
322
323 if ( ! function_exists( '_wp_oembed_get_object' ) ) {
324 include ABSPATH . WPINC . '/class-oembed.php';
325 }
326
327 // get an oembed object.
328 $oembed = _wp_oembed_get_object();
329
330 // Grab any links on their own lines that may be embeds.
331 if ( preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $content, $matches ) ) {
332
333 // To hold the extracted stuff we find.
334 $embeds = array();
335
336 foreach ( $matches[1] as $link_raw ) {
337 $url = wp_parse_url( $link_raw );
338
339 list( $proto, $link_all_but_proto ) = explode( '://', $link_raw ); // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
340
341 // Check whether this "link" is really an embed.
342 foreach ( $oembed->providers as $matchmask => $data ) {
343 list( $providerurl, $regex ) = $data; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
344
345 // Turn the asterisk-type provider URLs into regex.
346 if ( ! $regex ) {
347 $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
348 $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
349 }
350
351 if ( preg_match( $matchmask, $link_raw ) ) {
352 $embeds[] = $link_all_but_proto; // @todo Check unique before adding
353
354 // @todo Try to get ID's for the ones we care about (shortcode_keepers)
355 break;
356 }
357 }
358 }
359
360 if ( ! empty( $embeds ) ) {
361 if ( ! isset( $extracted['has'] ) ) {
362 $extracted['has'] = array();
363 }
364 $extracted['has']['embed'] = count( $embeds );
365 $extracted['embed'] = array( 'url' => array() );
366 foreach ( $embeds as $e ) {
367 $extracted['embed']['url'][] = $e;
368 }
369 }
370 }
371 }
372
373 return $extracted;
374 }
375
376 /**
377 * Get image fields for matching images.
378 *
379 * @uses Jetpack_PostImages
380 *
381 * @param WP_Post $post A post object.
382 * @param array $args Optional args, see defaults list for details.
383 * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
384 *
385 * @return array Returns an array of all images meeting the specified criteria in $args.
386 */
387 private static function get_image_fields( $post, $args = array(), $extract_alt_text = false ) {
388
389 if ( ! $post instanceof WP_Post ) {
390 return array();
391 }
392
393 $defaults = array(
394 'width' => 200, // Required minimum width (if possible to determine).
395 'height' => 200, // Required minimum height (if possible to determine).
396 );
397
398 $args = wp_parse_args( $args, $defaults );
399
400 $image_list = array();
401 $image_booleans = array();
402 $image_booleans['gallery'] = 0;
403
404 $from_featured_image = Jetpack_PostImages::from_thumbnail( $post->ID, $args['width'], $args['height'] );
405 if ( ! empty( $from_featured_image ) ) {
406 if ( $extract_alt_text ) {
407 $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_featured_image ) );
408 } else {
409 $srcs = wp_list_pluck( $from_featured_image, 'src' );
410 $image_list = array_merge( $image_list, $srcs );
411 }
412 }
413
414 $from_slideshow = Jetpack_PostImages::from_slideshow( $post->ID, $args['width'], $args['height'] );
415 if ( ! empty( $from_slideshow ) ) {
416 if ( $extract_alt_text ) {
417 $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_slideshow ) );
418 } else {
419 $srcs = wp_list_pluck( $from_slideshow, 'src' );
420 $image_list = array_merge( $image_list, $srcs );
421 }
422 }
423
424 $from_gallery = Jetpack_PostImages::from_gallery( $post->ID );
425 if ( ! empty( $from_gallery ) ) {
426 if ( $extract_alt_text ) {
427 $image_list = array_merge( $image_list, self::reduce_extracted_images( $from_gallery ) );
428 } else {
429 $srcs = wp_list_pluck( $from_gallery, 'src' );
430 $image_list = array_merge( $image_list, $srcs );
431 }
432 ++$image_booleans['gallery']; // @todo This count isn't correct, will only every count 1
433 }
434
435 // @todo Can we check width/height of these efficiently? Could maybe use query args at least, before we strip them out
436 $image_list = self::get_images_from_html( $post->post_content, $image_list, $extract_alt_text );
437
438 return self::build_image_struct( $image_list, $image_booleans );
439 }
440
441 /**
442 * Given an extracted image array reduce to src, alt_text, src_width, and src_height.
443 *
444 * @param array $images extracted image array.
445 *
446 * @return array reduced image array
447 */
448 protected static function reduce_extracted_images( $images ) {
449 $ret_images = array();
450 foreach ( $images as $image ) {
451 // skip if src isn't set.
452 if ( empty( $image['src'] ) ) {
453 continue;
454 }
455 $ret_image = array(
456 'url' => $image['src'],
457 );
458 if ( ! empty( $image['src_height'] ) || ! empty( $image['src_width'] ) ) {
459 $ret_image['src_width'] = $image['src_width'] ?? '';
460 $ret_image['src_height'] = $image['src_height'] ?? '';
461 }
462 if ( ! empty( $image['alt_text'] ) ) {
463 $ret_image['alt_text'] = $image['alt_text'];
464 } else {
465 $ret_image = $image['src'];
466 }
467 $ret_images[] = $ret_image;
468 }
469 return $ret_images;
470 }
471
472 /**
473 * Helper function to get images from HTML and return it with the set sturcture.
474 *
475 * @param string $content HTML content.
476 * @param array $image_list Array of already found images.
477 * @param string $extract_alt_text Whether or not to extract the alt text.
478 *
479 * @return array|array[] Array of images.
480 */
481 public static function extract_images_from_content( $content, $image_list, $extract_alt_text = false ) {
482 $image_list = self::get_images_from_html( $content, $image_list, $extract_alt_text );
483 return self::build_image_struct( $image_list, array() );
484 }
485
486 /**
487 * Produces a set structure for extracted media items.
488 *
489 * @param array $image_list Array of images.
490 * @param array $image_booleans Image booleans.
491 *
492 * @return array|array[]
493 */
494 public static function build_image_struct( $image_list, $image_booleans ) {
495 if ( ! empty( $image_list ) ) {
496 $retval = array( 'image' => array() );
497 $image_list = array_unique( $image_list, SORT_REGULAR );
498 foreach ( $image_list as $img ) {
499 if ( is_string( $img ) ) {
500 $retval['image'][] = array( 'url' => $img );
501 } else {
502 $retval['image'][] = $img;
503 }
504 }
505 $image_booleans['image'] = count( $retval['image'] );
506 if ( ! empty( $image_booleans ) ) {
507 $retval['has'] = $image_booleans;
508 }
509 return $retval;
510 } else {
511 return array();
512 }
513 }
514
515 /**
516 * Extracts images from html.
517 *
518 * @param string $html Some markup, possibly containing image tags.
519 * @param array $images_already_extracted (just an array of image URLs without query strings, no special structure), used for de-duplication.
520 * @param boolean $extract_alt_text Should alt_text be extracted, defaults to false.
521 *
522 * @return array Image URLs extracted from the HTML, stripped of query params and de-duped
523 */
524 public static function get_images_from_html( $html, $images_already_extracted, $extract_alt_text = false ) {
525 $image_list = $images_already_extracted;
526 $from_html = Jetpack_PostImages::from_html( $html );
527 // early return if no image in html.
528 if ( empty( $from_html ) ) {
529 return $image_list;
530 }
531 // process images.
532 foreach ( $from_html as $extracted_image ) {
533 $image_url = $extracted_image['src'];
534 $length = strpos( $image_url, '?' );
535 $src = wp_parse_url( $image_url );
536
537 if ( $src && isset( $src['scheme'] ) && isset( $src['host'] ) && isset( $src['path'] ) ) {
538 // Rebuild the URL without the query string.
539 $queryless = $src['scheme'] . '://' . $src['host'] . $src['path'];
540 } elseif ( $length ) {
541 // If wp_parse_url() didn't work, strip off the query string the old fashioned way.
542 $queryless = substr( $image_url, 0, $length );
543 } else {
544 // Failing that, there was no spoon! Err ... query string!
545 $queryless = $image_url;
546 }
547
548 // Discard URLs that are longer then 4KB, these are likely data URIs or malformed HTML.
549 if ( 4096 < strlen( $queryless ) ) {
550 continue;
551 }
552
553 if ( ! in_array( $queryless, $image_list, true ) ) {
554 $image_to_add = array(
555 'url' => $queryless,
556 );
557 if ( $extract_alt_text ) {
558 if ( ! empty( $extracted_image['alt_text'] ) ) {
559 $image_to_add['alt_text'] = $extracted_image['alt_text'];
560 }
561 if ( ! empty( $extracted_image['src_width'] ) || ! empty( $extracted_image['src_height'] ) ) {
562 $image_to_add['src_width'] = $extracted_image['src_width'];
563 $image_to_add['src_height'] = $extracted_image['src_height'];
564 }
565 } else {
566 $image_to_add = $queryless;
567 }
568 $image_list[] = $image_to_add;
569 }
570 }
571 return $image_list;
572 }
573
574 /**
575 * Strips concents of all tags, shortcodes, and decodes HTML entities.
576 *
577 * @param string $content Original content.
578 *
579 * @return string Cleaned content.
580 */
581 private static function get_stripped_content( $content ) {
582 $clean_content = wp_strip_all_tags( $content );
583 $clean_content = html_entity_decode( $clean_content, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
584 // completely strip shortcodes and any content they enclose.
585 $clean_content = strip_shortcodes( $clean_content );
586 return $clean_content;
587 }
588 }
589