Нет описания

class.media.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. <?php
  2. require_once( JETPACK__PLUGIN_DIR . 'sal/class.json-api-date.php' );
  3. /**
  4. * Class to handle different actions related to media.
  5. */
  6. class Jetpack_Media {
  7. public static $WP_ORIGINAL_MEDIA = '_wp_original_post_media';
  8. public static $WP_REVISION_HISTORY = '_wp_revision_history';
  9. public static $REVISION_HISTORY_MAXIMUM_AMOUNT = 0;
  10. public static $WP_ATTACHMENT_IMAGE_ALT = '_wp_attachment_image_alt';
  11. /**
  12. * Generate a filename in function of the original filename of the media.
  13. * The returned name has the `{basename}-{hash}-{random-number}.{ext}` shape.
  14. * The hash is built according to the filename trying to avoid name collisions
  15. * with other media files.
  16. *
  17. * @param number $media_id - media post ID.
  18. * @param string $new_filename - the new filename.
  19. * @return string A random filename.
  20. */
  21. public static function generate_new_filename( $media_id, $new_filename ) {
  22. // Get the right filename extension.
  23. $new_filename_paths = pathinfo( $new_filename );
  24. $new_file_ext = $new_filename_paths['extension'];
  25. // Get the file parts from the current attachment.
  26. $current_file = get_attached_file( $media_id );
  27. $current_file_parts = pathinfo( $current_file );
  28. $current_file_ext = $current_file_parts['extension'];
  29. $current_file_dirname = $current_file_parts['dirname'];
  30. // Take out filename from the original file or from the current attachment.
  31. $original_media = (array) self::get_original_media( $media_id );
  32. if ( ! empty( $original_media ) ) {
  33. $original_file_parts = pathinfo( $original_media['file'] );
  34. $filename_base = $original_file_parts['filename'];
  35. } else {
  36. $filename_base = $current_file_parts['filename'];
  37. }
  38. // Add unique seed based on the filename.
  39. $filename_base .= '-' . crc32( $filename_base ) . '-';
  40. $number_suffix = time() . rand( 100, 999 );
  41. do {
  42. $filename = $filename_base;
  43. $filename .= $number_suffix;
  44. $file_ext = $new_file_ext ? $new_file_ext : $current_file_ext;
  45. $new_filename = "{$filename}.{$file_ext}";
  46. $new_path = "{$current_file_dirname}/$new_filename";
  47. $number_suffix++;
  48. } while ( file_exists( $new_path ) );
  49. return $new_filename;
  50. }
  51. /**
  52. * File urls use the post (image item) date to generate a folder path.
  53. * Post dates can change, so we use the original date used in the `guid`
  54. * url so edits can remain in the same folder. In the following function
  55. * we capture a string in the format of `YYYY/MM` from the guid.
  56. *
  57. * For example with a guid of
  58. * "http://test.files.wordpress.com/2016/10/test.png" the resulting string
  59. * would be: "2016/10"
  60. *
  61. * @param number $media_id
  62. * @return string
  63. */
  64. private static function get_time_string_from_guid( $media_id ) {
  65. $time = date( "Y/m", strtotime( current_time( 'mysql' ) ) );
  66. if ( $media = get_post( $media_id ) ) {
  67. $pattern = '/\/(\d{4}\/\d{2})\//';
  68. preg_match( $pattern, $media->guid, $matches );
  69. if ( count( $matches ) > 1 ) {
  70. $time = $matches[1];
  71. }
  72. }
  73. return $time;
  74. }
  75. /**
  76. * Return an array of allowed mime_type items used to upload a media file.
  77. *
  78. * @return array mime_type array
  79. */
  80. static function get_allowed_mime_types( $default_mime_types ) {
  81. return array_unique( array_merge( $default_mime_types, array(
  82. 'application/msword', // .doc
  83. 'application/vnd.ms-powerpoint', // .ppt, .pps
  84. 'application/vnd.ms-excel', // .xls
  85. 'application/vnd.openxmlformats-officedocument.presentationml.presentation', // .pptx
  86. 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', // .ppsx
  87. 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // .xlsx
  88. 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // .docx
  89. 'application/vnd.oasis.opendocument.text', // .odt
  90. 'application/pdf', // .pdf
  91. ) ) );
  92. }
  93. /**
  94. * Checks that the mime type of the file
  95. * is among those in a filterable list of mime types.
  96. *
  97. * @param string $file Path to file to get its mime type.
  98. * @return bool
  99. */
  100. protected static function is_file_supported_for_sideloading( $file ) {
  101. return jetpack_is_file_supported_for_sideloading( $file );
  102. }
  103. /**
  104. * Try to remove the temporal file from the given file array.
  105. *
  106. * @param array $file_array Array with data about the temporal file
  107. * @return bool `true` if the file has been removed. `false` either the file doesn't exist or it couldn't be removed.
  108. */
  109. private static function remove_tmp_file( $file_array ) {
  110. if ( ! file_exists ( $file_array['tmp_name'] ) ) {
  111. return false;
  112. }
  113. return @unlink( $file_array['tmp_name'] );
  114. }
  115. /**
  116. * Save the given temporal file considering file type,
  117. * correct location according to the original file path, etc.
  118. * The file type control is done through of `jetpack_supported_media_sideload_types` filter,
  119. * which allows define to the users their own file types list.
  120. *
  121. * @param array $file_array file to save
  122. * @param number $media_id
  123. * @return array|WP_Error an array with information about the new file saved or a WP_Error is something went wrong.
  124. */
  125. public static function save_temporary_file( $file_array, $media_id ) {
  126. $tmp_filename = $file_array['tmp_name'];
  127. if ( ! file_exists( $tmp_filename ) ) {
  128. return new WP_Error( 'invalid_input', 'No media provided in input.' );
  129. }
  130. // add additional mime_types through of the `jetpack_supported_media_sideload_types` filter
  131. $mime_type_static_filter = array(
  132. 'Jetpack_Media',
  133. 'get_allowed_mime_types'
  134. );
  135. add_filter( 'jetpack_supported_media_sideload_types', $mime_type_static_filter );
  136. if (
  137. ! self::is_file_supported_for_sideloading( $tmp_filename ) &&
  138. ! file_is_displayable_image( $tmp_filename )
  139. ) {
  140. @unlink( $tmp_filename );
  141. return new WP_Error( 'invalid_input', 'Invalid file type.', 403 );
  142. }
  143. remove_filter( 'jetpack_supported_media_sideload_types', $mime_type_static_filter );
  144. // generate a new file name
  145. $tmp_new_filename = self::generate_new_filename( $media_id, $file_array[ 'name' ] );
  146. // start to create the parameters to move the temporal file
  147. $overrides = array( 'test_form' => false );
  148. // get time according to the original filaname
  149. $time = self::get_time_string_from_guid( $media_id );
  150. $file_array['name'] = $tmp_new_filename;
  151. $file = wp_handle_sideload( $file_array, $overrides, $time );
  152. self::remove_tmp_file( $file_array );
  153. if ( isset( $file['error'] ) ) {
  154. return new WP_Error( 'upload_error', $file['error'] );
  155. }
  156. return $file;
  157. }
  158. /**
  159. * Return an object with an snapshot of a revision item.
  160. *
  161. * @param object $media_item - media post object
  162. * @return object a revision item
  163. */
  164. public static function get_snapshot( $media_item ) {
  165. $current_file = get_attached_file( $media_item->ID );
  166. $file_paths = pathinfo( $current_file );
  167. $snapshot = array(
  168. 'date' => (string) WPCOM_JSON_API_Date::format_date( $media_item->post_modified_gmt, $media_item->post_modified ),
  169. 'URL' => (string) wp_get_attachment_url( $media_item->ID ),
  170. 'file' => (string) $file_paths['basename'],
  171. 'extension' => (string) $file_paths['extension'],
  172. 'mime_type' => (string) $media_item->post_mime_type,
  173. 'size' => (int) filesize( $current_file ),
  174. );
  175. return (object) $snapshot;
  176. }
  177. /**
  178. * Add a new item into revision_history array.
  179. *
  180. * @param object $media_item - media post object
  181. * @param file $file - file recently added
  182. * @param bool $has_original_media - condition is the original media has been already added
  183. * @return bool `true` if the item has been added. Otherwise `false`.
  184. */
  185. public static function register_revision( $media_item, $file, $has_original_media ) {
  186. if ( is_wp_error( $file ) || ! $has_original_media ) {
  187. return false;
  188. }
  189. add_post_meta( $media_item->ID, self::$WP_REVISION_HISTORY, self::get_snapshot( $media_item ) );
  190. }
  191. /**
  192. * Return the `revision_history` of the given media.
  193. *
  194. * @param number $media_id - media post ID
  195. * @return array `revision_history` array
  196. */
  197. public static function get_revision_history( $media_id ) {
  198. return array_reverse( get_post_meta( $media_id, self::$WP_REVISION_HISTORY ) );
  199. }
  200. /**
  201. * Return the original media data
  202. */
  203. public static function get_original_media( $media_id ) {
  204. $original = get_post_meta( $media_id, self::$WP_ORIGINAL_MEDIA, true );
  205. $original = $original ? $original : array();
  206. return $original;
  207. }
  208. public static function delete_file( $pathname ) {
  209. if ( ! file_exists( $pathname ) || ! is_file( $pathname ) ) {
  210. // let's touch a fake file to try to `really` remove the media file
  211. touch( $pathname );
  212. }
  213. return wp_delete_file( $pathname );
  214. }
  215. /**
  216. * Try to delete a file according to the dirname of
  217. * the media attached file and the filename.
  218. *
  219. * @param number $media_id - media post ID
  220. * @param string $filename - basename of the file ( name-of-file.ext )
  221. * @return bool `true` is the file has been removed, `false` if not.
  222. */
  223. private static function delete_media_history_file( $media_id, $filename ) {
  224. $attached_path = get_attached_file( $media_id );
  225. $attached_parts = pathinfo( $attached_path );
  226. $dirname = $attached_parts['dirname'];
  227. $pathname = $dirname . '/' . $filename;
  228. // remove thumbnails
  229. $metadata = wp_generate_attachment_metadata( $media_id, $pathname );
  230. if ( isset( $metadata ) && isset( $metadata['sizes'] ) ) {
  231. foreach ( $metadata['sizes'] as $size => $properties ) {
  232. self::delete_file( $dirname . '/' . $properties['file'] );
  233. }
  234. }
  235. // remove primary file
  236. self::delete_file( $pathname );
  237. }
  238. /**
  239. * Remove specific items from the `revision history` array
  240. * depending on the given criteria: array(
  241. * 'from' => (int) <from>,
  242. * 'to' => (int) <to>,
  243. * )
  244. *
  245. * Also, it removes the file defined in each item.
  246. *
  247. * @param number $media_id - media post ID
  248. * @param object $criteria - criteria to remove the items
  249. * @param array [$revision_history] - revision history array
  250. * @return array `revision_history` array updated.
  251. */
  252. public static function remove_items_from_revision_history( $media_id, $criteria, $revision_history ) {
  253. if ( ! isset ( $revision_history ) ) {
  254. $revision_history = self::get_revision_history( $media_id );
  255. }
  256. $from = $criteria['from'];
  257. $to = $criteria['to'] ? $criteria['to'] : ( $from + 1 );
  258. for ( $i = $from; $i < $to; $i++ ) {
  259. $removed_item = array_slice( $revision_history, $from, 1 );
  260. if ( ! $removed_item ) {
  261. break;
  262. }
  263. array_splice( $revision_history, $from, 1 );
  264. self::delete_media_history_file( $media_id, $removed_item[0]->file );
  265. }
  266. // override all history items
  267. delete_post_meta( $media_id, self::$WP_REVISION_HISTORY );
  268. $revision_history = array_reverse( $revision_history );
  269. foreach ( $revision_history as &$item ) {
  270. add_post_meta( $media_id, self::$WP_REVISION_HISTORY, $item );
  271. }
  272. return $revision_history;
  273. }
  274. /**
  275. * Limit the number of items of the `revision_history` array.
  276. * When the stack is overflowing the oldest item is remove from there (FIFO).
  277. *
  278. * @param number $media_id - media post ID
  279. * @param number [$limit] - maximun amount of items. 20 as default.
  280. * @return array items removed from `revision_history`
  281. */
  282. public static function limit_revision_history( $media_id, $limit = null) {
  283. if ( is_null( $limit ) ) {
  284. $limit = self::$REVISION_HISTORY_MAXIMUM_AMOUNT;
  285. }
  286. $revision_history = self::get_revision_history( $media_id );
  287. $total = count( $revision_history );
  288. if ( $total < $limit ) {
  289. return array();
  290. }
  291. self::remove_items_from_revision_history(
  292. $media_id,
  293. array( 'from' => $limit, 'to' => $total ),
  294. $revision_history
  295. );
  296. return self::get_revision_history( $media_id );
  297. }
  298. /**
  299. * Remove the original file and clean the post metadata.
  300. *
  301. * @param number $media_id - media post ID
  302. */
  303. public static function clean_original_media( $media_id ) {
  304. $original_file = self::get_original_media( $media_id );
  305. if ( ! $original_file ) {
  306. return null;
  307. }
  308. self::delete_media_history_file( $media_id, $original_file->file );
  309. return delete_post_meta( $media_id, self::$WP_ORIGINAL_MEDIA );
  310. }
  311. /**
  312. * Clean `revision_history` of the given $media_id. it means:
  313. * - remove all media files tied to the `revision_history` items.
  314. * - clean `revision_history` meta data.
  315. * - remove and clean the `original_media`
  316. *
  317. * @param number $media_id - media post ID
  318. * @return array results of removing these files
  319. */
  320. public static function clean_revision_history( $media_id ) {
  321. self::clean_original_media( $media_id );
  322. $revision_history = self::get_revision_history( $media_id );
  323. $total = count( $revision_history );
  324. $updated_history = array();
  325. if ( $total < 1 ) {
  326. return $updated_history;
  327. }
  328. $updated_history = self::remove_items_from_revision_history(
  329. $media_id,
  330. array( 'from' => 0, 'to' => $total ),
  331. $revision_history
  332. );
  333. return $updated_history;
  334. }
  335. /**
  336. * Edit media item process:
  337. *
  338. * - update attachment file
  339. * - preserve original media file
  340. * - trace revision history
  341. *
  342. * @param number $media_id - media post ID.
  343. * @param array $file_array - temporal file.
  344. * @return {Post|WP_Error} Updated media item or a WP_Error is something went wrong.
  345. */
  346. public static function edit_media_file( $media_id, $file_array ) {
  347. $media_item = get_post( $media_id );
  348. $has_original_media = self::get_original_media( $media_id );
  349. if ( ! $has_original_media ) {
  350. // The first time that the media is updated
  351. // the original media is stored into the revision_history.
  352. $snapshot = self::get_snapshot( $media_item );
  353. //phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
  354. add_post_meta( $media_id, self::$WP_ORIGINAL_MEDIA, $snapshot, true );
  355. }
  356. // Save temporary file in the correct location.
  357. $uploaded_file = self::save_temporary_file( $file_array, $media_id );
  358. if ( is_wp_error( $uploaded_file ) ) {
  359. self::remove_tmp_file( $file_array );
  360. return $uploaded_file;
  361. }
  362. // Revision_history control.
  363. self::register_revision( $media_item, $uploaded_file, $has_original_media );
  364. $uploaded_path = $uploaded_file['file'];
  365. $udpated_mime_type = $uploaded_file['type'];
  366. $was_updated = update_attached_file( $media_id, $uploaded_path );
  367. if ( ! $was_updated ) {
  368. return WP_Error( 'update_error', 'Media update error' );
  369. }
  370. // Check maximum amount of revision_history before updating the attachment metadata.
  371. self::limit_revision_history( $media_id );
  372. $new_metadata = wp_generate_attachment_metadata( $media_id, $uploaded_path );
  373. wp_update_attachment_metadata( $media_id, $new_metadata );
  374. $edited_action = wp_update_post(
  375. (object) array(
  376. 'ID' => $media_id,
  377. 'post_mime_type' => $udpated_mime_type,
  378. ),
  379. true
  380. );
  381. if ( is_wp_error( $edited_action ) ) {
  382. return $edited_action;
  383. }
  384. return $media_item;
  385. }
  386. }
  387. // hook: clean revision history when the media item is deleted
  388. function clean_revision_history( $media_id ) {
  389. Jetpack_Media::clean_revision_history( $media_id );
  390. };
  391. add_action( 'delete_attachment', 'clean_revision_history' );