PageRenderTime 317ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

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