class.media.php 16 KB

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