class-wp-rest-attachments-controller.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. <?php
  2. /**
  3. * REST API: WP_REST_Attachments_Controller class
  4. *
  5. * @package WordPress
  6. * @subpackage REST_API
  7. * @since 4.7.0
  8. */
  9. /**
  10. * Core controller used to access attachments via the REST API.
  11. *
  12. * @since 4.7.0
  13. *
  14. * @see WP_REST_Posts_Controller
  15. */
  16. class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
  17. /**
  18. * Determines the allowed query_vars for a get_items() response and
  19. * prepares for WP_Query.
  20. *
  21. * @since 4.7.0
  22. *
  23. * @param array $prepared_args Optional. Array of prepared arguments. Default empty array.
  24. * @param WP_REST_Request $request Optional. Request to prepare items for.
  25. * @return array Array of query arguments.
  26. */
  27. protected function prepare_items_query( $prepared_args = array(), $request = null ) {
  28. $query_args = parent::prepare_items_query( $prepared_args, $request );
  29. if ( empty( $query_args['post_status'] ) ) {
  30. $query_args['post_status'] = 'inherit';
  31. }
  32. $media_types = $this->get_media_types();
  33. if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) {
  34. $query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
  35. }
  36. if ( ! empty( $request['mime_type'] ) ) {
  37. $parts = explode( '/', $request['mime_type'] );
  38. if ( isset( $media_types[ $parts[0] ] ) && in_array( $request['mime_type'], $media_types[ $parts[0] ], true ) ) {
  39. $query_args['post_mime_type'] = $request['mime_type'];
  40. }
  41. }
  42. // Filter query clauses to include filenames.
  43. if ( isset( $query_args['s'] ) ) {
  44. add_filter( 'posts_clauses', '_filter_query_attachment_filenames' );
  45. }
  46. return $query_args;
  47. }
  48. /**
  49. * Checks if a given request has access to create an attachment.
  50. *
  51. * @since 4.7.0
  52. *
  53. * @param WP_REST_Request $request Full details about the request.
  54. * @return WP_Error|true Boolean true if the attachment may be created, or a WP_Error if not.
  55. */
  56. public function create_item_permissions_check( $request ) {
  57. $ret = parent::create_item_permissions_check( $request );
  58. if ( ! $ret || is_wp_error( $ret ) ) {
  59. return $ret;
  60. }
  61. if ( ! current_user_can( 'upload_files' ) ) {
  62. return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to upload media on this site.' ), array( 'status' => 400 ) );
  63. }
  64. // Attaching media to a post requires ability to edit said post.
  65. if ( ! empty( $request['post'] ) ) {
  66. $parent = get_post( (int) $request['post'] );
  67. $post_parent_type = get_post_type_object( $parent->post_type );
  68. if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
  69. return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to upload media to this post.' ), array( 'status' => rest_authorization_required_code() ) );
  70. }
  71. }
  72. return true;
  73. }
  74. /**
  75. * Creates a single attachment.
  76. *
  77. * @since 4.7.0
  78. *
  79. * @param WP_REST_Request $request Full details about the request.
  80. * @return WP_Error|WP_REST_Response Response object on success, WP_Error object on failure.
  81. */
  82. public function create_item( $request ) {
  83. if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
  84. return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
  85. }
  86. // Get the file via $_FILES or raw data.
  87. $files = $request->get_file_params();
  88. $headers = $request->get_headers();
  89. if ( ! empty( $files ) ) {
  90. $file = $this->upload_from_file( $files, $headers );
  91. } else {
  92. $file = $this->upload_from_data( $request->get_body(), $headers );
  93. }
  94. if ( is_wp_error( $file ) ) {
  95. return $file;
  96. }
  97. $name = basename( $file['file'] );
  98. $name_parts = pathinfo( $name );
  99. $name = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );
  100. $url = $file['url'];
  101. $type = $file['type'];
  102. $file = $file['file'];
  103. // use image exif/iptc data for title and caption defaults if possible
  104. $image_meta = wp_read_image_metadata( $file );
  105. if ( ! empty( $image_meta ) ) {
  106. if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
  107. $request['title'] = $image_meta['title'];
  108. }
  109. if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
  110. $request['caption'] = $image_meta['caption'];
  111. }
  112. }
  113. $attachment = $this->prepare_item_for_database( $request );
  114. $attachment->post_mime_type = $type;
  115. $attachment->guid = $url;
  116. if ( empty( $attachment->post_title ) ) {
  117. $attachment->post_title = preg_replace( '/\.[^.]+$/', '', basename( $file ) );
  118. }
  119. // $post_parent is inherited from $attachment['post_parent'].
  120. $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true );
  121. if ( is_wp_error( $id ) ) {
  122. if ( 'db_update_error' === $id->get_error_code() ) {
  123. $id->add_data( array( 'status' => 500 ) );
  124. } else {
  125. $id->add_data( array( 'status' => 400 ) );
  126. }
  127. return $id;
  128. }
  129. $attachment = get_post( $id );
  130. /**
  131. * Fires after a single attachment is created or updated via the REST API.
  132. *
  133. * @since 4.7.0
  134. *
  135. * @param WP_Post $attachment Inserted or updated attachment
  136. * object.
  137. * @param WP_REST_Request $request The request sent to the API.
  138. * @param bool $creating True when creating an attachment, false when updating.
  139. */
  140. do_action( 'rest_insert_attachment', $attachment, $request, true );
  141. // Include admin functions to get access to wp_generate_attachment_metadata().
  142. require_once ABSPATH . 'wp-admin/includes/admin.php';
  143. wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
  144. if ( isset( $request['alt_text'] ) ) {
  145. update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
  146. }
  147. $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
  148. if ( is_wp_error( $fields_update ) ) {
  149. return $fields_update;
  150. }
  151. $request->set_param( 'context', 'edit' );
  152. $response = $this->prepare_item_for_response( $attachment, $request );
  153. $response = rest_ensure_response( $response );
  154. $response->set_status( 201 );
  155. $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ) );
  156. return $response;
  157. }
  158. /**
  159. * Updates a single attachment.
  160. *
  161. * @since 4.7.0
  162. *
  163. * @param WP_REST_Request $request Full details about the request.
  164. * @return WP_Error|WP_REST_Response Response object on success, WP_Error object on failure.
  165. */
  166. public function update_item( $request ) {
  167. if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
  168. return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
  169. }
  170. $response = parent::update_item( $request );
  171. if ( is_wp_error( $response ) ) {
  172. return $response;
  173. }
  174. $response = rest_ensure_response( $response );
  175. $data = $response->get_data();
  176. if ( isset( $request['alt_text'] ) ) {
  177. update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
  178. }
  179. $attachment = get_post( $request['id'] );
  180. /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
  181. do_action( 'rest_insert_attachment', $data, $request, false );
  182. $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
  183. if ( is_wp_error( $fields_update ) ) {
  184. return $fields_update;
  185. }
  186. $request->set_param( 'context', 'edit' );
  187. $response = $this->prepare_item_for_response( $attachment, $request );
  188. $response = rest_ensure_response( $response );
  189. return $response;
  190. }
  191. /**
  192. * Prepares a single attachment for create or update.
  193. *
  194. * @since 4.7.0
  195. *
  196. * @param WP_REST_Request $request Request object.
  197. * @return WP_Error|stdClass $prepared_attachment Post object.
  198. */
  199. protected function prepare_item_for_database( $request ) {
  200. $prepared_attachment = parent::prepare_item_for_database( $request );
  201. // Attachment caption (post_excerpt internally)
  202. if ( isset( $request['caption'] ) ) {
  203. if ( is_string( $request['caption'] ) ) {
  204. $prepared_attachment->post_excerpt = $request['caption'];
  205. } elseif ( isset( $request['caption']['raw'] ) ) {
  206. $prepared_attachment->post_excerpt = $request['caption']['raw'];
  207. }
  208. }
  209. // Attachment description (post_content internally)
  210. if ( isset( $request['description'] ) ) {
  211. if ( is_string( $request['description'] ) ) {
  212. $prepared_attachment->post_content = $request['description'];
  213. } elseif ( isset( $request['description']['raw'] ) ) {
  214. $prepared_attachment->post_content = $request['description']['raw'];
  215. }
  216. }
  217. if ( isset( $request['post'] ) ) {
  218. $prepared_attachment->post_parent = (int) $request['post'];
  219. }
  220. return $prepared_attachment;
  221. }
  222. /**
  223. * Prepares a single attachment output for response.
  224. *
  225. * @since 4.7.0
  226. *
  227. * @param WP_Post $post Attachment object.
  228. * @param WP_REST_Request $request Request object.
  229. * @return WP_REST_Response Response object.
  230. */
  231. public function prepare_item_for_response( $post, $request ) {
  232. $response = parent::prepare_item_for_response( $post, $request );
  233. $fields = $this->get_fields_for_response( $request );
  234. $data = $response->get_data();
  235. if ( in_array( 'description', $fields, true ) ) {
  236. $data['description'] = array(
  237. 'raw' => $post->post_content,
  238. /** This filter is documented in wp-includes/post-template.php */
  239. 'rendered' => apply_filters( 'the_content', $post->post_content ),
  240. );
  241. }
  242. if ( in_array( 'caption', $fields, true ) ) {
  243. /** This filter is documented in wp-includes/post-template.php */
  244. $caption = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
  245. $data['caption'] = array(
  246. 'raw' => $post->post_excerpt,
  247. 'rendered' => $caption,
  248. );
  249. }
  250. if ( in_array( 'alt_text', $fields, true ) ) {
  251. $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
  252. }
  253. if ( in_array( 'media_type', $fields, true ) ) {
  254. $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
  255. }
  256. if ( in_array( 'mime_type', $fields, true ) ) {
  257. $data['mime_type'] = $post->post_mime_type;
  258. }
  259. if ( in_array( 'media_details', $fields, true ) ) {
  260. $data['media_details'] = wp_get_attachment_metadata( $post->ID );
  261. // Ensure empty details is an empty object.
  262. if ( empty( $data['media_details'] ) ) {
  263. $data['media_details'] = new stdClass;
  264. } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
  265. foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
  266. if ( isset( $size_data['mime-type'] ) ) {
  267. $size_data['mime_type'] = $size_data['mime-type'];
  268. unset( $size_data['mime-type'] );
  269. }
  270. // Use the same method image_downsize() does.
  271. $image_src = wp_get_attachment_image_src( $post->ID, $size );
  272. if ( ! $image_src ) {
  273. continue;
  274. }
  275. $size_data['source_url'] = $image_src[0];
  276. }
  277. $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
  278. if ( ! empty( $full_src ) ) {
  279. $data['media_details']['sizes']['full'] = array(
  280. 'file' => wp_basename( $full_src[0] ),
  281. 'width' => $full_src[1],
  282. 'height' => $full_src[2],
  283. 'mime_type' => $post->post_mime_type,
  284. 'source_url' => $full_src[0],
  285. );
  286. }
  287. } else {
  288. $data['media_details']['sizes'] = new stdClass;
  289. }
  290. }
  291. if ( in_array( 'post', $fields, true ) ) {
  292. $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
  293. }
  294. if ( in_array( 'source_url', $fields, true ) ) {
  295. $data['source_url'] = wp_get_attachment_url( $post->ID );
  296. }
  297. $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
  298. $data = $this->filter_response_by_context( $data, $context );
  299. $links = $response->get_links();
  300. // Wrap the data in a response object.
  301. $response = rest_ensure_response( $data );
  302. $response->add_links( $links );
  303. /**
  304. * Filters an attachment returned from the REST API.
  305. *
  306. * Allows modification of the attachment right before it is returned.
  307. *
  308. * @since 4.7.0
  309. *
  310. * @param WP_REST_Response $response The response object.
  311. * @param WP_Post $post The original attachment post.
  312. * @param WP_REST_Request $request Request used to generate the response.
  313. */
  314. return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
  315. }
  316. /**
  317. * Retrieves the attachment's schema, conforming to JSON Schema.
  318. *
  319. * @since 4.7.0
  320. *
  321. * @return array Item schema as an array.
  322. */
  323. public function get_item_schema() {
  324. $schema = parent::get_item_schema();
  325. $schema['properties']['alt_text'] = array(
  326. 'description' => __( 'Alternative text to display when attachment is not displayed.' ),
  327. 'type' => 'string',
  328. 'context' => array( 'view', 'edit', 'embed' ),
  329. 'arg_options' => array(
  330. 'sanitize_callback' => 'sanitize_text_field',
  331. ),
  332. );
  333. $schema['properties']['caption'] = array(
  334. 'description' => __( 'The attachment caption.' ),
  335. 'type' => 'object',
  336. 'context' => array( 'view', 'edit', 'embed' ),
  337. 'arg_options' => array(
  338. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  339. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
  340. ),
  341. 'properties' => array(
  342. 'raw' => array(
  343. 'description' => __( 'Caption for the attachment, as it exists in the database.' ),
  344. 'type' => 'string',
  345. 'context' => array( 'edit' ),
  346. ),
  347. 'rendered' => array(
  348. 'description' => __( 'HTML caption for the attachment, transformed for display.' ),
  349. 'type' => 'string',
  350. 'context' => array( 'view', 'edit', 'embed' ),
  351. 'readonly' => true,
  352. ),
  353. ),
  354. );
  355. $schema['properties']['description'] = array(
  356. 'description' => __( 'The attachment description.' ),
  357. 'type' => 'object',
  358. 'context' => array( 'view', 'edit' ),
  359. 'arg_options' => array(
  360. 'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
  361. 'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
  362. ),
  363. 'properties' => array(
  364. 'raw' => array(
  365. 'description' => __( 'Description for the object, as it exists in the database.' ),
  366. 'type' => 'string',
  367. 'context' => array( 'edit' ),
  368. ),
  369. 'rendered' => array(
  370. 'description' => __( 'HTML description for the object, transformed for display.' ),
  371. 'type' => 'string',
  372. 'context' => array( 'view', 'edit' ),
  373. 'readonly' => true,
  374. ),
  375. ),
  376. );
  377. $schema['properties']['media_type'] = array(
  378. 'description' => __( 'Attachment type.' ),
  379. 'type' => 'string',
  380. 'enum' => array( 'image', 'file' ),
  381. 'context' => array( 'view', 'edit', 'embed' ),
  382. 'readonly' => true,
  383. );
  384. $schema['properties']['mime_type'] = array(
  385. 'description' => __( 'The attachment MIME type.' ),
  386. 'type' => 'string',
  387. 'context' => array( 'view', 'edit', 'embed' ),
  388. 'readonly' => true,
  389. );
  390. $schema['properties']['media_details'] = array(
  391. 'description' => __( 'Details about the media file, specific to its type.' ),
  392. 'type' => 'object',
  393. 'context' => array( 'view', 'edit', 'embed' ),
  394. 'readonly' => true,
  395. );
  396. $schema['properties']['post'] = array(
  397. 'description' => __( 'The ID for the associated post of the attachment.' ),
  398. 'type' => 'integer',
  399. 'context' => array( 'view', 'edit' ),
  400. );
  401. $schema['properties']['source_url'] = array(
  402. 'description' => __( 'URL to the original attachment file.' ),
  403. 'type' => 'string',
  404. 'format' => 'uri',
  405. 'context' => array( 'view', 'edit', 'embed' ),
  406. 'readonly' => true,
  407. );
  408. unset( $schema['properties']['password'] );
  409. return $schema;
  410. }
  411. /**
  412. * Handles an upload via raw POST data.
  413. *
  414. * @since 4.7.0
  415. *
  416. * @param array $data Supplied file data.
  417. * @param array $headers HTTP headers from the request.
  418. * @return array|WP_Error Data from wp_handle_sideload().
  419. */
  420. protected function upload_from_data( $data, $headers ) {
  421. if ( empty( $data ) ) {
  422. return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
  423. }
  424. if ( empty( $headers['content_type'] ) ) {
  425. return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) );
  426. }
  427. if ( empty( $headers['content_disposition'] ) ) {
  428. return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) );
  429. }
  430. $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
  431. if ( empty( $filename ) ) {
  432. return new WP_Error( 'rest_upload_invalid_disposition', __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as `attachment; filename="image.png"` or similar.' ), array( 'status' => 400 ) );
  433. }
  434. if ( ! empty( $headers['content_md5'] ) ) {
  435. $content_md5 = array_shift( $headers['content_md5'] );
  436. $expected = trim( $content_md5 );
  437. $actual = md5( $data );
  438. if ( $expected !== $actual ) {
  439. return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
  440. }
  441. }
  442. // Get the content-type.
  443. $type = array_shift( $headers['content_type'] );
  444. /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload() */
  445. require_once ABSPATH . 'wp-admin/includes/admin.php';
  446. // Save the file.
  447. $tmpfname = wp_tempnam( $filename );
  448. $fp = fopen( $tmpfname, 'w+' );
  449. if ( ! $fp ) {
  450. return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) );
  451. }
  452. fwrite( $fp, $data );
  453. fclose( $fp );
  454. // Now, sideload it in.
  455. $file_data = array(
  456. 'error' => null,
  457. 'tmp_name' => $tmpfname,
  458. 'name' => $filename,
  459. 'type' => $type,
  460. );
  461. $size_check = self::check_upload_size( $file_data );
  462. if ( is_wp_error( $size_check ) ) {
  463. return $size_check;
  464. }
  465. $overrides = array(
  466. 'test_form' => false,
  467. );
  468. $sideloaded = wp_handle_sideload( $file_data, $overrides );
  469. if ( isset( $sideloaded['error'] ) ) {
  470. @unlink( $tmpfname );
  471. return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
  472. }
  473. return $sideloaded;
  474. }
  475. /**
  476. * Parses filename from a Content-Disposition header value.
  477. *
  478. * As per RFC6266:
  479. *
  480. * content-disposition = "Content-Disposition" ":"
  481. * disposition-type *( ";" disposition-parm )
  482. *
  483. * disposition-type = "inline" | "attachment" | disp-ext-type
  484. * ; case-insensitive
  485. * disp-ext-type = token
  486. *
  487. * disposition-parm = filename-parm | disp-ext-parm
  488. *
  489. * filename-parm = "filename" "=" value
  490. * | "filename*" "=" ext-value
  491. *
  492. * disp-ext-parm = token "=" value
  493. * | ext-token "=" ext-value
  494. * ext-token = <the characters in token, followed by "*">
  495. *
  496. * @since 4.7.0
  497. *
  498. * @link http://tools.ietf.org/html/rfc2388
  499. * @link http://tools.ietf.org/html/rfc6266
  500. *
  501. * @param string[] $disposition_header List of Content-Disposition header values.
  502. * @return string|null Filename if available, or null if not found.
  503. */
  504. public static function get_filename_from_disposition( $disposition_header ) {
  505. // Get the filename.
  506. $filename = null;
  507. foreach ( $disposition_header as $value ) {
  508. $value = trim( $value );
  509. if ( strpos( $value, ';' ) === false ) {
  510. continue;
  511. }
  512. list( $type, $attr_parts ) = explode( ';', $value, 2 );
  513. $attr_parts = explode( ';', $attr_parts );
  514. $attributes = array();
  515. foreach ( $attr_parts as $part ) {
  516. if ( strpos( $part, '=' ) === false ) {
  517. continue;
  518. }
  519. list( $key, $value ) = explode( '=', $part, 2 );
  520. $attributes[ trim( $key ) ] = trim( $value );
  521. }
  522. if ( empty( $attributes['filename'] ) ) {
  523. continue;
  524. }
  525. $filename = trim( $attributes['filename'] );
  526. // Unquote quoted filename, but after trimming.
  527. if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
  528. $filename = substr( $filename, 1, -1 );
  529. }
  530. }
  531. return $filename;
  532. }
  533. /**
  534. * Retrieves the query params for collections of attachments.
  535. *
  536. * @since 4.7.0
  537. *
  538. * @return array Query parameters for the attachment collection as an array.
  539. */
  540. public function get_collection_params() {
  541. $params = parent::get_collection_params();
  542. $params['status']['default'] = 'inherit';
  543. $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
  544. $media_types = $this->get_media_types();
  545. $params['media_type'] = array(
  546. 'default' => null,
  547. 'description' => __( 'Limit result set to attachments of a particular media type.' ),
  548. 'type' => 'string',
  549. 'enum' => array_keys( $media_types ),
  550. );
  551. $params['mime_type'] = array(
  552. 'default' => null,
  553. 'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
  554. 'type' => 'string',
  555. );
  556. return $params;
  557. }
  558. /**
  559. * Validates whether the user can query private statuses.
  560. *
  561. * @since 4.7.0
  562. *
  563. * @param mixed $value Status value.
  564. * @param WP_REST_Request $request Request object.
  565. * @param string $parameter Additional parameter to pass for validation.
  566. * @return WP_Error|bool True if the user may query, WP_Error if not.
  567. */
  568. public function validate_user_can_query_private_statuses( $value, $request, $parameter ) {
  569. if ( 'inherit' === $value ) {
  570. return true;
  571. }
  572. return parent::validate_user_can_query_private_statuses( $value, $request, $parameter );
  573. }
  574. /**
  575. * Handles an upload via multipart/form-data ($_FILES).
  576. *
  577. * @since 4.7.0
  578. *
  579. * @param array $files Data from the `$_FILES` superglobal.
  580. * @param array $headers HTTP headers from the request.
  581. * @return array|WP_Error Data from wp_handle_upload().
  582. */
  583. protected function upload_from_file( $files, $headers ) {
  584. if ( empty( $files ) ) {
  585. return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
  586. }
  587. // Verify hash, if given.
  588. if ( ! empty( $headers['content_md5'] ) ) {
  589. $content_md5 = array_shift( $headers['content_md5'] );
  590. $expected = trim( $content_md5 );
  591. $actual = md5_file( $files['file']['tmp_name'] );
  592. if ( $expected !== $actual ) {
  593. return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
  594. }
  595. }
  596. // Pass off to WP to handle the actual upload.
  597. $overrides = array(
  598. 'test_form' => false,
  599. );
  600. // Bypasses is_uploaded_file() when running unit tests.
  601. if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
  602. $overrides['action'] = 'wp_handle_mock_upload';
  603. }
  604. $size_check = self::check_upload_size( $files['file'] );
  605. if ( is_wp_error( $size_check ) ) {
  606. return $size_check;
  607. }
  608. /** Include admin functions to get access to wp_handle_upload() */
  609. require_once ABSPATH . 'wp-admin/includes/admin.php';
  610. $file = wp_handle_upload( $files['file'], $overrides );
  611. if ( isset( $file['error'] ) ) {
  612. return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
  613. }
  614. return $file;
  615. }
  616. /**
  617. * Retrieves the supported media types.
  618. *
  619. * Media types are considered the MIME type category.
  620. *
  621. * @since 4.7.0
  622. *
  623. * @return array Array of supported media types.
  624. */
  625. protected function get_media_types() {
  626. $media_types = array();
  627. foreach ( get_allowed_mime_types() as $mime_type ) {
  628. $parts = explode( '/', $mime_type );
  629. if ( ! isset( $media_types[ $parts[0] ] ) ) {
  630. $media_types[ $parts[0] ] = array();
  631. }
  632. $media_types[ $parts[0] ][] = $mime_type;
  633. }
  634. return $media_types;
  635. }
  636. /**
  637. * Determine if uploaded file exceeds space quota on multisite.
  638. *
  639. * Replicates check_upload_size().
  640. *
  641. * @since 4.9.8
  642. *
  643. * @param array $file $_FILES array for a given file.
  644. * @return true|WP_Error True if can upload, error for errors.
  645. */
  646. protected function check_upload_size( $file ) {
  647. if ( ! is_multisite() ) {
  648. return true;
  649. }
  650. if ( get_site_option( 'upload_space_check_disabled' ) ) {
  651. return true;
  652. }
  653. $space_left = get_upload_space_available();
  654. $file_size = filesize( $file['tmp_name'] );
  655. if ( $space_left < $file_size ) {
  656. /* translators: %s: required disk space in kilobytes */
  657. return new WP_Error( 'rest_upload_limited_space', sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $file_size - $space_left ) / KB_IN_BYTES ) ), array( 'status' => 400 ) );
  658. }
  659. if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
  660. /* translators: %s: maximum allowed file size in kilobytes */
  661. return new WP_Error( 'rest_upload_file_too_big', sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), get_site_option( 'fileupload_maxk', 1500 ) ), array( 'status' => 400 ) );
  662. }
  663. if ( upload_is_user_over_quota( false ) ) {
  664. return new WP_Error( 'rest_upload_user_quota_exceeded', __( 'You have used your space quota. Please delete files before uploading.' ), array( 'status' => 400 ) );
  665. }
  666. return true;
  667. }
  668. }