PageRenderTime 73ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/media.php

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