<?php

class WP_REST_Attachments_Controller extends WP_REST_Posts_Controller {

	/**
	 * Create a single attachment
	 *
	 * @param WP_REST_Request $request Full details about the request
	 * @return WP_Error|WP_REST_Response
	 */
	public function create_item( $request ) {

		// Permissions check - Note: "upload_files" cap is returned for an attachment by $post_type_obj->cap->create_posts
		$post_type_obj = get_post_type_object( $this->post_type );
		if ( ! current_user_can( $post_type_obj->cap->create_posts ) || ! current_user_can( $post_type_obj->cap->edit_posts ) ) {
			return new WP_Error( 'rest_cannot_create', __( 'Sorry, you are not allowed to post on this site.' ), array( 'status' => 400 ) );
		}

		// If a user is trying to attach to a post make sure they have permissions. Bail early if post_id is not being passed
		if ( ! empty( $request['post'] ) ) {
			$parent = get_post( (int) $request['post'] );
			$post_parent_type = get_post_type_object( $parent->post_type );
			if ( ! current_user_can( $post_parent_type->cap->edit_post, $request['post'] ) ) {
				return new WP_Error( 'rest_cannot_edit', __( 'Sorry, you are not allowed to edit this post.' ), array( 'status' => 401 ) );
			}
		}

		// Get the file via $_FILES or raw data
		$files = $request->get_file_params();
		$headers = $request->get_headers();
		if ( ! empty( $files ) ) {
			$file = $this->upload_from_file( $files, $headers );
		} else {
			$file = $this->upload_from_data( $request->get_body(), $headers );
		}

		if ( is_wp_error( $file ) ) {
			return $file;
		}

		$name       = basename( $file['file'] );
		$name_parts = pathinfo( $name );
		$name       = trim( substr( $name, 0, -(1 + strlen( $name_parts['extension'] ) ) ) );

		$url     = $file['url'];
		$type    = $file['type'];
		$file    = $file['file'];
		$title   = $name;
		$caption = '';

		// use image exif/iptc data for title and caption defaults if possible
		// @codingStandardsIgnoreStart
		$image_meta = @wp_read_image_metadata( $file );
		// @codingStandardsIgnoreEnd
		if ( ! empty( $image_meta ) ) {
			if ( empty( $request['title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
				$title = $image_meta['title'];
			}

			if ( empty( $request['caption'] ) && trim( $image_meta['caption'] ) ) {
				$caption = $image_meta['caption'];
			}
		}

		$attachment = $this->prepare_item_for_database( $request );
		$attachment->file = $file;
		$attachment->post_mime_type = $type;
		$attachment->guid = $url;
		$id = wp_insert_post( $attachment, true );
		if ( is_wp_error( $id ) ) {
			return $id;
		}

		/** Include admin functions to get access to wp_generate_attachment_metadata() */
		require_once ABSPATH . 'wp-admin/includes/admin.php';

		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );

		if ( isset( $request['alt_text'] ) ) {
			update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $request['alt_text'] ) );
		}

		$this->update_additional_fields_for_object( $attachment, $request );

		$response = $this->get_item( array(
			'id'      => $id,
			'context' => 'edit',
		) );
		$response = rest_ensure_response( $response );
		$response->set_status( 201 );
		$response->header( 'Location', rest_url( '/wp/v2/' . $this->get_post_type_base( $attachment->post_type ) . '/' . $id ) );

		/**
		 * Fires after a single attachment is created or updated via the REST API.
		 *
		 * @param object          $attachment Inserted attachment.
		 * @param WP_REST_Request $request    The request sent to the API.
		 * @param bool            $creating   True when creating an attachment, false when updating.
		 */
		do_action( 'rest_insert_attachment', $attachment, $request, true );

		return $response;

	}

	/**
	 * Update a single post
	 *
	 * @param WP_REST_Request $request Full details about the request
	 * @return WP_Error|WP_REST_Response
	 */
	public function update_item( $request ) {
		$response = parent::update_item( $request );
		if ( is_wp_error( $response ) ) {
			return $response;
		}

		$response = rest_ensure_response( $response );
		$data = $response->get_data();

		if ( isset( $request['alt_text'] ) ) {
			update_post_meta( $data['id'], '_wp_attachment_image_alt', $request['alt_text'] );
		}

		$response = $this->get_item( array(
			'id'      => $data['id'],
			'context' => 'edit',
		));

		/* This action is documented in lib/endpoints/class-wp-rest-attachments-controller.php */
		do_action( 'rest_insert_attachment', $data, $request, false );

		return rest_ensure_response( $response );
	}

	/**
	 * Prepare a single attachment for create or update
	 *
	 * @param WP_REST_Request $request Request object
	 * @return WP_Error|obj $prepared_attachment Post object
	 */
	protected function prepare_item_for_database( $request ) {
		$prepared_attachment = parent::prepare_item_for_database( $request );

		if ( isset( $request['caption'] ) ) {
			$prepared_attachment->post_excerpt = $request['caption'];
		}

		if ( isset( $request['description'] ) ) {
			$prepared_attachment->post_content = $request['description'];
		}

		if ( isset( $request['post'] ) ) {
			$prepared_attachment->post_parent = (int) $request['post'];
		}

		return $prepared_attachment;
	}

	/**
	 * Prepare a single attachment output for response
	 *
	 * @param WP_Post $post Post object
	 * @param WP_REST_Request $request Request object
	 * @return array $response
	 */
	public function prepare_item_for_response( $post, $request ) {
		$response = parent::prepare_item_for_response( $post, $request );
		$data = $response->get_data();

		$data['alt_text']      = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
		$data['caption']       = $post->post_excerpt;
		$data['description']   = $post->post_content;
		$data['media_type']    = wp_attachment_is_image( $post->ID ) ? 'image' : 'file';
		$data['media_details'] = wp_get_attachment_metadata( $post->ID );
		$data['post']          = ! empty( $post->post_parent ) ? (int) $post->post_parent : null;
		$data['source_url']    = wp_get_attachment_url( $post->ID );

		// Ensure empty details is an empty object
		if ( empty( $data['media_details'] ) ) {
			$data['media_details'] = new stdClass;
		} elseif ( ! empty( $data['media_details']['sizes'] ) ) {
			$img_url_basename = wp_basename( $data['source_url'] );

			foreach ( $data['media_details']['sizes'] as $size => &$size_data ) {
				// Use the same method image_downsize() does
				$image_src = wp_get_attachment_image_src( $post->ID, $size );

				if ( ! $image_src ) {
					continue;
				}

				$size_data['source_url'] = $image_src[0];
			}
		} else {
			$data['media_details']['sizes'] = new stdClass;
		}

		$context = ! empty( $request['context'] ) ? $request['context'] : 'view';

		$data = $this->filter_response_by_context( $data, $context );

		// Wrap the data in a response object
		$data = rest_ensure_response( $data );

		$data->add_links( $this->prepare_links( $post ) );

		/**
		 * Filter an attachment returned from the API.
		 *
		 * Allows modification of the attachment right before it is returned.
		 *
		 * @param array           $data     Key value array of attachment data: alt_text, caption, description,
		 *                                  media_type, media_details, post, source_url. Piossibly media_details.
		 * @param WP_Post         $post     The attachment post.
		 * @param WP_REST_Request $request  Request used to generate the response.
		 */
		return apply_filters( 'rest_prepare_attachment', $data, $post, $request );
	}

	/**
	 * Get the Attachment's schema, conforming to JSON Schema
	 *
	 * @return array
	 */
	public function get_item_schema() {

		$schema = parent::get_item_schema();

		$schema['properties']['alt_text'] = array(
			'description'     => 'Alternative text to display when attachment is not displayed.',
			'type'            => 'string',
			'context'         => array( 'view', 'edit', 'embed' ),
			'arg_options'     => array(
				'sanitize_callback' => 'sanitize_text_field',
			),
			);
		$schema['properties']['caption'] = array(
			'description'     => 'The caption for the attachment.',
			'type'            => 'string',
			'context'         => array( 'view', 'edit' ),
			'arg_options'     => array(
				'sanitize_callback' => 'wp_filter_post_kses',
			),
			);
		$schema['properties']['description'] = array(
			'description'     => 'The description for the attachment.',
			'type'            => 'string',
			'context'         => array( 'view', 'edit' ),
			'arg_options'     => array(
				'sanitize_callback' => 'wp_filter_post_kses',
			),
			);
		$schema['properties']['media_type'] = array(
			'description'     => 'Type of attachment.',
			'type'            => 'string',
			'enum'            => array( 'image', 'file' ),
			'context'         => array( 'view', 'edit', 'embed' ),
			'readonly'        => true,
			);
		$schema['properties']['media_details'] = array(
			'description'     => 'Details about the attachment file, specific to its type.',
			'type'            => 'object',
			'context'         => array( 'view', 'edit', 'embed' ),
			'readonly'        => true,
			);
		$schema['properties']['post'] = array(
			'description'     => 'The ID for the associated post of the attachment.',
			'type'            => 'integer',
			'context'         => array( 'view', 'edit' ),
			);
		$schema['properties']['source_url'] = array(
			'description'     => 'URL to the original attachment file.',
			'type'            => 'string',
			'format'          => 'uri',
			'context'         => array( 'view', 'edit', 'embed' ),
			'readonly'        => true,
			);
		return $schema;
	}

	/**
	 * Handle an upload via raw POST data
	 *
	 * @param array $data Supplied file data
	 * @param array $headers HTTP headers from the request
	 * @return array|WP_Error Data from {@see wp_handle_sideload()}
	 */
	protected function upload_from_data( $data, $headers ) {
		if ( empty( $data ) ) {
			return new WP_Error( 'rest_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
		}

		if ( empty( $headers['content_type'] ) ) {
			return new WP_Error( 'rest_upload_no_content_type', __( 'No Content-Type supplied' ), array( 'status' => 400 ) );
		}

		if ( empty( $headers['content_disposition'] ) ) {
			return new WP_Error( 'rest_upload_no_content_disposition', __( 'No Content-Disposition supplied' ), array( 'status' => 400 ) );
		}

		// Get the filename
		$filename = null;

		foreach ( $headers['content_disposition'] as $part ) {
			$part = trim( $part );

			if ( strpos( $part, 'filename' ) !== 0 ) {
				continue;
			}

			$filenameparts = explode( '=', $part );
			$filename      = trim( $filenameparts[1] );
		}

		if ( empty( $filename ) ) {
			return new WP_Error( 'rest_upload_invalid_disposition', __( 'Invalid Content-Disposition supplied. Content-Disposition needs to be formatted as "filename=image.png" or similar.' ), array( 'status' => 400 ) );
		}

		if ( ! empty( $headers['content_md5'] ) ) {
			$content_md5 = array_shift( $headers['content_md5'] );
			$expected = trim( $content_md5 );
			$actual   = md5( $data );

			if ( $expected !== $actual ) {
				return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected' ), array( 'status' => 412 ) );
			}
		}

		// Get the content-type
		$type = array_shift( $headers['content_type'] );

		// Save the file
		$tmpfname = wp_tempnam( $filename );

		$fp = fopen( $tmpfname, 'w+' );

		if ( ! $fp ) {
			return new WP_Error( 'rest_upload_file_error', __( 'Could not open file handle' ), array( 'status' => 500 ) );
		}

		fwrite( $fp, $data );
		fclose( $fp );

		// Now, sideload it in
		$file_data = array(
			'error'    => null,
			'tmp_name' => $tmpfname,
			'name'     => $filename,
			'type'     => $type,
		);
		$overrides = array(
			'test_form' => false,
		);
		$sideloaded = wp_handle_sideload( $file_data, $overrides );

		if ( isset( $sideloaded['error'] ) ) {
			// @codingStandardsIgnoreStart
			@unlink( $tmpfname );
			// @codingStandardsIgnoreEnd
			return new WP_Error( 'rest_upload_sideload_error', $sideloaded['error'], array( 'status' => 500 ) );
		}

		return $sideloaded;
	}

	/**
	 * Handle an upload via multipart/form-data ($_FILES)
	 *
	 * @param array $files Data from $_FILES
	 * @param array $headers HTTP headers from the request
	 * @return array|WP_Error Data from {@see wp_handle_upload()}
	 */
	protected function upload_from_file( $files, $headers ) {
		if ( empty( $files ) ) {
			return new WP_Error( 'rest_upload_no_data', __( 'No data supplied' ), array( 'status' => 400 ) );
		}

		// Verify hash, if given
		if ( ! empty( $headers['content_md5'] ) ) {
			$content_md5 = array_shift( $headers['content_md5'] );
			$expected = trim( $content_md5 );
			$actual = md5_file( $files['file']['tmp_name'] );
			if ( $expected !== $actual ) {
				return new WP_Error( 'rest_upload_hash_mismatch', __( 'Content hash did not match expected' ), array( 'status' => 412 ) );
			}
		}

		// Pass off to WP to handle the actual upload
		$overrides = array(
			'test_form'   => false,
		);
		// Bypasses is_uploaded_file() when running unit tests
		if ( defined( 'DIR_TESTDATA' ) && DIR_TESTDATA ) {
			$overrides['action'] = 'wp_handle_mock_upload';
		}

		/** Include admin functions to get access to wp_handle_upload() */
		require_once ABSPATH . 'wp-admin/includes/admin.php';
		$file = wp_handle_upload( $files['file'], $overrides );

		if ( isset( $file['error'] ) ) {
			return new WP_Error( 'rest_upload_unknown_error', $file['error'], array( 'status' => 500 ) );
		}

		return $file;
	}

}
