PageRenderTime 74ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

https://bitbucket.org/skyarch-iijima/wordpress
PHP | 3958 lines | 1934 code | 440 blank | 1584 comment | 395 complexity | 1cafc46a1a5e7146d64b2ee53ab7c5c1 MD5 | raw file
  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. The second
  38. * parameter will be the value that was in the $size parameter. The returned
  39. * type for the hook is an array with the width as the first element and the
  40. * height as the second element.
  41. *
  42. * @since 2.5.0
  43. *
  44. * @global int $content_width
  45. *
  46. * @param int $width Width of the image in pixels.
  47. * @param int $height Height of the image in pixels.
  48. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array
  49. * of width and height values in pixels (in that order).
  50. * Default 'medium'.
  51. * @param string $context Optional. Could be 'display' (like in a theme) or 'edit'
  52. * (like inserting into an editor). Default null.
  53. * @return array Width and height of what the result image should resize to.
  54. */
  55. function image_constrain_size_for_editor( $width, $height, $size = 'medium', $context = null ) {
  56. global $content_width;
  57. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  58. if ( ! $context )
  59. $context = is_admin() ? 'edit' : 'display';
  60. if ( is_array($size) ) {
  61. $max_width = $size[0];
  62. $max_height = $size[1];
  63. }
  64. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  65. $max_width = intval(get_option('thumbnail_size_w'));
  66. $max_height = intval(get_option('thumbnail_size_h'));
  67. // last chance thumbnail size defaults
  68. if ( !$max_width && !$max_height ) {
  69. $max_width = 128;
  70. $max_height = 96;
  71. }
  72. }
  73. elseif ( $size == 'medium' ) {
  74. $max_width = intval(get_option('medium_size_w'));
  75. $max_height = intval(get_option('medium_size_h'));
  76. }
  77. elseif ( $size == 'medium_large' ) {
  78. $max_width = intval( get_option( 'medium_large_size_w' ) );
  79. $max_height = intval( get_option( 'medium_large_size_h' ) );
  80. if ( intval( $content_width ) > 0 ) {
  81. $max_width = min( intval( $content_width ), $max_width );
  82. }
  83. }
  84. elseif ( $size == 'large' ) {
  85. /*
  86. * We're inserting a large size image into the editor. If it's a really
  87. * big image we'll scale it down to fit reasonably within the editor
  88. * itself, and within the theme's content width if it's known. The user
  89. * can resize it in the editor if they wish.
  90. */
  91. $max_width = intval(get_option('large_size_w'));
  92. $max_height = intval(get_option('large_size_h'));
  93. if ( intval($content_width) > 0 ) {
  94. $max_width = min( intval($content_width), $max_width );
  95. }
  96. } elseif ( ! empty( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  97. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  98. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  99. // Only in admin. Assume that theme authors know what they're doing.
  100. if ( intval( $content_width ) > 0 && 'edit' === $context ) {
  101. $max_width = min( intval( $content_width ), $max_width );
  102. }
  103. }
  104. // $size == 'full' has no constraint
  105. else {
  106. $max_width = $width;
  107. $max_height = $height;
  108. }
  109. /**
  110. * Filters the maximum image size dimensions for the editor.
  111. *
  112. * @since 2.5.0
  113. *
  114. * @param array $max_image_size An array with the width as the first element,
  115. * and the height as the second element.
  116. * @param string|array $size Size of what the result image should be.
  117. * @param string $context The context the image is being resized for.
  118. * Possible values are 'display' (like in a theme)
  119. * or 'edit' (like inserting into an editor).
  120. */
  121. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  122. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  123. }
  124. /**
  125. * Retrieve width and height attributes using given width and height values.
  126. *
  127. * Both attributes are required in the sense that both parameters must have a
  128. * value, but are optional in that if you set them to false or null, then they
  129. * will not be added to the returned string.
  130. *
  131. * You can set the value using a string, but it will only take numeric values.
  132. * If you wish to put 'px' after the numbers, then it will be stripped out of
  133. * the return.
  134. *
  135. * @since 2.5.0
  136. *
  137. * @param int|string $width Image width in pixels.
  138. * @param int|string $height Image height in pixels.
  139. * @return string HTML attributes for width and, or height.
  140. */
  141. function image_hwstring( $width, $height ) {
  142. $out = '';
  143. if ($width)
  144. $out .= 'width="'.intval($width).'" ';
  145. if ($height)
  146. $out .= 'height="'.intval($height).'" ';
  147. return $out;
  148. }
  149. /**
  150. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  151. *
  152. * Array with image url, width, height, and whether is intermediate size, in
  153. * that order is returned on success is returned. $is_intermediate is true if
  154. * $url is a resized image, false if it is the original.
  155. *
  156. * The URL might be the original image, or it might be a resized version. This
  157. * function won't create a new resized copy, it will just return an already
  158. * resized one if it exists.
  159. *
  160. * A plugin may use the {@see 'image_downsize'} filter to hook into and offer image
  161. * resizing services for images. The hook must return an array with the same
  162. * elements that are returned in the function. The first element being the URL
  163. * to the new image that was resized.
  164. *
  165. * @since 2.5.0
  166. *
  167. * @param int $id Attachment ID for image.
  168. * @param array|string $size Optional. Image size to scale to. Accepts any valid image size,
  169. * or an array of width and height values in pixels (in that order).
  170. * Default 'medium'.
  171. * @return false|array Array containing the image URL, width, height, and boolean for whether
  172. * the image is an intermediate size. False on failure.
  173. */
  174. function image_downsize( $id, $size = 'medium' ) {
  175. $is_image = wp_attachment_is_image( $id );
  176. /**
  177. * Filters whether to preempt the output of image_downsize().
  178. *
  179. * Passing a truthy value to the filter will effectively short-circuit
  180. * down-sizing the image, returning that value as output instead.
  181. *
  182. * @since 2.5.0
  183. *
  184. * @param bool $downsize Whether to short-circuit the image downsize. Default false.
  185. * @param int $id Attachment ID for image.
  186. * @param array|string $size Size of image. Image size or array of width and height values (in that order).
  187. * Default 'medium'.
  188. */
  189. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
  190. return $out;
  191. }
  192. $img_url = wp_get_attachment_url($id);
  193. $meta = wp_get_attachment_metadata($id);
  194. $width = $height = 0;
  195. $is_intermediate = false;
  196. $img_url_basename = wp_basename($img_url);
  197. // If the file isn't an image, attempt to replace its URL with a rendered image from its meta.
  198. // Otherwise, a non-image type could be returned.
  199. if ( ! $is_image ) {
  200. if ( ! empty( $meta['sizes'] ) ) {
  201. $img_url = str_replace( $img_url_basename, $meta['sizes']['full']['file'], $img_url );
  202. $img_url_basename = $meta['sizes']['full']['file'];
  203. $width = $meta['sizes']['full']['width'];
  204. $height = $meta['sizes']['full']['height'];
  205. } else {
  206. return false;
  207. }
  208. }
  209. // try for a new style intermediate size
  210. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  211. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  212. $width = $intermediate['width'];
  213. $height = $intermediate['height'];
  214. $is_intermediate = true;
  215. }
  216. elseif ( $size == 'thumbnail' ) {
  217. // fall back to the old thumbnail
  218. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  219. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  220. $width = $info[0];
  221. $height = $info[1];
  222. $is_intermediate = true;
  223. }
  224. }
  225. if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
  226. // any other type: use the real image
  227. $width = $meta['width'];
  228. $height = $meta['height'];
  229. }
  230. if ( $img_url) {
  231. // we have the actual image size, but might need to further constrain it if content_width is narrower
  232. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  233. return array( $img_url, $width, $height, $is_intermediate );
  234. }
  235. return false;
  236. }
  237. /**
  238. * Register a new image size.
  239. *
  240. * Cropping behavior for the image size is dependent on the value of $crop:
  241. * 1. If false (default), images will be scaled, not cropped.
  242. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  243. * - x_crop_position accepts 'left' 'center', or 'right'.
  244. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  245. * Images will be cropped to the specified dimensions within the defined crop area.
  246. * 3. If true, images will be cropped to the specified dimensions using center positions.
  247. *
  248. * @since 2.9.0
  249. *
  250. * @global array $_wp_additional_image_sizes Associative array of additional image sizes.
  251. *
  252. * @param string $name Image size identifier.
  253. * @param int $width Image width in pixels.
  254. * @param int $height Image height in pixels.
  255. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  256. * An array can specify positioning of the crop area. Default false.
  257. */
  258. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  259. global $_wp_additional_image_sizes;
  260. $_wp_additional_image_sizes[ $name ] = array(
  261. 'width' => absint( $width ),
  262. 'height' => absint( $height ),
  263. 'crop' => $crop,
  264. );
  265. }
  266. /**
  267. * Check if an image size exists.
  268. *
  269. * @since 3.9.0
  270. *
  271. * @param string $name The image size to check.
  272. * @return bool True if the image size exists, false if not.
  273. */
  274. function has_image_size( $name ) {
  275. $sizes = wp_get_additional_image_sizes();
  276. return isset( $sizes[ $name ] );
  277. }
  278. /**
  279. * Remove a new image size.
  280. *
  281. * @since 3.9.0
  282. *
  283. * @global array $_wp_additional_image_sizes
  284. *
  285. * @param string $name The image size to remove.
  286. * @return bool True if the image size was successfully removed, false on failure.
  287. */
  288. function remove_image_size( $name ) {
  289. global $_wp_additional_image_sizes;
  290. if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
  291. unset( $_wp_additional_image_sizes[ $name ] );
  292. return true;
  293. }
  294. return false;
  295. }
  296. /**
  297. * Registers an image size for the post thumbnail.
  298. *
  299. * @since 2.9.0
  300. *
  301. * @see add_image_size() for details on cropping behavior.
  302. *
  303. * @param int $width Image width in pixels.
  304. * @param int $height Image height in pixels.
  305. * @param bool|array $crop Optional. Whether to crop images to specified width and height or resize.
  306. * An array can specify positioning of the crop area. Default false.
  307. */
  308. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  309. add_image_size( 'post-thumbnail', $width, $height, $crop );
  310. }
  311. /**
  312. * Gets an img tag for an image attachment, scaling it down if requested.
  313. *
  314. * The {@see 'get_image_tag_class'} filter allows for changing the class name for the
  315. * image without having to use regular expressions on the HTML content. The
  316. * parameters are: what WordPress will use for the class, the Attachment ID,
  317. * image align value, and the size the image should be.
  318. *
  319. * The second filter, {@see 'get_image_tag'}, has the HTML content, which can then be
  320. * further manipulated by a plugin to change all attribute values and even HTML
  321. * content.
  322. *
  323. * @since 2.5.0
  324. *
  325. * @param int $id Attachment ID.
  326. * @param string $alt Image Description for the alt attribute.
  327. * @param string $title Image Description for the title attribute.
  328. * @param string $align Part of the class name for aligning the image.
  329. * @param string|array $size Optional. Registered image size to retrieve a tag for. Accepts any
  330. * valid image size, or an array of width and height values in pixels
  331. * (in that order). Default 'medium'.
  332. * @return string HTML IMG element for given image attachment
  333. */
  334. function get_image_tag( $id, $alt, $title, $align, $size = 'medium' ) {
  335. list( $img_src, $width, $height ) = image_downsize($id, $size);
  336. $hwstring = image_hwstring($width, $height);
  337. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  338. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  339. /**
  340. * Filters the value of the attachment's image tag class attribute.
  341. *
  342. * @since 2.6.0
  343. *
  344. * @param string $class CSS class name or space-separated list of classes.
  345. * @param int $id Attachment ID.
  346. * @param string $align Part of the class name for aligning the image.
  347. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  348. * Default 'medium'.
  349. */
  350. $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
  351. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  352. /**
  353. * Filters the HTML content for the image tag.
  354. *
  355. * @since 2.6.0
  356. *
  357. * @param string $html HTML content for the image.
  358. * @param int $id Attachment ID.
  359. * @param string $alt Alternate text.
  360. * @param string $title Attachment title.
  361. * @param string $align Part of the class name for aligning the image.
  362. * @param string|array $size Size of image. Image size or array of width and height values (in that order).
  363. * Default 'medium'.
  364. */
  365. return apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  366. }
  367. /**
  368. * Calculates the new dimensions for a down-sampled image.
  369. *
  370. * If either width or height are empty, no constraint is applied on
  371. * that dimension.
  372. *
  373. * @since 2.5.0
  374. *
  375. * @param int $current_width Current width of the image.
  376. * @param int $current_height Current height of the image.
  377. * @param int $max_width Optional. Max width in pixels to constrain to. Default 0.
  378. * @param int $max_height Optional. Max height in pixels to constrain to. Default 0.
  379. * @return array First item is the width, the second item is the height.
  380. */
  381. function wp_constrain_dimensions( $current_width, $current_height, $max_width = 0, $max_height = 0 ) {
  382. if ( !$max_width && !$max_height )
  383. return array( $current_width, $current_height );
  384. $width_ratio = $height_ratio = 1.0;
  385. $did_width = $did_height = false;
  386. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  387. $width_ratio = $max_width / $current_width;
  388. $did_width = true;
  389. }
  390. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  391. $height_ratio = $max_height / $current_height;
  392. $did_height = true;
  393. }
  394. // Calculate the larger/smaller ratios
  395. $smaller_ratio = min( $width_ratio, $height_ratio );
  396. $larger_ratio = max( $width_ratio, $height_ratio );
  397. if ( (int) round( $current_width * $larger_ratio ) > $max_width || (int) round( $current_height * $larger_ratio ) > $max_height ) {
  398. // The larger ratio is too big. It would result in an overflow.
  399. $ratio = $smaller_ratio;
  400. } else {
  401. // The larger ratio fits, and is likely to be a more "snug" fit.
  402. $ratio = $larger_ratio;
  403. }
  404. // Very small dimensions may result in 0, 1 should be the minimum.
  405. $w = max ( 1, (int) round( $current_width * $ratio ) );
  406. $h = max ( 1, (int) round( $current_height * $ratio ) );
  407. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  408. // We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result.
  409. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  410. // Note: $did_width means it is possible $smaller_ratio == $width_ratio.
  411. if ( $did_width && $w == $max_width - 1 ) {
  412. $w = $max_width; // Round it up
  413. }
  414. // Note: $did_height means it is possible $smaller_ratio == $height_ratio.
  415. if ( $did_height && $h == $max_height - 1 ) {
  416. $h = $max_height; // Round it up
  417. }
  418. /**
  419. * Filters dimensions to constrain down-sampled images to.
  420. *
  421. * @since 4.1.0
  422. *
  423. * @param array $dimensions The image width and height.
  424. * @param int $current_width The current width of the image.
  425. * @param int $current_height The current height of the image.
  426. * @param int $max_width The maximum width permitted.
  427. * @param int $max_height The maximum height permitted.
  428. */
  429. return apply_filters( 'wp_constrain_dimensions', array( $w, $h ), $current_width, $current_height, $max_width, $max_height );
  430. }
  431. /**
  432. * Retrieves calculated resize dimensions for use in WP_Image_Editor.
  433. *
  434. * Calculates dimensions and coordinates for a resized image that fits
  435. * within a specified width and height.
  436. *
  437. * Cropping behavior is dependent on the value of $crop:
  438. * 1. If false (default), images will not be cropped.
  439. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  440. * - x_crop_position accepts 'left' 'center', or 'right'.
  441. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  442. * Images will be cropped to the specified dimensions within the defined crop area.
  443. * 3. If true, images will be cropped to the specified dimensions using center positions.
  444. *
  445. * @since 2.5.0
  446. *
  447. * @param int $orig_w Original width in pixels.
  448. * @param int $orig_h Original height in pixels.
  449. * @param int $dest_w New width in pixels.
  450. * @param int $dest_h New height in pixels.
  451. * @param bool|array $crop Optional. Whether to crop image to specified width and height or resize.
  452. * An array can specify positioning of the crop area. Default false.
  453. * @return false|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
  454. */
  455. function image_resize_dimensions( $orig_w, $orig_h, $dest_w, $dest_h, $crop = false ) {
  456. if ($orig_w <= 0 || $orig_h <= 0)
  457. return false;
  458. // at least one of dest_w or dest_h must be specific
  459. if ($dest_w <= 0 && $dest_h <= 0)
  460. return false;
  461. /**
  462. * Filters whether to preempt calculating the image resize dimensions.
  463. *
  464. * Passing a non-null value to the filter will effectively short-circuit
  465. * image_resize_dimensions(), returning that value instead.
  466. *
  467. * @since 3.4.0
  468. *
  469. * @param null|mixed $null Whether to preempt output of the resize dimensions.
  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 Whether to crop image to specified width and height or resize.
  475. * An array can specify positioning of the crop area. Default false.
  476. */
  477. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  478. if ( null !== $output )
  479. return $output;
  480. if ( $crop ) {
  481. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  482. $aspect_ratio = $orig_w / $orig_h;
  483. $new_w = min($dest_w, $orig_w);
  484. $new_h = min($dest_h, $orig_h);
  485. if ( ! $new_w ) {
  486. $new_w = (int) round( $new_h * $aspect_ratio );
  487. }
  488. if ( ! $new_h ) {
  489. $new_h = (int) round( $new_w / $aspect_ratio );
  490. }
  491. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  492. $crop_w = round($new_w / $size_ratio);
  493. $crop_h = round($new_h / $size_ratio);
  494. if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
  495. $crop = array( 'center', 'center' );
  496. }
  497. list( $x, $y ) = $crop;
  498. if ( 'left' === $x ) {
  499. $s_x = 0;
  500. } elseif ( 'right' === $x ) {
  501. $s_x = $orig_w - $crop_w;
  502. } else {
  503. $s_x = floor( ( $orig_w - $crop_w ) / 2 );
  504. }
  505. if ( 'top' === $y ) {
  506. $s_y = 0;
  507. } elseif ( 'bottom' === $y ) {
  508. $s_y = $orig_h - $crop_h;
  509. } else {
  510. $s_y = floor( ( $orig_h - $crop_h ) / 2 );
  511. }
  512. } else {
  513. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  514. $crop_w = $orig_w;
  515. $crop_h = $orig_h;
  516. $s_x = 0;
  517. $s_y = 0;
  518. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  519. }
  520. // if the resulting image would be the same size or larger we don't want to resize it
  521. if ( $new_w >= $orig_w && $new_h >= $orig_h && $dest_w != $orig_w && $dest_h != $orig_h ) {
  522. return false;
  523. }
  524. // the return array matches the parameters to imagecopyresampled()
  525. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  526. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  527. }
  528. /**
  529. * Resizes an image to make a thumbnail or intermediate size.
  530. *
  531. * The returned array has the file size, the image width, and image height. The
  532. * {@see 'image_make_intermediate_size'} filter can be used to hook in and change the
  533. * values of the returned array. The only parameter is the resized file path.
  534. *
  535. * @since 2.5.0
  536. *
  537. * @param string $file File path.
  538. * @param int $width Image width.
  539. * @param int $height Image height.
  540. * @param bool $crop Optional. Whether to crop image to specified width and height or resize.
  541. * Default false.
  542. * @return false|array False, if no image was created. Metadata array on success.
  543. */
  544. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  545. if ( $width || $height ) {
  546. $editor = wp_get_image_editor( $file );
  547. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  548. return false;
  549. $resized_file = $editor->save();
  550. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  551. unset( $resized_file['path'] );
  552. return $resized_file;
  553. }
  554. }
  555. return false;
  556. }
  557. /**
  558. * Helper function to test if aspect ratios for two images match.
  559. *
  560. * @since 4.6.0
  561. *
  562. * @param int $source_width Width of the first image in pixels.
  563. * @param int $source_height Height of the first image in pixels.
  564. * @param int $target_width Width of the second image in pixels.
  565. * @param int $target_height Height of the second image in pixels.
  566. * @return bool True if aspect ratios match within 1px. False if not.
  567. */
  568. function wp_image_matches_ratio( $source_width, $source_height, $target_width, $target_height ) {
  569. /*
  570. * To test for varying crops, we constrain the dimensions of the larger image
  571. * to the dimensions of the smaller image and see if they match.
  572. */
  573. if ( $source_width > $target_width ) {
  574. $constrained_size = wp_constrain_dimensions( $source_width, $source_height, $target_width );
  575. $expected_size = array( $target_width, $target_height );
  576. } else {
  577. $constrained_size = wp_constrain_dimensions( $target_width, $target_height, $source_width );
  578. $expected_size = array( $source_width, $source_height );
  579. }
  580. // If the image dimensions are within 1px of the expected size, we consider it a match.
  581. $matched = ( abs( $constrained_size[0] - $expected_size[0] ) <= 1 && abs( $constrained_size[1] - $expected_size[1] ) <= 1 );
  582. return $matched;
  583. }
  584. /**
  585. * Retrieves the image's intermediate size (resized) path, width, and height.
  586. *
  587. * The $size parameter can be an array with the width and height respectively.
  588. * If the size matches the 'sizes' metadata array for width and height, then it
  589. * will be used. If there is no direct match, then the nearest image size larger
  590. * than the specified size will be used. If nothing is found, then the function
  591. * will break out and return false.
  592. *
  593. * The metadata 'sizes' is used for compatible sizes that can be used for the
  594. * parameter $size value.
  595. *
  596. * The url path will be given, when the $size parameter is a string.
  597. *
  598. * If you are passing an array for the $size, you should consider using
  599. * add_image_size() so that a cropped version is generated. It's much more
  600. * efficient than having to find the closest-sized image and then having the
  601. * browser scale down the image.
  602. *
  603. * @since 2.5.0
  604. *
  605. * @param int $post_id Attachment ID.
  606. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array
  607. * of width and height values in pixels (in that order).
  608. * Default 'thumbnail'.
  609. * @return false|array $data {
  610. * Array of file relative path, width, and height on success. Additionally includes absolute
  611. * path and URL if registered size is passed to $size parameter. False on failure.
  612. *
  613. * @type string $file Image's path relative to uploads directory
  614. * @type int $width Width of image
  615. * @type int $height Height of image
  616. * @type string $path Image's absolute filesystem path.
  617. * @type string $url Image's URL.
  618. * }
  619. */
  620. function image_get_intermediate_size( $post_id, $size = 'thumbnail' ) {
  621. if ( ! $size || ! is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) || empty( $imagedata['sizes'] ) ) {
  622. return false;
  623. }
  624. $data = array();
  625. // Find the best match when '$size' is an array.
  626. if ( is_array( $size ) ) {
  627. $candidates = array();
  628. if ( ! isset( $imagedata['file'] ) && isset( $imagedata['sizes']['full'] ) ) {
  629. $imagedata['height'] = $imagedata['sizes']['full']['height'];
  630. $imagedata['width'] = $imagedata['sizes']['full']['width'];
  631. }
  632. foreach ( $imagedata['sizes'] as $_size => $data ) {
  633. // If there's an exact match to an existing image size, short circuit.
  634. if ( $data['width'] == $size[0] && $data['height'] == $size[1] ) {
  635. $candidates[ $data['width'] * $data['height'] ] = $data;
  636. break;
  637. }
  638. // If it's not an exact match, consider larger sizes with the same aspect ratio.
  639. if ( $data['width'] >= $size[0] && $data['height'] >= $size[1] ) {
  640. // If '0' is passed to either size, we test ratios against the original file.
  641. if ( 0 === $size[0] || 0 === $size[1] ) {
  642. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $imagedata['width'], $imagedata['height'] );
  643. } else {
  644. $same_ratio = wp_image_matches_ratio( $data['width'], $data['height'], $size[0], $size[1] );
  645. }
  646. if ( $same_ratio ) {
  647. $candidates[ $data['width'] * $data['height'] ] = $data;
  648. }
  649. }
  650. }
  651. if ( ! empty( $candidates ) ) {
  652. // Sort the array by size if we have more than one candidate.
  653. if ( 1 < count( $candidates ) ) {
  654. ksort( $candidates );
  655. }
  656. $data = array_shift( $candidates );
  657. /*
  658. * When the size requested is smaller than the thumbnail dimensions, we
  659. * fall back to the thumbnail size to maintain backwards compatibility with
  660. * pre 4.6 versions of WordPress.
  661. */
  662. } elseif ( ! empty( $imagedata['sizes']['thumbnail'] ) && $imagedata['sizes']['thumbnail']['width'] >= $size[0] && $imagedata['sizes']['thumbnail']['width'] >= $size[1] ) {
  663. $data = $imagedata['sizes']['thumbnail'];
  664. } else {
  665. return false;
  666. }
  667. // Constrain the width and height attributes to the requested values.
  668. list( $data['width'], $data['height'] ) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  669. } elseif ( ! empty( $imagedata['sizes'][ $size ] ) ) {
  670. $data = $imagedata['sizes'][ $size ];
  671. }
  672. // If we still don't have a match at this point, return false.
  673. if ( empty( $data ) ) {
  674. return false;
  675. }
  676. // include the full filesystem path of the intermediate file
  677. if ( empty( $data['path'] ) && ! empty( $data['file'] ) && ! empty( $imagedata['file'] ) ) {
  678. $file_url = wp_get_attachment_url($post_id);
  679. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  680. $data['url'] = path_join( dirname($file_url), $data['file'] );
  681. }
  682. /**
  683. * Filters the output of image_get_intermediate_size()
  684. *
  685. * @since 4.4.0
  686. *
  687. * @see image_get_intermediate_size()
  688. *
  689. * @param array $data Array of file relative path, width, and height on success. May also include
  690. * file absolute path and URL.
  691. * @param int $post_id The post_id of the image attachment
  692. * @param string|array $size Registered image size or flat array of initially-requested height and width
  693. * dimensions (in that order).
  694. */
  695. return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );
  696. }
  697. /**
  698. * Gets the available intermediate image sizes.
  699. *
  700. * @since 3.0.0
  701. *
  702. * @return array Returns a filtered array of image size strings.
  703. */
  704. function get_intermediate_image_sizes() {
  705. $_wp_additional_image_sizes = wp_get_additional_image_sizes();
  706. $image_sizes = array('thumbnail', 'medium', 'medium_large', 'large'); // Standard sizes
  707. if ( ! empty( $_wp_additional_image_sizes ) ) {
  708. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  709. }
  710. /**
  711. * Filters the list of intermediate image sizes.
  712. *
  713. * @since 2.5.0
  714. *
  715. * @param array $image_sizes An array of intermediate image sizes. Defaults
  716. * are 'thumbnail', 'medium', 'medium_large', 'large'.
  717. */
  718. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  719. }
  720. /**
  721. * Retrieve an image to represent an attachment.
  722. *
  723. * A mime icon for files, thumbnail or intermediate size for images.
  724. *
  725. * The returned array contains four values: the URL of the attachment image src,
  726. * the width of the image file, the height of the image file, and a boolean
  727. * representing whether the returned array describes an intermediate (generated)
  728. * image size or the original, full-sized upload.
  729. *
  730. * @since 2.5.0
  731. *
  732. * @param int $attachment_id Image attachment ID.
  733. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  734. * and height values in pixels (in that order). Default 'thumbnail'.
  735. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  736. * @return false|array Returns an array (url, width, height, is_intermediate), or false, if no image is available.
  737. */
  738. function wp_get_attachment_image_src( $attachment_id, $size = 'thumbnail', $icon = false ) {
  739. // get a thumbnail or intermediate image if there is one
  740. $image = image_downsize( $attachment_id, $size );
  741. if ( ! $image ) {
  742. $src = false;
  743. if ( $icon && $src = wp_mime_type_icon( $attachment_id ) ) {
  744. /** This filter is documented in wp-includes/post.php */
  745. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  746. $src_file = $icon_dir . '/' . wp_basename( $src );
  747. @list( $width, $height ) = getimagesize( $src_file );
  748. }
  749. if ( $src && $width && $height ) {
  750. $image = array( $src, $width, $height );
  751. }
  752. }
  753. /**
  754. * Filters the image src result.
  755. *
  756. * @since 4.3.0
  757. *
  758. * @param array|false $image Either array with src, width & height, icon src, or false.
  759. * @param int $attachment_id Image attachment ID.
  760. * @param string|array $size Size of image. Image size or array of width and height values
  761. * (in that order). Default 'thumbnail'.
  762. * @param bool $icon Whether the image should be treated as an icon. Default false.
  763. */
  764. return apply_filters( 'wp_get_attachment_image_src', $image, $attachment_id, $size, $icon );
  765. }
  766. /**
  767. * Get an HTML img element representing an image attachment
  768. *
  769. * While `$size` will accept an array, it is better to register a size with
  770. * add_image_size() so that a cropped version is generated. It's much more
  771. * efficient than having to find the closest-sized image and then having the
  772. * browser scale down the image.
  773. *
  774. * @since 2.5.0
  775. *
  776. * @param int $attachment_id Image attachment ID.
  777. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width
  778. * and height values in pixels (in that order). Default 'thumbnail'.
  779. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  780. * @param string|array $attr Optional. Attributes for the image markup. Default empty.
  781. * @return string HTML img element or empty string on failure.
  782. */
  783. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  784. $html = '';
  785. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  786. if ( $image ) {
  787. list($src, $width, $height) = $image;
  788. $hwstring = image_hwstring($width, $height);
  789. $size_class = $size;
  790. if ( is_array( $size_class ) ) {
  791. $size_class = join( 'x', $size_class );
  792. }
  793. $attachment = get_post($attachment_id);
  794. $default_attr = array(
  795. 'src' => $src,
  796. 'class' => "attachment-$size_class size-$size_class",
  797. 'alt' => trim( strip_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) ),
  798. );
  799. $attr = wp_parse_args( $attr, $default_attr );
  800. // Generate 'srcset' and 'sizes' if not already present.
  801. if ( empty( $attr['srcset'] ) ) {
  802. $image_meta = wp_get_attachment_metadata( $attachment_id );
  803. if ( is_array( $image_meta ) ) {
  804. $size_array = array( absint( $width ), absint( $height ) );
  805. $srcset = wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id );
  806. $sizes = wp_calculate_image_sizes( $size_array, $src, $image_meta, $attachment_id );
  807. if ( $srcset && ( $sizes || ! empty( $attr['sizes'] ) ) ) {
  808. $attr['srcset'] = $srcset;
  809. if ( empty( $attr['sizes'] ) ) {
  810. $attr['sizes'] = $sizes;
  811. }
  812. }
  813. }
  814. }
  815. /**
  816. * Filters the list of attachment image attributes.
  817. *
  818. * @since 2.8.0
  819. *
  820. * @param array $attr Attributes for the image markup.
  821. * @param WP_Post $attachment Image attachment post.
  822. * @param string|array $size Requested size. Image size or array of width and height values
  823. * (in that order). Default 'thumbnail'.
  824. */
  825. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment, $size );
  826. $attr = array_map( 'esc_attr', $attr );
  827. $html = rtrim("<img $hwstring");
  828. foreach ( $attr as $name => $value ) {
  829. $html .= " $name=" . '"' . $value . '"';
  830. }
  831. $html .= ' />';
  832. }
  833. return $html;
  834. }
  835. /**
  836. * Get the URL of an image attachment.
  837. *
  838. * @since 4.4.0
  839. *
  840. * @param int $attachment_id Image attachment ID.
  841. * @param string|array $size Optional. Image size to retrieve. Accepts any valid image size, or an array
  842. * of width and height values in pixels (in that order). Default 'thumbnail'.
  843. * @param bool $icon Optional. Whether the image should be treated as an icon. Default false.
  844. * @return string|false Attachment URL or false if no image is available.
  845. */
  846. function wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false ) {
  847. $image = wp_get_attachment_image_src( $attachment_id, $size, $icon );
  848. return isset( $image['0'] ) ? $image['0'] : false;
  849. }
  850. /**
  851. * Get the attachment path relative to the upload directory.
  852. *
  853. * @since 4.4.1
  854. * @access private
  855. *
  856. * @param string $file Attachment file name.
  857. * @return string Attachment path relative to the upload directory.
  858. */
  859. function _wp_get_attachment_relative_path( $file ) {
  860. $dirname = dirname( $file );
  861. if ( '.' === $dirname ) {
  862. return '';
  863. }
  864. if ( false !== strpos( $dirname, 'wp-content/uploads' ) ) {
  865. // Get the directory name relative to the upload directory (back compat for pre-2.7 uploads)
  866. $dirname = substr( $dirname, strpos( $dirname, 'wp-content/uploads' ) + 18 );
  867. $dirname = ltrim( $dirname, '/' );
  868. }
  869. return $dirname;
  870. }
  871. /**
  872. * Get the image size as array from its meta data.
  873. *
  874. * Used for responsive images.
  875. *
  876. * @since 4.4.0
  877. * @access private
  878. *
  879. * @param string $size_name Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
  880. * @param array $image_meta The image meta data.
  881. * @return array|bool Array of width and height values in pixels (in that order)
  882. * or false if the size doesn't exist.
  883. */
  884. function _wp_get_image_size_from_meta( $size_name, $image_meta ) {
  885. if ( $size_name === 'full' ) {
  886. return array(
  887. absint( $image_meta['width'] ),
  888. absint( $image_meta['height'] ),
  889. );
  890. } elseif ( ! empty( $image_meta['sizes'][$size_name] ) ) {
  891. return array(
  892. absint( $image_meta['sizes'][$size_name]['width'] ),
  893. absint( $image_meta['sizes'][$size_name]['height'] ),
  894. );
  895. }
  896. return false;
  897. }
  898. /**
  899. * Retrieves the value for an image attachment's 'srcset' attribute.
  900. *
  901. * @since 4.4.0
  902. *
  903. * @see wp_calculate_image_srcset()
  904. *
  905. * @param int $attachment_id Image attachment ID.
  906. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of
  907. * width and height values in pixels (in that order). Default 'medium'.
  908. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  909. * Default null.
  910. * @return string|bool A 'srcset' value string or false.
  911. */
  912. function wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null ) {
  913. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  914. return false;
  915. }
  916. if ( ! is_array( $image_meta ) ) {
  917. $image_meta = wp_get_attachment_metadata( $attachment_id );
  918. }
  919. $image_src = $image[0];
  920. $size_array = array(
  921. absint( $image[1] ),
  922. absint( $image[2] )
  923. );
  924. return wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  925. }
  926. /**
  927. * A helper function to calculate the image sources to include in a 'srcset' attribute.
  928. *
  929. * @since 4.4.0
  930. *
  931. * @param array $size_array Array of width and height values in pixels (in that order).
  932. * @param string $image_src The 'src' of the image.
  933. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  934. * @param int $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
  935. * @return string|bool The 'srcset' attribute value. False on error or when only one source exists.
  936. */
  937. function wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 ) {
  938. /**
  939. * Let plugins pre-filter the image meta to be able to fix inconsistencies in the stored data.
  940. *
  941. * @since 4.5.0
  942. *
  943. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  944. * @param array $size_array Array of width and height values in pixels (in that order).
  945. * @param string $image_src The 'src' of the image.
  946. * @param int $attachment_id The image attachment ID or 0 if not supplied.
  947. */
  948. $image_meta = apply_filters( 'wp_calculate_image_srcset_meta', $image_meta, $size_array, $image_src, $attachment_id );
  949. if ( empty( $image_meta['sizes'] ) || ! isset( $image_meta['file'] ) || strlen( $image_meta['file'] ) < 4 ) {
  950. return false;
  951. }
  952. $image_sizes = $image_meta['sizes'];
  953. // Get the width and height of the image.
  954. $image_width = (int) $size_array[0];
  955. $image_height = (int) $size_array[1];
  956. // Bail early if error/no width.
  957. if ( $image_width < 1 ) {
  958. return false;
  959. }
  960. $image_basename = wp_basename( $image_meta['file'] );
  961. /*
  962. * WordPress flattens animated GIFs into one frame when generating intermediate sizes.
  963. * To avoid hiding animation in user content, if src is a full size GIF, a srcset attribute is not generated.
  964. * If src is an intermediate size GIF, the full size is excluded from srcset to keep a flattened GIF from becoming animated.
  965. */
  966. if ( ! isset( $image_sizes['thumbnail']['mime-type'] ) || 'image/gif' !== $image_sizes['thumbnail']['mime-type'] ) {
  967. $image_sizes[] = array(
  968. 'width' => $image_meta['width'],
  969. 'height' => $image_meta['height'],
  970. 'file' => $image_basename,
  971. );
  972. } elseif ( strpos( $image_src, $image_meta['file'] ) ) {
  973. return false;
  974. }
  975. // Retrieve the uploads sub-directory from the full size image.
  976. $dirname = _wp_get_attachment_relative_path( $image_meta['file'] );
  977. if ( $dirname ) {
  978. $dirname = trailingslashit( $dirname );
  979. }
  980. $upload_dir = wp_get_upload_dir();
  981. $image_baseurl = trailingslashit( $upload_dir['baseurl'] ) . $dirname;
  982. /*
  983. * If currently on HTTPS, prefer HTTPS URLs when we know they're supported by the domain
  984. * (which is to say, when they share the domain name of the current request).
  985. */
  986. if ( is_ssl() && 'https' !== substr( $image_baseurl, 0, 5 ) && parse_url( $image_baseurl, PHP_URL_HOST ) === $_SERVER['HTTP_HOST'] ) {
  987. $image_baseurl = set_url_scheme( $image_baseurl, 'https' );
  988. }
  989. /*
  990. * Images that have been edited in WordPress after being uploaded will
  991. * contain a unique hash. Look for that hash and use it later to filter
  992. * out images that are leftovers from previous versions.
  993. */
  994. $image_edited = preg_match( '/-e[0-9]{13}/', wp_basename( $image_src ), $image_edit_hash );
  995. /**
  996. * Filters the maximum image width to be included in a 'srcset' attribute.
  997. *
  998. * @since 4.4.0
  999. *
  1000. * @param int $max_width The maximum image width to be included in the 'srcset'. Default '1600'.
  1001. * @param array $size_array Array of width and height values in pixels (in that order).
  1002. */
  1003. $max_srcset_image_width = apply_filters( 'max_srcset_image_width', 1600, $size_array );
  1004. // Array to hold URL candidates.
  1005. $sources = array();
  1006. /**
  1007. * To make sure the ID matches our image src, we will check to see if any sizes in our attachment
  1008. * meta match our $image_src. If no matches are found we don't return a srcset to avoid serving
  1009. * an incorrect image. See #35045.
  1010. */
  1011. $src_matched = false;
  1012. /*
  1013. * Loop through available images. Only use images that are resized
  1014. * versions of the same edit.
  1015. */
  1016. foreach ( $image_sizes as $image ) {
  1017. $is_src = false;
  1018. // Check if image meta isn't corrupted.
  1019. if ( ! is_array( $image ) ) {
  1020. continue;
  1021. }
  1022. // If the file name is part of the `src`, we've confirmed a match.
  1023. if ( ! $src_matched && false !== strpos( $image_src, $dirname . $image['file'] ) ) {
  1024. $src_matched = $is_src = true;
  1025. }
  1026. // Filter out images that are from previous edits.
  1027. if ( $image_edited && ! strpos( $image['file'], $image_edit_hash[0] ) ) {
  1028. continue;
  1029. }
  1030. /*
  1031. * Filters out images that are wider than '$max_srcset_image_width' unless
  1032. * that file is in the 'src' attribute.
  1033. */
  1034. if ( $max_srcset_image_width && $image['width'] > $max_srcset_image_width && ! $is_src ) {
  1035. continue;
  1036. }
  1037. // If the image dimensions are within 1px of the expected size, use it.
  1038. if ( wp_image_matches_ratio( $image_width, $image_height, $image['width'], $image['height'] ) ) {
  1039. // Add the URL, descriptor, and value to the sources array to be returned.
  1040. $source = array(
  1041. 'url' => $image_baseurl . $image['file'],
  1042. 'descriptor' => 'w',
  1043. 'value' => $image['width'],
  1044. );
  1045. // The 'src' image has to be the first in the 'srcset', because of a bug in iOS8. See #35030.
  1046. if ( $is_src ) {
  1047. $sources = array( $image['width'] => $source ) + $sources;
  1048. } else {
  1049. $sources[ $image['width'] ] = $source;
  1050. }
  1051. }
  1052. }
  1053. /**
  1054. * Filters an image's 'srcset' sources.
  1055. *
  1056. * @since 4.4.0
  1057. *
  1058. * @param array $sources {
  1059. * One or more arrays of source data to include in the 'srcset'.
  1060. *
  1061. * @type array $width {
  1062. * @type string $url The URL of an image source.
  1063. * @type string $descriptor The descriptor type used in the image candidate string,
  1064. * either 'w' or 'x'.
  1065. * @type int $value The source width if paired with a 'w' descriptor, or a
  1066. * pixel density value if paired with an 'x' descriptor.
  1067. * }
  1068. * }
  1069. * @param array $size_array Array of width and height values in pixels (in that order).
  1070. * @param string $image_src The 'src' of the image.
  1071. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1072. * @param int $attachment_id Image attachment ID or 0.
  1073. */
  1074. $sources = apply_filters( 'wp_calculate_image_srcset', $sources, $size_array, $image_src, $image_meta, $attachment_id );
  1075. // Only return a 'srcset' value if there is more than one source.
  1076. if ( ! $src_matched || count( $sources ) < 2 ) {
  1077. return false;
  1078. }
  1079. $srcset = '';
  1080. foreach ( $sources as $source ) {
  1081. $srcset .= str_replace( ' ', '%20', $source['url'] ) . ' ' . $source['value'] . $source['descriptor'] . ', ';
  1082. }
  1083. return rtrim( $srcset, ', ' );
  1084. }
  1085. /**
  1086. * Retrieves the value for an image attachment's 'sizes' attribute.
  1087. *
  1088. * @since 4.4.0
  1089. *
  1090. * @see wp_calculate_image_sizes()
  1091. *
  1092. * @param int $attachment_id Image attachment ID.
  1093. * @param array|string $size Optional. Image size. Accepts any valid image size, or an array of width
  1094. * and height values in pixels (in that order). Default 'medium'.
  1095. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1096. * Default null.
  1097. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1098. */
  1099. function wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null ) {
  1100. if ( ! $image = wp_get_attachment_image_src( $attachment_id, $size ) ) {
  1101. return false;
  1102. }
  1103. if ( ! is_array( $image_meta ) ) {
  1104. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1105. }
  1106. $image_src = $image[0];
  1107. $size_array = array(
  1108. absint( $image[1] ),
  1109. absint( $image[2] )
  1110. );
  1111. return wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1112. }
  1113. /**
  1114. * Creates a 'sizes' attribute value for an image.
  1115. *
  1116. * @since 4.4.0
  1117. *
  1118. * @param array|string $size Image size to retrieve. Accepts any valid image size, or an array
  1119. * of width and height values in pixels (in that order). Default 'medium'.
  1120. * @param string $image_src Optional. The URL to the image file. Default null.
  1121. * @param array $image_meta Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
  1122. * Default null.
  1123. * @param int $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
  1124. * is needed when using the image size name as argument for `$size`. Default 0.
  1125. * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
  1126. */
  1127. function wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 ) {
  1128. $width = 0;
  1129. if ( is_array( $size ) ) {
  1130. $width = absint( $size[0] );
  1131. } elseif ( is_string( $size ) ) {
  1132. if ( ! $image_meta && $attachment_id ) {
  1133. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1134. }
  1135. if ( is_array( $image_meta ) ) {
  1136. $size_array = _wp_get_image_size_from_meta( $size, $image_meta );
  1137. if ( $size_array ) {
  1138. $width = absint( $size_array[0] );
  1139. }
  1140. }
  1141. }
  1142. if ( ! $width ) {
  1143. return false;
  1144. }
  1145. // Setup the default 'sizes' attribute.
  1146. $sizes = sprintf( '(max-width: %1$dpx) 100vw, %1$dpx', $width );
  1147. /**
  1148. * Filters the output of 'wp_calculate_image_sizes()'.
  1149. *
  1150. * @since 4.4.0
  1151. *
  1152. * @param string $sizes A source size value for use in a 'sizes' attribute.
  1153. * @param array|string $size Requested size. Image size or array of width and height values
  1154. * in pixels (in that order).
  1155. * @param string|null $image_src The URL to the image file or null.
  1156. * @param array|null $image_meta The image meta data as returned by wp_get_attachment_metadata() or null.
  1157. * @param int $attachment_id Image attachment ID of the original image or 0.
  1158. */
  1159. return apply_filters( 'wp_calculate_image_sizes', $sizes, $size, $image_src, $image_meta, $attachment_id );
  1160. }
  1161. /**
  1162. * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
  1163. *
  1164. * @since 4.4.0
  1165. *
  1166. * @see wp_image_add_srcset_and_sizes()
  1167. *
  1168. * @param string $content The raw post content to be filtered.
  1169. * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
  1170. */
  1171. function wp_make_content_images_responsive( $content ) {
  1172. if ( ! preg_match_all( '/<img [^>]+>/', $content, $matches ) ) {
  1173. return $content;
  1174. }
  1175. $selected_images = $attachment_ids = array();
  1176. foreach( $matches[0] as $image ) {
  1177. if ( false === strpos( $image, ' srcset=' ) && preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) &&
  1178. ( $attachment_id = absint( $class_id[1] ) ) ) {
  1179. /*
  1180. * If exactly the same image tag is used more than once, overwrite it.
  1181. * All identical tags will be replaced later with 'str_replace()'.
  1182. */
  1183. $selected_images[ $image ] = $attachment_id;
  1184. // Overwrite the ID when the same image is included more than once.
  1185. $attachment_ids[ $attachment_id ] = true;
  1186. }
  1187. }
  1188. if ( count( $attachment_ids ) > 1 ) {
  1189. /*
  1190. * Warm the object cache with post and meta information for all found
  1191. * images to avoid making individual database calls.
  1192. */
  1193. _prime_post_caches( array_keys( $attachment_ids ), false, true );
  1194. }
  1195. foreach ( $selected_images as $image => $attachment_id ) {
  1196. $image_meta = wp_get_attachment_metadata( $attachment_id );
  1197. $content = str_replace( $image, wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ), $content );
  1198. }
  1199. return $content;
  1200. }
  1201. /**
  1202. * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
  1203. *
  1204. * @since 4.4.0
  1205. *
  1206. * @see wp_calculate_image_srcset()
  1207. * @see wp_calculate_image_sizes()
  1208. *
  1209. * @param string $image An HTML 'img' element to be filtered.
  1210. * @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
  1211. * @param int $attachment_id Image attachment ID.
  1212. * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
  1213. */
  1214. function wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id ) {
  1215. // Ensure the image meta exists.
  1216. if ( empty( $image_meta['sizes'] ) ) {
  1217. return $image;
  1218. }
  1219. $image_src = preg_match( '/src="([^"]+)"/', $image, $match_src ) ? $match_src[1] : '';
  1220. list( $image_src ) = explode( '?', $image_src );
  1221. // Return early if we couldn't get the image source.
  1222. if ( ! $image_src ) {
  1223. return $image;
  1224. }
  1225. // Bail early if an image has been inserted and later edited.
  1226. if ( preg_match( '/-e[0-9]{13}/', $image_meta['file'], $img_edit_hash ) &&
  1227. strpos( wp_basename( $image_src ), $img_edit_hash[0] ) === false ) {
  1228. return $image;
  1229. }
  1230. $width = preg_match( '/ width="([0-9]+)"/', $image, $match_width ) ? (int) $match_width[1] : 0;
  1231. $height = preg_match( '/ height="([0-9]+)"/', $image, $match_height ) ? (int) $match_height[1] : 0;
  1232. if ( ! $width || ! $height ) {
  1233. /*
  1234. * If attempts to parse the size value failed, attempt to use the image meta data to match
  1235. * the image file name from 'src' against the available sizes for an attachment.
  1236. */
  1237. $image_filename = wp_basename( $image_src );
  1238. if ( $image_filename === wp_basename( $image_meta['file'] ) ) {
  1239. $width = (int) $image_meta['width'];
  1240. $height = (int) $image_meta['height'];
  1241. } else {
  1242. foreach( $image_meta['sizes'] as $image_size_data ) {
  1243. if ( $image_filename === $image_size_data['file'] ) {
  1244. $width = (int) $image_size_data['width'];
  1245. $height = (int) $image_size_data['height'];
  1246. break;
  1247. }
  1248. }
  1249. }
  1250. }
  1251. if ( ! $width || ! $height ) {
  1252. return $image;
  1253. }
  1254. $size_array = array( $width, $height );
  1255. $srcset = wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id );
  1256. if ( $srcset ) {
  1257. // Check if there is already a 'sizes' attribute.
  1258. $sizes = strpos( $image, ' sizes=' );
  1259. if ( ! $sizes ) {
  1260. $sizes = wp_calculate_image_sizes( $size_array, $image_src, $image_meta, $attachment_id );
  1261. }
  1262. }
  1263. if ( $srcset && $sizes ) {
  1264. // Format the 'srcset' and 'sizes' string and escape attributes.
  1265. $attr = sprintf( ' srcset="%s"', esc_attr( $srcset ) );
  1266. if ( is_string( $sizes ) ) {
  1267. $attr .= sprintf( ' sizes="%s"', esc_attr( $sizes ) );
  1268. }
  1269. // Add 'srcset' and 'sizes' attributes to the image markup.
  1270. $image = preg_replace( '/<img ([^>]+?)[\/ ]*>/', '<img $1' . $attr . ' />', $image );
  1271. }
  1272. return $image;
  1273. }
  1274. /**
  1275. * Adds a 'wp-post-image' class to post thumbnails. Internal use only.
  1276. *
  1277. * Uses the {@see 'begin_fetch_post_thumbnail_html'} and {@see 'end_fetch_post_thumbnail_html'}
  1278. * action hooks to dynamically add/remove itself so as to only filter post thumbnails.
  1279. *
  1280. * @ignore
  1281. * @since 2.9.0
  1282. *
  1283. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1284. * @return array Modified array of attributes including the new 'wp-post-image' class.
  1285. */
  1286. function _wp_post_thumbnail_class_filter( $attr ) {
  1287. $attr['class'] .= ' wp-post-image';
  1288. return $attr;
  1289. }
  1290. /**
  1291. * Adds '_wp_post_thumbnail_class_filter' callback to the 'wp_get_attachment_image_attributes'
  1292. * filter hook. Internal use only.
  1293. *
  1294. * @ignore
  1295. * @since 2.9.0
  1296. *
  1297. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1298. */
  1299. function _wp_post_thumbnail_class_filter_add( $attr ) {
  1300. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1301. }
  1302. /**
  1303. * Removes the '_wp_post_thumbnail_class_filter' callback from the 'wp_get_attachment_image_attributes'
  1304. * filter hook. Internal use only.
  1305. *
  1306. * @ignore
  1307. * @since 2.9.0
  1308. *
  1309. * @param array $attr Thumbnail attributes including src, class, alt, title.
  1310. */
  1311. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  1312. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  1313. }
  1314. add_shortcode('wp_caption', 'img_caption_shortcode');
  1315. add_shortcode('caption', 'img_caption_shortcode');
  1316. /**
  1317. * Builds the Caption shortcode output.
  1318. *
  1319. * Allows a plugin to replace the content that would otherwise be returned. The
  1320. * filter is {@see 'img_caption_shortcode'} and passes an empty string, the attr
  1321. * parameter and the content parameter values.
  1322. *
  1323. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  1324. * 'caption'.
  1325. *
  1326. * @since 2.6.0
  1327. *
  1328. * @param array $attr {
  1329. * Attributes of the caption shortcode.
  1330. *
  1331. * @type string $id ID of the div element for the caption.
  1332. * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
  1333. * 'aligncenter', alignright', 'alignnone'.
  1334. * @type int $width The width of the caption, in pixels.
  1335. * @type string $caption The caption text.
  1336. * @type string $class Additional class name(s) added to the caption container.
  1337. * }
  1338. * @param string $content Shortcode content.
  1339. * @return string HTML content to display the caption.
  1340. */
  1341. function img_caption_shortcode( $attr, $content = null ) {
  1342. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  1343. if ( ! isset( $attr['caption'] ) ) {
  1344. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  1345. $content = $matches[1];
  1346. $attr['caption'] = trim( $matches[2] );
  1347. }
  1348. } elseif ( strpos( $attr['caption'], '<' ) !== false ) {
  1349. $attr['caption'] = wp_kses( $attr['caption'], 'post' );
  1350. }
  1351. /**
  1352. * Filters the default caption shortcode output.
  1353. *
  1354. * If the filtered output isn't empty, it will be used instead of generating
  1355. * the default caption template.
  1356. *
  1357. * @since 2.6.0
  1358. *
  1359. * @see img_caption_shortcode()
  1360. *
  1361. * @param string $output The caption output. Default empty.
  1362. * @param array $attr Attributes of the caption shortcode.
  1363. * @param string $content The image element, possibly wrapped in a hyperlink.
  1364. */
  1365. $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
  1366. if ( $output != '' )
  1367. return $output;
  1368. $atts = shortcode_atts( array(
  1369. 'id' => '',
  1370. 'align' => 'alignnone',
  1371. 'width' => '',
  1372. 'caption' => '',
  1373. 'class' => '',
  1374. ), $attr, 'caption' );
  1375. $atts['width'] = (int) $atts['width'];
  1376. if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
  1377. return $content;
  1378. if ( ! empty( $atts['id'] ) )
  1379. $atts['id'] = 'id="' . esc_attr( sanitize_html_class( $atts['id'] ) ) . '" ';
  1380. $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
  1381. $html5 = current_theme_supports( 'html5', 'caption' );
  1382. // HTML5 captions never added the extra 10px to the image width
  1383. $width = $html5 ? $atts['width'] : ( 10 + $atts['width'] );
  1384. /**
  1385. * Filters the width of an image's caption.
  1386. *
  1387. * By default, the caption is 10 pixels greater than the width of the image,
  1388. * to prevent post content from running up against a floated image.
  1389. *
  1390. * @since 3.7.0
  1391. *
  1392. * @see img_caption_shortcode()
  1393. *
  1394. * @param int $width Width of the caption in pixels. To remove this inline style,
  1395. * return zero.
  1396. * @param array $atts Attributes of the caption shortcode.
  1397. * @param string $content The image element, possibly wrapped in a hyperlink.
  1398. */
  1399. $caption_width = apply_filters( 'img_caption_shortcode_width', $width, $atts, $content );
  1400. $style = '';
  1401. if ( $caption_width ) {
  1402. $style = 'style="max-width: ' . (int) $caption_width . 'px" ';
  1403. }
  1404. if ( $html5 ) {
  1405. $html = '<figure ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
  1406. . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
  1407. } else {
  1408. $html = '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
  1409. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
  1410. }
  1411. return $html;
  1412. }
  1413. add_shortcode('gallery', 'gallery_shortcode');
  1414. /**
  1415. * Builds the Gallery shortcode output.
  1416. *
  1417. * This implements the functionality of the Gallery Shortcode for displaying
  1418. * WordPress images on a post.
  1419. *
  1420. * @since 2.5.0
  1421. *
  1422. * @staticvar int $instance
  1423. *
  1424. * @param array $attr {
  1425. * Attributes of the gallery shortcode.
  1426. *
  1427. * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
  1428. * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
  1429. * Accepts any valid SQL ORDERBY statement.
  1430. * @type int $id Post ID.
  1431. * @type string $itemtag HTML tag to use for each image in the gallery.
  1432. * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
  1433. * @type string $icontag HTML tag to use for each image's icon.
  1434. * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
  1435. * @type string $captiontag HTML tag to use for each image's caption.
  1436. * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
  1437. * @type int $columns Number of columns of images to display. Default 3.
  1438. * @type string|array $size Size of the images to display. Accepts any valid image size, or an array of width
  1439. * and height values in pixels (in that order). Default 'thumbnail'.
  1440. * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
  1441. * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
  1442. * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
  1443. * @type string $link What to link each image to. Default empty (links to the attachment page).
  1444. * Accepts 'file', 'none'.
  1445. * }
  1446. * @return string HTML content to display gallery.
  1447. */
  1448. function gallery_shortcode( $attr ) {
  1449. $post = get_post();
  1450. static $instance = 0;
  1451. $instance++;
  1452. if ( ! empty( $attr['ids'] ) ) {
  1453. // 'ids' is explicitly ordered, unless you specify otherwise.
  1454. if ( empty( $attr['orderby'] ) ) {
  1455. $attr['orderby'] = 'post__in';
  1456. }
  1457. $attr['include'] = $attr['ids'];
  1458. }
  1459. /**
  1460. * Filters the default gallery shortcode output.
  1461. *
  1462. * If the filtered output isn't empty, it will be used instead of generating
  1463. * the default gallery template.
  1464. *
  1465. * @since 2.5.0
  1466. * @since 4.2.0 The `$instance` parameter was added.
  1467. *
  1468. * @see gallery_shortcode()
  1469. *
  1470. * @param string $output The gallery output. Default empty.
  1471. * @param array $attr Attributes of the gallery shortcode.
  1472. * @param int $instance Unique numeric ID of this gallery shortcode instance.
  1473. */
  1474. $output = apply_filters( 'post_gallery', '', $attr, $instance );
  1475. if ( $output != '' ) {
  1476. return $output;
  1477. }
  1478. $html5 = current_theme_supports( 'html5', 'gallery' );
  1479. $atts = shortcode_atts( array(
  1480. 'order' => 'ASC',
  1481. 'orderby' => 'menu_order ID',
  1482. 'id' => $post ? $post->ID : 0,
  1483. 'itemtag' => $html5 ? 'figure' : 'dl',
  1484. 'icontag' => $html5 ? 'div' : 'dt',
  1485. 'captiontag' => $html5 ? 'figcaption' : 'dd',
  1486. 'columns' => 3,
  1487. 'size' => 'thumbnail',
  1488. 'include' => '',
  1489. 'exclude' => '',
  1490. 'link' => ''
  1491. ), $attr, 'gallery' );
  1492. $id = intval( $atts['id'] );
  1493. if ( ! empty( $atts['include'] ) ) {
  1494. $_attachments = get_posts( array( 'include' => $atts['include'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1495. $attachments = array();
  1496. foreach ( $_attachments as $key => $val ) {
  1497. $attachments[$val->ID] = $_attachments[$key];
  1498. }
  1499. } elseif ( ! empty( $atts['exclude'] ) ) {
  1500. $attachments = get_children( array( 'post_parent' => $id, 'exclude' => $atts['exclude'], 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1501. } else {
  1502. $attachments = get_children( array( 'post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $atts['order'], 'orderby' => $atts['orderby'] ) );
  1503. }
  1504. if ( empty( $attachments ) ) {
  1505. return '';
  1506. }
  1507. if ( is_feed() ) {
  1508. $output = "\n";
  1509. foreach ( $attachments as $att_id => $attachment ) {
  1510. $output .= wp_get_attachment_link( $att_id, $atts['size'], true ) . "\n";
  1511. }
  1512. return $output;
  1513. }
  1514. $itemtag = tag_escape( $atts['itemtag'] );
  1515. $captiontag = tag_escape( $atts['captiontag'] );
  1516. $icontag = tag_escape( $atts['icontag'] );
  1517. $valid_tags = wp_kses_allowed_html( 'post' );
  1518. if ( ! isset( $valid_tags[ $itemtag ] ) ) {
  1519. $itemtag = 'dl';
  1520. }
  1521. if ( ! isset( $valid_tags[ $captiontag ] ) ) {
  1522. $captiontag = 'dd';
  1523. }
  1524. if ( ! isset( $valid_tags[ $icontag ] ) ) {
  1525. $icontag = 'dt';
  1526. }
  1527. $columns = intval( $atts['columns'] );
  1528. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  1529. $float = is_rtl() ? 'right' : 'left';
  1530. $selector = "gallery-{$instance}";
  1531. $gallery_style = '';
  1532. /**
  1533. * Filters whether to print default gallery styles.
  1534. *
  1535. * @since 3.1.0
  1536. *
  1537. * @param bool $print Whether to print default gallery styles.
  1538. * Defaults to false if the theme supports HTML5 galleries.
  1539. * Otherwise, defaults to true.
  1540. */
  1541. if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
  1542. $gallery_style = "
  1543. <style type='text/css'>
  1544. #{$selector} {
  1545. margin: auto;
  1546. }
  1547. #{$selector} .gallery-item {
  1548. float: {$float};
  1549. margin-top: 10px;
  1550. text-align: center;
  1551. width: {$itemwidth}%;
  1552. }
  1553. #{$selector} img {
  1554. border: 2px solid #cfcfcf;
  1555. }
  1556. #{$selector} .gallery-caption {
  1557. margin-left: 0;
  1558. }
  1559. /* see gallery_shortcode() in wp-includes/media.php */
  1560. </style>\n\t\t";
  1561. }
  1562. $size_class = sanitize_html_class( $atts['size'] );
  1563. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  1564. /**
  1565. * Filters the default gallery shortcode CSS styles.
  1566. *
  1567. * @since 2.5.0
  1568. *
  1569. * @param string $gallery_style Default CSS styles and opening HTML div container
  1570. * for the gallery shortcode output.
  1571. */
  1572. $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
  1573. $i = 0;
  1574. foreach ( $attachments as $id => $attachment ) {
  1575. $attr = ( trim( $attachment->post_excerpt ) ) ? array( 'aria-describedby' => "$selector-$id" ) : '';
  1576. if ( ! empty( $atts['link'] ) && 'file' === $atts['link'] ) {
  1577. $image_output = wp_get_attachment_link( $id, $atts['size'], false, false, false, $attr );
  1578. } elseif ( ! empty( $atts['link'] ) && 'none' === $atts['link'] ) {
  1579. $image_output = wp_get_attachment_image( $id, $atts['size'], false, $attr );
  1580. } else {
  1581. $image_output = wp_get_attachment_link( $id, $atts['size'], true, false, false, $attr );
  1582. }
  1583. $image_meta = wp_get_attachment_metadata( $id );
  1584. $orientation = '';
  1585. if ( isset( $image_meta['height'], $image_meta['width'] ) ) {
  1586. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  1587. }
  1588. $output .= "<{$itemtag} class='gallery-item'>";
  1589. $output .= "
  1590. <{$icontag} class='gallery-icon {$orientation}'>
  1591. $image_output
  1592. </{$icontag}>";
  1593. if ( $captiontag && trim($attachment->post_excerpt) ) {
  1594. $output .= "
  1595. <{$captiontag} class='wp-caption-text gallery-caption' id='$selector-$id'>
  1596. " . wptexturize($attachment->post_excerpt) . "
  1597. </{$captiontag}>";
  1598. }
  1599. $output .= "</{$itemtag}>";
  1600. if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
  1601. $output .= '<br style="clear: both" />';
  1602. }
  1603. }
  1604. if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
  1605. $output .= "
  1606. <br style='clear: both' />";
  1607. }
  1608. $output .= "
  1609. </div>\n";
  1610. return $output;
  1611. }
  1612. /**
  1613. * Outputs the templates used by playlists.
  1614. *
  1615. * @since 3.9.0
  1616. */
  1617. function wp_underscore_playlist_templates() {
  1618. ?>
  1619. <script type="text/html" id="tmpl-wp-playlist-current-item">
  1620. <# if ( data.image ) { #>
  1621. <img src="{{ data.thumb.src }}" alt="" />
  1622. <# } #>
  1623. <div class="wp-playlist-caption">
  1624. <span class="wp-playlist-item-meta wp-playlist-item-title"><?php
  1625. /* translators: playlist item title */
  1626. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{ data.title }}' );
  1627. ?></span>
  1628. <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
  1629. <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
  1630. </div>
  1631. </script>
  1632. <script type="text/html" id="tmpl-wp-playlist-item">
  1633. <div class="wp-playlist-item">
  1634. <a class="wp-playlist-caption" href="{{ data.src }}">
  1635. {{ data.index ? ( data.index + '. ' ) : '' }}
  1636. <# if ( data.caption ) { #>
  1637. {{ data.caption }}
  1638. <# } else { #>
  1639. <span class="wp-playlist-item-title"><?php
  1640. /* translators: playlist item title */
  1641. printf( _x( '&#8220;%s&#8221;', 'playlist item title' ), '{{{ data.title }}}' );
  1642. ?></span>
  1643. <# if ( data.artists && data.meta.artist ) { #>
  1644. <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
  1645. <# } #>
  1646. <# } #>
  1647. </a>
  1648. <# if ( data.meta.length_formatted ) { #>
  1649. <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
  1650. <# } #>
  1651. </div>
  1652. </script>
  1653. <?php
  1654. }
  1655. /**
  1656. * Outputs and enqueue default scripts and styles for playlists.
  1657. *
  1658. * @since 3.9.0
  1659. *
  1660. * @param string $type Type of playlist. Accepts 'audio' or 'video'.
  1661. */
  1662. function wp_playlist_scripts( $type ) {
  1663. wp_enqueue_style( 'wp-mediaelement' );
  1664. wp_enqueue_script( 'wp-playlist' );
  1665. ?>
  1666. <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
  1667. <?php
  1668. add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
  1669. add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
  1670. }
  1671. /**
  1672. * Builds the Playlist shortcode output.
  1673. *
  1674. * This implements the functionality of the playlist shortcode for displaying
  1675. * a collection of WordPress audio or video files in a post.
  1676. *
  1677. * @since 3.9.0
  1678. *
  1679. * @global int $content_width
  1680. * @staticvar int $instance
  1681. *
  1682. * @param array $attr {
  1683. * Array of default playlist attributes.
  1684. *
  1685. * @type string $type Type of playlist to display. Accepts 'audio' or 'video'. Default 'audio'.
  1686. * @type string $order Designates ascending or descending order of items in the playlist.
  1687. * Accepts 'ASC', 'DESC'. Default 'ASC'.
  1688. * @type string $orderby Any column, or columns, to sort the playlist. If $ids are
  1689. * passed, this defaults to the order of the $ids array ('post__in').
  1690. * Otherwise default is 'menu_order ID'.
  1691. * @type int $id If an explicit $ids array is not present, this parameter
  1692. * will determine which attachments are used for the playlist.
  1693. * Default is the current post ID.
  1694. * @type array $ids Create a playlist out of these explicit attachment IDs. If empty,
  1695. * a playlist will be created from all $type attachments of $id.
  1696. * Default empty.
  1697. * @type array $exclude List of specific attachment IDs to exclude from the playlist. Default empty.
  1698. * @type string $style Playlist style to use. Accepts 'light' or 'dark'. Default 'light'.
  1699. * @type bool $tracklist Whether to show or hide the playlist. Default true.
  1700. * @type bool $tracknumbers Whether to show or hide the numbers next to entries in the playlist. Default true.
  1701. * @type bool $images Show or hide the video or audio thumbnail (Featured Image/post
  1702. * thumbnail). Default true.
  1703. * @type bool $artists Whether to show or hide artist name in the playlist. Default true.
  1704. * }
  1705. *
  1706. * @return string Playlist output. Empty string if the passed type is unsupported.
  1707. */
  1708. function wp_playlist_shortcode( $attr ) {
  1709. global $content_width;
  1710. $post = get_post();
  1711. static $instance = 0;
  1712. $instance++;
  1713. if ( ! empty( $attr['ids'] ) ) {
  1714. // 'ids' is explicitly ordered, unless you specify otherwise.
  1715. if ( empty( $attr['orderby'] ) ) {
  1716. $attr['orderby'] = 'post__in';
  1717. }
  1718. $attr['include'] = $attr['ids'];
  1719. }
  1720. /**
  1721. * Filters the playlist output.
  1722. *
  1723. * Passing a non-empty value to the filter will short-circuit generation
  1724. * of the default playlist output, returning the passed value instead.
  1725. *
  1726. * @since 3.9.0
  1727. * @since 4.2.0 The `$instance` parameter was added.
  1728. *
  1729. * @param string $output Playlist output. Default empty.
  1730. * @param array $attr An array of shortcode attributes.
  1731. * @param int $instance Unique numeric ID of this playlist shortcode instance.
  1732. */
  1733. $output = apply_filters( 'post_playlist', '', $attr, $instance );
  1734. if ( $output != '' ) {
  1735. return $output;
  1736. }
  1737. $atts = shortcode_atts( array(
  1738. 'type' => 'audio',
  1739. 'order' => 'ASC',
  1740. 'orderby' => 'menu_order ID',
  1741. 'id' => $post ? $post->ID : 0,
  1742. 'include' => '',
  1743. 'exclude' => '',
  1744. 'style' => 'light',
  1745. 'tracklist' => true,
  1746. 'tracknumbers' => true,
  1747. 'images' => true,
  1748. 'artists' => true
  1749. ), $attr, 'playlist' );
  1750. $id = intval( $atts['id'] );
  1751. if ( $atts['type'] !== 'audio' ) {
  1752. $atts['type'] = 'video';
  1753. }
  1754. $args = array(
  1755. 'post_status' => 'inherit',
  1756. 'post_type' => 'attachment',
  1757. 'post_mime_type' => $atts['type'],
  1758. 'order' => $atts['order'],
  1759. 'orderby' => $atts['orderby']
  1760. );
  1761. if ( ! empty( $atts['include'] ) ) {
  1762. $args['include'] = $atts['include'];
  1763. $_attachments = get_posts( $args );
  1764. $attachments = array();
  1765. foreach ( $_attachments as $key => $val ) {
  1766. $attachments[$val->ID] = $_attachments[$key];
  1767. }
  1768. } elseif ( ! empty( $atts['exclude'] ) ) {
  1769. $args['post_parent'] = $id;
  1770. $args['exclude'] = $atts['exclude'];
  1771. $attachments = get_children( $args );
  1772. } else {
  1773. $args['post_parent'] = $id;
  1774. $attachments = get_children( $args );
  1775. }
  1776. if ( empty( $attachments ) ) {
  1777. return '';
  1778. }
  1779. if ( is_feed() ) {
  1780. $output = "\n";
  1781. foreach ( $attachments as $att_id => $attachment ) {
  1782. $output .= wp_get_attachment_link( $att_id ) . "\n";
  1783. }
  1784. return $output;
  1785. }
  1786. $outer = 22; // default padding and border of wrapper
  1787. $default_width = 640;
  1788. $default_height = 360;
  1789. $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
  1790. $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
  1791. $data = array(
  1792. 'type' => $atts['type'],
  1793. // don't pass strings to JSON, will be truthy in JS
  1794. 'tracklist' => wp_validate_boolean( $atts['tracklist'] ),
  1795. 'tracknumbers' => wp_validate_boolean( $atts['tracknumbers'] ),
  1796. 'images' => wp_validate_boolean( $atts['images'] ),
  1797. 'artists' => wp_validate_boolean( $atts['artists'] ),
  1798. );
  1799. $tracks = array();
  1800. foreach ( $attachments as $attachment ) {
  1801. $url = wp_get_attachment_url( $attachment->ID );
  1802. $ftype = wp_check_filetype( $url, wp_get_mime_types() );
  1803. $track = array(
  1804. 'src' => $url,
  1805. 'type' => $ftype['type'],
  1806. 'title' => $attachment->post_title,
  1807. 'caption' => $attachment->post_excerpt,
  1808. 'description' => $attachment->post_content
  1809. );
  1810. $track['meta'] = array();
  1811. $meta = wp_get_attachment_metadata( $attachment->ID );
  1812. if ( ! empty( $meta ) ) {
  1813. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  1814. if ( ! empty( $meta[ $key ] ) ) {
  1815. $track['meta'][ $key ] = $meta[ $key ];
  1816. }
  1817. }
  1818. if ( 'video' === $atts['type'] ) {
  1819. if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
  1820. $width = $meta['width'];
  1821. $height = $meta['height'];
  1822. $theme_height = round( ( $height * $theme_width ) / $width );
  1823. } else {
  1824. $width = $default_width;
  1825. $height = $default_height;
  1826. }
  1827. $track['dimensions'] = array(
  1828. 'original' => compact( 'width', 'height' ),
  1829. 'resized' => array(
  1830. 'width' => $theme_width,
  1831. 'height' => $theme_height
  1832. )
  1833. );
  1834. }
  1835. }
  1836. if ( $atts['images'] ) {
  1837. $thumb_id = get_post_thumbnail_id( $attachment->ID );
  1838. if ( ! empty( $thumb_id ) ) {
  1839. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'full' );
  1840. $track['image'] = compact( 'src', 'width', 'height' );
  1841. list( $src, $width, $height ) = wp_get_attachment_image_src( $thumb_id, 'thumbnail' );
  1842. $track['thumb'] = compact( 'src', 'width', 'height' );
  1843. } else {
  1844. $src = wp_mime_type_icon( $attachment->ID );
  1845. $width = 48;
  1846. $height = 64;
  1847. $track['image'] = compact( 'src', 'width', 'height' );
  1848. $track['thumb'] = compact( 'src', 'width', 'height' );
  1849. }
  1850. }
  1851. $tracks[] = $track;
  1852. }
  1853. $data['tracks'] = $tracks;
  1854. $safe_type = esc_attr( $atts['type'] );
  1855. $safe_style = esc_attr( $atts['style'] );
  1856. ob_start();
  1857. if ( 1 === $instance ) {
  1858. /**
  1859. * Prints and enqueues playlist scripts, styles, and JavaScript templates.
  1860. *
  1861. * @since 3.9.0
  1862. *
  1863. * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
  1864. * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
  1865. */
  1866. do_action( 'wp_playlist_scripts', $atts['type'], $atts['style'] );
  1867. } ?>
  1868. <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
  1869. <?php if ( 'audio' === $atts['type'] ): ?>
  1870. <div class="wp-playlist-current-item"></div>
  1871. <?php endif ?>
  1872. <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
  1873. echo (int) $theme_width;
  1874. ?>"<?php if ( 'video' === $safe_type ):
  1875. echo ' height="', (int) $theme_height, '"';
  1876. endif; ?>></<?php echo $safe_type ?>>
  1877. <div class="wp-playlist-next"></div>
  1878. <div class="wp-playlist-prev"></div>
  1879. <noscript>
  1880. <ol><?php
  1881. foreach ( $attachments as $att_id => $attachment ) {
  1882. printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
  1883. }
  1884. ?></ol>
  1885. </noscript>
  1886. <script type="application/json" class="wp-playlist-script"><?php echo wp_json_encode( $data ) ?></script>
  1887. </div>
  1888. <?php
  1889. return ob_get_clean();
  1890. }
  1891. add_shortcode( 'playlist', 'wp_playlist_shortcode' );
  1892. /**
  1893. * Provides a No-JS Flash fallback as a last resort for audio / video.
  1894. *
  1895. * @since 3.6.0
  1896. *
  1897. * @param string $url The media element URL.
  1898. * @return string Fallback HTML.
  1899. */
  1900. function wp_mediaelement_fallback( $url ) {
  1901. /**
  1902. * Filters the Mediaelement fallback output for no-JS.
  1903. *
  1904. * @since 3.6.0
  1905. *
  1906. * @param string $output Fallback output for no-JS.
  1907. * @param string $url Media file URL.
  1908. */
  1909. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  1910. }
  1911. /**
  1912. * Returns a filtered list of WP-supported audio formats.
  1913. *
  1914. * @since 3.6.0
  1915. *
  1916. * @return array Supported audio formats.
  1917. */
  1918. function wp_get_audio_extensions() {
  1919. /**
  1920. * Filters the list of supported audio formats.
  1921. *
  1922. * @since 3.6.0
  1923. *
  1924. * @param array $extensions An array of support audio formats. Defaults are
  1925. * 'mp3', 'ogg', 'flac', 'm4a', 'wav'.
  1926. */
  1927. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'flac', 'm4a', 'wav' ) );
  1928. }
  1929. /**
  1930. * Returns useful keys to use to lookup data from an attachment's stored metadata.
  1931. *
  1932. * @since 3.9.0
  1933. *
  1934. * @param WP_Post $attachment The current attachment, provided for context.
  1935. * @param string $context Optional. The context. Accepts 'edit', 'display'. Default 'display'.
  1936. * @return array Key/value pairs of field keys to labels.
  1937. */
  1938. function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
  1939. $fields = array(
  1940. 'artist' => __( 'Artist' ),
  1941. 'album' => __( 'Album' ),
  1942. );
  1943. if ( 'display' === $context ) {
  1944. $fields['genre'] = __( 'Genre' );
  1945. $fields['year'] = __( 'Year' );
  1946. $fields['length_formatted'] = _x( 'Length', 'video or audio' );
  1947. } elseif ( 'js' === $context ) {
  1948. $fields['bitrate'] = __( 'Bitrate' );
  1949. $fields['bitrate_mode'] = __( 'Bitrate Mode' );
  1950. }
  1951. /**
  1952. * Filters the editable list of keys to look up data from an attachment's metadata.
  1953. *
  1954. * @since 3.9.0
  1955. *
  1956. * @param array $fields Key/value pairs of field keys to labels.
  1957. * @param WP_Post $attachment Attachment object.
  1958. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  1959. */
  1960. return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
  1961. }
  1962. /**
  1963. * Builds the Audio shortcode output.
  1964. *
  1965. * This implements the functionality of the Audio Shortcode for displaying
  1966. * WordPress mp3s in a post.
  1967. *
  1968. * @since 3.6.0
  1969. *
  1970. * @staticvar int $instance
  1971. *
  1972. * @param array $attr {
  1973. * Attributes of the audio shortcode.
  1974. *
  1975. * @type string $src URL to the source of the audio file. Default empty.
  1976. * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
  1977. * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
  1978. * @type string $preload The 'preload' attribute for the `<audio>` element. Default 'none'.
  1979. * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
  1980. * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%;'.
  1981. * }
  1982. * @param string $content Shortcode content.
  1983. * @return string|void HTML content to display audio.
  1984. */
  1985. function wp_audio_shortcode( $attr, $content = '' ) {
  1986. $post_id = get_post() ? get_the_ID() : 0;
  1987. static $instance = 0;
  1988. $instance++;
  1989. /**
  1990. * Filters the default audio shortcode output.
  1991. *
  1992. * If the filtered output isn't empty, it will be used instead of generating the default audio template.
  1993. *
  1994. * @since 3.6.0
  1995. *
  1996. * @param string $html Empty variable to be replaced with shortcode markup.
  1997. * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
  1998. * @param string $content Shortcode content.
  1999. * @param int $instance Unique numeric ID of this audio shortcode instance.
  2000. */
  2001. $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instance );
  2002. if ( '' !== $override ) {
  2003. return $override;
  2004. }
  2005. $audio = null;
  2006. $default_types = wp_get_audio_extensions();
  2007. $defaults_atts = array(
  2008. 'src' => '',
  2009. 'loop' => '',
  2010. 'autoplay' => '',
  2011. 'preload' => 'none',
  2012. 'class' => 'wp-audio-shortcode',
  2013. 'style' => 'width: 100%;'
  2014. );
  2015. foreach ( $default_types as $type ) {
  2016. $defaults_atts[$type] = '';
  2017. }
  2018. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  2019. $primary = false;
  2020. if ( ! empty( $atts['src'] ) ) {
  2021. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2022. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  2023. return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2024. }
  2025. $primary = true;
  2026. array_unshift( $default_types, 'src' );
  2027. } else {
  2028. foreach ( $default_types as $ext ) {
  2029. if ( ! empty( $atts[ $ext ] ) ) {
  2030. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2031. if ( strtolower( $type['ext'] ) === $ext ) {
  2032. $primary = true;
  2033. }
  2034. }
  2035. }
  2036. }
  2037. if ( ! $primary ) {
  2038. $audios = get_attached_media( 'audio', $post_id );
  2039. if ( empty( $audios ) ) {
  2040. return;
  2041. }
  2042. $audio = reset( $audios );
  2043. $atts['src'] = wp_get_attachment_url( $audio->ID );
  2044. if ( empty( $atts['src'] ) ) {
  2045. return;
  2046. }
  2047. array_unshift( $default_types, 'src' );
  2048. }
  2049. /**
  2050. * Filters the media library used for the audio shortcode.
  2051. *
  2052. * @since 3.6.0
  2053. *
  2054. * @param string $library Media library used for the audio shortcode.
  2055. */
  2056. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  2057. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2058. wp_enqueue_style( 'wp-mediaelement' );
  2059. wp_enqueue_script( 'wp-mediaelement' );
  2060. }
  2061. /**
  2062. * Filters the class attribute for the audio shortcode output container.
  2063. *
  2064. * @since 3.6.0
  2065. * @since 4.9.0 The `$atts` parameter was added.
  2066. *
  2067. * @param string $class CSS class or list of space-separated classes.
  2068. * @param array $atts Array of audio shortcode attributes.
  2069. */
  2070. $atts['class'] = apply_filters( 'wp_audio_shortcode_class', $atts['class'], $atts );
  2071. $html_atts = array(
  2072. 'class' => $atts['class'],
  2073. 'id' => sprintf( 'audio-%d-%d', $post_id, $instance ),
  2074. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2075. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2076. 'preload' => $atts['preload'],
  2077. 'style' => $atts['style'],
  2078. );
  2079. // These ones should just be omitted altogether if they are blank
  2080. foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  2081. if ( empty( $html_atts[$a] ) ) {
  2082. unset( $html_atts[$a] );
  2083. }
  2084. }
  2085. $attr_strings = array();
  2086. foreach ( $html_atts as $k => $v ) {
  2087. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2088. }
  2089. $html = '';
  2090. if ( 'mediaelement' === $library && 1 === $instance ) {
  2091. $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  2092. }
  2093. $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
  2094. $fileurl = '';
  2095. $source = '<source type="%s" src="%s" />';
  2096. foreach ( $default_types as $fallback ) {
  2097. if ( ! empty( $atts[ $fallback ] ) ) {
  2098. if ( empty( $fileurl ) ) {
  2099. $fileurl = $atts[ $fallback ];
  2100. }
  2101. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2102. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2103. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2104. }
  2105. }
  2106. if ( 'mediaelement' === $library ) {
  2107. $html .= wp_mediaelement_fallback( $fileurl );
  2108. }
  2109. $html .= '</audio>';
  2110. /**
  2111. * Filters the audio shortcode output.
  2112. *
  2113. * @since 3.6.0
  2114. *
  2115. * @param string $html Audio shortcode HTML output.
  2116. * @param array $atts Array of audio shortcode attributes.
  2117. * @param string $audio Audio file.
  2118. * @param int $post_id Post ID.
  2119. * @param string $library Media library used for the audio shortcode.
  2120. */
  2121. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  2122. }
  2123. add_shortcode( 'audio', 'wp_audio_shortcode' );
  2124. /**
  2125. * Returns a filtered list of WP-supported video formats.
  2126. *
  2127. * @since 3.6.0
  2128. *
  2129. * @return array List of supported video formats.
  2130. */
  2131. function wp_get_video_extensions() {
  2132. /**
  2133. * Filters the list of supported video formats.
  2134. *
  2135. * @since 3.6.0
  2136. *
  2137. * @param array $extensions An array of support video formats. Defaults are
  2138. * 'mp4', 'm4v', 'webm', 'ogv', 'flv'.
  2139. */
  2140. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'flv' ) );
  2141. }
  2142. /**
  2143. * Builds the Video shortcode output.
  2144. *
  2145. * This implements the functionality of the Video Shortcode for displaying
  2146. * WordPress mp4s in a post.
  2147. *
  2148. * @since 3.6.0
  2149. *
  2150. * @global int $content_width
  2151. * @staticvar int $instance
  2152. *
  2153. * @param array $attr {
  2154. * Attributes of the shortcode.
  2155. *
  2156. * @type string $src URL to the source of the video file. Default empty.
  2157. * @type int $height Height of the video embed in pixels. Default 360.
  2158. * @type int $width Width of the video embed in pixels. Default $content_width or 640.
  2159. * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
  2160. * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
  2161. * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
  2162. * @type string $preload The 'preload' attribute for the `<video>` element.
  2163. * Default 'metadata'.
  2164. * @type string $class The 'class' attribute for the `<video>` element.
  2165. * Default 'wp-video-shortcode'.
  2166. * }
  2167. * @param string $content Shortcode content.
  2168. * @return string|void HTML content to display video.
  2169. */
  2170. function wp_video_shortcode( $attr, $content = '' ) {
  2171. global $content_width;
  2172. $post_id = get_post() ? get_the_ID() : 0;
  2173. static $instance = 0;
  2174. $instance++;
  2175. /**
  2176. * Filters the default video shortcode output.
  2177. *
  2178. * If the filtered output isn't empty, it will be used instead of generating
  2179. * the default video template.
  2180. *
  2181. * @since 3.6.0
  2182. *
  2183. * @see wp_video_shortcode()
  2184. *
  2185. * @param string $html Empty variable to be replaced with shortcode markup.
  2186. * @param array $attr Attributes of the shortcode. @see wp_video_shortcode()
  2187. * @param string $content Video shortcode content.
  2188. * @param int $instance Unique numeric ID of this video shortcode instance.
  2189. */
  2190. $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instance );
  2191. if ( '' !== $override ) {
  2192. return $override;
  2193. }
  2194. $video = null;
  2195. $default_types = wp_get_video_extensions();
  2196. $defaults_atts = array(
  2197. 'src' => '',
  2198. 'poster' => '',
  2199. 'loop' => '',
  2200. 'autoplay' => '',
  2201. 'preload' => 'metadata',
  2202. 'width' => 640,
  2203. 'height' => 360,
  2204. 'class' => 'wp-video-shortcode',
  2205. );
  2206. foreach ( $default_types as $type ) {
  2207. $defaults_atts[$type] = '';
  2208. }
  2209. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  2210. if ( is_admin() ) {
  2211. // shrink the video so it isn't huge in the admin
  2212. if ( $atts['width'] > $defaults_atts['width'] ) {
  2213. $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
  2214. $atts['width'] = $defaults_atts['width'];
  2215. }
  2216. } else {
  2217. // if the video is bigger than the theme
  2218. if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
  2219. $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
  2220. $atts['width'] = $content_width;
  2221. }
  2222. }
  2223. $is_vimeo = $is_youtube = false;
  2224. $yt_pattern = '#^https?://(?:www\.)?(?:youtube\.com/watch|youtu\.be/)#';
  2225. $vimeo_pattern = '#^https?://(.+\.)?vimeo\.com/.*#';
  2226. $primary = false;
  2227. if ( ! empty( $atts['src'] ) ) {
  2228. $is_vimeo = ( preg_match( $vimeo_pattern, $atts['src'] ) );
  2229. $is_youtube = ( preg_match( $yt_pattern, $atts['src'] ) );
  2230. if ( ! $is_youtube && ! $is_vimeo ) {
  2231. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  2232. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  2233. return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  2234. }
  2235. }
  2236. if ( $is_vimeo ) {
  2237. wp_enqueue_script( 'mediaelement-vimeo' );
  2238. }
  2239. $primary = true;
  2240. array_unshift( $default_types, 'src' );
  2241. } else {
  2242. foreach ( $default_types as $ext ) {
  2243. if ( ! empty( $atts[ $ext ] ) ) {
  2244. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  2245. if ( strtolower( $type['ext'] ) === $ext ) {
  2246. $primary = true;
  2247. }
  2248. }
  2249. }
  2250. }
  2251. if ( ! $primary ) {
  2252. $videos = get_attached_media( 'video', $post_id );
  2253. if ( empty( $videos ) ) {
  2254. return;
  2255. }
  2256. $video = reset( $videos );
  2257. $atts['src'] = wp_get_attachment_url( $video->ID );
  2258. if ( empty( $atts['src'] ) ) {
  2259. return;
  2260. }
  2261. array_unshift( $default_types, 'src' );
  2262. }
  2263. /**
  2264. * Filters the media library used for the video shortcode.
  2265. *
  2266. * @since 3.6.0
  2267. *
  2268. * @param string $library Media library used for the video shortcode.
  2269. */
  2270. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  2271. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  2272. wp_enqueue_style( 'wp-mediaelement' );
  2273. wp_enqueue_script( 'wp-mediaelement' );
  2274. wp_enqueue_script( 'mediaelement-vimeo' );
  2275. }
  2276. // Mediaelement has issues with some URL formats for Vimeo and YouTube, so
  2277. // update the URL to prevent the ME.js player from breaking.
  2278. if ( 'mediaelement' === $library ) {
  2279. if ( $is_youtube ) {
  2280. // Remove `feature` query arg and force SSL - see #40866.
  2281. $atts['src'] = remove_query_arg( 'feature', $atts['src'] );
  2282. $atts['src'] = set_url_scheme( $atts['src'], 'https' );
  2283. } elseif ( $is_vimeo ) {
  2284. // Remove all query arguments and force SSL - see #40866.
  2285. $parsed_vimeo_url = wp_parse_url( $atts['src'] );
  2286. $vimeo_src = 'https://' . $parsed_vimeo_url['host'] . $parsed_vimeo_url['path'];
  2287. // Add loop param for mejs bug - see #40977, not needed after #39686.
  2288. $loop = $atts['loop'] ? '1' : '0';
  2289. $atts['src'] = add_query_arg( 'loop', $loop, $vimeo_src );
  2290. }
  2291. }
  2292. /**
  2293. * Filters the class attribute for the video shortcode output container.
  2294. *
  2295. * @since 3.6.0
  2296. * @since 4.9.0 The `$atts` parameter was added.
  2297. *
  2298. * @param string $class CSS class or list of space-separated classes.
  2299. * @param array $atts Array of video shortcode attributes.
  2300. */
  2301. $atts['class'] = apply_filters( 'wp_video_shortcode_class', $atts['class'], $atts );
  2302. $html_atts = array(
  2303. 'class' => $atts['class'],
  2304. 'id' => sprintf( 'video-%d-%d', $post_id, $instance ),
  2305. 'width' => absint( $atts['width'] ),
  2306. 'height' => absint( $atts['height'] ),
  2307. 'poster' => esc_url( $atts['poster'] ),
  2308. 'loop' => wp_validate_boolean( $atts['loop'] ),
  2309. 'autoplay' => wp_validate_boolean( $atts['autoplay'] ),
  2310. 'preload' => $atts['preload'],
  2311. );
  2312. // These ones should just be omitted altogether if they are blank
  2313. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  2314. if ( empty( $html_atts[$a] ) ) {
  2315. unset( $html_atts[$a] );
  2316. }
  2317. }
  2318. $attr_strings = array();
  2319. foreach ( $html_atts as $k => $v ) {
  2320. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  2321. }
  2322. $html = '';
  2323. if ( 'mediaelement' === $library && 1 === $instance ) {
  2324. $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  2325. }
  2326. $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  2327. $fileurl = '';
  2328. $source = '<source type="%s" src="%s" />';
  2329. foreach ( $default_types as $fallback ) {
  2330. if ( ! empty( $atts[ $fallback ] ) ) {
  2331. if ( empty( $fileurl ) ) {
  2332. $fileurl = $atts[ $fallback ];
  2333. }
  2334. if ( 'src' === $fallback && $is_youtube ) {
  2335. $type = array( 'type' => 'video/youtube' );
  2336. } elseif ( 'src' === $fallback && $is_vimeo ) {
  2337. $type = array( 'type' => 'video/vimeo' );
  2338. } else {
  2339. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  2340. }
  2341. $url = add_query_arg( '_', $instance, $atts[ $fallback ] );
  2342. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  2343. }
  2344. }
  2345. if ( ! empty( $content ) ) {
  2346. if ( false !== strpos( $content, "\n" ) ) {
  2347. $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
  2348. }
  2349. $html .= trim( $content );
  2350. }
  2351. if ( 'mediaelement' === $library ) {
  2352. $html .= wp_mediaelement_fallback( $fileurl );
  2353. }
  2354. $html .= '</video>';
  2355. $width_rule = '';
  2356. if ( ! empty( $atts['width'] ) ) {
  2357. $width_rule = sprintf( 'width: %dpx;', $atts['width'] );
  2358. }
  2359. $output = sprintf( '<div style="%s" class="wp-video">%s</div>', $width_rule, $html );
  2360. /**
  2361. * Filters the output of the video shortcode.
  2362. *
  2363. * @since 3.6.0
  2364. *
  2365. * @param string $output Video shortcode HTML output.
  2366. * @param array $atts Array of video shortcode attributes.
  2367. * @param string $video Video file.
  2368. * @param int $post_id Post ID.
  2369. * @param string $library Media library used for the video shortcode.
  2370. */
  2371. return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
  2372. }
  2373. add_shortcode( 'video', 'wp_video_shortcode' );
  2374. /**
  2375. * Displays previous image link that has the same post parent.
  2376. *
  2377. * @since 2.5.0
  2378. *
  2379. * @see adjacent_image_link()
  2380. *
  2381. * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
  2382. * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
  2383. * default to 'post_title' or `$text`. Default 'thumbnail'.
  2384. * @param string $text Optional. Link text. Default false.
  2385. */
  2386. function previous_image_link( $size = 'thumbnail', $text = false ) {
  2387. adjacent_image_link(true, $size, $text);
  2388. }
  2389. /**
  2390. * Displays next image link that has the same post parent.
  2391. *
  2392. * @since 2.5.0
  2393. *
  2394. * @see adjacent_image_link()
  2395. *
  2396. * @param string|array $size Optional. Image size. Accepts any valid image size, an array of width and
  2397. * height values in pixels (in that order), 0, or 'none'. 0 or 'none' will
  2398. * default to 'post_title' or `$text`. Default 'thumbnail'.
  2399. * @param string $text Optional. Link text. Default false.
  2400. */
  2401. function next_image_link( $size = 'thumbnail', $text = false ) {
  2402. adjacent_image_link(false, $size, $text);
  2403. }
  2404. /**
  2405. * Displays next or previous image link that has the same post parent.
  2406. *
  2407. * Retrieves the current attachment object from the $post global.
  2408. *
  2409. * @since 2.5.0
  2410. *
  2411. * @param bool $prev Optional. Whether to display the next (false) or previous (true) link. Default true.
  2412. * @param string|array $size Optional. Image size. Accepts any valid image size, or an array of width and height
  2413. * values in pixels (in that order). Default 'thumbnail'.
  2414. * @param bool $text Optional. Link text. Default false.
  2415. */
  2416. function adjacent_image_link( $prev = true, $size = 'thumbnail', $text = false ) {
  2417. $post = get_post();
  2418. $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );
  2419. foreach ( $attachments as $k => $attachment ) {
  2420. if ( $attachment->ID == $post->ID ) {
  2421. break;
  2422. }
  2423. }
  2424. $output = '';
  2425. $attachment_id = 0;
  2426. if ( $attachments ) {
  2427. $k = $prev ? $k - 1 : $k + 1;
  2428. if ( isset( $attachments[ $k ] ) ) {
  2429. $attachment_id = $attachments[ $k ]->ID;
  2430. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  2431. }
  2432. }
  2433. $adjacent = $prev ? 'previous' : 'next';
  2434. /**
  2435. * Filters the adjacent image link.
  2436. *
  2437. * The dynamic portion of the hook name, `$adjacent`, refers to the type of adjacency,
  2438. * either 'next', or 'previous'.
  2439. *
  2440. * @since 3.5.0
  2441. *
  2442. * @param string $output Adjacent image HTML markup.
  2443. * @param int $attachment_id Attachment ID
  2444. * @param string $size Image size.
  2445. * @param string $text Link text.
  2446. */
  2447. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  2448. }
  2449. /**
  2450. * Retrieves taxonomies attached to given the attachment.
  2451. *
  2452. * @since 2.5.0
  2453. * @since 4.7.0 Introduced the `$output` parameter.
  2454. *
  2455. * @param int|array|object $attachment Attachment ID, data array, or data object.
  2456. * @param string $output Output type. 'names' to return an array of taxonomy names,
  2457. * or 'objects' to return an array of taxonomy objects.
  2458. * Default is 'names'.
  2459. * @return array Empty array on failure. List of taxonomies on success.
  2460. */
  2461. function get_attachment_taxonomies( $attachment, $output = 'names' ) {
  2462. if ( is_int( $attachment ) ) {
  2463. $attachment = get_post( $attachment );
  2464. } elseif ( is_array( $attachment ) ) {
  2465. $attachment = (object) $attachment;
  2466. }
  2467. if ( ! is_object($attachment) )
  2468. return array();
  2469. $file = get_attached_file( $attachment->ID );
  2470. $filename = basename( $file );
  2471. $objects = array('attachment');
  2472. if ( false !== strpos($filename, '.') )
  2473. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  2474. if ( !empty($attachment->post_mime_type) ) {
  2475. $objects[] = 'attachment:' . $attachment->post_mime_type;
  2476. if ( false !== strpos($attachment->post_mime_type, '/') )
  2477. foreach ( explode('/', $attachment->post_mime_type) as $token )
  2478. if ( !empty($token) )
  2479. $objects[] = "attachment:$token";
  2480. }
  2481. $taxonomies = array();
  2482. foreach ( $objects as $object ) {
  2483. if ( $taxes = get_object_taxonomies( $object, $output ) ) {
  2484. $taxonomies = array_merge( $taxonomies, $taxes );
  2485. }
  2486. }
  2487. if ( 'names' === $output ) {
  2488. $taxonomies = array_unique( $taxonomies );
  2489. }
  2490. return $taxonomies;
  2491. }
  2492. /**
  2493. * Retrieves all of the taxonomy names that are registered for attachments.
  2494. *
  2495. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  2496. *
  2497. * @since 3.5.0
  2498. *
  2499. * @see get_taxonomies()
  2500. *
  2501. * @param string $output Optional. The type of taxonomy output to return. Accepts 'names' or 'objects'.
  2502. * Default 'names'.
  2503. * @return array The names of all taxonomy of $object_type.
  2504. */
  2505. function get_taxonomies_for_attachments( $output = 'names' ) {
  2506. $taxonomies = array();
  2507. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  2508. foreach ( $taxonomy->object_type as $object_type ) {
  2509. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  2510. if ( 'names' == $output )
  2511. $taxonomies[] = $taxonomy->name;
  2512. else
  2513. $taxonomies[ $taxonomy->name ] = $taxonomy;
  2514. break;
  2515. }
  2516. }
  2517. }
  2518. return $taxonomies;
  2519. }
  2520. /**
  2521. * Create new GD image resource with transparency support
  2522. *
  2523. * @todo: Deprecate if possible.
  2524. *
  2525. * @since 2.9.0
  2526. *
  2527. * @param int $width Image width in pixels.
  2528. * @param int $height Image height in pixels..
  2529. * @return resource The GD image resource.
  2530. */
  2531. function wp_imagecreatetruecolor($width, $height) {
  2532. $img = imagecreatetruecolor($width, $height);
  2533. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  2534. imagealphablending($img, false);
  2535. imagesavealpha($img, true);
  2536. }
  2537. return $img;
  2538. }
  2539. /**
  2540. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  2541. *
  2542. * @since 2.9.0
  2543. *
  2544. * @see wp_constrain_dimensions()
  2545. *
  2546. * @param int $example_width The width of an example embed.
  2547. * @param int $example_height The height of an example embed.
  2548. * @param int $max_width The maximum allowed width.
  2549. * @param int $max_height The maximum allowed height.
  2550. * @return array The maximum possible width and height based on the example ratio.
  2551. */
  2552. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  2553. $example_width = (int) $example_width;
  2554. $example_height = (int) $example_height;
  2555. $max_width = (int) $max_width;
  2556. $max_height = (int) $max_height;
  2557. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  2558. }
  2559. /**
  2560. * Determines the maximum upload size allowed in php.ini.
  2561. *
  2562. * @since 2.5.0
  2563. *
  2564. * @return int Allowed upload size.
  2565. */
  2566. function wp_max_upload_size() {
  2567. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  2568. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  2569. /**
  2570. * Filters the maximum upload size allowed in php.ini.
  2571. *
  2572. * @since 2.5.0
  2573. *
  2574. * @param int $size Max upload size limit in bytes.
  2575. * @param int $u_bytes Maximum upload filesize in bytes.
  2576. * @param int $p_bytes Maximum size of POST data in bytes.
  2577. */
  2578. return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  2579. }
  2580. /**
  2581. * Returns a WP_Image_Editor instance and loads file into it.
  2582. *
  2583. * @since 3.5.0
  2584. *
  2585. * @param string $path Path to the file to load.
  2586. * @param array $args Optional. Additional arguments for retrieving the image editor.
  2587. * Default empty array.
  2588. * @return WP_Image_Editor|WP_Error The WP_Image_Editor object if successful, an WP_Error
  2589. * object otherwise.
  2590. */
  2591. function wp_get_image_editor( $path, $args = array() ) {
  2592. $args['path'] = $path;
  2593. if ( ! isset( $args['mime_type'] ) ) {
  2594. $file_info = wp_check_filetype( $args['path'] );
  2595. // If $file_info['type'] is false, then we let the editor attempt to
  2596. // figure out the file type, rather than forcing a failure based on extension.
  2597. if ( isset( $file_info ) && $file_info['type'] )
  2598. $args['mime_type'] = $file_info['type'];
  2599. }
  2600. $implementation = _wp_image_editor_choose( $args );
  2601. if ( $implementation ) {
  2602. $editor = new $implementation( $path );
  2603. $loaded = $editor->load();
  2604. if ( is_wp_error( $loaded ) )
  2605. return $loaded;
  2606. return $editor;
  2607. }
  2608. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  2609. }
  2610. /**
  2611. * Tests whether there is an editor that supports a given mime type or methods.
  2612. *
  2613. * @since 3.5.0
  2614. *
  2615. * @param string|array $args Optional. Array of arguments to retrieve the image editor supports.
  2616. * Default empty array.
  2617. * @return bool True if an eligible editor is found; false otherwise.
  2618. */
  2619. function wp_image_editor_supports( $args = array() ) {
  2620. return (bool) _wp_image_editor_choose( $args );
  2621. }
  2622. /**
  2623. * Tests which editors are capable of supporting the request.
  2624. *
  2625. * @ignore
  2626. * @since 3.5.0
  2627. *
  2628. * @param array $args Optional. Array of arguments for choosing a capable editor. Default empty array.
  2629. * @return string|false Class name for the first editor that claims to support the request. False if no
  2630. * editor claims to support the request.
  2631. */
  2632. function _wp_image_editor_choose( $args = array() ) {
  2633. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  2634. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  2635. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  2636. /**
  2637. * Filters the list of image editing library classes.
  2638. *
  2639. * @since 3.5.0
  2640. *
  2641. * @param array $image_editors List of available image editors. Defaults are
  2642. * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
  2643. */
  2644. $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  2645. foreach ( $implementations as $implementation ) {
  2646. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  2647. continue;
  2648. if ( isset( $args['mime_type'] ) &&
  2649. ! call_user_func(
  2650. array( $implementation, 'supports_mime_type' ),
  2651. $args['mime_type'] ) ) {
  2652. continue;
  2653. }
  2654. if ( isset( $args['methods'] ) &&
  2655. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  2656. continue;
  2657. }
  2658. return $implementation;
  2659. }
  2660. return false;
  2661. }
  2662. /**
  2663. * Prints default Plupload arguments.
  2664. *
  2665. * @since 3.4.0
  2666. */
  2667. function wp_plupload_default_settings() {
  2668. $wp_scripts = wp_scripts();
  2669. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  2670. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  2671. return;
  2672. $max_upload_size = wp_max_upload_size();
  2673. $allowed_extensions = array_keys( get_allowed_mime_types() );
  2674. $extensions = array();
  2675. foreach ( $allowed_extensions as $extension ) {
  2676. $extensions = array_merge( $extensions, explode( '|', $extension ) );
  2677. }
  2678. /*
  2679. * Since 4.9 the `runtimes` setting is hardcoded in our version of Plupload to `html5,html4`,
  2680. * and the `flash_swf_url` and `silverlight_xap_url` are not used.
  2681. */
  2682. $defaults = array(
  2683. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  2684. 'url' => admin_url( 'async-upload.php', 'relative' ),
  2685. 'filters' => array(
  2686. 'max_file_size' => $max_upload_size . 'b',
  2687. 'mime_types' => array( array( 'extensions' => implode( ',', $extensions ) ) ),
  2688. ),
  2689. );
  2690. // Currently only iOS Safari supports multiple files uploading but iOS 7.x has a bug that prevents uploading of videos
  2691. // when enabled. See #29602.
  2692. if ( wp_is_mobile() && strpos( $_SERVER['HTTP_USER_AGENT'], 'OS 7_' ) !== false &&
  2693. strpos( $_SERVER['HTTP_USER_AGENT'], 'like Mac OS X' ) !== false ) {
  2694. $defaults['multi_selection'] = false;
  2695. }
  2696. /**
  2697. * Filters the Plupload default settings.
  2698. *
  2699. * @since 3.4.0
  2700. *
  2701. * @param array $defaults Default Plupload settings array.
  2702. */
  2703. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  2704. $params = array(
  2705. 'action' => 'upload-attachment',
  2706. );
  2707. /**
  2708. * Filters the Plupload default parameters.
  2709. *
  2710. * @since 3.4.0
  2711. *
  2712. * @param array $params Default Plupload parameters array.
  2713. */
  2714. $params = apply_filters( 'plupload_default_params', $params );
  2715. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  2716. $defaults['multipart_params'] = $params;
  2717. $settings = array(
  2718. 'defaults' => $defaults,
  2719. 'browser' => array(
  2720. 'mobile' => wp_is_mobile(),
  2721. 'supported' => _device_can_upload(),
  2722. ),
  2723. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  2724. );
  2725. $script = 'var _wpPluploadSettings = ' . wp_json_encode( $settings ) . ';';
  2726. if ( $data )
  2727. $script = "$data\n$script";
  2728. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  2729. }
  2730. /**
  2731. * Prepares an attachment post object for JS, where it is expected
  2732. * to be JSON-encoded and fit into an Attachment model.
  2733. *
  2734. * @since 3.5.0
  2735. *
  2736. * @param mixed $attachment Attachment ID or object.
  2737. * @return array|void Array of attachment details.
  2738. */
  2739. function wp_prepare_attachment_for_js( $attachment ) {
  2740. if ( ! $attachment = get_post( $attachment ) )
  2741. return;
  2742. if ( 'attachment' != $attachment->post_type )
  2743. return;
  2744. $meta = wp_get_attachment_metadata( $attachment->ID );
  2745. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  2746. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  2747. else
  2748. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  2749. $attachment_url = wp_get_attachment_url( $attachment->ID );
  2750. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  2751. $response = array(
  2752. 'id' => $attachment->ID,
  2753. 'title' => $attachment->post_title,
  2754. 'filename' => wp_basename( get_attached_file( $attachment->ID ) ),
  2755. 'url' => $attachment_url,
  2756. 'link' => get_attachment_link( $attachment->ID ),
  2757. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  2758. 'author' => $attachment->post_author,
  2759. 'description' => $attachment->post_content,
  2760. 'caption' => $attachment->post_excerpt,
  2761. 'name' => $attachment->post_name,
  2762. 'status' => $attachment->post_status,
  2763. 'uploadedTo' => $attachment->post_parent,
  2764. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  2765. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  2766. 'menuOrder' => $attachment->menu_order,
  2767. 'mime' => $attachment->post_mime_type,
  2768. 'type' => $type,
  2769. 'subtype' => $subtype,
  2770. 'icon' => wp_mime_type_icon( $attachment->ID ),
  2771. 'dateFormatted' => mysql2date( __( 'F j, Y' ), $attachment->post_date ),
  2772. 'nonces' => array(
  2773. 'update' => false,
  2774. 'delete' => false,
  2775. 'edit' => false
  2776. ),
  2777. 'editLink' => false,
  2778. 'meta' => false,
  2779. );
  2780. $author = new WP_User( $attachment->post_author );
  2781. if ( $author->exists() ) {
  2782. $response['authorName'] = html_entity_decode( $author->display_name, ENT_QUOTES, get_bloginfo( 'charset' ) );
  2783. } else {
  2784. $response['authorName'] = __( '(no author)' );
  2785. }
  2786. if ( $attachment->post_parent ) {
  2787. $post_parent = get_post( $attachment->post_parent );
  2788. } else {
  2789. $post_parent = false;
  2790. }
  2791. if ( $post_parent ) {
  2792. $parent_type = get_post_type_object( $post_parent->post_type );
  2793. if ( $parent_type && $parent_type->show_ui && current_user_can( 'edit_post', $attachment->post_parent ) ) {
  2794. $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
  2795. }
  2796. if ( $parent_type && current_user_can( 'read_post', $attachment->post_parent ) ) {
  2797. $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(no title)' );
  2798. }
  2799. }
  2800. $attached_file = get_attached_file( $attachment->ID );
  2801. if ( isset( $meta['filesize'] ) ) {
  2802. $bytes = $meta['filesize'];
  2803. } elseif ( file_exists( $attached_file ) ) {
  2804. $bytes = filesize( $attached_file );
  2805. } else {
  2806. $bytes = '';
  2807. }
  2808. if ( $bytes ) {
  2809. $response['filesizeInBytes'] = $bytes;
  2810. $response['filesizeHumanReadable'] = size_format( $bytes );
  2811. }
  2812. $context = get_post_meta( $attachment->ID, '_wp_attachment_context', true );
  2813. $response['context'] = ( $context ) ? $context : '';
  2814. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  2815. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  2816. $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  2817. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  2818. }
  2819. if ( current_user_can( 'delete_post', $attachment->ID ) )
  2820. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  2821. if ( $meta && ( 'image' === $type || ! empty( $meta['sizes'] ) ) ) {
  2822. $sizes = array();
  2823. /** This filter is documented in wp-admin/includes/media.php */
  2824. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  2825. 'thumbnail' => __('Thumbnail'),
  2826. 'medium' => __('Medium'),
  2827. 'large' => __('Large'),
  2828. 'full' => __('Full Size'),
  2829. ) );
  2830. unset( $possible_sizes['full'] );
  2831. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  2832. // First: run the image_downsize filter. If it returns something, we can use its data.
  2833. // If the filter does not return something, then image_downsize() is just an expensive
  2834. // way to check the image metadata, which we do second.
  2835. foreach ( $possible_sizes as $size => $label ) {
  2836. /** This filter is documented in wp-includes/media.php */
  2837. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  2838. if ( empty( $downsize[3] ) ) {
  2839. continue;
  2840. }
  2841. $sizes[ $size ] = array(
  2842. 'height' => $downsize[2],
  2843. 'width' => $downsize[1],
  2844. 'url' => $downsize[0],
  2845. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  2846. );
  2847. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  2848. // Nothing from the filter, so consult image metadata if we have it.
  2849. $size_meta = $meta['sizes'][ $size ];
  2850. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  2851. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  2852. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  2853. $sizes[ $size ] = array(
  2854. 'height' => $height,
  2855. 'width' => $width,
  2856. 'url' => $base_url . $size_meta['file'],
  2857. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  2858. );
  2859. }
  2860. }
  2861. if ( 'image' === $type ) {
  2862. $sizes['full'] = array( 'url' => $attachment_url );
  2863. if ( isset( $meta['height'], $meta['width'] ) ) {
  2864. $sizes['full']['height'] = $meta['height'];
  2865. $sizes['full']['width'] = $meta['width'];
  2866. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  2867. }
  2868. $response = array_merge( $response, $sizes['full'] );
  2869. } elseif ( $meta['sizes']['full']['file'] ) {
  2870. $sizes['full'] = array(
  2871. 'url' => $base_url . $meta['sizes']['full']['file'],
  2872. 'height' => $meta['sizes']['full']['height'],
  2873. 'width' => $meta['sizes']['full']['width'],
  2874. 'orientation' => $meta['sizes']['full']['height'] > $meta['sizes']['full']['width'] ? 'portrait' : 'landscape'
  2875. );
  2876. }
  2877. $response = array_merge( $response, array( 'sizes' => $sizes ) );
  2878. }
  2879. if ( $meta && 'video' === $type ) {
  2880. if ( isset( $meta['width'] ) )
  2881. $response['width'] = (int) $meta['width'];
  2882. if ( isset( $meta['height'] ) )
  2883. $response['height'] = (int) $meta['height'];
  2884. }
  2885. if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  2886. if ( isset( $meta['length_formatted'] ) )
  2887. $response['fileLength'] = $meta['length_formatted'];
  2888. $response['meta'] = array();
  2889. foreach ( wp_get_attachment_id3_keys( $attachment, 'js' ) as $key => $label ) {
  2890. $response['meta'][ $key ] = false;
  2891. if ( ! empty( $meta[ $key ] ) ) {
  2892. $response['meta'][ $key ] = $meta[ $key ];
  2893. }
  2894. }
  2895. $id = get_post_thumbnail_id( $attachment->ID );
  2896. if ( ! empty( $id ) ) {
  2897. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  2898. $response['image'] = compact( 'src', 'width', 'height' );
  2899. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  2900. $response['thumb'] = compact( 'src', 'width', 'height' );
  2901. } else {
  2902. $src = wp_mime_type_icon( $attachment->ID );
  2903. $width = 48;
  2904. $height = 64;
  2905. $response['image'] = compact( 'src', 'width', 'height' );
  2906. $response['thumb'] = compact( 'src', 'width', 'height' );
  2907. }
  2908. }
  2909. if ( function_exists('get_compat_media_markup') )
  2910. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  2911. /**
  2912. * Filters the attachment data prepared for JavaScript.
  2913. *
  2914. * @since 3.5.0
  2915. *
  2916. * @param array $response Array of prepared attachment data.
  2917. * @param int|object $attachment Attachment ID or object.
  2918. * @param array $meta Array of attachment meta data.
  2919. */
  2920. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  2921. }
  2922. /**
  2923. * Enqueues all scripts, styles, settings, and templates necessary to use
  2924. * all media JS APIs.
  2925. *
  2926. * @since 3.5.0
  2927. *
  2928. * @global int $content_width
  2929. * @global wpdb $wpdb
  2930. * @global WP_Locale $wp_locale
  2931. *
  2932. * @param array $args {
  2933. * Arguments for enqueuing media scripts.
  2934. *
  2935. * @type int|WP_Post A post object or ID.
  2936. * }
  2937. */
  2938. function wp_enqueue_media( $args = array() ) {
  2939. // Enqueue me just once per page, please.
  2940. if ( did_action( 'wp_enqueue_media' ) )
  2941. return;
  2942. global $content_width, $wpdb, $wp_locale;
  2943. $defaults = array(
  2944. 'post' => null,
  2945. );
  2946. $args = wp_parse_args( $args, $defaults );
  2947. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  2948. // to ensure plugins will work. We will then unset those tabs.
  2949. $tabs = array(
  2950. // handler action suffix => tab label
  2951. 'type' => '',
  2952. 'type_url' => '',
  2953. 'gallery' => '',
  2954. 'library' => '',
  2955. );
  2956. /** This filter is documented in wp-admin/includes/media.php */
  2957. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  2958. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  2959. $props = array(
  2960. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  2961. 'align' => get_option( 'image_default_align' ), // empty default
  2962. 'size' => get_option( 'image_default_size' ), // empty default
  2963. );
  2964. $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
  2965. $mimes = get_allowed_mime_types();
  2966. $ext_mimes = array();
  2967. foreach ( $exts as $ext ) {
  2968. foreach ( $mimes as $ext_preg => $mime_match ) {
  2969. if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
  2970. $ext_mimes[ $ext ] = $mime_match;
  2971. break;
  2972. }
  2973. }
  2974. }
  2975. /**
  2976. * Allows showing or hiding the "Create Audio Playlist" button in the media library.
  2977. *
  2978. * By default, the "Create Audio Playlist" button will always be shown in
  2979. * the media library. If this filter returns `null`, a query will be run
  2980. * to determine whether the media library contains any audio items. This
  2981. * was the default behavior prior to version 4.8.0, but this query is
  2982. * expensive for large media libraries.
  2983. *
  2984. * @since 4.7.4
  2985. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  2986. *
  2987. * @link https://core.trac.wordpress.org/ticket/31071
  2988. *
  2989. * @param bool|null Whether to show the button, or `null` to decide based
  2990. * on whether any audio files exist in the media library.
  2991. */
  2992. $show_audio_playlist = apply_filters( 'media_library_show_audio_playlist', true );
  2993. if ( null === $show_audio_playlist ) {
  2994. $show_audio_playlist = $wpdb->get_var( "
  2995. SELECT ID
  2996. FROM $wpdb->posts
  2997. WHERE post_type = 'attachment'
  2998. AND post_mime_type LIKE 'audio%'
  2999. LIMIT 1
  3000. " );
  3001. }
  3002. /**
  3003. * Allows showing or hiding the "Create Video Playlist" button in the media library.
  3004. *
  3005. * By default, the "Create Video Playlist" button will always be shown in
  3006. * the media library. If this filter returns `null`, a query will be run
  3007. * to determine whether the media library contains any video items. This
  3008. * was the default behavior prior to version 4.8.0, but this query is
  3009. * expensive for large media libraries.
  3010. *
  3011. * @since 4.7.4
  3012. * @since 4.8.0 The filter's default value is `true` rather than `null`.
  3013. *
  3014. * @link https://core.trac.wordpress.org/ticket/31071
  3015. *
  3016. * @param bool|null Whether to show the button, or `null` to decide based
  3017. * on whether any video files exist in the media library.
  3018. */
  3019. $show_video_playlist = apply_filters( 'media_library_show_video_playlist', true );
  3020. if ( null === $show_video_playlist ) {
  3021. $show_video_playlist = $wpdb->get_var( "
  3022. SELECT ID
  3023. FROM $wpdb->posts
  3024. WHERE post_type = 'attachment'
  3025. AND post_mime_type LIKE 'video%'
  3026. LIMIT 1
  3027. " );
  3028. }
  3029. /**
  3030. * Allows overriding the list of months displayed in the media library.
  3031. *
  3032. * By default (if this filter does not return an array), a query will be
  3033. * run to determine the months that have media items. This query can be
  3034. * expensive for large media libraries, so it may be desirable for sites to
  3035. * override this behavior.
  3036. *
  3037. * @since 4.7.4
  3038. *
  3039. * @link https://core.trac.wordpress.org/ticket/31071
  3040. *
  3041. * @param array|null An array of objects with `month` and `year`
  3042. * properties, or `null` (or any other non-array value)
  3043. * for default behavior.
  3044. */
  3045. $months = apply_filters( 'media_library_months_with_files', null );
  3046. if ( ! is_array( $months ) ) {
  3047. $months = $wpdb->get_results( $wpdb->prepare( "
  3048. SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
  3049. FROM $wpdb->posts
  3050. WHERE post_type = %s
  3051. ORDER BY post_date DESC
  3052. ", 'attachment' ) );
  3053. }
  3054. foreach ( $months as $month_year ) {
  3055. $month_year->text = sprintf( __( '%1$s %2$d' ), $wp_locale->get_month( $month_year->month ), $month_year->year );
  3056. }
  3057. $settings = array(
  3058. 'tabs' => $tabs,
  3059. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  3060. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  3061. /** This filter is documented in wp-admin/includes/media.php */
  3062. 'captions' => ! apply_filters( 'disable_captions', '' ),
  3063. 'nonce' => array(
  3064. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  3065. ),
  3066. 'post' => array(
  3067. 'id' => 0,
  3068. ),
  3069. 'defaultProps' => $props,
  3070. 'attachmentCounts' => array(
  3071. 'audio' => ( $show_audio_playlist ) ? 1 : 0,
  3072. 'video' => ( $show_video_playlist ) ? 1 : 0,
  3073. ),
  3074. 'oEmbedProxyUrl' => rest_url( 'oembed/1.0/proxy' ),
  3075. 'embedExts' => $exts,
  3076. 'embedMimes' => $ext_mimes,
  3077. 'contentWidth' => $content_width,
  3078. 'months' => $months,
  3079. 'mediaTrash' => MEDIA_TRASH ? 1 : 0,
  3080. );
  3081. $post = null;
  3082. if ( isset( $args['post'] ) ) {
  3083. $post = get_post( $args['post'] );
  3084. $settings['post'] = array(
  3085. 'id' => $post->ID,
  3086. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  3087. );
  3088. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
  3089. if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
  3090. if ( wp_attachment_is( 'audio', $post ) ) {
  3091. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  3092. } elseif ( wp_attachment_is( 'video', $post ) ) {
  3093. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  3094. }
  3095. }
  3096. if ( $thumbnail_support ) {
  3097. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  3098. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  3099. }
  3100. }
  3101. if ( $post ) {
  3102. $post_type_object = get_post_type_object( $post->post_type );
  3103. } else {
  3104. $post_type_object = get_post_type_object( 'post' );
  3105. }
  3106. $strings = array(
  3107. // Generic
  3108. 'url' => __( 'URL' ),
  3109. 'addMedia' => __( 'Add Media' ),
  3110. 'search' => __( 'Search' ),
  3111. 'select' => __( 'Select' ),
  3112. 'cancel' => __( 'Cancel' ),
  3113. 'update' => __( 'Update' ),
  3114. 'replace' => __( 'Replace' ),
  3115. 'remove' => __( 'Remove' ),
  3116. 'back' => __( 'Back' ),
  3117. /* translators: This is a would-be plural string used in the media manager.
  3118. If there is not a word you can use in your language to avoid issues with the
  3119. lack of plural support here, turn it into "selected: %d" then translate it.
  3120. */
  3121. 'selected' => __( '%d selected' ),
  3122. 'dragInfo' => __( 'Drag and drop to reorder media files.' ),
  3123. // Upload
  3124. 'uploadFilesTitle' => __( 'Upload Files' ),
  3125. 'uploadImagesTitle' => __( 'Upload Images' ),
  3126. // Library
  3127. 'mediaLibraryTitle' => __( 'Media Library' ),
  3128. 'insertMediaTitle' => __( 'Add Media' ),
  3129. 'createNewGallery' => __( 'Create a new gallery' ),
  3130. 'createNewPlaylist' => __( 'Create a new playlist' ),
  3131. 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  3132. 'returnToLibrary' => __( '&#8592; Return to library' ),
  3133. 'allMediaItems' => __( 'All media items' ),
  3134. 'allDates' => __( 'All dates' ),
  3135. 'noItemsFound' => __( 'No items found.' ),
  3136. 'insertIntoPost' => $post_type_object->labels->insert_into_item,
  3137. 'unattached' => __( 'Unattached' ),
  3138. 'trash' => _x( 'Trash', 'noun' ),
  3139. 'uploadedToThisPost' => $post_type_object->labels->uploaded_to_this_item,
  3140. 'warnDelete' => __( "You are about to permanently delete this item from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3141. 'warnBulkDelete' => __( "You are about to permanently delete these items from your site.\nThis action cannot be undone.\n 'Cancel' to stop, 'OK' to delete." ),
  3142. 'warnBulkTrash' => __( "You are about to trash these items.\n 'Cancel' to stop, 'OK' to delete." ),
  3143. 'bulkSelect' => __( 'Bulk Select' ),
  3144. 'cancelSelection' => __( 'Cancel Selection' ),
  3145. 'trashSelected' => __( 'Trash Selected' ),
  3146. 'untrashSelected' => __( 'Untrash Selected' ),
  3147. 'deleteSelected' => __( 'Delete Selected' ),
  3148. 'deletePermanently' => __( 'Delete Permanently' ),
  3149. 'apply' => __( 'Apply' ),
  3150. 'filterByDate' => __( 'Filter by date' ),
  3151. 'filterByType' => __( 'Filter by type' ),
  3152. 'searchMediaLabel' => __( 'Search Media' ),
  3153. 'searchMediaPlaceholder' => __( 'Search media items...' ), // placeholder (no ellipsis)
  3154. 'noMedia' => __( 'No media files found.' ),
  3155. // Library Details
  3156. 'attachmentDetails' => __( 'Attachment Details' ),
  3157. // From URL
  3158. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  3159. // Featured Images
  3160. 'setFeaturedImageTitle' => $post_type_object->labels->featured_image,
  3161. 'setFeaturedImage' => $post_type_object->labels->set_featured_image,
  3162. // Gallery
  3163. 'createGalleryTitle' => __( 'Create Gallery' ),
  3164. 'editGalleryTitle' => __( 'Edit Gallery' ),
  3165. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  3166. 'insertGallery' => __( 'Insert gallery' ),
  3167. 'updateGallery' => __( 'Update gallery' ),
  3168. 'addToGallery' => __( 'Add to gallery' ),
  3169. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  3170. 'reverseOrder' => __( 'Reverse order' ),
  3171. // Edit Image
  3172. 'imageDetailsTitle' => __( 'Image Details' ),
  3173. 'imageReplaceTitle' => __( 'Replace Image' ),
  3174. 'imageDetailsCancel' => __( 'Cancel Edit' ),
  3175. 'editImage' => __( 'Edit Image' ),
  3176. // Crop Image
  3177. 'chooseImage' => __( 'Choose Image' ),
  3178. 'selectAndCrop' => __( 'Select and Crop' ),
  3179. 'skipCropping' => __( 'Skip Cropping' ),
  3180. 'cropImage' => __( 'Crop Image' ),
  3181. 'cropYourImage' => __( 'Crop your image' ),
  3182. 'cropping' => __( 'Cropping&hellip;' ),
  3183. /* translators: 1: suggested width number, 2: suggested height number. */
  3184. 'suggestedDimensions' => __( 'Suggested image dimensions: %1$s by %2$s pixels.' ),
  3185. 'cropError' => __( 'There has been an error cropping your image.' ),
  3186. // Edit Audio
  3187. 'audioDetailsTitle' => __( 'Audio Details' ),
  3188. 'audioReplaceTitle' => __( 'Replace Audio' ),
  3189. 'audioAddSourceTitle' => __( 'Add Audio Source' ),
  3190. 'audioDetailsCancel' => __( 'Cancel Edit' ),
  3191. // Edit Video
  3192. 'videoDetailsTitle' => __( 'Video Details' ),
  3193. 'videoReplaceTitle' => __( 'Replace Video' ),
  3194. 'videoAddSourceTitle' => __( 'Add Video Source' ),
  3195. 'videoDetailsCancel' => __( 'Cancel Edit' ),
  3196. 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
  3197. 'videoAddTrackTitle' => __( 'Add Subtitles' ),
  3198. // Playlist
  3199. 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
  3200. 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
  3201. 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
  3202. 'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
  3203. 'insertPlaylist' => __( 'Insert audio playlist' ),
  3204. 'updatePlaylist' => __( 'Update audio playlist' ),
  3205. 'addToPlaylist' => __( 'Add to audio playlist' ),
  3206. 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
  3207. // Video Playlist
  3208. 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
  3209. 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
  3210. 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
  3211. 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
  3212. 'insertVideoPlaylist' => __( 'Insert video playlist' ),
  3213. 'updateVideoPlaylist' => __( 'Update video playlist' ),
  3214. 'addToVideoPlaylist' => __( 'Add to video playlist' ),
  3215. 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
  3216. );
  3217. /**
  3218. * Filters the media view settings.
  3219. *
  3220. * @since 3.5.0
  3221. *
  3222. * @param array $settings List of media view settings.
  3223. * @param WP_Post $post Post object.
  3224. */
  3225. $settings = apply_filters( 'media_view_settings', $settings, $post );
  3226. /**
  3227. * Filters the media view strings.
  3228. *
  3229. * @since 3.5.0
  3230. *
  3231. * @param array $strings List of media view strings.
  3232. * @param WP_Post $post Post object.
  3233. */
  3234. $strings = apply_filters( 'media_view_strings', $strings, $post );
  3235. $strings['settings'] = $settings;
  3236. // Ensure we enqueue media-editor first, that way media-views is
  3237. // registered internally before we try to localize it. see #24724.
  3238. wp_enqueue_script( 'media-editor' );
  3239. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  3240. wp_enqueue_script( 'media-audiovideo' );
  3241. wp_enqueue_style( 'media-views' );
  3242. if ( is_admin() ) {
  3243. wp_enqueue_script( 'mce-view' );
  3244. wp_enqueue_script( 'image-edit' );
  3245. }
  3246. wp_enqueue_style( 'imgareaselect' );
  3247. wp_plupload_default_settings();
  3248. require_once ABSPATH . WPINC . '/media-template.php';
  3249. add_action( 'admin_footer', 'wp_print_media_templates' );
  3250. add_action( 'wp_footer', 'wp_print_media_templates' );
  3251. add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
  3252. /**
  3253. * Fires at the conclusion of wp_enqueue_media().
  3254. *
  3255. * @since 3.5.0
  3256. */
  3257. do_action( 'wp_enqueue_media' );
  3258. }
  3259. /**
  3260. * Retrieves media attached to the passed post.
  3261. *
  3262. * @since 3.6.0
  3263. *
  3264. * @param string $type Mime type.
  3265. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  3266. * @return array Found attachments.
  3267. */
  3268. function get_attached_media( $type, $post = 0 ) {
  3269. if ( ! $post = get_post( $post ) )
  3270. return array();
  3271. $args = array(
  3272. 'post_parent' => $post->ID,
  3273. 'post_type' => 'attachment',
  3274. 'post_mime_type' => $type,
  3275. 'posts_per_page' => -1,
  3276. 'orderby' => 'menu_order',
  3277. 'order' => 'ASC',
  3278. );
  3279. /**
  3280. * Filters arguments used to retrieve media attached to the given post.
  3281. *
  3282. * @since 3.6.0
  3283. *
  3284. * @param array $args Post query arguments.
  3285. * @param string $type Mime type of the desired media.
  3286. * @param mixed $post Post ID or object.
  3287. */
  3288. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  3289. $children = get_children( $args );
  3290. /**
  3291. * Filters the list of media attached to the given post.
  3292. *
  3293. * @since 3.6.0
  3294. *
  3295. * @param array $children Associative array of media attached to the given post.
  3296. * @param string $type Mime type of the media desired.
  3297. * @param mixed $post Post ID or object.
  3298. */
  3299. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  3300. }
  3301. /**
  3302. * Check the content blob for an audio, video, object, embed, or iframe tags.
  3303. *
  3304. * @since 3.6.0
  3305. *
  3306. * @param string $content A string which might contain media data.
  3307. * @param array $types An array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'.
  3308. * @return array A list of found HTML media embeds.
  3309. */
  3310. function get_media_embedded_in_content( $content, $types = null ) {
  3311. $html = array();
  3312. /**
  3313. * Filters the embedded media types that are allowed to be returned from the content blob.
  3314. *
  3315. * @since 4.2.0
  3316. *
  3317. * @param array $allowed_media_types An array of allowed media types. Default media types are
  3318. * 'audio', 'video', 'object', 'embed', and 'iframe'.
  3319. */
  3320. $allowed_media_types = apply_filters( 'media_embedded_in_content_allowed_types', array( 'audio', 'video', 'object', 'embed', 'iframe' ) );
  3321. if ( ! empty( $types ) ) {
  3322. if ( ! is_array( $types ) ) {
  3323. $types = array( $types );
  3324. }
  3325. $allowed_media_types = array_intersect( $allowed_media_types, $types );
  3326. }
  3327. $tags = implode( '|', $allowed_media_types );
  3328. if ( preg_match_all( '#<(?P<tag>' . $tags . ')[^<]*?(?:>[\s\S]*?<\/(?P=tag)>|\s*\/>)#', $content, $matches ) ) {
  3329. foreach ( $matches[0] as $match ) {
  3330. $html[] = $match;
  3331. }
  3332. }
  3333. return $html;
  3334. }
  3335. /**
  3336. * Retrieves galleries from the passed post's content.
  3337. *
  3338. * @since 3.6.0
  3339. *
  3340. * @param int|WP_Post $post Post ID or object.
  3341. * @param bool $html Optional. Whether to return HTML or data in the array. Default true.
  3342. * @return array A list of arrays, each containing gallery data and srcs parsed
  3343. * from the expanded shortcode.
  3344. */
  3345. function get_post_galleries( $post, $html = true ) {
  3346. if ( ! $post = get_post( $post ) )
  3347. return array();
  3348. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  3349. return array();
  3350. $galleries = array();
  3351. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  3352. foreach ( $matches as $shortcode ) {
  3353. if ( 'gallery' === $shortcode[2] ) {
  3354. $srcs = array();
  3355. $shortcode_attrs = shortcode_parse_atts( $shortcode[3] );
  3356. if ( ! is_array( $shortcode_attrs ) ) {
  3357. $shortcode_attrs = array();
  3358. }
  3359. // Specify the post id of the gallery we're viewing if the shortcode doesn't reference another post already.
  3360. if ( ! isset( $shortcode_attrs['id'] ) ) {
  3361. $shortcode[3] .= ' id="' . intval( $post->ID ) . '"';
  3362. }
  3363. $gallery = do_shortcode_tag( $shortcode );
  3364. if ( $html ) {
  3365. $galleries[] = $gallery;
  3366. } else {
  3367. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  3368. if ( ! empty( $src ) ) {
  3369. foreach ( $src as $s ) {
  3370. $srcs[] = $s[2];
  3371. }
  3372. }
  3373. $galleries[] = array_merge(
  3374. $shortcode_attrs,
  3375. array(
  3376. 'src' => array_values( array_unique( $srcs ) )
  3377. )
  3378. );
  3379. }
  3380. }
  3381. }
  3382. }
  3383. /**
  3384. * Filters the list of all found galleries in the given post.
  3385. *
  3386. * @since 3.6.0
  3387. *
  3388. * @param array $galleries Associative array of all found post galleries.
  3389. * @param WP_Post $post Post object.
  3390. */
  3391. return apply_filters( 'get_post_galleries', $galleries, $post );
  3392. }
  3393. /**
  3394. * Check a specified post's content for gallery and, if present, return the first
  3395. *
  3396. * @since 3.6.0
  3397. *
  3398. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  3399. * @param bool $html Optional. Whether to return HTML or data. Default is true.
  3400. * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  3401. */
  3402. function get_post_gallery( $post = 0, $html = true ) {
  3403. $galleries = get_post_galleries( $post, $html );
  3404. $gallery = reset( $galleries );
  3405. /**
  3406. * Filters the first-found post gallery.
  3407. *
  3408. * @since 3.6.0
  3409. *
  3410. * @param array $gallery The first-found post gallery.
  3411. * @param int|WP_Post $post Post ID or object.
  3412. * @param array $galleries Associative array of all found post galleries.
  3413. */
  3414. return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  3415. }
  3416. /**
  3417. * Retrieve the image srcs from galleries from a post's content, if present
  3418. *
  3419. * @since 3.6.0
  3420. *
  3421. * @see get_post_galleries()
  3422. *
  3423. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  3424. * @return array A list of lists, each containing image srcs parsed.
  3425. * from an expanded shortcode
  3426. */
  3427. function get_post_galleries_images( $post = 0 ) {
  3428. $galleries = get_post_galleries( $post, false );
  3429. return wp_list_pluck( $galleries, 'src' );
  3430. }
  3431. /**
  3432. * Checks a post's content for galleries and return the image srcs for the first found gallery
  3433. *
  3434. * @since 3.6.0
  3435. *
  3436. * @see get_post_gallery()
  3437. *
  3438. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global `$post`.
  3439. * @return array A list of a gallery's image srcs in order.
  3440. */
  3441. function get_post_gallery_images( $post = 0 ) {
  3442. $gallery = get_post_gallery( $post, false );
  3443. return empty( $gallery['src'] ) ? array() : $gallery['src'];
  3444. }
  3445. /**
  3446. * Maybe attempts to generate attachment metadata, if missing.
  3447. *
  3448. * @since 3.9.0
  3449. *
  3450. * @param WP_Post $attachment Attachment object.
  3451. */
  3452. function wp_maybe_generate_attachment_metadata( $attachment ) {
  3453. if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
  3454. return;
  3455. }
  3456. $file = get_attached_file( $attachment_id );
  3457. $meta = wp_get_attachment_metadata( $attachment_id );
  3458. if ( empty( $meta ) && file_exists( $file ) ) {
  3459. $_meta = get_post_meta( $attachment_id );
  3460. $regeneration_lock = 'wp_generating_att_' . $attachment_id;
  3461. if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
  3462. set_transient( $regeneration_lock, $file );
  3463. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
  3464. delete_transient( $regeneration_lock );
  3465. }
  3466. }
  3467. }
  3468. /**
  3469. * Tries to convert an attachment URL into a post ID.
  3470. *
  3471. * @since 4.0.0
  3472. *
  3473. * @global wpdb $wpdb WordPress database abstraction object.
  3474. *
  3475. * @param string $url The URL to resolve.
  3476. * @return int The found post ID, or 0 on failure.
  3477. */
  3478. function attachment_url_to_postid( $url ) {
  3479. global $wpdb;
  3480. $dir = wp_get_upload_dir();
  3481. $path = $url;
  3482. $site_url = parse_url( $dir['url'] );
  3483. $image_path = parse_url( $path );
  3484. //force the protocols to match if needed
  3485. if ( isset( $image_path['scheme'] ) && ( $image_path['scheme'] !== $site_url['scheme'] ) ) {
  3486. $path = str_replace( $image_path['scheme'], $site_url['scheme'], $path );
  3487. }
  3488. if ( 0 === strpos( $path, $dir['baseurl'] . '/' ) ) {
  3489. $path = substr( $path, strlen( $dir['baseurl'] . '/' ) );
  3490. }
  3491. $sql = $wpdb->prepare(
  3492. "SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
  3493. $path
  3494. );
  3495. $post_id = $wpdb->get_var( $sql );
  3496. /**
  3497. * Filters an attachment id found by URL.
  3498. *
  3499. * @since 4.2.0
  3500. *
  3501. * @param int|null $post_id The post_id (if any) found by the function.
  3502. * @param string $url The URL being looked up.
  3503. */
  3504. return (int) apply_filters( 'attachment_url_to_postid', $post_id, $url );
  3505. }
  3506. /**
  3507. * Returns the URLs for CSS files used in an iframe-sandbox'd TinyMCE media view.
  3508. *
  3509. * @since 4.0.0
  3510. *
  3511. * @return array The relevant CSS file URLs.
  3512. */
  3513. function wpview_media_sandbox_styles() {
  3514. $version = 'ver=' . get_bloginfo( 'version' );
  3515. $mediaelement = includes_url( "js/mediaelement/mediaelementplayer-legacy.min.css?$version" );
  3516. $wpmediaelement = includes_url( "js/mediaelement/wp-mediaelement.css?$version" );
  3517. return array( $mediaelement, $wpmediaelement );
  3518. }