PageRenderTime 69ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/APP/wp-includes/media.php

https://bitbucket.org/AFelipeTrujillo/goblog
PHP | 3105 lines | 1512 code | 341 blank | 1252 comment | 314 complexity | 8fa567db388bf940d839361afc3cc6a4 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * WordPress API for media display.
  4. *
  5. * @package WordPress
  6. * @subpackage Media
  7. */
  8. /**
  9. * Scale down the default size of an image.
  10. *
  11. * This is so that the image is a better fit for the editor and theme.
  12. *
  13. * The $size parameter accepts either an array or a string. The supported string
  14. * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at
  15. * 128 width and 96 height in pixels. Also supported for the string value is
  16. * 'medium' and 'full'. The 'full' isn't actually supported, but any value other
  17. * than the supported will result in the content_width size or 500 if that is
  18. * not set.
  19. *
  20. * Finally, there is a filter named 'editor_max_image_size', that will be called
  21. * on the calculated array for width and height, respectively. The second
  22. * parameter will be the value that was in the $size parameter. The returned
  23. * type for the hook is an array with the width as the first element and the
  24. * height as the second element.
  25. *
  26. * @since 2.5.0
  27. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  28. *
  29. * @param int $width Width of the image
  30. * @param int $height Height of the image
  31. * @param string|array $size Size of what the result image should be.
  32. * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor)
  33. * @return array Width and height of what the result image should resize to.
  34. */
  35. function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) {
  36. global $content_width, $_wp_additional_image_sizes;
  37. if ( ! $context )
  38. $context = is_admin() ? 'edit' : 'display';
  39. if ( is_array($size) ) {
  40. $max_width = $size[0];
  41. $max_height = $size[1];
  42. }
  43. elseif ( $size == 'thumb' || $size == 'thumbnail' ) {
  44. $max_width = intval(get_option('thumbnail_size_w'));
  45. $max_height = intval(get_option('thumbnail_size_h'));
  46. // last chance thumbnail size defaults
  47. if ( !$max_width && !$max_height ) {
  48. $max_width = 128;
  49. $max_height = 96;
  50. }
  51. }
  52. elseif ( $size == 'medium' ) {
  53. $max_width = intval(get_option('medium_size_w'));
  54. $max_height = intval(get_option('medium_size_h'));
  55. // if no width is set, default to the theme content width if available
  56. }
  57. elseif ( $size == 'large' ) {
  58. // We're inserting a large size image into the editor. If it's a really
  59. // big image we'll scale it down to fit reasonably within the editor
  60. // itself, and within the theme's content width if it's known. The user
  61. // can resize it in the editor if they wish.
  62. $max_width = intval(get_option('large_size_w'));
  63. $max_height = intval(get_option('large_size_h'));
  64. if ( intval($content_width) > 0 )
  65. $max_width = min( intval($content_width), $max_width );
  66. } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) {
  67. $max_width = intval( $_wp_additional_image_sizes[$size]['width'] );
  68. $max_height = intval( $_wp_additional_image_sizes[$size]['height'] );
  69. if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing.
  70. $max_width = min( intval($content_width), $max_width );
  71. }
  72. // $size == 'full' has no constraint
  73. else {
  74. $max_width = $width;
  75. $max_height = $height;
  76. }
  77. /**
  78. * Filter the maximum image size dimensions for the editor.
  79. *
  80. * @since 2.5.0
  81. *
  82. * @param array $max_image_size An array with the width as the first element,
  83. * and the height as the second element.
  84. * @param string|array $size Size of what the result image should be.
  85. * @param string $context The context the image is being resized for.
  86. * Possible values are 'display' (like in a theme)
  87. * or 'edit' (like inserting into an editor).
  88. */
  89. list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context );
  90. return wp_constrain_dimensions( $width, $height, $max_width, $max_height );
  91. }
  92. /**
  93. * Retrieve width and height attributes using given width and height values.
  94. *
  95. * Both attributes are required in the sense that both parameters must have a
  96. * value, but are optional in that if you set them to false or null, then they
  97. * will not be added to the returned string.
  98. *
  99. * You can set the value using a string, but it will only take numeric values.
  100. * If you wish to put 'px' after the numbers, then it will be stripped out of
  101. * the return.
  102. *
  103. * @since 2.5.0
  104. *
  105. * @param int|string $width Optional. Width attribute value.
  106. * @param int|string $height Optional. Height attribute value.
  107. * @return string HTML attributes for width and, or height.
  108. */
  109. function image_hwstring($width, $height) {
  110. $out = '';
  111. if ($width)
  112. $out .= 'width="'.intval($width).'" ';
  113. if ($height)
  114. $out .= 'height="'.intval($height).'" ';
  115. return $out;
  116. }
  117. /**
  118. * Scale an image to fit a particular size (such as 'thumb' or 'medium').
  119. *
  120. * Array with image url, width, height, and whether is intermediate size, in
  121. * that order is returned on success is returned. $is_intermediate is true if
  122. * $url is a resized image, false if it is the original.
  123. *
  124. * The URL might be the original image, or it might be a resized version. This
  125. * function won't create a new resized copy, it will just return an already
  126. * resized one if it exists.
  127. *
  128. * A plugin may use the 'image_downsize' filter to hook into and offer image
  129. * resizing services for images. The hook must return an array with the same
  130. * elements that are returned in the function. The first element being the URL
  131. * to the new image that was resized.
  132. *
  133. * @since 2.5.0
  134. *
  135. * @param int $id Attachment ID for image.
  136. * @param array|string $size Optional, default is 'medium'. Size of image, either array or string.
  137. * @return bool|array False on failure, array on success.
  138. */
  139. function image_downsize($id, $size = 'medium') {
  140. if ( !wp_attachment_is_image($id) )
  141. return false;
  142. /**
  143. * Filter whether to preempt the output of image_downsize().
  144. *
  145. * Passing a truthy value to the filter will effectively short-circuit
  146. * down-sizing the image, returning that value as output instead.
  147. *
  148. * @since 2.5.0
  149. *
  150. * @param bool $downsize Whether to short-circuit the image downsize. Default false.
  151. * @param int $id Attachment ID for image.
  152. * @param array|string $size Size of image, either array or string. Default 'medium'.
  153. */
  154. if ( $out = apply_filters( 'image_downsize', false, $id, $size ) ) {
  155. return $out;
  156. }
  157. $img_url = wp_get_attachment_url($id);
  158. $meta = wp_get_attachment_metadata($id);
  159. $width = $height = 0;
  160. $is_intermediate = false;
  161. $img_url_basename = wp_basename($img_url);
  162. // try for a new style intermediate size
  163. if ( $intermediate = image_get_intermediate_size($id, $size) ) {
  164. $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url);
  165. $width = $intermediate['width'];
  166. $height = $intermediate['height'];
  167. $is_intermediate = true;
  168. }
  169. elseif ( $size == 'thumbnail' ) {
  170. // fall back to the old thumbnail
  171. if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) {
  172. $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url);
  173. $width = $info[0];
  174. $height = $info[1];
  175. $is_intermediate = true;
  176. }
  177. }
  178. if ( !$width && !$height && isset( $meta['width'], $meta['height'] ) ) {
  179. // any other type: use the real image
  180. $width = $meta['width'];
  181. $height = $meta['height'];
  182. }
  183. if ( $img_url) {
  184. // we have the actual image size, but might need to further constrain it if content_width is narrower
  185. list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size );
  186. return array( $img_url, $width, $height, $is_intermediate );
  187. }
  188. return false;
  189. }
  190. /**
  191. * Register a new image size.
  192. *
  193. * Cropping behavior for the image size is dependent on the value of $crop:
  194. * 1. If false (default), images will be scaled, not cropped.
  195. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  196. * - x_crop_position accepts 'left' 'center', or 'right'.
  197. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  198. * Images will be cropped to the specified dimensions within the defined crop area.
  199. * 3. If true, images will be cropped to the specified dimensions using center positions.
  200. *
  201. * @since 2.9.0
  202. *
  203. * @param string $name Image size identifier.
  204. * @param int $width Image width in pixels.
  205. * @param int $height Image height in pixels.
  206. * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
  207. * An array can specify positioning of the crop area. Default false.
  208. * @return bool|array False, if no image was created. Metadata array on success.
  209. */
  210. function add_image_size( $name, $width = 0, $height = 0, $crop = false ) {
  211. global $_wp_additional_image_sizes;
  212. $_wp_additional_image_sizes[ $name ] = array(
  213. 'width' => absint( $width ),
  214. 'height' => absint( $height ),
  215. 'crop' => $crop,
  216. );
  217. }
  218. /**
  219. * Check if an image size exists.
  220. *
  221. * @since 3.9.0
  222. *
  223. * @param string $name The image size to check.
  224. * @return bool True if the image size exists, false if not.
  225. */
  226. function has_image_size( $name ) {
  227. global $_wp_additional_image_sizes;
  228. return isset( $_wp_additional_image_sizes[ $name ] );
  229. }
  230. /**
  231. * Remove a new image size.
  232. *
  233. * @since 3.9.0
  234. *
  235. * @param string $name The image size to remove.
  236. * @return bool True if the image size was successfully removed, false on failure.
  237. */
  238. function remove_image_size( $name ) {
  239. global $_wp_additional_image_sizes;
  240. if ( isset( $_wp_additional_image_sizes[ $name ] ) ) {
  241. unset( $_wp_additional_image_sizes[ $name ] );
  242. return true;
  243. }
  244. return false;
  245. }
  246. /**
  247. * Registers an image size for the post thumbnail.
  248. *
  249. * @since 2.9.0
  250. * @see add_image_size() for details on cropping behavior.
  251. *
  252. * @param int $width Image width in pixels.
  253. * @param int $height Image height in pixels.
  254. * @param bool|array $crop Optional. Whether to crop images to specified height and width or resize.
  255. * An array can specify positioning of the crop area. Default false.
  256. * @return bool|array False, if no image was created. Metadata array on success.
  257. */
  258. function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) {
  259. add_image_size( 'post-thumbnail', $width, $height, $crop );
  260. }
  261. /**
  262. * An <img src /> tag for an image attachment, scaling it down if requested.
  263. *
  264. * The filter 'get_image_tag_class' allows for changing the class name for the
  265. * image without having to use regular expressions on the HTML content. The
  266. * parameters are: what WordPress will use for the class, the Attachment ID,
  267. * image align value, and the size the image should be.
  268. *
  269. * The second filter 'get_image_tag' has the HTML content, which can then be
  270. * further manipulated by a plugin to change all attribute values and even HTML
  271. * content.
  272. *
  273. * @since 2.5.0
  274. *
  275. * @param int $id Attachment ID.
  276. * @param string $alt Image Description for the alt attribute.
  277. * @param string $title Image Description for the title attribute.
  278. * @param string $align Part of the class name for aligning the image.
  279. * @param string $size Optional. Default is 'medium'.
  280. * @return string HTML IMG element for given image attachment
  281. */
  282. function get_image_tag($id, $alt, $title, $align, $size='medium') {
  283. list( $img_src, $width, $height ) = image_downsize($id, $size);
  284. $hwstring = image_hwstring($width, $height);
  285. $title = $title ? 'title="' . esc_attr( $title ) . '" ' : '';
  286. $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id;
  287. /**
  288. * Filter the value of the attachment's image tag class attribute.
  289. *
  290. * @since 2.6.0
  291. *
  292. * @param string $class CSS class name or space-separated list of classes.
  293. * @param int $id Attachment ID.
  294. * @param string $align Part of the class name for aligning the image.
  295. * @param string $size Optional. Default is 'medium'.
  296. */
  297. $class = apply_filters( 'get_image_tag_class', $class, $id, $align, $size );
  298. $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />';
  299. /**
  300. * Filter the HTML content for the image tag.
  301. *
  302. * @since 2.6.0
  303. *
  304. * @param string $html HTML content for the image.
  305. * @param int $id Attachment ID.
  306. * @param string $alt Alternate text.
  307. * @param string $title Attachment title.
  308. * @param string $align Part of the class name for aligning the image.
  309. * @param string $size Optional. Default is 'medium'.
  310. */
  311. $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size );
  312. return $html;
  313. }
  314. /**
  315. * Calculates the new dimensions for a downsampled image.
  316. *
  317. * If either width or height are empty, no constraint is applied on
  318. * that dimension.
  319. *
  320. * @since 2.5.0
  321. *
  322. * @param int $current_width Current width of the image.
  323. * @param int $current_height Current height of the image.
  324. * @param int $max_width Optional. Maximum wanted width.
  325. * @param int $max_height Optional. Maximum wanted height.
  326. * @return array First item is the width, the second item is the height.
  327. */
  328. function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) {
  329. if ( !$max_width and !$max_height )
  330. return array( $current_width, $current_height );
  331. $width_ratio = $height_ratio = 1.0;
  332. $did_width = $did_height = false;
  333. if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) {
  334. $width_ratio = $max_width / $current_width;
  335. $did_width = true;
  336. }
  337. if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) {
  338. $height_ratio = $max_height / $current_height;
  339. $did_height = true;
  340. }
  341. // Calculate the larger/smaller ratios
  342. $smaller_ratio = min( $width_ratio, $height_ratio );
  343. $larger_ratio = max( $width_ratio, $height_ratio );
  344. if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height )
  345. // The larger ratio is too big. It would result in an overflow.
  346. $ratio = $smaller_ratio;
  347. else
  348. // The larger ratio fits, and is likely to be a more "snug" fit.
  349. $ratio = $larger_ratio;
  350. // Very small dimensions may result in 0, 1 should be the minimum.
  351. $w = max ( 1, intval( $current_width * $ratio ) );
  352. $h = max ( 1, intval( $current_height * $ratio ) );
  353. // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short
  354. // 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.
  355. // Thus we look for dimensions that are one pixel shy of the max value and bump them up
  356. if ( $did_width && $w == $max_width - 1 )
  357. $w = $max_width; // Round it up
  358. if ( $did_height && $h == $max_height - 1 )
  359. $h = $max_height; // Round it up
  360. return array( $w, $h );
  361. }
  362. /**
  363. * Retrieve calculated resize dimensions for use in WP_Image_Editor.
  364. *
  365. * Calculates dimensions and coordinates for a resized image that fits
  366. * within a specified width and height.
  367. *
  368. * Cropping behavior is dependent on the value of $crop:
  369. * 1. If false (default), images will not be cropped.
  370. * 2. If an array in the form of array( x_crop_position, y_crop_position ):
  371. * - x_crop_position accepts 'left' 'center', or 'right'.
  372. * - y_crop_position accepts 'top', 'center', or 'bottom'.
  373. * Images will be cropped to the specified dimensions within the defined crop area.
  374. * 3. If true, images will be cropped to the specified dimensions using center positions.
  375. *
  376. * @since 2.5.0
  377. *
  378. * @param int $orig_w Original width in pixels.
  379. * @param int $orig_h Original height in pixels.
  380. * @param int $dest_w New width in pixels.
  381. * @param int $dest_h New height in pixels.
  382. * @param bool|array $crop Optional. Whether to crop image to specified height and width or resize.
  383. * An array can specify positioning of the crop area. Default false.
  384. * @return bool|array False on failure. Returned array matches parameters for `imagecopyresampled()`.
  385. */
  386. function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) {
  387. if ($orig_w <= 0 || $orig_h <= 0)
  388. return false;
  389. // at least one of dest_w or dest_h must be specific
  390. if ($dest_w <= 0 && $dest_h <= 0)
  391. return false;
  392. /**
  393. * Filter whether to preempt calculating the image resize dimensions.
  394. *
  395. * Passing a non-null value to the filter will effectively short-circuit
  396. * image_resize_dimensions(), returning that value instead.
  397. *
  398. * @since 3.4.0
  399. *
  400. * @param null|mixed $null Whether to preempt output of the resize dimensions.
  401. * @param int $orig_w Original width in pixels.
  402. * @param int $orig_h Original height in pixels.
  403. * @param int $dest_w New width in pixels.
  404. * @param int $dest_h New height in pixels.
  405. * @param bool|array $crop Whether to crop image to specified height and width or resize.
  406. * An array can specify positioning of the crop area. Default false.
  407. */
  408. $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop );
  409. if ( null !== $output )
  410. return $output;
  411. if ( $crop ) {
  412. // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h
  413. $aspect_ratio = $orig_w / $orig_h;
  414. $new_w = min($dest_w, $orig_w);
  415. $new_h = min($dest_h, $orig_h);
  416. if ( !$new_w ) {
  417. $new_w = intval($new_h * $aspect_ratio);
  418. }
  419. if ( !$new_h ) {
  420. $new_h = intval($new_w / $aspect_ratio);
  421. }
  422. $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
  423. $crop_w = round($new_w / $size_ratio);
  424. $crop_h = round($new_h / $size_ratio);
  425. if ( ! is_array( $crop ) || count( $crop ) !== 2 ) {
  426. $crop = array( 'center', 'center' );
  427. }
  428. list( $x, $y ) = $crop;
  429. if ( 'left' === $x ) {
  430. $s_x = 0;
  431. } elseif ( 'right' === $x ) {
  432. $s_x = $orig_w - $crop_w;
  433. } else {
  434. $s_x = floor( ( $orig_w - $crop_w ) / 2 );
  435. }
  436. if ( 'top' === $y ) {
  437. $s_y = 0;
  438. } elseif ( 'bottom' === $y ) {
  439. $s_y = $orig_h - $crop_h;
  440. } else {
  441. $s_y = floor( ( $orig_h - $crop_h ) / 2 );
  442. }
  443. } else {
  444. // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box
  445. $crop_w = $orig_w;
  446. $crop_h = $orig_h;
  447. $s_x = 0;
  448. $s_y = 0;
  449. list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h );
  450. }
  451. // if the resulting image would be the same size or larger we don't want to resize it
  452. if ( $new_w >= $orig_w && $new_h >= $orig_h )
  453. return false;
  454. // the return array matches the parameters to imagecopyresampled()
  455. // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h
  456. return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
  457. }
  458. /**
  459. * Resize an image to make a thumbnail or intermediate size.
  460. *
  461. * The returned array has the file size, the image width, and image height. The
  462. * filter 'image_make_intermediate_size' can be used to hook in and change the
  463. * values of the returned array. The only parameter is the resized file path.
  464. *
  465. * @since 2.5.0
  466. *
  467. * @param string $file File path.
  468. * @param int $width Image width.
  469. * @param int $height Image height.
  470. * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize.
  471. * @return bool|array False, if no image was created. Metadata array on success.
  472. */
  473. function image_make_intermediate_size( $file, $width, $height, $crop = false ) {
  474. if ( $width || $height ) {
  475. $editor = wp_get_image_editor( $file );
  476. if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
  477. return false;
  478. $resized_file = $editor->save();
  479. if ( ! is_wp_error( $resized_file ) && $resized_file ) {
  480. unset( $resized_file['path'] );
  481. return $resized_file;
  482. }
  483. }
  484. return false;
  485. }
  486. /**
  487. * Retrieve the image's intermediate size (resized) path, width, and height.
  488. *
  489. * The $size parameter can be an array with the width and height respectively.
  490. * If the size matches the 'sizes' metadata array for width and height, then it
  491. * will be used. If there is no direct match, then the nearest image size larger
  492. * than the specified size will be used. If nothing is found, then the function
  493. * will break out and return false.
  494. *
  495. * The metadata 'sizes' is used for compatible sizes that can be used for the
  496. * parameter $size value.
  497. *
  498. * The url path will be given, when the $size parameter is a string.
  499. *
  500. * If you are passing an array for the $size, you should consider using
  501. * add_image_size() so that a cropped version is generated. It's much more
  502. * efficient than having to find the closest-sized image and then having the
  503. * browser scale down the image.
  504. *
  505. * @since 2.5.0
  506. * @see add_image_size()
  507. *
  508. * @param int $post_id Attachment ID for image.
  509. * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string.
  510. * @return bool|array False on failure or array of file path, width, and height on success.
  511. */
  512. function image_get_intermediate_size($post_id, $size='thumbnail') {
  513. if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) )
  514. return false;
  515. // get the best one for a specified set of dimensions
  516. if ( is_array($size) && !empty($imagedata['sizes']) ) {
  517. foreach ( $imagedata['sizes'] as $_size => $data ) {
  518. // already cropped to width or height; so use this size
  519. if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) {
  520. $file = $data['file'];
  521. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  522. return compact( 'file', 'width', 'height' );
  523. }
  524. // add to lookup table: area => size
  525. $areas[$data['width'] * $data['height']] = $_size;
  526. }
  527. if ( !$size || !empty($areas) ) {
  528. // find for the smallest image not smaller than the desired size
  529. ksort($areas);
  530. foreach ( $areas as $_size ) {
  531. $data = $imagedata['sizes'][$_size];
  532. if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) {
  533. // Skip images with unexpectedly divergent aspect ratios (crops)
  534. // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop
  535. $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false );
  536. // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size
  537. if ( 'thumbnail' != $_size && ( !$maybe_cropped || ( $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] ) || ( $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'] ) ) )
  538. continue;
  539. // If we're still here, then we're going to use this size
  540. $file = $data['file'];
  541. list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size );
  542. return compact( 'file', 'width', 'height' );
  543. }
  544. }
  545. }
  546. }
  547. if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) )
  548. return false;
  549. $data = $imagedata['sizes'][$size];
  550. // include the full filesystem path of the intermediate file
  551. if ( empty($data['path']) && !empty($data['file']) ) {
  552. $file_url = wp_get_attachment_url($post_id);
  553. $data['path'] = path_join( dirname($imagedata['file']), $data['file'] );
  554. $data['url'] = path_join( dirname($file_url), $data['file'] );
  555. }
  556. return $data;
  557. }
  558. /**
  559. * Get the available image sizes
  560. * @since 3.0.0
  561. * @return array Returns a filtered array of image size strings
  562. */
  563. function get_intermediate_image_sizes() {
  564. global $_wp_additional_image_sizes;
  565. $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes
  566. if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) )
  567. $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) );
  568. /**
  569. * Filter the list of intermediate image sizes.
  570. *
  571. * @since 2.5.0
  572. *
  573. * @param array $image_sizes An array of intermediate image sizes. Defaults
  574. * are 'thumbnail', 'medium', 'large'.
  575. */
  576. return apply_filters( 'intermediate_image_sizes', $image_sizes );
  577. }
  578. /**
  579. * Retrieve an image to represent an attachment.
  580. *
  581. * A mime icon for files, thumbnail or intermediate size for images.
  582. *
  583. * @since 2.5.0
  584. *
  585. * @param int $attachment_id Image attachment ID.
  586. * @param string $size Optional, default is 'thumbnail'.
  587. * @param bool $icon Optional, default is false. Whether it is an icon.
  588. * @return bool|array Returns an array (url, width, height), or false, if no image is available.
  589. */
  590. function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) {
  591. // get a thumbnail or intermediate image if there is one
  592. if ( $image = image_downsize($attachment_id, $size) )
  593. return $image;
  594. $src = false;
  595. if ( $icon && $src = wp_mime_type_icon($attachment_id) ) {
  596. /** This filter is documented in wp-includes/post.php */
  597. $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/media' );
  598. $src_file = $icon_dir . '/' . wp_basename($src);
  599. @list($width, $height) = getimagesize($src_file);
  600. }
  601. if ( $src && $width && $height )
  602. return array( $src, $width, $height );
  603. return false;
  604. }
  605. /**
  606. * Get an HTML img element representing an image attachment
  607. *
  608. * While $size will accept an array, it is better to register a size with
  609. * add_image_size() so that a cropped version is generated. It's much more
  610. * efficient than having to find the closest-sized image and then having the
  611. * browser scale down the image.
  612. *
  613. * @since 2.5.0
  614. *
  615. * @see add_image_size()
  616. * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions
  617. *
  618. * @param int $attachment_id Image attachment ID.
  619. * @param string $size Optional, default is 'thumbnail'.
  620. * @param bool $icon Optional, default is false. Whether it is an icon.
  621. * @param mixed $attr Optional, attributes for the image markup.
  622. * @return string HTML img element or empty string on failure.
  623. */
  624. function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') {
  625. $html = '';
  626. $image = wp_get_attachment_image_src($attachment_id, $size, $icon);
  627. if ( $image ) {
  628. list($src, $width, $height) = $image;
  629. $hwstring = image_hwstring($width, $height);
  630. if ( is_array($size) )
  631. $size = join('x', $size);
  632. $attachment = get_post($attachment_id);
  633. $default_attr = array(
  634. 'src' => $src,
  635. 'class' => "attachment-$size",
  636. 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first
  637. );
  638. if ( empty($default_attr['alt']) )
  639. $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption
  640. if ( empty($default_attr['alt']) )
  641. $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title
  642. $attr = wp_parse_args($attr, $default_attr);
  643. /**
  644. * Filter the list of attachment image attributes.
  645. *
  646. * @since 2.8.0
  647. *
  648. * @param mixed $attr Attributes for the image markup.
  649. * @param int $attachment_id Image attachment ID.
  650. */
  651. $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment );
  652. $attr = array_map( 'esc_attr', $attr );
  653. $html = rtrim("<img $hwstring");
  654. foreach ( $attr as $name => $value ) {
  655. $html .= " $name=" . '"' . $value . '"';
  656. }
  657. $html .= ' />';
  658. }
  659. return $html;
  660. }
  661. /**
  662. * Adds a 'wp-post-image' class to post thumbnails
  663. * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to
  664. * dynamically add/remove itself so as to only filter post thumbnails
  665. *
  666. * @since 2.9.0
  667. * @param array $attr Attributes including src, class, alt, title
  668. * @return array
  669. */
  670. function _wp_post_thumbnail_class_filter( $attr ) {
  671. $attr['class'] .= ' wp-post-image';
  672. return $attr;
  673. }
  674. /**
  675. * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter
  676. *
  677. * @since 2.9.0
  678. */
  679. function _wp_post_thumbnail_class_filter_add( $attr ) {
  680. add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  681. }
  682. /**
  683. * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter
  684. *
  685. * @since 2.9.0
  686. */
  687. function _wp_post_thumbnail_class_filter_remove( $attr ) {
  688. remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' );
  689. }
  690. add_shortcode('wp_caption', 'img_caption_shortcode');
  691. add_shortcode('caption', 'img_caption_shortcode');
  692. /**
  693. * The Caption shortcode.
  694. *
  695. * Allows a plugin to replace the content that would otherwise be returned. The
  696. * filter is 'img_caption_shortcode' and passes an empty string, the attr
  697. * parameter and the content parameter values.
  698. *
  699. * The supported attributes for the shortcode are 'id', 'align', 'width', and
  700. * 'caption'.
  701. *
  702. * @since 2.6.0
  703. *
  704. * @param array $attr {
  705. * Attributes of the caption shortcode.
  706. *
  707. * @type string $id ID of the div element for the caption.
  708. * @type string $align Class name that aligns the caption. Default 'alignnone'. Accepts 'alignleft',
  709. * 'aligncenter', alignright', 'alignnone'.
  710. * @type int $width The width of the caption, in pixels.
  711. * @type string $caption The caption text.
  712. * @type string $class Additional class name(s) added to the caption container.
  713. * }
  714. * @param string $content Optional. Shortcode content.
  715. * @return string HTML content to display the caption.
  716. */
  717. function img_caption_shortcode( $attr, $content = null ) {
  718. // New-style shortcode with the caption inside the shortcode with the link and image tags.
  719. if ( ! isset( $attr['caption'] ) ) {
  720. if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) {
  721. $content = $matches[1];
  722. $attr['caption'] = trim( $matches[2] );
  723. }
  724. }
  725. /**
  726. * Filter the default caption shortcode output.
  727. *
  728. * If the filtered output isn't empty, it will be used instead of generating
  729. * the default caption template.
  730. *
  731. * @since 2.6.0
  732. *
  733. * @see img_caption_shortcode()
  734. *
  735. * @param string $output The caption output. Default empty.
  736. * @param array $attr Attributes of the caption shortcode.
  737. * @param string $content The image element, possibly wrapped in a hyperlink.
  738. */
  739. $output = apply_filters( 'img_caption_shortcode', '', $attr, $content );
  740. if ( $output != '' )
  741. return $output;
  742. $atts = shortcode_atts( array(
  743. 'id' => '',
  744. 'align' => 'alignnone',
  745. 'width' => '',
  746. 'caption' => '',
  747. 'class' => '',
  748. ), $attr, 'caption' );
  749. $atts['width'] = (int) $atts['width'];
  750. if ( $atts['width'] < 1 || empty( $atts['caption'] ) )
  751. return $content;
  752. if ( ! empty( $atts['id'] ) )
  753. $atts['id'] = 'id="' . esc_attr( $atts['id'] ) . '" ';
  754. $class = trim( 'wp-caption ' . $atts['align'] . ' ' . $atts['class'] );
  755. if ( current_theme_supports( 'html5', 'caption' ) ) {
  756. return '<figure ' . $atts['id'] . 'style="width: ' . (int) $atts['width'] . 'px;" class="' . esc_attr( $class ) . '">'
  757. . do_shortcode( $content ) . '<figcaption class="wp-caption-text">' . $atts['caption'] . '</figcaption></figure>';
  758. }
  759. $caption_width = 10 + $atts['width'];
  760. /**
  761. * Filter the width of an image's caption.
  762. *
  763. * By default, the caption is 10 pixels greater than the width of the image,
  764. * to prevent post content from running up against a floated image.
  765. *
  766. * @since 3.7.0
  767. *
  768. * @see img_caption_shortcode()
  769. *
  770. * @param int $caption_width Width of the caption in pixels. To remove this inline style,
  771. * return zero.
  772. * @param array $atts Attributes of the caption shortcode.
  773. * @param string $content The image element, possibly wrapped in a hyperlink.
  774. */
  775. $caption_width = apply_filters( 'img_caption_shortcode_width', $caption_width, $atts, $content );
  776. $style = '';
  777. if ( $caption_width )
  778. $style = 'style="width: ' . (int) $caption_width . 'px" ';
  779. return '<div ' . $atts['id'] . $style . 'class="' . esc_attr( $class ) . '">'
  780. . do_shortcode( $content ) . '<p class="wp-caption-text">' . $atts['caption'] . '</p></div>';
  781. }
  782. add_shortcode('gallery', 'gallery_shortcode');
  783. /**
  784. * The Gallery shortcode.
  785. *
  786. * This implements the functionality of the Gallery Shortcode for displaying
  787. * WordPress images on a post.
  788. *
  789. * @since 2.5.0
  790. *
  791. * @param array $attr {
  792. * Attributes of the gallery shortcode.
  793. *
  794. * @type string $order Order of the images in the gallery. Default 'ASC'. Accepts 'ASC', 'DESC'.
  795. * @type string $orderby The field to use when ordering the images. Default 'menu_order ID'.
  796. * Accepts any valid SQL ORDERBY statement.
  797. * @type int $id Post ID.
  798. * @type string $itemtag HTML tag to use for each image in the gallery.
  799. * Default 'dl', or 'figure' when the theme registers HTML5 gallery support.
  800. * @type string $icontag HTML tag to use for each image's icon.
  801. * Default 'dt', or 'div' when the theme registers HTML5 gallery support.
  802. * @type string $captiontag HTML tag to use for each image's caption.
  803. * Default 'dd', or 'figcaption' when the theme registers HTML5 gallery support.
  804. * @type int $columns Number of columns of images to display. Default 3.
  805. * @type string $size Size of the images to display. Default 'thumbnail'.
  806. * @type string $ids A comma-separated list of IDs of attachments to display. Default empty.
  807. * @type string $include A comma-separated list of IDs of attachments to include. Default empty.
  808. * @type string $exclude A comma-separated list of IDs of attachments to exclude. Default empty.
  809. * @type string $link What to link each image to. Default empty (links to the attachment page).
  810. * Accepts 'file', 'none'.
  811. * }
  812. * @return string HTML content to display gallery.
  813. */
  814. function gallery_shortcode( $attr ) {
  815. $post = get_post();
  816. static $instance = 0;
  817. $instance++;
  818. if ( ! empty( $attr['ids'] ) ) {
  819. // 'ids' is explicitly ordered, unless you specify otherwise.
  820. if ( empty( $attr['orderby'] ) )
  821. $attr['orderby'] = 'post__in';
  822. $attr['include'] = $attr['ids'];
  823. }
  824. /**
  825. * Filter the default gallery shortcode output.
  826. *
  827. * If the filtered output isn't empty, it will be used instead of generating
  828. * the default gallery template.
  829. *
  830. * @since 2.5.0
  831. *
  832. * @see gallery_shortcode()
  833. *
  834. * @param string $output The gallery output. Default empty.
  835. * @param array $attr Attributes of the gallery shortcode.
  836. */
  837. $output = apply_filters( 'post_gallery', '', $attr );
  838. if ( $output != '' )
  839. return $output;
  840. // We're trusting author input, so let's at least make sure it looks like a valid orderby statement
  841. if ( isset( $attr['orderby'] ) ) {
  842. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  843. if ( !$attr['orderby'] )
  844. unset( $attr['orderby'] );
  845. }
  846. $html5 = current_theme_supports( 'html5', 'gallery' );
  847. extract(shortcode_atts(array(
  848. 'order' => 'ASC',
  849. 'orderby' => 'menu_order ID',
  850. 'id' => $post ? $post->ID : 0,
  851. 'itemtag' => $html5 ? 'figure' : 'dl',
  852. 'icontag' => $html5 ? 'div' : 'dt',
  853. 'captiontag' => $html5 ? 'figcaption' : 'dd',
  854. 'columns' => 3,
  855. 'size' => 'thumbnail',
  856. 'include' => '',
  857. 'exclude' => '',
  858. 'link' => ''
  859. ), $attr, 'gallery'));
  860. $id = intval($id);
  861. if ( 'RAND' == $order )
  862. $orderby = 'none';
  863. if ( !empty($include) ) {
  864. $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  865. $attachments = array();
  866. foreach ( $_attachments as $key => $val ) {
  867. $attachments[$val->ID] = $_attachments[$key];
  868. }
  869. } elseif ( !empty($exclude) ) {
  870. $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  871. } else {
  872. $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) );
  873. }
  874. if ( empty($attachments) )
  875. return '';
  876. if ( is_feed() ) {
  877. $output = "\n";
  878. foreach ( $attachments as $att_id => $attachment )
  879. $output .= wp_get_attachment_link($att_id, $size, true) . "\n";
  880. return $output;
  881. }
  882. $itemtag = tag_escape($itemtag);
  883. $captiontag = tag_escape($captiontag);
  884. $icontag = tag_escape($icontag);
  885. $valid_tags = wp_kses_allowed_html( 'post' );
  886. if ( ! isset( $valid_tags[ $itemtag ] ) )
  887. $itemtag = 'dl';
  888. if ( ! isset( $valid_tags[ $captiontag ] ) )
  889. $captiontag = 'dd';
  890. if ( ! isset( $valid_tags[ $icontag ] ) )
  891. $icontag = 'dt';
  892. $columns = intval($columns);
  893. $itemwidth = $columns > 0 ? floor(100/$columns) : 100;
  894. $float = is_rtl() ? 'right' : 'left';
  895. $selector = "gallery-{$instance}";
  896. $gallery_style = $gallery_div = '';
  897. /**
  898. * Filter whether to print default gallery styles.
  899. *
  900. * @since 3.1.0
  901. *
  902. * @param bool $print Whether to print default gallery styles.
  903. * Defaults to false if the theme supports HTML5 galleries.
  904. * Otherwise, defaults to true.
  905. */
  906. if ( apply_filters( 'use_default_gallery_style', ! $html5 ) ) {
  907. $gallery_style = "
  908. <style type='text/css'>
  909. #{$selector} {
  910. margin: auto;
  911. }
  912. #{$selector} .gallery-item {
  913. float: {$float};
  914. margin-top: 10px;
  915. text-align: center;
  916. width: {$itemwidth}%;
  917. }
  918. #{$selector} img {
  919. border: 2px solid #cfcfcf;
  920. }
  921. #{$selector} .gallery-caption {
  922. margin-left: 0;
  923. }
  924. /* see gallery_shortcode() in wp-includes/media.php */
  925. </style>\n\t\t";
  926. }
  927. $size_class = sanitize_html_class( $size );
  928. $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>";
  929. /**
  930. * Filter the default gallery shortcode CSS styles.
  931. *
  932. * @since 2.5.0
  933. *
  934. * @param string $gallery_style Default gallery shortcode CSS styles.
  935. * @param string $gallery_div Opening HTML div container for the gallery shortcode output.
  936. */
  937. $output = apply_filters( 'gallery_style', $gallery_style . $gallery_div );
  938. $i = 0;
  939. foreach ( $attachments as $id => $attachment ) {
  940. if ( ! empty( $link ) && 'file' === $link )
  941. $image_output = wp_get_attachment_link( $id, $size, false, false );
  942. elseif ( ! empty( $link ) && 'none' === $link )
  943. $image_output = wp_get_attachment_image( $id, $size, false );
  944. else
  945. $image_output = wp_get_attachment_link( $id, $size, true, false );
  946. $image_meta = wp_get_attachment_metadata( $id );
  947. $orientation = '';
  948. if ( isset( $image_meta['height'], $image_meta['width'] ) )
  949. $orientation = ( $image_meta['height'] > $image_meta['width'] ) ? 'portrait' : 'landscape';
  950. $output .= "<{$itemtag} class='gallery-item'>";
  951. $output .= "
  952. <{$icontag} class='gallery-icon {$orientation}'>
  953. $image_output
  954. </{$icontag}>";
  955. if ( $captiontag && trim($attachment->post_excerpt) ) {
  956. $output .= "
  957. <{$captiontag} class='wp-caption-text gallery-caption'>
  958. " . wptexturize($attachment->post_excerpt) . "
  959. </{$captiontag}>";
  960. }
  961. $output .= "</{$itemtag}>";
  962. if ( ! $html5 && $columns > 0 && ++$i % $columns == 0 ) {
  963. $output .= '<br style="clear: both" />';
  964. }
  965. }
  966. if ( ! $html5 && $columns > 0 && $i % $columns !== 0 ) {
  967. $output .= "
  968. <br style='clear: both' />";
  969. }
  970. $output .= "
  971. </div>\n";
  972. return $output;
  973. }
  974. /**
  975. * Output the templates used by playlists.
  976. *
  977. * @since 3.9.0
  978. */
  979. function wp_underscore_playlist_templates() {
  980. ?>
  981. <script type="text/html" id="tmpl-wp-playlist-current-item">
  982. <# if ( data.image ) { #>
  983. <img src="{{ data.thumb.src }}"/>
  984. <# } #>
  985. <div class="wp-playlist-caption">
  986. <span class="wp-playlist-item-meta wp-playlist-item-title">&#8220;{{ data.title }}&#8221;</span>
  987. <# if ( data.meta.album ) { #><span class="wp-playlist-item-meta wp-playlist-item-album">{{ data.meta.album }}</span><# } #>
  988. <# if ( data.meta.artist ) { #><span class="wp-playlist-item-meta wp-playlist-item-artist">{{ data.meta.artist }}</span><# } #>
  989. </div>
  990. </script>
  991. <script type="text/html" id="tmpl-wp-playlist-item">
  992. <div class="wp-playlist-item">
  993. <a class="wp-playlist-caption" href="{{ data.src }}">
  994. {{ data.index ? ( data.index + '. ' ) : '' }}
  995. <# if ( data.caption ) { #>
  996. {{ data.caption }}
  997. <# } else { #>
  998. <span class="wp-playlist-item-title">&#8220;{{{ data.title }}}&#8221;</span>
  999. <# if ( data.artists && data.meta.artist ) { #>
  1000. <span class="wp-playlist-item-artist"> &mdash; {{ data.meta.artist }}</span>
  1001. <# } #>
  1002. <# } #>
  1003. </a>
  1004. <# if ( data.meta.length_formatted ) { #>
  1005. <div class="wp-playlist-item-length">{{ data.meta.length_formatted }}</div>
  1006. <# } #>
  1007. </div>
  1008. </script>
  1009. <?php
  1010. }
  1011. /**
  1012. * Output and enqueue default scripts and styles for playlists.
  1013. *
  1014. * @since 3.9.0
  1015. *
  1016. * @param string $type Type of playlist. Accepts 'audio' or 'video'.
  1017. */
  1018. function wp_playlist_scripts( $type ) {
  1019. wp_enqueue_style( 'wp-mediaelement' );
  1020. wp_enqueue_script( 'wp-playlist' );
  1021. ?>
  1022. <!--[if lt IE 9]><script>document.createElement('<?php echo esc_js( $type ) ?>');</script><![endif]-->
  1023. <?php
  1024. add_action( 'wp_footer', 'wp_underscore_playlist_templates', 0 );
  1025. add_action( 'admin_footer', 'wp_underscore_playlist_templates', 0 );
  1026. }
  1027. add_action( 'wp_playlist_scripts', 'wp_playlist_scripts' );
  1028. /**
  1029. * The playlist shortcode.
  1030. *
  1031. * This implements the functionality of the playlist shortcode for displaying
  1032. * a collection of WordPress audio or video files in a post.
  1033. *
  1034. * @since 3.9.0
  1035. *
  1036. * @param array $attr Playlist shortcode attributes.
  1037. * @return string Playlist output. Empty string if the passed type is unsupported.
  1038. */
  1039. function wp_playlist_shortcode( $attr ) {
  1040. global $content_width;
  1041. $post = get_post();
  1042. static $instance = 0;
  1043. $instance++;
  1044. if ( ! empty( $attr['ids'] ) ) {
  1045. // 'ids' is explicitly ordered, unless you specify otherwise.
  1046. if ( empty( $attr['orderby'] ) ) {
  1047. $attr['orderby'] = 'post__in';
  1048. }
  1049. $attr['include'] = $attr['ids'];
  1050. }
  1051. /**
  1052. * Filter the playlist output.
  1053. *
  1054. * Passing a non-empty value to the filter will short-circuit generation
  1055. * of the default playlist output, returning the passed value instead.
  1056. *
  1057. * @since 3.9.0
  1058. *
  1059. * @param string $output Playlist output. Default empty.
  1060. * @param array $attr An array of shortcode attributes.
  1061. */
  1062. $output = apply_filters( 'post_playlist', '', $attr );
  1063. if ( $output != '' ) {
  1064. return $output;
  1065. }
  1066. /*
  1067. * We're trusting author input, so let's at least make sure it looks
  1068. * like a valid orderby statement.
  1069. */
  1070. if ( isset( $attr['orderby'] ) ) {
  1071. $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] );
  1072. if ( ! $attr['orderby'] )
  1073. unset( $attr['orderby'] );
  1074. }
  1075. extract( shortcode_atts( array(
  1076. 'type' => 'audio',
  1077. 'order' => 'ASC',
  1078. 'orderby' => 'menu_order ID',
  1079. 'id' => $post ? $post->ID : 0,
  1080. 'include' => '',
  1081. 'exclude' => '',
  1082. 'style' => 'light',
  1083. 'tracklist' => true,
  1084. 'tracknumbers' => true,
  1085. 'images' => true,
  1086. 'artists' => true
  1087. ), $attr, 'playlist' ) );
  1088. $id = intval( $id );
  1089. if ( 'RAND' == $order ) {
  1090. $orderby = 'none';
  1091. }
  1092. $args = array(
  1093. 'post_status' => 'inherit',
  1094. 'post_type' => 'attachment',
  1095. 'post_mime_type' => $type,
  1096. 'order' => $order,
  1097. 'orderby' => $orderby
  1098. );
  1099. if ( ! empty( $include ) ) {
  1100. $args['include'] = $include;
  1101. $_attachments = get_posts( $args );
  1102. $attachments = array();
  1103. foreach ( $_attachments as $key => $val ) {
  1104. $attachments[$val->ID] = $_attachments[$key];
  1105. }
  1106. } elseif ( ! empty( $exclude ) ) {
  1107. $args['post_parent'] = $id;
  1108. $args['exclude'] = $exclude;
  1109. $attachments = get_children( $args );
  1110. } else {
  1111. $args['post_parent'] = $id;
  1112. $attachments = get_children( $args );
  1113. }
  1114. if ( empty( $attachments ) ) {
  1115. return '';
  1116. }
  1117. if ( is_feed() ) {
  1118. $output = "\n";
  1119. foreach ( $attachments as $att_id => $attachment ) {
  1120. $output .= wp_get_attachment_link( $att_id ) . "\n";
  1121. }
  1122. return $output;
  1123. }
  1124. $outer = 22; // default padding and border of wrapper
  1125. $default_width = 640;
  1126. $default_height = 360;
  1127. $theme_width = empty( $content_width ) ? $default_width : ( $content_width - $outer );
  1128. $theme_height = empty( $content_width ) ? $default_height : round( ( $default_height * $theme_width ) / $default_width );
  1129. $data = compact( 'type' );
  1130. // don't pass strings to JSON, will be truthy in JS
  1131. foreach ( array( 'tracklist', 'tracknumbers', 'images', 'artists' ) as $key ) {
  1132. $data[$key] = filter_var( $$key, FILTER_VALIDATE_BOOLEAN );
  1133. }
  1134. $tracks = array();
  1135. foreach ( $attachments as $attachment ) {
  1136. $url = wp_get_attachment_url( $attachment->ID );
  1137. $ftype = wp_check_filetype( $url, wp_get_mime_types() );
  1138. $track = array(
  1139. 'src' => $url,
  1140. 'type' => $ftype['type'],
  1141. 'title' => $attachment->post_title,
  1142. 'caption' => $attachment->post_excerpt,
  1143. 'description' => $attachment->post_content
  1144. );
  1145. $track['meta'] = array();
  1146. $meta = wp_get_attachment_metadata( $attachment->ID );
  1147. if ( ! empty( $meta ) ) {
  1148. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  1149. if ( ! empty( $meta[ $key ] ) ) {
  1150. $track['meta'][ $key ] = $meta[ $key ];
  1151. }
  1152. }
  1153. if ( 'video' === $type ) {
  1154. if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) {
  1155. $width = $meta['width'];
  1156. $height = $meta['height'];
  1157. $theme_height = round( ( $height * $theme_width ) / $width );
  1158. } else {
  1159. $width = $default_width;
  1160. $height = $default_height;
  1161. }
  1162. $track['dimensions'] = array(
  1163. 'original' => compact( 'width', 'height' ),
  1164. 'resized' => array(
  1165. 'width' => $theme_width,
  1166. 'height' => $theme_height
  1167. )
  1168. );
  1169. }
  1170. }
  1171. if ( $images ) {
  1172. $id = get_post_thumbnail_id( $attachment->ID );
  1173. if ( ! empty( $id ) ) {
  1174. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  1175. $track['image'] = compact( 'src', 'width', 'height' );
  1176. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  1177. $track['thumb'] = compact( 'src', 'width', 'height' );
  1178. } else {
  1179. $src = wp_mime_type_icon( $attachment->ID );
  1180. $width = 48;
  1181. $height = 64;
  1182. $track['image'] = compact( 'src', 'width', 'height' );
  1183. $track['thumb'] = compact( 'src', 'width', 'height' );
  1184. }
  1185. }
  1186. $tracks[] = $track;
  1187. }
  1188. $data['tracks'] = $tracks;
  1189. $safe_type = esc_attr( $type );
  1190. $safe_style = esc_attr( $style );
  1191. ob_start();
  1192. if ( 1 === $instance ) {
  1193. /**
  1194. * Print and enqueue playlist scripts, styles, and JavaScript templates.
  1195. *
  1196. * @since 3.9.0
  1197. *
  1198. * @param string $type Type of playlist. Possible values are 'audio' or 'video'.
  1199. * @param string $style The 'theme' for the playlist. Core provides 'light' and 'dark'.
  1200. */
  1201. do_action( 'wp_playlist_scripts', $type, $style );
  1202. } ?>
  1203. <div class="wp-playlist wp-<?php echo $safe_type ?>-playlist wp-playlist-<?php echo $safe_style ?>">
  1204. <?php if ( 'audio' === $type ): ?>
  1205. <div class="wp-playlist-current-item"></div>
  1206. <?php endif ?>
  1207. <<?php echo $safe_type ?> controls="controls" preload="none" width="<?php
  1208. echo (int) $theme_width;
  1209. ?>"<?php if ( 'video' === $safe_type ):
  1210. echo ' height="', (int) $theme_height, '"';
  1211. endif; ?>></<?php echo $safe_type ?>>
  1212. <div class="wp-playlist-next"></div>
  1213. <div class="wp-playlist-prev"></div>
  1214. <noscript>
  1215. <ol><?php
  1216. foreach ( $attachments as $att_id => $attachment ) {
  1217. printf( '<li>%s</li>', wp_get_attachment_link( $att_id ) );
  1218. }
  1219. ?></ol>
  1220. </noscript>
  1221. <script type="application/json"><?php echo json_encode( $data ) ?></script>
  1222. </div>
  1223. <?php
  1224. return ob_get_clean();
  1225. }
  1226. add_shortcode( 'playlist', 'wp_playlist_shortcode' );
  1227. /**
  1228. * Provide a No-JS Flash fallback as a last resort for audio / video
  1229. *
  1230. * @since 3.6.0
  1231. *
  1232. * @param string $url
  1233. * @return string Fallback HTML
  1234. */
  1235. function wp_mediaelement_fallback( $url ) {
  1236. /**
  1237. * Filter the Mediaelement fallback output for no-JS.
  1238. *
  1239. * @since 3.6.0
  1240. *
  1241. * @param string $output Fallback output for no-JS.
  1242. * @param string $url Media file URL.
  1243. */
  1244. return apply_filters( 'wp_mediaelement_fallback', sprintf( '<a href="%1$s">%1$s</a>', esc_url( $url ) ), $url );
  1245. }
  1246. /**
  1247. * Return a filtered list of WP-supported audio formats.
  1248. *
  1249. * @since 3.6.0
  1250. * @return array
  1251. */
  1252. function wp_get_audio_extensions() {
  1253. /**
  1254. * Filter the list of supported audio formats.
  1255. *
  1256. * @since 3.6.0
  1257. *
  1258. * @param array $extensions An array of support audio formats. Defaults are
  1259. * 'mp3', 'ogg', 'wma', 'm4a', 'wav'.
  1260. */
  1261. return apply_filters( 'wp_audio_extensions', array( 'mp3', 'ogg', 'wma', 'm4a', 'wav' ) );
  1262. }
  1263. /**
  1264. * Return useful keys to use to lookup data from an attachment's stored metadata.
  1265. *
  1266. * @since 3.9.0
  1267. *
  1268. * @param WP_Post $attachment The current attachment, provided for context.
  1269. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  1270. * @return array Key/value pairs of field keys to labels.
  1271. */
  1272. function wp_get_attachment_id3_keys( $attachment, $context = 'display' ) {
  1273. $fields = array(
  1274. 'artist' => __( 'Artist' ),
  1275. 'album' => __( 'Album' ),
  1276. );
  1277. if ( 'display' === $context ) {
  1278. $fields['genre'] = __( 'Genre' );
  1279. $fields['year'] = __( 'Year' );
  1280. $fields['length_formatted'] = _x( 'Length', 'video or audio' );
  1281. }
  1282. /**
  1283. * Filter the editable list of keys to look up data from an attachment's metadata.
  1284. *
  1285. * @since 3.9.0
  1286. *
  1287. * @param array $fields Key/value pairs of field keys to labels.
  1288. * @param WP_Post $attachment Attachment object.
  1289. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  1290. */
  1291. return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
  1292. }
  1293. /**
  1294. * The Audio shortcode.
  1295. *
  1296. * This implements the functionality of the Audio Shortcode for displaying
  1297. * WordPress mp3s in a post.
  1298. *
  1299. * @since 3.6.0
  1300. *
  1301. * @param array $attr {
  1302. * Attributes of the audio shortcode.
  1303. *
  1304. * @type string $src URL to the source of the audio file. Default empty.
  1305. * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
  1306. * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
  1307. * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
  1308. * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
  1309. * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instances}'.
  1310. * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
  1311. * }
  1312. * @param string $content Optional. Shortcode content.
  1313. * @return string HTML content to display audio.
  1314. */
  1315. function wp_audio_shortcode( $attr, $content = '' ) {
  1316. $post_id = get_post() ? get_the_ID() : 0;
  1317. static $instances = 0;
  1318. $instances++;
  1319. /**
  1320. * Filter the default audio shortcode output.
  1321. *
  1322. * If the filtered output isn't empty, it will be used instead of generating the default audio template.
  1323. *
  1324. * @since 3.6.0
  1325. *
  1326. * @param string $html Empty variable to be replaced with shortcode markup.
  1327. * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
  1328. * @param string $content Shortcode content.
  1329. * @param int $instances Unique numeric ID of this audio shortcode instance.
  1330. */
  1331. $html = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instances );
  1332. if ( '' !== $html )
  1333. return $html;
  1334. $audio = null;
  1335. $default_types = wp_get_audio_extensions();
  1336. $defaults_atts = array(
  1337. 'src' => '',
  1338. 'loop' => '',
  1339. 'autoplay' => '',
  1340. 'preload' => 'none'
  1341. );
  1342. foreach ( $default_types as $type )
  1343. $defaults_atts[$type] = '';
  1344. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  1345. extract( $atts );
  1346. $primary = false;
  1347. if ( ! empty( $src ) ) {
  1348. $type = wp_check_filetype( $src, wp_get_mime_types() );
  1349. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) )
  1350. return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  1351. $primary = true;
  1352. array_unshift( $default_types, 'src' );
  1353. } else {
  1354. foreach ( $default_types as $ext ) {
  1355. if ( ! empty( $$ext ) ) {
  1356. $type = wp_check_filetype( $$ext, wp_get_mime_types() );
  1357. if ( strtolower( $type['ext'] ) === $ext )
  1358. $primary = true;
  1359. }
  1360. }
  1361. }
  1362. if ( ! $primary ) {
  1363. $audios = get_attached_media( 'audio', $post_id );
  1364. if ( empty( $audios ) )
  1365. return;
  1366. $audio = reset( $audios );
  1367. $src = wp_get_attachment_url( $audio->ID );
  1368. if ( empty( $src ) )
  1369. return;
  1370. array_unshift( $default_types, 'src' );
  1371. }
  1372. /**
  1373. * Filter the media library used for the audio shortcode.
  1374. *
  1375. * @since 3.6.0
  1376. *
  1377. * @param string $library Media library used for the audio shortcode.
  1378. */
  1379. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  1380. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1381. wp_enqueue_style( 'wp-mediaelement' );
  1382. wp_enqueue_script( 'wp-mediaelement' );
  1383. }
  1384. /**
  1385. * Filter the class attribute for the audio shortcode output container.
  1386. *
  1387. * @since 3.6.0
  1388. *
  1389. * @param string $class CSS class or list of space-separated classes.
  1390. */
  1391. $atts = array(
  1392. 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
  1393. 'id' => sprintf( 'audio-%d-%d', $post_id, $instances ),
  1394. 'loop' => $loop,
  1395. 'autoplay' => $autoplay,
  1396. 'preload' => $preload,
  1397. 'style' => 'width: 100%',
  1398. );
  1399. // These ones should just be omitted altogether if they are blank
  1400. foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  1401. if ( empty( $atts[$a] ) )
  1402. unset( $atts[$a] );
  1403. }
  1404. $attr_strings = array();
  1405. foreach ( $atts as $k => $v ) {
  1406. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1407. }
  1408. $html = '';
  1409. if ( 'mediaelement' === $library && 1 === $instances )
  1410. $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  1411. $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
  1412. $fileurl = '';
  1413. $source = '<source type="%s" src="%s" />';
  1414. foreach ( $default_types as $fallback ) {
  1415. if ( ! empty( $$fallback ) ) {
  1416. if ( empty( $fileurl ) )
  1417. $fileurl = $$fallback;
  1418. $type = wp_check_filetype( $$fallback, wp_get_mime_types() );
  1419. $url = add_query_arg( '_', $instances, $$fallback );
  1420. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  1421. }
  1422. }
  1423. if ( 'mediaelement' === $library )
  1424. $html .= wp_mediaelement_fallback( $fileurl );
  1425. $html .= '</audio>';
  1426. /**
  1427. * Filter the audio shortcode output.
  1428. *
  1429. * @since 3.6.0
  1430. *
  1431. * @param string $html Audio shortcode HTML output.
  1432. * @param array $atts Array of audio shortcode attributes.
  1433. * @param string $audio Audio file.
  1434. * @param int $post_id Post ID.
  1435. * @param string $library Media library used for the audio shortcode.
  1436. */
  1437. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  1438. }
  1439. add_shortcode( 'audio', 'wp_audio_shortcode' );
  1440. /**
  1441. * Return a filtered list of WP-supported video formats
  1442. *
  1443. * @since 3.6.0
  1444. * @return array
  1445. */
  1446. function wp_get_video_extensions() {
  1447. /**
  1448. * Filter the list of supported video formats.
  1449. *
  1450. * @since 3.6.0
  1451. *
  1452. * @param array $extensions An array of support video formats. Defaults are
  1453. * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
  1454. */
  1455. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  1456. }
  1457. /**
  1458. * The Video shortcode.
  1459. *
  1460. * This implements the functionality of the Video Shortcode for displaying
  1461. * WordPress mp4s in a post.
  1462. *
  1463. * @since 3.6.0
  1464. *
  1465. * @param array $attr {
  1466. * Attributes of the shortcode.
  1467. *
  1468. * @type string $src URL to the source of the video file. Default empty.
  1469. * @type int $height Height of the video embed in pixels. Default 360.
  1470. * @type int $width Width of the video embed in pixels. Default $content_width or 640.
  1471. * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
  1472. * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
  1473. * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
  1474. * @type string $preload The 'preload' attribute for the `<video>` element.
  1475. * Default 'metadata'.
  1476. * @type string $class The 'class' attribute for the `<video>` element.
  1477. * Default 'wp-video-shortcode'.
  1478. * @type string $id The 'id' attribute for the `<video>` element.
  1479. * Default 'video-{$post_id}-{$instances}'.
  1480. * }
  1481. * @param string $content Optional. Shortcode content.
  1482. * @return string HTML content to display video.
  1483. */
  1484. function wp_video_shortcode( $attr, $content = '' ) {
  1485. global $content_width;
  1486. $post_id = get_post() ? get_the_ID() : 0;
  1487. static $instances = 0;
  1488. $instances++;
  1489. /**
  1490. * Filter the default video shortcode output.
  1491. *
  1492. * If the filtered output isn't empty, it will be used instead of generating
  1493. * the default video template.
  1494. *
  1495. * @since 3.6.0
  1496. *
  1497. * @see wp_video_shortcode()
  1498. *
  1499. * @param string $html Empty variable to be replaced with shortcode markup.
  1500. * @param array $attr Attributes of the video shortcode.
  1501. * @param string $content Video shortcode content.
  1502. * @param int $instances Unique numeric ID of this video shortcode instance.
  1503. */
  1504. $html = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instances );
  1505. if ( '' !== $html )
  1506. return $html;
  1507. $video = null;
  1508. $default_types = wp_get_video_extensions();
  1509. $defaults_atts = array(
  1510. 'src' => '',
  1511. 'poster' => '',
  1512. 'loop' => '',
  1513. 'autoplay' => '',
  1514. 'preload' => 'metadata',
  1515. 'width' => 640,
  1516. 'height' => 360,
  1517. );
  1518. foreach ( $default_types as $type )
  1519. $defaults_atts[$type] = '';
  1520. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  1521. extract( $atts );
  1522. if ( is_admin() ) {
  1523. // shrink the video so it isn't huge in the admin
  1524. if ( $width > $defaults_atts['width'] ) {
  1525. $height = round( ( $height * $defaults_atts['width'] ) / $width );
  1526. $width = $defaults_atts['width'];
  1527. }
  1528. } else {
  1529. // if the video is bigger than the theme
  1530. if ( ! empty( $content_width ) && $width > $content_width ) {
  1531. $height = round( ( $height * $content_width ) / $width );
  1532. $width = $content_width;
  1533. }
  1534. }
  1535. $yt_pattern = '#^https?://(:?www\.)?(:?youtube\.com/watch|youtu\.be/)#';
  1536. $primary = false;
  1537. if ( ! empty( $src ) ) {
  1538. if ( ! preg_match( $yt_pattern, $src ) ) {
  1539. $type = wp_check_filetype( $src, wp_get_mime_types() );
  1540. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  1541. return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $src ), esc_html( $src ) );
  1542. }
  1543. }
  1544. $primary = true;
  1545. array_unshift( $default_types, 'src' );
  1546. } else {
  1547. foreach ( $default_types as $ext ) {
  1548. if ( ! empty( $$ext ) ) {
  1549. $type = wp_check_filetype( $$ext, wp_get_mime_types() );
  1550. if ( strtolower( $type['ext'] ) === $ext )
  1551. $primary = true;
  1552. }
  1553. }
  1554. }
  1555. if ( ! $primary ) {
  1556. $videos = get_attached_media( 'video', $post_id );
  1557. if ( empty( $videos ) )
  1558. return;
  1559. $video = reset( $videos );
  1560. $src = wp_get_attachment_url( $video->ID );
  1561. if ( empty( $src ) )
  1562. return;
  1563. array_unshift( $default_types, 'src' );
  1564. }
  1565. /**
  1566. * Filter the media library used for the video shortcode.
  1567. *
  1568. * @since 3.6.0
  1569. *
  1570. * @param string $library Media library used for the video shortcode.
  1571. */
  1572. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  1573. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1574. wp_enqueue_style( 'wp-mediaelement' );
  1575. wp_enqueue_script( 'wp-mediaelement' );
  1576. }
  1577. /**
  1578. * Filter the class attribute for the video shortcode output container.
  1579. *
  1580. * @since 3.6.0
  1581. *
  1582. * @param string $class CSS class or list of space-separated classes.
  1583. */
  1584. $atts = array(
  1585. 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
  1586. 'id' => sprintf( 'video-%d-%d', $post_id, $instances ),
  1587. 'width' => absint( $width ),
  1588. 'height' => absint( $height ),
  1589. 'poster' => esc_url( $poster ),
  1590. 'loop' => $loop,
  1591. 'autoplay' => $autoplay,
  1592. 'preload' => $preload,
  1593. );
  1594. // These ones should just be omitted altogether if they are blank
  1595. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  1596. if ( empty( $atts[$a] ) )
  1597. unset( $atts[$a] );
  1598. }
  1599. $attr_strings = array();
  1600. foreach ( $atts as $k => $v ) {
  1601. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1602. }
  1603. $html = '';
  1604. if ( 'mediaelement' === $library && 1 === $instances )
  1605. $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  1606. $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  1607. $fileurl = '';
  1608. $source = '<source type="%s" src="%s" />';
  1609. foreach ( $default_types as $fallback ) {
  1610. if ( ! empty( $$fallback ) ) {
  1611. if ( empty( $fileurl ) )
  1612. $fileurl = $$fallback;
  1613. if ( 'src' === $fallback && preg_match( $yt_pattern, $src ) ) {
  1614. $type = array( 'type' => 'video/youtube' );
  1615. } else {
  1616. $type = wp_check_filetype( $$fallback, wp_get_mime_types() );
  1617. }
  1618. $url = add_query_arg( '_', $instances, $$fallback );
  1619. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  1620. }
  1621. }
  1622. if ( ! empty( $content ) ) {
  1623. if ( false !== strpos( $content, "\n" ) )
  1624. $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
  1625. $html .= trim( $content );
  1626. }
  1627. if ( 'mediaelement' === $library )
  1628. $html .= wp_mediaelement_fallback( $fileurl );
  1629. $html .= '</video>';
  1630. $html = sprintf( '<div style="width: %dpx; max-width: 100%%;" class="wp-video">%s</div>', $width, $html );
  1631. /**
  1632. * Filter the output of the video shortcode.
  1633. *
  1634. * @since 3.6.0
  1635. *
  1636. * @param string $html Video shortcode HTML output.
  1637. * @param array $atts Array of video shortcode attributes.
  1638. * @param string $video Video file.
  1639. * @param int $post_id Post ID.
  1640. * @param string $library Media library used for the video shortcode.
  1641. */
  1642. return apply_filters( 'wp_video_shortcode', $html, $atts, $video, $post_id, $library );
  1643. }
  1644. add_shortcode( 'video', 'wp_video_shortcode' );
  1645. /**
  1646. * Display previous image link that has the same post parent.
  1647. *
  1648. * @since 2.5.0
  1649. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1650. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1651. * @return string HTML content.
  1652. */
  1653. function previous_image_link($size = 'thumbnail', $text = false) {
  1654. adjacent_image_link(true, $size, $text);
  1655. }
  1656. /**
  1657. * Display next image link that has the same post parent.
  1658. *
  1659. * @since 2.5.0
  1660. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1661. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1662. * @return string HTML content.
  1663. */
  1664. function next_image_link($size = 'thumbnail', $text = false) {
  1665. adjacent_image_link(false, $size, $text);
  1666. }
  1667. /**
  1668. * Display next or previous image link that has the same post parent.
  1669. *
  1670. * Retrieves the current attachment object from the $post global.
  1671. *
  1672. * @since 2.5.0
  1673. *
  1674. * @param bool $prev Optional. Default is true to display previous link, false for next.
  1675. */
  1676. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  1677. $post = get_post();
  1678. $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' ) ) );
  1679. foreach ( $attachments as $k => $attachment )
  1680. if ( $attachment->ID == $post->ID )
  1681. break;
  1682. $k = $prev ? $k - 1 : $k + 1;
  1683. $output = $attachment_id = null;
  1684. if ( isset( $attachments[ $k ] ) ) {
  1685. $attachment_id = $attachments[ $k ]->ID;
  1686. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  1687. }
  1688. $adjacent = $prev ? 'previous' : 'next';
  1689. /**
  1690. * Filter the adjacent image link.
  1691. *
  1692. * The dynamic portion of the hook name, $adjacent, refers to the type of adjacency,
  1693. * either 'next', or 'previous'.
  1694. *
  1695. * @since 3.5.0
  1696. *
  1697. * @param string $output Adjacent image HTML markup.
  1698. * @param int $attachment_id Attachment ID
  1699. * @param string $size Image size.
  1700. * @param string $text Link text.
  1701. */
  1702. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  1703. }
  1704. /**
  1705. * Retrieve taxonomies attached to the attachment.
  1706. *
  1707. * @since 2.5.0
  1708. *
  1709. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  1710. * @return array Empty array on failure. List of taxonomies on success.
  1711. */
  1712. function get_attachment_taxonomies($attachment) {
  1713. if ( is_int( $attachment ) )
  1714. $attachment = get_post($attachment);
  1715. else if ( is_array($attachment) )
  1716. $attachment = (object) $attachment;
  1717. if ( ! is_object($attachment) )
  1718. return array();
  1719. $filename = basename($attachment->guid);
  1720. $objects = array('attachment');
  1721. if ( false !== strpos($filename, '.') )
  1722. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  1723. if ( !empty($attachment->post_mime_type) ) {
  1724. $objects[] = 'attachment:' . $attachment->post_mime_type;
  1725. if ( false !== strpos($attachment->post_mime_type, '/') )
  1726. foreach ( explode('/', $attachment->post_mime_type) as $token )
  1727. if ( !empty($token) )
  1728. $objects[] = "attachment:$token";
  1729. }
  1730. $taxonomies = array();
  1731. foreach ( $objects as $object )
  1732. if ( $taxes = get_object_taxonomies($object) )
  1733. $taxonomies = array_merge($taxonomies, $taxes);
  1734. return array_unique($taxonomies);
  1735. }
  1736. /**
  1737. * Return all of the taxonomy names that are registered for attachments.
  1738. *
  1739. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  1740. *
  1741. * @since 3.5.0
  1742. * @see get_attachment_taxonomies()
  1743. * @uses get_taxonomies()
  1744. *
  1745. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  1746. * @return array The names of all taxonomy of $object_type.
  1747. */
  1748. function get_taxonomies_for_attachments( $output = 'names' ) {
  1749. $taxonomies = array();
  1750. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1751. foreach ( $taxonomy->object_type as $object_type ) {
  1752. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  1753. if ( 'names' == $output )
  1754. $taxonomies[] = $taxonomy->name;
  1755. else
  1756. $taxonomies[ $taxonomy->name ] = $taxonomy;
  1757. break;
  1758. }
  1759. }
  1760. }
  1761. return $taxonomies;
  1762. }
  1763. /**
  1764. * Create new GD image resource with transparency support
  1765. * @TODO: Deprecate if possible.
  1766. *
  1767. * @since 2.9.0
  1768. *
  1769. * @param int $width Image width
  1770. * @param int $height Image height
  1771. * @return image resource
  1772. */
  1773. function wp_imagecreatetruecolor($width, $height) {
  1774. $img = imagecreatetruecolor($width, $height);
  1775. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1776. imagealphablending($img, false);
  1777. imagesavealpha($img, true);
  1778. }
  1779. return $img;
  1780. }
  1781. /**
  1782. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1783. *
  1784. * @since 2.9.0
  1785. * @see WP_Embed::register_handler()
  1786. */
  1787. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1788. global $wp_embed;
  1789. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  1790. }
  1791. /**
  1792. * Unregister a previously registered embed handler.
  1793. *
  1794. * @since 2.9.0
  1795. * @see WP_Embed::unregister_handler()
  1796. */
  1797. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1798. global $wp_embed;
  1799. $wp_embed->unregister_handler( $id, $priority );
  1800. }
  1801. /**
  1802. * Create default array of embed parameters.
  1803. *
  1804. * The width defaults to the content width as specified by the theme. If the
  1805. * theme does not specify a content width, then 500px is used.
  1806. *
  1807. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  1808. *
  1809. * The 'embed_defaults' filter can be used to adjust either of these values.
  1810. *
  1811. * @since 2.9.0
  1812. *
  1813. * @return array Default embed parameters.
  1814. */
  1815. function wp_embed_defaults() {
  1816. if ( ! empty( $GLOBALS['content_width'] ) )
  1817. $width = (int) $GLOBALS['content_width'];
  1818. if ( empty( $width ) )
  1819. $width = 500;
  1820. $height = min( ceil( $width * 1.5 ), 1000 );
  1821. /**
  1822. * Filter the default array of embed dimensions.
  1823. *
  1824. * @since 2.9.0
  1825. *
  1826. * @param int $width Width of the embed in pixels.
  1827. * @param int $height Height of the embed in pixels.
  1828. */
  1829. return apply_filters( 'embed_defaults', compact( 'width', 'height' ) );
  1830. }
  1831. /**
  1832. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1833. *
  1834. * @since 2.9.0
  1835. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  1836. *
  1837. * @param int $example_width The width of an example embed.
  1838. * @param int $example_height The height of an example embed.
  1839. * @param int $max_width The maximum allowed width.
  1840. * @param int $max_height The maximum allowed height.
  1841. * @return array The maximum possible width and height based on the example ratio.
  1842. */
  1843. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1844. $example_width = (int) $example_width;
  1845. $example_height = (int) $example_height;
  1846. $max_width = (int) $max_width;
  1847. $max_height = (int) $max_height;
  1848. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  1849. }
  1850. /**
  1851. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1852. *
  1853. * @since 2.9.0
  1854. * @see WP_oEmbed
  1855. *
  1856. * @uses _wp_oembed_get_object()
  1857. * @uses WP_oEmbed::get_html()
  1858. *
  1859. * @param string $url The URL that should be embedded.
  1860. * @param array $args Additional arguments and parameters.
  1861. * @return bool|string False on failure or the embed HTML on success.
  1862. */
  1863. function wp_oembed_get( $url, $args = '' ) {
  1864. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1865. $oembed = _wp_oembed_get_object();
  1866. return $oembed->get_html( $url, $args );
  1867. }
  1868. /**
  1869. * Adds a URL format and oEmbed provider URL pair.
  1870. *
  1871. * @since 2.9.0
  1872. * @see WP_oEmbed
  1873. *
  1874. * @uses _wp_oembed_get_object()
  1875. *
  1876. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1877. * @param string $provider The URL to the oEmbed provider.
  1878. * @param boolean $regex Whether the $format parameter is in a regex format.
  1879. */
  1880. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1881. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1882. $oembed = _wp_oembed_get_object();
  1883. $oembed->providers[$format] = array( $provider, $regex );
  1884. }
  1885. /**
  1886. * Removes an oEmbed provider.
  1887. *
  1888. * @since 3.5.0
  1889. * @see WP_oEmbed
  1890. *
  1891. * @uses _wp_oembed_get_object()
  1892. *
  1893. * @param string $format The URL format for the oEmbed provider to remove.
  1894. */
  1895. function wp_oembed_remove_provider( $format ) {
  1896. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1897. $oembed = _wp_oembed_get_object();
  1898. if ( isset( $oembed->providers[ $format ] ) ) {
  1899. unset( $oembed->providers[ $format ] );
  1900. return true;
  1901. }
  1902. return false;
  1903. }
  1904. /**
  1905. * Determines if default embed handlers should be loaded.
  1906. *
  1907. * Checks to make sure that the embeds library hasn't already been loaded. If
  1908. * it hasn't, then it will load the embeds library.
  1909. *
  1910. * @since 2.9.0
  1911. */
  1912. function wp_maybe_load_embeds() {
  1913. /**
  1914. * Filter whether to load the default embed handlers.
  1915. *
  1916. * Returning a falsey value will prevent loading the default embed handlers.
  1917. *
  1918. * @since 2.9.0
  1919. *
  1920. * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
  1921. */
  1922. if ( ! apply_filters( 'load_default_embeds', true ) ) {
  1923. return;
  1924. }
  1925. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  1926. /**
  1927. * Filter the audio embed handler callback.
  1928. *
  1929. * @since 3.6.0
  1930. *
  1931. * @param callback $handler Audio embed handler callback function.
  1932. */
  1933. wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
  1934. /**
  1935. * Filter the video embed handler callback.
  1936. *
  1937. * @since 3.6.0
  1938. *
  1939. * @param callback $handler Video embed handler callback function.
  1940. */
  1941. wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  1942. }
  1943. /**
  1944. * The Google Video embed handler callback. Google Video does not support oEmbed.
  1945. *
  1946. * @see WP_Embed::register_handler()
  1947. * @see WP_Embed::shortcode()
  1948. *
  1949. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1950. * @param array $attr Embed attributes.
  1951. * @param string $url The original URL that was matched by the regex.
  1952. * @param array $rawattr The original unmodified attributes.
  1953. * @return string The embed HTML.
  1954. */
  1955. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  1956. // If the user supplied a fixed width AND height, use it
  1957. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  1958. $width = (int) $rawattr['width'];
  1959. $height = (int) $rawattr['height'];
  1960. } else {
  1961. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  1962. }
  1963. /**
  1964. * Filter the Google Video embed output.
  1965. *
  1966. * @since 2.9.0
  1967. *
  1968. * @param string $html Google Video HTML embed markup.
  1969. * @param array $matches The regex matches from the provided regex.
  1970. * @param array $attr An array of embed attributes.
  1971. * @param string $url The original URL that was matched by the regex.
  1972. * @param array $rawattr The original unmodified attributes.
  1973. */
  1974. return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&amp;hl=en&amp;fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr );
  1975. }
  1976. /**
  1977. * Audio embed handler callback.
  1978. *
  1979. * @since 3.6.0
  1980. *
  1981. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  1982. * @param array $attr Embed attributes.
  1983. * @param string $url The original URL that was matched by the regex.
  1984. * @param array $rawattr The original unmodified attributes.
  1985. * @return string The embed HTML.
  1986. */
  1987. function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  1988. $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
  1989. /**
  1990. * Filter the audio embed output.
  1991. *
  1992. * @since 3.6.0
  1993. *
  1994. * @param string $audio Audio embed output.
  1995. * @param array $attr An array of embed attributes.
  1996. * @param string $url The original URL that was matched by the regex.
  1997. * @param array $rawattr The original unmodified attributes.
  1998. */
  1999. return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  2000. }
  2001. /**
  2002. * Video embed handler callback.
  2003. *
  2004. * @since 3.6.0
  2005. *
  2006. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2007. * @param array $attr Embed attributes.
  2008. * @param string $url The original URL that was matched by the regex.
  2009. * @param array $rawattr The original unmodified attributes.
  2010. * @return string The embed HTML.
  2011. */
  2012. function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  2013. $dimensions = '';
  2014. if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  2015. $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  2016. $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  2017. }
  2018. $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
  2019. /**
  2020. * Filter the video embed output.
  2021. *
  2022. * @since 3.6.0
  2023. *
  2024. * @param string $video Video embed output.
  2025. * @param array $attr An array of embed attributes.
  2026. * @param string $url The original URL that was matched by the regex.
  2027. * @param array $rawattr The original unmodified attributes.
  2028. */
  2029. return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  2030. }
  2031. /**
  2032. * Converts a shorthand byte value to an integer byte value.
  2033. *
  2034. * @since 2.3.0
  2035. *
  2036. * @param string $size A shorthand byte value.
  2037. * @return int An integer byte value.
  2038. */
  2039. function wp_convert_hr_to_bytes( $size ) {
  2040. $size = strtolower( $size );
  2041. $bytes = (int) $size;
  2042. if ( strpos( $size, 'k' ) !== false )
  2043. $bytes = intval( $size ) * 1024;
  2044. elseif ( strpos( $size, 'm' ) !== false )
  2045. $bytes = intval($size) * 1024 * 1024;
  2046. elseif ( strpos( $size, 'g' ) !== false )
  2047. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  2048. return $bytes;
  2049. }
  2050. /**
  2051. * Determine the maximum upload size allowed in php.ini.
  2052. *
  2053. * @since 2.5.0
  2054. *
  2055. * @return int Allowed upload size.
  2056. */
  2057. function wp_max_upload_size() {
  2058. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  2059. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  2060. /**
  2061. * Filter the maximum upload size allowed in php.ini.
  2062. *
  2063. * @since 2.5.0
  2064. *
  2065. * @param int $size Max upload size limit in bytes.
  2066. * @param int $u_bytes Maximum upload filesize in bytes.
  2067. * @param int $p_bytes Maximum size of POST data in bytes.
  2068. */
  2069. return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  2070. }
  2071. /**
  2072. * Returns a WP_Image_Editor instance and loads file into it.
  2073. *
  2074. * @since 3.5.0
  2075. * @access public
  2076. *
  2077. * @param string $path Path to file to load
  2078. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2079. * @return WP_Image_Editor|WP_Error
  2080. */
  2081. function wp_get_image_editor( $path, $args = array() ) {
  2082. $args['path'] = $path;
  2083. if ( ! isset( $args['mime_type'] ) ) {
  2084. $file_info = wp_check_filetype( $args['path'] );
  2085. // If $file_info['type'] is false, then we let the editor attempt to
  2086. // figure out the file type, rather than forcing a failure based on extension.
  2087. if ( isset( $file_info ) && $file_info['type'] )
  2088. $args['mime_type'] = $file_info['type'];
  2089. }
  2090. $implementation = _wp_image_editor_choose( $args );
  2091. if ( $implementation ) {
  2092. $editor = new $implementation( $path );
  2093. $loaded = $editor->load();
  2094. if ( is_wp_error( $loaded ) )
  2095. return $loaded;
  2096. return $editor;
  2097. }
  2098. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  2099. }
  2100. /**
  2101. * Tests whether there is an editor that supports a given mime type or methods.
  2102. *
  2103. * @since 3.5.0
  2104. * @access public
  2105. *
  2106. * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2107. * @return boolean true if an eligible editor is found; false otherwise
  2108. */
  2109. function wp_image_editor_supports( $args = array() ) {
  2110. return (bool) _wp_image_editor_choose( $args );
  2111. }
  2112. /**
  2113. * Tests which editors are capable of supporting the request.
  2114. *
  2115. * @since 3.5.0
  2116. * @access private
  2117. *
  2118. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2119. * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  2120. */
  2121. function _wp_image_editor_choose( $args = array() ) {
  2122. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  2123. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  2124. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  2125. /**
  2126. * Filter the list of image editing library classes.
  2127. *
  2128. * @since 3.5.0
  2129. *
  2130. * @param array $image_editors List of available image editors. Defaults are
  2131. * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
  2132. */
  2133. $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  2134. foreach ( $implementations as $implementation ) {
  2135. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  2136. continue;
  2137. if ( isset( $args['mime_type'] ) &&
  2138. ! call_user_func(
  2139. array( $implementation, 'supports_mime_type' ),
  2140. $args['mime_type'] ) ) {
  2141. continue;
  2142. }
  2143. if ( isset( $args['methods'] ) &&
  2144. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  2145. continue;
  2146. }
  2147. return $implementation;
  2148. }
  2149. return false;
  2150. }
  2151. /**
  2152. * Prints default plupload arguments.
  2153. *
  2154. * @since 3.4.0
  2155. */
  2156. function wp_plupload_default_settings() {
  2157. global $wp_scripts;
  2158. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  2159. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  2160. return;
  2161. $max_upload_size = wp_max_upload_size();
  2162. $defaults = array(
  2163. 'runtimes' => 'html5,flash,silverlight,html4',
  2164. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  2165. 'url' => admin_url( 'async-upload.php', 'relative' ),
  2166. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  2167. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  2168. 'filters' => array(
  2169. 'max_file_size' => $max_upload_size . 'b',
  2170. ),
  2171. );
  2172. // Multi-file uploading doesn't currently work in iOS Safari,
  2173. // single-file allows the built-in camera to be used as source for images
  2174. if ( wp_is_mobile() )
  2175. $defaults['multi_selection'] = false;
  2176. /**
  2177. * Filter the Plupload default settings.
  2178. *
  2179. * @since 3.4.0
  2180. *
  2181. * @param array $defaults Default Plupload settings array.
  2182. */
  2183. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  2184. $params = array(
  2185. 'action' => 'upload-attachment',
  2186. );
  2187. /**
  2188. * Filter the Plupload default parameters.
  2189. *
  2190. * @since 3.4.0
  2191. *
  2192. * @param array $params Default Plupload parameters array.
  2193. */
  2194. $params = apply_filters( 'plupload_default_params', $params );
  2195. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  2196. $defaults['multipart_params'] = $params;
  2197. $settings = array(
  2198. 'defaults' => $defaults,
  2199. 'browser' => array(
  2200. 'mobile' => wp_is_mobile(),
  2201. 'supported' => _device_can_upload(),
  2202. ),
  2203. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  2204. );
  2205. $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  2206. if ( $data )
  2207. $script = "$data\n$script";
  2208. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  2209. }
  2210. add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  2211. /**
  2212. * Prepares an attachment post object for JS, where it is expected
  2213. * to be JSON-encoded and fit into an Attachment model.
  2214. *
  2215. * @since 3.5.0
  2216. *
  2217. * @param mixed $attachment Attachment ID or object.
  2218. * @return array Array of attachment details.
  2219. */
  2220. function wp_prepare_attachment_for_js( $attachment ) {
  2221. if ( ! $attachment = get_post( $attachment ) )
  2222. return;
  2223. if ( 'attachment' != $attachment->post_type )
  2224. return;
  2225. $meta = wp_get_attachment_metadata( $attachment->ID );
  2226. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  2227. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  2228. else
  2229. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  2230. $attachment_url = wp_get_attachment_url( $attachment->ID );
  2231. $response = array(
  2232. 'id' => $attachment->ID,
  2233. 'title' => $attachment->post_title,
  2234. 'filename' => wp_basename( $attachment->guid ),
  2235. 'url' => $attachment_url,
  2236. 'link' => get_attachment_link( $attachment->ID ),
  2237. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  2238. 'author' => $attachment->post_author,
  2239. 'description' => $attachment->post_content,
  2240. 'caption' => $attachment->post_excerpt,
  2241. 'name' => $attachment->post_name,
  2242. 'status' => $attachment->post_status,
  2243. 'uploadedTo' => $attachment->post_parent,
  2244. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  2245. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  2246. 'menuOrder' => $attachment->menu_order,
  2247. 'mime' => $attachment->post_mime_type,
  2248. 'type' => $type,
  2249. 'subtype' => $subtype,
  2250. 'icon' => wp_mime_type_icon( $attachment->ID ),
  2251. 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  2252. 'nonces' => array(
  2253. 'update' => false,
  2254. 'delete' => false,
  2255. 'edit' => false
  2256. ),
  2257. 'editLink' => false,
  2258. );
  2259. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  2260. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  2261. $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  2262. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  2263. }
  2264. if ( current_user_can( 'delete_post', $attachment->ID ) )
  2265. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  2266. if ( $meta && 'image' === $type ) {
  2267. $sizes = array();
  2268. /** This filter is documented in wp-admin/includes/media.php */
  2269. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  2270. 'thumbnail' => __('Thumbnail'),
  2271. 'medium' => __('Medium'),
  2272. 'large' => __('Large'),
  2273. 'full' => __('Full Size'),
  2274. ) );
  2275. unset( $possible_sizes['full'] );
  2276. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  2277. // First: run the image_downsize filter. If it returns something, we can use its data.
  2278. // If the filter does not return something, then image_downsize() is just an expensive
  2279. // way to check the image metadata, which we do second.
  2280. foreach ( $possible_sizes as $size => $label ) {
  2281. /** This filter is documented in wp-includes/media.php */
  2282. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  2283. if ( ! $downsize[3] )
  2284. continue;
  2285. $sizes[ $size ] = array(
  2286. 'height' => $downsize[2],
  2287. 'width' => $downsize[1],
  2288. 'url' => $downsize[0],
  2289. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  2290. );
  2291. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  2292. if ( ! isset( $base_url ) )
  2293. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  2294. // Nothing from the filter, so consult image metadata if we have it.
  2295. $size_meta = $meta['sizes'][ $size ];
  2296. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  2297. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  2298. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  2299. $sizes[ $size ] = array(
  2300. 'height' => $height,
  2301. 'width' => $width,
  2302. 'url' => $base_url . $size_meta['file'],
  2303. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  2304. );
  2305. }
  2306. }
  2307. $sizes['full'] = array( 'url' => $attachment_url );
  2308. if ( isset( $meta['height'], $meta['width'] ) ) {
  2309. $sizes['full']['height'] = $meta['height'];
  2310. $sizes['full']['width'] = $meta['width'];
  2311. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  2312. }
  2313. $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
  2314. } elseif ( $meta && 'video' === $type ) {
  2315. if ( isset( $meta['width'] ) )
  2316. $response['width'] = (int) $meta['width'];
  2317. if ( isset( $meta['height'] ) )
  2318. $response['height'] = (int) $meta['height'];
  2319. }
  2320. if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  2321. if ( isset( $meta['length_formatted'] ) )
  2322. $response['fileLength'] = $meta['length_formatted'];
  2323. $response['meta'] = array();
  2324. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  2325. if ( ! empty( $meta[ $key ] ) ) {
  2326. $response['meta'][ $key ] = $meta[ $key ];
  2327. }
  2328. }
  2329. $id = get_post_thumbnail_id( $attachment->ID );
  2330. if ( ! empty( $id ) ) {
  2331. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  2332. $response['image'] = compact( 'src', 'width', 'height' );
  2333. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  2334. $response['thumb'] = compact( 'src', 'width', 'height' );
  2335. } else {
  2336. $src = wp_mime_type_icon( $attachment->ID );
  2337. $width = 48;
  2338. $height = 64;
  2339. $response['image'] = compact( 'src', 'width', 'height' );
  2340. $response['thumb'] = compact( 'src', 'width', 'height' );
  2341. }
  2342. }
  2343. if ( function_exists('get_compat_media_markup') )
  2344. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  2345. /**
  2346. * Filter the attachment data prepared for JavaScript.
  2347. *
  2348. * @since 3.5.0
  2349. *
  2350. * @param array $response Array of prepared attachment data.
  2351. * @param int|object $attachment Attachment ID or object.
  2352. * @param array $meta Array of attachment meta data.
  2353. */
  2354. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  2355. }
  2356. /**
  2357. * Enqueues all scripts, styles, settings, and templates necessary to use
  2358. * all media JS APIs.
  2359. *
  2360. * @since 3.5.0
  2361. */
  2362. function wp_enqueue_media( $args = array() ) {
  2363. // Enqueue me just once per page, please.
  2364. if ( did_action( 'wp_enqueue_media' ) )
  2365. return;
  2366. global $content_width;
  2367. $defaults = array(
  2368. 'post' => null,
  2369. );
  2370. $args = wp_parse_args( $args, $defaults );
  2371. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  2372. // to ensure plugins will work. We will then unset those tabs.
  2373. $tabs = array(
  2374. // handler action suffix => tab label
  2375. 'type' => '',
  2376. 'type_url' => '',
  2377. 'gallery' => '',
  2378. 'library' => '',
  2379. );
  2380. /** This filter is documented in wp-admin/includes/media.php */
  2381. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  2382. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  2383. $props = array(
  2384. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  2385. 'align' => get_option( 'image_default_align' ), // empty default
  2386. 'size' => get_option( 'image_default_size' ), // empty default
  2387. );
  2388. $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
  2389. $mimes = get_allowed_mime_types();
  2390. $ext_mimes = array();
  2391. foreach ( $exts as $ext ) {
  2392. foreach ( $mimes as $ext_preg => $mime_match ) {
  2393. if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
  2394. $ext_mimes[ $ext ] = $mime_match;
  2395. break;
  2396. }
  2397. }
  2398. }
  2399. $audio = $video = 0;
  2400. $counts = (array) wp_count_attachments();
  2401. foreach ( $counts as $mime => $total ) {
  2402. if ( 0 === strpos( $mime, 'audio/' ) ) {
  2403. $audio += (int) $total;
  2404. } elseif ( 0 === strpos( $mime, 'video/' ) ) {
  2405. $video += (int) $total;
  2406. }
  2407. }
  2408. $settings = array(
  2409. 'tabs' => $tabs,
  2410. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  2411. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  2412. /** This filter is documented in wp-admin/includes/media.php */
  2413. 'captions' => ! apply_filters( 'disable_captions', '' ),
  2414. 'nonce' => array(
  2415. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  2416. ),
  2417. 'post' => array(
  2418. 'id' => 0,
  2419. ),
  2420. 'defaultProps' => $props,
  2421. 'attachmentCounts' => array(
  2422. 'audio' => $audio,
  2423. 'video' => $video
  2424. ),
  2425. 'embedExts' => $exts,
  2426. 'embedMimes' => $ext_mimes,
  2427. 'contentWidth' => $content_width,
  2428. );
  2429. $post = null;
  2430. if ( isset( $args['post'] ) ) {
  2431. $post = get_post( $args['post'] );
  2432. $settings['post'] = array(
  2433. 'id' => $post->ID,
  2434. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  2435. );
  2436. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
  2437. if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
  2438. if ( 0 === strpos( $post->post_mime_type, 'audio/' ) ) {
  2439. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  2440. } elseif ( 0 === strpos( $post->post_mime_type, 'video/' ) ) {
  2441. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  2442. }
  2443. }
  2444. if ( $thumbnail_support ) {
  2445. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  2446. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  2447. }
  2448. }
  2449. $hier = $post && is_post_type_hierarchical( $post->post_type );
  2450. $strings = array(
  2451. // Generic
  2452. 'url' => __( 'URL' ),
  2453. 'addMedia' => __( 'Add Media' ),
  2454. 'search' => __( 'Search' ),
  2455. 'select' => __( 'Select' ),
  2456. 'cancel' => __( 'Cancel' ),
  2457. 'update' => __( 'Update' ),
  2458. 'replace' => __( 'Replace' ),
  2459. 'remove' => __( 'Remove' ),
  2460. 'back' => __( 'Back' ),
  2461. /* translators: This is a would-be plural string used in the media manager.
  2462. If there is not a word you can use in your language to avoid issues with the
  2463. lack of plural support here, turn it into "selected: %d" then translate it.
  2464. */
  2465. 'selected' => __( '%d selected' ),
  2466. 'dragInfo' => __( 'Drag and drop to reorder images.' ),
  2467. // Upload
  2468. 'uploadFilesTitle' => __( 'Upload Files' ),
  2469. 'uploadImagesTitle' => __( 'Upload Images' ),
  2470. // Library
  2471. 'mediaLibraryTitle' => __( 'Media Library' ),
  2472. 'insertMediaTitle' => __( 'Insert Media' ),
  2473. 'createNewGallery' => __( 'Create a new gallery' ),
  2474. 'createNewPlaylist' => __( 'Create a new playlist' ),
  2475. 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  2476. 'returnToLibrary' => __( '&#8592; Return to library' ),
  2477. 'allMediaItems' => __( 'All media items' ),
  2478. 'noItemsFound' => __( 'No items found.' ),
  2479. 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
  2480. 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
  2481. 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
  2482. // From URL
  2483. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  2484. // Featured Images
  2485. 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
  2486. 'setFeaturedImage' => __( 'Set featured image' ),
  2487. // Gallery
  2488. 'createGalleryTitle' => __( 'Create Gallery' ),
  2489. 'editGalleryTitle' => __( 'Edit Gallery' ),
  2490. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  2491. 'insertGallery' => __( 'Insert gallery' ),
  2492. 'updateGallery' => __( 'Update gallery' ),
  2493. 'addToGallery' => __( 'Add to gallery' ),
  2494. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  2495. 'reverseOrder' => __( 'Reverse order' ),
  2496. // Edit Image
  2497. 'imageDetailsTitle' => __( 'Image Details' ),
  2498. 'imageReplaceTitle' => __( 'Replace Image' ),
  2499. 'imageDetailsCancel' => __( 'Cancel Edit' ),
  2500. 'editImage' => __( 'Edit Image' ),
  2501. // Crop Image
  2502. 'chooseImage' => __( 'Choose Image' ),
  2503. 'selectAndCrop' => __( 'Select and Crop' ),
  2504. 'skipCropping' => __( 'Skip Cropping' ),
  2505. 'cropImage' => __( 'Crop Image' ),
  2506. 'cropYourImage' => __( 'Crop your image' ),
  2507. 'cropping' => __( 'Cropping&hellip;' ),
  2508. 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
  2509. 'cropError' => __( 'There has been an error cropping your image.' ),
  2510. // Edit Audio
  2511. 'audioDetailsTitle' => __( 'Audio Details' ),
  2512. 'audioReplaceTitle' => __( 'Replace Audio' ),
  2513. 'audioAddSourceTitle' => __( 'Add Audio Source' ),
  2514. 'audioDetailsCancel' => __( 'Cancel Edit' ),
  2515. // Edit Video
  2516. 'videoDetailsTitle' => __( 'Video Details' ),
  2517. 'videoReplaceTitle' => __( 'Replace Video' ),
  2518. 'videoAddSourceTitle' => __( 'Add Video Source' ),
  2519. 'videoDetailsCancel' => __( 'Cancel Edit' ),
  2520. 'videoSelectPosterImageTitle' => _( 'Select Poster Image' ),
  2521. 'videoAddTrackTitle' => __( 'Add Subtitles' ),
  2522. // Playlist
  2523. 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
  2524. 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
  2525. 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
  2526. 'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
  2527. 'insertPlaylist' => __( 'Insert audio playlist' ),
  2528. 'updatePlaylist' => __( 'Update audio playlist' ),
  2529. 'addToPlaylist' => __( 'Add to audio playlist' ),
  2530. 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
  2531. // Video Playlist
  2532. 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
  2533. 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
  2534. 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
  2535. 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
  2536. 'insertVideoPlaylist' => __( 'Insert video playlist' ),
  2537. 'updateVideoPlaylist' => __( 'Update video playlist' ),
  2538. 'addToVideoPlaylist' => __( 'Add to video playlist' ),
  2539. 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
  2540. );
  2541. /**
  2542. * Filter the media view settings.
  2543. *
  2544. * @since 3.5.0
  2545. *
  2546. * @param array $settings List of media view settings.
  2547. * @param WP_Post $post Post object.
  2548. */
  2549. $settings = apply_filters( 'media_view_settings', $settings, $post );
  2550. /**
  2551. * Filter the media view strings.
  2552. *
  2553. * @since 3.5.0
  2554. *
  2555. * @param array $strings List of media view strings.
  2556. * @param WP_Post $post Post object.
  2557. */
  2558. $strings = apply_filters( 'media_view_strings', $strings, $post );
  2559. $strings['settings'] = $settings;
  2560. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  2561. wp_enqueue_script( 'media-editor' );
  2562. wp_enqueue_script( 'media-audiovideo' );
  2563. wp_enqueue_style( 'media-views' );
  2564. if ( is_admin() ) {
  2565. wp_enqueue_script( 'mce-view' );
  2566. wp_enqueue_script( 'image-edit' );
  2567. }
  2568. wp_enqueue_style( 'imgareaselect' );
  2569. wp_plupload_default_settings();
  2570. require_once ABSPATH . WPINC . '/media-template.php';
  2571. add_action( 'admin_footer', 'wp_print_media_templates' );
  2572. add_action( 'wp_footer', 'wp_print_media_templates' );
  2573. add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
  2574. /**
  2575. * Fires at the conclusion of wp_enqueue_media().
  2576. *
  2577. * @since 3.5.0
  2578. */
  2579. do_action( 'wp_enqueue_media' );
  2580. }
  2581. /**
  2582. * Retrieve media attached to the passed post.
  2583. *
  2584. * @since 3.6.0
  2585. *
  2586. * @param string $type (Mime) type of media desired
  2587. * @param mixed $post Post ID or object
  2588. * @return array Found attachments
  2589. */
  2590. function get_attached_media( $type, $post = 0 ) {
  2591. if ( ! $post = get_post( $post ) )
  2592. return array();
  2593. $args = array(
  2594. 'post_parent' => $post->ID,
  2595. 'post_type' => 'attachment',
  2596. 'post_mime_type' => $type,
  2597. 'posts_per_page' => -1,
  2598. 'orderby' => 'menu_order',
  2599. 'order' => 'ASC',
  2600. );
  2601. /**
  2602. * Filter arguments used to retrieve media attached to the given post.
  2603. *
  2604. * @since 3.6.0
  2605. *
  2606. * @param array $args Post query arguments.
  2607. * @param string $type Mime type of the desired media.
  2608. * @param mixed $post Post ID or object.
  2609. */
  2610. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  2611. $children = get_children( $args );
  2612. /**
  2613. * Filter the
  2614. *
  2615. * @since 3.6.0
  2616. *
  2617. * @param array $children Associative array of media attached to the given post.
  2618. * @param string $type Mime type of the media desired.
  2619. * @param mixed $post Post ID or object.
  2620. */
  2621. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  2622. }
  2623. /**
  2624. * Check the content blob for an <audio>, <video> <object>, <embed>, or <iframe>
  2625. *
  2626. * @since 3.6.0
  2627. *
  2628. * @param string $content A string which might contain media data.
  2629. * @param array $types array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'
  2630. * @return array A list of found HTML media embeds
  2631. */
  2632. function get_media_embedded_in_content( $content, $types = null ) {
  2633. $html = array();
  2634. $allowed_media_types = array( 'audio', 'video', 'object', 'embed', 'iframe' );
  2635. if ( ! empty( $types ) ) {
  2636. if ( ! is_array( $types ) )
  2637. $types = array( $types );
  2638. $allowed_media_types = array_intersect( $allowed_media_types, $types );
  2639. }
  2640. foreach ( $allowed_media_types as $tag ) {
  2641. if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
  2642. $html[] = $matches[0];
  2643. }
  2644. }
  2645. return $html;
  2646. }
  2647. /**
  2648. * Retrieve galleries from the passed post's content.
  2649. *
  2650. * @since 3.6.0
  2651. *
  2652. * @param int|WP_Post $post Optional. Post ID or object.
  2653. * @param bool $html Whether to return HTML or data in the array.
  2654. * @return array A list of arrays, each containing gallery data and srcs parsed
  2655. * from the expanded shortcode.
  2656. */
  2657. function get_post_galleries( $post, $html = true ) {
  2658. if ( ! $post = get_post( $post ) )
  2659. return array();
  2660. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  2661. return array();
  2662. $galleries = array();
  2663. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  2664. foreach ( $matches as $shortcode ) {
  2665. if ( 'gallery' === $shortcode[2] ) {
  2666. $srcs = array();
  2667. $count = 1;
  2668. $gallery = do_shortcode_tag( $shortcode );
  2669. if ( $html ) {
  2670. $galleries[] = $gallery;
  2671. } else {
  2672. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  2673. if ( ! empty( $src ) ) {
  2674. foreach ( $src as $s )
  2675. $srcs[] = $s[2];
  2676. }
  2677. $data = shortcode_parse_atts( $shortcode[3] );
  2678. $data['src'] = array_values( array_unique( $srcs ) );
  2679. $galleries[] = $data;
  2680. }
  2681. }
  2682. }
  2683. }
  2684. /**
  2685. * Filter the list of all found galleries in the given post.
  2686. *
  2687. * @since 3.6.0
  2688. *
  2689. * @param array $galleries Associative array of all found post galleries.
  2690. * @param WP_Post $post Post object.
  2691. */
  2692. return apply_filters( 'get_post_galleries', $galleries, $post );
  2693. }
  2694. /**
  2695. * Check a specified post's content for gallery and, if present, return the first
  2696. *
  2697. * @since 3.6.0
  2698. *
  2699. * @param int|WP_Post $post Optional. Post ID or object.
  2700. * @param bool $html Whether to return HTML or data.
  2701. * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  2702. */
  2703. function get_post_gallery( $post = 0, $html = true ) {
  2704. $galleries = get_post_galleries( $post, $html );
  2705. $gallery = reset( $galleries );
  2706. /**
  2707. * Filter the first-found post gallery.
  2708. *
  2709. * @since 3.6.0
  2710. *
  2711. * @param array $gallery The first-found post gallery.
  2712. * @param int|WP_Post $post Post ID or object.
  2713. * @param array $galleries Associative array of all found post galleries.
  2714. */
  2715. return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  2716. }
  2717. /**
  2718. * Retrieve the image srcs from galleries from a post's content, if present
  2719. *
  2720. * @since 3.6.0
  2721. *
  2722. * @param mixed $post Optional. Post ID or object.
  2723. * @return array A list of lists, each containing image srcs parsed
  2724. * from an expanded shortcode
  2725. */
  2726. function get_post_galleries_images( $post = 0 ) {
  2727. $galleries = get_post_galleries( $post, false );
  2728. return wp_list_pluck( $galleries, 'src' );
  2729. }
  2730. /**
  2731. * Check a post's content for galleries and return the image srcs for the first found gallery
  2732. *
  2733. * @since 3.6.0
  2734. *
  2735. * @param mixed $post Optional. Post ID or object.
  2736. * @return array A list of a gallery's image srcs in order
  2737. */
  2738. function get_post_gallery_images( $post = 0 ) {
  2739. $gallery = get_post_gallery( $post, false );
  2740. return empty( $gallery['src'] ) ? array() : $gallery['src'];
  2741. }
  2742. /**
  2743. * Maybe attempt to generate attachment metadata, if missing.
  2744. *
  2745. * @since 3.9.0
  2746. *
  2747. * @param WP_Post $attachment Attachment object.
  2748. */
  2749. function wp_maybe_generate_attachment_metadata( $attachment ) {
  2750. if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
  2751. return;
  2752. }
  2753. $file = get_attached_file( $attachment_id );
  2754. $meta = wp_get_attachment_metadata( $attachment_id );
  2755. if ( empty( $meta ) && file_exists( $file ) ) {
  2756. $_meta = get_post_meta( $attachment_id );
  2757. $regeneration_lock = 'wp_generating_att_' . $attachment_id;
  2758. if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
  2759. set_transient( $regeneration_lock, $file );
  2760. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
  2761. delete_transient( $regeneration_lock );
  2762. }
  2763. }
  2764. }