PageRenderTime 49ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/jetpack/class.jetpack-post-images.php

https://gitlab.com/juanito.abelo/nlmobile
PHP | 505 lines | 381 code | 58 blank | 66 comment | 60 complexity | ff1410437d19c43dc170faa044800969 MD5 | raw file
  1. <?php
  2. /**
  3. * Useful for finding an image to display alongside/in representation of a specific post.
  4. *
  5. * Includes a few different methods, all of which return a similar-format array containing
  6. * details of any images found. Everything can (should) be called statically, it's just a
  7. * function-bucket. You can also call Jetpack_PostImages::get_image() to cycle through all of the methods until
  8. * one of them finds something useful.
  9. *
  10. * This file is included verbatim in Jetpack
  11. */
  12. class Jetpack_PostImages {
  13. /**
  14. * If a slideshow is embedded within a post, then parse out the images involved and return them
  15. */
  16. static function from_slideshow( $post_id, $width = 200, $height = 200 ) {
  17. $images = array();
  18. $post = get_post( $post_id );
  19. if ( !empty( $post->post_password ) )
  20. return $images;
  21. if ( false === has_shortcode( $post->post_content, 'slideshow' ) ) {
  22. return false; // no slideshow - bail
  23. }
  24. $permalink = get_permalink( $post->ID );
  25. // Mechanic: Somebody set us up the bomb
  26. $old_post = $GLOBALS['post'];
  27. $GLOBALS['post'] = $post;
  28. $old_shortcodes = $GLOBALS['shortcode_tags'];
  29. $GLOBALS['shortcode_tags'] = array( 'slideshow' => $old_shortcodes['slideshow'] );
  30. // Find all the slideshows
  31. preg_match_all( '/' . get_shortcode_regex() . '/sx', $post->post_content, $slideshow_matches, PREG_SET_ORDER );
  32. ob_start(); // The slideshow shortcode handler calls wp_print_scripts and wp_print_styles... not too happy about that
  33. foreach ( $slideshow_matches as $slideshow_match ) {
  34. $slideshow = do_shortcode_tag( $slideshow_match );
  35. if ( false === $pos = stripos( $slideshow, 'slideShow.images' ) ) // must be something wrong - or we changed the output format in which case none of the following will work
  36. continue;
  37. $start = strpos( $slideshow, '[', $pos );
  38. $end = strpos( $slideshow, ']', $start );
  39. $post_images = json_decode( str_replace( "'", '"', substr( $slideshow, $start, $end - $start + 1 ) ) ); // parse via JSON
  40. foreach ( $post_images as $post_image ) {
  41. if ( !$post_image_id = absint( $post_image->id ) )
  42. continue;
  43. $meta = wp_get_attachment_metadata( $post_image_id );
  44. // Must be larger than 200x200 (or user-specified)
  45. if ( !isset( $meta['width'] ) || $meta['width'] < $width )
  46. continue;
  47. if ( !isset( $meta['height'] ) || $meta['height'] < $height )
  48. continue;
  49. $url = wp_get_attachment_url( $post_image_id );
  50. $images[] = array(
  51. 'type' => 'image',
  52. 'from' => 'slideshow',
  53. 'src' => $url,
  54. 'src_width' => $meta['width'],
  55. 'src_height' => $meta['height'],
  56. 'href' => $permalink,
  57. );
  58. }
  59. }
  60. ob_end_clean();
  61. // Operator: Main screen turn on
  62. $GLOBALS['shortcode_tags'] = $old_shortcodes;
  63. $GLOBALS['post'] = $old_post;
  64. return $images;
  65. }
  66. /**
  67. * If a gallery is detected, then get all the images from it.
  68. */
  69. static function from_gallery( $post_id ) {
  70. $images = array();
  71. $post = get_post( $post_id );
  72. if ( !empty( $post->post_password ) )
  73. return $images;
  74. if ( false === has_shortcode( $post->post_content, 'gallery' ) ) {
  75. return false; // no gallery - bail
  76. }
  77. $permalink = get_permalink( $post->ID );
  78. // CATS: All your base are belong to us
  79. $old_post = $GLOBALS['post'];
  80. $GLOBALS['post'] = $post;
  81. $old_shortcodes = $GLOBALS['shortcode_tags'];
  82. $GLOBALS['shortcode_tags'] = array( 'gallery' => $old_shortcodes['gallery'] );
  83. // Find all the galleries
  84. preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $gallery_matches, PREG_SET_ORDER );
  85. foreach ( $gallery_matches as $gallery_match ) {
  86. $gallery = do_shortcode_tag( $gallery_match );
  87. // Um... no images in the gallery - bail
  88. if ( false === $pos = stripos( $gallery, '<img' ) )
  89. continue;
  90. preg_match_all( '/<img\s+[^>]*src=([\'"])([^\'"]*)\\1/', $gallery, $image_match, PREG_PATTERN_ORDER | PREG_OFFSET_CAPTURE );
  91. $a_pos = 0;
  92. foreach ( $image_match[2] as $src ) {
  93. list( $raw_src ) = explode( '?', $src[0] ); // pull off any Query string (?w=250)
  94. $raw_src = wp_specialchars_decode( $raw_src ); // rawify it
  95. $raw_src = esc_url_raw( $raw_src ); // clean it
  96. $a_pos = strrpos( substr( $gallery, 0, $src[1] ), '<a', $a_pos ); // is there surrounding <a>?
  97. if ( false !== $a_pos && preg_match( '/<a\s+[^>]*href=([\'"])([^\'"]*)\\1/', $gallery, $href_match, 0, $a_pos ) ) {
  98. $href = wp_specialchars_decode( $href_match[2] );
  99. $href = esc_url_raw( $href );
  100. } else {
  101. // CATS: You have no chance to survive make your time
  102. $href = $raw_src;
  103. }
  104. $a_pos = $src[1];
  105. $images[] = array(
  106. 'type' => 'image',
  107. 'from' => 'gallery',
  108. 'src' => $raw_src,
  109. 'href' => $permalink, // $href,
  110. );
  111. }
  112. }
  113. // Captain: For great justice
  114. $GLOBALS['shortcode_tags'] = $old_shortcodes;
  115. $GLOBALS['post'] = $old_post;
  116. return $images;
  117. }
  118. /**
  119. * Get attachment images for a specified post and return them. Also make sure
  120. * their dimensions are at or above a required minimum.
  121. */
  122. static function from_attachment( $post_id, $width = 200, $height = 200 ) {
  123. $images = array();
  124. $post = get_post( $post_id );
  125. if ( !empty( $post->post_password ) )
  126. return $images;
  127. $post_images = get_posts( array(
  128. 'post_parent' => $post_id, // Must be children of post
  129. 'numberposts' => 5, // No more than 5
  130. 'post_type' => 'attachment', // Must be attachments
  131. 'post_mime_type' => 'image', // Must be images
  132. ) );
  133. if ( !$post_images )
  134. return false;
  135. $permalink = get_permalink( $post_id );
  136. foreach ( $post_images as $post_image ) {
  137. $meta = wp_get_attachment_metadata( $post_image->ID );
  138. // Must be larger than 200x200
  139. if ( !isset( $meta['width'] ) || $meta['width'] < $width )
  140. continue;
  141. if ( !isset( $meta['height'] ) || $meta['height'] < $height )
  142. continue;
  143. $url = wp_get_attachment_url( $post_image->ID );
  144. $images[] = array(
  145. 'type' => 'image',
  146. 'from' => 'attachment',
  147. 'src' => $url,
  148. 'src_width' => $meta['width'],
  149. 'src_height' => $meta['height'],
  150. 'href' => $permalink,
  151. );
  152. }
  153. /*
  154. * We only want to pass back attached images that were actually inserted.
  155. * We can load up all the images found in the HTML source and then
  156. * compare URLs to see if an image is attached AND inserted.
  157. */
  158. $html_images = self::from_html( $post_id );
  159. $inserted_images = array();
  160. foreach( $html_images as $html_image ) {
  161. $src = parse_url( $html_image['src'] );
  162. // strip off any query strings from src
  163. if( ! empty( $src['scheme'] ) && ! empty( $src['host'] ) ) {
  164. $inserted_images[] = $src['scheme'] . '://' . $src['host'] . $src['path'];
  165. } elseif( ! empty( $src['host'] ) ) {
  166. $inserted_images[] = set_url_scheme( 'http://' . $src['host'] . $src['path'] );
  167. } else {
  168. $inserted_images[] = site_url( '/' ) . $src['path'];
  169. }
  170. }
  171. foreach( $images as $i => $image ) {
  172. if ( !in_array( $image['src'], $inserted_images ) )
  173. unset( $images[$i] );
  174. }
  175. return $images;
  176. }
  177. /**
  178. * Check if a Featured Image is set for this post, and return it in a similar
  179. * format to the other images?_from_*() methods.
  180. * @param int $post_id The post ID to check
  181. * @return Array containing details of the Featured Image, or empty array if none.
  182. */
  183. static function from_thumbnail( $post_id, $width = 200, $height = 200 ) {
  184. $images = array();
  185. $post = get_post( $post_id );
  186. if ( !empty( $post->post_password ) )
  187. return $images;
  188. if ( !function_exists( 'get_post_thumbnail_id' ) )
  189. return $images;
  190. $thumb = get_post_thumbnail_id( $post_id );
  191. if ( $thumb ) {
  192. $meta = wp_get_attachment_metadata( $thumb );
  193. // Must be larger than requested minimums
  194. if ( !isset( $meta['width'] ) || $meta['width'] < $width )
  195. return $images;
  196. if ( !isset( $meta['height'] ) || $meta['height'] < $height )
  197. return $images;
  198. $too_big = ( ( ! empty( $meta['width'] ) && $meta['width'] > 1200 ) || ( ! empty( $meta['height'] ) && $meta['height'] > 1200 ) );
  199. if ( $too_big ) {
  200. $img_src = wp_get_attachment_image_src( $thumb, array( 1200, 1200 ) );
  201. } else {
  202. $img_src = wp_get_attachment_image_src( $thumb, 'full' );
  203. }
  204. $url = $img_src[0];
  205. $images = array( array( // Other methods below all return an array of arrays
  206. 'type' => 'image',
  207. 'from' => 'thumbnail',
  208. 'src' => $url,
  209. 'src_width' => $img_src[1],
  210. 'src_height' => $img_src[2],
  211. 'href' => get_permalink( $thumb ),
  212. ) );
  213. }
  214. return $images;
  215. }
  216. /**
  217. * Very raw -- just parse the HTML and pull out any/all img tags and return their src
  218. * @param mixed $html_or_id The HTML string to parse for images, or a post id
  219. * @return Array containing images
  220. */
  221. static function from_html( $html_or_id ) {
  222. $images = array();
  223. if ( is_numeric( $html_or_id ) ) {
  224. $post = get_post( $html_or_id );
  225. if ( empty( $post ) || !empty( $post->post_password ) )
  226. return $images;
  227. $html = $post->post_content; // DO NOT apply the_content filters here, it will cause loops
  228. } else {
  229. $html = $html_or_id;
  230. }
  231. if ( !$html )
  232. return $images;
  233. preg_match_all( '!<img.*src=[\'"]([^"]+)[\'"].*/?>!iUs', $html, $matches );
  234. if ( !empty( $matches[1] ) ) {
  235. foreach ( $matches[1] as $match ) {
  236. if ( stristr( $match, '/smilies/' ) )
  237. continue;
  238. $images[] = array(
  239. 'type' => 'image',
  240. 'from' => 'html',
  241. 'src' => html_entity_decode( $match ),
  242. 'href' => '', // No link to apply to these. Might potentially parse for that as well, but not for now
  243. );
  244. }
  245. }
  246. return $images;
  247. }
  248. /**
  249. * @param int $post_id The post ID to check
  250. * @param int $size
  251. * @return Array containing details of the image, or empty array if none.
  252. */
  253. static function from_blavatar( $post_id, $size = 96 ) {
  254. $permalink = get_permalink( $post_id );
  255. if ( function_exists( 'jetpack_has_site_icon' ) && jetpack_has_site_icon() ) {
  256. $url = jetpack_site_icon_url( null, $size, $default = false );
  257. } elseif ( function_exists( 'blavatar_domain' ) && function_exists( 'blavatar_exists' ) && function_exists( 'blavatar_url' ) ) {
  258. $domain = blavatar_domain( $permalink );
  259. if ( ! blavatar_exists( $domain ) ) {
  260. return array();
  261. }
  262. $url = blavatar_url( $domain, 'img', $size );
  263. }
  264. return array( array(
  265. 'type' => 'image',
  266. 'from' => 'blavatar',
  267. 'src' => $url,
  268. 'src_width' => $size,
  269. 'src_height' => $size,
  270. 'href' => $permalink,
  271. ) );
  272. }
  273. /**
  274. * @param int $post_id The post ID to check
  275. * @param int $size
  276. * @param string $default The default image to use.
  277. * @return Array containing details of the image, or empty array if none.
  278. */
  279. static function from_gravatar( $post_id, $size = 96, $default = false ) {
  280. $post = get_post( $post_id );
  281. $permalink = get_permalink( $post_id );
  282. if ( function_exists( 'get_avatar_url' ) ) {
  283. $url = get_avatar_url( $post->post_author, $size, $default, true );
  284. if ( $url && is_array( $url ) ) {
  285. $url = $url[0];
  286. }
  287. } else {
  288. $has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
  289. if ( !$has_filter ) {
  290. add_filter( 'pre_option_show_avatars', '__return_true' );
  291. }
  292. $avatar = get_avatar( $post->post_author, $size, $default );
  293. if ( !$has_filter ) {
  294. remove_filter( 'pre_option_show_avatars', '__return_true' );
  295. }
  296. if ( !$avatar ) {
  297. return array();
  298. }
  299. if ( !preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $matches ) ) {
  300. return array();
  301. }
  302. $url = wp_specialchars_decode( $matches[1], ENT_QUOTES );
  303. }
  304. return array( array(
  305. 'type' => 'image',
  306. 'from' => 'gravatar',
  307. 'src' => $url,
  308. 'src_width' => $size,
  309. 'src_height' => $size,
  310. 'href' => $permalink,
  311. ) );
  312. }
  313. /**
  314. * Run through the different methods that we have available to try to find a single good
  315. * display image for this post.
  316. * @param int $post_id
  317. * @param array $args Other arguments (currently width and height required for images where possible to determine)
  318. * @return Array containing details of the best image to be used
  319. */
  320. static function get_image( $post_id, $args = array() ) {
  321. $image = '';
  322. do_action( 'jetpack_postimages_pre_get_image', $post_id );
  323. $media = self::get_images( $post_id, $args );
  324. if ( is_array( $media ) ) {
  325. foreach ( $media as $item ) {
  326. if ( 'image' == $item['type'] ) {
  327. $image = $item;
  328. break;
  329. }
  330. }
  331. }
  332. do_action( 'jetpack_postimages_post_get_image', $post_id );
  333. return $image;
  334. }
  335. /**
  336. * Get an array containing a collection of possible images for this post, stopping once we hit a method
  337. * that returns something useful.
  338. * @param int $post_id
  339. * @param array $args Optional args, see defaults list for details
  340. * @return Array containing images that would be good for representing this post
  341. */
  342. static function get_images( $post_id, $args = array() ) {
  343. // Figure out which image to attach to this post.
  344. $media = false;
  345. $media = apply_filters( 'jetpack_images_pre_get_images', $media, $post_id, $args );
  346. if ( $media )
  347. return $media;
  348. $defaults = array(
  349. 'width' => 200, // Required minimum width (if possible to determine)
  350. 'height' => 200, // Required minimum height (if possible to determine)
  351. 'fallback_to_avatars' => false, // Optionally include Blavatar and Gravatar (in that order) in the image stack
  352. 'avatar_size' => 96, // Used for both Grav and Blav
  353. 'gravatar_default' => false, // Default image to use if we end up with no Gravatar
  354. 'from_thumbnail' => true, // Use these flags to specifcy which methods to use to find an image
  355. 'from_slideshow' => true,
  356. 'from_gallery' => true,
  357. 'from_attachment' => true,
  358. 'from_html' => true,
  359. 'html_content' => '' // HTML string to pass to from_html()
  360. );
  361. $args = wp_parse_args( $args, $defaults );
  362. $media = false;
  363. if ( $args['from_thumbnail'] )
  364. $media = self::from_thumbnail( $post_id, $args['width'], $args['height'] );
  365. if ( !$media && $args['from_slideshow'] )
  366. $media = self::from_slideshow( $post_id, $args['width'], $args['height'] );
  367. if ( !$media && $args['from_gallery'] )
  368. $media = self::from_gallery( $post_id );
  369. if ( !$media && $args['from_attachment'] )
  370. $media = self::from_attachment( $post_id, $args['width'], $args['height'] );
  371. if ( !$media && $args['from_html'] ) {
  372. if ( empty( $args['html_content'] ) )
  373. $media = self::from_html( $post_id ); // Use the post_id, which will load the content
  374. else
  375. $media = self::from_html( $args['html_content'] ); // If html_content is provided, use that
  376. }
  377. if ( !$media && $args['fallback_to_avatars'] ) {
  378. $media = self::from_blavatar( $post_id, $args['avatar_size'] );
  379. if ( !$media )
  380. $media = self::from_gravatar( $post_id, $args['avatar_size'], $args['gravatar_default'] );
  381. }
  382. return apply_filters( 'jetpack_images_get_images', $media, $post_id, $args );
  383. }
  384. /**
  385. * Takes an image URL and pixel dimensions then returns a URL for the
  386. * resized and croped image.
  387. *
  388. * @param string $src
  389. * @param int $dimension
  390. * @return string Transformed image URL
  391. */
  392. static function fit_image_url( $src, $width, $height ) {
  393. $width = (int) $width;
  394. $height = (int) $height;
  395. // Umm...
  396. if ( $width < 1 || $height < 1 ) {
  397. return $src;
  398. }
  399. // See if we should bypass WordPress.com SaaS resizing
  400. if ( has_filter( 'jetpack_images_fit_image_url_override' ) ) {
  401. return apply_filters( 'jetpack_images_fit_image_url_override', $src, $width, $height );
  402. }
  403. // If WPCOM hosted image use native transformations
  404. $img_host = parse_url( $src, PHP_URL_HOST );
  405. if ( '.files.wordpress.com' == substr( $img_host, -20 ) ) {
  406. return add_query_arg( array( 'w' => $width, 'h' => $height, 'crop' => 1 ), $src );
  407. }
  408. // Use Photon magic
  409. if( function_exists( 'jetpack_photon_url' ) ) {
  410. return jetpack_photon_url( $src, array( 'resize' => "$width,$height" ) );
  411. }
  412. // Arg... no way to resize image using WordPress.com infrastructure!
  413. return $src;
  414. }
  415. }