home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-includes / rest-api / endpoints / class-wp-rest-attachments-controller.php next >
Encoding:
PHP Script  |  2018-01-15  |  23.0 KB  |  744 lines

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