PageRenderTime 38ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/media.php

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