PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 2.7.5
Jetpack – WP Security, Backup, Speed, & Growth v2.7.5
16.2-beta 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 All 501 releases
jetpack / class.media-extractor.php

class.media-extractor.php in Jetpack – WP Security, Backup, Speed, & Growth 2.7.5, at class.media-extractor.php

407 lines 15.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
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 * @todo Additionally, have some filters on number of items in each field
7 */
8 class Jetpack_Media_Meta_Extractor {
9
10 // Some consts for what to extract
11 const ALL = 255;
12 const LINKS = 1;
13 const MENTIONS = 2;
14 const IMAGES = 4;
15 const SHORTCODES = 8; // Only the keeper shortcodes below
16 const EMBEDS = 16;
17 const HASHTAGS = 32;
18
19 // For these, we try to extract some data from the shortcode, rather than just recording its presence (which we do for all)
20 // There should be a function get_{shortcode}_id( $atts ) or static method SomethingShortcode::get_{shortcode}_id( $atts ) for these.
21 private static $KEEPER_SHORTCODES = array(
22 'youtube',
23 'vimeo',
24 'hulu',
25 'ted',
26 'audio',
27 'wpvideo',
28 );
29
30 /**
31 * Gets the specified media and meta info from the given post.
32 * NOTE: If you have the post's HTML content already and don't need image data, use extract_from_content() instead.
33 *
34 * @param $blog_id The ID of the blog
35 * @param $post_id The ID of the post
36 * @param $what_to_extract (int) A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS
37 * @returns a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error
38 */
39 static public function extract( $blog_id, $post_id, $what_to_extract = self::ALL ) {
40
41 // multisite?
42 if ( function_exists( 'switch_to_blog') )
43 switch_to_blog( $blog_id );
44
45 $post = get_post( $post_id );
46 $content = $post->post_title . "\n\n" . $post->post_content;
47 $char_cnt = strlen( $content );
48
49 //prevent running extraction on really huge amounts of content
50 if ( $char_cnt > 100000 ) //about 20k English words
51 $content = substr( $content, 0, 100000 );
52
53 $extracted = array();
54
55 // Get images first, we need the full post for that
56 if ( self::IMAGES & $what_to_extract ) {
57 $extracted = self::get_image_fields( $post );
58
59 // Turn off images so we can safely call extract_from_content() below
60 $what_to_extract = $what_to_extract - self::IMAGES;
61 }
62
63 if ( function_exists( 'switch_to_blog') )
64 restore_current_blog();
65
66 // All of the other things besides images can be extracted from just the content
67 $extracted = self::extract_from_content( $content, $what_to_extract, $extracted );
68
69 return $extracted;
70 }
71
72 /**
73 * Gets the specified meta info from the given post content.
74 * NOTE: If you want IMAGES, call extract( $blog_id, $post_id, ...) which will give you more/better image extraction
75 * This method will give you an error if you ask for IMAGES.
76 *
77 * @param $content The HTML post_content of a post
78 * @param $what_to_extract (int) A mask of things to extract, e.g. Jetpack_Media_Meta_Extractor::IMAGES | Jetpack_Media_Meta_Extractor::MENTIONS
79 * @param $already_extracted (array) Previously extracted things, e.g. images from extract(), which can be used for x-referencing here
80 * @returns a structure containing metadata about the embedded things, or empty array if nothing found, or WP_Error on error
81 */
82 static public function extract_from_content( $content, $what_to_extract = self::ALL, $already_extracted = array() ) {
83 $stripped_content = self::get_stripped_content( $content );
84
85 // Maybe start wtih some previously extracted things (e.g. images from extract()
86 $extracted = $already_extracted;
87
88 // Embedded media objects will have already been converted to shortcodes by pre_kses hooks on save.
89
90 if ( self::IMAGES & $what_to_extract ) {
91 // Should've called extract( $blog_id, $post_id ) if you want images
92 return new WP_Error( 'media-extraction-error', "IMAGES extraction not supported in extract_from_content()" );
93 }
94
95 // ----------------------------------- MENTIONS ------------------------------
96
97 if ( self::MENTIONS & $what_to_extract ) {
98 if ( preg_match_all( '/(^|\s)@(\w+)/u', $stripped_content, $matches ) ) {
99 $mentions = array_values( array_unique( $matches[2] ) ); //array_unique() retains the keys!
100 $mentions = array_map( 'strtolower', $mentions );
101 $extracted['mention'] = array( 'name' => $mentions );
102 if ( !isset( $extracted['has'] ) )
103 $extracted['has'] = array();
104 $extracted['has']['mention'] = count( $mentions );
105 }
106 }
107
108 // ----------------------------------- HASHTAGS ------------------------------
109 /* Some hosts may not compile with --enable-unicode-properties and kick a warning
110 Warning: preg_match_all() [function.preg-match-all]: Compilation failed: support for \P, \p, and \X has not been compiled
111 if ( self::HASHTAGS & $what_to_extract ) {
112 //This regex does not exactly match Twitter's
113 // if there are problems/complaints we should implement this:
114 // https://github.com/twitter/twitter-text-java/blob/master/src/com/twitter/Regex.java
115 if ( preg_match_all( '/(?:^|\s)#(\w*\p{L}+\w*)/u', $stripped_content, $matches ) ) {
116 $hashtags = array_values( array_unique( $matches[1] ) ); //array_unique() retains the keys!
117 $hashtags = array_map( 'strtolower', $hashtags );
118 $extracted['hashtag'] = array( 'name' => $hashtags );
119 if ( !isset( $extracted['has'] ) )
120 $extracted['has'] = array();
121 $extracted['has']['hashtag'] = count( $hashtags );
122 }
123 }
124 */
125 // ----------------------------------- SHORTCODES ------------------------------
126
127 // Always look for shortcodes.
128 // If we don't want them, we'll just remove them, so we don't grab them as links below
129 $shortcode_pattern = '/' . get_shortcode_regex() . '/s';
130 if ( preg_match_all( $shortcode_pattern, $content, $matches ) ) {
131
132 $shortcode_total_count = 0;
133 $shortcode_type_counts = array();
134 $shortcode_types = array();
135 $shortcode_details = array();
136
137 if ( self::SHORTCODES & $what_to_extract ) {
138
139 foreach( $matches[2] as $key => $shortcode ) {
140 //Elasticsearch (and probably other things) doesn't deal well with some chars as key names
141 $shortcode_name = preg_replace( '/[.,*"\'\/\\\\#+ ]/', '_', $shortcode );
142
143 $attr = shortcode_parse_atts( $matches[3][ $key ] );
144
145 $shortcode_total_count++;
146 if ( ! isset( $shortcode_type_counts[$shortcode_name] ) )
147 $shortcode_type_counts[$shortcode_name] = 0;
148 $shortcode_type_counts[$shortcode_name]++;
149
150 // Store (uniquely) presence of all shortcode regardless of whether it's a keeper (for those, get ID below)
151 // @todo Store number of occurrences?
152 if ( ! in_array( $shortcode_name, $shortcode_types ) )
153 $shortcode_types[] = $shortcode_name;
154
155 // For keeper shortcodes, also store the id/url of the object (e.g. youtube video, TED talk, etc.)
156 if ( in_array( $shortcode, self::$KEEPER_SHORTCODES ) ) {
157 unset( $id ); // Clear shortcode ID data left from the last shortcode
158 // We'll try to get the salient ID from the function jetpack_shortcode_get_xyz_id()
159 // If the shortcode is a class, we'll call XyzShortcode::get_xyz_id()
160 $shortcode_get_id_func = "jetpack_shortcode_get_{$shortcode}_id";
161 $shortcode_class_name = ucfirst( $shortcode ) . 'Shortcode';
162 $shortcode_get_id_method = "get_{$shortcode}_id";
163 if ( function_exists( $shortcode_get_id_func ) ) {
164 $id = call_user_func( $shortcode_get_id_func, $attr );
165 } else if ( method_exists( $shortcode_class_name, $shortcode_get_id_method ) ) {
166 $id = call_user_func( array( $shortcode_class_name, $shortcode_get_id_method ), $attr );
167 }
168 if ( ! empty( $id )
169 && ( ! isset( $shortcode_details[$shortcode_name] ) || ! in_array( $id, $shortcode_details[$shortcode_name] ) ) )
170 $shortcode_details[$shortcode_name][] = $id;
171 }
172 }
173
174 if ( $shortcode_total_count > 0 ) {
175 // Add the shortcode info to the $extracted array
176 if ( !isset( $extracted['has'] ) )
177 $extracted['has'] = array();
178 $extracted['has']['shortcode'] = $shortcode_total_count;
179 $extracted['shortcode'] = array();
180 foreach ( $shortcode_type_counts as $type => $count )
181 $extracted['shortcode'][$type] = array( 'count' => $count );
182 if ( ! empty( $shortcode_types ) )
183 $extracted['shortcode_types'] = $shortcode_types;
184 foreach ( $shortcode_details as $type => $id )
185 $extracted['shortcode'][$type]['id'] = $id;
186 }
187 }
188
189 // Remove the shortcodes form our copy of $content, so we don't count links in them as links below.
190 $content = preg_replace( $shortcode_pattern, ' ', $content );
191 }
192
193 // ----------------------------------- LINKS ------------------------------
194
195 if ( self::LINKS & $what_to_extract ) {
196
197 // To hold the extracted stuff we find
198 $links = array();
199
200 // @todo Get the text inside the links?
201
202 // Grab any links, whether in <a href="..." or not, but subtract those from shortcodes and images
203 // (we treat embed links as just another link)
204 if ( preg_match_all( '#(?:^|\s|"|\')(https?://([^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))))#', $content, $matches ) ) {
205
206 foreach ( $matches[1] as $link_raw ) {
207 $url = parse_url( $link_raw );
208
209 // Build a simple form of the URL so we can compare it to ones we found in IMAGES or SHORTCODES and exclude those
210 $simple_url = $url['scheme'] . '://' . $url['host'] . ( ! empty( $url['path'] ) ? $url['path'] : '' );
211 if ( isset( $extracted['image']['url'] ) ) {
212 if ( in_array( $simple_url, (array) $extracted['image']['url'] ) )
213 continue;
214 }
215
216 list( $proto, $link_all_but_proto ) = explode( '://', $link_raw );
217
218 // Build a reversed hostname
219 $host_parts = array_reverse( explode( '.', $url['host'] ) );
220 $host_reversed = '';
221 foreach ( $host_parts as $part ) {
222 $host_reversed .= ( ! empty( $host_reversed ) ? '.' : '' ) . $part;
223 }
224
225 $link_analyzed = '';
226 if ( !empty( $url['path'] ) ) {
227 // The whole path (no query args or fragments)
228 $path = substr( $url['path'], 1 ); // strip the leading '/'
229 $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $path;
230
231 // The path split by /
232 $path_split = explode( '/', $path );
233 if ( count( $path_split ) > 1 ) {
234 $link_analyzed .= ' ' . implode( ' ', $path_split );
235 }
236
237 // The fragment
238 if ( ! empty( $url['fragment'] ) )
239 $link_analyzed .= ( ! empty( $link_analyzed ) ? ' ' : '' ) . $url['fragment'];
240 }
241
242 // @todo Check unique before adding
243 $links[] = array(
244 'url' => $link_all_but_proto,
245 'host_reversed' => $host_reversed,
246 'host' => $url['host'],
247 );
248 }
249
250 }
251
252 $link_count = count( $links );
253 $extracted['link'] = $links;
254 if ( $link_count ) {
255 if ( !isset( $extracted['has'] ) )
256 $extracted['has'] = array();
257 $extracted['has']['link'] = $link_count;
258 }
259 }
260
261 // ----------------------------------- EMBEDS ------------------------------
262
263 //Embeds are just individual links on their own line
264 if ( self::EMBEDS & $what_to_extract ) {
265
266 if ( !function_exists( '_wp_oembed_get_object' ) )
267 include( ABSPATH . WPINC . '/class-oembed.php' );
268
269 // get an oembed object
270 $oembed = _wp_oembed_get_object();
271
272 // Grab any links on their own lines that may be embeds
273 if ( preg_match_all( '|^\s*(https?://[^\s"]+)\s*$|im', $content, $matches ) ) {
274
275 // To hold the extracted stuff we find
276 $embeds = array();
277
278 foreach ( $matches[1] as $link_raw ) {
279 $url = parse_url( $link_raw );
280
281 list( $proto, $link_all_but_proto ) = explode( '://', $link_raw );
282
283 // Check whether this "link" is really an embed.
284 foreach ( $oembed->providers as $matchmask => $data ) {
285 list( $providerurl, $regex ) = $data;
286
287 // Turn the asterisk-type provider URLs into regex
288 if ( !$regex ) {
289 $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i';
290 $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask );
291 }
292
293 if ( preg_match( $matchmask, $link_raw ) ) {
294 $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML
295 $embeds[] = $link_all_but_proto; // @todo Check unique before adding
296
297 // @todo Try to get ID's for the ones we care about (shortcode_keepers)
298 break;
299 }
300 }
301 }
302
303 if ( ! empty( $embeds ) ) {
304 if ( !isset( $extracted['has'] ) )
305 $extracted['has'] = array();
306 $extracted['has']['embed'] = count( $embeds );
307 $extracted['embed'] = array( 'url' => array() );
308 foreach ( $embeds as $e )
309 $extracted['embed']['url'][] = $e;
310 }
311 }
312 }
313
314 return $extracted;
315 }
316
317 /**
318 * @param $post A post object
319 * @param $args (array) Optional args, see defaults list for details
320 * @returns array Returns an array of all images meeting the specified criteria in $args
321 *
322 * Uses Jetpack Post Images
323 */
324 private static function get_image_fields( $post, $args = array() ) {
325
326 $defaults = array(
327 'width' => 200, // Required minimum width (if possible to determine)
328 'height' => 200, // Required minimum height (if possible to determine)
329 );
330
331 $args = wp_parse_args( $args, $defaults );
332
333 $image_list = array();
334 $image_booleans = array();
335 $image_booleans['gallery'] = 0;
336
337 $from_slideshow = Jetpack_PostImages::from_slideshow( $post->ID, $args['width'], $args['height'] );
338 if ( !empty( $from_slideshow ) ) {
339 $srcs = wp_list_pluck( $from_slideshow, 'src' );
340 $image_list = array_merge( $image_list, $srcs );
341 }
342
343 $from_gallery = Jetpack_PostImages::from_gallery( $post->ID );
344 if ( !empty( $from_gallery ) ) {
345 $srcs = wp_list_pluck( $from_gallery, 'src' );
346 $image_list = array_merge( $image_list, $srcs );
347 $image_booleans['gallery']++; // @todo This count isn't correct, will only every count 1
348 }
349
350 // @todo Can we check width/height of these efficiently? Could maybe use query args at least, before we strip them out
351 $image_list = Jetpack_Media_Meta_Extractor::get_images_from_html( $post->post_content, $image_list );
352
353 if ( ! empty( $image_list ) ) {
354 $retval = array( 'image' => array() );
355 $unique_imgs = array_unique( $image_list );
356 foreach ( $image_list as $img ) {
357 $retval['image'][] = array( 'url' => $img );
358 }
359 $image_booleans['image'] = count( $retval['image'] );
360 if ( ! empty( $image_booleans ) )
361 $retval['has'] = $image_booleans;
362 return $retval;
363 } else {
364 return array();
365 }
366 }
367
368 /**
369 *
370 * @param string $html Some markup, possibly containing image tags
371 * @param array $images_already_extracted (just an array of image URLs without query strings, no special structure), used for de-duplication
372 * @return array Image URLs extracted from the HTML, stripped of query params and de-duped
373 */
374 public static function get_images_from_html( $html, $images_already_extracted ) {
375 $image_list = $images_already_extracted;
376 $from_html = Jetpack_PostImages::from_html( $html );
377 if ( !empty( $from_html ) ) {
378 $srcs = wp_list_pluck( $from_html, 'src' );
379 foreach( $srcs as $image_url ) {
380 if ( $src = parse_url( $image_url ) ) {
381 // Rebuild the URL without the query string
382 $queryless = $src['scheme'] . '://' . $src['host'] . $src['path'];
383 } elseif ( $length = strpos( $image_url, '?' ) ) {
384 // If parse_url() didn't work, strip off theh query string the old fashioned way
385 $queryless = substr( $image_url, 0, $length );
386 } else {
387 // Failing that, there was no spoon! Err ... query string!
388 $queryless = $image_url;
389 }
390
391 if ( ! in_array( $queryless, $image_list ) ) {
392 $image_list[] = $queryless;
393 }
394 }
395 }
396 return $image_list;
397 }
398
399 private static function get_stripped_content( $content ) {
400 $clean_content = strip_tags( $content );
401 $clean_content = html_entity_decode( $clean_content );
402 //completely strip shortcodes and any content they enclose
403 $clean_content = strip_shortcodes( $clean_content );
404 return $clean_content;
405 }
406 }
407