[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

/wp-includes/rest-api/endpoints/ -> class-wp-rest-attachments-controller.php (source)

   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       = wp_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          // Include image functions to get access to wp_read_image_metadata().
 126          require_once  ABSPATH . 'wp-admin/includes/image.php';
 127  
 128          // use image exif/iptc data for title and caption defaults if possible
 129          $image_meta = wp_read_image_metadata( $file );
 130  
 131          if ( ! empty( $image_meta ) ) {
 132              if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
 133                  $request['title'] = $image_meta['title'];
 134              }
 135  
 136              if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
 137                  $request['caption'] = $image_meta['caption'];
 138              }
 139          }
 140  
 141          $attachment                 = $this->prepare_item_for_database( $request );
 142          $attachment->post_mime_type = $type;
 143          $attachment->guid           = $url;
 144  
 145          if ( empty( $attachment->post_title ) ) {
 146              $attachment->post_title = preg_replace( '/\.[^.]+$/', '', wp_basename( $file ) );
 147          }
 148  
 149          // $post_parent is inherited from $attachment['post_parent'].
 150          $id = wp_insert_attachment( wp_slash( (array) $attachment ), $file, 0, true );
 151  
 152          if ( is_wp_error( $id ) ) {
 153              if ( 'db_update_error' === $id->get_error_code() ) {
 154                  $id->add_data( array( 'status' => 500 ) );
 155              } else {
 156                  $id->add_data( array( 'status' => 400 ) );
 157              }
 158              return $id;
 159          }
 160  
 161          $attachment = get_post( $id );
 162  
 163          /**
 164           * Fires after a single attachment is created or updated via the REST API.
 165           *
 166           * @since 4.7.0
 167           *
 168           * @param WP_Post         $attachment Inserted or updated attachment
 169           *                                    object.
 170           * @param WP_REST_Request $request    The request sent to the API.
 171           * @param bool            $creating   True when creating an attachment, false when updating.
 172           */
 173          do_action( 'rest_insert_attachment', $attachment, $request, true );
 174  
 175          // Include admin function to get access to wp_generate_attachment_metadata().
 176          require_once  ABSPATH . 'wp-admin/includes/media.php';
 177  
 178          wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
 179  
 180          if ( isset( $request['alt_text'] ) ) {
 181              update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
 182          }
 183  
 184          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 185  
 186          if ( is_wp_error( $fields_update ) ) {
 187              return $fields_update;
 188          }
 189  
 190          $request->set_param( 'context', 'edit' );
 191  
 192          /**
 193           * Fires after a single attachment is completely created or updated via the REST API.
 194           *
 195           * @since 5.0.0
 196           *
 197           * @param WP_Post         $attachment Inserted or updated attachment object.
 198           * @param WP_REST_Request $request    Request object.
 199           * @param bool            $creating   True when creating an attachment, false when updating.
 200           */
 201          do_action( 'rest_after_insert_attachment', $attachment, $request, true );
 202  
 203          $response = $this->prepare_item_for_response( $attachment, $request );
 204          $response = rest_ensure_response( $response );
 205          $response->set_status( 201 );
 206          $response->header( 'Location', rest_url( sprintf( '%s/%s/%d', $this->namespace, $this->rest_base, $id ) ) );
 207  
 208          return $response;
 209      }
 210  
 211      /**
 212       * Updates a single attachment.
 213       *
 214       * @since 4.7.0
 215       *
 216       * @param WP_REST_Request $request Full details about the request.
 217       * @return WP_Error|WP_REST_Response Response object on success, WP_Error object on failure.
 218       */
 219  	public function update_item( $request ) {
 220          if ( ! empty( $request['post'] ) && in_array( get_post_type( $request['post'] ), array( 'revision', 'attachment' ), true ) ) {
 221              return new WP_Error( 'rest_invalid_param', __( 'Invalid parent type.' ), array( 'status' => 400 ) );
 222          }
 223  
 224          $response = parent::update_item( $request );
 225  
 226          if ( is_wp_error( $response ) ) {
 227              return $response;
 228          }
 229  
 230          $response = rest_ensure_response( $response );
 231          $data     = $response->get_data();
 232  
 233          if ( isset( $request['alt_text'] ) ) {
 234              update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
 235          }
 236  
 237          $attachment = get_post( $request['id'] );
 238  
 239          $fields_update = $this->update_additional_fields_for_object( $attachment, $request );
 240  
 241          if ( is_wp_error( $fields_update ) ) {
 242              return $fields_update;
 243          }
 244  
 245          $request->set_param( 'context', 'edit' );
 246  
 247          /** This action is documented in wp-includes/rest-api/endpoints/class-wp-rest-attachments-controller.php */
 248          do_action( 'rest_after_insert_attachment', $attachment, $request, false );
 249  
 250          $response = $this->prepare_item_for_response( $attachment, $request );
 251          $response = rest_ensure_response( $response );
 252  
 253          return $response;
 254      }
 255  
 256      /**
 257       * Prepares a single attachment for create or update.
 258       *
 259       * @since 4.7.0
 260       *
 261       * @param WP_REST_Request $request Request object.
 262       * @return WP_Error|stdClass $prepared_attachment Post object.
 263       */
 264  	protected function prepare_item_for_database( $request ) {
 265          $prepared_attachment = parent::prepare_item_for_database( $request );
 266  
 267          // Attachment caption (post_excerpt internally)
 268          if ( isset( $request['caption'] ) ) {
 269              if ( is_string( $request['caption'] ) ) {
 270                  $prepared_attachment->post_excerpt = $request['caption'];
 271              } elseif ( isset( $request['caption']['raw'] ) ) {
 272                  $prepared_attachment->post_excerpt = $request['caption']['raw'];
 273              }
 274          }
 275  
 276          // Attachment description (post_content internally)
 277          if ( isset( $request['description'] ) ) {
 278              if ( is_string( $request['description'] ) ) {
 279                  $prepared_attachment->post_content = $request['description'];
 280              } elseif ( isset( $request['description']['raw'] ) ) {
 281                  $prepared_attachment->post_content = $request['description']['raw'];
 282              }
 283          }
 284  
 285          if ( isset( $request['post'] ) ) {
 286              $prepared_attachment->post_parent = (int) $request['post'];
 287          }
 288  
 289          return $prepared_attachment;
 290      }
 291  
 292      /**
 293       * Prepares a single attachment output for response.
 294       *
 295       * @since 4.7.0
 296       *
 297       * @param WP_Post         $post    Attachment object.
 298       * @param WP_REST_Request $request Request object.
 299       * @return WP_REST_Response Response object.
 300       */
 301  	public function prepare_item_for_response( $post, $request ) {
 302          $response = parent::prepare_item_for_response( $post, $request );
 303          $fields   = $this->get_fields_for_response( $request );
 304          $data     = $response->get_data();
 305  
 306          if ( in_array( 'description', $fields, true ) ) {
 307              $data['description'] = array(
 308                  'raw'      => $post->post_content,
 309                  /** This filter is documented in wp-includes/post-template.php */
 310                  'rendered' => apply_filters( 'the_content', $post->post_content ),
 311              );
 312          }
 313  
 314          if ( in_array( 'caption', $fields, true ) ) {
 315              /** This filter is documented in wp-includes/post-template.php */
 316              $caption         = apply_filters( 'the_excerpt', apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ) );
 317              $data['caption'] = array(
 318                  'raw'      => $post->post_excerpt,
 319                  'rendered' => $caption,
 320              );
 321          }
 322  
 323          if ( in_array( 'alt_text', $fields, true ) ) {
 324              $data['alt_text'] = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
 325          }
 326  
 327          if ( in_array( 'media_type', $fields, true ) ) {
 328              $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
 329          }
 330  
 331          if ( in_array( 'mime_type', $fields, true ) ) {
 332              $data['mime_type'] = $post->post_mime_type;
 333          }
 334  
 335          if ( in_array( 'media_details', $fields, true ) ) {
 336              $data['media_details'] = wp_get_attachment_metadata( $post->ID );
 337  
 338              // Ensure empty details is an empty object.
 339              if ( empty( $data['media_details'] ) ) {
 340                  $data['media_details'] = new stdClass;
 341              } elseif ( ! empty( $data['media_details']['sizes'] ) ) {
 342  
 343                  foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
 344  
 345                      if ( isset( $size_data['mime-type'] ) ) {
 346                          $size_data['mime_type'] = $size_data['mime-type'];
 347                          unset( $size_data['mime-type'] );
 348                      }
 349  
 350                      // Use the same method image_downsize() does.
 351                      $image_src = wp_get_attachment_image_src( $post->ID, $size );
 352                      if ( ! $image_src ) {
 353                          continue;
 354                      }
 355  
 356                      $size_data['source_url'] = $image_src[0];
 357                  }
 358  
 359                  $full_src = wp_get_attachment_image_src( $post->ID, 'full' );
 360  
 361                  if ( ! empty( $full_src ) ) {
 362                      $data['media_details']['sizes']['full'] = array(
 363                          'file'       => wp_basename( $full_src[0] ),
 364                          'width'      => $full_src[1],
 365                          'height'     => $full_src[2],
 366                          'mime_type'  => $post->post_mime_type,
 367                          'source_url' => $full_src[0],
 368                      );
 369                  }
 370              } else {
 371                  $data['media_details']['sizes'] = new stdClass;
 372              }
 373          }
 374  
 375          if ( in_array( 'post', $fields, true ) ) {
 376              $data['post'] = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
 377          }
 378  
 379          if ( in_array( 'source_url', $fields, true ) ) {
 380              $data['source_url'] = wp_get_attachment_url( $post->ID );
 381          }
 382  
 383          $context = ! empty( $request['context'] ) ? $request['context'] : 'view';
 384  
 385          $data = $this->filter_response_by_context( $data, $context );
 386  
 387          $links = $response->get_links();
 388  
 389          // Wrap the data in a response object.
 390          $response = rest_ensure_response( $data );
 391  
 392          foreach ( $links as $rel => $rel_links ) {
 393              foreach ( $rel_links as $link ) {
 394                  $response->add_link( $rel, $link['href'], $link['attributes'] );
 395              }
 396          }
 397  
 398          /**
 399           * Filters an attachment returned from the REST API.
 400           *
 401           * Allows modification of the attachment right before it is returned.
 402           *
 403           * @since 4.7.0
 404           *
 405           * @param WP_REST_Response $response The response object.
 406           * @param WP_Post          $post     The original attachment post.
 407           * @param WP_REST_Request  $request  Request used to generate the response.
 408           */
 409          return apply_filters( 'rest_prepare_attachment', $response, $post, $request );
 410      }
 411  
 412      /**
 413       * Retrieves the attachment's schema, conforming to JSON Schema.
 414       *
 415       * @since 4.7.0
 416       *
 417       * @return array Item schema as an array.
 418       */
 419  	public function get_item_schema() {
 420  
 421          $schema = parent::get_item_schema();
 422  
 423          $schema['properties']['alt_text'] = array(
 424              'description' => __( 'Alternative text to display when attachment is not displayed.' ),
 425              'type'        => 'string',
 426              'context'     => array( 'view', 'edit', 'embed' ),
 427              'arg_options' => array(
 428                  'sanitize_callback' => 'sanitize_text_field',
 429              ),
 430          );
 431  
 432          $schema['properties']['caption'] = array(
 433              'description' => __( 'The attachment caption.' ),
 434              'type'        => 'object',
 435              'context'     => array( 'view', 'edit', 'embed' ),
 436              'arg_options' => array(
 437                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
 438                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
 439              ),
 440              'properties'  => array(
 441                  'raw'      => array(
 442                      'description' => __( 'Caption for the attachment, as it exists in the database.' ),
 443                      'type'        => 'string',
 444                      'context'     => array( 'edit' ),
 445                  ),
 446                  'rendered' => array(
 447                      'description' => __( 'HTML caption for the attachment, transformed for display.' ),
 448                      'type'        => 'string',
 449                      'context'     => array( 'view', 'edit', 'embed' ),
 450                      'readonly'    => true,
 451                  ),
 452              ),
 453          );
 454  
 455          $schema['properties']['description'] = array(
 456              'description' => __( 'The attachment description.' ),
 457              'type'        => 'object',
 458              'context'     => array( 'view', 'edit' ),
 459              'arg_options' => array(
 460                  'sanitize_callback' => null, // Note: sanitization implemented in self::prepare_item_for_database()
 461                  'validate_callback' => null, // Note: validation implemented in self::prepare_item_for_database()
 462              ),
 463              'properties'  => array(
 464                  'raw'      => array(
 465                      'description' => __( 'Description for the object, as it exists in the database.' ),
 466                      'type'        => 'string',
 467                      'context'     => array( 'edit' ),
 468                  ),
 469                  'rendered' => array(
 470                      'description' => __( 'HTML description for the object, transformed for display.' ),
 471                      'type'        => 'string',
 472                      'context'     => array( 'view', 'edit' ),
 473                      'readonly'    => true,
 474                  ),
 475              ),
 476          );
 477  
 478          $schema['properties']['media_type'] = array(
 479              'description' => __( 'Attachment type.' ),
 480              'type'        => 'string',
 481              'enum'        => array( 'image', 'file' ),
 482              'context'     => array( 'view', 'edit', 'embed' ),
 483              'readonly'    => true,
 484          );
 485  
 486          $schema['properties']['mime_type'] = array(
 487              'description' => __( 'The attachment MIME type.' ),
 488              'type'        => 'string',
 489              'context'     => array( 'view', 'edit', 'embed' ),
 490              'readonly'    => true,
 491          );
 492  
 493          $schema['properties']['media_details'] = array(
 494              'description' => __( 'Details about the media file, specific to its type.' ),
 495              'type'        => 'object',
 496              'context'     => array( 'view', 'edit', 'embed' ),
 497              'readonly'    => true,
 498          );
 499  
 500          $schema['properties']['post'] = array(
 501              'description' => __( 'The ID for the associated post of the attachment.' ),
 502              'type'        => 'integer',
 503              'context'     => array( 'view', 'edit' ),
 504          );
 505  
 506          $schema['properties']['source_url'] = array(
 507              'description' => __( 'URL to the original attachment file.' ),
 508              'type'        => 'string',
 509              'format'      => 'uri',
 510              'context'     => array( 'view', 'edit', 'embed' ),
 511              'readonly'    => true,
 512          );
 513  
 514          unset( $schema['properties']['password'] );
 515  
 516          return $schema;
 517      }
 518  
 519      /**
 520       * Handles an upload via raw POST data.
 521       *
 522       * @since 4.7.0
 523       *
 524       * @param array $data    Supplied file data.
 525       * @param array $headers HTTP headers from the request.
 526       * @return array|WP_Error Data from wp_handle_sideload().
 527       */
 528  	protected function upload_from_data( $data, $headers ) {
 529          if ( empty( $data ) ) {
 530              return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
 531          }
 532  
 533          if ( empty( $headers['content_type'] ) ) {
 534              return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied.' ), array( 'status' => 400 ) );
 535          }
 536  
 537          if ( empty( $headers['content_disposition'] ) ) {
 538              return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied.' ), array( 'status' => 400 ) );
 539          }
 540  
 541          $filename = self::get_filename_from_disposition( $headers['content_disposition'] );
 542  
 543          if ( empty( $filename ) ) {
 544              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 ) );
 545          }
 546  
 547          if ( ! empty( $headers['content_md5'] ) ) {
 548              $content_md5 = array_shift( $headers['content_md5'] );
 549              $expected    = trim( $content_md5 );
 550              $actual      = md5( $data );
 551  
 552              if ( $expected !== $actual ) {
 553                  return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
 554              }
 555          }
 556  
 557          // Get the content-type.
 558          $type = array_shift( $headers['content_type'] );
 559  
 560          /** Include admin functions to get access to wp_tempnam() and wp_handle_sideload(). */
 561          require_once  ABSPATH . 'wp-admin/includes/file.php';
 562  
 563          // Save the file.
 564          $tmpfname = wp_tempnam( $filename );
 565  
 566          $fp = fopen( $tmpfname, 'w+' );
 567  
 568          if ( ! $fp ) {
 569              return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle.' ), array( 'status' => 500 ) );
 570          }
 571  
 572          fwrite( $fp, $data );
 573          fclose( $fp );
 574  
 575          // Now, sideload it in.
 576          $file_data = array(
 577              'error'    => null,
 578              'tmp_name' => $tmpfname,
 579              'name'     => $filename,
 580              'type'     => $type,
 581          );
 582  
 583          $size_check = self::check_upload_size( $file_data );
 584          if ( is_wp_error( $size_check ) ) {
 585              return $size_check;
 586          }
 587  
 588          $overrides = array(
 589              'test_form' => false,
 590          );
 591  
 592          $sideloaded = wp_handle_sideload( $file_data, $overrides );
 593  
 594          if ( isset( $sideloaded['error'] ) ) {
 595              @unlink( $tmpfname );
 596  
 597              return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
 598          }
 599  
 600          return $sideloaded;
 601      }
 602  
 603      /**
 604       * Parses filename from a Content-Disposition header value.
 605       *
 606       * As per RFC6266:
 607       *
 608       *     content-disposition = "Content-Disposition" ":"
 609       *                            disposition-type *( ";" disposition-parm )
 610       *
 611       *     disposition-type    = "inline" | "attachment" | disp-ext-type
 612       *                         ; case-insensitive
 613       *     disp-ext-type       = token
 614       *
 615       *     disposition-parm    = filename-parm | disp-ext-parm
 616       *
 617       *     filename-parm       = "filename" "=" value
 618       *                         | "filename*" "=" ext-value
 619       *
 620       *     disp-ext-parm       = token "=" value
 621       *                         | ext-token "=" ext-value
 622       *     ext-token           = <the characters in token, followed by "*">
 623       *
 624       * @since 4.7.0
 625       *
 626       * @link http://tools.ietf.org/html/rfc2388
 627       * @link http://tools.ietf.org/html/rfc6266
 628       *
 629       * @param string[] $disposition_header List of Content-Disposition header values.
 630       * @return string|null Filename if available, or null if not found.
 631       */
 632  	public static function get_filename_from_disposition( $disposition_header ) {
 633          // Get the filename.
 634          $filename = null;
 635  
 636          foreach ( $disposition_header as $value ) {
 637              $value = trim( $value );
 638  
 639              if ( strpos( $value, ';' ) === false ) {
 640                  continue;
 641              }
 642  
 643              list( $type, $attr_parts ) = explode( ';', $value, 2 );
 644  
 645              $attr_parts = explode( ';', $attr_parts );
 646              $attributes = array();
 647  
 648              foreach ( $attr_parts as $part ) {
 649                  if ( strpos( $part, '=' ) === false ) {
 650                      continue;
 651                  }
 652  
 653                  list( $key, $value ) = explode( '=', $part, 2 );
 654  
 655                  $attributes[ trim( $key ) ] = trim( $value );
 656              }
 657  
 658              if ( empty( $attributes['filename'] ) ) {
 659                  continue;
 660              }
 661  
 662              $filename = trim( $attributes['filename'] );
 663  
 664              // Unquote quoted filename, but after trimming.
 665              if ( substr( $filename, 0, 1 ) === '"' && substr( $filename, -1, 1 ) === '"' ) {
 666                  $filename = substr( $filename, 1, -1 );
 667              }
 668          }
 669  
 670          return $filename;
 671      }
 672  
 673      /**
 674       * Retrieves the query params for collections of attachments.
 675       *
 676       * @since 4.7.0
 677       *
 678       * @return array Query parameters for the attachment collection as an array.
 679       */
 680  	public function get_collection_params() {
 681          $params                            = parent::get_collection_params();
 682          $params['status']['default']       = 'inherit';
 683          $params['status']['items']['enum'] = array( 'inherit', 'private', 'trash' );
 684          $media_types                       = $this->get_media_types();
 685  
 686          $params['media_type'] = array(
 687              'default'     => null,
 688              'description' => __( 'Limit result set to attachments of a particular media type.' ),
 689              'type'        => 'string',
 690              'enum'        => array_keys( $media_types ),
 691          );
 692  
 693          $params['mime_type'] = array(
 694              'default'     => null,
 695              'description' => __( 'Limit result set to attachments of a particular MIME type.' ),
 696              'type'        => 'string',
 697          );
 698  
 699          return $params;
 700      }
 701  
 702      /**
 703       * Handles an upload via multipart/form-data ($_FILES).
 704       *
 705       * @since 4.7.0
 706       *
 707       * @param array $files   Data from the `$_FILES` superglobal.
 708       * @param array $headers HTTP headers from the request.
 709       * @return array|WP_Error Data from wp_handle_upload().
 710       */
 711  	protected function upload_from_file( $files, $headers ) {
 712          if ( empty( $files ) ) {
 713              return new WP_Error( 'rest_upload_no_data', __( 'No data supplied.' ), array( 'status' => 400 ) );
 714          }
 715  
 716          // Verify hash, if given.
 717          if ( ! empty( $headers['content_md5'] ) ) {
 718              $content_md5 = array_shift( $headers['content_md5'] );
 719              $expected    = trim( $content_md5 );
 720              $actual      = md5_file( $files['file']['tmp_name'] );
 721  
 722              if ( $expected !== $actual ) {
 723                  return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected.' ), array( 'status' => 412 ) );
 724              }
 725          }
 726  
 727          // Pass off to WP to handle the actual upload.
 728          $overrides = array(
 729              'test_form' => false,
 730          );
 731  
 732          // Bypasses is_uploaded_file() when running unit tests.
 733          if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
 734              $overrides['action'] = 'wp_handle_mock_upload';
 735          }
 736  
 737          $size_check = self::check_upload_size( $files['file'] );
 738          if ( is_wp_error( $size_check ) ) {
 739              return $size_check;
 740          }
 741  
 742          /** Include admin function to get access to wp_handle_upload(). */
 743          require_once  ABSPATH . 'wp-admin/includes/file.php';
 744  
 745          $file = wp_handle_upload( $files['file'], $overrides );
 746  
 747          if ( isset( $file['error'] ) ) {
 748              return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
 749          }
 750  
 751          return $file;
 752      }
 753  
 754      /**
 755       * Retrieves the supported media types.
 756       *
 757       * Media types are considered the MIME type category.
 758       *
 759       * @since 4.7.0
 760       *
 761       * @return array Array of supported media types.
 762       */
 763  	protected function get_media_types() {
 764          $media_types = array();
 765  
 766          foreach ( get_allowed_mime_types() as $mime_type ) {
 767              $parts = explode( '/', $mime_type );
 768  
 769              if ( ! isset( $media_types[ $parts[0] ] ) ) {
 770                  $media_types[ $parts[0] ] = array();
 771              }
 772  
 773              $media_types[ $parts[0] ][] = $mime_type;
 774          }
 775  
 776          return $media_types;
 777      }
 778  
 779      /**
 780       * Determine if uploaded file exceeds space quota on multisite.
 781       *
 782       * Replicates check_upload_size().
 783       *
 784       * @since 4.9.8
 785       *
 786       * @param array $file $_FILES array for a given file.
 787       * @return true|WP_Error True if can upload, error for errors.
 788       */
 789  	protected function check_upload_size( $file ) {
 790          if ( ! is_multisite() ) {
 791              return true;
 792          }
 793  
 794          if ( get_site_option( 'upload_space_check_disabled' ) ) {
 795              return true;
 796          }
 797  
 798          $space_left = get_upload_space_available();
 799  
 800          $file_size = filesize( $file['tmp_name'] );
 801          if ( $space_left < $file_size ) {
 802              /* translators: %s: required disk space in kilobytes */
 803              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 ) );
 804          }
 805  
 806          if ( $file_size > ( KB_IN_BYTES * get_site_option( 'fileupload_maxk', 1500 ) ) ) {
 807              /* translators: %s: maximum allowed file size in kilobytes */
 808              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 ) );
 809          }
 810  
 811          // Include admin function to get access to upload_is_user_over_quota().
 812          require_once  ABSPATH . 'wp-admin/includes/ms.php';
 813  
 814          if ( upload_is_user_over_quota( false ) ) {
 815              return new WP_Error( 'rest_upload_user_quota_exceeded', __( 'You have used your space quota. Please delete files before uploading.' ), array( 'status' => 400 ) );
 816          }
 817          return true;
 818      }
 819  
 820  }


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7