class-wpseo-image-utils.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO
  6. */
  7. /**
  8. * WPSEO_Image_Utils.
  9. */
  10. class WPSEO_Image_Utils {
  11. /**
  12. * Find an attachment ID for a given URL.
  13. *
  14. * @param string $url The URL to find the attachment for.
  15. *
  16. * @return int The found attachment ID, or 0 if none was found.
  17. */
  18. public static function get_attachment_by_url( $url ) {
  19. /*
  20. * As get_attachment_by_url won't work on resized versions of images,
  21. * we strip out the size part of an image URL.
  22. */
  23. $url = preg_replace( '/(.*)-\d+x\d+\.(jpg|png|gif)$/', '$1.$2', $url );
  24. // Don't try to do this for external URLs.
  25. if ( strpos( $url, get_site_url() ) !== 0 ) {
  26. return 0;
  27. }
  28. if ( function_exists( 'wpcom_vip_attachment_url_to_postid' ) ) {
  29. // @codeCoverageIgnoreStart -- We can't test this properly.
  30. return (int) wpcom_vip_attachment_url_to_postid( $url );
  31. // @codeCoverageIgnoreEnd -- The rest we _can_ test.
  32. }
  33. return self::attachment_url_to_postid( $url );
  34. }
  35. /**
  36. * Implements the attachment_url_to_postid with use of WP Cache.
  37. *
  38. * @param string $url The attachment URL for which we want to know the Post ID.
  39. *
  40. * @return int The Post ID belonging to the attachment, 0 if not found.
  41. */
  42. protected static function attachment_url_to_postid( $url ) {
  43. $cache_key = sprintf( 'yoast_attachment_url_post_id_%s', md5( $url ) );
  44. // Set the ID based on the hashed URL in the cache.
  45. $id = wp_cache_get( $cache_key );
  46. if ( $id === 'not_found' ) {
  47. return 0;
  48. }
  49. // ID is found in cache, return.
  50. if ( $id !== false ) {
  51. return $id;
  52. }
  53. // phpcs:ignore WordPress.VIP.RestrictedFunctions -- We use the WP COM version if we can, see above.
  54. $id = attachment_url_to_postid( $url );
  55. if ( empty( $id ) ) {
  56. wp_cache_set( $cache_key, 'not_found', '', ( 12 * HOUR_IN_SECONDS + wp_rand( 0, ( 4 * HOUR_IN_SECONDS ) ) ) );
  57. return 0;
  58. }
  59. // We have the Post ID, but it's not in the cache yet. We do that here and return.
  60. wp_cache_set( $cache_key, $id, '', ( 24 * HOUR_IN_SECONDS + wp_rand( 0, ( 12 * HOUR_IN_SECONDS ) ) ) );
  61. return $id;
  62. }
  63. /**
  64. * Retrieves the image data.
  65. *
  66. * @param array $image Image array with URL and metadata.
  67. * @param int $attachment_id Attachment ID.
  68. *
  69. * @return false|array $image {
  70. * Array of image data
  71. *
  72. * @type string $alt Image's alt text.
  73. * @type string $alt Image's alt text.
  74. * @type int $width Width of image.
  75. * @type int $height Height of image.
  76. * @type string $type Image's MIME type.
  77. * @type string $url Image's URL.
  78. * @type int $filesize The file size in bytes, if already set.
  79. * }
  80. */
  81. public static function get_data( $image, $attachment_id ) {
  82. if ( ! is_array( $image ) ) {
  83. return false;
  84. }
  85. // Deals with non-set keys and values being null or false.
  86. if ( empty( $image['width'] ) || empty( $image['height'] ) ) {
  87. return false;
  88. }
  89. $image['id'] = $attachment_id;
  90. $image['alt'] = self::get_alt_tag( $attachment_id );
  91. $image['pixels'] = ( (int) $image['width'] * (int) $image['height'] );
  92. if ( ! isset( $image['type'] ) ) {
  93. $image['type'] = get_post_mime_type( $attachment_id );
  94. }
  95. // Keep only the keys we need, and nothing else.
  96. return array_intersect_key( $image, array_flip( [ 'id', 'alt', 'path', 'width', 'height', 'pixels', 'type', 'size', 'url', 'filesize' ] ) );
  97. }
  98. /**
  99. * Checks a size version of an image to see if it's not too heavy.
  100. *
  101. * @param array $image Image to check the file size of.
  102. *
  103. * @return bool True when the image is within limits, false if not.
  104. */
  105. public static function has_usable_file_size( $image ) {
  106. if ( ! is_array( $image ) || $image === [] ) {
  107. return false;
  108. }
  109. /**
  110. * Filter: 'wpseo_image_image_weight_limit' - Determines what the maximum weight
  111. * (in bytes) of an image is allowed to be, default is 2 MB.
  112. *
  113. * @api int - The maximum weight (in bytes) of an image.
  114. */
  115. $max_size = apply_filters( 'wpseo_image_image_weight_limit', 2097152 );
  116. // We cannot check without a path, so assume it's fine.
  117. if ( ! isset( $image['path'] ) ) {
  118. return true;
  119. }
  120. return ( self::get_file_size( $image ) <= $max_size );
  121. }
  122. /**
  123. * Find the right version of an image based on size.
  124. *
  125. * @param int $attachment_id Attachment ID.
  126. * @param string $size Size name.
  127. *
  128. * @return array|false Returns an array with image data on success, false on failure.
  129. */
  130. public static function get_image( $attachment_id, $size ) {
  131. $image = false;
  132. if ( $size === 'full' ) {
  133. $image = self::get_full_size_image_data( $attachment_id );
  134. }
  135. if ( ! $image ) {
  136. $image = image_get_intermediate_size( $attachment_id, $size );
  137. $image['size'] = $size;
  138. }
  139. if ( ! $image ) {
  140. return false;
  141. }
  142. return self::get_data( $image, $attachment_id );
  143. }
  144. /**
  145. * Returns the image data for the full size image.
  146. *
  147. * @param int $attachment_id Attachment ID.
  148. *
  149. * @return array|false Array when there is a full size image. False if not.
  150. */
  151. protected static function get_full_size_image_data( $attachment_id ) {
  152. $image = wp_get_attachment_metadata( $attachment_id );
  153. if ( ! is_array( $image ) ) {
  154. return false;
  155. }
  156. $image['url'] = wp_get_attachment_image_url( $attachment_id, 'full' );
  157. $image['path'] = get_attached_file( $attachment_id );
  158. $image['size'] = 'full';
  159. return $image;
  160. }
  161. /**
  162. * Finds the full file path for a given image file.
  163. *
  164. * @param string $path The relative file path.
  165. *
  166. * @return string The full file path.
  167. */
  168. public static function get_absolute_path( $path ) {
  169. static $uploads;
  170. if ( $uploads === null ) {
  171. $uploads = wp_get_upload_dir();
  172. }
  173. // Add the uploads basedir if the path does not start with it.
  174. if ( empty( $uploads['error'] ) && strpos( $path, $uploads['basedir'] ) !== 0 ) {
  175. return $uploads['basedir'] . DIRECTORY_SEPARATOR . ltrim( $path, DIRECTORY_SEPARATOR );
  176. }
  177. return $path;
  178. }
  179. /**
  180. * Get the relative path of the image.
  181. *
  182. * @param string $img Image URL.
  183. *
  184. * @return string The expanded image URL.
  185. */
  186. public static function get_relative_path( $img ) {
  187. if ( $img[0] !== '/' ) {
  188. return $img;
  189. }
  190. // If it's a relative URL, it's relative to the domain, not necessarily to the WordPress install, we
  191. // want to preserve domain name and URL scheme (http / https) though.
  192. $parsed_url = wp_parse_url( home_url() );
  193. $img = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $img;
  194. return $img;
  195. }
  196. /**
  197. * Get the image file size.
  198. *
  199. * @param array $image An image array object.
  200. *
  201. * @return int The file size in bytes.
  202. */
  203. public static function get_file_size( $image ) {
  204. if ( isset( $image['filesize'] ) ) {
  205. return $image['filesize'];
  206. }
  207. // If the file size for the file is over our limit, we're going to go for a smaller version.
  208. // @todo Save the filesize to the image metadata.
  209. // phpcs:ignore Generic.PHP.NoSilencedErrors.Discouraged -- If file size doesn't properly return, we'll not fail.
  210. return @filesize( self::get_absolute_path( $image['path'] ) );
  211. }
  212. /**
  213. * Returns the different image variations for consideration.
  214. *
  215. * @param int $attachment_id The attachment to return the variations for.
  216. *
  217. * @return array The different variations possible for this attachment ID.
  218. */
  219. public static function get_variations( $attachment_id ) {
  220. $variations = [];
  221. foreach ( self::get_sizes() as $size ) {
  222. $variation = self::get_image( $attachment_id, $size );
  223. // The get_image function returns false if the size doesn't exist for this attachment.
  224. if ( $variation ) {
  225. $variations[] = $variation;
  226. }
  227. }
  228. return $variations;
  229. }
  230. /**
  231. * Check original size of image. If original image is too small, return false, else return true.
  232. *
  233. * Filters a list of variations by a certain set of usable dimensions.
  234. *
  235. * @param array $usable_dimensions {
  236. * The parameters to check against.
  237. *
  238. * @type int $min_width Minimum width of image.
  239. * @type int $max_width Maximum width of image.
  240. * @type int $min_height Minimum height of image.
  241. * @type int $max_height Maximum height of image.
  242. * }
  243. * @param array $variations The variations that should be considered.
  244. *
  245. * @return array Whether a variation is fit for display or not.
  246. */
  247. public static function filter_usable_dimensions( $usable_dimensions, $variations ) {
  248. $filtered = [];
  249. foreach ( $variations as $variation ) {
  250. $dimensions = $variation;
  251. if ( self::has_usable_dimensions( $dimensions, $usable_dimensions ) ) {
  252. $filtered[] = $variation;
  253. }
  254. }
  255. return $filtered;
  256. }
  257. /**
  258. * Filters a list of variations by (disk) file size.
  259. *
  260. * @param array $variations The variations to consider.
  261. *
  262. * @return array The validations that pass the required file size limits.
  263. */
  264. public static function filter_usable_file_size( $variations ) {
  265. foreach ( $variations as $variation ) {
  266. // We return early to prevent measuring the file size of all the variations.
  267. if ( self::has_usable_file_size( $variation ) ) {
  268. return [ $variation ];
  269. }
  270. }
  271. return [];
  272. }
  273. /**
  274. * Retrieve the internal WP image file sizes.
  275. *
  276. * @return array $image_sizes An array of image sizes.
  277. */
  278. public static function get_sizes() {
  279. /**
  280. * Filter: 'wpseo_image_sizes' - Determines which image sizes we'll loop through to get an appropriate image.
  281. *
  282. * @api array - The array of image sizes to loop through.
  283. */
  284. return apply_filters( 'wpseo_image_sizes', [ 'full', 'large', 'medium_large' ] );
  285. }
  286. /**
  287. * Grabs an image alt text.
  288. *
  289. * @param int $attachment_id The attachment ID.
  290. *
  291. * @return string The image alt text.
  292. */
  293. public static function get_alt_tag( $attachment_id ) {
  294. return (string) get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
  295. }
  296. /**
  297. * Checks whether an img sizes up to the parameters.
  298. *
  299. * @param array $dimensions The image values.
  300. * @param array $usable_dimensions The parameters to check against.
  301. *
  302. * @return bool True if the image has usable measurements, false if not.
  303. */
  304. private static function has_usable_dimensions( $dimensions, $usable_dimensions ) {
  305. foreach ( [ 'width', 'height' ] as $param ) {
  306. $minimum = $usable_dimensions[ 'min_' . $param ];
  307. $maximum = $usable_dimensions[ 'max_' . $param ];
  308. $current = $dimensions[ $param ];
  309. if ( ( $current < $minimum ) || ( $current > $maximum ) ) {
  310. return false;
  311. }
  312. }
  313. return true;
  314. }
  315. /**
  316. * Gets the post's first usable content image. Null if none is available.
  317. *
  318. * @param int $post_id The post id.
  319. *
  320. * @return string|null The image URL.
  321. */
  322. public static function get_first_usable_content_image_for_post( $post_id = null ) {
  323. $post = get_post( $post_id );
  324. // We know get_post() returns the post or null.
  325. if ( ! $post ) {
  326. return null;
  327. }
  328. $image_finder = new WPSEO_Content_Images();
  329. $images = $image_finder->get_images( $post->ID, $post );
  330. return self::get_first_image( $images );
  331. }
  332. /**
  333. * Gets the term's first usable content image. Null if none is available.
  334. *
  335. * @param int $term_id The term id.
  336. *
  337. * @return string|null The image URL.
  338. */
  339. public static function get_first_content_image_for_term( $term_id ) {
  340. $term_description = term_description( $term_id );
  341. // We know term_description() returns a string which may be empty.
  342. if ( $term_description === '' ) {
  343. return null;
  344. }
  345. $image_finder = new WPSEO_Content_Images();
  346. $images = $image_finder->get_images_from_content( $term_description );
  347. return self::get_first_image( $images );
  348. }
  349. /**
  350. * Retrieves an attachment ID for an image uploaded in the settings.
  351. *
  352. * Due to self::get_attachment_by_url returning 0 instead of false.
  353. * 0 is also a possibility when no ID is available.
  354. *
  355. * @param string $setting The setting the image is stored in.
  356. *
  357. * @return int|bool The attachment id, or false or 0 if no ID is available.
  358. */
  359. public static function get_attachment_id_from_settings( $setting ) {
  360. $image_id = WPSEO_Options::get( $setting . '_id', false );
  361. if ( ! $image_id ) {
  362. $image = WPSEO_Options::get( $setting, false );
  363. if ( $image ) {
  364. // There is not an option to put a URL in an image field in the settings anymore, only to upload it through the media manager.
  365. // This means an attachment always exists, so doing this is only needed once.
  366. $image_id = self::get_attachment_by_url( $image );
  367. WPSEO_Options::set( $setting . '_id', $image_id );
  368. }
  369. }
  370. return $image_id;
  371. }
  372. /**
  373. * Retrieves the first possible image url from an array of images.
  374. *
  375. * @param array $images The array to extract image url from.
  376. *
  377. * @return string|null The extracted image url when found, null when not found.
  378. */
  379. protected static function get_first_image( $images ) {
  380. if ( ! is_array( $images ) ) {
  381. return null;
  382. }
  383. $images = array_filter( $images );
  384. if ( empty( $images ) ) {
  385. return null;
  386. }
  387. return reset( $images );
  388. }
  389. }