Make WordPress Core

Changeset 39011


Ignore:
Timestamp:
10/30/2016 05:39:09 AM (10 years ago)
Author:
DrewAPicture
Message:

Docs: Add much more complete and syntactically correct documentation throughout the WP_REST_Attachments_Controller class.

Props Soean, mrahmadawais, flixos90.
See #38398.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php

    r38832 r39011  
    11<?php
    2 
     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 */
    317class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {
    418
    519        /**
    6          * Determine the allowed query_vars for a get_items() response and
    7          * prepare for WP_Query.
    8          *
    9          * @param array           $prepared_args Optional. Array of prepared arguments.
     20         * Determines the allowed query_vars for a get_items() response and
     21         * prepares for WP_Query.
     22         *
     23         * @since 4.7.0
     24         * @access protected
     25         *
     26         * @param array           $prepared_args Optional. Array of prepared arguments. Default empty array.
    1027         * @param WP_REST_Request $request       Optional. Request to prepare items for.
    1128         * @return array Array of query arguments.
     
    1330        protected function prepare_items_query( $prepared_args = array(), $request = null ) {
    1431                $query_args = parent::prepare_items_query( $prepared_args, $request );
     32
    1533                if ( empty( $query_args['post_status'] ) || ! in_array( $query_args['post_status'], array( 'inherit', 'private', 'trash' ), true ) ) {
    1634                        $query_args['post_status'] = 'inherit';
    1735                }
     36
    1837                $media_types = $this->get_media_types();
     38
    1939                if ( ! empty( $request['media_type'] ) && isset( $media_types[ $request['media_type'] ] ) ) {
    2040                        $query_args['post_mime_type'] = $media_types[ $request['media_type'] ];
    2141                }
     42
    2243                if ( ! empty( $request['mime_type'] ) ) {
    2344                        $parts = explode( '/', $request['mime_type'] );
     
    2647                        }
    2748                }
     49
    2850                return $query_args;
    2951        }
    3052
    3153        /**
    32          * Check if a given request has access to create an attachment.
    33          *
    34          * @param  WP_REST_Request $request Full details about the request.
     54         * Checks if a given request has access to create an attachment.
     55         *
     56         * @since 4.7.0
     57         * @access public
     58         *
     59         * @param WP_REST_Request $request Full details about the request.
    3560         * @return WP_Error|true Boolean true if the attachment may be created, or a WP_Error if not.
    3661         */
    3762        public function create_item_permissions_check( $request ) {
    3863                $ret = parent::create_item_permissions_check( $request );
     64
    3965                if ( ! $ret || is_wp_error( $ret ) ) {
    4066                        return $ret;
     
    4975                        $parent = $this->get_post( (int) $request['post'] );
    5076                        $post_parent_type = get_post_type_object( $parent->post_type );
     77
    5178                        if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
    5279                                return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to upload media to this resource.' ), array( 'status' => rest_authorization_required_code() ) );
     
    5885
    5986        /**
    60          * Create a single attachment.
     87         * Creates a single attachment.
     88         *
     89         * @since 4.7.0
     90         * @access public
    6191         *
    6292         * @param WP_REST_Request $request Full details about the request.
     
    6999                }
    70100
    71                 // Get the file via $_FILES or raw data
     101                // Get the file via $_FILES or raw data.
    72102                $files = $request->get_file_params();
    73103                $headers = $request->get_headers();
     104
    74105                if ( ! empty( $files ) ) {
    75106                        $file = $this->upload_from_file( $files, $headers );
     
    91122
    92123                // use image exif/iptc data for title and caption defaults if possible
    93                 // @codingStandardsIgnoreStart
    94124                $image_meta = @wp_read_image_metadata( $file );
    95                 // @codingStandardsIgnoreEnd
     125
    96126                if ( ! empty( $image_meta ) ) {
    97127                        if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
     
    114144
    115145                $id = wp_insert_post( $attachment, true );
     146
    116147                if ( is_wp_error( $id ) ) {
    117148                        if ( 'db_update_error' === $id->get_error_code() ) {
     
    122153                        return $id;
    123154                }
     155
    124156                $attachment = $this->get_post( $id );
    125157
     
    134166
    135167                $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
     168
    136169                if ( is_wp_error( $fields_update ) ) {
    137170                        return $fields_update;
     
    147180                 * Fires after a single attachment is created or updated via the REST API.
    148181                 *
     182                 * @since 4.7.0
     183                 *
    149184                 * @param object          $attachment Inserted attachment.
    150185                 * @param WP_REST_Request $request    The request sent to the API.
    151                  * @param boolean         $creating   True when creating an attachment, false when updating.
     186                 * @param bool            $creating   True when creating an attachment, false when updating.
    152187                 */
    153188                do_action( 'rest_insert_attachment', $attachment, $request, true );
    154189
    155190                return $response;
    156 
    157         }
    158 
    159         /**
    160          * Update a single post.
     191        }
     192
     193        /**
     194         * Updates a single attachment.
     195         *
     196         * @since 4.7.0
     197         * @access public
    161198         *
    162199         * @param WP_REST_Request $request Full details about the request.
     
    167204                        return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
    168205                }
     206
    169207                $response = parent::update_item( $request );
     208
    170209                if ( is_wp_error( $response ) ) {
    171210                        return $response;
     
    182221
    183222                $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
     223
    184224                if ( is_wp_error( $fields_update ) ) {
    185225                        return $fields_update;
     
    190230                $response = rest_ensure_response( $response );
    191231
    192                 /* This action is documented in lib/endpoints/class-wp-rest-attachments-controller.php */
     232                /* This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
    193233                do_action( 'rest_insert_attachment', $data, $request, false );
    194234
     
    197237
    198238        /**
    199          * Prepare a single attachment for create or update.
     239         * Prepares a single attachment for create or update.
     240         *
     241         * @since 4.7.0
     242         * @access public
    200243         *
    201244         * @param WP_REST_Request $request Request object.
     
    221264
    222265        /**
    223          * Prepare a single attachment output for response.
    224          *
    225          * @param WP_Post         $post    Post object.
     266         * Prepares a single attachment output for response.
     267         *
     268         * @since 4.7.0
     269         * @access public
     270         *
     271         * @param WP_Post         $post    Attachment object.
    226272         * @param WP_REST_Request $request Request object.
    227273         * @return WP_REST_Response Response object.
     
    262308
    263309                        $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
     310
    264311                        if ( ! empty( $full_src ) ) {
    265312                                $data['media_details']['sizes']['full'] = array(
    266                                         'file'          => wp_basename( $full_src[0] ),
    267                                         'width'         => $full_src[1],
    268                                         'height'        => $full_src[2],
    269                                         'mime_type'     => $post->post_mime_type,
    270                                         'source_url'    => $full_src[0],
    271                                         );
     313                                        'file'       => wp_basename( $full_src[0] ),
     314                                        'width'      => $full_src[1],
     315                                        'height'     => $full_src[2],
     316                                        'mime_type'  => $post->post_mime_type,
     317                                        'source_url' => $full_src[0],
     318                                );
    272319                        }
    273320                } else {
     
    285332
    286333                /**
    287                  * Filter an attachment returned from the API.
     334                 * Filters an attachment returned from the REST API.
    288335                 *
    289336                 * Allows modification of the attachment right before it is returned.
    290337                 *
    291                  * @param WP_REST_Response  $response   The response object.
    292                  * @param WP_Post           $post       The original attachment post.
    293                  * @param WP_REST_Request   $request    Request used to generate the response.
     338                 * @since 4.7.0
     339                 *
     340                 * @param WP_REST_Response $response The response object.
     341                 * @param WP_Post          $post     The original attachment post.
     342                 * @param WP_REST_Request  $request  Request used to generate the response.
    294343                 */
    295344                return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
     
    297346
    298347        /**
    299          * Get the Attachment's schema, conforming to JSON Schema.
     348         * Retrieves the attachment's schema, conforming to JSON Schema.
     349         *
     350         * @since 4.7.0
     351         * @access public
    300352         *
    301353         * @return array Item schema as an array.
     
    313365                        ),
    314366                );
     367
    315368                $schema['properties']['caption'] = array(
    316369                        'description'     => __( 'The caption for the resource.' ),
     
    321374                        ),
    322375                );
     376
    323377                $schema['properties']['description'] = array(
    324378                        'description'     => __( 'The description for the resource.' ),
     
    329383                        ),
    330384                );
     385
    331386                $schema['properties']['media_type'] = array(
    332387                        'description'     => __( 'Type of resource.' ),
     
    336391                        'readonly'        => true,
    337392                );
     393
    338394                $schema['properties']['mime_type'] = array(
    339395                        'description'     => __( 'MIME type of resource.' ),
     
    342398                        'readonly'        => true,
    343399                );
     400
    344401                $schema['properties']['media_details'] = array(
    345402                        'description'     => __( 'Details about the resource file, specific to its type.' ),
     
    348405                        'readonly'        => true,
    349406                );
     407
    350408                $schema['properties']['post'] = array(
    351409                        'description'     => __( 'The id for the associated post of the resource.' ),
     
    353411                        'context'         => array( 'view', 'edit' ),
    354412                );
     413
    355414                $schema['properties']['source_url'] = array(
    356415                        'description'     => __( 'URL to the original resource file.' ),
     
    360419                        'readonly'        => true,
    361420                );
     421
    362422                return $schema;
    363423        }
    364424
    365425        /**
    366          * Handle an upload via raw POST data.
     426         * Handles an upload via raw POST data.
     427         *
     428         * @since 4.7.0
     429         * @access protected
    367430         *
    368431         * @param array $data    Supplied file data.
    369432         * @param array $headers HTTP headers from the request.
    370          * @return array|WP_Error Data from {@see wp_handle_sideload()}.
     433         * @return array|WP_Error Data from wp_handle_sideload().
    371434         */
    372435        protected function upload_from_data( $data, $headers ) {
     
    391454                if ( ! empty( $headers['content_md5'] ) ) {
    392455                        $content_md5 = array_shift( $headers['content_md5'] );
    393                         $expected = trim( $content_md5 );
    394                         $actual   = md5( $data );
     456                        $expected    = trim( $content_md5 );
     457                        $actual      = md5( $data );
    395458
    396459                        if ( $expected !== $actual ) {
     
    424487                        'type'     => $type,
    425488                );
     489
    426490                $overrides = array(
    427491                        'test_form' => false,
    428492                );
     493
    429494                $sideloaded = wp_handle_sideload( $file_data, $overrides );
    430495
    431496                if ( isset( $sideloaded['error'] ) ) {
    432                         // @codingStandardsIgnoreStart
    433497                        @unlink( $tmpfname );
    434                         // @codingStandardsIgnoreEnd
     498
    435499                        return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
    436500                }
     
    440504
    441505        /**
    442          * Parse filename from a Content-Disposition header value.
     506         * Parses filename from a Content-Disposition header value.
    443507         *
    444508         * As per RFC6266:
     
    460524         *     ext-token           = <the characters in token, followed by "*">
    461525         *
    462          * @see http://tools.ietf.org/html/rfc2388
    463          * @see http://tools.ietf.org/html/rfc6266
     526         * @since 4.7.0
     527         * @access public
     528         *
     529         * @link http://tools.ietf.org/html/rfc2388
     530         * @link http://tools.ietf.org/html/rfc6266
    464531         *
    465532         * @param string[] $disposition_header List of Content-Disposition header values.
     
    478545
    479546                        list( $type, $attr_parts ) = explode( ';', $value, 2 );
     547
    480548                        $attr_parts = explode( ';', $attr_parts );
    481549                        $attributes = array();
     550
    482551                        foreach ( $attr_parts as $part ) {
    483552                                if ( strpos( $part, '=' ) === false ) {
     
    486555
    487556                                list( $key, $value ) = explode( '=', $part, 2 );
     557
    488558                                $attributes[ trim( $key ) ] = trim( $value );
    489559                        }
     
    505575
    506576        /**
    507          * Get the query params for collections of attachments.
     577         * Retrieves the query params for collections of attachments.
     578         *
     579         * @since 4.7.0
     580         * @access public
    508581         *
    509582         * @return array Query parameters for the attachment collection as an array.
     
    514587                $params['status']['enum'] = array( 'inherit', 'private', 'trash' );
    515588                $media_types = $this->get_media_types();
     589
    516590                $params['media_type'] = array(
    517                         'default'            => null,
    518                         'description'        => __( 'Limit result set to attachments of a particular media type.' ),
    519                         'type'               => 'string',
    520                         'enum'               => array_keys( $media_types ),
    521                         'validate_callback'  => 'rest_validate_request_arg',
    522                 );
     591                        'default'           => null,
     592                        'description'       => __( 'Limit result set to attachments of a particular media type.' ),
     593                        'type'              => 'string',
     594                        'enum'              => array_keys( $media_types ),
     595                        'validate_callback' => 'rest_validate_request_arg',
     596                );
     597
    523598                $params['mime_type'] = array(
    524                         'default'            => null,
    525                         'description'        => __( 'Limit result set to attachments of a particular MIME type.' ),
    526                         'type'               => 'string',
    527                 );
     599                        'default'     => null,
     600                        'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
     601                        'type'        => 'string',
     602                );
     603
    528604                return $params;
    529605        }
    530606
    531607        /**
    532          * Validate whether the user can query private statuses
    533          *
    534          * @param  mixed           $value     Status value.
    535          * @param  WP_REST_Request $request   Request object.
    536          * @param  string          $parameter Additional parameter to pass to validation.
    537          * @return WP_Error|boolean Boolean true if the user may query, WP_Error if not.
     608         * Validates whether the user can query private statuses.
     609         *
     610         * @since 4.7.0
     611         * @access public
     612         *
     613         * @param mixed           $value     Status value.
     614         * @param WP_REST_Request $request   Request object.
     615         * @param string          $parameter Additional parameter to pass for validation.
     616         * @return WP_Error|bool True if the user may query, WP_Error if not.
    538617         */
    539618        public function validate_user_can_query_private_statuses( $value, $request, $parameter ) {
     
    541620                        return true;
    542621                }
     622
    543623                return parent::validate_user_can_query_private_statuses( $value, $request, $parameter );
    544624        }
    545625
    546626        /**
    547          * Handle an upload via multipart/form-data ($_FILES).
    548          *
    549          * @param array $files   Data from $_FILES.
     627         * Handles an upload via multipart/form-data ($_FILES).
     628         *
     629         * @since 4.7.0
     630         * @access protected
     631         *
     632         * @param array $files   Data from the `$_FILES` superglobal.
    550633         * @param array $headers HTTP headers from the request.
    551          * @return array|WP_Error Data from {@see wp_handle_upload()}.
     634         * @return array|WP_Error Data from wp_handle_upload().
    552635         */
    553636        protected function upload_from_file( $files, $headers ) {
     
    559642                if ( ! empty( $headers['content_md5'] ) ) {
    560643                        $content_md5 = array_shift( $headers['content_md5'] );
    561                         $expected = trim( $content_md5 );
    562                         $actual = md5_file( $files['file']['tmp_name'] );
     644                        $expected    = trim( $content_md5 );
     645                        $actual      = md5_file( $files['file']['tmp_name'] );
     646
    563647                        if ( $expected !== $actual ) {
    564648                                return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
     
    570654                        'test_form'   => false,
    571655                );
     656
    572657                // Bypasses is_uploaded_file() when running unit tests.
    573658                if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
     
    575660                }
    576661
    577                 // Include admin functions to get access to wp_handle_upload().
     662                /** Include admin functions to get access to wp_handle_upload() */
    578663                require_once ABSPATH . 'wp-admin/includes/admin.php';
     664
    579665                $file = wp_handle_upload( $files['file'], $overrides );
    580666
     
    587673
    588674        /**
    589          * Get the supported media types.
     675         * Retrieves the supported media types.
    590676         *
    591677         * Media types are considered the MIME type category.
    592678         *
    593          * @return array
     679         * @since 4.7.0
     680         * @access protected
     681         *
     682         * @return array Array of supported media types.
    594683         */
    595684        protected function get_media_types() {
    596685                $media_types = array();
     686
    597687                foreach ( get_allowed_mime_types() as $mime_type ) {
    598688                        $parts = explode( '/', $mime_type );
     689
    599690                        if ( ! isset( $media_types[ $parts[0] ] ) ) {
    600691                                $media_types[ $parts[0] ] = array();
    601692                        }
     693
    602694                        $media_types[ $parts[0] ][] = $mime_type;
    603695                }
     696
    604697                return $media_types;
    605698        }
Note: See TracChangeset for help on using the changeset viewer.