PageRenderTime 70ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/media.php

https://github.com/dedavidd/piratenpartij.nl
PHP | 3220 lines | 1581 code | 342 blank | 1297 comment | 320 complexity | d6f8a198c5c351d87dcd1be6833d0336 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, GPL-3.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"><?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. }
  1321. /**
  1322. * Filter the editable list of keys to look up data from an attachment's metadata.
  1323. *
  1324. * @since 3.9.0
  1325. *
  1326. * @param array $fields Key/value pairs of field keys to labels.
  1327. * @param WP_Post $attachment Attachment object.
  1328. * @param string $context The context. Accepts 'edit', 'display'. Default 'display'.
  1329. */
  1330. return apply_filters( 'wp_get_attachment_id3_keys', $fields, $attachment, $context );
  1331. }
  1332. /**
  1333. * The Audio shortcode.
  1334. *
  1335. * This implements the functionality of the Audio Shortcode for displaying
  1336. * WordPress mp3s in a post.
  1337. *
  1338. * @since 3.6.0
  1339. *
  1340. * @param array $attr {
  1341. * Attributes of the audio shortcode.
  1342. *
  1343. * @type string $src URL to the source of the audio file. Default empty.
  1344. * @type string $loop The 'loop' attribute for the `<audio>` element. Default empty.
  1345. * @type string $autoplay The 'autoplay' attribute for the `<audio>` element. Default empty.
  1346. * @type string $preload The 'preload' attribute for the `<audio>` element. Default empty.
  1347. * @type string $class The 'class' attribute for the `<audio>` element. Default 'wp-audio-shortcode'.
  1348. * @type string $id The 'id' attribute for the `<audio>` element. Default 'audio-{$post_id}-{$instances}'.
  1349. * @type string $style The 'style' attribute for the `<audio>` element. Default 'width: 100%'.
  1350. * }
  1351. * @param string $content Optional. Shortcode content.
  1352. * @return string HTML content to display audio.
  1353. */
  1354. function wp_audio_shortcode( $attr, $content = '' ) {
  1355. $post_id = get_post() ? get_the_ID() : 0;
  1356. static $instances = 0;
  1357. $instances++;
  1358. /**
  1359. * Filter the default audio shortcode output.
  1360. *
  1361. * If the filtered output isn't empty, it will be used instead of generating the default audio template.
  1362. *
  1363. * @since 3.6.0
  1364. *
  1365. * @param string $html Empty variable to be replaced with shortcode markup.
  1366. * @param array $attr Attributes of the shortcode. @see wp_audio_shortcode()
  1367. * @param string $content Shortcode content.
  1368. * @param int $instances Unique numeric ID of this audio shortcode instance.
  1369. */
  1370. $override = apply_filters( 'wp_audio_shortcode_override', '', $attr, $content, $instances );
  1371. if ( '' !== $override ) {
  1372. return $override;
  1373. }
  1374. $audio = null;
  1375. $default_types = wp_get_audio_extensions();
  1376. $defaults_atts = array(
  1377. 'src' => '',
  1378. 'loop' => '',
  1379. 'autoplay' => '',
  1380. 'preload' => 'none'
  1381. );
  1382. foreach ( $default_types as $type ) {
  1383. $defaults_atts[$type] = '';
  1384. }
  1385. $atts = shortcode_atts( $defaults_atts, $attr, 'audio' );
  1386. $primary = false;
  1387. if ( ! empty( $atts['src'] ) ) {
  1388. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  1389. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  1390. return sprintf( '<a class="wp-embedded-audio" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  1391. }
  1392. $primary = true;
  1393. array_unshift( $default_types, 'src' );
  1394. } else {
  1395. foreach ( $default_types as $ext ) {
  1396. if ( ! empty( $atts[ $ext ] ) ) {
  1397. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  1398. if ( strtolower( $type['ext'] ) === $ext ) {
  1399. $primary = true;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. if ( ! $primary ) {
  1405. $audios = get_attached_media( 'audio', $post_id );
  1406. if ( empty( $audios ) ) {
  1407. return;
  1408. }
  1409. $audio = reset( $audios );
  1410. $atts['src'] = wp_get_attachment_url( $audio->ID );
  1411. if ( empty( $atts['src'] ) ) {
  1412. return;
  1413. }
  1414. array_unshift( $default_types, 'src' );
  1415. }
  1416. /**
  1417. * Filter the media library used for the audio shortcode.
  1418. *
  1419. * @since 3.6.0
  1420. *
  1421. * @param string $library Media library used for the audio shortcode.
  1422. */
  1423. $library = apply_filters( 'wp_audio_shortcode_library', 'mediaelement' );
  1424. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1425. wp_enqueue_style( 'wp-mediaelement' );
  1426. wp_enqueue_script( 'wp-mediaelement' );
  1427. }
  1428. /**
  1429. * Filter the class attribute for the audio shortcode output container.
  1430. *
  1431. * @since 3.6.0
  1432. *
  1433. * @param string $class CSS class or list of space-separated classes.
  1434. */
  1435. $html_atts = array(
  1436. 'class' => apply_filters( 'wp_audio_shortcode_class', 'wp-audio-shortcode' ),
  1437. 'id' => sprintf( 'audio-%d-%d', $post_id, $instances ),
  1438. 'loop' => $atts['loop'],
  1439. 'autoplay' => $atts['autoplay'],
  1440. 'preload' => $atts['preload'],
  1441. 'style' => 'width: 100%; visibility: hidden;',
  1442. );
  1443. // These ones should just be omitted altogether if they are blank
  1444. foreach ( array( 'loop', 'autoplay', 'preload' ) as $a ) {
  1445. if ( empty( $html_atts[$a] ) ) {
  1446. unset( $html_atts[$a] );
  1447. }
  1448. }
  1449. $attr_strings = array();
  1450. foreach ( $html_atts as $k => $v ) {
  1451. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1452. }
  1453. $html = '';
  1454. if ( 'mediaelement' === $library && 1 === $instances ) {
  1455. $html .= "<!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->\n";
  1456. }
  1457. $html .= sprintf( '<audio %s controls="controls">', join( ' ', $attr_strings ) );
  1458. $fileurl = '';
  1459. $source = '<source type="%s" src="%s" />';
  1460. foreach ( $default_types as $fallback ) {
  1461. if ( ! empty( $atts[ $fallback ] ) ) {
  1462. if ( empty( $fileurl ) ) {
  1463. $fileurl = $atts[ $fallback ];
  1464. }
  1465. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  1466. $url = add_query_arg( '_', $instances, $atts[ $fallback ] );
  1467. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  1468. }
  1469. }
  1470. if ( 'mediaelement' === $library ) {
  1471. $html .= wp_mediaelement_fallback( $fileurl );
  1472. }
  1473. $html .= '</audio>';
  1474. /**
  1475. * Filter the audio shortcode output.
  1476. *
  1477. * @since 3.6.0
  1478. *
  1479. * @param string $html Audio shortcode HTML output.
  1480. * @param array $atts Array of audio shortcode attributes.
  1481. * @param string $audio Audio file.
  1482. * @param int $post_id Post ID.
  1483. * @param string $library Media library used for the audio shortcode.
  1484. */
  1485. return apply_filters( 'wp_audio_shortcode', $html, $atts, $audio, $post_id, $library );
  1486. }
  1487. add_shortcode( 'audio', 'wp_audio_shortcode' );
  1488. /**
  1489. * Return a filtered list of WP-supported video formats
  1490. *
  1491. * @since 3.6.0
  1492. * @return array
  1493. */
  1494. function wp_get_video_extensions() {
  1495. /**
  1496. * Filter the list of supported video formats.
  1497. *
  1498. * @since 3.6.0
  1499. *
  1500. * @param array $extensions An array of support video formats. Defaults are
  1501. * 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv'.
  1502. */
  1503. return apply_filters( 'wp_video_extensions', array( 'mp4', 'm4v', 'webm', 'ogv', 'wmv', 'flv' ) );
  1504. }
  1505. /**
  1506. * The Video shortcode.
  1507. *
  1508. * This implements the functionality of the Video Shortcode for displaying
  1509. * WordPress mp4s in a post.
  1510. *
  1511. * @since 3.6.0
  1512. *
  1513. * @param array $attr {
  1514. * Attributes of the shortcode.
  1515. *
  1516. * @type string $src URL to the source of the video file. Default empty.
  1517. * @type int $height Height of the video embed in pixels. Default 360.
  1518. * @type int $width Width of the video embed in pixels. Default $content_width or 640.
  1519. * @type string $poster The 'poster' attribute for the `<video>` element. Default empty.
  1520. * @type string $loop The 'loop' attribute for the `<video>` element. Default empty.
  1521. * @type string $autoplay The 'autoplay' attribute for the `<video>` element. Default empty.
  1522. * @type string $preload The 'preload' attribute for the `<video>` element.
  1523. * Default 'metadata'.
  1524. * @type string $class The 'class' attribute for the `<video>` element.
  1525. * Default 'wp-video-shortcode'.
  1526. * @type string $id The 'id' attribute for the `<video>` element.
  1527. * Default 'video-{$post_id}-{$instances}'.
  1528. * }
  1529. * @param string $content Optional. Shortcode content.
  1530. * @return string HTML content to display video.
  1531. */
  1532. function wp_video_shortcode( $attr, $content = '' ) {
  1533. global $content_width;
  1534. $post_id = get_post() ? get_the_ID() : 0;
  1535. static $instances = 0;
  1536. $instances++;
  1537. /**
  1538. * Filter the default video shortcode output.
  1539. *
  1540. * If the filtered output isn't empty, it will be used instead of generating
  1541. * the default video template.
  1542. *
  1543. * @since 3.6.0
  1544. *
  1545. * @see wp_video_shortcode()
  1546. *
  1547. * @param string $html Empty variable to be replaced with shortcode markup.
  1548. * @param array $attr Attributes of the video shortcode.
  1549. * @param string $content Video shortcode content.
  1550. * @param int $instances Unique numeric ID of this video shortcode instance.
  1551. */
  1552. $override = apply_filters( 'wp_video_shortcode_override', '', $attr, $content, $instances );
  1553. if ( '' !== $override ) {
  1554. return $override;
  1555. }
  1556. $video = null;
  1557. $default_types = wp_get_video_extensions();
  1558. $defaults_atts = array(
  1559. 'src' => '',
  1560. 'poster' => '',
  1561. 'loop' => '',
  1562. 'autoplay' => '',
  1563. 'preload' => 'metadata',
  1564. 'width' => 640,
  1565. 'height' => 360,
  1566. );
  1567. foreach ( $default_types as $type ) {
  1568. $defaults_atts[$type] = '';
  1569. }
  1570. $atts = shortcode_atts( $defaults_atts, $attr, 'video' );
  1571. if ( is_admin() ) {
  1572. // shrink the video so it isn't huge in the admin
  1573. if ( $atts['width'] > $defaults_atts['width'] ) {
  1574. $atts['height'] = round( ( $atts['height'] * $defaults_atts['width'] ) / $atts['width'] );
  1575. $atts['width'] = $defaults_atts['width'];
  1576. }
  1577. } else {
  1578. // if the video is bigger than the theme
  1579. if ( ! empty( $content_width ) && $atts['width'] > $content_width ) {
  1580. $atts['height'] = round( ( $atts['height'] * $content_width ) / $atts['width'] );
  1581. $atts['width'] = $content_width;
  1582. }
  1583. }
  1584. $yt_pattern = '#^https?://(:?www\.)?(:?youtube\.com/watch|youtu\.be/)#';
  1585. $primary = false;
  1586. if ( ! empty( $atts['src'] ) ) {
  1587. if ( ! preg_match( $yt_pattern, $atts['src'] ) ) {
  1588. $type = wp_check_filetype( $atts['src'], wp_get_mime_types() );
  1589. if ( ! in_array( strtolower( $type['ext'] ), $default_types ) ) {
  1590. return sprintf( '<a class="wp-embedded-video" href="%s">%s</a>', esc_url( $atts['src'] ), esc_html( $atts['src'] ) );
  1591. }
  1592. }
  1593. $primary = true;
  1594. array_unshift( $default_types, 'src' );
  1595. } else {
  1596. foreach ( $default_types as $ext ) {
  1597. if ( ! empty( $atts[ $ext ] ) ) {
  1598. $type = wp_check_filetype( $atts[ $ext ], wp_get_mime_types() );
  1599. if ( strtolower( $type['ext'] ) === $ext ) {
  1600. $primary = true;
  1601. }
  1602. }
  1603. }
  1604. }
  1605. if ( ! $primary ) {
  1606. $videos = get_attached_media( 'video', $post_id );
  1607. if ( empty( $videos ) ) {
  1608. return;
  1609. }
  1610. $video = reset( $videos );
  1611. $atts['src'] = wp_get_attachment_url( $video->ID );
  1612. if ( empty( $atts['src'] ) ) {
  1613. return;
  1614. }
  1615. array_unshift( $default_types, 'src' );
  1616. }
  1617. /**
  1618. * Filter the media library used for the video shortcode.
  1619. *
  1620. * @since 3.6.0
  1621. *
  1622. * @param string $library Media library used for the video shortcode.
  1623. */
  1624. $library = apply_filters( 'wp_video_shortcode_library', 'mediaelement' );
  1625. if ( 'mediaelement' === $library && did_action( 'init' ) ) {
  1626. wp_enqueue_style( 'wp-mediaelement' );
  1627. wp_enqueue_script( 'wp-mediaelement' );
  1628. }
  1629. /**
  1630. * Filter the class attribute for the video shortcode output container.
  1631. *
  1632. * @since 3.6.0
  1633. *
  1634. * @param string $class CSS class or list of space-separated classes.
  1635. */
  1636. $html_atts = array(
  1637. 'class' => apply_filters( 'wp_video_shortcode_class', 'wp-video-shortcode' ),
  1638. 'id' => sprintf( 'video-%d-%d', $post_id, $instances ),
  1639. 'width' => absint( $atts['width'] ),
  1640. 'height' => absint( $atts['height'] ),
  1641. 'poster' => esc_url( $atts['poster'] ),
  1642. 'loop' => $atts['loop'],
  1643. 'autoplay' => $atts['autoplay'],
  1644. 'preload' => $atts['preload'],
  1645. );
  1646. // These ones should just be omitted altogether if they are blank
  1647. foreach ( array( 'poster', 'loop', 'autoplay', 'preload' ) as $a ) {
  1648. if ( empty( $html_atts[$a] ) ) {
  1649. unset( $html_atts[$a] );
  1650. }
  1651. }
  1652. $attr_strings = array();
  1653. foreach ( $html_atts as $k => $v ) {
  1654. $attr_strings[] = $k . '="' . esc_attr( $v ) . '"';
  1655. }
  1656. $html = '';
  1657. if ( 'mediaelement' === $library && 1 === $instances ) {
  1658. $html .= "<!--[if lt IE 9]><script>document.createElement('video');</script><![endif]-->\n";
  1659. }
  1660. $html .= sprintf( '<video %s controls="controls">', join( ' ', $attr_strings ) );
  1661. $fileurl = '';
  1662. $source = '<source type="%s" src="%s" />';
  1663. foreach ( $default_types as $fallback ) {
  1664. if ( ! empty( $atts[ $fallback ] ) ) {
  1665. if ( empty( $fileurl ) ) {
  1666. $fileurl = $atts[ $fallback ];
  1667. }
  1668. if ( 'src' === $fallback && preg_match( $yt_pattern, $atts['src'] ) ) {
  1669. $type = array( 'type' => 'video/youtube' );
  1670. } else {
  1671. $type = wp_check_filetype( $atts[ $fallback ], wp_get_mime_types() );
  1672. }
  1673. $url = add_query_arg( '_', $instances, $atts[ $fallback ] );
  1674. $html .= sprintf( $source, $type['type'], esc_url( $url ) );
  1675. }
  1676. }
  1677. if ( ! empty( $content ) ) {
  1678. if ( false !== strpos( $content, "\n" ) ) {
  1679. $content = str_replace( array( "\r\n", "\n", "\t" ), '', $content );
  1680. }
  1681. $html .= trim( $content );
  1682. }
  1683. if ( 'mediaelement' === $library ) {
  1684. $html .= wp_mediaelement_fallback( $fileurl );
  1685. }
  1686. $html .= '</video>';
  1687. $output = sprintf( '<div style="width: %dpx; max-width: 100%%;" class="wp-video">%s</div>', $atts['width'], $html );
  1688. /**
  1689. * Filter the output of the video shortcode.
  1690. *
  1691. * @since 3.6.0
  1692. *
  1693. * @param string $output Video shortcode HTML output.
  1694. * @param array $atts Array of video shortcode attributes.
  1695. * @param string $video Video file.
  1696. * @param int $post_id Post ID.
  1697. * @param string $library Media library used for the video shortcode.
  1698. */
  1699. return apply_filters( 'wp_video_shortcode', $output, $atts, $video, $post_id, $library );
  1700. }
  1701. add_shortcode( 'video', 'wp_video_shortcode' );
  1702. /**
  1703. * Display previous image link that has the same post parent.
  1704. *
  1705. * @since 2.5.0
  1706. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1707. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1708. * @return string HTML content.
  1709. */
  1710. function previous_image_link($size = 'thumbnail', $text = false) {
  1711. adjacent_image_link(true, $size, $text);
  1712. }
  1713. /**
  1714. * Display next image link that has the same post parent.
  1715. *
  1716. * @since 2.5.0
  1717. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text;
  1718. * @param string $text Optional, default is false. If included, link will reflect $text variable.
  1719. * @return string HTML content.
  1720. */
  1721. function next_image_link($size = 'thumbnail', $text = false) {
  1722. adjacent_image_link(false, $size, $text);
  1723. }
  1724. /**
  1725. * Display next or previous image link that has the same post parent.
  1726. *
  1727. * Retrieves the current attachment object from the $post global.
  1728. *
  1729. * @since 2.5.0
  1730. *
  1731. * @param bool $prev Optional. Default is true to display previous link, false for next.
  1732. */
  1733. function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) {
  1734. $post = get_post();
  1735. $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' ) ) );
  1736. foreach ( $attachments as $k => $attachment ) {
  1737. if ( $attachment->ID == $post->ID ) {
  1738. break;
  1739. }
  1740. }
  1741. $output = '';
  1742. $attachment_id = 0;
  1743. if ( $attachments ) {
  1744. $k = $prev ? $k - 1 : $k + 1;
  1745. if ( isset( $attachments[ $k ] ) ) {
  1746. $attachment_id = $attachments[ $k ]->ID;
  1747. $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text );
  1748. }
  1749. }
  1750. $adjacent = $prev ? 'previous' : 'next';
  1751. /**
  1752. * Filter the adjacent image link.
  1753. *
  1754. * The dynamic portion of the hook name, $adjacent, refers to the type of adjacency,
  1755. * either 'next', or 'previous'.
  1756. *
  1757. * @since 3.5.0
  1758. *
  1759. * @param string $output Adjacent image HTML markup.
  1760. * @param int $attachment_id Attachment ID
  1761. * @param string $size Image size.
  1762. * @param string $text Link text.
  1763. */
  1764. echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text );
  1765. }
  1766. /**
  1767. * Retrieve taxonomies attached to the attachment.
  1768. *
  1769. * @since 2.5.0
  1770. *
  1771. * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object.
  1772. * @return array Empty array on failure. List of taxonomies on success.
  1773. */
  1774. function get_attachment_taxonomies($attachment) {
  1775. if ( is_int( $attachment ) )
  1776. $attachment = get_post($attachment);
  1777. else if ( is_array($attachment) )
  1778. $attachment = (object) $attachment;
  1779. if ( ! is_object($attachment) )
  1780. return array();
  1781. $filename = basename($attachment->guid);
  1782. $objects = array('attachment');
  1783. if ( false !== strpos($filename, '.') )
  1784. $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1);
  1785. if ( !empty($attachment->post_mime_type) ) {
  1786. $objects[] = 'attachment:' . $attachment->post_mime_type;
  1787. if ( false !== strpos($attachment->post_mime_type, '/') )
  1788. foreach ( explode('/', $attachment->post_mime_type) as $token )
  1789. if ( !empty($token) )
  1790. $objects[] = "attachment:$token";
  1791. }
  1792. $taxonomies = array();
  1793. foreach ( $objects as $object )
  1794. if ( $taxes = get_object_taxonomies($object) )
  1795. $taxonomies = array_merge($taxonomies, $taxes);
  1796. return array_unique($taxonomies);
  1797. }
  1798. /**
  1799. * Return all of the taxonomy names that are registered for attachments.
  1800. *
  1801. * Handles mime-type-specific taxonomies such as attachment:image and attachment:video.
  1802. *
  1803. * @since 3.5.0
  1804. * @see get_attachment_taxonomies()
  1805. * @uses get_taxonomies()
  1806. *
  1807. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default.
  1808. * @return array The names of all taxonomy of $object_type.
  1809. */
  1810. function get_taxonomies_for_attachments( $output = 'names' ) {
  1811. $taxonomies = array();
  1812. foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) {
  1813. foreach ( $taxonomy->object_type as $object_type ) {
  1814. if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) {
  1815. if ( 'names' == $output )
  1816. $taxonomies[] = $taxonomy->name;
  1817. else
  1818. $taxonomies[ $taxonomy->name ] = $taxonomy;
  1819. break;
  1820. }
  1821. }
  1822. }
  1823. return $taxonomies;
  1824. }
  1825. /**
  1826. * Create new GD image resource with transparency support
  1827. * @TODO: Deprecate if possible.
  1828. *
  1829. * @since 2.9.0
  1830. *
  1831. * @param int $width Image width
  1832. * @param int $height Image height
  1833. * @return image resource
  1834. */
  1835. function wp_imagecreatetruecolor($width, $height) {
  1836. $img = imagecreatetruecolor($width, $height);
  1837. if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) {
  1838. imagealphablending($img, false);
  1839. imagesavealpha($img, true);
  1840. }
  1841. return $img;
  1842. }
  1843. /**
  1844. * Register an embed handler. This function should probably only be used for sites that do not support oEmbed.
  1845. *
  1846. * @since 2.9.0
  1847. * @see WP_Embed::register_handler()
  1848. */
  1849. function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) {
  1850. global $wp_embed;
  1851. $wp_embed->register_handler( $id, $regex, $callback, $priority );
  1852. }
  1853. /**
  1854. * Unregister a previously registered embed handler.
  1855. *
  1856. * @since 2.9.0
  1857. * @see WP_Embed::unregister_handler()
  1858. */
  1859. function wp_embed_unregister_handler( $id, $priority = 10 ) {
  1860. global $wp_embed;
  1861. $wp_embed->unregister_handler( $id, $priority );
  1862. }
  1863. /**
  1864. * Create default array of embed parameters.
  1865. *
  1866. * The width defaults to the content width as specified by the theme. If the
  1867. * theme does not specify a content width, then 500px is used.
  1868. *
  1869. * The default height is 1.5 times the width, or 1000px, whichever is smaller.
  1870. *
  1871. * The 'embed_defaults' filter can be used to adjust either of these values.
  1872. *
  1873. * @since 2.9.0
  1874. *
  1875. * @param string $url Optional. The URL that should be embedded. Default empty.
  1876. *
  1877. * @return array Default embed parameters.
  1878. */
  1879. function wp_embed_defaults( $url = '' ) {
  1880. if ( ! empty( $GLOBALS['content_width'] ) )
  1881. $width = (int) $GLOBALS['content_width'];
  1882. if ( empty( $width ) )
  1883. $width = 500;
  1884. $height = min( ceil( $width * 1.5 ), 1000 );
  1885. /**
  1886. * Filter the default array of embed dimensions.
  1887. *
  1888. * @since 2.9.0
  1889. *
  1890. * @param int $width Width of the embed in pixels.
  1891. * @param int $height Height of the embed in pixels.
  1892. * @param string $url The URL that should be embedded.
  1893. */
  1894. return apply_filters( 'embed_defaults', compact( 'width', 'height' ), $url );
  1895. }
  1896. /**
  1897. * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height.
  1898. *
  1899. * @since 2.9.0
  1900. * @uses wp_constrain_dimensions() This function passes the widths and the heights.
  1901. *
  1902. * @param int $example_width The width of an example embed.
  1903. * @param int $example_height The height of an example embed.
  1904. * @param int $max_width The maximum allowed width.
  1905. * @param int $max_height The maximum allowed height.
  1906. * @return array The maximum possible width and height based on the example ratio.
  1907. */
  1908. function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) {
  1909. $example_width = (int) $example_width;
  1910. $example_height = (int) $example_height;
  1911. $max_width = (int) $max_width;
  1912. $max_height = (int) $max_height;
  1913. return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height );
  1914. }
  1915. /**
  1916. * Attempts to fetch the embed HTML for a provided URL using oEmbed.
  1917. *
  1918. * @since 2.9.0
  1919. * @see WP_oEmbed
  1920. *
  1921. * @uses _wp_oembed_get_object()
  1922. * @uses WP_oEmbed::get_html()
  1923. *
  1924. * @param string $url The URL that should be embedded.
  1925. * @param array $args Additional arguments and parameters.
  1926. * @return bool|string False on failure or the embed HTML on success.
  1927. */
  1928. function wp_oembed_get( $url, $args = '' ) {
  1929. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1930. $oembed = _wp_oembed_get_object();
  1931. return $oembed->get_html( $url, $args );
  1932. }
  1933. /**
  1934. * Adds a URL format and oEmbed provider URL pair.
  1935. *
  1936. * @since 2.9.0
  1937. * @see WP_oEmbed
  1938. *
  1939. * @uses _wp_oembed_get_object()
  1940. *
  1941. * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards.
  1942. * @param string $provider The URL to the oEmbed provider.
  1943. * @param boolean $regex Whether the $format parameter is in a regex format.
  1944. */
  1945. function wp_oembed_add_provider( $format, $provider, $regex = false ) {
  1946. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1947. if ( did_action( 'plugins_loaded' ) ) {
  1948. $oembed = _wp_oembed_get_object();
  1949. $oembed->providers[$format] = array( $provider, $regex );
  1950. } else {
  1951. WP_oEmbed::_add_provider_early( $format, $provider, $regex );
  1952. }
  1953. }
  1954. /**
  1955. * Removes an oEmbed provider.
  1956. *
  1957. * @since 3.5.0
  1958. * @see WP_oEmbed
  1959. *
  1960. * @uses _wp_oembed_get_object()
  1961. *
  1962. * @param string $format The URL format for the oEmbed provider to remove.
  1963. */
  1964. function wp_oembed_remove_provider( $format ) {
  1965. require_once( ABSPATH . WPINC . '/class-oembed.php' );
  1966. if ( did_action( 'plugins_loaded' ) ) {
  1967. $oembed = _wp_oembed_get_object();
  1968. if ( isset( $oembed->providers[ $format ] ) ) {
  1969. unset( $oembed->providers[ $format ] );
  1970. return true;
  1971. }
  1972. } else {
  1973. WP_oEmbed::_remove_provider_early( $format );
  1974. }
  1975. return false;
  1976. }
  1977. /**
  1978. * Determines if default embed handlers should be loaded.
  1979. *
  1980. * Checks to make sure that the embeds library hasn't already been loaded. If
  1981. * it hasn't, then it will load the embeds library.
  1982. *
  1983. * @since 2.9.0
  1984. */
  1985. function wp_maybe_load_embeds() {
  1986. /**
  1987. * Filter whether to load the default embed handlers.
  1988. *
  1989. * Returning a falsey value will prevent loading the default embed handlers.
  1990. *
  1991. * @since 2.9.0
  1992. *
  1993. * @param bool $maybe_load_embeds Whether to load the embeds library. Default true.
  1994. */
  1995. if ( ! apply_filters( 'load_default_embeds', true ) ) {
  1996. return;
  1997. }
  1998. wp_embed_register_handler( 'youtube_embed_url', '#https?://(www.)?youtube\.com/embed/([^/]+)#i', 'wp_embed_handler_youtube' );
  1999. wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' );
  2000. /**
  2001. * Filter the audio embed handler callback.
  2002. *
  2003. * @since 3.6.0
  2004. *
  2005. * @param callback $handler Audio embed handler callback function.
  2006. */
  2007. wp_embed_register_handler( 'audio', '#^https?://.+?\.(' . join( '|', wp_get_audio_extensions() ) . ')$#i', apply_filters( 'wp_audio_embed_handler', 'wp_embed_handler_audio' ), 9999 );
  2008. /**
  2009. * Filter the video embed handler callback.
  2010. *
  2011. * @since 3.6.0
  2012. *
  2013. * @param callback $handler Video embed handler callback function.
  2014. */
  2015. wp_embed_register_handler( 'video', '#^https?://.+?\.(' . join( '|', wp_get_video_extensions() ) . ')$#i', apply_filters( 'wp_video_embed_handler', 'wp_embed_handler_video' ), 9999 );
  2016. }
  2017. /**
  2018. * The Google Video embed handler callback. Google Video does not support oEmbed.
  2019. *
  2020. * @see WP_Embed::register_handler()
  2021. * @see WP_Embed::shortcode()
  2022. *
  2023. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2024. * @param array $attr Embed attributes.
  2025. * @param string $url The original URL that was matched by the regex.
  2026. * @param array $rawattr The original unmodified attributes.
  2027. * @return string The embed HTML.
  2028. */
  2029. function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) {
  2030. // If the user supplied a fixed width AND height, use it
  2031. if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) {
  2032. $width = (int) $rawattr['width'];
  2033. $height = (int) $rawattr['height'];
  2034. } else {
  2035. list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] );
  2036. }
  2037. /**
  2038. * Filter the Google Video embed output.
  2039. *
  2040. * @since 2.9.0
  2041. *
  2042. * @param string $html Google Video HTML embed markup.
  2043. * @param array $matches The regex matches from the provided regex.
  2044. * @param array $attr An array of embed attributes.
  2045. * @param string $url The original URL that was matched by the regex.
  2046. * @param array $rawattr The original unmodified attributes.
  2047. */
  2048. return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&amp;hl=en&amp;fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr );
  2049. }
  2050. /**
  2051. * The YouTube embed handler callback. Catches URLs that can be parsed but aren't supported by oEmbed.
  2052. *
  2053. * @since 4.0.0
  2054. *
  2055. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2056. * @param array $attr Embed attributes.
  2057. * @param string $url The original URL that was matched by the regex.
  2058. * @param array $rawattr The original unmodified attributes.
  2059. * @return string The embed HTML.
  2060. */
  2061. function wp_embed_handler_youtube( $matches, $attr, $url, $rawattr ) {
  2062. global $wp_embed;
  2063. $embed = $wp_embed->autoembed( "https://youtube.com/watch?v={$matches[2]}" );
  2064. /**
  2065. * Filter the YoutTube embed output.
  2066. *
  2067. * @since 4.0.0
  2068. *
  2069. * @param string $embed YouTube embed output.
  2070. * @param array $attr An array of embed attributes.
  2071. * @param string $url The original URL that was matched by the regex.
  2072. * @param array $rawattr The original unmodified attributes.
  2073. */
  2074. return apply_filters( 'wp_embed_handler_youtube', $embed, $attr, $url, $rawattr );
  2075. }
  2076. /**
  2077. * Audio embed handler callback.
  2078. *
  2079. * @since 3.6.0
  2080. *
  2081. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2082. * @param array $attr Embed attributes.
  2083. * @param string $url The original URL that was matched by the regex.
  2084. * @param array $rawattr The original unmodified attributes.
  2085. * @return string The embed HTML.
  2086. */
  2087. function wp_embed_handler_audio( $matches, $attr, $url, $rawattr ) {
  2088. $audio = sprintf( '[audio src="%s" /]', esc_url( $url ) );
  2089. /**
  2090. * Filter the audio embed output.
  2091. *
  2092. * @since 3.6.0
  2093. *
  2094. * @param string $audio Audio embed output.
  2095. * @param array $attr An array of embed attributes.
  2096. * @param string $url The original URL that was matched by the regex.
  2097. * @param array $rawattr The original unmodified attributes.
  2098. */
  2099. return apply_filters( 'wp_embed_handler_audio', $audio, $attr, $url, $rawattr );
  2100. }
  2101. /**
  2102. * Video embed handler callback.
  2103. *
  2104. * @since 3.6.0
  2105. *
  2106. * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}.
  2107. * @param array $attr Embed attributes.
  2108. * @param string $url The original URL that was matched by the regex.
  2109. * @param array $rawattr The original unmodified attributes.
  2110. * @return string The embed HTML.
  2111. */
  2112. function wp_embed_handler_video( $matches, $attr, $url, $rawattr ) {
  2113. $dimensions = '';
  2114. if ( ! empty( $rawattr['width'] ) && ! empty( $rawattr['height'] ) ) {
  2115. $dimensions .= sprintf( 'width="%d" ', (int) $rawattr['width'] );
  2116. $dimensions .= sprintf( 'height="%d" ', (int) $rawattr['height'] );
  2117. }
  2118. $video = sprintf( '[video %s src="%s" /]', $dimensions, esc_url( $url ) );
  2119. /**
  2120. * Filter the video embed output.
  2121. *
  2122. * @since 3.6.0
  2123. *
  2124. * @param string $video Video embed output.
  2125. * @param array $attr An array of embed attributes.
  2126. * @param string $url The original URL that was matched by the regex.
  2127. * @param array $rawattr The original unmodified attributes.
  2128. */
  2129. return apply_filters( 'wp_embed_handler_video', $video, $attr, $url, $rawattr );
  2130. }
  2131. /**
  2132. * Converts a shorthand byte value to an integer byte value.
  2133. *
  2134. * @since 2.3.0
  2135. *
  2136. * @param string $size A shorthand byte value.
  2137. * @return int An integer byte value.
  2138. */
  2139. function wp_convert_hr_to_bytes( $size ) {
  2140. $size = strtolower( $size );
  2141. $bytes = (int) $size;
  2142. if ( strpos( $size, 'k' ) !== false )
  2143. $bytes = intval( $size ) * 1024;
  2144. elseif ( strpos( $size, 'm' ) !== false )
  2145. $bytes = intval($size) * 1024 * 1024;
  2146. elseif ( strpos( $size, 'g' ) !== false )
  2147. $bytes = intval( $size ) * 1024 * 1024 * 1024;
  2148. return $bytes;
  2149. }
  2150. /**
  2151. * Determine the maximum upload size allowed in php.ini.
  2152. *
  2153. * @since 2.5.0
  2154. *
  2155. * @return int Allowed upload size.
  2156. */
  2157. function wp_max_upload_size() {
  2158. $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) );
  2159. $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) );
  2160. /**
  2161. * Filter the maximum upload size allowed in php.ini.
  2162. *
  2163. * @since 2.5.0
  2164. *
  2165. * @param int $size Max upload size limit in bytes.
  2166. * @param int $u_bytes Maximum upload filesize in bytes.
  2167. * @param int $p_bytes Maximum size of POST data in bytes.
  2168. */
  2169. return apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes );
  2170. }
  2171. /**
  2172. * Returns a WP_Image_Editor instance and loads file into it.
  2173. *
  2174. * @since 3.5.0
  2175. * @access public
  2176. *
  2177. * @param string $path Path to file to load
  2178. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2179. * @return WP_Image_Editor|WP_Error
  2180. */
  2181. function wp_get_image_editor( $path, $args = array() ) {
  2182. $args['path'] = $path;
  2183. if ( ! isset( $args['mime_type'] ) ) {
  2184. $file_info = wp_check_filetype( $args['path'] );
  2185. // If $file_info['type'] is false, then we let the editor attempt to
  2186. // figure out the file type, rather than forcing a failure based on extension.
  2187. if ( isset( $file_info ) && $file_info['type'] )
  2188. $args['mime_type'] = $file_info['type'];
  2189. }
  2190. $implementation = _wp_image_editor_choose( $args );
  2191. if ( $implementation ) {
  2192. $editor = new $implementation( $path );
  2193. $loaded = $editor->load();
  2194. if ( is_wp_error( $loaded ) )
  2195. return $loaded;
  2196. return $editor;
  2197. }
  2198. return new WP_Error( 'image_no_editor', __('No editor could be selected.') );
  2199. }
  2200. /**
  2201. * Tests whether there is an editor that supports a given mime type or methods.
  2202. *
  2203. * @since 3.5.0
  2204. * @access public
  2205. *
  2206. * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2207. * @return boolean true if an eligible editor is found; false otherwise
  2208. */
  2209. function wp_image_editor_supports( $args = array() ) {
  2210. return (bool) _wp_image_editor_choose( $args );
  2211. }
  2212. /**
  2213. * Tests which editors are capable of supporting the request.
  2214. *
  2215. * @since 3.5.0
  2216. * @access private
  2217. *
  2218. * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} }
  2219. * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request.
  2220. */
  2221. function _wp_image_editor_choose( $args = array() ) {
  2222. require_once ABSPATH . WPINC . '/class-wp-image-editor.php';
  2223. require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php';
  2224. require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php';
  2225. /**
  2226. * Filter the list of image editing library classes.
  2227. *
  2228. * @since 3.5.0
  2229. *
  2230. * @param array $image_editors List of available image editors. Defaults are
  2231. * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'.
  2232. */
  2233. $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) );
  2234. foreach ( $implementations as $implementation ) {
  2235. if ( ! call_user_func( array( $implementation, 'test' ), $args ) )
  2236. continue;
  2237. if ( isset( $args['mime_type'] ) &&
  2238. ! call_user_func(
  2239. array( $implementation, 'supports_mime_type' ),
  2240. $args['mime_type'] ) ) {
  2241. continue;
  2242. }
  2243. if ( isset( $args['methods'] ) &&
  2244. array_diff( $args['methods'], get_class_methods( $implementation ) ) ) {
  2245. continue;
  2246. }
  2247. return $implementation;
  2248. }
  2249. return false;
  2250. }
  2251. /**
  2252. * Prints default plupload arguments.
  2253. *
  2254. * @since 3.4.0
  2255. */
  2256. function wp_plupload_default_settings() {
  2257. global $wp_scripts;
  2258. $data = $wp_scripts->get_data( 'wp-plupload', 'data' );
  2259. if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) )
  2260. return;
  2261. $max_upload_size = wp_max_upload_size();
  2262. $defaults = array(
  2263. 'runtimes' => 'html5,flash,silverlight,html4',
  2264. 'file_data_name' => 'async-upload', // key passed to $_FILE.
  2265. 'url' => admin_url( 'async-upload.php', 'relative' ),
  2266. 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ),
  2267. 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ),
  2268. 'filters' => array(
  2269. 'max_file_size' => $max_upload_size . 'b',
  2270. ),
  2271. );
  2272. /**
  2273. * Filter the Plupload default settings.
  2274. *
  2275. * @since 3.4.0
  2276. *
  2277. * @param array $defaults Default Plupload settings array.
  2278. */
  2279. $defaults = apply_filters( 'plupload_default_settings', $defaults );
  2280. $params = array(
  2281. 'action' => 'upload-attachment',
  2282. );
  2283. /**
  2284. * Filter the Plupload default parameters.
  2285. *
  2286. * @since 3.4.0
  2287. *
  2288. * @param array $params Default Plupload parameters array.
  2289. */
  2290. $params = apply_filters( 'plupload_default_params', $params );
  2291. $params['_wpnonce'] = wp_create_nonce( 'media-form' );
  2292. $defaults['multipart_params'] = $params;
  2293. $settings = array(
  2294. 'defaults' => $defaults,
  2295. 'browser' => array(
  2296. 'mobile' => wp_is_mobile(),
  2297. 'supported' => _device_can_upload(),
  2298. ),
  2299. 'limitExceeded' => is_multisite() && ! is_upload_space_available()
  2300. );
  2301. $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';';
  2302. if ( $data )
  2303. $script = "$data\n$script";
  2304. $wp_scripts->add_data( 'wp-plupload', 'data', $script );
  2305. }
  2306. add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' );
  2307. /**
  2308. * Prepares an attachment post object for JS, where it is expected
  2309. * to be JSON-encoded and fit into an Attachment model.
  2310. *
  2311. * @since 3.5.0
  2312. *
  2313. * @param mixed $attachment Attachment ID or object.
  2314. * @return array Array of attachment details.
  2315. */
  2316. function wp_prepare_attachment_for_js( $attachment ) {
  2317. if ( ! $attachment = get_post( $attachment ) )
  2318. return;
  2319. if ( 'attachment' != $attachment->post_type )
  2320. return;
  2321. $meta = wp_get_attachment_metadata( $attachment->ID );
  2322. if ( false !== strpos( $attachment->post_mime_type, '/' ) )
  2323. list( $type, $subtype ) = explode( '/', $attachment->post_mime_type );
  2324. else
  2325. list( $type, $subtype ) = array( $attachment->post_mime_type, '' );
  2326. $attachment_url = wp_get_attachment_url( $attachment->ID );
  2327. $response = array(
  2328. 'id' => $attachment->ID,
  2329. 'title' => $attachment->post_title,
  2330. 'filename' => wp_basename( $attachment->guid ),
  2331. 'url' => $attachment_url,
  2332. 'link' => get_attachment_link( $attachment->ID ),
  2333. 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
  2334. 'author' => $attachment->post_author,
  2335. 'description' => $attachment->post_content,
  2336. 'caption' => $attachment->post_excerpt,
  2337. 'name' => $attachment->post_name,
  2338. 'status' => $attachment->post_status,
  2339. 'uploadedTo' => $attachment->post_parent,
  2340. 'date' => strtotime( $attachment->post_date_gmt ) * 1000,
  2341. 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000,
  2342. 'menuOrder' => $attachment->menu_order,
  2343. 'mime' => $attachment->post_mime_type,
  2344. 'type' => $type,
  2345. 'subtype' => $subtype,
  2346. 'icon' => wp_mime_type_icon( $attachment->ID ),
  2347. 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ),
  2348. 'nonces' => array(
  2349. 'update' => false,
  2350. 'delete' => false,
  2351. 'edit' => false
  2352. ),
  2353. 'editLink' => false,
  2354. );
  2355. $author = new WP_User( $attachment->post_author );
  2356. $response['authorName'] = $author->display_name;
  2357. if ( $attachment->post_parent ) {
  2358. $post_parent = get_post( $attachment->post_parent );
  2359. $response['uploadedToLink'] = get_edit_post_link( $attachment->post_parent, 'raw' );
  2360. $response['uploadedToTitle'] = $post_parent->post_title ? $post_parent->post_title : __( '(No title)' );
  2361. }
  2362. $attached_file = get_attached_file( $attachment->ID );
  2363. if ( file_exists( $attached_file ) ) {
  2364. $bytes = filesize( $attached_file );
  2365. $response['filesizeInBytes'] = $bytes;
  2366. $response['filesizeHumanReadable'] = size_format( $bytes );
  2367. }
  2368. if ( current_user_can( 'edit_post', $attachment->ID ) ) {
  2369. $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID );
  2370. $response['nonces']['edit'] = wp_create_nonce( 'image_editor-' . $attachment->ID );
  2371. $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' );
  2372. }
  2373. if ( current_user_can( 'delete_post', $attachment->ID ) )
  2374. $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID );
  2375. if ( $meta && 'image' === $type ) {
  2376. $sizes = array();
  2377. /** This filter is documented in wp-admin/includes/media.php */
  2378. $possible_sizes = apply_filters( 'image_size_names_choose', array(
  2379. 'thumbnail' => __('Thumbnail'),
  2380. 'medium' => __('Medium'),
  2381. 'large' => __('Large'),
  2382. 'full' => __('Full Size'),
  2383. ) );
  2384. unset( $possible_sizes['full'] );
  2385. // Loop through all potential sizes that may be chosen. Try to do this with some efficiency.
  2386. // First: run the image_downsize filter. If it returns something, we can use its data.
  2387. // If the filter does not return something, then image_downsize() is just an expensive
  2388. // way to check the image metadata, which we do second.
  2389. foreach ( $possible_sizes as $size => $label ) {
  2390. /** This filter is documented in wp-includes/media.php */
  2391. if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) {
  2392. if ( ! $downsize[3] )
  2393. continue;
  2394. $sizes[ $size ] = array(
  2395. 'height' => $downsize[2],
  2396. 'width' => $downsize[1],
  2397. 'url' => $downsize[0],
  2398. 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape',
  2399. );
  2400. } elseif ( isset( $meta['sizes'][ $size ] ) ) {
  2401. if ( ! isset( $base_url ) )
  2402. $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url );
  2403. // Nothing from the filter, so consult image metadata if we have it.
  2404. $size_meta = $meta['sizes'][ $size ];
  2405. // We have the actual image size, but might need to further constrain it if content_width is narrower.
  2406. // Thumbnail, medium, and full sizes are also checked against the site's height/width options.
  2407. list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' );
  2408. $sizes[ $size ] = array(
  2409. 'height' => $height,
  2410. 'width' => $width,
  2411. 'url' => $base_url . $size_meta['file'],
  2412. 'orientation' => $height > $width ? 'portrait' : 'landscape',
  2413. );
  2414. }
  2415. }
  2416. $sizes['full'] = array( 'url' => $attachment_url );
  2417. if ( isset( $meta['height'], $meta['width'] ) ) {
  2418. $sizes['full']['height'] = $meta['height'];
  2419. $sizes['full']['width'] = $meta['width'];
  2420. $sizes['full']['orientation'] = $meta['height'] > $meta['width'] ? 'portrait' : 'landscape';
  2421. }
  2422. $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] );
  2423. } elseif ( $meta && 'video' === $type ) {
  2424. if ( isset( $meta['width'] ) )
  2425. $response['width'] = (int) $meta['width'];
  2426. if ( isset( $meta['height'] ) )
  2427. $response['height'] = (int) $meta['height'];
  2428. }
  2429. if ( $meta && ( 'audio' === $type || 'video' === $type ) ) {
  2430. if ( isset( $meta['length_formatted'] ) )
  2431. $response['fileLength'] = $meta['length_formatted'];
  2432. $response['meta'] = array();
  2433. foreach ( wp_get_attachment_id3_keys( $attachment ) as $key => $label ) {
  2434. if ( ! empty( $meta[ $key ] ) ) {
  2435. $response['meta'][ $key ] = $meta[ $key ];
  2436. }
  2437. }
  2438. $id = get_post_thumbnail_id( $attachment->ID );
  2439. if ( ! empty( $id ) ) {
  2440. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'full' );
  2441. $response['image'] = compact( 'src', 'width', 'height' );
  2442. list( $src, $width, $height ) = wp_get_attachment_image_src( $id, 'thumbnail' );
  2443. $response['thumb'] = compact( 'src', 'width', 'height' );
  2444. } else {
  2445. $src = wp_mime_type_icon( $attachment->ID );
  2446. $width = 48;
  2447. $height = 64;
  2448. $response['image'] = compact( 'src', 'width', 'height' );
  2449. $response['thumb'] = compact( 'src', 'width', 'height' );
  2450. }
  2451. }
  2452. if ( function_exists('get_compat_media_markup') )
  2453. $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) );
  2454. /**
  2455. * Filter the attachment data prepared for JavaScript.
  2456. *
  2457. * @since 3.5.0
  2458. *
  2459. * @param array $response Array of prepared attachment data.
  2460. * @param int|object $attachment Attachment ID or object.
  2461. * @param array $meta Array of attachment meta data.
  2462. */
  2463. return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta );
  2464. }
  2465. /**
  2466. * Enqueues all scripts, styles, settings, and templates necessary to use
  2467. * all media JS APIs.
  2468. *
  2469. * @since 3.5.0
  2470. */
  2471. function wp_enqueue_media( $args = array() ) {
  2472. // Enqueue me just once per page, please.
  2473. if ( did_action( 'wp_enqueue_media' ) )
  2474. return;
  2475. global $content_width, $wpdb;
  2476. $defaults = array(
  2477. 'post' => null,
  2478. );
  2479. $args = wp_parse_args( $args, $defaults );
  2480. // We're going to pass the old thickbox media tabs to `media_upload_tabs`
  2481. // to ensure plugins will work. We will then unset those tabs.
  2482. $tabs = array(
  2483. // handler action suffix => tab label
  2484. 'type' => '',
  2485. 'type_url' => '',
  2486. 'gallery' => '',
  2487. 'library' => '',
  2488. );
  2489. /** This filter is documented in wp-admin/includes/media.php */
  2490. $tabs = apply_filters( 'media_upload_tabs', $tabs );
  2491. unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] );
  2492. $props = array(
  2493. 'link' => get_option( 'image_default_link_type' ), // db default is 'file'
  2494. 'align' => get_option( 'image_default_align' ), // empty default
  2495. 'size' => get_option( 'image_default_size' ), // empty default
  2496. );
  2497. $exts = array_merge( wp_get_audio_extensions(), wp_get_video_extensions() );
  2498. $mimes = get_allowed_mime_types();
  2499. $ext_mimes = array();
  2500. foreach ( $exts as $ext ) {
  2501. foreach ( $mimes as $ext_preg => $mime_match ) {
  2502. if ( preg_match( '#' . $ext . '#i', $ext_preg ) ) {
  2503. $ext_mimes[ $ext ] = $mime_match;
  2504. break;
  2505. }
  2506. }
  2507. }
  2508. $has_audio = $wpdb->get_var( "
  2509. SELECT ID
  2510. FROM $wpdb->posts
  2511. WHERE post_type = 'attachment'
  2512. AND post_mime_type LIKE 'audio%'
  2513. LIMIT 1
  2514. " );
  2515. $has_video = $wpdb->get_var( "
  2516. SELECT ID
  2517. FROM $wpdb->posts
  2518. WHERE post_type = 'attachment'
  2519. AND post_mime_type LIKE 'video%'
  2520. LIMIT 1
  2521. " );
  2522. $settings = array(
  2523. 'tabs' => $tabs,
  2524. 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ),
  2525. 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ),
  2526. /** This filter is documented in wp-admin/includes/media.php */
  2527. 'captions' => ! apply_filters( 'disable_captions', '' ),
  2528. 'nonce' => array(
  2529. 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ),
  2530. ),
  2531. 'post' => array(
  2532. 'id' => 0,
  2533. ),
  2534. 'defaultProps' => $props,
  2535. 'attachmentCounts' => array(
  2536. 'audio' => ( $has_audio ) ? 1 : 0,
  2537. 'video' => ( $has_video ) ? 1 : 0
  2538. ),
  2539. 'embedExts' => $exts,
  2540. 'embedMimes' => $ext_mimes,
  2541. 'contentWidth' => $content_width,
  2542. );
  2543. $post = null;
  2544. if ( isset( $args['post'] ) ) {
  2545. $post = get_post( $args['post'] );
  2546. $settings['post'] = array(
  2547. 'id' => $post->ID,
  2548. 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ),
  2549. );
  2550. $thumbnail_support = current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' );
  2551. if ( ! $thumbnail_support && 'attachment' === $post->post_type && $post->post_mime_type ) {
  2552. if ( 0 === strpos( $post->post_mime_type, 'audio/' ) ) {
  2553. $thumbnail_support = post_type_supports( 'attachment:audio', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:audio' );
  2554. } elseif ( 0 === strpos( $post->post_mime_type, 'video/' ) ) {
  2555. $thumbnail_support = post_type_supports( 'attachment:video', 'thumbnail' ) || current_theme_supports( 'post-thumbnails', 'attachment:video' );
  2556. }
  2557. }
  2558. if ( $thumbnail_support ) {
  2559. $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true );
  2560. $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1;
  2561. }
  2562. }
  2563. $hier = $post && is_post_type_hierarchical( $post->post_type );
  2564. $strings = array(
  2565. // Generic
  2566. 'url' => __( 'URL' ),
  2567. 'addMedia' => __( 'Add Media' ),
  2568. 'search' => __( 'Search' ),
  2569. 'select' => __( 'Select' ),
  2570. 'cancel' => __( 'Cancel' ),
  2571. 'update' => __( 'Update' ),
  2572. 'replace' => __( 'Replace' ),
  2573. 'remove' => __( 'Remove' ),
  2574. 'back' => __( 'Back' ),
  2575. /* translators: This is a would-be plural string used in the media manager.
  2576. If there is not a word you can use in your language to avoid issues with the
  2577. lack of plural support here, turn it into "selected: %d" then translate it.
  2578. */
  2579. 'selected' => __( '%d selected' ),
  2580. 'dragInfo' => __( 'Drag and drop to reorder images.' ),
  2581. // Upload
  2582. 'uploadFilesTitle' => __( 'Upload Files' ),
  2583. 'uploadImagesTitle' => __( 'Upload Images' ),
  2584. // Library
  2585. 'mediaLibraryTitle' => __( 'Media Library' ),
  2586. 'insertMediaTitle' => __( 'Insert Media' ),
  2587. 'createNewGallery' => __( 'Create a new gallery' ),
  2588. 'createNewPlaylist' => __( 'Create a new playlist' ),
  2589. 'createNewVideoPlaylist' => __( 'Create a new video playlist' ),
  2590. 'returnToLibrary' => __( '&#8592; Return to library' ),
  2591. 'allMediaItems' => __( 'All media items' ),
  2592. 'allMediaTypes' => __( 'All media types' ),
  2593. 'noItemsFound' => __( 'No items found.' ),
  2594. 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ),
  2595. 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ),
  2596. 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ),
  2597. // From URL
  2598. 'insertFromUrlTitle' => __( 'Insert from URL' ),
  2599. // Featured Images
  2600. 'setFeaturedImageTitle' => __( 'Set Featured Image' ),
  2601. 'setFeaturedImage' => __( 'Set featured image' ),
  2602. // Gallery
  2603. 'createGalleryTitle' => __( 'Create Gallery' ),
  2604. 'editGalleryTitle' => __( 'Edit Gallery' ),
  2605. 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ),
  2606. 'insertGallery' => __( 'Insert gallery' ),
  2607. 'updateGallery' => __( 'Update gallery' ),
  2608. 'addToGallery' => __( 'Add to gallery' ),
  2609. 'addToGalleryTitle' => __( 'Add to Gallery' ),
  2610. 'reverseOrder' => __( 'Reverse order' ),
  2611. // Edit Image
  2612. 'imageDetailsTitle' => __( 'Image Details' ),
  2613. 'imageReplaceTitle' => __( 'Replace Image' ),
  2614. 'imageDetailsCancel' => __( 'Cancel Edit' ),
  2615. 'editImage' => __( 'Edit Image' ),
  2616. // Crop Image
  2617. 'chooseImage' => __( 'Choose Image' ),
  2618. 'selectAndCrop' => __( 'Select and Crop' ),
  2619. 'skipCropping' => __( 'Skip Cropping' ),
  2620. 'cropImage' => __( 'Crop Image' ),
  2621. 'cropYourImage' => __( 'Crop your image' ),
  2622. 'cropping' => __( 'Cropping&hellip;' ),
  2623. 'suggestedDimensions' => __( 'Suggested image dimensions:' ),
  2624. 'cropError' => __( 'There has been an error cropping your image.' ),
  2625. // Edit Audio
  2626. 'audioDetailsTitle' => __( 'Audio Details' ),
  2627. 'audioReplaceTitle' => __( 'Replace Audio' ),
  2628. 'audioAddSourceTitle' => __( 'Add Audio Source' ),
  2629. 'audioDetailsCancel' => __( 'Cancel Edit' ),
  2630. // Edit Video
  2631. 'videoDetailsTitle' => __( 'Video Details' ),
  2632. 'videoReplaceTitle' => __( 'Replace Video' ),
  2633. 'videoAddSourceTitle' => __( 'Add Video Source' ),
  2634. 'videoDetailsCancel' => __( 'Cancel Edit' ),
  2635. 'videoSelectPosterImageTitle' => __( 'Select Poster Image' ),
  2636. 'videoAddTrackTitle' => __( 'Add Subtitles' ),
  2637. // Playlist
  2638. 'playlistDragInfo' => __( 'Drag and drop to reorder tracks.' ),
  2639. 'createPlaylistTitle' => __( 'Create Audio Playlist' ),
  2640. 'editPlaylistTitle' => __( 'Edit Audio Playlist' ),
  2641. 'cancelPlaylistTitle' => __( '&#8592; Cancel Audio Playlist' ),
  2642. 'insertPlaylist' => __( 'Insert audio playlist' ),
  2643. 'updatePlaylist' => __( 'Update audio playlist' ),
  2644. 'addToPlaylist' => __( 'Add to audio playlist' ),
  2645. 'addToPlaylistTitle' => __( 'Add to Audio Playlist' ),
  2646. // Video Playlist
  2647. 'videoPlaylistDragInfo' => __( 'Drag and drop to reorder videos.' ),
  2648. 'createVideoPlaylistTitle' => __( 'Create Video Playlist' ),
  2649. 'editVideoPlaylistTitle' => __( 'Edit Video Playlist' ),
  2650. 'cancelVideoPlaylistTitle' => __( '&#8592; Cancel Video Playlist' ),
  2651. 'insertVideoPlaylist' => __( 'Insert video playlist' ),
  2652. 'updateVideoPlaylist' => __( 'Update video playlist' ),
  2653. 'addToVideoPlaylist' => __( 'Add to video playlist' ),
  2654. 'addToVideoPlaylistTitle' => __( 'Add to Video Playlist' ),
  2655. );
  2656. /**
  2657. * Filter the media view settings.
  2658. *
  2659. * @since 3.5.0
  2660. *
  2661. * @param array $settings List of media view settings.
  2662. * @param WP_Post $post Post object.
  2663. */
  2664. $settings = apply_filters( 'media_view_settings', $settings, $post );
  2665. /**
  2666. * Filter the media view strings.
  2667. *
  2668. * @since 3.5.0
  2669. *
  2670. * @param array $strings List of media view strings.
  2671. * @param WP_Post $post Post object.
  2672. */
  2673. $strings = apply_filters( 'media_view_strings', $strings, $post );
  2674. $strings['settings'] = $settings;
  2675. wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings );
  2676. wp_enqueue_script( 'media-editor' );
  2677. wp_enqueue_script( 'media-audiovideo' );
  2678. wp_enqueue_style( 'media-views' );
  2679. if ( is_admin() ) {
  2680. wp_enqueue_script( 'mce-view' );
  2681. wp_enqueue_script( 'image-edit' );
  2682. }
  2683. wp_enqueue_style( 'imgareaselect' );
  2684. wp_plupload_default_settings();
  2685. require_once ABSPATH . WPINC . '/media-template.php';
  2686. add_action( 'admin_footer', 'wp_print_media_templates' );
  2687. add_action( 'wp_footer', 'wp_print_media_templates' );
  2688. add_action( 'customize_controls_print_footer_scripts', 'wp_print_media_templates' );
  2689. /**
  2690. * Fires at the conclusion of wp_enqueue_media().
  2691. *
  2692. * @since 3.5.0
  2693. */
  2694. do_action( 'wp_enqueue_media' );
  2695. }
  2696. /**
  2697. * Retrieve media attached to the passed post.
  2698. *
  2699. * @since 3.6.0
  2700. *
  2701. * @param string $type Mime type.
  2702. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  2703. * @return array Found attachments.
  2704. */
  2705. function get_attached_media( $type, $post = 0 ) {
  2706. if ( ! $post = get_post( $post ) )
  2707. return array();
  2708. $args = array(
  2709. 'post_parent' => $post->ID,
  2710. 'post_type' => 'attachment',
  2711. 'post_mime_type' => $type,
  2712. 'posts_per_page' => -1,
  2713. 'orderby' => 'menu_order',
  2714. 'order' => 'ASC',
  2715. );
  2716. /**
  2717. * Filter arguments used to retrieve media attached to the given post.
  2718. *
  2719. * @since 3.6.0
  2720. *
  2721. * @param array $args Post query arguments.
  2722. * @param string $type Mime type of the desired media.
  2723. * @param mixed $post Post ID or object.
  2724. */
  2725. $args = apply_filters( 'get_attached_media_args', $args, $type, $post );
  2726. $children = get_children( $args );
  2727. /**
  2728. * Filter the list of media attached to the given post.
  2729. *
  2730. * @since 3.6.0
  2731. *
  2732. * @param array $children Associative array of media attached to the given post.
  2733. * @param string $type Mime type of the media desired.
  2734. * @param mixed $post Post ID or object.
  2735. */
  2736. return (array) apply_filters( 'get_attached_media', $children, $type, $post );
  2737. }
  2738. /**
  2739. * Check the content blob for an <audio>, <video> <object>, <embed>, or <iframe>
  2740. *
  2741. * @since 3.6.0
  2742. *
  2743. * @param string $content A string which might contain media data.
  2744. * @param array $types array of media types: 'audio', 'video', 'object', 'embed', or 'iframe'
  2745. * @return array A list of found HTML media embeds
  2746. */
  2747. function get_media_embedded_in_content( $content, $types = null ) {
  2748. $html = array();
  2749. $allowed_media_types = array( 'audio', 'video', 'object', 'embed', 'iframe' );
  2750. if ( ! empty( $types ) ) {
  2751. if ( ! is_array( $types ) )
  2752. $types = array( $types );
  2753. $allowed_media_types = array_intersect( $allowed_media_types, $types );
  2754. }
  2755. foreach ( $allowed_media_types as $tag ) {
  2756. if ( preg_match( '#' . get_tag_regex( $tag ) . '#', $content, $matches ) ) {
  2757. $html[] = $matches[0];
  2758. }
  2759. }
  2760. return $html;
  2761. }
  2762. /**
  2763. * Retrieve galleries from the passed post's content.
  2764. *
  2765. * @since 3.6.0
  2766. *
  2767. * @param int|WP_Post $post Optional. Post ID or object.
  2768. * @param bool $html Whether to return HTML or data in the array.
  2769. * @return array A list of arrays, each containing gallery data and srcs parsed
  2770. * from the expanded shortcode.
  2771. */
  2772. function get_post_galleries( $post, $html = true ) {
  2773. if ( ! $post = get_post( $post ) )
  2774. return array();
  2775. if ( ! has_shortcode( $post->post_content, 'gallery' ) )
  2776. return array();
  2777. $galleries = array();
  2778. if ( preg_match_all( '/' . get_shortcode_regex() . '/s', $post->post_content, $matches, PREG_SET_ORDER ) ) {
  2779. foreach ( $matches as $shortcode ) {
  2780. if ( 'gallery' === $shortcode[2] ) {
  2781. $srcs = array();
  2782. $gallery = do_shortcode_tag( $shortcode );
  2783. if ( $html ) {
  2784. $galleries[] = $gallery;
  2785. } else {
  2786. preg_match_all( '#src=([\'"])(.+?)\1#is', $gallery, $src, PREG_SET_ORDER );
  2787. if ( ! empty( $src ) ) {
  2788. foreach ( $src as $s )
  2789. $srcs[] = $s[2];
  2790. }
  2791. $data = shortcode_parse_atts( $shortcode[3] );
  2792. $data['src'] = array_values( array_unique( $srcs ) );
  2793. $galleries[] = $data;
  2794. }
  2795. }
  2796. }
  2797. }
  2798. /**
  2799. * Filter the list of all found galleries in the given post.
  2800. *
  2801. * @since 3.6.0
  2802. *
  2803. * @param array $galleries Associative array of all found post galleries.
  2804. * @param WP_Post $post Post object.
  2805. */
  2806. return apply_filters( 'get_post_galleries', $galleries, $post );
  2807. }
  2808. /**
  2809. * Check a specified post's content for gallery and, if present, return the first
  2810. *
  2811. * @since 3.6.0
  2812. *
  2813. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  2814. * @param bool $html Whether to return HTML or data.
  2815. * @return string|array Gallery data and srcs parsed from the expanded shortcode.
  2816. */
  2817. function get_post_gallery( $post = 0, $html = true ) {
  2818. $galleries = get_post_galleries( $post, $html );
  2819. $gallery = reset( $galleries );
  2820. /**
  2821. * Filter the first-found post gallery.
  2822. *
  2823. * @since 3.6.0
  2824. *
  2825. * @param array $gallery The first-found post gallery.
  2826. * @param int|WP_Post $post Post ID or object.
  2827. * @param array $galleries Associative array of all found post galleries.
  2828. */
  2829. return apply_filters( 'get_post_gallery', $gallery, $post, $galleries );
  2830. }
  2831. /**
  2832. * Retrieve the image srcs from galleries from a post's content, if present
  2833. *
  2834. * @since 3.6.0
  2835. *
  2836. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  2837. * @return array A list of lists, each containing image srcs parsed.
  2838. * from an expanded shortcode
  2839. */
  2840. function get_post_galleries_images( $post = 0 ) {
  2841. $galleries = get_post_galleries( $post, false );
  2842. return wp_list_pluck( $galleries, 'src' );
  2843. }
  2844. /**
  2845. * Check a post's content for galleries and return the image srcs for the first found gallery
  2846. *
  2847. * @since 3.6.0
  2848. *
  2849. * @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
  2850. * @return array A list of a gallery's image srcs in order.
  2851. */
  2852. function get_post_gallery_images( $post = 0 ) {
  2853. $gallery = get_post_gallery( $post, false );
  2854. return empty( $gallery['src'] ) ? array() : $gallery['src'];
  2855. }
  2856. /**
  2857. * Maybe attempt to generate attachment metadata, if missing.
  2858. *
  2859. * @since 3.9.0
  2860. *
  2861. * @param WP_Post $attachment Attachment object.
  2862. */
  2863. function wp_maybe_generate_attachment_metadata( $attachment ) {
  2864. if ( empty( $attachment ) || ( empty( $attachment->ID ) || ! $attachment_id = (int) $attachment->ID ) ) {
  2865. return;
  2866. }
  2867. $file = get_attached_file( $attachment_id );
  2868. $meta = wp_get_attachment_metadata( $attachment_id );
  2869. if ( empty( $meta ) && file_exists( $file ) ) {
  2870. $_meta = get_post_meta( $attachment_id );
  2871. $regeneration_lock = 'wp_generating_att_' . $attachment_id;
  2872. if ( ! array_key_exists( '_wp_attachment_metadata', $_meta ) && ! get_transient( $regeneration_lock ) ) {
  2873. set_transient( $regeneration_lock, $file );
  2874. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $file ) );
  2875. delete_transient( $regeneration_lock );
  2876. }
  2877. }
  2878. }