PageRenderTime 92ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

https://github.com/markjaquith/WordPress
PHP | 5374 lines | 2582 code | 643 blank | 2149 comment | 493 complexity | d8284eee926c7cb0ce9fa97279beb5ac MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. * @subpackage Media
  7. */
  8. /**
  9. * Retrieve additional image sizes.
  10. *
  11. * @since 4.7.0
  12. *
  13. * @global array $_wp_additional_image_sizes
  14. *
  15. * @return array Additional images size data.
  16. */
  17. function wp_get_additional_image_sizes() {
  18. global $_wp_additional_image_sizes;
  19. if ( ! $_wp_additional_image_sizes ) {
  20. $_wp_additional_image_sizes = array();
  21. }
  22. return $_wp_additional_image_sizes;
  23. }
  24. /**
  25. * Scale down the default size of an image.
  26. *
  27. * This is so that the image is a better fit for the editor and theme.
  28. *
  29. * The `$size` parameter accepts either an array or a string. The supported string
  30. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  31. * 128 width and 96 height in pixels. Also supported for the string value is
  32. * 'medium', 'medium_large' and 'full'. The 'full' isn't actually supported, but any value other
  33. * than the supported will result in the content_width size or 500 if that is
  34. * not set.
  35. *
  36. * Finally, there is a filter named {@see 'editor_max_image_size'}, that will be
  37. * called on the calculated array for width and height, respectively.
  38. *
  39. * @since 2.5.0
  40. *
  41. * @global int $content_width
  42. *
  43. * @param int $width Width of the image in pixels.
  44. * @param int $height Height of the image in pixels.
  45. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  46. * of width and height values in pixels (in that order). Default 'medium'.
  47. * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
  48. * (like inserting into an editor). Default null.
  49. * @return int[] {
  50. * An array of width and height values.
  51. *
  52. * @type int $0 The maximum width in pixels.
  53. * @type int $1 The maximum height in pixels.
  54. * }
  55. */
  56. function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  57. global $content_width;
  58. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  59. if ( ! $context ) {
  60. $context = is_admin() ? 'edit' : 'display';
  61. }
  62. if ( is_array( $size ) ) {
  63. $max_width = $size[0];
  64. $max_height = $size[1];
  65. } elseif ( 'thumb' === $size || 'thumbnail' === $size ) {
  66. $max_width = (int) get_option( 'thumbnail_size_w' );
  67. $max_height = (int) get_option( 'thumbnail_size_h' );
  68. // Last chance thumbnail size defaults.
  69. if ( ! $max_width && ! $max_height ) {
  70. $max_width = 128;
  71. $max_height = 96;
  72. }
  73. } elseif ( 'medium' === $size ) {
  74. $max_width = (int) get_option( 'medium_size_w' );
  75. $max_height = (int) get_option( 'medium_size_h' );
  76. } elseif ( 'medium_large' === $size ) {
  77. $max_width = (int) get_option( 'medium_large_size_w' );
  78. $max_height = (int) get_option( 'medium_large_size_h' );
  79. if ( (int) $content_width > 0 ) {
  80. $max_width = min( (int) $content_width, $max_width );
  81. }
  82. } elseif ( 'large' === $size ) {
  83. /*
  84. * We're inserting a large size image into the editor. If it's a really
  85. * big image we'll scale it down to fit reasonably within the editor
  86. * itself, and within the theme's content width if it's known. The user
  87. * can resize it in the editor if they wish.
  88. */
  89. $max_width = (int) get_option( 'large_size_w' );
  90. $max_height = (int) get_option( 'large_size_h' );
  91. if ( (int) $content_width > 0 ) {
  92. $max_width = min( (int) $content_width, $max_width );
  93. }
  94. } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ), true ) ) {
  95. $max_width = (int) $_wp_additional_image_sizes[ $size ]['width'];
  96. $max_height = (int) $_wp_additional_image_sizes[ $size ]['height'];
  97. // Only in admin. Assume that theme authors know what they're doing.
  98. if ( (int) $content_width > 0 && 'edit' === $context ) {
  99. $max_width = min( (int) $content_width, $max_width );
  100. }
  101. } else { // $size === 'full' has no constraint.
  102. $max_width = $width;
  103. $max_height = $height;
  104. }
  105. /**
  106. * Filters the maximum image size dimensions for the editor.
  107. *
  108. * @since 2.5.0
  109. *
  110. * @param int[] $max_image_size {
  111. * An array of width and height values.
  112. *
  113. * @type int $0 The maximum width in pixels.
  114. * @type int $1 The maximum height in pixels.
  115. * }
  116. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  117. * an array of width and height values in pixels (in that order).
  118. * @param string $context The context the image is being resized for.
  119. * Possible values are 'display' (like in a theme)
  120. * or 'edit' (like inserting into an editor).
  121. */
  122. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  123. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  124. }
  125. /**
  126. * Retrieve width and height attributes using given width and height values.
  127. *
  128. * Both attributes are required in the sense that both parameters must have a
  129. * value, but are optional in that if you set them to false or null, then they
  130. * will not be added to the returned string.
  131. *
  132. * You can set the value using a string, but it will only take numeric values.
  133. * If you wish to put 'px' after the numbers, then it will be stripped out of
  134. * the return.
  135. *
  136. * @since 2.5.0
  137. *
  138. * @param int|string $width Image width in pixels.
  139. * @param int|string $height Image height in pixels.
  140. * @return string HTML attributes for width and, or height.
  141. */
  142. function image_hwstring( $width, $height ) {
  143. $out = '';
  144. if ( $width ) {
  145. $out .= 'width="' . (int) $width . '" ';
  146. }
  147. if ( $height ) {
  148. $out .= 'height="' . (int) $height . '" ';
  149. }
  150. return $out;
  151. }
  152. /**
  153. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  154. *
  155. * The URL might be the original image, or it might be a resized version. This
  156. * function won't create a new resized copy, it will just return an already
  157. * resized one if it exists.
  158. *
  159. * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
  160. * resizing services for images. The hook must return an array with the same
  161. * elements that are normally returned from the function.
  162. *
  163. * @since 2.5.0
  164. *
  165. * @param int $id Attachment ID for image.
  166. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  167. * of width and height values in pixels (in that order). Default 'medium'.
  168. * @return array|false {
  169. * Array of image data, or boolean false if no image is available.
  170. *
  171. * @type string $0 Image source URL.
  172. * @type int $1 Image width in pixels.
  173. * @type int $2 Image height in pixels.
  174. * @type bool $3 Whether the image is a resized image.
  175. * }
  176. */
  177. function image_downsize( $id, $size = 'medium' ) {
  178. $is_image = wp_attachment_is_image( $id );
  179. /**
  180. * Filters whether to preempt the output of image_downsize().
  181. *
  182. * Returning a truthy value from the filter will effectively short-circuit
  183. * down-sizing the image, returning that value instead.
  184. *
  185. * @since 2.5.0
  186. *
  187. * @param bool|array $downsize Whether to short-circuit the image downsize.
  188. * @param int $id Attachment ID for image.
  189. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  190. * an array of width and height values in pixels (in that order).
  191. */
  192. $out = apply_filters( 'image_downsize', false, $id, $size );
  193. if ( $out ) {
  194. return $out;
  195. }
  196. $img_url = wp_get_attachment_url( $id );
  197. $meta = wp_get_attachment_metadata( $id );
  198. $width = 0;
  199. $height = 0;
  200. $is_intermediate = false;
  201. $img_url_basename = wp_basename( $img_url );
  202. // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
  203. // Otherwise, a non-image type could be returned.
  204. if ( ! $is_image ) {
  205. if ( ! empty( $meta['sizes']['full'] ) ) {
  206. $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
  207. $img_url_basename = $meta['sizes']['full']['file'];
  208. $width = $meta['sizes']['full']['width'];
  209. $height = $meta['sizes']['full']['height'];
  210. } else {
  211. return false;
  212. }
  213. }
  214. // Try for a new style intermediate size.
  215. $intermediate = image_get_intermediate_size( $id, $size );
  216. if ( $intermediate ) {
  217. $img_url = str_replace( $img_url_basename, $intermediate['file'], $img_url );
  218. $width = $intermediate['width'];
  219. $height = $intermediate['height'];
  220. $is_intermediate = true;
  221. } elseif ( 'thumbnail' === $size ) {
  222. // Fall back to the old thumbnail.
  223. $thumb_file = wp_get_attachment_thumb_file( $id );
  224. $info = null;
  225. if ( $thumb_file ) {
  226. $info = wp_getimagesize( $thumb_file );
  227. }
  228. if ( $thumb_file && $info ) {
  229. $img_url = str_replace( $img_url_basename, wp_basename( $thumb_file ), $img_url );
  230. $width = $info[0];
  231. $height = $info[1];
  232. $is_intermediate = true;
  233. }
  234. }
  235. if ( ! $width && ! $height && isset( $meta['width'], $meta['height'] ) ) {
  236. // Any other type: use the real image.
  237. $width = $meta['width'];
  238. $height = $meta['height'];
  239. }
  240. if ( $img_url ) {
  241. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  242. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  243. return array( $img_url, $width, $height, $is_intermediate );
  244. }
  245. return false;
  246. }
  247. /**
  248. * Register a new image size.
  249. *
  250. * @since 2.9.0
  251. *
  252. * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
  253. *
  254. * @param string $name Image size identifier.
  255. * @param int $width Optional. Image width in pixels. Default 0.
  256. * @param int $height Optional. Image height in pixels. Default 0.
  257. * @param bool|array $crop Optional. Image cropping behavior. If false, the image will be scaled (default),
  258. * If true, image will be cropped to the specified dimensions using center positions.
  259. * If an array, the image will be cropped using the array to specify the crop location.
  260. * Array values must be in the format: array( x_crop_position, y_crop_position ) where:
  261. * - x_crop_position accepts: 'left', 'center', or 'right'.
  262. * - y_crop_position accepts: 'top', 'center', or 'bottom'.
  263. */
  264. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  265. global $_wp_additional_image_sizes;
  266. $_wp_additional_image_sizes[ $name ] = array(
  267. 'width' => absint( $width ),
  268. 'height' => absint( $height ),
  269. 'crop' => $crop,
  270. );
  271. }
  272. /**
  273. * Check if an image size exists.
  274. *
  275. * @since 3.9.0
  276. *
  277. * @param string $name The image size to check.
  278. * @return bool True if the image size exists, false if not.
  279. */
  280. function has_image_size( $name ) {
  281. $sizes = wp_get_additional_image_sizes();
  282. return isset( $sizes[ $name ] );
  283. }
  284. /**
  285. * Remove a new image size.
  286. *
  287. * @since 3.9.0
  288. *
  289. * @global array $_wp_additional_image_sizes
  290. *
  291. * @param string $name The image size to remove.
  292. * @return bool True if the image size was successfully removed, false on failure.
  293. */
  294. function remove_image_size( $name ) {
  295. global $_wp_additional_image_sizes;
  296. if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
  297. unset( $_wp_additional_image_sizes[ $name ] );
  298. return true;
  299. }
  300. return false;
  301. }
  302. /**
  303. * Registers an image size for the post thumbnail.
  304. *
  305. * @since 2.9.0
  306. *
  307. * @see add_image_size() for details on cropping behavior.
  308. *
  309. * @param int $width Image width in pixels.
  310. * @param int $height Image height in pixels.
  311. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  312. * An array can specify positioning of the crop area. Default false.
  313. */
  314. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  315. add_image_size( 'post-thumbnail', $width, $height, $crop );
  316. }
  317. /**
  318. * Gets an img tag for an image attachment, scaling it down if requested.
  319. *
  320. * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
  321. * image without having to use regular expressions on the HTML content. The
  322. * parameters are: what WordPress will use for the class, the Attachment ID,
  323. * image align value, and the size the image should be.
  324. *
  325. * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
  326. * further manipulated by a plugin to change all attribute values and even HTML
  327. * content.
  328. *
  329. * @since 2.5.0
  330. *
  331. * @param int $id Attachment ID.
  332. * @param string $alt Image description for the alt attribute.
  333. * @param string $title Image description for the title attribute.
  334. * @param string $align Part of the class name for aligning the image.
  335. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
  336. * width and height values in pixels (in that order). Default 'medium'.
  337. * @return string HTML IMG element for given image attachment
  338. */
  339. function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
  340. list( $img_src, $width, $height ) = image_downsize( $id, $size );
  341. $hwstring = image_hwstring( $width, $height );
  342. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  343. $size_class = is_array( $size ) ? implode( 'x', $size ) : $size;
  344. $class = 'align' . esc_attr( $align ) . ' size-' . esc_attr( $size_class ) . ' wp-image-' . $id;
  345. /**
  346. * Filters the value of the attachment's image tag class attribute.
  347. *
  348. * @since 2.6.0
  349. *
  350. * @param string $class CSS class name or space-separated list of classes.
  351. * @param int $id Attachment ID.
  352. * @param string $align Part of the class name for aligning the image.
  353. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  354. * an array of width and height values in pixels (in that order).
  355. */
  356. $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
  357. $html = '<img src="' . esc_attr( $img_src ) . '" alt="' . esc_attr( $alt ) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  358. /**
  359. * Filters the HTML content for the image tag.
  360. *
  361. * @since 2.6.0
  362. *
  363. * @param string $html HTML content for the image.
  364. * @param int $id Attachment ID.
  365. * @param string $alt Image description for the alt attribute.
  366. * @param string $title Image description for the title attribute.
  367. * @param string $align Part of the class name for aligning the image.
  368. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  369. * an array of width and height values in pixels (in that order).
  370. */
  371. return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  372. }
  373. /**
  374. * Calculates the new dimensions for a down-sampled image.
  375. *
  376. * If either width or height are empty, no constraint is applied on
  377. * that dimension.
  378. *
  379. * @since 2.5.0
  380. *
  381. * @param int $current_width Current width of the image.
  382. * @param int $current_height Current height of the image.
  383. * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
  384. * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
  385. * @return int[] {
  386. * An array of width and height values.
  387. *
  388. * @type int $0 The width in pixels.
  389. * @type int $1 The height in pixels.
  390. * }
  391. */
  392. function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
  393. if ( ! $max_width && ! $max_height ) {
  394. return array( $current_width, $current_height );
  395. }
  396. $width_ratio = 1.0;
  397. $height_ratio = 1.0;
  398. $did_width = false;
  399. $did_height = false;
  400. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  401. $width_ratio = $max_width / $current_width;
  402. $did_width = true;
  403. }
  404. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  405. $height_ratio = $max_height / $current_height;
  406. $did_height = true;
  407. }
  408. // Calculate the larger/smaller ratios.
  409. $smaller_ratio = min( $width_ratio, $height_ratio );
  410. $larger_ratio = max( $width_ratio, $height_ratio );
  411. if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
  412. // The larger ratio is too big. It would result in an overflow.
  413. $ratio = $smaller_ratio;
  414. } else {
  415. // The larger ratio fits, and is likely to be a more "snug" fit.
  416. $ratio = $larger_ratio;
  417. }
  418. // Very small dimensions may result in 0, 1 should be the minimum.
  419. $w = max( 1, (int) round( $current_width * $ratio ) );
  420. $h = max( 1, (int) round( $current_height * $ratio ) );
  421. /*
  422. * Sometimes, due to rounding, we'll end up with a result like this:
  423. * 465x700 in a 177x177 box is 117x176... a pixel short.
  424. * We also have issues with recursive calls resulting in an ever-changing result.
  425. * Constraining to the result of a constraint should yield the original result.
  426. * Thus we look for dimensions that are one pixel shy of the max value and bump them up.
  427. */
  428. // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
  429. if ( $did_width && $w === $max_width - 1 ) {
  430. $w = $max_width; // Round it up.
  431. }
  432. // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
  433. if ( $did_height && $h === $max_height - 1 ) {
  434. $h = $max_height; // Round it up.
  435. }
  436. /**
  437. * Filters dimensions to constrain down-sampled images to.
  438. *
  439. * @since 4.1.0
  440. *
  441. * @param int[] $dimensions {
  442. * An array of width and height values.
  443. *
  444. * @type int $0 The width in pixels.
  445. * @type int $1 The height in pixels.
  446. * }
  447. * @param int $current_width The current width of the image.
  448. * @param int $current_height The current height of the image.
  449. * @param int $max_width The maximum width permitted.
  450. * @param int $max_height The maximum height permitted.
  451. */
  452. return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
  453. }
  454. /**
  455. * Retrieves calculated resize dimensions for use in WP_Image_Editor.
  456. *
  457. * Calculates dimensions and coordinates for a resized image that fits
  458. * within a specified width and height.
  459. *
  460. * Cropping behavior is dependent on the value of $crop:
  461. * 1. If false (default), images will not be cropped.
  462. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  463. * - x_crop_position accepts 'left' 'center', or 'right'.
  464. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  465. * Images will be cropped to the specified dimensions within the defined crop area.
  466. * 3. If true, images will be cropped to the specified dimensions using center positions.
  467. *
  468. * @since 2.5.0
  469. *
  470. * @param int $orig_w Original width in pixels.
  471. * @param int $orig_h Original height in pixels.
  472. * @param int $dest_w New width in pixels.
  473. * @param int $dest_h New height in pixels.
  474. * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
  475. * An array can specify positioning of the crop area. Default false.
  476. * @return array|false Returned array matches parameters for `imagecopyresampled()`. False on failure.
  477. */
  478. function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
  479. if ( $orig_w <= 0 || $orig_h <= 0 ) {
  480. return false;
  481. }
  482. // At least one of $dest_w or $dest_h must be specific.
  483. if ( $dest_w <= 0 && $dest_h <= 0 ) {
  484. return false;
  485. }
  486. /**
  487. * Filters whether to preempt calculating the image resize dimensions.
  488. *
  489. * Returning a non-null value from the filter will effectively short-circuit
  490. * image_resize_dimensions(), returning that value instead.
  491. *
  492. * @since 3.4.0
  493. *
  494. * @param null|mixed $null Whether to preempt output of the resize dimensions.
  495. * @param int $orig_w Original width in pixels.
  496. * @param int $orig_h Original height in pixels.
  497. * @param int $dest_w New width in pixels.
  498. * @param int $dest_h New height in pixels.
  499. * @param bool|array $crop Whether to crop image to specified width and height or resize.
  500. * An array can specify positioning of the crop area. Default false.
  501. */
  502. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  503. if ( null !== $output ) {
  504. return $output;
  505. }
  506. // Stop if the destination size is larger than the original image dimensions.
  507. if ( empty( $dest_h ) ) {
  508. if ( $orig_w < $dest_w ) {
  509. return false;
  510. }
  511. } elseif ( empty( $dest_w ) ) {
  512. if ( $orig_h < $dest_h ) {
  513. return false;
  514. }
  515. } else {
  516. if ( $orig_w < $dest_w && $orig_h < $dest_h ) {
  517. return false;
  518. }
  519. }
  520. if ( $crop ) {
  521. /*
  522. * Crop the largest possible portion of the original image that we can size to $dest_w x $dest_h.
  523. * Note that the requested crop dimensions are used as a maximum bounding box for the original image.
  524. * If the original image's width or height is less than the requested width or height
  525. * only the greater one will be cropped.
  526. * For example when the original image is 600x300, and the requested crop dimensions are 400x400,
  527. * the resulting image will be 400x300.
  528. */
  529. $aspect_ratio = $orig_w / $orig_h;
  530. $new_w = min( $dest_w, $orig_w );
  531. $new_h = min( $dest_h, $orig_h );
  532. if ( ! $new_w ) {
  533. $new_w = (int) round( $new_h * $aspect_ratio );
  534. }
  535. if ( ! $new_h ) {
  536. $new_h = (int) round( $new_w / $aspect_ratio );
  537. }
  538. $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );
  539. $crop_w = round( $new_w / $size_ratio );
  540. $crop_h = round( $new_h / $size_ratio );
  541. if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
  542. $crop = array( 'center', 'center' );
  543. }
  544. list( $x, $y ) = $crop;
  545. if ( 'left' === $x ) {
  546. $s_x = 0;
  547. } elseif ( 'right' === $x ) {
  548. $s_x = $orig_w - $crop_w;
  549. } else {
  550. $s_x = floor( ( $orig_w - $crop_w ) / 2 );
  551. }
  552. if ( 'top' === $y ) {
  553. $s_y = 0;
  554. } elseif ( 'bottom' === $y ) {
  555. $s_y = $orig_h - $crop_h;
  556. } else {
  557. $s_y = floor( ( $orig_h - $crop_h ) / 2 );
  558. }
  559. } else {
  560. // Resize using $dest_w x $dest_h as a maximum bounding box.
  561. $crop_w = $orig_w;
  562. $crop_h = $orig_h;
  563. $s_x = 0;
  564. $s_y = 0;
  565. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  566. }
  567. if ( wp_fuzzy_number_match( $new_w, $orig_w ) && wp_fuzzy_number_match( $new_h, $orig_h ) ) {
  568. // The new size has virtually the same dimensions as the original image.
  569. /**
  570. * Filters whether to proceed with making an image sub-size with identical dimensions
  571. * with the original/source image. Differences of 1px may be due to rounding and are ignored.
  572. *
  573. * @since 5.3.0
  574. *
  575. * @param bool $proceed The filtered value.
  576. * @param int $orig_w Original image width.
  577. * @param int $orig_h Original image height.
  578. */
  579. $proceed = (bool) apply_filters( 'wp_image_resize_identical_dimensions', false, $orig_w, $orig_h );
  580. if ( ! $proceed ) {
  581. return false;
  582. }
  583. }
  584. // The return array matches the parameters to imagecopyresampled().
  585. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  586. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  587. }
  588. /**
  589. * Resizes an image to make a thumbnail or intermediate size.
  590. *
  591. * The returned array has the file size, the image width, and image height. The
  592. * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
  593. * values of the returned array. The only parameter is the resized file path.
  594. *
  595. * @since 2.5.0
  596. *
  597. * @param string $file File path.
  598. * @param int $width Image width.
  599. * @param int $height Image height.
  600. * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
  601. * Default false.
  602. * @return array|false Metadata array on success. False if no image was created.
  603. */
  604. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  605. if ( $width || $height ) {
  606. $editor = wp_get_image_editor( $file );
  607. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) {
  608. return false;
  609. }
  610. $resized_file = $editor->save();
  611. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  612. unset( $resized_file['path'] );
  613. return $resized_file;
  614. }
  615. }
  616. return false;
  617. }
  618. /**
  619. * Helper function to test if aspect ratios for two images match.
  620. *
  621. * @since 4.6.0
  622. *
  623. * @param int $source_width Width of the first image in pixels.
  624. * @param int $source_height Height of the first image in pixels.
  625. * @param int $target_width Width of the second image in pixels.
  626. * @param int $target_height Height of the second image in pixels.
  627. * @return bool True if aspect ratios match within 1px. False if not.
  628. */
  629. function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
  630. /*
  631. * To test for varying crops, we constrain the dimensions of the larger image
  632. * to the dimensions of the smaller image and see if they match.
  633. */
  634. if ( $source_width > $target_width ) {
  635. $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
  636. $expected_size = array( $target_width, $target_height );
  637. } else {
  638. $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
  639. $expected_size = array( $source_width, $source_height );
  640. }
  641. // If the image dimensions are within 1px of the expected size, we consider it a match.
  642. $matched = ( wp_fuzzy_number_match( $constrained_size[0], $expected_size[0] ) && wp_fuzzy_number_match( $constrained_size[1], $expected_size[1] ) );
  643. return $matched;
  644. }
  645. /**
  646. * Retrieves the image's intermediate size (resized) path, width, and height.
  647. *
  648. * The $size parameter can be an array with the width and height respectively.
  649. * If the size matches the 'sizes' metadata array for width and height, then it
  650. * will be used. If there is no direct match, then the nearest image size larger
  651. * than the specified size will be used. If nothing is found, then the function
  652. * will break out and return false.
  653. *
  654. * The metadata 'sizes' is used for compatible sizes that can be used for the
  655. * parameter $size value.
  656. *
  657. * The url path will be given, when the $size parameter is a string.
  658. *
  659. * If you are passing an array for the $size, you should consider using
  660. * add_image_size() so that a cropped version is generated. It's much more
  661. * efficient than having to find the closest-sized image and then having the
  662. * browser scale down the image.
  663. *
  664. * @since 2.5.0
  665. *
  666. * @param int $post_id Attachment ID.
  667. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  668. * of width and height values in pixels (in that order). Default 'thumbnail'.
  669. * @return array|false {
  670. * Array of file relative path, width, and height on success. Additionally includes absolute
  671. * path and URL if registered size is passed to `$size` parameter. False on failure.
  672. *
  673. * @type string $file Path of image relative to uploads directory.
  674. * @type int $width Width of image in pixels.
  675. * @type int $height Height of image in pixels.
  676. * @type string $path Absolute filesystem path of image.
  677. * @type string $url URL of image.
  678. * }
  679. */
  680. function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
  681. $imagedata = wp_get_attachment_metadata( $post_id );
  682. if ( ! $size || ! is_array( $imagedata ) || empty( $imagedata['sizes'] ) ) {
  683. return false;
  684. }
  685. $data = array();
  686. // Find the best match when '$size' is an array.
  687. if ( is_array( $size ) ) {
  688. $candidates = array();
  689. if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
  690. $imagedata['height'] = $imagedata['sizes']['full']['height'];
  691. $imagedata['width'] = $imagedata['sizes']['full']['width'];
  692. }
  693. foreach ( $imagedata['sizes'] as $_size => $data ) {
  694. // If there's an exact match to an existing image size, short circuit.
  695. if ( (int) $data['width'] === (int) $size[0] && (int) $data['height'] === (int) $size[1] ) {
  696. $candidates[ $data['width'] * $data['height'] ] = $data;
  697. break;
  698. }
  699. // If it's not an exact match, consider larger sizes with the same aspect ratio.
  700. if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
  701. // If '0' is passed to either size, we test ratios against the original file.
  702. if ( 0 === $size[0] || 0 === $size[1] ) {
  703. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
  704. } else {
  705. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
  706. }
  707. if ( $same_ratio ) {
  708. $candidates[ $data['width'] * $data['height'] ] = $data;
  709. }
  710. }
  711. }
  712. if ( ! empty( $candidates ) ) {
  713. // Sort the array by size if we have more than one candidate.
  714. if ( 1 < count( $candidates ) ) {
  715. ksort( $candidates );
  716. }
  717. $data = array_shift( $candidates );
  718. /*
  719. * When the size requested is smaller than the thumbnail dimensions, we
  720. * fall back to the thumbnail size to maintain backward compatibility with
  721. * pre 4.6 versions of WordPress.
  722. */
  723. } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
  724. $data = $imagedata['sizes']['thumbnail'];
  725. } else {
  726. return false;
  727. }
  728. // Constrain the width and height attributes to the requested values.
  729. list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  730. } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
  731. $data = $imagedata['sizes'][ $size ];
  732. }
  733. // If we still don't have a match at this point, return false.
  734. if ( empty( $data ) ) {
  735. return false;
  736. }
  737. // Include the full filesystem path of the intermediate file.
  738. if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
  739. $file_url = wp_get_attachment_url( $post_id );
  740. $data['path'] = path_join( dirname( $imagedata['file'] ), $data['file'] );
  741. $data['url'] = path_join( dirname( $file_url ), $data['file'] );
  742. }
  743. /**
  744. * Filters the output of image_get_intermediate_size()
  745. *
  746. * @since 4.4.0
  747. *
  748. * @see image_get_intermediate_size()
  749. *
  750. * @param array $data Array of file relative path, width, and height on success. May also include
  751. * file absolute path and URL.
  752. * @param int $post_id The ID of the image attachment.
  753. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  754. * an array of width and height values in pixels (in that order).
  755. */
  756. return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
  757. }
  758. /**
  759. * Gets the available intermediate image size names.
  760. *
  761. * @since 3.0.0
  762. *
  763. * @return string[] An array of image size names.
  764. */
  765. function get_intermediate_image_sizes() {
  766. $default_sizes = array( 'thumbnail', 'medium', 'medium_large', 'large' );
  767. $additional_sizes = wp_get_additional_image_sizes();
  768. if ( ! empty( $additional_sizes ) ) {
  769. $default_sizes = array_merge( $default_sizes, array_keys( $additional_sizes ) );
  770. }
  771. /**
  772. * Filters the list of intermediate image sizes.
  773. *
  774. * @since 2.5.0
  775. *
  776. * @param string[] $default_sizes An array of intermediate image size names. Defaults
  777. * are 'thumbnail', 'medium', 'medium_large', 'large'.
  778. */
  779. return apply_filters( 'intermediate_image_sizes', $default_sizes );
  780. }
  781. /**
  782. * Returns a normalized list of all currently registered image sub-sizes.
  783. *
  784. * @since 5.3.0
  785. * @uses wp_get_additional_image_sizes()
  786. * @uses get_intermediate_image_sizes()
  787. *
  788. * @return array[] Associative array of arrays of image sub-size information,
  789. * keyed by image size name.
  790. */
  791. function wp_get_registered_image_subsizes() {
  792. $additional_sizes = wp_get_additional_image_sizes();
  793. $all_sizes = array();
  794. foreach ( get_intermediate_image_sizes() as $size_name ) {
  795. $size_data = array(
  796. 'width' => 0,
  797. 'height' => 0,
  798. 'crop' => false,
  799. );
  800. if ( isset( $additional_sizes[ $size_name ]['width'] ) ) {
  801. // For sizes added by plugins and themes.
  802. $size_data['width'] = (int) $additional_sizes[ $size_name ]['width'];
  803. } else {
  804. // For default sizes set in options.
  805. $size_data['width'] = (int) get_option( "{$size_name}_size_w" );
  806. }
  807. if ( isset( $additional_sizes[ $size_name ]['height'] ) ) {
  808. $size_data['height'] = (int) $additional_sizes[ $size_name ]['height'];
  809. } else {
  810. $size_data['height'] = (int) get_option( "{$size_name}_size_h" );
  811. }
  812. if ( empty( $size_data['width'] ) && empty( $size_data['height'] ) ) {
  813. // This size isn't set.
  814. continue;
  815. }
  816. if ( isset( $additional_sizes[ $size_name ]['crop'] ) ) {
  817. $size_data['crop'] = $additional_sizes[ $size_name ]['crop'];
  818. } else {
  819. $size_data['crop'] = get_option( "{$size_name}_crop" );
  820. }
  821. if ( ! is_array( $size_data['crop'] ) || empty( $size_data['crop'] ) ) {
  822. $size_data['crop'] = (bool) $size_data['crop'];
  823. }
  824. $all_sizes[ $size_name ] = $size_data;
  825. }
  826. return $all_sizes;
  827. }
  828. /**
  829. * Retrieves an image to represent an attachment.
  830. *
  831. * @since 2.5.0
  832. *
  833. * @param int $attachment_id Image attachment ID.
  834. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
  835. * width and height values in pixels (in that order). Default 'thumbnail'.
  836. * @param bool $icon Optional. Whether the image should fall back to a mime type icon. Default false.
  837. * @return array|false {
  838. * Array of image data, or boolean false if no image is available.
  839. *
  840. * @type string $0 Image source URL.
  841. * @type int $1 Image width in pixels.
  842. * @type int $2 Image height in pixels.
  843. * @type bool $3 Whether the image is a resized image.
  844. * }
  845. */
  846. function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
  847. // Get a thumbnail or intermediate image if there is one.
  848. $image = image_downsize( $attachment_id, $size );
  849. if ( ! $image ) {
  850. $src = false;
  851. if ( $icon ) {
  852. $src = wp_mime_type_icon( $attachment_id );
  853. if ( $src ) {
  854. /** This filter is documented in wp-includes/post.php */
  855. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  856. $src_file = $icon_dir . '/' . wp_basename( $src );
  857. list( $width, $height ) = wp_getimagesize( $src_file );
  858. }
  859. }
  860. if ( $src && $width && $height ) {
  861. $image = array( $src, $width, $height, false );
  862. }
  863. }
  864. /**
  865. * Filters the attachment image source result.
  866. *
  867. * @since 4.3.0
  868. *
  869. * @param array|false $image {
  870. * Array of image data, or boolean false if no image is available.
  871. *
  872. * @type string $0 Image source URL.
  873. * @type int $1 Image width in pixels.
  874. * @type int $2 Image height in pixels.
  875. * @type bool $3 Whether the image is a resized image.
  876. * }
  877. * @param int $attachment_id Image attachment ID.
  878. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  879. * an array of width and height values in pixels (in that order).
  880. * @param bool $icon Whether the image should be treated as an icon.
  881. */
  882. return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
  883. }
  884. /**
  885. * Get an HTML img element representing an image attachment.
  886. *
  887. * While `$size` will accept an array, it is better to register a size with
  888. * add_image_size() so that a cropped version is generated. It's much more
  889. * efficient than having to find the closest-sized image and then having the
  890. * browser scale down the image.
  891. *
  892. * @since 2.5.0
  893. * @since 4.4.0 The `$srcset` and `$sizes` attributes were added.
  894. * @since 5.5.0 The `$loading` attribute was added.
  895. *
  896. * @param int $attachment_id Image attachment ID.
  897. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  898. * of width and height values in pixels (in that order). Default 'thumbnail'.
  899. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  900. * @param string|array $attr {
  901. * Optional. Attributes for the image markup.
  902. *
  903. * @type string $src Image attachment URL.
  904. * @type string $class CSS class name or space-separated list of classes.
  905. * Default `attachment-$size_class size-$size_class`,
  906. * where `$size_class` is the image size being requested.
  907. * @type string $alt Image description for the alt attribute.
  908. * @type string $srcset The 'srcset' attribute value.
  909. * @type string $sizes The 'sizes' attribute value.
  910. * @type string|false $loading The 'loading' attribute value. Passing a value of false
  911. * will result in the attribute being omitted for the image.
  912. * Defaults to 'lazy', depending on wp_lazy_loading_enabled().
  913. * }
  914. * @return string HTML img element or empty string on failure.
  915. */
  916. function wp_get_attachment_image( $attachment_id, $size = 'thumbnail', $icon = false, $attr = '' ) {
  917. $html = '';
  918. $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
  919. if ( $image ) {
  920. list( $src, $width, $height ) = $image;
  921. $attachment = get_post( $attachment_id );
  922. $hwstring = image_hwstring( $width, $height );
  923. $size_class = $size;
  924. if ( is_array( $size_class ) ) {
  925. $size_class = implode( 'x', $size_class );
  926. }
  927. $default_attr = array(
  928. 'src' => $src,
  929. 'class' => "attachment-$size_class size-$size_class",
  930. 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
  931. );
  932. // Add `loading` attribute.
  933. if ( wp_lazy_loading_enabled( 'img', 'wp_get_attachment_image' ) ) {
  934. $default_attr['loading'] = wp_get_loading_attr_default( 'wp_get_attachment_image' );
  935. }
  936. $attr = wp_parse_args( $attr, $default_attr );
  937. // If the default value of `lazy` for the `loading` attribute is overridden
  938. // to omit the attribute for this image, ensure it is not included.
  939. if ( array_key_exists( 'loading', $attr ) && ! $attr['loading'] ) {
  940. unset( $attr['loading'] );
  941. }
  942. // Generate 'srcset' and 'sizes' if not already present.
  943. if ( empty( $attr['srcset'] ) ) {
  944. $image_meta = wp_get_attachment_metadata( $attachment_id );
  945. if ( is_array( $image_meta ) ) {
  946. $size_array = array( absint( $width ), absint( $height ) );
  947. $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
  948. $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
  949. if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
  950. $attr['srcset'] = $srcset;
  951. if ( empty( $attr['sizes'] ) ) {
  952. $attr['sizes'] = $sizes;
  953. }
  954. }
  955. }
  956. }
  957. /**
  958. * Filters the list of attachment image attributes.
  959. *
  960. * @since 2.8.0
  961. *
  962. * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
  963. * See wp_get_attachment_image().
  964. * @param WP_Post $attachment Image attachment post.
  965. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  966. * an array of width and height values in pixels (in that order).
  967. */
  968. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
  969. $attr = array_map( 'esc_attr', $attr );
  970. $html = rtrim( "<img $hwstring" );
  971. foreach ( $attr as $name => $value ) {
  972. $html .= " $name=" . '"' . $value . '"';
  973. }
  974. $html .= ' />';
  975. }
  976. /**
  977. * HTML img element representing an image attachment.
  978. *
  979. * @since 5.6.0
  980. *
  981. * @param string $html HTML img element or empty string on failure.
  982. * @param int $attachment_id Image attachment ID.
  983. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  984. * an array of width and height values in pixels (in that order).
  985. * @param bool $icon Whether the image should be treated as an icon.
  986. * @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
  987. * See wp_get_attachment_image().
  988. */
  989. return apply_filters( 'wp_get_attachment_image', $html, $attachment_id, $size, $icon, $attr );
  990. }
  991. /**
  992. * Get the URL of an image attachment.
  993. *
  994. * @since 4.4.0
  995. *
  996. * @param int $attachment_id Image attachment ID.
  997. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
  998. * width and height values in pixels (in that order). Default 'thumbnail'.
  999. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  1000. * @return string|false Attachment URL or false if no image is available. If `$size` does not match
  1001. * any registered image size, the original image URL will be returned.
  1002. */
  1003. function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
  1004. $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
  1005. return isset( $image[0] ) ? $image[0] : false;
  1006. }
  1007. /**
  1008. * Get the attachment path relative to the upload directory.
  1009. *
  1010. * @since 4.4.1
  1011. * @access private
  1012. *
  1013. * @param string $file Attachment file name.
  1014. * @return string Attachment path relative to the upload directory.
  1015. */
  1016. function _wp_get_attachment_relative_path( $file ) {
  1017. $dirname = dirname( $file );
  1018. if ( '.' === $dirname ) {
  1019. return '';
  1020. }
  1021. if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
  1022. // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads).
  1023. $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
  1024. $dirname = ltrim( $dirname, '/' );
  1025. }
  1026. return $dirname;
  1027. }
  1028. /**
  1029. * Get the image size as array from its meta data.
  1030. *
  1031. * Used for responsive images.
  1032. *
  1033. * @since 4.4.0
  1034. * @access private
  1035. *
  1036. * @param string $size_name Image size. Accepts any registered image size name.
  1037. * @param array $image_meta The image meta data.
  1038. * @return array|false {
  1039. * Array of width and height or false if the size isn't present in the meta data.
  1040. *
  1041. * @type int $0 Image width.
  1042. * @type int $1 Image height.
  1043. * }
  1044. */
  1045. function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
  1046. if ( 'full' === $size_name ) {
  1047. return array(
  1048. absint( $image_meta['width'] ),
  1049. absint( $image_meta['height'] ),
  1050. );
  1051. } elseif ( ! empty( $image_meta['sizes'][ $size_name ] ) ) {
  1052. return array(
  1053. absint( $image_meta['sizes'][ $size_name ]['width'] ),
  1054. absint( $image_meta['sizes'][ $size_name ]['height'] ),
  1055. );
  1056. }
  1057. return false;
  1058. }
  1059. /**
  1060. * Retrieves the value for an image attachment's 'srcset' attribute.
  1061. *
  1062. * @since 4.4.0
  1063. *
  1064. * @see wp_calculate_image_srcset()
  1065. *
  1066. * @param int $attachment_id Image attachment ID.
  1067. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
  1068. * width and height values in pixels (in that order). Default 'medium'.
  1069. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1070. * Default null.
  1071. * @return string|false A 'srcset' value string or false.
  1072. */
  1073. function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
  1074. $image = wp_get_attachment_image_src( $attachment_id, $size );
  1075. if ( ! $image ) {
  1076. return false;
  1077. }
  1078. if ( ! is_array( $image_meta ) ) {
  1079. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1080. }
  1081. $image_src = $image[0];
  1082. $size_array = array(
  1083. absint( $image[1] ),
  1084. absint( $image[2] ),
  1085. );
  1086. return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  1087. }
  1088. /**
  1089. * A helper function to calculate the image sources to include in a 'srcset' attribute.
  1090. *
  1091. * @since 4.4.0
  1092. *
  1093. * @param int[] $size_array {
  1094. * An array of width and height values.
  1095. *
  1096. * @type int $0 The width in pixels.
  1097. * @type int $1 The height in pixels.
  1098. * }
  1099. * @param string $image_src The 'src' of the image.
  1100. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1101. * @param int $attachment_id Optional. The image attachment ID. Default 0.
  1102. * @return string|false The 'srcset' attribute value. False on error or when only one source exists.
  1103. */
  1104. function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
  1105. /**
  1106. * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
  1107. *
  1108. * @since 4.5.0
  1109. *
  1110. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1111. * @param int[] $size_array {
  1112. * An array of requested width and height values.
  1113. *
  1114. * @type int $0 The width in pixels.
  1115. * @type int $1 The height in pixels.
  1116. * }
  1117. * @param string $image_src The 'src' of the image.
  1118. * @param int $attachment_id The image attachment ID or 0 if not supplied.
  1119. */
  1120. $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
  1121. if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
  1122. return false;
  1123. }
  1124. $image_sizes = $image_meta['sizes'];
  1125. // Get the width and height of the image.
  1126. $image_width = (int) $size_array[0];
  1127. $image_height = (int) $size_array[1];
  1128. // Bail early if error/no width.
  1129. if ( $image_width < 1 ) {
  1130. return false;
  1131. }
  1132. $image_basename = wp_basename( $image_meta['file'] );
  1133. /*
  1134. * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
  1135. * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
  1136. * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
  1137. */
  1138. if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
  1139. $image_sizes[] = array(
  1140. 'width' => $image_meta['width'],
  1141. 'height' => $image_meta['height'],
  1142. 'file' => $image_basename,
  1143. );
  1144. } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
  1145. return false;
  1146. }
  1147. // Retrieve the uploads sub-directory from the full size image.
  1148. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
  1149. if ( $dirname ) {
  1150. $dirname = trailingslashit( $dirname );
  1151. }
  1152. $upload_dir = wp_get_upload_dir();
  1153. $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
  1154. /*
  1155. * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
  1156. * (which is to say, when they share the domain name of the current request).
  1157. */
  1158. if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
  1159. $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
  1160. }
  1161. /*
  1162. * Images that have been edited in WordPress after being uploaded will
  1163. * contain a unique hash. Look for that hash and use it later to filter
  1164. * out images that are leftovers from previous versions.
  1165. */
  1166. $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
  1167. /**
  1168. * Filters the maximum image width to be included in a 'srcset' attribute.
  1169. *
  1170. * @since 4.4.0
  1171. *
  1172. * @param int $max_width The maximum image width to be included in the 'srcset'. Default '2048'.
  1173. * @param int[] $size_array {
  1174. * An array of requested width and height values.
  1175. *
  1176. * @type int $0 The width in pixels.
  1177. * @type int $1 The height in pixels.
  1178. * }
  1179. */
  1180. $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 2048, $size_array );
  1181. // Array to hold URL candidates.
  1182. $sources = array();
  1183. /**
  1184. * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
  1185. * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
  1186. * an incorrect image. See #35045.
  1187. */
  1188. $src_matched = false;
  1189. /*
  1190. * Loop through available images. Only use images that are resized
  1191. * versions of the same edit.
  1192. */
  1193. foreach ( $image_sizes as $image ) {
  1194. $is_src = false;
  1195. // Check if image meta isn't corrupted.
  1196. if ( ! is_array( $image ) ) {
  1197. continue;
  1198. }
  1199. // If the file name is part of the `src`, we've confirmed a match.
  1200. if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
  1201. $src_matched = true;
  1202. $is_src = true;
  1203. }
  1204. // Filter out images that are from previous edits.
  1205. if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
  1206. continue;
  1207. }
  1208. /*
  1209. * Filters out images that are wider than '$max_srcset_image_width' unless
  1210. * that file is in the 'src' attribute.
  1211. */
  1212. if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
  1213. continue;
  1214. }
  1215. // If the image dimensions are within 1px of the expected size, use it.
  1216. if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
  1217. // Add the URL, descriptor, and value to the sources array to be returned.
  1218. $source = array(
  1219. 'url' => $image_baseurl . $image['file'],
  1220. 'descriptor' => 'w',
  1221. 'value' => $image['width'],
  1222. );
  1223. // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
  1224. if ( $is_src ) {
  1225. $sources = array( $image['width'] => $source ) + $sources;
  1226. } else {
  1227. $sources[ $image['width'] ] = $source;
  1228. }
  1229. }
  1230. }
  1231. /**
  1232. * Filters an image's 'srcset' sources.
  1233. *
  1234. * @since 4.4.0
  1235. *
  1236. * @param array $sources {
  1237. * One or more arrays of source data to include in the 'srcset'.
  1238. *
  1239. * @type array $width {
  1240. * @type string $url The URL of an image source.
  1241. * @type string $descriptor The descriptor type used in the image candidate string,
  1242. * either 'w' or 'x'.
  1243. * @type int $value The source width if paired with a 'w' descriptor, or a
  1244. * pixel density value if paired with an 'x' descriptor.
  1245. * }
  1246. * }
  1247. * @param array $size_array {
  1248. * An array of requested width and height values.
  1249. *
  1250. * @type int $0 The width in pixels.
  1251. * @type int $1 The height in pixels.
  1252. * }
  1253. * @param string $image_src The 'src' of the image.
  1254. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1255. * @param int $attachment_id Image attachment ID or 0.
  1256. */
  1257. $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
  1258. // Only return a 'srcset' value if there is more than one source.
  1259. if ( ! $src_matched || ! is_array( $sources ) || count( $sources ) < 2 ) {
  1260. return false;
  1261. }
  1262. $srcset = '';
  1263. foreach ( $sources as $source ) {
  1264. $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
  1265. }
  1266. return rtrim( $srcset, ', ' );
  1267. }
  1268. /**
  1269. * Retrieves the value for an image attachment's 'sizes' attribute.
  1270. *
  1271. * @since 4.4.0
  1272. *
  1273. * @see wp_calculate_image_sizes()
  1274. *
  1275. * @param int $attachment_id Image attachment ID.
  1276. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array of
  1277. * width and height values in pixels (in that order). Default 'medium'.
  1278. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1279. * Default null.
  1280. * @return string|false A valid source size value for use in a 'sizes' attribute or false.
  1281. */
  1282. function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
  1283. $image = wp_get_attachment_image_src( $attachment_id, $size );
  1284. if ( ! $image ) {
  1285. return false;
  1286. }
  1287. if ( ! is_array( $image_meta ) ) {
  1288. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1289. }
  1290. $image_src = $image[0];
  1291. $size_array = array(
  1292. absint( $image[1] ),
  1293. absint( $image[2] ),
  1294. );
  1295. return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1296. }
  1297. /**
  1298. * Creates a 'sizes' attribute value for an image.
  1299. *
  1300. * @since 4.4.0
  1301. *
  1302. * @param string|int[] $size Image size. Accepts any registered image size name, or an array of
  1303. * width and height values in pixels (in that order).
  1304. * @param string $image_src Optional. The URL to the image file. Default null.
  1305. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1306. * Default null.
  1307. * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
  1308. * is needed when using the image size name as argument for `$size`. Default 0.
  1309. * @return string|false A valid source size value for use in a 'sizes' attribute or false.
  1310. */
  1311. function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
  1312. $width = 0;
  1313. if ( is_array( $size ) ) {
  1314. $width = absint( $size[0] );
  1315. } elseif ( is_string( $size ) ) {
  1316. if ( ! $image_meta && $attachment_id ) {
  1317. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1318. }
  1319. if ( is_array( $image_meta ) ) {
  1320. $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
  1321. if ( $size_array ) {
  1322. $width = absint( $size_array[0] );
  1323. }
  1324. }
  1325. }
  1326. if ( ! $width ) {
  1327. return false;
  1328. }
  1329. // Setup the default 'sizes' attribute.
  1330. $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
  1331. /**
  1332. * Filters the output of 'wp_calculate_image_sizes()'.
  1333. *
  1334. * @since 4.4.0
  1335. *
  1336. * @param string $sizes A source size value for use in a 'sizes' attribute.
  1337. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  1338. * an array of width and height values in pixels (in that order).
  1339. * @param string|null $image_src The URL to the image file or null.
  1340. * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
  1341. * @param int $attachment_id Image attachment ID of the original image or 0.
  1342. */
  1343. return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
  1344. }
  1345. /**
  1346. * Determines if the image meta data is for the image source file.
  1347. *
  1348. * The image meta data is retrieved by attachment post ID. In some cases the post IDs may change.
  1349. * For example when the website is exported and imported at another website. Then the
  1350. * attachment post IDs that are in post_content for the exported website may not match
  1351. * the same attachments at the new website.
  1352. *
  1353. * @since 5.5.0
  1354. *
  1355. * @param string $image_location The full path or URI to the image file.
  1356. * @param array $image_meta The attachment meta data as returned by 'wp_get_attachment_metadata()'.
  1357. * @param int $attachment_id Optional. The image attachment ID. Default 0.
  1358. * @return bool Whether the image meta is for this image file.
  1359. */
  1360. function wp_image_file_matches_image_meta( $image_location, $image_meta, $attachment_id = 0 ) {
  1361. $match = false;
  1362. // Ensure the $image_meta is valid.
  1363. if ( isset( $image_meta['file'] ) && strlen( $image_meta['file'] ) > 4 ) {
  1364. // Remove quiery args if image URI.
  1365. list( $image_location ) = explode( '?', $image_location );
  1366. // Check if the relative image path from the image meta is at the end of $image_location.
  1367. if ( strrpos( $image_location, $image_meta['file'] ) === strlen( $image_location ) - strlen( $image_meta['file'] ) ) {
  1368. $match = true;
  1369. } else {
  1370. // Retrieve the uploads sub-directory from the full size image.
  1371. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
  1372. if ( $dirname ) {
  1373. $dirname = trailingslashit( $dirname );
  1374. }
  1375. if ( ! empty( $image_meta['original_image'] ) ) {
  1376. $relative_path = $dirname . $image_meta['original_image'];
  1377. if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
  1378. $match = true;
  1379. }
  1380. }
  1381. if ( ! $match && ! empty( $image_meta['sizes'] ) ) {
  1382. foreach ( $image_meta['sizes'] as $image_size_data ) {
  1383. $relative_path = $dirname . $image_size_data['file'];
  1384. if ( strrpos( $image_location, $relative_path ) === strlen( $image_location ) - strlen( $relative_path ) ) {
  1385. $match = true;
  1386. break;
  1387. }
  1388. }
  1389. }
  1390. }
  1391. }
  1392. /**
  1393. * Filters whether an image path or URI matches image meta.
  1394. *
  1395. * @since 5.5.0
  1396. *
  1397. * @param bool $match Whether the image relative path from the image meta
  1398. * matches the end of the URI or path to the image file.
  1399. * @param string $image_location Full path or URI to the tested image file.
  1400. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1401. * @param int $attachment_id The image attachment ID or 0 if not supplied.
  1402. */
  1403. return apply_filters( 'wp_image_file_matches_image_meta', $match, $image_location, $image_meta, $attachment_id );
  1404. }
  1405. /**
  1406. * Determines an image's width and height dimensions based on the source file.
  1407. *
  1408. * @since 5.5.0
  1409. *
  1410. * @param string $image_src The image source file.
  1411. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1412. * @param int $attachment_id Optional. The image attachment ID. Default 0.
  1413. * @return array|false Array with first element being the width and second element being the height,
  1414. * or false if dimensions cannot be determined.
  1415. */
  1416. function wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id = 0 ) {
  1417. $dimensions = false;
  1418. // Is it a full size image?
  1419. if (
  1420. isset( $image_meta['file'] ) &&
  1421. strpos( $image_src, wp_basename( $image_meta['file'] ) ) !== false
  1422. ) {
  1423. $dimensions = array(
  1424. (int) $image_meta['width'],
  1425. (int) $image_meta['height'],
  1426. );
  1427. }
  1428. if ( ! $dimensions && ! empty( $image_meta['sizes'] ) ) {
  1429. $src_filename = wp_basename( $image_src );
  1430. foreach ( $image_meta['sizes'] as $image_size_data ) {
  1431. if ( $src_filename === $image_size_data['file'] ) {
  1432. $dimensions = array(
  1433. (int) $image_size_data['width'],
  1434. (int) $image_size_data['height'],
  1435. );
  1436. break;
  1437. }
  1438. }
  1439. }
  1440. /**
  1441. * Filters the 'wp_image_src_get_dimensions' value.
  1442. *
  1443. * @since 5.7.0
  1444. *
  1445. * @param array|false $dimensions Array with first element being the width
  1446. * and second element being the height, or
  1447. * false if dimensions could not be determined.
  1448. * @param string $image_src The image source file.
  1449. * @param array $image_meta The image meta data as returned by
  1450. * 'wp_get_attachment_metadata()'.
  1451. * @param int $attachment_id The image attachment ID. Default 0.
  1452. */
  1453. return apply_filters( 'wp_image_src_get_dimensions', $dimensions, $image_src, $image_meta, $attachment_id );
  1454. }
  1455. /**
  1456. * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
  1457. *
  1458. * @since 4.4.0
  1459. *
  1460. * @see wp_calculate_image_srcset()
  1461. * @see wp_calculate_image_sizes()
  1462. *
  1463. * @param string $image An HTML 'img' element to be filtered.
  1464. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1465. * @param int $attachment_id Image attachment ID.
  1466. * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
  1467. */
  1468. function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
  1469. // Ensure the image meta exists.
  1470. if ( empty( $image_meta['sizes'] ) ) {
  1471. return $image;
  1472. }
  1473. $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
  1474. list( $image_src ) = explode( '?', $image_src );
  1475. // Return early if we couldn't get the image source.
  1476. if ( ! $image_src ) {
  1477. return $image;
  1478. }
  1479. // Bail early if an image has been inserted and later edited.
  1480. if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
  1481. strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
  1482. return $image;
  1483. }
  1484. $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
  1485. $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
  1486. if ( $width && $height ) {
  1487. $size_array = array( $width, $height );
  1488. } else {
  1489. $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
  1490. if ( ! $size_array ) {
  1491. return $image;
  1492. }
  1493. }
  1494. $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  1495. if ( $srcset ) {
  1496. // Check if there is already a 'sizes' attribute.
  1497. $sizes = strpos( $image, ' sizes=' );
  1498. if ( ! $sizes ) {
  1499. $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1500. }
  1501. }
  1502. if ( $srcset && $sizes ) {
  1503. // Format the 'srcset' and 'sizes' string and escape attributes.
  1504. $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
  1505. if ( is_string( $sizes ) ) {
  1506. $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
  1507. }
  1508. // Add the srcset and sizes attributes to the image markup.
  1509. return preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
  1510. }
  1511. return $image;
  1512. }
  1513. /**
  1514. * Determines whether to add the `loading` attribute to the specified tag in the specified context.
  1515. *
  1516. * @since 5.5.0
  1517. * @since 5.7.0 Now returns `true` by default for `iframe` tags.
  1518. *
  1519. * @param string $tag_name The tag name.
  1520. * @param string $context Additional context, like the current filter name
  1521. * or the function name from where this was called.
  1522. * @return bool Whether to add the attribute.
  1523. */
  1524. function wp_lazy_loading_enabled( $tag_name, $context ) {
  1525. // By default add to all 'img' and 'iframe' tags.
  1526. // See https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-loading
  1527. // See https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-loading
  1528. $default = ( 'img' === $tag_name || 'iframe' === $tag_name );
  1529. /**
  1530. * Filters whether to add the `loading` attribute to the specified tag in the specified context.
  1531. *
  1532. * @since 5.5.0
  1533. *
  1534. * @param bool $default Default value.
  1535. * @param string $tag_name The tag name.
  1536. * @param string $context Additional context, like the current filter name
  1537. * or the function name from where this was called.
  1538. */
  1539. return (bool) apply_filters( 'wp_lazy_loading_enabled', $default, $tag_name, $context );
  1540. }
  1541. /**
  1542. * Filters specific tags in post content and modifies their markup.
  1543. *
  1544. * Modifies HTML tags in post content to include new browser and HTML technologies
  1545. * that may not have existed at the time of post creation. These modifications currently
  1546. * include adding `srcset`, `sizes`, and `loading` attributes to `img` HTML tags, as well
  1547. * as adding `loading` attributes to `iframe` HTML tags.
  1548. * Future similar optimizations should be added/expected here.
  1549. *
  1550. * @since 5.5.0
  1551. * @since 5.7.0 Now supports adding `loading` attributes to `iframe` tags.
  1552. *
  1553. * @see wp_img_tag_add_width_and_height_attr()
  1554. * @see wp_img_tag_add_srcset_and_sizes_attr()
  1555. * @see wp_img_tag_add_loading_attr()
  1556. * @see wp_iframe_tag_add_loading_attr()
  1557. *
  1558. * @param string $content The HTML content to be filtered.
  1559. * @param string $context Optional. Additional context to pass to the filters.
  1560. * Defaults to `current_filter()` when not set.
  1561. * @return string Converted content with images modified.
  1562. */
  1563. function wp_filter_content_tags( $content, $context = null ) {
  1564. if ( null === $context ) {
  1565. $context = current_filter();
  1566. }
  1567. $add_img_loading_attr = wp_lazy_loading_enabled( 'img', $context );
  1568. $add_iframe_loading_attr = wp_lazy_loading_enabled( 'iframe', $context );
  1569. if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
  1570. return $content;
  1571. }
  1572. // List of the unique `img` tags found in $content.
  1573. $images = array();
  1574. // List of the unique `iframe` tags found in $content.
  1575. $iframes = array();
  1576. foreach ( $matches as $match ) {
  1577. list( $tag, $tag_name ) = $match;
  1578. switch ( $tag_name ) {
  1579. case 'img':
  1580. if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) {
  1581. $attachment_id = absint( $class_id[1] );
  1582. if ( $attachment_id ) {
  1583. // If exactly the same image tag is used more than once, overwrite it.
  1584. // All identical tags will be replaced later with 'str_replace()'.
  1585. $images[ $tag ] = $attachment_id;
  1586. break;
  1587. }
  1588. }
  1589. $images[ $tag ] = 0;
  1590. break;
  1591. case 'iframe':
  1592. $iframes[ $tag ] = 0;
  1593. break;
  1594. }
  1595. }
  1596. // Reduce the array to unique attachment IDs.
  1597. $attachment_ids = array_unique( array_filter( array_values( $images ) ) );
  1598. if ( count( $attachment_ids ) > 1 ) {
  1599. /*
  1600. * Warm the object cache with post and meta information for all found
  1601. * images to avoid making individual database calls.
  1602. */
  1603. _prime_post_caches( $attachment_ids, false, true );
  1604. }
  1605. // Iterate through the matches in order of occurrence as it is relevant for whether or not to lazy-load.
  1606. foreach ( $matches as $match ) {
  1607. // Filter an image match.
  1608. if ( isset( $images[ $match[0] ] ) ) {
  1609. $filtered_image = $match[0];
  1610. $attachment_id = $images[ $match[0] ];
  1611. // Add 'width' and 'height' attributes if applicable.
  1612. if ( $attachment_id > 0 && false === strpos( $filtered_image, ' width=' ) && false === strpos( $filtered_image, ' height=' ) ) {
  1613. $filtered_image = wp_img_tag_add_width_and_height_attr( $filtered_image, $context, $attachment_id );
  1614. }
  1615. // Add 'srcset' and 'sizes' attributes if applicable.
  1616. if ( $attachment_id > 0 && false === strpos( $filtered_image, ' srcset=' ) ) {
  1617. $filtered_image = wp_img_tag_add_srcset_and_sizes_attr( $filtered_image, $context, $attachment_id );
  1618. }
  1619. // Add 'loading' attribute if applicable.
  1620. if ( $add_img_loading_attr && false === strpos( $filtered_image, ' loading=' ) ) {
  1621. $filtered_image = wp_img_tag_add_loading_attr( $filtered_image, $context );
  1622. }
  1623. if ( $filtered_image !== $match[0] ) {
  1624. $content = str_replace( $match[0], $filtered_image, $content );
  1625. }
  1626. }
  1627. // Filter an iframe match.
  1628. if ( isset( $iframes[ $match[0] ] ) ) {
  1629. $filtered_iframe = $match[0];
  1630. // Add 'loading' attribute if applicable.
  1631. if ( $add_iframe_loading_attr && false === strpos( $filtered_iframe, ' loading=' ) ) {
  1632. $filtered_iframe = wp_iframe_tag_add_loading_attr( $filtered_iframe, $context );
  1633. }
  1634. if ( $filtered_iframe !== $match[0] ) {
  1635. $content = str_replace( $match[0], $filtered_iframe, $content );
  1636. }
  1637. }
  1638. }
  1639. return $content;
  1640. }
  1641. /**
  1642. * Adds `loading` attribute to an `img` HTML tag.
  1643. *
  1644. * @since 5.5.0
  1645. *
  1646. * @param string $image The HTML `img` tag where the attribute should be added.
  1647. * @param string $context Additional context to pass to the filters.
  1648. * @return string Converted `img` tag with `loading` attribute added.
  1649. */
  1650. function wp_img_tag_add_loading_attr( $image, $context ) {
  1651. // Get loading attribute value to use. This must occur before the conditional check below so that even images that
  1652. // are ineligible for being lazy-loaded are considered.
  1653. $value = wp_get_loading_attr_default( $context );
  1654. // Images should have source and dimension attributes for the `loading` attribute to be added.
  1655. if ( false === strpos( $image, ' src="' ) || false === strpos( $image, ' width="' ) || false === strpos( $image, ' height="' ) ) {
  1656. return $image;
  1657. }
  1658. /**
  1659. * Filters the `loading` attribute value to add to an image. Default `lazy`.
  1660. *
  1661. * Returning `false` or an empty string will not add the attribute.
  1662. * Returning `true` will add the default value.
  1663. *
  1664. * @since 5.5.0
  1665. *
  1666. * @param string|bool $value The `loading` attribute value. Returning a falsey value will result in
  1667. * the attribute being omitted for the image.
  1668. * @param string $image The HTML `img` tag to be filtered.
  1669. * @param string $context Additional context about how the function was called or where the img tag is.
  1670. */
  1671. $value = apply_filters( 'wp_img_tag_add_loading_attr', $value, $image, $context );
  1672. if ( $value ) {
  1673. if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
  1674. $value = 'lazy';
  1675. }
  1676. return str_replace( '<img', '<img loading="' . esc_attr( $value ) . '"', $image );
  1677. }
  1678. return $image;
  1679. }
  1680. /**
  1681. * Adds `width` and `height` attributes to an `img` HTML tag.
  1682. *
  1683. * @since 5.5.0
  1684. *
  1685. * @param string $image The HTML `img` tag where the attribute should be added.
  1686. * @param string $context Additional context to pass to the filters.
  1687. * @param int $attachment_id Image attachment ID.
  1688. * @return string Converted 'img' element with 'width' and 'height' attributes added.
  1689. */
  1690. function wp_img_tag_add_width_and_height_attr( $image, $context, $attachment_id ) {
  1691. $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
  1692. list( $image_src ) = explode( '?', $image_src );
  1693. // Return early if we couldn't get the image source.
  1694. if ( ! $image_src ) {
  1695. return $image;
  1696. }
  1697. /**
  1698. * Filters whether to add the missing `width` and `height` HTML attributes to the img tag. Default `true`.
  1699. *
  1700. * Returning anything else than `true` will not add the attributes.
  1701. *
  1702. * @since 5.5.0
  1703. *
  1704. * @param bool $value The filtered value, defaults to `true`.
  1705. * @param string $image The HTML `img` tag where the attribute should be added.
  1706. * @param string $context Additional context about how the function was called or where the img tag is.
  1707. * @param int $attachment_id The image attachment ID.
  1708. */
  1709. $add = apply_filters( 'wp_img_tag_add_width_and_height_attr', true, $image, $context, $attachment_id );
  1710. if ( true === $add ) {
  1711. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1712. $size_array = wp_image_src_get_dimensions( $image_src, $image_meta, $attachment_id );
  1713. if ( $size_array ) {
  1714. $hw = trim( image_hwstring( $size_array[0], $size_array[1] ) );
  1715. return str_replace( '<img', "<img {$hw}", $image );
  1716. }
  1717. }
  1718. return $image;
  1719. }
  1720. /**
  1721. * Adds `srcset` and `sizes` attributes to an existing `img` HTML tag.
  1722. *
  1723. * @since 5.5.0
  1724. *
  1725. * @param string $image The HTML `img` tag where the attribute should be added.
  1726. * @param string $context Additional context to pass to the filters.
  1727. * @param int $attachment_id Image attachment ID.
  1728. * @return string Converted 'img' element with 'loading' attribute added.
  1729. */
  1730. function wp_img_tag_add_srcset_and_sizes_attr( $image, $context, $attachment_id ) {
  1731. /**
  1732. * Filters whether to add the `srcset` and `sizes` HTML attributes to the img tag. Default `true`.
  1733. *
  1734. * Returning anything else than `true` will not add the attributes.
  1735. *
  1736. * @since 5.5.0
  1737. *
  1738. * @param bool $value The filtered value, defaults to `true`.
  1739. * @param string $image The HTML `img` tag where the attribute should be added.
  1740. * @param string $context Additional context about how the function was called or where the img tag is.
  1741. * @param int $attachment_id The image attachment ID.
  1742. */
  1743. $add = apply_filters( 'wp_img_tag_add_srcset_and_sizes_attr', true, $image, $context, $attachment_id );
  1744. if ( true === $add ) {
  1745. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1746. return wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );
  1747. }
  1748. return $image;
  1749. }
  1750. /**
  1751. * Adds `loading` attribute to an `iframe` HTML tag.
  1752. *
  1753. * @since 5.7.0
  1754. *
  1755. * @param string $iframe The HTML `iframe` tag where the attribute should be added.
  1756. * @param string $context Additional context to pass to the filters.
  1757. * @return string Converted `iframe` tag with `loading` attribute added.
  1758. */
  1759. function wp_iframe_tag_add_loading_attr( $iframe, $context ) {
  1760. // Iframes with fallback content (see `wp_filter_oembed_result()`) should not be lazy-loaded because they are
  1761. // visually hidden initially.
  1762. if ( false !== strpos( $iframe, ' data-secret="' ) ) {
  1763. return $iframe;
  1764. }
  1765. // Get loading attribute value to use. This must occur before the conditional check below so that even iframes that
  1766. // are ineligible for being lazy-loaded are considered.
  1767. $value = wp_get_loading_attr_default( $context );
  1768. // Iframes should have source and dimension attributes for the `loading` attribute to be added.
  1769. if ( false === strpos( $iframe, ' src="' ) || false === strpos( $iframe, ' width="' ) || false === strpos( $iframe, ' height="' ) ) {
  1770. return $iframe;
  1771. }
  1772. /**
  1773. * Filters the `loading` attribute value to add to an iframe. Default `lazy`.
  1774. *
  1775. * Returning `false` or an empty string will not add the attribute.
  1776. * Returning `true` will add the default value.
  1777. *
  1778. * @since 5.7.0
  1779. *
  1780. * @param string|bool $value The `loading` attribute value. Returning a falsey value will result in
  1781. * the attribute being omitted for the iframe.
  1782. * @param string $iframe The HTML `iframe` tag to be filtered.
  1783. * @param string $context Additional context about how the function was called or where the iframe tag is.
  1784. */
  1785. $value = apply_filters( 'wp_iframe_tag_add_loading_attr', $value, $iframe, $context );
  1786. if ( $value ) {
  1787. if ( ! in_array( $value, array( 'lazy', 'eager' ), true ) ) {
  1788. $value = 'lazy';
  1789. }
  1790. return str_replace( '<iframe', '<iframe loading="' . esc_attr( $value ) . '"', $iframe );
  1791. }
  1792. return $iframe;
  1793. }
  1794. /**
  1795. * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
  1796. *
  1797. * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
  1798. * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
  1799. *
  1800. * @ignore
  1801. * @since 2.9.0
  1802. *
  1803. * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
  1804. * @return string[] Modified array of attributes including the new 'wp-post-image' class.
  1805. */
  1806. function _wp_post_thumbnail_class_filter( $attr ) {
  1807. $attr['class'] .= ' wp-post-image';
  1808. return $attr;
  1809. }
  1810. /**
  1811. * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
  1812. * filter hook. Internal use only.
  1813. *
  1814. * @ignore
  1815. * @since 2.9.0
  1816. *
  1817. * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
  1818. */
  1819. function _wp_post_thumbnail_class_filter_add( $attr ) {
  1820. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1821. }
  1822. /**
  1823. * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
  1824. * filter hook. Internal use only.
  1825. *
  1826. * @ignore
  1827. * @since 2.9.0
  1828. *
  1829. * @param string[] $attr Array of thumbnail attributes including src, class, alt, title, keyed by attribute name.
  1830. */
  1831. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  1832. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1833. }
  1834. add_shortcode( 'wp_caption', 'img_caption_shortcode' );
  1835. add_shortcode( 'caption', 'img_caption_shortcode' );
  1836. /**
  1837. * Builds the Caption shortcode output.
  1838. *
  1839. * Allows a plugin to replace the content that would otherwise be returned. The
  1840. * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
  1841. * parameter and the content parameter values.
  1842. *
  1843. * The supported attributes for the shortcode are 'id', 'caption_id', 'align',
  1844. * 'width', 'caption', and 'class'.
  1845. *
  1846. * @since 2.6.0
  1847. * @since 3.9.0 The `class` attribute was added.
  1848. * @since 5.1.0 The `caption_id` attribute was added.
  1849. * @since 5.9.0 The `$content` parameter default value changed from `null` to `''`.
  1850. *
  1851. * @param array $attr {
  1852. * Attributes of the caption shortcode.
  1853. *
  1854. * @type string $id ID of the image and caption container element, i.e. `<figure>` or `<div>`.
  1855. * @type string $caption_id ID of the caption element, i.e. `<figcaption>` or `<p>`.
  1856. * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
  1857. * 'aligncenter', alignright', 'alignnone'.
  1858. * @type int $width The width of the caption, in pixels.
  1859. * @type string $caption The caption text.
  1860. * @type string $class Additional class name(s) added to the caption container.
  1861. * }
  1862. * @param string $content Optional. Shortcode content. Default empty string.
  1863. * @return string HTML content to display the caption.
  1864. */
  1865. function img_caption_shortcode( $attr, $content = '' ) {
  1866. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  1867. if ( ! isset( $attr['caption'] ) ) {
  1868. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  1869. $content = $matches[1];
  1870. $attr['caption'] = trim( $matches[2] );
  1871. }
  1872. } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
  1873. $attr['caption'] = wp_kses( $attr['caption'], 'post' );
  1874. }
  1875. /**
  1876. * Filters the default caption shortcode output.
  1877. *
  1878. * If the filtered output isn't empty, it will be used instead of generating
  1879. * the default caption template.
  1880. *
  1881. * @since 2.6.0
  1882. *
  1883. * @see img_caption_shortcode()
  1884. *
  1885. * @param string $output The caption output. Default empty.
  1886. * @param array $attr Attributes of the caption shortcode.
  1887. * @param string $content The image element, possibly wrapped in a hyperlink.
  1888. */
  1889. $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
  1890. if ( ! empty( $output ) ) {
  1891. return $output;
  1892. }
  1893. $atts = shortcode_atts(
  1894. array(
  1895. 'id' => '',
  1896. 'caption_id' => '',
  1897. 'align' => 'alignnone',
  1898. 'width' => '',
  1899. 'caption' => '',
  1900. 'class' => '',
  1901. ),
  1902. $attr,
  1903. 'caption'
  1904. );
  1905. $atts['width'] = (int) $atts['width'];
  1906. if ( $atts['width'] < 1 || empty( $atts['caption'] ) ) {
  1907. return $content;
  1908. }
  1909. $id = '';
  1910. $caption_id = '';
  1911. $describedby = '';
  1912. if ( $atts['id'] ) {
  1913. $atts['id'] = sanitize_html_class( $atts['id'] );
  1914. $id = 'id="' . esc_attr( $atts['id'] ) . '" ';
  1915. }
  1916. if ( $atts['caption_id'] ) {
  1917. $atts['caption_id'] = sanitize_html_class( $atts['caption_id'] );
  1918. } elseif ( $atts['id'] ) {
  1919. $atts['caption_id'] = 'caption-' . str_replace( '_', '-', $atts['id'] );
  1920. }
  1921. if ( $atts['caption_id'] ) {
  1922. $caption_id = 'id="' . esc_attr( $atts['caption_id'] ) . '" ';
  1923. $describedby = 'aria-describedby="' . esc_attr( $atts['caption_id'] ) . '" ';
  1924. }
  1925. $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
  1926. $html5 = current_theme_supports( 'html5', 'caption' );
  1927. // HTML5 captions never added the extra 10px to the image width.
  1928. $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
  1929. /**
  1930. * Filters the width of an image's caption.
  1931. *
  1932. * By default, the caption is 10 pixels greater than the width of the image,
  1933. * to prevent post content from running up against a floated image.
  1934. *
  1935. * @since 3.7.0
  1936. *
  1937. * @see img_caption_shortcode()
  1938. *
  1939. * @param int $width Width of the caption in pixels. To remove this inline style,
  1940. * return zero.
  1941. * @param array $atts Attributes of the caption shortcode.
  1942. * @param string $content The image element, possibly wrapped in a hyperlink.
  1943. */
  1944. $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
  1945. $style = '';
  1946. if ( $caption_width ) {
  1947. $style = 'style="width: ' . (int) $caption_width . 'px" ';
  1948. }
  1949. if ( $html5 ) {
  1950. $html = sprintf(
  1951. '<figure %s%s%sclass="%s">%s%s</figure>',
  1952. $id,
  1953. $describedby,
  1954. $style,
  1955. esc_attr( $class ),
  1956. do_shortcode( $content ),
  1957. sprintf(
  1958. '<figcaption %sclass="wp-caption-text">%s</figcaption>',
  1959. $caption_id,
  1960. $atts['caption']
  1961. )
  1962. );
  1963. } else {
  1964. $html = sprintf(
  1965. '<div %s%sclass="%s">%s%s</div>',
  1966. $id,
  1967. $style,
  1968. esc_attr( $class ),
  1969. str_replace( '<img ', '<img ' . $describedby, do_shortcode( $content ) ),
  1970. sprintf(
  1971. '<p %sclass="wp-caption-text">%s</p>',
  1972. $caption_id,
  1973. $atts['caption']
  1974. )
  1975. );
  1976. }
  1977. return $html;
  1978. }
  1979. add_shortcode( 'gallery', 'gallery_shortcode' );
  1980. /**
  1981. * Builds the Gallery shortcode output.
  1982. *
  1983. * This implements the functionality of the Gallery Shortcode for displaying
  1984. * WordPress images on a post.
  1985. *
  1986. * @since 2.5.0
  1987. *
  1988. * @param array $attr {
  1989. * Attributes of the gallery shortcode.
  1990. *
  1991. * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
  1992. * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
  1993. * Accepts any valid SQL ORDERBY statement.
  1994. * @type int $id Post ID.
  1995. * @type string $itemtag HTML tag to use for each image in the gallery.
  1996. * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
  1997. * @type string $icontag HTML tag to use for each image's icon.
  1998. * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
  1999. * @type string $captiontag HTML tag to use for each image's caption.
  2000. * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
  2001. * @type int $columns Number of columns of images to display. Default 3.
  2002. * @type string|int[] $size Size of the images to display. Accepts any registered image size name, or an array
  2003. * of width and height values in pixels (in that order). Default 'thumbnail'.
  2004. * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
  2005. * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
  2006. * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
  2007. * @type string $link What to link each image to. Default empty (links to the attachment page).
  2008. * Accepts 'file', 'none'.
  2009. * }
  2010. * @return string HTML content to display gallery.
  2011. */
  2012. function gallery_shortcode( $attr ) {
  2013. $post = get_post();
  2014. static $instance = 0;
  2015. $instance++;
  2016. if ( ! empty( $attr['ids'] ) ) {
  2017. // 'ids' is explicitly ordered, unless you specify otherwise.
  2018. if ( empty( $attr['orderby'] ) ) {
  2019. $attr['orderby'] = 'post__in';
  2020. }
  2021. $attr['include'] = $attr['ids'];
  2022. }
  2023. /**
  2024. * Filters the default gallery shortcode output.
  2025. *
  2026. * If the filtered output isn't empty, it will be used instead of generating
  2027. * the default gallery template.
  2028. *
  2029. * @since 2.5.0
  2030. * @since 4.2.0 The `$instance` parameter was added.
  2031. *
  2032. * @see gallery_shortcode()
  2033. *
  2034. * @param string $output The gallery output. Default empty.
  2035. * @param array $attr Attributes of the gallery shortcode.
  2036. * @param int $instance Unique numeric ID of this gallery shortcode instance.
  2037. */
  2038. $output = apply_filters( 'post_gallery', '', $attr, $instance );
  2039. if ( ! empty( $output ) ) {
  2040. return $output;
  2041. }
  2042. $html5 = current_theme_supports( 'html5', 'gallery' );
  2043. $atts = shortcode_atts(
  2044. array(
  2045. 'order' => 'ASC',
  2046. 'orderby' => 'menu_order ID',
  2047. 'id' => $post ? $post->ID : 0,
  2048. 'itemtag' => $html5 ? 'figure' : 'dl',
  2049. 'icontag' => $html5 ? 'div' : 'dt',
  2050. 'captiontag' => $html5 ? 'figcaption' : 'dd',
  2051. 'columns' => 3,
  2052. 'size' => 'thumbnail',
  2053. 'include' => '',
  2054. 'exclude' => '',
  2055. 'link' => '',
  2056. ),
  2057. $attr,
  2058. 'gallery'
  2059. );
  2060. $id = (int) $atts['id'];
  2061. if ( ! empty( $atts['include'] ) ) {
  2062. $_attachments = get_posts(
  2063. array(
  2064. 'include' => $atts['include'],
  2065. 'post_status' => 'inherit',
  2066. 'post_type' => 'attachment',
  2067. 'post_mime_type' => 'image',
  2068. 'order' => $atts['order'],
  2069. 'orderby' => $atts['orderby'],
  2070. )
  2071. );
  2072. $attachments = array();
  2073. foreach ( $_attachments as $key => $val ) {
  2074. $attachments[ $val->ID ] = $_attachments[ $key ];
  2075. }
  2076. } elseif ( ! empty( $atts['exclude'] ) ) {
  2077. $attachments = get_children(
  2078. array(
  2079. 'post_parent' => $id,
  2080. 'exclude' => $atts['exclude'],
  2081. 'post_status' => 'inherit',
  2082. 'post_type' => 'attachment',
  2083. 'post_mime_type' => 'image',
  2084. 'order' => $atts['order'],
  2085. 'orderby' => $atts['orderby'],
  2086. )
  2087. );
  2088. } else {
  2089. $attachments = get_children(
  2090. array(
  2091. 'post_parent' => $id,
  2092. 'post_status' => 'inherit',
  2093. 'post_type' => 'attachment',
  2094. 'post_mime_type' => 'image',
  2095. 'order' => $atts['order'],
  2096. 'orderby' => $atts['orderby'],
  2097. )
  2098. );
  2099. }
  2100. if ( empty( $attachments ) ) {
  2101. return '';
  2102. }
  2103. if ( is_feed() ) {
  2104. $output = "\n";
  2105. foreach ( $attachments as $att_id => $attachment ) {
  2106. if ( ! empty( $atts['link'] ) ) {
  2107. if ( 'none' === $atts['link'] ) {
  2108. $output .= wp_get_attachment_image( $att_id, $atts['size'], false, $attr );
  2109. } else {
  2110. $output .= wp_get_attachment_link( $att_id, $atts['size'], false );
  2111. }
  2112. } else {
  2113. $output .= wp_get_attachment_link( $att_id, $atts['size'], true );
  2114. }
  2115. $output .= "\n";
  2116. }
  2117. return $output;
  2118. }
  2119. $itemtag = tag_escape( $atts['itemtag'] );
  2120. $captiontag = tag_escape( $atts['captiontag'] );
  2121. $icontag = tag_escape( $atts['icontag'] );
  2122. $valid_tags = wp_kses_allowed_html( 'post' );
  2123. if ( ! isset( $valid_tags[ $itemtag ] ) ) {
  2124. $itemtag = 'dl';
  2125. }
  2126. if ( ! isset( $valid_tags[ $captiontag ] ) ) {
  2127. $captiontag = 'dd';
  2128. }
  2129. if ( ! isset( $valid_tags[ $icontag ] ) ) {
  2130. $icontag = 'dt';
  2131. }
  2132. $columns = (int) $atts['columns'];
  2133. $itemwidth = $columns > 0 ? floor( 100 / $columns ) : 100;
  2134. $float = is_rtl() ? 'right' : 'left';
  2135. $selector = "gallery-{$instance}";
  2136. $gallery_style = '';
  2137. /**
  2138. * Filters whether to print default gallery styles.
  2139. *
  2140. * @since 3.1.0
  2141. *
  2142. * @param bool $print Whether to print default gallery styles.
  2143. * Defaults to false if the theme supports HTML5 galleries.
  2144. * Otherwise, defaults to true.
  2145. */
  2146. if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
  2147. $type_attr = current_theme_supports( 'html5', 'style' ) ? '' : ' type="text/css"';
  2148. $gallery_style = "
  2149. <style{$type_attr}>
  2150. #{$selector} {
  2151. margin: auto;
  2152. }
  2153. #{$selector} .gallery-item {
  2154. float: {$float};
  2155. margin-top: 10px;
  2156. text-align: center;
  2157. width: {$itemwidth}%;
  2158. }
  2159. #{$selector} img {
  2160. border: 2px solid #cfcfcf;
  2161. }
  2162. #{$selector} .gallery-caption {
  2163. margin-left: 0;
  2164. }
  2165. /* see gallery_shortcode() in wp-includes/media.php */
  2166. </style>\n\t\t";
  2167. }
  2168. $size_class = sanitize_html_class( is_array( $atts['size'] ) ? implode( 'x', $atts['size'] ) : $atts['size'] );
  2169. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  2170. /**
  2171. * Filters the default gallery shortcode CSS styles.
  2172. *
  2173. * @since 2.5.0
  2174. *
  2175. * @param string $gallery_style Default CSS styles and opening HTML div container
  2176. * for the gallery shortcode output.
  2177. */
  2178. $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
  2179. $i = 0;
  2180. foreach ( $attachments as $id => $attachment ) {
  2181. $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
  2182. if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
  2183. $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
  2184. } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
  2185. $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
  2186. } else {
  2187. $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
  2188. }
  2189. $image_meta = wp_get_attachment_metadata( $id );
  2190. $orientation = '';
  2191. if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
  2192. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  2193. }
  2194. $output .= "<{$itemtag} class='gallery-item'>";
  2195. $output .= "
  2196. <{$icontag} class='gallery-icon {$orientation}'>
  2197. $image_output
  2198. </{$icontag}>";
  2199. if ( $captiontag && trim( $attachment->post_excerpt ) ) {
  2200. $output .= "
  2201. <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
  2202. " . wptexturize( $attachment->post_excerpt ) . "
  2203. </{$captiontag}>";
  2204. }
  2205. $output .= "</{$itemtag}>";
  2206. if ( ! $html5 && $columns > 0 && 0 === ++$i % $columns ) {
  2207. $output .= '<br style="clear: both" />';
  2208. }
  2209. }
  2210. if ( ! $html5 && $columns > 0 && 0 !== $i % $columns ) {
  2211. $output .= "
  2212. <br style='clear: both' />";
  2213. }
  2214. $output .= "
  2215. </div>\n";
  2216. return $output;
  2217. }
  2218. /**
  2219. * Outputs the templates used by playlists.
  2220. *
  2221. * @since 3.9.0
  2222. */
  2223. function wp_underscore_playlist_templates() {
  2224. ?>
  2225. <script type="text/html" id="tmpl-wp-playlist-current-item">
  2226. <# if ( data.thumb && data.thumb.src ) { #>
  2227. <img src="{{ data.thumb.src }}" alt="" />
  2228. <# } #>
  2229. <div class="wp-playlist-caption">
  2230. <span class="wp-playlist-item-meta wp-playlist-item-title">
  2231. <?php
  2232. /* translators: %s: Playlist item title. */
  2233. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
  2234. ?>
  2235. </span>
  2236. <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
  2237. <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
  2238. </div>
  2239. </script>
  2240. <script type="text/html" id="tmpl-wp-playlist-item">
  2241. <div class="wp-playlist-item">
  2242. <a class="wp-playlist-caption" href="{{ data.src }}">
  2243. {{ data.index ? ( data.index + '. ' ) : '' }}
  2244. <# if ( data.caption ) { #>
  2245. {{ data.caption }}
  2246. <# } else { #>
  2247. <span class="wp-playlist-item-title">
  2248. <?php
  2249. /* translators: %s: Playlist item title. */
  2250. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
  2251. ?>
  2252. </span>
  2253. <# if ( data.artists && data.meta.artist ) { #>
  2254. <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
  2255. <# } #>
  2256. <# } #>
  2257. </a>
  2258. <# if ( data.meta.length_formatted ) { #>
  2259. <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
  2260. <# } #>
  2261. </div>
  2262. </script>
  2263. <?php
  2264. }
  2265. /**
  2266. * Outputs and enqueue default scripts and styles for playlists.
  2267. *
  2268. * @since 3.9.0
  2269. *
  2270. * @param string $type Type of playlist. Accepts 'audio' or 'video'.
  2271. */
  2272. function wp_playlist_scripts( $type ) {
  2273. wp_enqueue_style( 'wp-mediaelement' );
  2274. wp_enqueue_script( 'wp-playlist' );
  2275. ?>
  2276. <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ); ?>');</script><![endif]-->
  2277. <?php
  2278. add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
  2279. add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
  2280. }
  2281. /**
  2282. * Builds the Playlist shortcode output.
  2283. *
  2284. * This implements the functionality of the playlist shortcode for displaying
  2285. * a collection of WordPress audio or video files in a post.
  2286. *
  2287. * @since 3.9.0
  2288. *
  2289. * @global int $content_width
  2290. *
  2291. * @param array $attr {
  2292. * Array of default playlist attributes.
  2293. *
  2294. * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
  2295. * @type string $order Designates ascending or descending order of items in the playlist.
  2296. * Accepts 'ASC', 'DESC'. Default 'ASC'.
  2297. * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
  2298. * passed, this defaults to the order of the $ids array ('post__in').
  2299. * Otherwise default is 'menu_order ID'.
  2300. * @type int $id If an explicit $ids array is not present, this parameter
  2301. * will determine which attachments are used for the playlist.
  2302. * Default is the current post ID.
  2303. * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
  2304. * a playlist will be created from all $type attachments of $id.
  2305. * Default empty.
  2306. * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
  2307. * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
  2308. * @type bool $tracklist Whether to show or hide the playlist. Default true.
  2309. * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
  2310. * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
  2311. * thumbnail). Default true.
  2312. * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
  2313. * }
  2314. *
  2315. * @return string Playlist output. Empty string if the passed type is unsupported.
  2316. */
  2317. function wp_playlist_shortcode( $attr ) {
  2318. global $content_width;
  2319. $post = get_post();
  2320. static $instance = 0;
  2321. $instance++;
  2322. if ( ! empty( $attr['ids'] ) ) {
  2323. // 'ids' is explicitly ordered, unless you specify otherwise.
  2324. if ( empty( $attr['orderby'] ) ) {
  2325. $attr['orderby'] = 'post__in';
  2326. }
  2327. $attr['include'] = $attr['ids'];
  2328. }
  2329. /**
  2330. * Filters the playlist output.
  2331. *
  2332. * Returning a non-empty value from the filter will short-circuit generation
  2333. * of the default playlist output, returning the passed value instead.
  2334. *
  2335. * @since 3.9.0
  2336. * @since 4.2.0 The `$instance` parameter was added.
  2337. *
  2338. * @param string $output Playlist output. Default empty.
  2339. * @param array $attr An array of shortcode attributes.
  2340. * @param int $instance Unique numeric ID of this playlist shortcode instance.
  2341. */
  2342. $output = apply_filters( 'post_playlist', '', $attr, $instance );
  2343. if ( ! empty( $output ) ) {
  2344. return $output;
  2345. }
  2346. $atts = shortcode_atts(
  2347. array(
  2348. 'type' => 'audio',
  2349. 'order' => 'ASC',
  2350. 'orderby' => 'menu_order ID',
  2351. 'id' => $post ? $post->ID : 0,
  2352. 'include' => '',
  2353. 'exclude' => '',
  2354. 'style' => 'light',
  2355. 'tracklist' => true,
  2356. 'tracknumbers' => true,
  2357. 'images' => true,
  2358. 'artists' => true,
  2359. ),
  2360. $attr,
  2361. 'playlist'
  2362. );
  2363. $id = (int) $atts['id'];
  2364. if ( 'audio' !== $atts['type'] ) {
  2365. $atts['type'] = 'video';
  2366. }
  2367. $args = array(
  2368. 'post_status' => 'inherit',
  2369. 'post_type' => 'attachment',
  2370. 'post_mime_type' => $atts['type'],
  2371. 'order' => $atts['order'],
  2372. 'orderby' => $atts['orderby'],
  2373. );
  2374. if ( ! empty( $atts['include'] ) ) {
  2375. $args['include'] = $atts['include'];
  2376. $_attachments = get_posts( $args );
  2377. $attachments = array();
  2378. foreach ( $_attachments as $key => $val ) {
  2379. $attachments[ $val->ID ] = $_attachments[ $key ];
  2380. }
  2381. } elseif ( ! empty( $atts['exclude'] ) ) {
  2382. $args['post_parent'] = $id;
  2383. $args['exclude'] = $atts['exclude'];
  2384. $attachments = get_children( $args );
  2385. } else {
  2386. $args['post_parent'] = $id;
  2387. $attachments = get_children( $args );
  2388. }
  2389. if ( empty( $attachments ) ) {
  2390. return '';
  2391. }
  2392. if ( is_feed() ) {
  2393. $output = "\n";
  2394. foreach ( $attachments as $att_id => $attachment ) {
  2395. $output .= wp_get_attachment_link( $att_id ) . "\n";
  2396. }
  2397. return $output;
  2398. }
  2399. $outer = 22; // Default padding and border of wrapper.
  2400. $default_width = 640;
  2401. $default_height = 360;
  2402. $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
  2403. $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
  2404. $data = array(
  2405. 'type' => $atts['type'],
  2406. // Don't pass strings to JSON, will be truthy in JS.
  2407. 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
  2408. 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
  2409. 'images' => wp_validate_boolean( $atts['images'] ),
  2410. 'artists' => wp_validate_boolean( $atts['artists'] ),
  2411. );
  2412. $tracks = array();
  2413. foreach ( $attachments as $attachment ) {
  2414. $url = wp_get_attachment_url( $attachment->ID );
  2415. $ftype = wp_check_filetype( $url, wp_get_mime_types() );
  2416. $track = array(
  2417. 'src' => $url,
  2418. 'type' => $ftype['type'],
  2419. 'title' => $attachment->post_title,
  2420. 'caption' => $attachment->post_excerpt,
  2421. 'description' => $attachment->post_content,
  2422. );
  2423. $track['meta'] = array();
  2424. $meta = wp_get_attachment_metadata( $attachment->ID );
  2425. if ( ! empty( $meta ) ) {
  2426. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  2427. if ( ! empty( $meta[ $key ] ) ) {
  2428. $track['meta'][ $key ] = $meta[ $key ];
  2429. }
  2430. }
  2431. if ( 'video' === $atts['type'] ) {
  2432. if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
  2433. $width = $meta['width'];
  2434. $height = $meta['height'];
  2435. $theme_height = round( ( $height * $theme_width ) / $width );
  2436. } else {
  2437. $width = $default_width;
  2438. $height = $default_height;
  2439. }
  2440. $track['dimensions'] = array(
  2441. 'original' => compact( 'width', 'height' ),
  2442. 'resized' => array(
  2443. 'width' => $theme_width,
  2444. 'height' => $theme_height,
  2445. ),
  2446. );
  2447. }
  2448. }
  2449. if ( $atts['images'] ) {
  2450. $thumb_id = get_post_thumbnail_id( $attachment->ID );
  2451. if ( ! empty( $thumb_id ) ) {
  2452. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
  2453. $track['image'] = compact( 'src', 'width', 'height' );
  2454. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
  2455. $track['thumb'] = compact( 'src', 'width', 'height' );
  2456. } else {
  2457. $src = wp_mime_type_icon( $attachment->ID );
  2458. $width = 48;
  2459. $height = 64;
  2460. $track['image'] = compact( 'src', 'width', 'height' );
  2461. $track['thumb'] = compact( 'src', 'width', 'height' );
  2462. }
  2463. }
  2464. $tracks[] = $track;
  2465. }
  2466. $data['tracks'] = $tracks;
  2467. $safe_type = esc_attr( $atts['type'] );
  2468. $safe_style = esc_attr( $atts['style'] );
  2469. ob_start();
  2470. if ( 1 === $instance ) {
  2471. /**
  2472. * Prints and enqueues playlist scripts, styles, and JavaScript templates.
  2473. *
  2474. * @since 3.9.0
  2475. *
  2476. * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
  2477. * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
  2478. */
  2479. do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
  2480. }
  2481. ?>
  2482. <div class="wp-playlist wp-<?php echo $safe_type; ?>-playlist wp-playlist-<?php echo $safe_style; ?>">
  2483. <?php if ( 'audio' === $atts['type'] ) : ?>
  2484. <div class="wp-playlist-current-item"></div>
  2485. <?php endif; ?>
  2486. <<?php echo $safe_type; ?> controls="controls" preload="none" width="<?php echo (int) $theme_width; ?>"
  2487. <?php
  2488. if ( 'video' === $safe_type ) {
  2489. echo ' height="', (int) $theme_height, '"';
  2490. }
  2491. ?>
  2492. ></<?php echo $safe_type; ?>>
  2493. <div class="wp-playlist-next"></div>
  2494. <div class="wp-playlist-prev"></div>
  2495. <noscript>
  2496. <ol>
  2497. <?php
  2498. foreach ( $attachments as $att_id => $attachment ) {
  2499. printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
  2500. }
  2501. ?>
  2502. </ol>
  2503. </noscript>
  2504. <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ); ?></script>
  2505. </div>
  2506. <?php
  2507. return ob_get_clean();
  2508. }
  2509. add_shortcode( 'playlist', 'wp_playlist_shortcode' );
  2510. /**
  2511. * Provides a No-JS Flash fallback as a last resort for audio / video.
  2512. *
  2513. * @since 3.6.0
  2514. *
  2515. * @param string $url The media element URL.
  2516. * @return string Fallback HTML.
  2517. */
  2518. function wp_mediaelement_fallback( $url ) {
  2519. /**
  2520. * Filters the Mediaelement fallback output for no-JS.
  2521. *
  2522. * @since 3.6.0
  2523. *
  2524. * @param string $output Fallback output for no-JS.
  2525. * @param string $url Media file URL.
  2526. */
  2527. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  2528. }
  2529. /**
  2530. * Returns a filtered list of supported audio formats.
  2531. *
  2532. * @since 3.6.0
  2533. *
  2534. * @return string[] Supported audio formats.
  2535. */
  2536. function wp_get_audio_extensions() {
  2537. /**
  2538. * Filters the list of supported audio formats.
  2539. *
  2540. * @since 3.6.0
  2541. *
  2542. * @param string[] $extensions An array of supported audio formats. Defaults are
  2543. * 'mp3', 'ogg', 'flac', 'm4a', 'wav'.
  2544. */
  2545. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
  2546. }
  2547. /**
  2548. * Returns useful keys to use to lookup data from an attachment's stored metadata.
  2549. *
  2550. * @since 3.9.0
  2551. *
  2552. * @param WP_Post $attachment The current attachment, provided for context.
  2553. * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
  2554. * @return string[] Key/value pairs of field keys to labels.
  2555. */
  2556. function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
  2557. $fields = array(
  2558. 'artist' => __( 'Artist' ),
  2559. 'album' => __( 'Album' ),
  2560. );
  2561. if ( 'display' === $context ) {
  2562. $fields['genre'] = __( 'Genre' );
  2563. $fields['year'] = __( 'Year' );
  2564. $fields['length_formatted'] = _x( 'Length', 'video or audio' );
  2565. } elseif ( 'js' === $context ) {
  2566. $fields['bitrate'] = __( 'Bitrate' );
  2567. $fields['bitrate_mode'] = __( 'Bitrate Mode' );
  2568. }
  2569. /**
  2570. * Filters the editable list of keys to look up data from an attachment's metadata.
  2571. *
  2572. * @since 3.9.0
  2573. *
  2574. * @param array $fields Key/value pairs of field keys to labels.
  2575. * @param WP_Post $attachment Attachment object.
  2576. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  2577. */
  2578. return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
  2579. }
  2580. /**
  2581. * Builds the Audio shortcode output.
  2582. *
  2583. * This implements the functionality of the Audio Shortcode for displaying
  2584. * WordPress mp3s in a post.
  2585. *
  2586. * @since 3.6.0
  2587. *
  2588. * @param array $attr {
  2589. * Attributes of the audio shortcode.
  2590. *
  2591. * @type string $src URL to the source of the audio file. Default empty.
  2592. * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
  2593. * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
  2594. * @type string $preload The 'preload' attribute for the `<audio>` element. Default 'none'.
  2595. * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
  2596. * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
  2597. * }
  2598. * @param string $content Shortcode content.
  2599. * @return string|void HTML content to display audio.
  2600. */
  2601. function wp_audio_shortcode( $attr, $content = '' ) {
  2602. $post_id = get_post() ? get_the_ID() : 0;
  2603. static $instance = 0;
  2604. $instance++;
  2605. /**
  2606. * Filters the default audio shortcode output.
  2607. *
  2608. * If the filtered output isn't empty, it will be used instead of generating the default audio template.
  2609. *
  2610. * @since 3.6.0
  2611. *
  2612. * @param string $html Empty variable to be replaced with shortcode markup.
  2613. * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
  2614. * @param string $content Shortcode content.
  2615. * @param int $instance Unique numeric ID of this audio shortcode instance.
  2616. */
  2617. $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
  2618. if ( '' !== $override ) {
  2619. return $override;
  2620. }
  2621. $audio = null;
  2622. $default_types = wp_get_audio_extensions();
  2623. $defaults_atts = array(
  2624. 'src' => '',
  2625. 'loop' => '',
  2626. 'autoplay' => '',
  2627. 'preload' => 'none',
  2628. 'class' => 'wp-audio-shortcode',
  2629. 'style' => 'width: 100%;',
  2630. );
  2631. foreach ( $default_types as $type ) {
  2632. $defaults_atts[ $type ] = '';
  2633. }
  2634. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  2635. $primary = false;
  2636. if ( ! empty( $atts['src'] ) ) {
  2637. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2638. if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
  2639. return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2640. }
  2641. $primary = true;
  2642. array_unshift( $default_types, 'src' );
  2643. } else {
  2644. foreach ( $default_types as $ext ) {
  2645. if ( ! empty( $atts[ $ext ] ) ) {
  2646. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2647. if ( strtolower( $type['ext'] ) === $ext ) {
  2648. $primary = true;
  2649. }
  2650. }
  2651. }
  2652. }
  2653. if ( ! $primary ) {
  2654. $audios = get_attached_media( 'audio', $post_id );
  2655. if ( empty( $audios ) ) {
  2656. return;
  2657. }
  2658. $audio = reset( $audios );
  2659. $atts['src'] = wp_get_attachment_url( $audio->ID );
  2660. if ( empty( $atts['src'] ) ) {
  2661. return;
  2662. }
  2663. array_unshift( $default_types, 'src' );
  2664. }
  2665. /**
  2666. * Filters the media library used for the audio shortcode.
  2667. *
  2668. * @since 3.6.0
  2669. *
  2670. * @param string $library Media library used for the audio shortcode.
  2671. */
  2672. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  2673. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2674. wp_enqueue_style( 'wp-mediaelement' );
  2675. wp_enqueue_script( 'wp-mediaelement' );
  2676. }
  2677. /**
  2678. * Filters the class attribute for the audio shortcode output container.
  2679. *
  2680. * @since 3.6.0
  2681. * @since 4.9.0 The `$atts` parameter was added.
  2682. *
  2683. * @param string $class CSS class or list of space-separated classes.
  2684. * @param array $atts Array of audio shortcode attributes.
  2685. */
  2686. $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
  2687. $html_atts = array(
  2688. 'class' => $atts['class'],
  2689. 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
  2690. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2691. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2692. 'preload' => $atts['preload'],
  2693. 'style' => $atts['style'],
  2694. );
  2695. // These ones should just be omitted altogether if they are blank.
  2696. foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  2697. if ( empty( $html_atts[ $a ] ) ) {
  2698. unset( $html_atts[ $a ] );
  2699. }
  2700. }
  2701. $attr_strings = array();
  2702. foreach ( $html_atts as $k => $v ) {
  2703. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2704. }
  2705. $html = '';
  2706. if ( 'mediaelement' === $library && 1 === $instance ) {
  2707. $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  2708. }
  2709. $html .= sprintf( '<audio %s controls="controls">', implode( ' ', $attr_strings ) );
  2710. $fileurl = '';
  2711. $source = '<source type="%s" src="%s" />';
  2712. foreach ( $default_types as $fallback ) {
  2713. if ( ! empty( $atts[ $fallback ] ) ) {
  2714. if ( empty( $fileurl ) ) {
  2715. $fileurl = $atts[ $fallback ];
  2716. }
  2717. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2718. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2719. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2720. }
  2721. }
  2722. if ( 'mediaelement' === $library ) {
  2723. $html .= wp_mediaelement_fallback( $fileurl );
  2724. }
  2725. $html .= '</audio>';
  2726. /**
  2727. * Filters the audio shortcode output.
  2728. *
  2729. * @since 3.6.0
  2730. *
  2731. * @param string $html Audio shortcode HTML output.
  2732. * @param array $atts Array of audio shortcode attributes.
  2733. * @param string $audio Audio file.
  2734. * @param int $post_id Post ID.
  2735. * @param string $library Media library used for the audio shortcode.
  2736. */
  2737. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  2738. }
  2739. add_shortcode( 'audio', 'wp_audio_shortcode' );
  2740. /**
  2741. * Returns a filtered list of supported video formats.
  2742. *
  2743. * @since 3.6.0
  2744. *
  2745. * @return string[] List of supported video formats.
  2746. */
  2747. function wp_get_video_extensions() {
  2748. /**
  2749. * Filters the list of supported video formats.
  2750. *
  2751. * @since 3.6.0
  2752. *
  2753. * @param string[] $extensions An array of supported video formats. Defaults are
  2754. * 'mp4', 'm4v', 'webm', 'ogv', 'flv'.
  2755. */
  2756. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
  2757. }
  2758. /**
  2759. * Builds the Video shortcode output.
  2760. *
  2761. * This implements the functionality of the Video Shortcode for displaying
  2762. * WordPress mp4s in a post.
  2763. *
  2764. * @since 3.6.0
  2765. *
  2766. * @global int $content_width
  2767. *
  2768. * @param array $attr {
  2769. * Attributes of the shortcode.
  2770. *
  2771. * @type string $src URL to the source of the video file. Default empty.
  2772. * @type int $height Height of the video embed in pixels. Default 360.
  2773. * @type int $width Width of the video embed in pixels. Default $content_width or 640.
  2774. * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
  2775. * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
  2776. * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
  2777. * @type string $preload The 'preload' attribute for the `<video>` element.
  2778. * Default 'metadata'.
  2779. * @type string $class The 'class' attribute for the `<video>` element.
  2780. * Default 'wp-video-shortcode'.
  2781. * }
  2782. * @param string $content Shortcode content.
  2783. * @return string|void HTML content to display video.
  2784. */
  2785. function wp_video_shortcode( $attr, $content = '' ) {
  2786. global $content_width;
  2787. $post_id = get_post() ? get_the_ID() : 0;
  2788. static $instance = 0;
  2789. $instance++;
  2790. /**
  2791. * Filters the default video shortcode output.
  2792. *
  2793. * If the filtered output isn't empty, it will be used instead of generating
  2794. * the default video template.
  2795. *
  2796. * @since 3.6.0
  2797. *
  2798. * @see wp_video_shortcode()
  2799. *
  2800. * @param string $html Empty variable to be replaced with shortcode markup.
  2801. * @param array $attr Attributes of the shortcode. @see wp_video_shortcode()
  2802. * @param string $content Video shortcode content.
  2803. * @param int $instance Unique numeric ID of this video shortcode instance.
  2804. */
  2805. $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
  2806. if ( '' !== $override ) {
  2807. return $override;
  2808. }
  2809. $video = null;
  2810. $default_types = wp_get_video_extensions();
  2811. $defaults_atts = array(
  2812. 'src' => '',
  2813. 'poster' => '',
  2814. 'loop' => '',
  2815. 'autoplay' => '',
  2816. 'preload' => 'metadata',
  2817. 'width' => 640,
  2818. 'height' => 360,
  2819. 'class' => 'wp-video-shortcode',
  2820. );
  2821. foreach ( $default_types as $type ) {
  2822. $defaults_atts[ $type ] = '';
  2823. }
  2824. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  2825. if ( is_admin() ) {
  2826. // Shrink the video so it isn't huge in the admin.
  2827. if ( $atts['width'] > $defaults_atts['width'] ) {
  2828. $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
  2829. $atts['width'] = $defaults_atts['width'];
  2830. }
  2831. } else {
  2832. // If the video is bigger than the theme.
  2833. if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
  2834. $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
  2835. $atts['width'] = $content_width;
  2836. }
  2837. }
  2838. $is_vimeo = false;
  2839. $is_youtube = false;
  2840. $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
  2841. $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
  2842. $primary = false;
  2843. if ( ! empty( $atts['src'] ) ) {
  2844. $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
  2845. $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
  2846. if ( ! $is_youtube && ! $is_vimeo ) {
  2847. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2848. if ( ! in_array( strtolower( $type['ext'] ), $default_types, true ) ) {
  2849. return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2850. }
  2851. }
  2852. if ( $is_vimeo ) {
  2853. wp_enqueue_script( 'mediaelement-vimeo' );
  2854. }
  2855. $primary = true;
  2856. array_unshift( $default_types, 'src' );
  2857. } else {
  2858. foreach ( $default_types as $ext ) {
  2859. if ( ! empty( $atts[ $ext ] ) ) {
  2860. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2861. if ( strtolower( $type['ext'] ) === $ext ) {
  2862. $primary = true;
  2863. }
  2864. }
  2865. }
  2866. }
  2867. if ( ! $primary ) {
  2868. $videos = get_attached_media( 'video', $post_id );
  2869. if ( empty( $videos ) ) {
  2870. return;
  2871. }
  2872. $video = reset( $videos );
  2873. $atts['src'] = wp_get_attachment_url( $video->ID );
  2874. if ( empty( $atts['src'] ) ) {
  2875. return;
  2876. }
  2877. array_unshift( $default_types, 'src' );
  2878. }
  2879. /**
  2880. * Filters the media library used for the video shortcode.
  2881. *
  2882. * @since 3.6.0
  2883. *
  2884. * @param string $library Media library used for the video shortcode.
  2885. */
  2886. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  2887. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2888. wp_enqueue_style( 'wp-mediaelement' );
  2889. wp_enqueue_script( 'wp-mediaelement' );
  2890. wp_enqueue_script( 'mediaelement-vimeo' );
  2891. }
  2892. // MediaElement.js has issues with some URL formats for Vimeo and YouTube,
  2893. // so update the URL to prevent the ME.js player from breaking.
  2894. if ( 'mediaelement' === $library ) {
  2895. if ( $is_youtube ) {
  2896. // Remove `feature` query arg and force SSL - see #40866.
  2897. $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
  2898. $atts['src'] = set_url_scheme( $atts['src'], 'https' );
  2899. } elseif ( $is_vimeo ) {
  2900. // Remove all query arguments and force SSL - see #40866.
  2901. $parsed_vimeo_url = wp_parse_url( $atts['src'] );
  2902. $vimeo_src = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
  2903. // Add loop param for mejs bug - see #40977, not needed after #39686.
  2904. $loop = $atts['loop'] ? '1' : '0';
  2905. $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
  2906. }
  2907. }
  2908. /**
  2909. * Filters the class attribute for the video shortcode output container.
  2910. *
  2911. * @since 3.6.0
  2912. * @since 4.9.0 The `$atts` parameter was added.
  2913. *
  2914. * @param string $class CSS class or list of space-separated classes.
  2915. * @param array $atts Array of video shortcode attributes.
  2916. */
  2917. $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
  2918. $html_atts = array(
  2919. 'class' => $atts['class'],
  2920. 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
  2921. 'width' => absint( $atts['width'] ),
  2922. 'height' => absint( $atts['height'] ),
  2923. 'poster' => esc_url( $atts['poster'] ),
  2924. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2925. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2926. 'preload' => $atts['preload'],
  2927. );
  2928. // These ones should just be omitted altogether if they are blank.
  2929. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  2930. if ( empty( $html_atts[ $a ] ) ) {
  2931. unset( $html_atts[ $a ] );
  2932. }
  2933. }
  2934. $attr_strings = array();
  2935. foreach ( $html_atts as $k => $v ) {
  2936. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2937. }
  2938. $html = '';
  2939. if ( 'mediaelement' === $library && 1 === $instance ) {
  2940. $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  2941. }
  2942. $html .= sprintf( '<video %s controls="controls">', implode( ' ', $attr_strings ) );
  2943. $fileurl = '';
  2944. $source = '<source type="%s" src="%s" />';
  2945. foreach ( $default_types as $fallback ) {
  2946. if ( ! empty( $atts[ $fallback ] ) ) {
  2947. if ( empty( $fileurl ) ) {
  2948. $fileurl = $atts[ $fallback ];
  2949. }
  2950. if ( 'src' === $fallback && $is_youtube ) {
  2951. $type = array( 'type' => 'video/youtube' );
  2952. } elseif ( 'src' === $fallback && $is_vimeo ) {
  2953. $type = array( 'type' => 'video/vimeo' );
  2954. } else {
  2955. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2956. }
  2957. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2958. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2959. }
  2960. }
  2961. if ( ! empty( $content ) ) {
  2962. if ( false !== strpos( $content, "\n" ) ) {
  2963. $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
  2964. }
  2965. $html .= trim( $content );
  2966. }
  2967. if ( 'mediaelement' === $library ) {
  2968. $html .= wp_mediaelement_fallback( $fileurl );
  2969. }
  2970. $html .= '</video>';
  2971. $width_rule = '';
  2972. if ( ! empty( $atts['width'] ) ) {
  2973. $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
  2974. }
  2975. $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
  2976. /**
  2977. * Filters the output of the video shortcode.
  2978. *
  2979. * @since 3.6.0
  2980. *
  2981. * @param string $output Video shortcode HTML output.
  2982. * @param array $atts Array of video shortcode attributes.
  2983. * @param string $video Video file.
  2984. * @param int $post_id Post ID.
  2985. * @param string $library Media library used for the video shortcode.
  2986. */
  2987. return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
  2988. }
  2989. add_shortcode( 'video', 'wp_video_shortcode' );
  2990. /**
  2991. * Gets the previous image link that has the same post parent.
  2992. *
  2993. * @since 5.8.0
  2994. *
  2995. * @see get_adjacent_image_link()
  2996. *
  2997. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  2998. * of width and height values in pixels (in that order). Default 'thumbnail'.
  2999. * @param string|false $text Optional. Link text. Default false.
  3000. * @return string Markup for previous image link.
  3001. */
  3002. function get_previous_image_link( $size = 'thumbnail', $text = false ) {
  3003. return get_adjacent_image_link( true, $size, $text );
  3004. }
  3005. /**
  3006. * Displays previous image link that has the same post parent.
  3007. *
  3008. * @since 2.5.0
  3009. *
  3010. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  3011. * of width and height values in pixels (in that order). Default 'thumbnail'.
  3012. * @param string|false $text Optional. Link text. Default false.
  3013. */
  3014. function previous_image_link( $size = 'thumbnail', $text = false ) {
  3015. echo get_previous_image_link( $size, $text );
  3016. }
  3017. /**
  3018. * Gets the next image link that has the same post parent.
  3019. *
  3020. * @since 5.8.0
  3021. *
  3022. * @see get_adjacent_image_link()
  3023. *
  3024. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  3025. * of width and height values in pixels (in that order). Default 'thumbnail'.
  3026. * @param string|false $text Optional. Link text. Default false.
  3027. * @return string Markup for next image link.
  3028. */
  3029. function get_next_image_link( $size = 'thumbnail', $text = false ) {
  3030. return get_adjacent_image_link( false, $size, $text );
  3031. }
  3032. /**
  3033. * Displays next image link that has the same post parent.
  3034. *
  3035. * @since 2.5.0
  3036. *
  3037. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  3038. * of width and height values in pixels (in that order). Default 'thumbnail'.
  3039. * @param string|false $text Optional. Link text. Default false.
  3040. */
  3041. function next_image_link( $size = 'thumbnail', $text = false ) {
  3042. echo get_next_image_link( $size, $text );
  3043. }
  3044. /**
  3045. * Gets the next or previous image link that has the same post parent.
  3046. *
  3047. * Retrieves the current attachment object from the $post global.
  3048. *
  3049. * @since 5.8.0
  3050. *
  3051. * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
  3052. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  3053. * of width and height values in pixels (in that order). Default 'thumbnail'.
  3054. * @param bool $text Optional. Link text. Default false.
  3055. * @return string Markup for image link.
  3056. */
  3057. function get_adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
  3058. $post = get_post();
  3059. $attachments = array_values(
  3060. get_children(
  3061. array(
  3062. 'post_parent' => $post->post_parent,
  3063. 'post_status' => 'inherit',
  3064. 'post_type' => 'attachment',
  3065. 'post_mime_type' => 'image',
  3066. 'order' => 'ASC',
  3067. 'orderby' => 'menu_order ID',
  3068. )
  3069. )
  3070. );
  3071. foreach ( $attachments as $k => $attachment ) {
  3072. if ( (int) $attachment->ID === (int) $post->ID ) {
  3073. break;
  3074. }
  3075. }
  3076. $output = '';
  3077. $attachment_id = 0;
  3078. if ( $attachments ) {
  3079. $k = $prev ? $k - 1 : $k + 1;
  3080. if ( isset( $attachments[ $k ] ) ) {
  3081. $attachment_id = $attachments[ $k ]->ID;
  3082. $attr = array( 'alt' => get_the_title( $attachment_id ) );
  3083. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text, $attr );
  3084. }
  3085. }
  3086. $adjacent = $prev ? 'previous' : 'next';
  3087. /**
  3088. * Filters the adjacent image link.
  3089. *
  3090. * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
  3091. * either 'next', or 'previous'.
  3092. *
  3093. * Possible hook names include:
  3094. *
  3095. * - `next_image_link`
  3096. * - `previous_image_link`
  3097. *
  3098. * @since 3.5.0
  3099. *
  3100. * @param string $output Adjacent image HTML markup.
  3101. * @param int $attachment_id Attachment ID
  3102. * @param string|int[] $size Requested image size. Can be any registered image size name, or
  3103. * an array of width and height values in pixels (in that order).
  3104. * @param string $text Link text.
  3105. */
  3106. return apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  3107. }
  3108. /**
  3109. * Displays next or previous image link that has the same post parent.
  3110. *
  3111. * Retrieves the current attachment object from the $post global.
  3112. *
  3113. * @since 2.5.0
  3114. *
  3115. * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
  3116. * @param string|int[] $size Optional. Image size. Accepts any registered image size name, or an array
  3117. * of width and height values in pixels (in that order). Default 'thumbnail'.
  3118. * @param bool $text Optional. Link text. Default false.
  3119. */
  3120. function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
  3121. echo get_adjacent_image_link( $prev, $size, $text );
  3122. }
  3123. /**
  3124. * Retrieves taxonomies attached to given the attachment.
  3125. *
  3126. * @since 2.5.0
  3127. * @since 4.7.0 Introduced the `$output` parameter.
  3128. *
  3129. * @param int|array|object $attachment Attachment ID, data array, or data object.
  3130. * @param string $output Output type. 'names' to return an array of taxonomy names,
  3131. * or 'objects' to return an array of taxonomy objects.
  3132. * Default is 'names'.
  3133. * @return string[]|WP_Taxonomy[] List of taxonomies or taxonomy names. Empty array on failure.
  3134. */
  3135. function get_attachment_taxonomies( $attachment, $output = 'names' ) {
  3136. if ( is_int( $attachment ) ) {
  3137. $attachment = get_post( $attachment );
  3138. } elseif ( is_array( $attachment ) ) {
  3139. $attachment = (object) $attachment;
  3140. }
  3141. if ( ! is_object( $attachment ) ) {
  3142. return array();
  3143. }
  3144. $file = get_attached_file( $attachment->ID );
  3145. $filename = wp_basename( $file );
  3146. $objects = array( 'attachment' );
  3147. if ( false !== strpos( $filename, '.' ) ) {
  3148. $objects[] = 'attachment:' . substr( $filename, strrpos( $filename, '.' ) + 1 );
  3149. }
  3150. if ( ! empty( $attachment->post_mime_type ) ) {
  3151. $objects[] = 'attachment:' . $attachment->post_mime_type;
  3152. if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
  3153. foreach ( explode( '/', $attachment->post_mime_type ) as $token ) {
  3154. if ( ! empty( $token ) ) {
  3155. $objects[] = "attachment:$token";
  3156. }
  3157. }
  3158. }
  3159. }
  3160. $taxonomies = array();
  3161. foreach ( $objects as $object ) {
  3162. $taxes = get_object_taxonomies( $object, $output );
  3163. if ( $taxes ) {
  3164. $taxonomies = array_merge( $taxonomies, $taxes );
  3165. }
  3166. }
  3167. if ( 'names' === $output ) {
  3168. $taxonomies = array_unique( $taxonomies );
  3169. }
  3170. return $taxonomies;
  3171. }
  3172. /**
  3173. * Retrieves all of the taxonomies that are registered for attachments.
  3174. *
  3175. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  3176. *
  3177. * @since 3.5.0
  3178. *
  3179. * @see get_taxonomies()
  3180. *
  3181. * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
  3182. * Default 'names'.
  3183. * @return string[]|WP_Taxonomy[] Array of names or objects of registered taxonomies for attachments.
  3184. */
  3185. function get_taxonomies_for_attachments( $output = 'names' ) {
  3186. $taxonomies = array();
  3187. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  3188. foreach ( $taxonomy->object_type as $object_type ) {
  3189. if ( 'attachment' === $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  3190. if ( 'names' === $output ) {
  3191. $taxonomies[] = $taxonomy->name;
  3192. } else {
  3193. $taxonomies[ $taxonomy->name ] = $taxonomy;
  3194. }
  3195. break;
  3196. }
  3197. }
  3198. }
  3199. return $taxonomies;
  3200. }
  3201. /**
  3202. * Determines whether the value is an acceptable type for GD image functions.
  3203. *
  3204. * In PHP 8.0, the GD extension uses GdImage objects for its data structures.
  3205. * This function checks if the passed value is either a resource of type `gd`
  3206. * or a GdImage object instance. Any other type will return false.
  3207. *
  3208. * @since 5.6.0
  3209. *
  3210. * @param resource|GdImage|false $image A value to check the type for.
  3211. * @return bool True if $image is either a GD image resource or GdImage instance,
  3212. * false otherwise.
  3213. */
  3214. function is_gd_image( $image ) {
  3215. if ( is_resource( $image ) && 'gd' === get_resource_type( $image )
  3216. || is_object( $image ) && $image instanceof GdImage
  3217. ) {
  3218. return true;
  3219. }
  3220. return false;
  3221. }
  3222. /**
  3223. * Create new GD image resource with transparency support
  3224. *
  3225. * @todo Deprecate if possible.
  3226. *
  3227. * @since 2.9.0
  3228. *
  3229. * @param int $width Image width in pixels.
  3230. * @param int $height Image height in pixels.
  3231. * @return resource|GdImage|false The GD image resource or GdImage instance on success.
  3232. * False on failure.
  3233. */
  3234. function wp_imagecreatetruecolor( $width, $height ) {
  3235. $img = imagecreatetruecolor( $width, $height );
  3236. if ( is_gd_image( $img )
  3237. && function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' )
  3238. ) {
  3239. imagealphablending( $img, false );
  3240. imagesavealpha( $img, true );
  3241. }
  3242. return $img;
  3243. }
  3244. /**
  3245. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  3246. *
  3247. * @since 2.9.0
  3248. *
  3249. * @see wp_constrain_dimensions()
  3250. *
  3251. * @param int $example_width The width of an example embed.
  3252. * @param int $example_height The height of an example embed.
  3253. * @param int $max_width The maximum allowed width.
  3254. * @param int $max_height The maximum allowed height.
  3255. * @return int[] {
  3256. * An array of maximum width and height values.
  3257. *
  3258. * @type int $0 The maximum width in pixels.
  3259. * @type int $1 The maximum height in pixels.
  3260. * }
  3261. */
  3262. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  3263. $example_width = (int) $example_width;
  3264. $example_height = (int) $example_height;
  3265. $max_width = (int) $max_width;
  3266. $max_height = (int) $max_height;
  3267. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  3268. }
  3269. /**
  3270. * Determines the maximum upload size allowed in php.ini.
  3271. *
  3272. * @since 2.5.0
  3273. *
  3274. * @return int Allowed upload size.
  3275. */
  3276. function wp_max_upload_size() {
  3277. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  3278. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  3279. /**
  3280. * Filters the maximum upload size allowed in php.ini.
  3281. *
  3282. * @since 2.5.0
  3283. *
  3284. * @param int $size Max upload size limit in bytes.
  3285. * @param int $u_bytes Maximum upload filesize in bytes.
  3286. * @param int $p_bytes Maximum size of POST data in bytes.
  3287. */
  3288. return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  3289. }
  3290. /**
  3291. * Returns a WP_Image_Editor instance and loads file into it.
  3292. *
  3293. * @since 3.5.0
  3294. *
  3295. * @param string $path Path to the file to load.
  3296. * @param array $args Optional. Additional arguments for retrieving the image editor.
  3297. * Default empty array.
  3298. * @return WP_Image_Editor|WP_Error The WP_Image_Editor object on success,
  3299. * a WP_Error object otherwise.
  3300. */
  3301. function wp_get_image_editor( $path, $args = array() ) {
  3302. $args['path'] = $path;
  3303. if ( ! isset( $args['mime_type'] ) ) {
  3304. $file_info = wp_check_filetype( $args['path'] );
  3305. // If $file_info['type'] is false, then we let the editor attempt to
  3306. // figure out the file type, rather than forcing a failure based on extension.
  3307. if ( isset( $file_info ) && $file_info['type'] ) {
  3308. $args['mime_type'] = $file_info['type'];
  3309. }
  3310. }
  3311. $implementation = _wp_image_editor_choose( $args );
  3312. if ( $implementation ) {
  3313. $editor = new $implementation( $path );
  3314. $loaded = $editor->load();
  3315. if ( is_wp_error( $loaded ) ) {
  3316. return $loaded;
  3317. }
  3318. return $editor;
  3319. }
  3320. return new WP_Error( 'image_no_editor', __( 'No editor could be selected.' ) );
  3321. }
  3322. /**
  3323. * Tests whether there is an editor that supports a given mime type or methods.
  3324. *
  3325. * @since 3.5.0
  3326. *
  3327. * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
  3328. * Default empty array.
  3329. * @return bool True if an eligible editor is found; false otherwise.
  3330. */
  3331. function wp_image_editor_supports( $args = array() ) {
  3332. return (bool) _wp_image_editor_choose( $args );
  3333. }
  3334. /**
  3335. * Tests which editors are capable of supporting the request.
  3336. *
  3337. * @ignore
  3338. * @since 3.5.0
  3339. *
  3340. * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
  3341. * @return string|false Class name for the first editor that claims to support the request.
  3342. * False if no editor claims to support the request.
  3343. */
  3344. function _wp_image_editor_choose( $args = array() ) {
  3345. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  3346. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  3347. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  3348. /**
  3349. * Filters the list of image editing library classes.
  3350. *
  3351. * @since 3.5.0
  3352. *
  3353. * @param string[] $image_editors Array of available image editor class names. Defaults are
  3354. * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
  3355. */
  3356. $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  3357. foreach ( $implementations as $implementation ) {
  3358. if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) {
  3359. continue;
  3360. }
  3361. if ( isset( $args['mime_type'] ) &&
  3362. ! call_user_func(
  3363. array( $implementation, 'supports_mime_type' ),
  3364. $args['mime_type']
  3365. ) ) {
  3366. continue;
  3367. }
  3368. if ( isset( $args['methods'] ) &&
  3369. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  3370. continue;
  3371. }
  3372. return $implementation;
  3373. }
  3374. return false;
  3375. }
  3376. /**
  3377. * Prints default Plupload arguments.
  3378. *
  3379. * @since 3.4.0
  3380. */
  3381. function wp_plupload_default_settings() {
  3382. $wp_scripts = wp_scripts();
  3383. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  3384. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) ) {
  3385. return;
  3386. }
  3387. $max_upload_size = wp_max_upload_size();
  3388. $allowed_extensions = array_keys( get_allowed_mime_types() );
  3389. $extensions = array();
  3390. foreach ( $allowed_extensions as $extension ) {
  3391. $extensions = array_merge( $extensions, explode( '|', $extension ) );
  3392. }
  3393. /*
  3394. * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
  3395. * and the `flash_swf_url` and `silverlight_xap_url` are not used.
  3396. */
  3397. $defaults = array(
  3398. 'file_data_name' => 'async-upload', // Key passed to $_FILE.
  3399. 'url' => admin_url( 'async-upload.php', 'relative' ),
  3400. 'filters' => array(
  3401. 'max_file_size' => $max_upload_size . 'b',
  3402. 'mime_types' => array( array( 'extensions' => implode( ',', $extensions ) ) ),
  3403. ),
  3404. );
  3405. /*
  3406. * Currently only iOS Safari supports multiple files uploading,
  3407. * but iOS 7.x has a bug that prevents uploading of videos when enabled.
  3408. * See #29602.
  3409. */
  3410. if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
  3411. strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
  3412. $defaults['multi_selection'] = false;
  3413. }
  3414. // Check if WebP images can be edited.
  3415. if ( ! wp_image_editor_supports( array( 'mime_type' => 'image/webp' ) ) ) {
  3416. $defaults['webp_upload_error'] = true;
  3417. }
  3418. /**
  3419. * Filters the Plupload default settings.
  3420. *
  3421. * @since 3.4.0
  3422. *
  3423. * @param array $defaults Default Plupload settings array.
  3424. */
  3425. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  3426. $params = array(
  3427. 'action' => 'upload-attachment',
  3428. );
  3429. /**
  3430. * Filters the Plupload default parameters.
  3431. *
  3432. * @since 3.4.0
  3433. *
  3434. * @param array $params Default Plupload parameters array.
  3435. */
  3436. $params = apply_filters( 'plupload_default_params', $params );
  3437. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  3438. $defaults['multipart_params'] = $params;
  3439. $settings = array(
  3440. 'defaults' => $defaults,
  3441. 'browser' => array(
  3442. 'mobile' => wp_is_mobile(),
  3443. 'supported' => _device_can_upload(),
  3444. ),
  3445. 'limitExceeded' => is_multisite() && ! is_upload_space_available(),
  3446. );
  3447. $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
  3448. if ( $data ) {
  3449. $script = "$data\n$script";
  3450. }
  3451. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  3452. }
  3453. /**
  3454. * Prepares an attachment post object for JS, where it is expected
  3455. * to be JSON-encoded and fit into an Attachment model.
  3456. *
  3457. * @since 3.5.0
  3458. *
  3459. * @param int|WP_Post $attachment Attachment ID or object.
  3460. * @return array|void {
  3461. * Array of attachment details, or void if the parameter does not correspond to an attachment.
  3462. *
  3463. * @type string $alt Alt text of the attachment.
  3464. * @type string $author ID of the attachment author, as a string.
  3465. * @type string $authorName Name of the attachment author.
  3466. * @type string $caption Caption for the attachment.
  3467. * @type array $compat Containing item and meta.
  3468. * @type string $context Context, whether it's used as the site icon for example.
  3469. * @type int $date Uploaded date, timestamp in milliseconds.
  3470. * @type string $dateFormatted Formatted date (e.g. June 29, 2018).
  3471. * @type string $description Description of the attachment.
  3472. * @type string $editLink URL to the edit page for the attachment.
  3473. * @type string $filename File name of the attachment.
  3474. * @type string $filesizeHumanReadable Filesize of the attachment in human readable format (e.g. 1 MB).
  3475. * @type int $filesizeInBytes Filesize of the attachment in bytes.
  3476. * @type int $height If the attachment is an image, represents the height of the image in pixels.
  3477. * @type string $icon Icon URL of the attachment (e.g. /wp-includes/images/media/archive.png).
  3478. * @type int $id ID of the attachment.
  3479. * @type string $link URL to the attachment.
  3480. * @type int $menuOrder Menu order of the attachment post.
  3481. * @type array $meta Meta data for the attachment.
  3482. * @type string $mime Mime type of the attachment (e.g. image/jpeg or application/zip).
  3483. * @type int $modified Last modified, timestamp in milliseconds.
  3484. * @type string $name Name, same as title of the attachment.
  3485. * @type array $nonces Nonces for update, delete and edit.
  3486. * @type string $orientation If the attachment is an image, represents the image orientation
  3487. * (landscape or portrait).
  3488. * @type array $sizes If the attachment is an image, contains an array of arrays
  3489. * for the images sizes: thumbnail, medium, large, and full.
  3490. * @type string $status Post status of the attachment (usually 'inherit').
  3491. * @type string $subtype Mime subtype of the attachment (usually the last part, e.g. jpeg or zip).
  3492. * @type string $title Title of the attachment (usually slugified file name without the extension).
  3493. * @type string $type Type of the attachment (usually first part of the mime type, e.g. image).
  3494. * @type int $uploadedTo Parent post to which the attachment was uploaded.
  3495. * @type string $uploadedToLink URL to the edit page of the parent post of the attachment.
  3496. * @type string $uploadedToTitle Post title of the parent of the attachment.
  3497. * @type string $url Direct URL to the attachment file (from wp-content).
  3498. * @type int $width If the attachment is an image, represents the width of the image in pixels.
  3499. * }
  3500. *
  3501. */
  3502. function wp_prepare_attachment_for_js( $attachment ) {
  3503. $attachment = get_post( $attachment );
  3504. if ( ! $attachment ) {
  3505. return;
  3506. }
  3507. if ( 'attachment' !== $attachment->post_type ) {
  3508. return;
  3509. }
  3510. $meta = wp_get_attachment_metadata( $attachment->ID );
  3511. if ( false !== strpos( $attachment->post_mime_type, '/' ) ) {
  3512. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  3513. } else {
  3514. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  3515. }
  3516. $attachment_url = wp_get_attachment_url( $attachment->ID );
  3517. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  3518. $response = array(
  3519. 'id' => $attachment->ID,
  3520. 'title' => $attachment->post_title,
  3521. 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
  3522. 'url' => $attachment_url,
  3523. 'link' => get_attachment_link( $attachment->ID ),
  3524. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  3525. 'author' => $attachment->post_author,
  3526. 'description' => $attachment->post_content,
  3527. 'caption' => $attachment->post_excerpt,
  3528. 'name' => $attachment->post_name,
  3529. 'status' => $attachment->post_status,
  3530. 'uploadedTo' => $attachment->post_parent,
  3531. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  3532. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  3533. 'menuOrder' => $attachment->menu_order,
  3534. 'mime' => $attachment->post_mime_type,
  3535. 'type' => $type,
  3536. 'subtype' => $subtype,
  3537. 'icon' => wp_mime_type_icon( $attachment->ID ),
  3538. 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
  3539. 'nonces' => array(
  3540. 'update' => false,
  3541. 'delete' => false,
  3542. 'edit' => false,
  3543. ),
  3544. 'editLink' => false,
  3545. 'meta' => false,
  3546. );
  3547. $author = new WP_User( $attachment->post_author );
  3548. if ( $author->exists() ) {
  3549. $author_name = $author->display_name ? $author->display_name : $author->nickname;
  3550. $response['authorName'] = html_entity_decode( $author_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
  3551. $response['authorLink'] = get_edit_user_link( $author->ID );
  3552. } else {
  3553. $response['authorName'] = __( '(no author)' );
  3554. }
  3555. if ( $attachment->post_parent ) {
  3556. $post_parent = get_post( $attachment->post_parent );
  3557. if ( $post_parent ) {
  3558. $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
  3559. $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
  3560. }
  3561. }
  3562. $attached_file = get_attached_file( $attachment->ID );
  3563. if ( isset( $meta['filesize'] ) ) {
  3564. $bytes = $meta['filesize'];
  3565. } elseif ( file_exists( $attached_file ) ) {
  3566. $bytes = filesize( $attached_file );
  3567. } else {
  3568. $bytes = '';
  3569. }
  3570. if ( $bytes ) {
  3571. $response['filesizeInBytes'] = $bytes;
  3572. $response['filesizeHumanReadable'] = size_format( $bytes );
  3573. }
  3574. $context = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
  3575. $response['context'] = ( $context ) ? $context : '';
  3576. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  3577. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  3578. $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  3579. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  3580. }
  3581. if ( current_user_can( 'delete_post', $attachment->ID ) ) {
  3582. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  3583. }
  3584. if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
  3585. $sizes = array();
  3586. /** This filter is documented in wp-admin/includes/media.php */
  3587. $possible_sizes = apply_filters(
  3588. 'image_size_names_choose',
  3589. array(
  3590. 'thumbnail' => __( 'Thumbnail' ),
  3591. 'medium' => __( 'Medium' ),
  3592. 'large' => __( 'Large' ),
  3593. 'full' => __( 'Full Size' ),
  3594. )
  3595. );
  3596. unset( $possible_sizes['full'] );
  3597. /*
  3598. * Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  3599. * First: run the image_downsize filter. If it returns something, we can use its data.
  3600. * If the filter does not return something, then image_downsize() is just an expensive way
  3601. * to check the image metadata, which we do second.
  3602. */
  3603. foreach ( $possible_sizes as $size => $label ) {
  3604. /** This filter is documented in wp-includes/media.php */
  3605. $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size );
  3606. if ( $downsize ) {
  3607. if ( empty( $downsize[3] ) ) {
  3608. continue;
  3609. }
  3610. $sizes[ $size ] = array(
  3611. 'height' => $downsize[2],
  3612. 'width' => $downsize[1],
  3613. 'url' => $downsize[0],
  3614. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  3615. );
  3616. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  3617. // Nothing from the filter, so consult image metadata if we have it.
  3618. $size_meta = $meta['sizes'][ $size ];
  3619. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  3620. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  3621. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  3622. $sizes[ $size ] = array(
  3623. 'height' => $height,
  3624. 'width' => $width,
  3625. 'url' => $base_url . $size_meta['file'],
  3626. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  3627. );
  3628. }
  3629. }
  3630. if ( 'image' === $type ) {
  3631. if ( ! empty( $meta['original_image'] ) ) {
  3632. $response['originalImageURL'] = wp_get_original_image_url( $attachment->ID );
  3633. $response['originalImageName'] = wp_basename( wp_get_original_image_path( $attachment->ID ) );
  3634. }
  3635. $sizes['full'] = array( 'url' => $attachment_url );
  3636. if ( isset( $meta['height'], $meta['width'] ) ) {
  3637. $sizes['full']['height'] = $meta['height'];
  3638. $sizes['full']['width'] = $meta['width'];
  3639. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  3640. }
  3641. $response = array_merge( $response, $sizes['full'] );
  3642. } elseif ( $meta['sizes']['full']['file'] ) {
  3643. $sizes['full'] = array(
  3644. 'url' => $base_url . $meta['sizes']['full']['file'],
  3645. 'height' => $meta['sizes']['full']['height'],
  3646. 'width' => $meta['sizes']['full']['width'],
  3647. 'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape',
  3648. );
  3649. }
  3650. $response = array_merge( $response, array( 'sizes' => $sizes ) );
  3651. }
  3652. if ( $meta && 'video' === $type ) {
  3653. if ( isset( $meta['width'] ) ) {
  3654. $response['width'] = (int) $meta['width'];
  3655. }
  3656. if ( isset( $meta['height'] ) ) {
  3657. $response['height'] = (int) $meta['height'];
  3658. }
  3659. }
  3660. if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  3661. if ( isset( $meta['length_formatted'] ) ) {
  3662. $response['fileLength'] = $meta['length_formatted'];
  3663. $response['fileLengthHumanReadable'] = human_readable_duration( $meta['length_formatted'] );
  3664. }
  3665. $response['meta'] = array();
  3666. foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
  3667. $response['meta'][ $key ] = false;
  3668. if ( ! empty( $meta[ $key ] ) ) {
  3669. $response['meta'][ $key ] = $meta[ $key ];
  3670. }
  3671. }
  3672. $id = get_post_thumbnail_id( $attachment->ID );
  3673. if ( ! empty( $id ) ) {
  3674. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  3675. $response['image'] = compact( 'src', 'width', 'height' );
  3676. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  3677. $response['thumb'] = compact( 'src', 'width', 'height' );
  3678. } else {
  3679. $src = wp_mime_type_icon( $attachment->ID );
  3680. $width = 48;
  3681. $height = 64;
  3682. $response['image'] = compact( 'src', 'width', 'height' );
  3683. $response['thumb'] = compact( 'src', 'width', 'height' );
  3684. }
  3685. }
  3686. if ( function_exists( 'get_compat_media_markup' ) ) {
  3687. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  3688. }
  3689. if ( function_exists( 'get_media_states' ) ) {
  3690. $media_states = get_media_states( $attachment );
  3691. if ( ! empty( $media_states ) ) {
  3692. $response['mediaStates'] = implode( ', ', $media_states );
  3693. }
  3694. }
  3695. /**
  3696. * Filters the attachment data prepared for JavaScript.
  3697. *
  3698. * @since 3.5.0
  3699. *
  3700. * @param array $response Array of prepared attachment data. @see wp_prepare_attachment_for_js().
  3701. * @param WP_Post $attachment Attachment object.
  3702. * @param array|false $meta Array of attachment meta data, or false if there is none.
  3703. */
  3704. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  3705. }
  3706. /**
  3707. * Enqueues all scripts, styles, settings, and templates necessary to use
  3708. * all media JS APIs.
  3709. *
  3710. * @since 3.5.0
  3711. *
  3712. * @global int $content_width
  3713. * @global wpdb $wpdb WordPress database abstraction object.
  3714. * @global WP_Locale $wp_locale WordPress date and time locale object.
  3715. *
  3716. * @param array $args {
  3717. * Arguments for enqueuing media scripts.
  3718. *
  3719. * @type int|WP_Post $post A post object or ID.
  3720. * }
  3721. */
  3722. function wp_enqueue_media( $args = array() ) {
  3723. // Enqueue me just once per page, please.
  3724. if ( did_action( 'wp_enqueue_media' ) ) {
  3725. return;
  3726. }
  3727. global $content_width, $wpdb, $wp_locale;
  3728. $defaults = array(
  3729. 'post' => null,
  3730. );
  3731. $args = wp_parse_args( $args, $defaults );
  3732. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  3733. // to ensure plugins will work. We will then unset those tabs.
  3734. $tabs = array(
  3735. // handler action suffix => tab label
  3736. 'type' => '',
  3737. 'type_url' => '',
  3738. 'gallery' => '',
  3739. 'library' => '',
  3740. );
  3741. /** This filter is documented in wp-admin/includes/media.php */
  3742. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  3743. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  3744. $props = array(
  3745. 'link' => get_option( 'image_default_link_type' ), // DB default is 'file'.
  3746. 'align' => get_option( 'image_default_align' ), // Empty default.
  3747. 'size' => get_option( 'image_default_size' ), // Empty default.
  3748. );
  3749. $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
  3750. $mimes = get_allowed_mime_types();
  3751. $ext_mimes = array();
  3752. foreach ( $exts as $ext ) {
  3753. foreach ( $mimes as $ext_preg => $mime_match ) {
  3754. if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
  3755. $ext_mimes[ $ext ] = $mime_match;
  3756. break;
  3757. }
  3758. }
  3759. }
  3760. /**
  3761. * Allows showing or hiding the "Create Audio Playlist" button in the media library.
  3762. *
  3763. * By default, the "Create Audio Playlist" button will always be shown in
  3764. * the media library. If this filter returns `null`, a query will be run
  3765. * to determine whether the media library contains any audio items. This
  3766. * was the default behavior prior to version 4.8.0, but this query is
  3767. * expensive for large media libraries.
  3768. *
  3769. * @since 4.7.4
  3770. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  3771. *
  3772. * @link https://core.trac.wordpress.org/ticket/31071
  3773. *
  3774. * @param bool|null $show Whether to show the button, or `null` to decide based
  3775. * on whether any audio files exist in the media library.
  3776. */
  3777. $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
  3778. if ( null === $show_audio_playlist ) {
  3779. $show_audio_playlist = $wpdb->get_var(
  3780. "
  3781. SELECT ID
  3782. FROM $wpdb->posts
  3783. WHERE post_type = 'attachment'
  3784. AND post_mime_type LIKE 'audio%'
  3785. LIMIT 1
  3786. "
  3787. );
  3788. }
  3789. /**
  3790. * Allows showing or hiding the "Create Video Playlist" button in the media library.
  3791. *
  3792. * By default, the "Create Video Playlist" button will always be shown in
  3793. * the media library. If this filter returns `null`, a query will be run
  3794. * to determine whether the media library contains any video items. This
  3795. * was the default behavior prior to version 4.8.0, but this query is
  3796. * expensive for large media libraries.
  3797. *
  3798. * @since 4.7.4
  3799. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  3800. *
  3801. * @link https://core.trac.wordpress.org/ticket/31071
  3802. *
  3803. * @param bool|null $show Whether to show the button, or `null` to decide based
  3804. * on whether any video files exist in the media library.
  3805. */
  3806. $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
  3807. if ( null === $show_video_playlist ) {
  3808. $show_video_playlist = $wpdb->get_var(
  3809. "
  3810. SELECT ID
  3811. FROM $wpdb->posts
  3812. WHERE post_type = 'attachment'
  3813. AND post_mime_type LIKE 'video%'
  3814. LIMIT 1
  3815. "
  3816. );
  3817. }
  3818. /**
  3819. * Allows overriding the list of months displayed in the media library.
  3820. *
  3821. * By default (if this filter does not return an array), a query will be
  3822. * run to determine the months that have media items. This query can be
  3823. * expensive for large media libraries, so it may be desirable for sites to
  3824. * override this behavior.
  3825. *
  3826. * @since 4.7.4
  3827. *
  3828. * @link https://core.trac.wordpress.org/ticket/31071
  3829. *
  3830. * @param array|null $months An array of objects with `month` and `year`
  3831. * properties, or `null` (or any other non-array value)
  3832. * for default behavior.
  3833. */
  3834. $months = apply_filters( 'media_library_months_with_files', null );
  3835. if ( ! is_array( $months ) ) {
  3836. $months = $wpdb->get_results(
  3837. $wpdb->prepare(
  3838. "
  3839. SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
  3840. FROM $wpdb->posts
  3841. WHERE post_type = %s
  3842. ORDER BY post_date DESC
  3843. ",
  3844. 'attachment'
  3845. )
  3846. );
  3847. }
  3848. foreach ( $months as $month_year ) {
  3849. $month_year->text = sprintf(
  3850. /* translators: 1: Month, 2: Year. */
  3851. __( '%1$s %2$d' ),
  3852. $wp_locale->get_month( $month_year->month ),
  3853. $month_year->year
  3854. );
  3855. }
  3856. /**
  3857. * Filters whether the Media Library grid has infinite scrolling. Default `false`.
  3858. *
  3859. * @since 5.8.0
  3860. *
  3861. * @param bool $infinite Whether the Media Library grid has infinite scrolling.
  3862. */
  3863. $infinite_scrolling = apply_filters( 'media_library_infinite_scrolling', false );
  3864. $settings = array(
  3865. 'tabs' => $tabs,
  3866. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url( 'media-upload.php' ) ),
  3867. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  3868. /** This filter is documented in wp-admin/includes/media.php */
  3869. 'captions' => ! apply_filters( 'disable_captions', '' ),
  3870. 'nonce' => array(
  3871. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  3872. ),
  3873. 'post' => array(
  3874. 'id' => 0,
  3875. ),
  3876. 'defaultProps' => $props,
  3877. 'attachmentCounts' => array(
  3878. 'audio' => ( $show_audio_playlist ) ? 1 : 0,
  3879. 'video' => ( $show_video_playlist ) ? 1 : 0,
  3880. ),
  3881. 'oEmbedProxyUrl' => rest_url( 'oembed/1.0/proxy' ),
  3882. 'embedExts' => $exts,
  3883. 'embedMimes' => $ext_mimes,
  3884. 'contentWidth' => $content_width,
  3885. 'months' => $months,
  3886. 'mediaTrash' => MEDIA_TRASH ? 1 : 0,
  3887. 'infiniteScrolling' => ( $infinite_scrolling ) ? 1 : 0,
  3888. );
  3889. $post = null;
  3890. if ( isset( $args['post'] ) ) {
  3891. $post = get_post( $args['post'] );
  3892. $settings['post'] = array(
  3893. 'id' => $post->ID,
  3894. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  3895. );
  3896. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
  3897. if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
  3898. if ( wp_attachment_is( 'audio', $post ) ) {
  3899. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  3900. } elseif ( wp_attachment_is( 'video', $post ) ) {
  3901. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  3902. }
  3903. }
  3904. if ( $thumbnail_support ) {
  3905. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  3906. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  3907. }
  3908. }
  3909. if ( $post ) {
  3910. $post_type_object = get_post_type_object( $post->post_type );
  3911. } else {
  3912. $post_type_object = get_post_type_object( 'post' );
  3913. }
  3914. $strings = array(
  3915. // Generic.
  3916. 'mediaFrameDefaultTitle' => __( 'Media' ),
  3917. 'url' => __( 'URL' ),
  3918. 'addMedia' => __( 'Add media' ),
  3919. 'search' => __( 'Search' ),
  3920. 'select' => __( 'Select' ),
  3921. 'cancel' => __( 'Cancel' ),
  3922. 'update' => __( 'Update' ),
  3923. 'replace' => __( 'Replace' ),
  3924. 'remove' => __( 'Remove' ),
  3925. 'back' => __( 'Back' ),
  3926. /*
  3927. * translators: This is a would-be plural string used in the media manager.
  3928. * If there is not a word you can use in your language to avoid issues with the
  3929. * lack of plural support here, turn it into "selected: %d" then translate it.
  3930. */
  3931. 'selected' => __( '%d selected' ),
  3932. 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
  3933. // Upload.
  3934. 'uploadFilesTitle' => __( 'Upload files' ),
  3935. 'uploadImagesTitle' => __( 'Upload images' ),
  3936. // Library.
  3937. 'mediaLibraryTitle' => __( 'Media Library' ),
  3938. 'insertMediaTitle' => __( 'Add media' ),
  3939. 'createNewGallery' => __( 'Create a new gallery' ),
  3940. 'createNewPlaylist' => __( 'Create a new playlist' ),
  3941. 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  3942. 'returnToLibrary' => __( '&#8592; Go to library' ),
  3943. 'allMediaItems' => __( 'All media items' ),
  3944. 'allDates' => __( 'All dates' ),
  3945. 'noItemsFound' => __( 'No items found.' ),
  3946. 'insertIntoPost' => $post_type_object->labels->insert_into_item,
  3947. 'unattached' => _x( 'Unattached', 'media items' ),
  3948. 'mine' => _x( 'Mine', 'media items' ),
  3949. 'trash' => _x( 'Trash', 'noun' ),
  3950. 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item,
  3951. 'warnDelete' => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3952. 'warnBulkDelete' => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3953. 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
  3954. 'bulkSelect' => __( 'Bulk select' ),
  3955. 'trashSelected' => __( 'Move to Trash' ),
  3956. 'restoreSelected' => __( 'Restore from Trash' ),
  3957. 'deletePermanently' => __( 'Delete permanently' ),
  3958. 'errorDeleting' => __( 'Error in deleting the attachment.' ),
  3959. 'apply' => __( 'Apply' ),
  3960. 'filterByDate' => __( 'Filter by date' ),
  3961. 'filterByType' => __( 'Filter by type' ),
  3962. 'searchLabel' => __( 'Search' ),
  3963. 'searchMediaLabel' => __( 'Search media' ), // Backward compatibility pre-5.3.
  3964. 'searchMediaPlaceholder' => __( 'Search media items...' ), // Placeholder (no ellipsis), backward compatibility pre-5.3.
  3965. /* translators: %d: Number of attachments found in a search. */
  3966. 'mediaFound' => __( 'Number of media items found: %d' ),
  3967. 'noMedia' => __( 'No media items found.' ),
  3968. 'noMediaTryNewSearch' => __( 'No media items found. Try a different search.' ),
  3969. // Library Details.
  3970. 'attachmentDetails' => __( 'Attachment details' ),
  3971. // From URL.
  3972. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  3973. // Featured Images.
  3974. 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
  3975. 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
  3976. // Gallery.
  3977. 'createGalleryTitle' => __( 'Create gallery' ),
  3978. 'editGalleryTitle' => __( 'Edit gallery' ),
  3979. 'cancelGalleryTitle' => __( '&#8592; Cancel gallery' ),
  3980. 'insertGallery' => __( 'Insert gallery' ),
  3981. 'updateGallery' => __( 'Update gallery' ),
  3982. 'addToGallery' => __( 'Add to gallery' ),
  3983. 'addToGalleryTitle' => __( 'Add to gallery' ),
  3984. 'reverseOrder' => __( 'Reverse order' ),
  3985. // Edit Image.
  3986. 'imageDetailsTitle' => __( 'Image details' ),
  3987. 'imageReplaceTitle' => __( 'Replace image' ),
  3988. 'imageDetailsCancel' => __( 'Cancel edit' ),
  3989. 'editImage' => __( 'Edit image' ),
  3990. // Crop Image.
  3991. 'chooseImage' => __( 'Choose image' ),
  3992. 'selectAndCrop' => __( 'Select and crop' ),
  3993. 'skipCropping' => __( 'Skip cropping' ),
  3994. 'cropImage' => __( 'Crop image' ),
  3995. 'cropYourImage' => __( 'Crop your image' ),
  3996. 'cropping' => __( 'Cropping&hellip;' ),
  3997. /* translators: 1: Suggested width number, 2: Suggested height number. */
  3998. 'suggestedDimensions' => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
  3999. 'cropError' => __( 'There has been an error cropping your image.' ),
  4000. // Edit Audio.
  4001. 'audioDetailsTitle' => __( 'Audio details' ),
  4002. 'audioReplaceTitle' => __( 'Replace audio' ),
  4003. 'audioAddSourceTitle' => __( 'Add audio source' ),
  4004. 'audioDetailsCancel' => __( 'Cancel edit' ),
  4005. // Edit Video.
  4006. 'videoDetailsTitle' => __( 'Video details' ),
  4007. 'videoReplaceTitle' => __( 'Replace video' ),
  4008. 'videoAddSourceTitle' => __( 'Add video source' ),
  4009. 'videoDetailsCancel' => __( 'Cancel edit' ),
  4010. 'videoSelectPosterImageTitle' => __( 'Select poster image' ),
  4011. 'videoAddTrackTitle' => __( 'Add subtitles' ),
  4012. // Playlist.
  4013. 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
  4014. 'createPlaylistTitle' => __( 'Create audio playlist' ),
  4015. 'editPlaylistTitle' => __( 'Edit audio playlist' ),
  4016. 'cancelPlaylistTitle' => __( '&#8592; Cancel audio playlist' ),
  4017. 'insertPlaylist' => __( 'Insert audio playlist' ),
  4018. 'updatePlaylist' => __( 'Update audio playlist' ),
  4019. 'addToPlaylist' => __( 'Add to audio playlist' ),
  4020. 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
  4021. // Video Playlist.
  4022. 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
  4023. 'createVideoPlaylistTitle' => __( 'Create video playlist' ),
  4024. 'editVideoPlaylistTitle' => __( 'Edit video playlist' ),
  4025. 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel video playlist' ),
  4026. 'insertVideoPlaylist' => __( 'Insert video playlist' ),
  4027. 'updateVideoPlaylist' => __( 'Update video playlist' ),
  4028. 'addToVideoPlaylist' => __( 'Add to video playlist' ),
  4029. 'addToVideoPlaylistTitle' => __( 'Add to video Playlist' ),
  4030. // Headings.
  4031. 'filterAttachments' => __( 'Filter media' ),
  4032. 'attachmentsList' => __( 'Media list' ),
  4033. );
  4034. /**
  4035. * Filters the media view settings.
  4036. *
  4037. * @since 3.5.0
  4038. *
  4039. * @param array $settings List of media view settings.
  4040. * @param WP_Post $post Post object.
  4041. */
  4042. $settings = apply_filters( 'media_view_settings', $settings, $post );
  4043. /**
  4044. * Filters the media view strings.
  4045. *
  4046. * @since 3.5.0
  4047. *
  4048. * @param string[] $strings Array of media view strings keyed by the name they'll be referenced by in JavaScript.
  4049. * @param WP_Post $post Post object.
  4050. */
  4051. $strings = apply_filters( 'media_view_strings', $strings, $post );
  4052. $strings['settings'] = $settings;
  4053. // Ensure we enqueue media-editor first, that way media-views
  4054. // is registered internally before we try to localize it. See #24724.
  4055. wp_enqueue_script( 'media-editor' );
  4056. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  4057. wp_enqueue_script( 'media-audiovideo' );
  4058. wp_enqueue_style( 'media-views' );
  4059. if ( is_admin() ) {
  4060. wp_enqueue_script( 'mce-view' );
  4061. wp_enqueue_script( 'image-edit' );
  4062. }
  4063. wp_enqueue_style( 'imgareaselect' );
  4064. wp_plupload_default_settings();
  4065. require_once ABSPATH . WPINC . '/media-template.php';
  4066. add_action( 'admin_footer', 'wp_print_media_templates' );
  4067. add_action( 'wp_footer', 'wp_print_media_templates' );
  4068. add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
  4069. /**
  4070. * Fires at the conclusion of wp_enqueue_media().
  4071. *
  4072. * @since 3.5.0
  4073. */
  4074. do_action( 'wp_enqueue_media' );
  4075. }
  4076. /**
  4077. * Retrieves media attached to the passed post.
  4078. *
  4079. * @since 3.6.0
  4080. *
  4081. * @param string $type Mime type.
  4082. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  4083. * @return WP_Post[] Array of media attached to the given post.
  4084. */
  4085. function get_attached_media( $type, $post = 0 ) {
  4086. $post = get_post( $post );
  4087. if ( ! $post ) {
  4088. return array();
  4089. }
  4090. $args = array(
  4091. 'post_parent' => $post->ID,
  4092. 'post_type' => 'attachment',
  4093. 'post_mime_type' => $type,
  4094. 'posts_per_page' => -1,
  4095. 'orderby' => 'menu_order',
  4096. 'order' => 'ASC',
  4097. );
  4098. /**
  4099. * Filters arguments used to retrieve media attached to the given post.
  4100. *
  4101. * @since 3.6.0
  4102. *
  4103. * @param array $args Post query arguments.
  4104. * @param string $type Mime type of the desired media.
  4105. * @param WP_Post $post Post object.
  4106. */
  4107. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  4108. $children = get_children( $args );
  4109. /**
  4110. * Filters the list of media attached to the given post.
  4111. *
  4112. * @since 3.6.0
  4113. *
  4114. * @param WP_Post[] $children Array of media attached to the given post.
  4115. * @param string $type Mime type of the media desired.
  4116. * @param WP_Post $post Post object.
  4117. */
  4118. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  4119. }
  4120. /**
  4121. * Check the content HTML for a audio, video, object, embed, or iframe tags.
  4122. *
  4123. * @since 3.6.0
  4124. *
  4125. * @param string $content A string of HTML which might contain media elements.
  4126. * @param string[] $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
  4127. * @return string[] Array of found HTML media elements.
  4128. */
  4129. function get_media_embedded_in_content( $content, $types = null ) {
  4130. $html = array();
  4131. /**
  4132. * Filters the embedded media types that are allowed to be returned from the content blob.
  4133. *
  4134. * @since 4.2.0
  4135. *
  4136. * @param string[] $allowed_media_types An array of allowed media types. Default media types are
  4137. * 'audio', 'video', 'object', 'embed', and 'iframe'.
  4138. */
  4139. $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
  4140. if ( ! empty( $types ) ) {
  4141. if ( ! is_array( $types ) ) {
  4142. $types = array( $types );
  4143. }
  4144. $allowed_media_types = array_intersect( $allowed_media_types, $types );
  4145. }
  4146. $tags = implode( '|', $allowed_media_types );
  4147. if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
  4148. foreach ( $matches[0] as $match ) {
  4149. $html[] = $match;
  4150. }
  4151. }
  4152. return $html;
  4153. }
  4154. /**
  4155. * Retrieves galleries from the passed post's content.
  4156. *
  4157. * @since 3.6.0
  4158. *
  4159. * @param int|WP_Post $post Post ID or object.
  4160. * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
  4161. * @return array A list of arrays, each containing gallery data and srcs parsed
  4162. * from the expanded shortcode.
  4163. */
  4164. function get_post_galleries( $post, $html = true ) {
  4165. $post = get_post( $post );
  4166. if ( ! $post ) {
  4167. return array();
  4168. }
  4169. if ( ! has_shortcode( $post->post_content, 'gallery' ) && ! has_block( 'gallery', $post->post_content ) ) {
  4170. return array();
  4171. }
  4172. $galleries = array();
  4173. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  4174. foreach ( $matches as $shortcode ) {
  4175. if ( 'gallery' === $shortcode[2] ) {
  4176. $srcs = array();
  4177. $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
  4178. if ( ! is_array( $shortcode_attrs ) ) {
  4179. $shortcode_attrs = array();
  4180. }
  4181. // Specify the post ID of the gallery we're viewing if the shortcode doesn't reference another post already.
  4182. if ( ! isset( $shortcode_attrs['id'] ) ) {
  4183. $shortcode[3] .= ' id="' . (int) $post->ID . '"';
  4184. }
  4185. $gallery = do_shortcode_tag( $shortcode );
  4186. if ( $html ) {
  4187. $galleries[] = $gallery;
  4188. } else {
  4189. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  4190. if ( ! empty( $src ) ) {
  4191. foreach ( $src as $s ) {
  4192. $srcs[] = $s[2];
  4193. }
  4194. }
  4195. $galleries[] = array_merge(
  4196. $shortcode_attrs,
  4197. array(
  4198. 'src' => array_values( array_unique( $srcs ) ),
  4199. )
  4200. );
  4201. }
  4202. }
  4203. }
  4204. }
  4205. if ( has_block( 'gallery', $post->post_content ) ) {
  4206. $post_blocks = parse_blocks( $post->post_content );
  4207. while ( $block = array_shift( $post_blocks ) ) {
  4208. $has_inner_blocks = ! empty( $block['innerBlocks'] );
  4209. // Skip blocks with no blockName and no innerHTML.
  4210. if ( ! $block['blockName'] ) {
  4211. continue;
  4212. }
  4213. // All blocks nested inside non-Gallery blocks should be in the root array.
  4214. if ( $has_inner_blocks && 'core/gallery' !== $block['blockName'] ) {
  4215. array_push( $post_blocks, ...$block['innerBlocks'] );
  4216. continue;
  4217. }
  4218. // New Gallery block format as HTML.
  4219. if ( $has_inner_blocks && $html ) {
  4220. $block_html = wp_list_pluck( $block['innerBlocks'], 'innerHTML' );
  4221. $galleries[] = '<figure>' . implode( ' ', $block_html ) . '</figure>';
  4222. continue;
  4223. }
  4224. $srcs = array();
  4225. // New Gallery block format as an array.
  4226. if ( $has_inner_blocks ) {
  4227. $attrs = wp_list_pluck( $block['innerBlocks'], 'attrs' );
  4228. $ids = wp_list_pluck( $attrs, 'id' );
  4229. foreach ( $ids as $id ) {
  4230. $url = wp_get_attachment_url( $id );
  4231. if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
  4232. $srcs[] = $url;
  4233. }
  4234. }
  4235. $galleries[] = array(
  4236. 'ids' => implode( ',', $ids ),
  4237. 'src' => $srcs,
  4238. );
  4239. continue;
  4240. }
  4241. // Old Gallery block format as HTML.
  4242. if ( $html ) {
  4243. $galleries[] = $block['innerHTML'];
  4244. continue;
  4245. }
  4246. // Old Gallery block format as an array.
  4247. $ids = ! empty( $block['attrs']['ids'] ) ? $block['attrs']['ids'] : array();
  4248. // If present, use the image IDs from the JSON blob as canonical.
  4249. if ( ! empty( $ids ) ) {
  4250. foreach ( $ids as $id ) {
  4251. $url = wp_get_attachment_url( $id );
  4252. if ( is_string( $url ) && ! in_array( $url, $srcs, true ) ) {
  4253. $srcs[] = $url;
  4254. }
  4255. }
  4256. $galleries[] = array(
  4257. 'ids' => implode( ',', $ids ),
  4258. 'src' => $srcs,
  4259. );
  4260. continue;
  4261. }
  4262. // Otherwise, extract srcs from the innerHTML.
  4263. preg_match_all( '#src=([\'"])(.+?)\1#is', $block['innerHTML'], $found_srcs, PREG_SET_ORDER );
  4264. if ( ! empty( $found_srcs[0] ) ) {
  4265. foreach ( $found_srcs as $src ) {
  4266. if ( isset( $src[2] ) && ! in_array( $src[2], $srcs, true ) ) {
  4267. $srcs[] = $src[2];
  4268. }
  4269. }
  4270. }
  4271. $galleries[] = array( 'src' => $srcs );
  4272. }
  4273. }
  4274. /**
  4275. * Filters the list of all found galleries in the given post.
  4276. *
  4277. * @since 3.6.0
  4278. *
  4279. * @param array $galleries Associative array of all found post galleries.
  4280. * @param WP_Post $post Post object.
  4281. */
  4282. return apply_filters( 'get_post_galleries', $galleries, $post );
  4283. }
  4284. /**
  4285. * Check a specified post's content for gallery and, if present, return the first
  4286. *
  4287. * @since 3.6.0
  4288. *
  4289. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  4290. * @param bool $html Optional. Whether to return HTML or data. Default is true.
  4291. * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  4292. */
  4293. function get_post_gallery( $post = 0, $html = true ) {
  4294. $galleries = get_post_galleries( $post, $html );
  4295. $gallery = reset( $galleries );
  4296. /**
  4297. * Filters the first-found post gallery.
  4298. *
  4299. * @since 3.6.0
  4300. *
  4301. * @param array $gallery The first-found post gallery.
  4302. * @param int|WP_Post $post Post ID or object.
  4303. * @param array $galleries Associative array of all found post galleries.
  4304. */
  4305. return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  4306. }
  4307. /**
  4308. * Retrieve the image srcs from galleries from a post's content, if present
  4309. *
  4310. * @since 3.6.0
  4311. *
  4312. * @see get_post_galleries()
  4313. *
  4314. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  4315. * @return array A list of lists, each containing image srcs parsed.
  4316. * from an expanded shortcode
  4317. */
  4318. function get_post_galleries_images( $post = 0 ) {
  4319. $galleries = get_post_galleries( $post, false );
  4320. return wp_list_pluck( $galleries, 'src' );
  4321. }
  4322. /**
  4323. * Checks a post's content for galleries and return the image srcs for the first found gallery
  4324. *
  4325. * @since 3.6.0
  4326. *
  4327. * @see get_post_gallery()
  4328. *
  4329. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  4330. * @return string[] A list of a gallery's image srcs in order.
  4331. */
  4332. function get_post_gallery_images( $post = 0 ) {
  4333. $gallery = get_post_gallery( $post, false );
  4334. return empty( $gallery['src'] ) ? array() : $gallery['src'];
  4335. }
  4336. /**
  4337. * Maybe attempts to generate attachment metadata, if missing.
  4338. *
  4339. * @since 3.9.0
  4340. *
  4341. * @param WP_Post $attachment Attachment object.
  4342. */
  4343. function wp_maybe_generate_attachment_metadata( $attachment ) {
  4344. if ( empty( $attachment ) || empty( $attachment->ID ) ) {
  4345. return;
  4346. }
  4347. $attachment_id = (int) $attachment->ID;
  4348. $file = get_attached_file( $attachment_id );
  4349. $meta = wp_get_attachment_metadata( $attachment_id );
  4350. if ( empty( $meta ) && file_exists( $file ) ) {
  4351. $_meta = get_post_meta( $attachment_id );
  4352. $_lock = 'wp_generating_att_' . $attachment_id;
  4353. if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $_lock ) ) {
  4354. set_transient( $_lock, $file );
  4355. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
  4356. delete_transient( $_lock );
  4357. }
  4358. }
  4359. }
  4360. /**
  4361. * Tries to convert an attachment URL into a post ID.
  4362. *
  4363. * @since 4.0.0
  4364. *
  4365. * @global wpdb $wpdb WordPress database abstraction object.
  4366. *
  4367. * @param string $url The URL to resolve.
  4368. * @return int The found post ID, or 0 on failure.
  4369. */
  4370. function attachment_url_to_postid( $url ) {
  4371. global $wpdb;
  4372. $dir = wp_get_upload_dir();
  4373. $path = $url;
  4374. $site_url = parse_url( $dir['url'] );
  4375. $image_path = parse_url( $path );
  4376. // Force the protocols to match if needed.
  4377. if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
  4378. $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
  4379. }
  4380. if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
  4381. $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
  4382. }
  4383. $sql = $wpdb->prepare(
  4384. "SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
  4385. $path
  4386. );
  4387. $results = $wpdb->get_results( $sql );
  4388. $post_id = null;
  4389. if ( $results ) {
  4390. // Use the first available result, but prefer a case-sensitive match, if exists.
  4391. $post_id = reset( $results )->post_id;
  4392. if ( count( $results ) > 1 ) {
  4393. foreach ( $results as $result ) {
  4394. if ( $path === $result->meta_value ) {
  4395. $post_id = $result->post_id;
  4396. break;
  4397. }
  4398. }
  4399. }
  4400. }
  4401. /**
  4402. * Filters an attachment ID found by URL.
  4403. *
  4404. * @since 4.2.0
  4405. *
  4406. * @param int|null $post_id The post_id (if any) found by the function.
  4407. * @param string $url The URL being looked up.
  4408. */
  4409. return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
  4410. }
  4411. /**
  4412. * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
  4413. *
  4414. * @since 4.0.0
  4415. *
  4416. * @return string[] The relevant CSS file URLs.
  4417. */
  4418. function wpview_media_sandbox_styles() {
  4419. $version = 'ver=' . get_bloginfo( 'version' );
  4420. $mediaelement = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" );
  4421. $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
  4422. return array( $mediaelement, $wpmediaelement );
  4423. }
  4424. /**
  4425. * Registers the personal data exporter for media.
  4426. *
  4427. * @param array[] $exporters An array of personal data exporters, keyed by their ID.
  4428. * @return array[] Updated array of personal data exporters.
  4429. */
  4430. function wp_register_media_personal_data_exporter( $exporters ) {
  4431. $exporters['wordpress-media'] = array(
  4432. 'exporter_friendly_name' => __( 'WordPress Media' ),
  4433. 'callback' => 'wp_media_personal_data_exporter',
  4434. );
  4435. return $exporters;
  4436. }
  4437. /**
  4438. * Finds and exports attachments associated with an email address.
  4439. *
  4440. * @since 4.9.6
  4441. *
  4442. * @param string $email_address The attachment owner email address.
  4443. * @param int $page Attachment page.
  4444. * @return array An array of personal data.
  4445. */
  4446. function wp_media_personal_data_exporter( $email_address, $page = 1 ) {
  4447. // Limit us to 50 attachments at a time to avoid timing out.
  4448. $number = 50;
  4449. $page = (int) $page;
  4450. $data_to_export = array();
  4451. $user = get_user_by( 'email', $email_address );
  4452. if ( false === $user ) {
  4453. return array(
  4454. 'data' => $data_to_export,
  4455. 'done' => true,
  4456. );
  4457. }
  4458. $post_query = new WP_Query(
  4459. array(
  4460. 'author' => $user->ID,
  4461. 'posts_per_page' => $number,
  4462. 'paged' => $page,
  4463. 'post_type' => 'attachment',
  4464. 'post_status' => 'any',
  4465. 'orderby' => 'ID',
  4466. 'order' => 'ASC',
  4467. )
  4468. );
  4469. foreach ( (array) $post_query->posts as $post ) {
  4470. $attachment_url = wp_get_attachment_url( $post->ID );
  4471. if ( $attachment_url ) {
  4472. $post_data_to_export = array(
  4473. array(
  4474. 'name' => __( 'URL' ),
  4475. 'value' => $attachment_url,
  4476. ),
  4477. );
  4478. $data_to_export[] = array(
  4479. 'group_id' => 'media',
  4480. 'group_label' => __( 'Media' ),
  4481. 'group_description' => __( 'User&#8217;s media data.' ),
  4482. 'item_id' => "post-{$post->ID}",
  4483. 'data' => $post_data_to_export,
  4484. );
  4485. }
  4486. }
  4487. $done = $post_query->max_num_pages <= $page;
  4488. return array(
  4489. 'data' => $data_to_export,
  4490. 'done' => $done,
  4491. );
  4492. }
  4493. /**
  4494. * Add additional default image sub-sizes.
  4495. *
  4496. * These sizes are meant to enhance the way WordPress displays images on the front-end on larger,
  4497. * high-density devices. They make it possible to generate more suitable `srcset` and `sizes` attributes
  4498. * when the users upload large images.
  4499. *
  4500. * The sizes can be changed or removed by themes and plugins but that is not recommended.
  4501. * The size "names" reflect the image dimensions, so changing the sizes would be quite misleading.
  4502. *
  4503. * @since 5.3.0
  4504. * @access private
  4505. */
  4506. function _wp_add_additional_image_sizes() {
  4507. // 2x medium_large size.
  4508. add_image_size( '1536x1536', 1536, 1536 );
  4509. // 2x large size.
  4510. add_image_size( '2048x2048', 2048, 2048 );
  4511. }
  4512. /**
  4513. * Callback to enable showing of the user error when uploading .heic images.
  4514. *
  4515. * @since 5.5.0
  4516. *
  4517. * @param array[] $plupload_settings The settings for Plupload.js.
  4518. * @return array[] Modified settings for Plupload.js.
  4519. */
  4520. function wp_show_heic_upload_error( $plupload_settings ) {
  4521. $plupload_settings['heic_upload_error'] = true;
  4522. return $plupload_settings;
  4523. }
  4524. /**
  4525. * Allows PHP's getimagesize() to be debuggable when necessary.
  4526. *
  4527. * @since 5.7.0
  4528. * @since 5.8.0 Added support for WebP images.
  4529. *
  4530. * @param string $filename The file path.
  4531. * @param array $image_info Optional. Extended image information (passed by reference).
  4532. * @return array|false Array of image information or false on failure.
  4533. */
  4534. function wp_getimagesize( $filename, array &$image_info = null ) {
  4535. // Don't silence errors when in debug mode, unless running unit tests.
  4536. if ( defined( 'WP_DEBUG' ) && WP_DEBUG
  4537. && ! defined( 'WP_RUN_CORE_TESTS' )
  4538. ) {
  4539. if ( 2 === func_num_args() ) {
  4540. $info = getimagesize( $filename, $image_info );
  4541. } else {
  4542. $info = getimagesize( $filename );
  4543. }
  4544. } else {
  4545. /*
  4546. * Silencing notice and warning is intentional.
  4547. *
  4548. * getimagesize() has a tendency to generate errors, such as
  4549. * "corrupt JPEG data: 7191 extraneous bytes before marker",
  4550. * even when it's able to provide image size information.
  4551. *
  4552. * See https://core.trac.wordpress.org/ticket/42480
  4553. */
  4554. if ( 2 === func_num_args() ) {
  4555. // phpcs:ignore WordPress.PHP.NoSilencedErrors
  4556. $info = @getimagesize( $filename, $image_info );
  4557. } else {
  4558. // phpcs:ignore WordPress.PHP.NoSilencedErrors
  4559. $info = @getimagesize( $filename );
  4560. }
  4561. }
  4562. if ( false !== $info ) {
  4563. return $info;
  4564. }
  4565. // For PHP versions that don't support WebP images,
  4566. // extract the image size info from the file headers.
  4567. if ( 'image/webp' === wp_get_image_mime( $filename ) ) {
  4568. $webp_info = wp_get_webp_info( $filename );
  4569. $width = $webp_info['width'];
  4570. $height = $webp_info['height'];
  4571. // Mimic the native return format.
  4572. if ( $width && $height ) {
  4573. return array(
  4574. $width,
  4575. $height,
  4576. IMAGETYPE_WEBP,
  4577. sprintf(
  4578. 'width="%d" height="%d"',
  4579. $width,
  4580. $height
  4581. ),
  4582. 'mime' => 'image/webp',
  4583. );
  4584. }
  4585. }
  4586. // The image could not be parsed.
  4587. return false;
  4588. }
  4589. /**
  4590. * Extracts meta information about a WebP file: width, height, and type.
  4591. *
  4592. * @since 5.8.0
  4593. *
  4594. * @param string $filename Path to a WebP file.
  4595. * @return array {
  4596. * An array of WebP image information.
  4597. *
  4598. * @type int|false $width Image width on success, false on failure.
  4599. * @type int|false $height Image height on success, false on failure.
  4600. * @type string|false $type The WebP type: one of 'lossy', 'lossless' or 'animated-alpha'.
  4601. * False on failure.
  4602. * }
  4603. */
  4604. function wp_get_webp_info( $filename ) {
  4605. $width = false;
  4606. $height = false;
  4607. $type = false;
  4608. if ( 'image/webp' !== wp_get_image_mime( $filename ) ) {
  4609. return compact( 'width', 'height', 'type' );
  4610. }
  4611. $magic = file_get_contents( $filename, false, null, 0, 40 );
  4612. if ( false === $magic ) {
  4613. return compact( 'width', 'height', 'type' );
  4614. }
  4615. // Make sure we got enough bytes.
  4616. if ( strlen( $magic ) < 40 ) {
  4617. return compact( 'width', 'height', 'type' );
  4618. }
  4619. // The headers are a little different for each of the three formats.
  4620. // Header values based on WebP docs, see https://developers.google.com/speed/webp/docs/riff_container.
  4621. switch ( substr( $magic, 12, 4 ) ) {
  4622. // Lossy WebP.
  4623. case 'VP8 ':
  4624. $parts = unpack( 'v2', substr( $magic, 26, 4 ) );
  4625. $width = (int) ( $parts[1] & 0x3FFF );
  4626. $height = (int) ( $parts[2] & 0x3FFF );
  4627. $type = 'lossy';
  4628. break;
  4629. // Lossless WebP.
  4630. case 'VP8L':
  4631. $parts = unpack( 'C4', substr( $magic, 21, 4 ) );
  4632. $width = (int) ( $parts[1] | ( ( $parts[2] & 0x3F ) << 8 ) ) + 1;
  4633. $height = (int) ( ( ( $parts[2] & 0xC0 ) >> 6 ) | ( $parts[3] << 2 ) | ( ( $parts[4] & 0x03 ) << 10 ) ) + 1;
  4634. $type = 'lossless';
  4635. break;
  4636. // Animated/alpha WebP.
  4637. case 'VP8X':
  4638. // Pad 24-bit int.
  4639. $width = unpack( 'V', substr( $magic, 24, 3 ) . "\x00" );
  4640. $width = (int) ( $width[1] & 0xFFFFFF ) + 1;
  4641. // Pad 24-bit int.
  4642. $height = unpack( 'V', substr( $magic, 27, 3 ) . "\x00" );
  4643. $height = (int) ( $height[1] & 0xFFFFFF ) + 1;
  4644. $type = 'animated-alpha';
  4645. break;
  4646. }
  4647. return compact( 'width', 'height', 'type' );
  4648. }
  4649. /**
  4650. * Gets the default value to use for a `loading` attribute on an element.
  4651. *
  4652. * This function should only be called for a tag and context if lazy-loading is generally enabled.
  4653. *
  4654. * The function usually returns 'lazy', but uses certain heuristics to guess whether the current element is likely to
  4655. * appear above the fold, in which case it returns a boolean `false`, which will lead to the `loading` attribute being
  4656. * omitted on the element. The purpose of this refinement is to avoid lazy-loading elements that are within the initial
  4657. * viewport, which can have a negative performance impact.
  4658. *
  4659. * Under the hood, the function uses {@see wp_increase_content_media_count()} every time it is called for an element
  4660. * within the main content. If the element is the very first content element, the `loading` attribute will be omitted.
  4661. * This default threshold of 1 content element to omit the `loading` attribute for can be customized using the
  4662. * {@see 'wp_omit_loading_attr_threshold'} filter.
  4663. *
  4664. * @since 5.9.0
  4665. *
  4666. * @param string $context Context for the element for which the `loading` attribute value is requested.
  4667. * @return string|bool The default `loading` attribute value. Either 'lazy', 'eager', or a boolean `false`, to indicate
  4668. * that the `loading` attribute should be skipped.
  4669. */
  4670. function wp_get_loading_attr_default( $context ) {
  4671. // Only elements with 'the_content' or 'the_post_thumbnail' context have special handling.
  4672. if ( 'the_content' !== $context && 'the_post_thumbnail' !== $context ) {
  4673. return 'lazy';
  4674. }
  4675. // Only elements within the main query loop have special handling.
  4676. if ( is_admin() || ! in_the_loop() || ! is_main_query() ) {
  4677. return 'lazy';
  4678. }
  4679. // Increase the counter since this is a main query content element.
  4680. $content_media_count = wp_increase_content_media_count();
  4681. // If the count so far is below the threshold, return `false` so that the `loading` attribute is omitted.
  4682. if ( $content_media_count <= wp_omit_loading_attr_threshold() ) {
  4683. return false;
  4684. }
  4685. // For elements after the threshold, lazy-load them as usual.
  4686. return 'lazy';
  4687. }
  4688. /**
  4689. * Gets the threshold for how many of the first content media elements to not lazy-load.
  4690. *
  4691. * This function runs the {@see 'wp_omit_loading_attr_threshold'} filter, which uses a default threshold value of 1.
  4692. * The filter is only run once per page load, unless the `$force` parameter is used.
  4693. *
  4694. * @since 5.9.0
  4695. *
  4696. * @param bool $force Optional. If set to true, the filter will be (re-)applied even if it already has been before.
  4697. * Default false.
  4698. * @return int The number of content media elements to not lazy-load.
  4699. */
  4700. function wp_omit_loading_attr_threshold( $force = false ) {
  4701. static $omit_threshold;
  4702. // This function may be called multiple times. Run the filter only once per page load.
  4703. if ( ! isset( $omit_threshold ) || $force ) {
  4704. /**
  4705. * Filters the threshold for how many of the first content media elements to not lazy-load.
  4706. *
  4707. * For these first content media elements, the `loading` attribute will be omitted. By default, this is the case
  4708. * for only the very first content media element.
  4709. *
  4710. * @since 5.9.0
  4711. *
  4712. * @param int $omit_threshold The number of media elements where the `loading` attribute will not be added. Default 1.
  4713. */
  4714. $omit_threshold = apply_filters( 'wp_omit_loading_attr_threshold', 1 );
  4715. }
  4716. return $omit_threshold;
  4717. }
  4718. /**
  4719. * Increases an internal content media count variable.
  4720. *
  4721. * @since 5.9.0
  4722. * @access private
  4723. *
  4724. * @param int $amount Optional. Amount to increase by. Default 1.
  4725. * @return int The latest content media count, after the increase.
  4726. */
  4727. function wp_increase_content_media_count( $amount = 1 ) {
  4728. static $content_media_count = 0;
  4729. $content_media_count += $amount;
  4730. return $content_media_count;
  4731. }