PageRenderTime 27ms CodeModel.GetById 49ms RepoModel.GetById 2ms app.codeStats 0ms

/wp-content/plugins/jetpack/class.media-extractor.php

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