diff --git a/src/wp-admin/includes/file.php b/src/wp-admin/includes/file.php index 79a08bb2b9cba..6ffdeea8ea78d 100644 --- a/src/wp-admin/includes/file.php +++ b/src/wp-admin/includes/file.php @@ -1356,6 +1356,87 @@ function download_url( $url, $timeout = 300, $signature_verification = false ) { return $tmpfname; } +/** + * Downloads an image from a URL to a temporary file. + * + * The URL is checked before anything is requested: it must name a file whose extension + * maps to an allowed image type, and it must pass wp_http_validate_url(). The only + * request is made by download_url(), and its response is limited to the maximum upload + * size plus one byte, so an oversized file is never written to disk in full and still + * fails a check against wp_max_upload_size(). + * + * The caller checks the size and the content of the downloaded file, and deletes the + * temporary file once it is done with it. + * + * @todo Use this function in WP_REST_Attachments_Controller::upload_from_url() as well. + * + * @since 7.3.0 + * @access private + * + * @param string $url The URL of the image. + * @return array|WP_Error { + * The downloaded file, or a WP_Error when the URL is refused (`invalid_image_url`) + * or the download fails (the error of download_url()). + * + * @type string $name The file name, taken from the path of the URL as it is. + * @type string $tmp_name The path of the temporary file. + * } + */ +function _wp_download_image_from_url( $url ) { + $invalid_url = __( 'Invalid URL. Provide a valid, publicly reachable HTTP or HTTPS image URL.' ); + if ( ! is_string( $url ) || '' === $url ) { + return new WP_Error( 'invalid_image_url', $invalid_url, array( 'status' => 400 ) ); + } + + // The name is taken from the URL's path as it is, without percent-decoding. + $filename = wp_basename( (string) wp_parse_url( $url, PHP_URL_PATH ) ); + if ( '' === $filename ) { + return new WP_Error( 'invalid_image_url', __( 'Could not determine a filename from the provided URL.' ), array( 'status' => 400 ) ); + } + + $filetype = wp_check_filetype( $filename ); + if ( ! $filetype['type'] || ! str_starts_with( $filetype['type'], 'image/' ) ) { + return new WP_Error( 'invalid_image_url', __( 'Only images can be uploaded from a URL.' ), array( 'status' => 400 ) ); + } + + if ( false === wp_http_validate_url( $url ) ) { + return new WP_Error( 'invalid_image_url', $invalid_url, array( 'status' => 400 ) ); + } + + /* + * One byte over the maximum is enough to fail a size check, so an oversized file is + * never written to disk in full. The limit applies to requests for this URL only and + * is removed again whatever the download gives. + */ + $max_size = (int) wp_max_upload_size(); + $limit_response_size = static function ( $args, $request_url ) use ( $url, $max_size ) { + if ( $request_url === $url ) { + $args['limit_response_size'] = $max_size + 1; + } + + return $args; + }; + + if ( $max_size > 0 ) { + add_filter( 'http_request_args', $limit_response_size, PHP_INT_MAX, 2 ); + } + + try { + $tmp_file = download_url( $url ); + } finally { + remove_filter( 'http_request_args', $limit_response_size, PHP_INT_MAX ); + } + + if ( is_wp_error( $tmp_file ) ) { + return $tmp_file; + } + + return array( + 'name' => $filename, + 'tmp_name' => $tmp_file, + ); +} + /** * Calculates and compares the MD5 of a file to its expected value. * diff --git a/src/wp-includes/abilities.php b/src/wp-includes/abilities.php index 835c19e04f949..1d4f0eda541b5 100644 --- a/src/wp-includes/abilities.php +++ b/src/wp-includes/abilities.php @@ -10,6 +10,7 @@ declare( strict_types = 1 ); require_once __DIR__ . '/abilities/class-wp-abilities-content.php'; +require_once __DIR__ . '/abilities/class-wp-abilities-media.php'; require_once __DIR__ . '/abilities/class-wp-abilities-settings.php'; require_once __DIR__ . '/abilities/class-wp-abilities-users.php'; @@ -50,6 +51,7 @@ function wp_register_core_ability_categories(): void { * * @since 6.9.0 * @since 7.2.0 Added the `core/content-query`, `core/settings-get`, and `core/users-query` abilities. + * @since 7.3.0 Added the `core/media-query`, `core/media-upload`, `core/media-update`, and `core/media-delete` abilities. * * @global wpdb $wpdb WordPress database abstraction object. */ @@ -379,4 +381,7 @@ function wp_register_core_abilities(): void { // Register the content abilities (currently the read-only `core/content-query`). ( new WP_Abilities_Content() )->register(); + + // Register the media abilities. + ( new WP_Abilities_Media() )->register(); } diff --git a/src/wp-includes/abilities/class-wp-abilities-content.php b/src/wp-includes/abilities/class-wp-abilities-content.php index a8d9954e30965..21916099a8516 100644 --- a/src/wp-includes/abilities/class-wp-abilities-content.php +++ b/src/wp-includes/abilities/class-wp-abilities-content.php @@ -124,18 +124,18 @@ public function register(): void { private function register_content_query(): void { /* * Post types must be registered with `show_in_abilities` before the ability is - * registered so they are included in its input schema. + * registered so they are included in its input schema. Attachments are exposed + * through the media abilities instead. */ - $post_types = array_values( get_post_types( array( 'show_in_abilities' => true ) ) ); + $post_types = $this->get_exposed_post_types(); if ( empty( $post_types ) ) { return; } /* * Internal statuses (e.g. `inherit`) are excluded here and from the statuses a query - * covers by default, so the posts of post types that rely on them (attachments) - * cannot be queried, not even by ID. Revisit if such a post type is ever exposed via - * `show_in_abilities`. + * covers by default, so the posts of post types that rely on them cannot be queried, + * not even by ID. */ $statuses = array_values( get_post_stati( array( 'internal' => false ) ) ); @@ -824,9 +824,20 @@ private function is_field_requested( string $path, array $fields ): bool { * @return WP_Post_Type|null The post type object, or null when the post type is not exposed. */ private function get_exposed_post_type( $post_type ): ?WP_Post_Type { - $post_type_object = is_string( $post_type ) ? get_post_type_object( $post_type ) : null; + return is_string( $post_type ) && in_array( $post_type, $this->get_exposed_post_types(), true ) ? get_post_type_object( $post_type ) : null; + } - return empty( $post_type_object->show_in_abilities ) ? null : $post_type_object; + /** + * Returns the names of the post types exposed through the Abilities API. + * + * Attachments are never exposed: the media abilities handle them. + * + * @since 7.3.0 + * + * @return list The post type names. + */ + private function get_exposed_post_types(): array { + return array_values( array_diff( get_post_types( array( 'show_in_abilities' => true ) ), array( 'attachment' ) ) ); } /** @@ -1362,7 +1373,7 @@ private function get_visible_author( int $user_id ): ?WP_User { } if ( ! isset( $this->visible_authors[ $user_id ] ) ) { - $post_types = array_values( array_filter( get_post_types( array( 'show_in_abilities' => true ), 'names' ), 'is_post_type_viewable' ) ); + $post_types = array_values( array_filter( $this->get_exposed_post_types(), 'is_post_type_viewable' ) ); $this->visible_authors[ $user_id ] = (int) count_user_posts( $user_id, $post_types ) > 0; } diff --git a/src/wp-includes/abilities/class-wp-abilities-media.php b/src/wp-includes/abilities/class-wp-abilities-media.php new file mode 100644 index 0000000000000..5936741cbd342 --- /dev/null +++ b/src/wp-includes/abilities/class-wp-abilities-media.php @@ -0,0 +1,2232 @@ +execute()`, which validates the input and + * checks permissions before running them. + * + * @since 7.3.0 + * + * @access private + */ +final class WP_Abilities_Media { + + /** + * The ability category used for media abilities. + * + * @since 7.3.0 + * @var string + */ + private const CATEGORY = 'content'; + + /** + * Default number of attachments returned per page, unless `where` lists them by ID or slug. + * + * @since 7.3.0 + * @var int + */ + private const DEFAULT_PER_PAGE = 10; + + /** + * Maximum number of attachments returned per page. + * + * @since 7.3.0 + * @var int + */ + private const MAX_PER_PAGE = 100; + + /** + * The statuses an attachment query can filter by. + * + * @since 7.3.0 + * @var list + */ + private const STATUSES = array( 'inherit', 'private', 'trash' ); + + /** + * The media type groups the `media_type` filter accepts. + * + * @since 7.3.0 + * @var list + */ + private const MEDIA_TYPES = array( 'application', 'audio', 'image', 'text', 'video' ); + + /** + * Default field paths returned when the caller does not request a field subset. + * + * @since 7.3.0 + * @var list + */ + private const DEFAULT_FIELDS = array( 'id', 'status', 'date', 'slug', 'title.rendered', 'media_type', 'mime_type', 'source_url' ); + + /** + * Globals that rendering a post changes: the global post and the globals that + * setup_postdata() populates. + * + * @since 7.3.0 + * @var list + */ + private const LOOP_GLOBALS = array( 'post', 'id', 'authordata', 'currentday', 'currentmonth', 'page', 'pages', 'multipage', 'more', 'numpages' ); + + /** + * Whether each author seen in the current call has posts the current user may read. + * + * @since 7.3.0 + * @var array + */ + private $visible_authors = array(); + + /** + * Registers all media abilities. + * + * Must run on the `wp_abilities_api_init` hook. + * + * @since 7.3.0 + */ + public function register(): void { + $item_schema = $this->get_item_schema(); + $fields_schema = $this->get_fields_input_schema( $item_schema['properties'] ); + + wp_register_ability( + 'core/media-query', + array( + 'label' => __( 'Query Media' ), + 'description' => __( 'Retrieves a paginated list of the media attachments the current user can read, filtered by any of IDs, slugs, status, media type, MIME type, parent post, and author. Requires an authenticated user. Filters are exact-match only; the ability does not perform full-text search.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_query_input_schema( $fields_schema ), + 'output_schema' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'items', 'pagination' ), + 'properties' => array( + 'items' => array( + 'type' => 'array', + 'items' => $item_schema, + 'description' => __( 'The readable attachments on the requested page, newest first. Can hold fewer attachments than `per_page`, because the totals can count matching attachments the current user cannot read.' ), + ), + 'pagination' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'total', 'total_pages' ), + 'properties' => array( + 'total' => array( + 'type' => 'integer', + 'description' => __( 'Total number of attachments matching the query, across all pages.' ), + ), + 'total_pages' => array( + 'type' => 'integer', + 'description' => __( 'Total number of pages for the query.' ), + ), + ), + 'description' => __( 'The totals of the query, across all pages.' ), + ), + ), + ), + 'execute_callback' => function ( $input = array() ) { + return $this->execute_media_query( $input ); + }, + 'permission_callback' => function ( $input = array() ): bool { + return $this->can_use_media(); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => true, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + + wp_register_ability( + 'core/media-upload', + array( + 'label' => __( 'Upload Media' ), + 'description' => __( 'Stores a file in the media library and returns the new attachment. The file is an image from a URL, or any file the current user may upload as base64 data. Requires an authenticated user who can upload files.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_upload_input_schema( $fields_schema ), + 'output_schema' => $item_schema, + 'execute_callback' => function ( $input = array() ) { + return $this->execute_media_upload( $input ); + }, + 'permission_callback' => function ( $input = array() ): bool { + return $this->can_use_media() && current_user_can( 'upload_files' ); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => false, + 'idempotent' => false, + ), + 'public' => true, + ), + ) + ); + + wp_register_ability( + 'core/media-update', + array( + 'label' => __( 'Update Media' ), + 'description' => __( 'Updates the given attributes of a media attachment and returns it. Attributes that are left out keep their stored values. Requires an authenticated user who can edit the attachment.' ), + 'category' => self::CATEGORY, + 'input_schema' => $this->get_update_input_schema( $fields_schema ), + 'output_schema' => $item_schema, + 'execute_callback' => function ( $input = array() ) { + return $this->execute_media_update( $input ); + }, + 'permission_callback' => function ( $input = array() ): bool { + return $this->check_item_permission( $input, 'edit_post' ); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => false, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + + wp_register_ability( + 'core/media-delete', + array( + 'label' => __( 'Delete Media' ), + 'description' => __( 'Moves a media attachment to the Trash, or deletes it and its files permanently when `permanent` is true. Unless the site keeps trashed media, only a permanent deletion is possible. Requires an authenticated user who can delete the attachment.' ), + 'category' => self::CATEGORY, + 'input_schema' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where' ), + 'properties' => array( + 'where' => $this->get_where_id_schema( __( 'Selects the attachment to delete.' ) ), + 'permanent' => array( + 'type' => 'boolean', + 'description' => __( 'Whether to delete the attachment and its files permanently instead of moving it to the Trash.' ), + ), + ), + ), + 'output_schema' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'outcome' ), + 'properties' => array( + 'outcome' => array( + 'type' => 'string', + 'enum' => array( 'deleted', 'trashed' ), + 'description' => __( 'What happened to the attachment: `deleted` or `trashed`.' ), + ), + ), + ), + 'execute_callback' => function ( $input = array() ) { + return $this->execute_media_delete( $input ); + }, + 'permission_callback' => function ( $input = array() ): bool { + return $this->check_item_permission( $input, 'delete_post' ); + }, + 'meta' => array( + 'annotations' => array( + 'readonly' => false, + 'destructive' => true, + 'idempotent' => true, + ), + 'public' => true, + ), + ) + ); + } + + /** + * Checks the conditions every media ability shares: a logged-in user, and the + * `attachment` post type with `show_in_abilities` on. + * + * @since 7.3.0 + * + * @return bool Whether the media abilities may be used. + */ + private function can_use_media(): bool { + $post_type_object = get_post_type_object( 'attachment' ); + + // Intentionally strict: every media ability requires a logged-in user, the query included. + return is_user_logged_in() && $post_type_object instanceof WP_Post_Type && $post_type_object->show_in_abilities; + } + + /** + * Permission callback for the `core/media-update` and `core/media-delete` abilities. + * + * The input is read defensively, as WP_Ability::check_permissions() does not prepare it. + * `where.id` must be a whole number of at least 1. When it names an attachment, the + * given capability on it is required. When it names nothing or another kind of post, + * the call is let through, so that the execute callback can report it as not found. + * + * @since 7.3.0 + * + * @param mixed $input The ability input. + * @param string $capability The capability required on the attachment: `edit_post` or `delete_post`. + * @return bool True if the request may proceed, false otherwise. + */ + private function check_item_permission( $input, string $capability ): bool { + if ( ! $this->can_use_media() ) { + return false; + } + + $input = rest_sanitize_object( $input ); + $where = isset( $input['where'] ) && rest_is_object( $input['where'] ) ? rest_sanitize_object( $input['where'] ) : array(); + $id = $this->parse_id( $where['id'] ?? null ); + if ( null === $id ) { + return false; + } + + $post = get_post( $id ); + + return ! $post instanceof WP_Post || 'attachment' !== $post->post_type || current_user_can( $capability, $id ); + } + + /** + * Parses a raw input value into an ID, or null when it is not a whole number of at least 1. + * + * Accepts the whole numbers that the integer schema accepts: native integers, floats such + * as the 7.0 that JSON encoders produce, and integer strings such as "7" or "007". + * Anything else, such as a fraction, is rejected rather than coerced, so a malformed ID + * can never resolve to another post. + * + * @since 7.3.0 + * + * @param mixed $value The raw input value. + * @return int|null The ID, or null when the value is not a valid ID. + */ + private function parse_id( $value ): ?int { + if ( is_int( $value ) ) { + return $value >= 1 ? $value : null; + } + + if ( is_string( $value ) && ctype_digit( $value ) ) { + $int = (int) $value; + + return $int >= 1 ? $int : null; + } + + if ( ! rest_is_integer( $value ) ) { + return null; + } + + /* + * Other whole numbers are read as floats, which hold every integer only up to 2 ** 53. + * Past that, the value may not be the one that was sent. + */ + $number = (float) $value; + + return $number >= 1 && $number <= 2 ** 53 ? (int) $number : null; + } + + /** + * Executes the `core/media-query` ability. + * + * The `status` filter is checked first, its values and then the capabilities they need. + * The other filters follow, and every attachment the query returns passes the row check + * of {@see self::is_readable_media()} before it is listed. + * + * @since 7.3.0 + * + * @param array $input The ability input, as prepared by WP_Ability::execute(). + * @return array|WP_Error A page of attachments, or a WP_Error on failure. + */ + private function execute_media_query( array $input ) { + // The author visibility memo is per call; see get_visible_author(). + $this->visible_authors = array(); + + $where = $input['where'] ?? array(); + $post_type_object = get_post_type_object( 'attachment' ); + + $statuses = $where['status'] ?? array( 'inherit' ); + foreach ( $statuses as $status ) { + $can_use_status = 'inherit' === $status + || ( 'private' === $status && current_user_can( $post_type_object->cap->read_private_posts ) ) + || current_user_can( $post_type_object->cap->edit_posts ); + if ( ! $can_use_status ) { + return new WP_Error( + 'media_cannot_filter_by_status', + __( 'Sorry, you are not allowed to filter media by this status.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + } + + /* + * Intentionally strict: the count leaves out the private attachments of other users + * unless the current user can read private posts, so the totals never count them. + */ + $query_args = array( + 'post_type' => 'attachment', + 'post_status' => array_values( $statuses ), + 'perm' => current_user_can( $post_type_object->cap->read_private_posts ) ? '' : 'readable', + 'orderby' => array( + 'date' => 'DESC', + 'ID' => 'DESC', + ), + 'ignore_sticky_posts' => true, + ); + + if ( array_key_exists( 'ids', $where ) ) { + $query_args['post__in'] = $where['ids']; + } + + if ( array_key_exists( 'slugs', $where ) ) { + $slugs = array_values( array_unique( array_filter( array_map( 'sanitize_title', $where['slugs'] ), static fn( $slug ) => '' !== $slug ) ) ); + if ( empty( $slugs ) ) { + return $this->invalid_param_error( 'media_invalid_filter', 'where[slugs]', __( 'The slugs filter must list one or more attachment slugs.' ) ); + } + $query_args['post_name__in'] = $slugs; + } + + /* + * A MIME type is a full type without wildcards, so it is matched exactly. A media + * type group, such as `image`, matches every type of that group. With both filters, + * an attachment matches when it matches either. + */ + $mime_types = array_merge( $where['media_type'] ?? array(), $where['mime_type'] ?? array() ); + if ( ! empty( $mime_types ) ) { + $query_args['post_mime_type'] = array_values( array_unique( $mime_types ) ); + } + + // The parent post is never looked up. + if ( array_key_exists( 'post', $where ) ) { + $query_args['post_parent'] = $where['post']; + } + + /* + * Null, int, or false: no author filter, the user ID to query, or a filter that names + * no user, which matches nothing. An `id` is never looked up: it matches the stored + * author ID. + */ + $author = $where['author'] ?? array(); + $author_id = $author['id'] ?? null; + + /* + * A slug that names no user, or a user the current user may not see, or another + * user than `id`, matches nothing. The visibility rule is the one the `author` + * field follows, so the filter cannot confirm a slug the field withholds. + */ + if ( isset( $author['slug'] ) ) { + $user = get_user_by( 'slug', $author['slug'] ); + $user = $user ? $this->get_visible_author( $user->ID ) : null; + $author_id = ! $user || ( null !== $author_id && $user->ID !== $author_id ) ? false : $user->ID; + } + + if ( false === $author_id ) { + return $this->prepare_query_output( array(), 0, 0 ); + } + if ( null !== $author_id ) { + $query_args['author'] = $author_id; + } + + $pagination = $input['pagination'] ?? array(); + $lists_items = isset( $query_args['post__in'] ) || isset( $query_args['post_name__in'] ); + $default_per_page = $lists_items ? self::MAX_PER_PAGE : self::DEFAULT_PER_PAGE; + $page = $pagination['page'] ?? 1; + + $query_args['paged'] = $page; + $query_args['posts_per_page'] = $pagination['per_page'] ?? $default_per_page; + + $query = new WP_Query( $query_args ); + $total = $this->get_query_total( $query, $query_args, $page ); + + /* + * Count the pages with the page size the query ran with, since query filters such + * as `pre_get_posts` callbacks can change it. Without paging, the query returns + * every attachment on one page. + */ + $query_per_page = (int) $query->get( 'posts_per_page' ); + if ( $query->get( 'nopaging' ) || $query_per_page < 1 ) { + $total_pages = $total > 0 ? 1 : 0; + } else { + $total_pages = (int) ceil( $total / $query_per_page ); + } + + if ( $total > 0 && $page > $total_pages ) { + return new WP_Error( + 'media_invalid_page_number', + __( 'The page number requested is larger than the number of pages available.' ), + array( 'status' => 404 ) + ); + } + + update_post_parent_caches( $query->posts ); + update_post_author_caches( $query->posts ); + + $fields = $this->normalize_fields( $input ); + $items = array(); + foreach ( $query->posts as $post ) { + // Query filters can add posts of other types. + if ( ! $post instanceof WP_Post || 'attachment' !== $post->post_type || ! $this->is_readable_media( $post ) ) { + continue; + } + $items[] = $this->format_media( $post, $fields ); + } + + return $this->prepare_query_output( $items, $total, $total_pages ); + } + + /** + * Executes the `core/media-upload` ability. + * + * The capability to upload is checked first, then the attributes, and only then is the + * file read, so a refused call never requests a URL, decodes data or writes a file. + * + * @since 7.3.0 + * + * @param array $input The ability input, as prepared by WP_Ability::execute(). + * @return array|WP_Error The new attachment, or a WP_Error on failure. + */ + private function execute_media_upload( array $input ) { + // The author visibility memo is per call; see get_visible_author(). + $this->visible_authors = array(); + + // Checked again after the permission callback, whose result a filter can change. + if ( ! current_user_can( 'upload_files' ) ) { + return new WP_Error( + 'media_cannot_upload', + __( 'Sorry, you are not allowed to upload media on this site.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $data = $input['data'] ?? array(); + $postarr = $this->prepare_attributes( $data, null ); + if ( is_wp_error( $postarr ) ) { + return $postarr; + } + + require_once ABSPATH . 'wp-admin/includes/file.php'; + require_once ABSPATH . 'wp-admin/includes/media.php'; + require_once ABSPATH . 'wp-admin/includes/image.php'; + + // The post date does not usually matter for pages, so an upload to one is not backdated. + $time = null; + $parent = ! empty( $postarr['post_parent'] ) ? get_post( $postarr['post_parent'] ) : null; + if ( $parent instanceof WP_Post && 'page' !== $parent->post_type && substr( $parent->post_date, 0, 4 ) > 0 ) { + $time = $parent->post_date; + } + + $file = $data['file']; + $stored = isset( $file['url'] ) + ? $this->store_from_url( $file['url'], $time ) + : $this->store_from_base64( $file['base64'], $file['filename'], $time ); + if ( is_wp_error( $stored ) ) { + return $stored; + } + + $image_meta = wp_read_image_metadata( $stored['file'] ); + + if ( '' === ( $postarr['post_title'] ?? '' ) ) { + $postarr['post_title'] = ! empty( $image_meta ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) + ? $image_meta['title'] + : preg_replace( '/\.[^.]+$/', '', wp_basename( $stored['file'] ) ); + } + + if ( '' === ( $postarr['post_excerpt'] ?? '' ) && ! empty( $image_meta ) && trim( $image_meta['caption'] ) ) { + $postarr['post_excerpt'] = $image_meta['caption']; + } + + $alt_text = null; + if ( array_key_exists( 'alt_text', $data ) ) { + $alt_text = $data['alt_text']; + } elseif ( ! empty( $image_meta ) && trim( $image_meta['alt'] ) ) { + $alt_text = $image_meta['alt']; + } + + $postarr['post_status'] = 'inherit'; + $postarr['post_mime_type'] = $stored['type']; + $postarr['guid'] = $stored['url']; + $postarr['post_author'] ??= get_current_user_id(); + $postarr['post_parent'] ??= 0; + + $attachment_id = wp_insert_attachment( wp_slash( $postarr ), $stored['file'], 0, true, false ); + if ( is_wp_error( $attachment_id ) ) { + return $this->save_failed_error( $attachment_id ); + } + + if ( null !== $alt_text ) { + update_post_meta( $attachment_id, '_wp_attachment_image_alt', wp_slash( sanitize_text_field( $alt_text ) ) ); + } + + wp_after_insert_post( $attachment_id, false, null ); + + /* + * Create the image sub-sizes and save the metadata. When the metadata cannot be + * generated, the attachment stays and is returned without it. + */ + wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $stored['file'] ) ); + + return $this->prepare_item( $attachment_id, $this->normalize_fields( $input ) ); + } + + /** + * Downloads an image from a URL and stores it in the uploads folder. + * + * _wp_download_image_from_url() checks the URL and makes the only request. The + * downloaded file must then pass the size checks and be an image as the file check + * sees it, and the temporary file is removed whatever the outcome. + * + * @since 7.3.0 + * + * @param string $url The URL of the image. + * @param string|null $time The time the uploads folder is chosen by, or null for now. + * @return array|WP_Error The stored file from store_file(), or a WP_Error. + */ + private function store_from_url( string $url, ?string $time ) { + $param = 'data[file][url]'; + $download = _wp_download_image_from_url( $url ); + if ( is_wp_error( $download ) ) { + if ( 'invalid_image_url' === $download->get_error_code() ) { + return $this->invalid_param_error( 'media_invalid_file', $param, $download->get_error_message() ); + } + + /* + * Intentionally strict: a failed download gives one fixed error, which holds + * nothing of the remote answer or of the error behind it. + */ + return new WP_Error( 'media_download_failed', __( 'Download failed.' ), array( 'status' => 500 ) ); + } + + $tmp_file = $download['tmp_name']; + try { + $size_error = $this->check_file_size( wp_filesize( $tmp_file ), $param ); + if ( $size_error ) { + return $size_error; + } + + /* + * Intentionally strict: the content must be an image as the file check sees it, for + * every user, also one who may upload any type. The upload handling below still + * runs its own type check. + */ + $checked = wp_check_filetype_and_ext( $tmp_file, $download['name'] ); + if ( ! $checked['ext'] || ! $checked['type'] || ! str_starts_with( $checked['type'], 'image/' ) ) { + return $this->invalid_param_error( 'media_invalid_file', $param, __( 'Only images can be uploaded from a URL.' ) ); + } + + return $this->store_file( $download['name'], $tmp_file, $time, $param ); + } finally { + // Of the temporary files, only the one the download returned is ever removed. + wp_delete_file( $tmp_file ); + } + } + + /** + * Decodes a file sent as base64 data and stores it in the uploads folder. + * + * @since 7.3.0 + * + * @param string $base64 The base64 data. + * @param string $filename The file name, which the upload handling sanitizes. + * @param string|null $time The time the uploads folder is chosen by, or null for now. + * @return array|WP_Error The stored file from store_file(), or a WP_Error. + */ + private function store_from_base64( string $base64, string $filename, ?string $time ) { + $param = 'data[file][base64]'; + $bytes = base64_decode( $base64, true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- The file is sent as base64 data. + if ( false === $bytes ) { + return $this->invalid_param_error( 'media_invalid_file', $param, __( 'The file data is not valid base64.' ) ); + } + + if ( '' === $bytes ) { + return $this->invalid_param_error( 'media_invalid_file', $param, __( 'File is empty. Please upload something more substantial.' ) ); + } + + $size_error = $this->check_file_size( strlen( $bytes ), $param ); + if ( $size_error ) { + return $size_error; + } + + $tmp_file = wp_tempnam( $filename ); + try { + // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- Writes the temporary file. + if ( false === file_put_contents( $tmp_file, $bytes ) ) { + return new WP_Error( 'media_upload_failed', __( 'Could not create temporary file.' ), array( 'status' => 500 ) ); + } + + return $this->store_file( $filename, $tmp_file, $time, 'data[file][filename]' ); + } finally { + wp_delete_file( $tmp_file ); + } + } + + /** + * Checks the size of a file against the network limits and the maximum upload size. + * + * @since 7.3.0 + * + * @param int $size The file size in bytes. + * @param string $param The input path of the file, such as `data[file][url]`. + * @return WP_Error|null The error, or null when the size is accepted. + */ + private function check_file_size( int $size, string $param ): ?WP_Error { + /* translators: %s: Maximum allowed file size in kilobytes. */ + $too_big = __( 'This file is too big. Files must be less than %s KB in size.' ); + + if ( is_multisite() && ! get_site_option( 'upload_space_check_disabled' ) ) { + $space_left = get_upload_space_available(); + if ( $space_left < $size ) { + return new WP_Error( + 'media_quota_exceeded', + /* translators: %s: Required disk space in kilobytes. */ + sprintf( __( 'Not enough space to upload. %s KB needed.' ), number_format( ( $size - $space_left ) / KB_IN_BYTES ) ), + array( 'status' => 400 ) + ); + } + + $max_kilobytes = get_site_option( 'fileupload_maxk', 1500 ); + if ( $size > KB_IN_BYTES * (int) $max_kilobytes ) { + return $this->invalid_param_error( 'media_invalid_file', $param, sprintf( $too_big, $max_kilobytes ) ); + } + } + + // Intentionally strict: a file sent as base64 data is held to the maximum upload size too. + $max_size = (int) wp_max_upload_size(); + if ( $max_size > 0 && $size > $max_size ) { + return $this->invalid_param_error( 'media_invalid_file', $param, sprintf( $too_big, number_format( $max_size / KB_IN_BYTES ) ) ); + } + + return null; + } + + /** + * Stores a temporary file in the uploads folder through the regular upload handling. + * + * The upload handling decides, for the current user, whether the file may be stored, + * from its name and its content. It is given no type, so the type always comes from + * that check. The same type rule is checked first, so that a refused type is reported + * as invalid input and any other failure of the upload handling as a server error. + * + * @since 7.3.0 + * + * @param string $filename The file name. + * @param string $tmp_file The path of the temporary file. + * @param string|null $time The time the uploads folder is chosen by, or null for now. + * @param string $type_param The input path a refused file type is reported for. + * @return array|WP_Error The `file`, `url` and `type` of the stored file, or a WP_Error. + */ + private function store_file( string $filename, string $tmp_file, ?string $time, string $type_param ) { + $checked = wp_check_filetype_and_ext( $tmp_file, $filename ); + if ( ( ! $checked['ext'] || ! $checked['type'] ) && ! current_user_can( 'unfiltered_upload' ) ) { + return $this->invalid_param_error( 'media_invalid_file', $type_param, __( 'Sorry, you are not allowed to upload this file type.' ) ); + } + + $upload = array( + 'name' => $filename, + 'tmp_name' => $tmp_file, + 'type' => '', + ); + + $stored = wp_handle_sideload( $upload, array( 'test_form' => false ), $time ); + if ( isset( $stored['error'] ) ) { + return new WP_Error( 'media_upload_failed', $stored['error'], array( 'status' => 500 ) ); + } + + return $stored; + } + + /** + * Executes the `core/media-update` ability. + * + * The attachment is looked up first, then the capability to edit it is checked, then + * every attribute rule, and only then is it saved, so a refused call writes nothing. + * + * @since 7.3.0 + * + * @param array $input The ability input, as prepared by WP_Ability::execute(). + * @return array|WP_Error The updated attachment, or a WP_Error on failure. + */ + private function execute_media_update( array $input ) { + // The author visibility memo is per call; see get_visible_author(). + $this->visible_authors = array(); + + $attachment = $this->get_requested_attachment( $input ); + if ( ! $attachment ) { + return $this->not_found_error(); + } + + // Checked again after the permission callback, whose result a filter can change. + if ( ! current_user_can( 'edit_post', $attachment->ID ) ) { + return new WP_Error( + 'media_cannot_edit', + __( 'Sorry, you are not allowed to edit this post.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + $data = $input['data'] ?? array(); + $postarr = $this->prepare_attributes( $data, $attachment ); + if ( is_wp_error( $postarr ) ) { + return $postarr; + } + + // Every update is saved, also one that only sends the alt text, so its modified date changes. + $postarr['ID'] = $attachment->ID; + $saved = wp_update_post( wp_slash( $postarr ), true ); + if ( is_wp_error( $saved ) ) { + return $this->save_failed_error( $saved ); + } + + // The alt text, when sent, is written once the save succeeded. + if ( array_key_exists( 'alt_text', $data ) ) { + update_post_meta( $attachment->ID, '_wp_attachment_image_alt', wp_slash( sanitize_text_field( $data['alt_text'] ) ) ); + } + + /* + * The save does not run the after-insert action for an attachment, so it runs here, + * once, after the alt text is written, with the attachment as it was before the save. + */ + wp_after_insert_post( $attachment->ID, true, $attachment ); + + return $this->prepare_item( $attachment->ID, $this->normalize_fields( $input ) ); + } + + /** + * Executes the `core/media-delete` ability. + * + * The attachment is looked up first, then the capability to delete it is checked. It is + * deleted permanently when `permanent` is true; otherwise it is moved to the Trash. The + * outcome is confirmed against the stored attachment afterwards. + * + * @since 7.3.0 + * + * @param array $input The ability input, as prepared by WP_Ability::execute(). + * @return array|WP_Error The outcome, or a WP_Error on failure. + */ + private function execute_media_delete( array $input ) { + $attachment = $this->get_requested_attachment( $input ); + if ( ! $attachment ) { + return $this->not_found_error(); + } + + // Checked again after the permission callback, whose result a filter can change. + if ( ! current_user_can( 'delete_post', $attachment->ID ) ) { + return new WP_Error( + 'media_cannot_delete', + __( 'Sorry, you are not allowed to delete this post.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + /* + * Intentionally strict: the outcome is read from the stored attachment, so a deletion + * that a filter made Core skip is an error, not a reported deletion. + */ + if ( ! empty( $input['permanent'] ) ) { + wp_delete_attachment( $attachment->ID, true ); + + return null === get_post( $attachment->ID ) ? array( 'outcome' => 'deleted' ) : $this->delete_failed_error(); + } + + /* + * Checked before wp_trash_post() is called: without trash days that call would delete + * the attachment, and with media trashing off it would still move the attachment to + * the Trash. + */ + if ( EMPTY_TRASH_DAYS < 1 || ! MEDIA_TRASH ) { + return new WP_Error( + 'media_trash_not_supported', + __( 'The attachment does not support trashing. Set "permanent" to delete it.' ), + array( 'status' => 501 ) + ); + } + + if ( 'trash' === $attachment->post_status ) { + return new WP_Error( + 'media_already_trashed', + __( 'The attachment has already been trashed.' ), + array( 'status' => 410 ) + ); + } + + wp_trash_post( $attachment->ID ); + $trashed = get_post( $attachment->ID ); + + return $trashed instanceof WP_Post && 'trash' === $trashed->post_status ? array( 'outcome' => 'trashed' ) : $this->delete_failed_error(); + } + + /** + * Returns the attachment that `where.id` names. + * + * The ID is read once from the prepared input, and the execute callback uses the + * returned attachment's ID for its capability check and the write. + * + * @since 7.3.0 + * + * @param array $input The ability input. + * @return WP_Post|null The attachment, or null when `where.id` names no attachment. + */ + private function get_requested_attachment( array $input ): ?WP_Post { + $id = $input['where']['id'] ?? 0; + $post = $id > 0 ? get_post( $id ) : null; + + return $post instanceof WP_Post && 'attachment' === $post->post_type ? $post : null; + } + + /** + * Checks the sent attributes and builds the attachment fields to save from them. + * + * Shared by the upload and update abilities. The array is built from scratch, one + * attribute at a time, so only the attributes of {@see self::get_attribute_properties()} + * reach the save, each mapped by name. The alt text is saved apart from the attachment + * and is left out. + * The checks run in the order `author`, `post`, `date`, `slug`, and for each attribute + * the value is checked before any capability. The first failure is returned. + * + * @since 7.3.0 + * + * @param array $data The `data` input. + * @param WP_Post|null $attachment The stored attachment on update, or null on upload. + * @return array|WP_Error The unslashed attachment fields, or a WP_Error. + */ + private function prepare_attributes( array $data, ?WP_Post $attachment ) { + $postarr = array(); + $post_type_object = get_post_type_object( 'attachment' ); + + if ( array_key_exists( 'author', $data ) ) { + $author_id = $data['author']; + + // The stored author sent again changes nothing. + if ( ! $attachment || (int) $attachment->post_author !== $author_id ) { + if ( get_current_user_id() !== $author_id ) { + // Checked before the user is looked up, so the error never tells whether a user exists. + if ( ! current_user_can( $post_type_object->cap->edit_others_posts ) ) { + return new WP_Error( + 'media_cannot_edit_others', + $attachment + ? __( 'Sorry, you are not allowed to update posts as this user.' ) + : __( 'Sorry, you are not allowed to create posts as this user.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + // Intentionally strict: the author must be an existing user who belongs to this site. + if ( ! get_userdata( $author_id ) || ( is_multisite() && ! is_user_member_of_blog( $author_id ) ) ) { + return $this->invalid_param_error( 'media_invalid_attribute', 'data[author]', __( 'Invalid author ID.' ) ); + } + } + + $postarr['post_author'] = $author_id; + } + } + + if ( array_key_exists( 'post', $data ) ) { + $parent_id = $data['post']; + + // The stored parent sent again needs no capability, also when that post no longer exists. + $is_current = $attachment && (int) $attachment->post_parent === $parent_id; + + // 0 leaves the attachment unattached, or detaches it, and needs nothing more. + if ( 0 !== $parent_id ) { + /* + * Checked before the post is looked up, so a missing and a forbidden post give + * the same error. Intentionally strict: on update, attaching to a post also + * needs the capability to edit that post. + */ + if ( ! $is_current && ! current_user_can( 'edit_post', $parent_id ) ) { + return new WP_Error( + 'media_cannot_attach', + $attachment + ? __( 'Sorry, you are not allowed to attach media to this post.' ) + : __( 'Sorry, you are not allowed to upload media to this post.' ), + array( 'status' => rest_authorization_required_code() ) + ); + } + + if ( in_array( get_post_type( $parent_id ), array( 'revision', 'attachment' ), true ) ) { + return $this->invalid_param_error( 'media_invalid_attribute', 'data[post]', __( 'Invalid parent type.' ) ); + } + } + + if ( ! $is_current ) { + $postarr['post_parent'] = $parent_id; + } + } + + if ( array_key_exists( 'date', $data ) ) { + $date = $data['date']; + $dates = null; + $is_unchanged = false; + if ( isset( $date['site'] ) ) { + $dates = rest_get_date_with_gmt( $date['site'] ); + $is_unchanged = $attachment && null !== $dates && $attachment->post_date === $dates[0]; + } elseif ( isset( $date['gmt'] ) ) { + $dates = rest_get_date_with_gmt( $date['gmt'], true ); + $is_unchanged = $attachment && null !== $dates && $attachment->post_date_gmt === $dates[1]; + } + + if ( null === $dates ) { + return $this->invalid_param_error( 'media_invalid_attribute', 'data[date]', __( 'Invalid date.' ) ); + } + + // On update, a date equal to the stored one counts as not sent. + if ( ! $is_unchanged ) { + $postarr['post_date'] = $dates[0]; + $postarr['post_date_gmt'] = $dates[1]; + if ( $attachment ) { + $postarr['edit_date'] = true; + } + } + } + + if ( array_key_exists( 'slug', $data ) ) { + $slug = sanitize_title( $data['slug'] ); + + // Intentionally strict: a slug that sanitizes to nothing is an error. + if ( '' === $slug ) { + return $this->invalid_param_error( 'media_invalid_attribute', 'data[slug]', __( 'The slug must contain at least one character that is valid in a slug.' ) ); + } + + $postarr['post_name'] = $slug; + } + + $text_fields = array( + 'title' => 'post_title', + 'caption' => 'post_excerpt', + 'description' => 'post_content', + ); + foreach ( $text_fields as $attribute => $field ) { + if ( array_key_exists( $attribute, $data ) ) { + $postarr[ $field ] = $data[ $attribute ]; + } + } + + return $postarr; + } + + /** + * Returns a written attachment in the requested fields. + * + * @since 7.3.0 + * + * @param int $attachment_id The attachment ID. + * @param list $fields The requested field paths. + * @return array The attachment, or only its ID when the current user may not read it. + */ + private function prepare_item( int $attachment_id, array $fields ): array { + $attachment = get_post( $attachment_id ); + + /* + * Intentionally strict: the written attachment passes the same row check as every + * query row. When the current user may not read it, the write stands but only its + * ID is returned, whatever the fields ask for. + */ + if ( ! $attachment instanceof WP_Post || ! $this->is_readable_media( $attachment ) ) { + return array( 'id' => $attachment_id ); + } + + return $this->format_media( $attachment, $fields ); + } + + /** + * Checks whether the current user can read an attachment. + * + * The parent chain is walked with get_post() alone first: a loop of two or more parents + * is not readable, and it must be found before any capability is checked, because the + * status lookup does not end for attachments that are each other's parent. An + * attachment that is its own parent counts as unattached. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @return bool Whether the attachment can be read. + */ + private function is_readable_media( WP_Post $post ): bool { + $seen = array( $post->ID => true ); + $current = $post; + while ( (int) $current->post_parent > 0 && (int) $current->post_parent !== $current->ID ) { + if ( isset( $seen[ (int) $current->post_parent ] ) ) { + return false; + } + + $current = get_post( (int) $current->post_parent ); + if ( ! $current instanceof WP_Post ) { + break; + } + + $seen[ $current->ID ] = true; + } + + return $this->can_read_post( $post ); + } + + /** + * Checks the read rule for an attachment or one of its parents, once the parent chain is + * known to be free of loops. + * + * A post is readable when it is published or the current user can read it, when its + * status is public, or when it inherits its status: then from its parent, whose post + * type must have `show_in_abilities` on and which must pass this check itself, or, without + * a parent or with one that no longer exists, as readable. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment or a parent of it. + * @return bool Whether the post can be read. + */ + private function can_read_post( WP_Post $post ): bool { + if ( 'publish' === $post->post_status || current_user_can( 'read_post', $post->ID ) ) { + return true; + } + + $status_object = get_post_status_object( $post->post_status ); + if ( $status_object && $status_object->public ) { + return true; + } + + if ( 'inherit' !== $post->post_status ) { + return false; + } + + $parent_id = (int) $post->post_parent; + $parent = $parent_id > 0 && $parent_id !== $post->ID ? get_post( $parent_id ) : null; + if ( ! $parent instanceof WP_Post ) { + return true; + } + + $parent_type = get_post_type_object( $parent->post_type ); + + return $parent_type instanceof WP_Post_Type && $parent_type->show_in_abilities && $this->can_read_post( $parent ); + } + + /** + * Returns the query total, recovering it when WP_Query skipped the count. + * + * WP_Query leaves `found_posts` at 0 when a requested page has no rows. A minimal + * unpaged query recovers it, so a page past the last one can be told apart from a + * query that matches nothing. + * + * @since 7.3.0 + * + * @param WP_Query $query The executed query. + * @param array $query_args The arguments used for the executed query. + * @param int $page The requested page. + * @return int Total matching rows across all pages. + */ + private function get_query_total( WP_Query $query, array $query_args, int $page ): int { + $total = (int) $query->found_posts; + + if ( $total > 0 || $page <= 1 ) { + return $total; + } + + $count_args = $query_args; + $count_args['fields'] = 'ids'; + $count_args['posts_per_page'] = 1; + $count_args['update_post_meta_cache'] = false; + $count_args['update_post_term_cache'] = false; + unset( $count_args['paged'] ); + + $count_query = new WP_Query( $count_args ); + + return (int) $count_query->found_posts; + } + + /** + * Returns the requested field paths, or the default set when none are given. + * + * @since 7.3.0 + * + * @param array $input The ability input. + * @return list The requested field paths. + */ + private function normalize_fields( array $input ): array { + $fields = $input['fields'] ?? array(); + + return empty( $fields ) ? self::DEFAULT_FIELDS : array_values( $fields ); + } + + /** + * Returns a user when the current user may see them as an author. + * + * The current user may see themselves, the users they can edit, every user when they can + * list users, and otherwise the authors of posts they can read in a publicly viewable post + * type exposed to abilities. A user the current user may not see is reported like a + * missing one. The post count is kept per author for the call, since count_user_posts() + * is not cached. + * + * @since 7.3.0 + * + * @param int $user_id The user ID. + * @return WP_User|null The user, or null when they no longer exist or may not be seen. + */ + private function get_visible_author( int $user_id ): ?WP_User { + $user = get_userdata( $user_id ); + if ( ! $user ) { + return null; + } + + if ( get_current_user_id() === $user_id || current_user_can( 'list_users' ) || current_user_can( 'edit_user', $user_id ) ) { + return $user; + } + + if ( ! isset( $this->visible_authors[ $user_id ] ) ) { + // Attachments are left out, as their status never counts as published. + $post_types = array_diff( get_post_types( array( 'show_in_abilities' => true ) ), array( 'attachment' ) ); + $post_types = array_values( array_filter( $post_types, 'is_post_type_viewable' ) ); + $this->visible_authors[ $user_id ] = (int) count_user_posts( $user_id, $post_types ) > 0; + } + + return $this->visible_authors[ $user_id ] ? $user : null; + } + + /** + * Formats an attachment into the ability output shape. + * + * The attachment is set up as the global post while its fields are built, so filters + * that rely on loop globals see it, and the previous global post is restored afterwards. + * Only the requested fields are included, and `id` always is. Raw sub-fields are only + * included when the current user can edit the attachment. A field none of whose + * requested sub-fields remain is left out. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @param list $fields The requested field paths. + * @return array The formatted attachment. + */ + private function format_media( WP_Post $post, array $fields ): array { + $previous_context = $this->get_post_context(); + $the_post_fired = did_action( 'the_post' ) > 0; + + /* + * Set up inside the try block and undone in the finally block, so a throw from a + * `the_post` callback or mid-render cannot leave the global post pointing at this + * attachment for the rest of the request. + */ + try { + $this->set_up_post_context( $post ); + + $can_edit = current_user_can( 'edit_post', $post->ID ); + $data = array( 'id' => $post->ID ); + + if ( rest_is_field_included( 'status', $fields ) ) { + $data['status'] = $post->post_status; + } + + foreach ( array( 'date', 'modified' ) as $field ) { + $dates = array(); + if ( rest_is_field_included( "{$field}.site", $fields ) ) { + $dates['site'] = $this->format_date( $post, $field, false ); + } + if ( rest_is_field_included( "{$field}.gmt", $fields ) ) { + $dates['gmt'] = $this->format_date( $post, $field, true ); + } + if ( ! empty( $dates ) ) { + $data[ $field ] = $dates; + } + } + + if ( rest_is_field_included( 'slug', $fields ) ) { + $data['slug'] = $post->post_name; + } + if ( rest_is_field_included( 'link', $fields ) ) { + $data['link'] = (string) get_permalink( $post ); + } + + $rendered_fields = array( + 'title' => array( 'post_title', 'get_title' ), + 'caption' => array( 'post_excerpt', 'get_rendered_excerpt' ), + 'description' => array( 'post_content', 'get_rendered_content' ), + ); + foreach ( $rendered_fields as $field => $spec ) { + list( $property, $render ) = $spec; + + $value = array(); + if ( $can_edit && rest_is_field_included( "{$field}.raw", $fields ) ) { + $value['raw'] = $post->$property; + } + if ( rest_is_field_included( "{$field}.rendered", $fields ) ) { + $value['rendered'] = $this->$render( $post ); + } + if ( ! empty( $value ) ) { + $data[ $field ] = $value; + } + } + + if ( rest_is_field_included( 'alt_text', $fields ) ) { + $data['alt_text'] = (string) get_post_meta( $post->ID, '_wp_attachment_image_alt', true ); + } + /* + * The output `media_type` is `image` or `file`, while the `media_type` filter takes + * the part of the MIME type before the slash, such as `audio`. The REST API reports + * and filters attachments the same way. As the check is by file extension, some + * attachments that the `image` filter matches, such as SVG files, report `file`. + */ + if ( rest_is_field_included( 'media_type', $fields ) ) { + $data['media_type'] = wp_attachment_is_image( $post->ID ) ? 'image' : 'file'; + } + if ( rest_is_field_included( 'mime_type', $fields ) ) { + $data['mime_type'] = $post->post_mime_type; + } + + if ( rest_is_field_included( 'source_url', $fields ) ) { + $source_url = wp_get_attachment_url( $post->ID ); + if ( $source_url ) { + $data['source_url'] = $source_url; + } + } + + $file_path = ''; + if ( rest_is_field_included( 'filename', $fields ) || rest_is_field_included( 'filesize', $fields ) ) { + $original_path = wp_get_original_image_path( $post->ID ); + $file_path = $original_path ? $original_path : get_attached_file( $post->ID ); + if ( $file_path && rest_is_field_included( 'filename', $fields ) ) { + $data['filename'] = wp_basename( $file_path ); + } + } + + $metadata = array(); + if ( rest_is_field_included( 'filesize', $fields ) || rest_is_field_included( 'media_details', $fields ) ) { + $metadata = wp_get_attachment_metadata( $post->ID ); + $metadata = is_array( $metadata ) ? $metadata : array(); + } + if ( rest_is_field_included( 'filesize', $fields ) ) { + if ( isset( $metadata['filesize'] ) && is_numeric( $metadata['filesize'] ) && $metadata['filesize'] > 0 ) { + $data['filesize'] = (int) $metadata['filesize']; + } elseif ( $file_path && is_readable( $file_path ) ) { + $data['filesize'] = wp_filesize( $file_path ); + } + } + + if ( rest_is_field_included( 'media_details', $fields ) ) { + $details = array(); + foreach ( array( 'width', 'height', 'length' ) as $key ) { + if ( isset( $metadata[ $key ] ) && is_numeric( $metadata[ $key ] ) && rest_is_field_included( "media_details.{$key}", $fields ) ) { + $details[ $key ] = (int) $metadata[ $key ]; + } + } + + /* + * Each size holds its width, height, MIME type and URL, and a size that lacks + * one of them is left out. The full size is added when the stored metadata has + * sub-sizes, also when none of them is kept. + */ + if ( ! empty( $metadata ) && rest_is_field_included( 'media_details.sizes', $fields ) ) { + $stored_sizes = is_array( $metadata['sizes'] ?? null ) ? $metadata['sizes'] : array(); + + /* + * The image URL lookup of a size reads the `file`, `width` and `height` of + * that size's stored entry, and for a file that is not an image those of the + * stored `full` entry, without checking them. A size whose lookup would read + * a missing one is left out before the lookup, so that incomplete stored + * metadata raises no warning. + */ + $is_complete = static function ( $entry ): bool { + return is_array( $entry ) && isset( $entry['file'], $entry['width'], $entry['height'] ); + }; + $can_look_up = static function ( string $name ) use ( $stored_sizes, $is_complete ): bool { + return empty( $stored_sizes[ $name ] ) || $is_complete( $stored_sizes[ $name ] ); + }; + $full_is_safe = wp_attachment_is_image( $post->ID ) || $can_look_up( 'full' ); + + $sizes = array(); + foreach ( $full_is_safe ? $stored_sizes : array() as $name => $size ) { + $name = (string) $name; + if ( ! $is_complete( $size ) || empty( $size['mime-type'] ) || ! is_string( $size['mime-type'] ) ) { + continue; + } + + $source = wp_get_attachment_image_src( $post->ID, $name ); + if ( $source ) { + $sizes[ $name ] = array( + 'width' => (int) $size['width'], + 'height' => (int) $size['height'], + 'mime_type' => $size['mime-type'], + 'source_url' => $source[0], + ); + } + } + + $full = ! empty( $stored_sizes ) && $can_look_up( 'full' ) ? wp_get_attachment_image_src( $post->ID, 'full' ) : false; + if ( $full && '' !== $post->post_mime_type ) { + $sizes['full'] = array( + 'width' => (int) $full[1], + 'height' => (int) $full[2], + 'mime_type' => $post->post_mime_type, + 'source_url' => $full[0], + ); + } + + // An empty list of sizes is a `stdClass`, so it encodes as an object for every caller. + $details['sizes'] = empty( $sizes ) ? new stdClass() : $sizes; + } + + // The whole field is an empty object without metadata; a sub-field left empty is left out. + if ( ! empty( $details ) ) { + $data['media_details'] = $details; + } elseif ( in_array( 'media_details', $fields, true ) ) { + $data['media_details'] = new stdClass(); + } + } + + if ( rest_is_field_included( 'post', $fields ) ) { + $data['post'] = (int) $post->post_parent; + } + + if ( rest_is_field_included( 'author', $fields ) ) { + $author_id = (int) $post->post_author; + $user = null; + if ( rest_is_field_included( 'author.name', $fields ) || rest_is_field_included( 'author.slug', $fields ) ) { + $user = $this->get_visible_author( $author_id ); + } + + $author = array(); + if ( rest_is_field_included( 'author.id', $fields ) ) { + $author['id'] = $author_id; + } + if ( rest_is_field_included( 'author.name', $fields ) ) { + $author['name'] = $user ? $user->display_name : null; + } + if ( rest_is_field_included( 'author.slug', $fields ) ) { + $author['slug'] = $user ? $user->user_nicename : null; + } + if ( ! empty( $author ) ) { + $data['author'] = $author; + } + } + + return $data; + } finally { + $this->restore_post_context( $previous_context, $the_post_fired ); + } + } + + /** + * Returns the attachment title with the protected and private prefixes stripped. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @return string The title. + */ + private function get_title( WP_Post $post ): string { + $strip = static function (): string { + return '%s'; + }; + add_filter( 'protected_title_format', $strip ); + add_filter( 'private_title_format', $strip ); + + /* + * The format filters are removed in a finally block so a throw from a title + * filter cannot leave them attached for the rest of the request. + */ + try { + $title = get_the_title( $post ); + + return is_string( $title ) ? $title : ''; + } finally { + remove_filter( 'protected_title_format', $strip ); + remove_filter( 'private_title_format', $strip ); + } + } + + /** + * Returns the attachment caption transformed for display. + * + * Applies the `get_the_excerpt` and `the_excerpt` filter chains, so an empty caption + * renders an excerpt of the description. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @return string The rendered caption. + */ + private function get_rendered_excerpt( WP_Post $post ): string { + /** This filter is documented in wp-includes/post-template.php */ + $excerpt = apply_filters( 'get_the_excerpt', $post->post_excerpt, $post ); + + /** This filter is documented in wp-includes/post-template.php */ + $excerpt = apply_filters( 'the_excerpt', $excerpt ); + + return is_string( $excerpt ) ? $excerpt : ''; + } + + /** + * Returns the attachment description transformed for display. + * + * Applies `the_content`, which adds the attachment markup in front of the text. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @return string The rendered description. + */ + private function get_rendered_content( WP_Post $post ): string { + /** This filter is documented in wp-includes/post-template.php */ + $content = apply_filters( 'the_content', $post->post_content ); + + return is_string( $content ) ? $content : ''; + } + + /** + * Returns the global post context, so it can be restored after a post is rendered. + * + * @since 7.3.0 + * + * @return array The loop globals, keyed by name, leaving out those that are not set. + */ + private function get_post_context(): array { + /* + * Copy each global by value. A calling function that binds a global with `global`, + * as load_template() and WP_Block::render() do, makes it a reference, which + * array_intersect_key( $GLOBALS, ... ) would keep. The saved copy would then follow + * the global to the rendered post, and the restore would put that post back. + */ + $context = array(); + foreach ( self::LOOP_GLOBALS as $name ) { + if ( ! array_key_exists( $name, $GLOBALS ) ) { + continue; + } + + $context[ $name ] = $GLOBALS[ $name ]; + } + + return $context; + } + + /** + * Sets up the global post context for rendering a post. + * + * Sets the global post and calls setup_postdata(), so filters that rely on loop globals + * render against the requested post. + * + * @since 7.3.0 + * + * @param WP_Post $post The post to render. + */ + private function set_up_post_context( WP_Post $post ): void { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Temporarily sets the global post for rendering. + $GLOBALS['post'] = $post; + setup_postdata( $post ); + } + + /** + * Restores the global post context saved by {@see self::get_post_context()}. + * + * Each loop global gets its previous value back, or is unset again when it was not set. + * wp_reset_postdata() alone is not enough: it does nothing when the main query has no + * post, which would leave the rendered post's data in the globals. When a post was set + * up before, setup_postdata() first runs for it again, as wp_reset_postdata() would, so + * callbacks on the `the_post` action can restore their own globals too. The saved values + * are put back even when such a callback throws. A global post that was never set up + * keeps the loop globals that setup_postdata() gives it. The `the_post` count is reset + * only when the ability was the first thing to fire that action and no global post was + * set, so rendering a post before the main query does not count as starting the loop. + * + * @since 7.3.0 + * + * @param array $previous_context The loop globals that get_post_context() returned. + * @param bool $the_post_fired Whether the `the_post` action had fired before the ability set up the post. + */ + private function restore_post_context( array $previous_context, bool $the_post_fired ): void { + $previous_post = $previous_context['post'] ?? null; + + /* + * A global post that was never set up, such as the main post before the loop + * starts, keeps what setup_postdata() gives it below. Do not put back the values + * saved before: `the_post` has fired then, so get_the_content() called without a + * post reads the loop globals instead of the post, and an unset `$pages` makes it + * throw a TypeError that breaks the page being rendered. + */ + $restore_saved_values = ! $previous_post instanceof WP_Post || is_array( $previous_context['pages'] ?? null ); + + try { + if ( $previous_post instanceof WP_Post ) { + // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Restores the previous global post context. + $GLOBALS['post'] = $previous_post; + setup_postdata( $previous_post ); + } + } finally { + if ( $restore_saved_values ) { + foreach ( self::LOOP_GLOBALS as $name ) { + if ( array_key_exists( $name, $previous_context ) ) { + $GLOBALS[ $name ] = $previous_context[ $name ]; + } else { + unset( $GLOBALS[ $name ] ); + } + } + } + + /* + * Only reset the `the_post` count when the ability was the first thing to fire it + * and no global post was set. Once it has fired, get_the_content() called without + * a post reads the loop globals unset above instead of the post. + */ + if ( ! $previous_post instanceof WP_Post && ! $the_post_fired ) { + unset( $GLOBALS['wp_actions']['the_post'] ); + } + } + } + + /** + * Formats a post date field as an ISO 8601 string, in the site's timezone or in GMT. + * + * In GMT, it reads the stored GMT date, deriving it from the local date when it is missing. + * + * @since 7.3.0 + * + * @param WP_Post $post The attachment. + * @param string $field Either 'date' or 'modified'. + * @param bool $gmt Whether to format the date in GMT instead of the site's timezone. + * @return string|null The ISO 8601 date, or null if unavailable. + */ + private function format_date( WP_Post $post, string $field, bool $gmt ): ?string { + $datetime = $gmt ? get_post_datetime( $post, $field, 'gmt' ) : false; + if ( ! $datetime ) { + $datetime = get_post_datetime( $post, $field ); + } + + if ( ! $datetime ) { + return null; + } + + /* + * A malformed stored date can still parse: a zero month formats with a negative + * year. The `date-time` format rejects it, which would fail output validation for + * the whole call, so it is reported as null too. + */ + $date = ( $gmt ? $datetime->setTimezone( new DateTimeZone( 'UTC' ) ) : $datetime )->format( 'c' ); + + return rest_parse_date( $date ) ? $date : null; + } + + /** + * Builds the query output for a page of formatted attachments. + * + * @since 7.3.0 + * + * @param array> $items The formatted attachments on the page. + * @param int $total Total number of attachments across all pages. + * @param int $total_pages Total number of pages. + * @return array The ability output. + */ + private function prepare_query_output( array $items, int $total, int $total_pages ): array { + return array( + 'items' => $items, + 'pagination' => array( + 'total' => $total, + 'total_pages' => $total_pages, + ), + ); + } + + /** + * Builds the output schema of a single attachment, shared by all media abilities. + * + * Only `id` is required, because it is always returned. The other fields are optional + * because the `fields` input lets the caller request any subset. The `fields` input + * lists each field, followed by the path of each of its sub-fields, such as + * `title.rendered`. + * + * @since 7.3.0 + * + * @return array The attachment JSON Schema. + */ + private function get_item_schema(): array { + $date_schema = static function ( string $description, string $site, string $gmt ): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'site' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => $site, + ), + 'gmt' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + 'description' => $gmt, + ), + ), + 'description' => $description, + ); + }; + + $text_schema = static function ( string $description, string $raw, string $rendered ): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'raw' => array( + 'type' => 'string', + 'description' => $raw, + ), + 'rendered' => array( + 'type' => 'string', + 'description' => $rendered, + ), + ), + 'description' => $description, + ); + }; + + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'description' => __( 'The attachment ID.' ), + ), + 'status' => array( + 'type' => 'string', + 'description' => __( 'The attachment status.' ), + ), + 'date' => $date_schema( + __( 'The upload date.' ), + __( "The upload date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), + __( 'The upload date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ) + ), + 'modified' => $date_schema( + __( 'The last modified date.' ), + __( "The last modified date, in ISO 8601 format using the site's timezone. Null when the date cannot be resolved." ), + __( 'The last modified date, in ISO 8601 format as GMT. Null when the date cannot be resolved.' ) + ), + 'slug' => array( + 'type' => 'string', + 'description' => __( 'The attachment slug.' ), + ), + 'link' => array( + 'type' => 'string', + 'format' => 'uri', + 'description' => __( 'The URL of the attachment page.' ), + ), + 'title' => $text_schema( + __( 'The attachment title.' ), + __( 'The title as stored. Present when the current user can edit the attachment.' ), + __( 'The title as it is displayed.' ) + ), + 'caption' => $text_schema( + __( 'The attachment caption.' ), + __( 'The caption as stored. Present when the current user can edit the attachment.' ), + __( 'The caption as it is displayed (HTML).' ) + ), + 'description' => $text_schema( + __( 'The attachment description.' ), + __( 'The description as stored. Present when the current user can edit the attachment.' ), + __( 'The description as it is displayed (HTML), with the attachment markup in front of it.' ) + ), + 'alt_text' => array( + 'type' => 'string', + 'description' => __( 'The alternative text, empty when there is none.' ), + ), + 'media_type' => array( + 'type' => 'string', + 'enum' => array( 'image', 'file' ), + 'description' => __( 'The kind of attachment: `image` for a JPEG, GIF, PNG, WebP, AVIF or HEIC image, `file` for any other attachment, including audio and video. These values differ from the `media_type` filter; `mime_type` gives the exact type.' ), + ), + 'mime_type' => array( + 'type' => 'string', + 'description' => __( 'The MIME type of the file.' ), + ), + 'source_url' => array( + 'type' => 'string', + 'format' => 'uri', + 'description' => __( 'The URL of the file. Left out when the attachment has no file.' ), + ), + 'filename' => array( + 'type' => 'string', + 'description' => __( 'The name of the original file. Left out when the attachment has no file.' ), + ), + 'filesize' => array( + 'type' => 'integer', + 'description' => __( 'The size of the file in bytes. Left out when it is not known.' ), + ), + 'media_details' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'width' => array( + 'type' => 'integer', + 'description' => __( 'The width in pixels, for images and videos.' ), + ), + 'height' => array( + 'type' => 'integer', + 'description' => __( 'The height in pixels, for images and videos.' ), + ), + 'length' => array( + 'type' => 'integer', + 'description' => __( 'The length in seconds, for audio and video.' ), + ), + 'sizes' => array( + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'width', 'height', 'mime_type', 'source_url' ), + 'properties' => array( + 'width' => array( + 'type' => 'integer', + 'description' => __( 'The width in pixels.' ), + ), + 'height' => array( + 'type' => 'integer', + 'description' => __( 'The height in pixels.' ), + ), + 'mime_type' => array( + 'type' => 'string', + 'description' => __( 'The MIME type of the size.' ), + ), + 'source_url' => array( + 'type' => 'string', + 'format' => 'uri', + 'description' => __( 'The URL of the size.' ), + ), + ), + ), + 'description' => __( 'The image sizes, keyed by size name, with `full` for the full size when there are sub-sizes. Empty when there are none.' ), + ), + ), + 'description' => __( 'Details of the file from its stored metadata. Empty when there is no metadata.' ), + ), + 'post' => array( + 'type' => 'integer', + 'description' => __( 'The ID of the post the attachment is attached to, 0 when it is unattached.' ), + ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'description' => __( 'The user ID of the author, as the `author.id` filter takes it.' ), + ), + 'name' => array( + 'type' => array( 'string', 'null' ), + 'description' => __( "The author's display name. Null when the author no longer exists or the current user may not see them." ), + ), + 'slug' => array( + 'type' => array( 'string', 'null' ), + 'description' => __( "The author's user slug (nicename), as the `author.slug` filter takes it. Null when the author no longer exists or the current user may not see them." ), + ), + ), + 'description' => __( 'The user who uploaded the attachment.' ), + ), + ), + ); + } + + /** + * Builds the schema of the `fields` input, shared by the query, upload and update abilities. + * + * @since 7.3.0 + * + * @param array $properties The attachment field definitions. + * @return array The `fields` JSON Schema. + */ + private function get_fields_input_schema( array $properties ): array { + $paths = array(); + foreach ( $properties as $name => $schema ) { + $paths[] = $name; + foreach ( array_keys( $schema['properties'] ?? array() ) as $sub_field ) { + $paths[] = "{$name}.{$sub_field}"; + } + } + + return array( + 'type' => 'array', + 'uniqueItems' => true, + 'items' => array( + 'type' => 'string', + 'enum' => $paths, + ), + 'description' => sprintf( + /* translators: %s: Comma-separated list of field paths. */ + __( 'Limit each returned attachment to these fields. A field such as `title` returns all of its sub-fields the current user can see, while a path such as `title.rendered` returns only that sub-field. The `id` is always included. If omitted or empty, the default fields are returned: %s. Raw sub-fields, such as `title.raw`, are left out when the current user cannot edit the attachment.' ), + '`' . implode( '`, `', self::DEFAULT_FIELDS ) . '`' + ), + ); + } + + /** + * Builds the input schema for the `core/media-query` ability. + * + * @since 7.3.0 + * + * @param array $fields_schema The `fields` JSON Schema. + * @return array The input JSON Schema. + */ + private function get_query_input_schema( array $fields_schema ): array { + return array( + 'type' => 'object', + 'default' => array(), + 'additionalProperties' => false, + 'properties' => array( + 'where' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'ids' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'maxItems' => self::MAX_PER_PAGE, + 'items' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + 'description' => __( 'Limit the query to these attachment IDs. If `pagination.per_page` is omitted, every matching attachment is returned on the first page.' ), + ), + 'slugs' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'maxItems' => self::MAX_PER_PAGE, + 'items' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'description' => __( 'Limit the query to attachments with these slugs. Each slug is sanitized as a post slug is, so `Team-Photo` matches `team-photo`.' ), + ), + 'status' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'enum' => self::STATUSES, + ), + 'description' => __( 'Filter by one or more statuses. Defaults to `inherit`, the status of every attachment that is neither private nor trashed. `private` requires the capability to read private posts or to edit posts, and `trash` the capability to edit posts.' ), + ), + 'media_type' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'enum' => self::MEDIA_TYPES, + ), + 'description' => __( 'Filter by one or more media types, the part of the MIME type before the slash. These values differ from the `media_type` output, which is only `image` or `file`; compare them with the start of `mime_type` instead.' ), + ), + 'mime_type' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'pattern' => '^[-.a-zA-Z0-9]+/[-.+a-zA-Z0-9]+$', + ), + 'description' => __( 'Filter by one or more exact MIME types, such as `image/jpeg`. Wildcards are not supported. With `media_type`, an attachment matches when it matches either filter.' ), + ), + 'post' => array( + 'type' => 'integer', + 'minimum' => 0, + 'description' => __( 'Filter by the ID of the post the attachments are attached to. Use 0 for unattached attachments.' ), + ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'The user ID of the author, as `author.id` is returned.' ), + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( "The author's user slug (nicename), as `author.slug` is returned." ), + ), + ), + 'description' => __( 'Filter by the author, given as the `id` or the `slug` the `author` field returns. A `slug` that names no user or a user the current user may not see, or an `id` and a `slug` that name different users, match nothing.' ), + ), + ), + 'description' => __( 'Selects the attachments to return. An attachment must match every given filter.' ), + ), + 'fields' => $fields_schema, + 'pagination' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'page' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'Page of results to return. Defaults to 1. Requesting a page beyond the last one is an error, unless nothing matches the query.' ), + ), + 'per_page' => array( + 'type' => 'integer', + 'minimum' => 1, + 'maximum' => self::MAX_PER_PAGE, + 'description' => sprintf( + /* translators: 1: Default number of attachments per page, 2: Maximum number of attachments per page. */ + __( 'Maximum number of attachments to return per page. Defaults to %1$d, or to %2$d when `where.ids` or `where.slugs` is given.' ), + self::DEFAULT_PER_PAGE, + self::MAX_PER_PAGE + ), + ), + ), + 'description' => __( 'Selects the page of results to return.' ), + ), + ), + ); + } + + /** + * Returns the schemas of the attributes an upload or an update can write. + * + * @since 7.3.0 + * + * @return array The attribute schemas, keyed by name. + */ + private function get_attribute_properties(): array { + return array( + 'title' => array( + 'type' => 'string', + 'description' => __( 'The attachment title.' ), + ), + 'caption' => array( + 'type' => 'string', + 'description' => __( 'The attachment caption.' ), + ), + 'description' => array( + 'type' => 'string', + 'description' => __( 'The attachment description.' ), + ), + 'alt_text' => array( + 'type' => 'string', + 'description' => __( 'The alternative text of the image.' ), + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'The attachment slug. It is sanitized as a post slug is, and made unique when it is taken.' ), + ), + 'date' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'site' => array( + 'type' => 'string', + 'format' => 'date-time', + 'description' => __( "The date in the site's timezone." ), + ), + 'gmt' => array( + 'type' => 'string', + 'format' => 'date-time', + 'description' => __( 'The date as GMT.' ), + ), + ), + 'description' => __( 'The attachment date, as `site`, `gmt` or both; `site` wins when both are given.' ), + ), + 'author' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'The user ID of the author. Another user than the current one requires the capability to edit the posts of others.' ), + ), + 'post' => array( + 'type' => 'integer', + 'minimum' => 0, + 'description' => __( 'The ID of the post to attach the attachment to, or 0 to leave it unattached or detach it. Requires the capability to edit that post.' ), + ), + ); + } + + /** + * Builds the input schema for the `core/media-upload` ability. + * + * @since 7.3.0 + * + * @param array $fields_schema The `fields` JSON Schema. + * @return array The input JSON Schema. + */ + private function get_upload_input_schema( array $fields_schema ): array { + $file = array( + 'file' => array( + 'anyOf' => array( + array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'url' ), + 'properties' => array( + 'url' => array( + 'type' => 'string', + 'format' => 'uri', + 'description' => __( 'The public HTTP or HTTPS URL of an image to download.' ), + ), + ), + ), + array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'base64', 'filename' ), + 'properties' => array( + 'base64' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'The file content as base64 data, without a `data:` prefix.' ), + ), + 'filename' => array( + 'type' => 'string', + 'minLength' => 1, + 'description' => __( 'The file name, with the extension that matches its content.' ), + ), + ), + ), + ), + 'description' => __( 'The file: an image from a `url`, or any file the current user may upload as `base64` data with its `filename`.' ), + ), + ); + + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'data' ), + 'properties' => array( + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'file' ), + 'properties' => array_merge( $file, $this->get_attribute_properties() ), + 'description' => __( 'The file and the attributes of the new attachment. Without a title, the title is taken from the image metadata or the file name.' ), + ), + 'fields' => $fields_schema, + ), + ); + } + + /** + * Builds the input schema for the `core/media-update` ability. + * + * @since 7.3.0 + * + * @param array $fields_schema The `fields` JSON Schema. + * @return array The input JSON Schema. + */ + private function get_update_input_schema( array $fields_schema ): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'data' ), + 'properties' => array( + 'where' => $this->get_where_id_schema( __( 'Selects the attachment to update.' ) ), + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => $this->get_attribute_properties(), + 'description' => __( 'The attributes to change. Attributes that are left out keep their stored values.' ), + ), + 'fields' => $fields_schema, + ), + ); + } + + /** + * Builds the schema of a `where` input that selects one attachment by ID. + * + * @since 7.3.0 + * + * @param string $description The description of `where`. + * @return array The `where` JSON Schema. + */ + private function get_where_id_schema( string $description ): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + 'description' => __( 'The attachment ID.' ), + ), + ), + 'description' => $description, + ); + } + + /** + * Builds the error for an input value that cannot be applied. + * + * @since 7.3.0 + * + * @param string $code The error code, such as `media_invalid_filter`. + * @param string $param The input path of the value, such as `where[slugs]`. + * @param string $message The error message. + * @return WP_Error The invalid parameter error. + */ + private function invalid_param_error( string $code, string $param, string $message ): WP_Error { + return new WP_Error( + $code, + $message, + array( + 'status' => 400, + 'params' => array( $param => $message ), + ) + ); + } + + /** + * Builds the error for a save that failed, from the error the save returned. + * + * @since 7.3.0 + * + * @param WP_Error $error The error the save returned. + * @return WP_Error The save failed error. + */ + private function save_failed_error( WP_Error $error ): WP_Error { + $is_database_error = in_array( $error->get_error_code(), array( 'db_insert_error', 'db_update_error' ), true ); + + return new WP_Error( + 'media_save_failed', + $error->get_error_message(), + array( 'status' => $is_database_error ? 500 : 400 ) + ); + } + + /** + * Builds the error for an ID that names no attachment. + * + * @since 7.3.0 + * + * @return WP_Error The not found error. + */ + private function not_found_error(): WP_Error { + return new WP_Error( + 'media_not_found', + __( 'The requested media was not found.' ), + array( 'status' => 404 ) + ); + } + + /** + * Builds the error for a deletion that failed or could not be confirmed. + * + * @since 7.3.0 + * + * @return WP_Error The delete failed error. + */ + private function delete_failed_error(): WP_Error { + return new WP_Error( + 'media_delete_failed', + __( 'The attachment could not be deleted.' ), + array( 'status' => 500 ) + ); + } +} diff --git a/src/wp-includes/post.php b/src/wp-includes/post.php index 3511fbfc81d7a..3fed0b2a8fffe 100644 --- a/src/wp-includes/post.php +++ b/src/wp-includes/post.php @@ -123,6 +123,7 @@ function create_initial_post_types() { 'delete_with_user' => true, 'supports' => array( 'title', 'author', 'comments' ), 'show_in_rest' => true, + 'show_in_abilities' => true, 'rest_base' => 'media', 'rest_controller_class' => 'WP_REST_Attachments_Controller', ) @@ -1755,8 +1756,9 @@ function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) * @type bool $show_in_rest Whether to include the post type in the REST API. Set this to true * for the post type to be available in the block editor. * @type bool $show_in_abilities Whether to expose this post type through the Abilities API, so the - * core content abilities can access its posts, subject to the current - * user's capabilities. Default false. + * core content abilities (the media abilities for attachments) can + * access its posts, subject to the current user's capabilities. + * Default false. * @type string $rest_base To change the base URL of REST API route. Default is $post_type. * @type string $rest_namespace To change the namespace URL of REST API route. Default is wp/v2. * @type string $rest_controller_class REST API controller class name. Default is 'WP_REST_Posts_Controller'. diff --git a/tests/phpunit/tests/abilities-api/testcase-media-ability.php b/tests/phpunit/tests/abilities-api/testcase-media-ability.php new file mode 100644 index 0000000000000..315319a2f1292 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-media-ability.php @@ -0,0 +1,808 @@ + + */ + protected const MEDIA_ABILITIES = array( 'core/media-query', 'core/media-upload', 'core/media-update', 'core/media-delete' ); + + /** + * The top-level keys of an item with the default fields. + * + * @since 7.3.0 + * + * @var list + */ + protected const DEFAULT_KEYS = array( 'id', 'status', 'date', 'slug', 'title', 'media_type', 'mime_type', 'source_url' ); + + /** + * The values the `fields` input takes, in schema order. + * + * @since 7.3.0 + * + * @var list + */ + protected const FIELDS = array( + 'id', + 'status', + 'date', + 'date.site', + 'date.gmt', + 'modified', + 'modified.site', + 'modified.gmt', + 'slug', + 'link', + 'title', + 'title.raw', + 'title.rendered', + 'caption', + 'caption.raw', + 'caption.rendered', + 'description', + 'description.raw', + 'description.rendered', + 'alt_text', + 'media_type', + 'mime_type', + 'source_url', + 'filename', + 'filesize', + 'media_details', + 'media_details.width', + 'media_details.height', + 'media_details.length', + 'media_details.sizes', + 'post', + 'author', + 'author.id', + 'author.name', + 'author.slug', + ); + + /** + * The roles the shared fixtures add, keyed by role name, with their capabilities. + * + * @since 7.3.0 + * + * @var array> + */ + protected const ROLES = array( + 'mdt_uploader' => array( + 'read' => true, + 'upload_files' => true, + ), + 'mdt_other_editor' => array( + 'read' => true, + 'edit_others_posts' => true, + 'edit_private_posts' => true, + ), + 'mdt_other_editor_uploader' => array( + 'read' => true, + 'upload_files' => true, + 'edit_others_posts' => true, + 'edit_private_posts' => true, + ), + 'mdt_no_caps' => array(), + ); + + /** + * Shared user IDs keyed by role or fixture name. + * + * @since 7.3.0 + * + * @var array + */ + protected static $user_ids = array(); + + /** + * Shared post and attachment IDs keyed by fixture name. + * + * @since 7.3.0 + * + * @var array + */ + protected static $post_ids = array(); + + /** + * Creates the shared users, posts and attachments. + * + * The attachments are rows without files, so no test class leaves a file behind. + * + * @since 7.3.0 + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + protected static function create_shared_fixtures( WP_UnitTest_Factory $factory ): void { + foreach ( self::ROLES as $role => $capabilities ) { + add_role( $role, $role, $capabilities ); + } + + self::$user_ids = array( + 'administrator' => $factory->user->create( array( 'role' => 'administrator' ) ), + 'editor' => $factory->user->create( array( 'role' => 'editor' ) ), + 'author' => $factory->user->create( array( 'role' => 'author' ) ), + 'author_without_posts' => $factory->user->create( array( 'role' => 'author' ) ), + 'contributor' => $factory->user->create( array( 'role' => 'contributor' ) ), + 'subscriber' => $factory->user->create( array( 'role' => 'subscriber' ) ), + 'uploader' => $factory->user->create( array( 'role' => 'mdt_uploader' ) ), + 'other_editor' => $factory->user->create( array( 'role' => 'mdt_other_editor' ) ), + 'other_editor_uploader' => $factory->user->create( array( 'role' => 'mdt_other_editor_uploader' ) ), + 'no_caps' => $factory->user->create( array( 'role' => 'mdt_no_caps' ) ), + ); + + $posts = array( + 'post' => $factory->post->create( + array( + 'post_author' => self::$user_ids['editor'], + 'post_status' => 'publish', + 'post_date' => '2020-05-15 10:00:00', + ) + ), + 'page' => $factory->post->create( + array( + 'post_type' => 'page', + 'post_author' => self::$user_ids['editor'], + 'post_status' => 'publish', + 'post_date' => '2019-03-10 10:00:00', + ) + ), + 'private_post' => $factory->post->create( + array( + 'post_author' => self::$user_ids['editor'], + 'post_status' => 'private', + ) + ), + 'author_post' => $factory->post->create( + array( + 'post_author' => self::$user_ids['author'], + 'post_status' => 'publish', + 'post_date' => '2021-07-20 10:00:00', + ) + ), + ); + + $posts['revision'] = $factory->post->create( + array( + 'post_type' => 'revision', + 'post_status' => 'inherit', + 'post_parent' => $posts['post'], + 'post_author' => self::$user_ids['editor'], + ) + ); + + $attachments = array( + 'unattached' => array( self::$user_ids['author'], 0, 'inherit', 'image/jpeg', 'mdt-unattached.jpg' ), + 'attached' => array( self::$user_ids['author'], $posts['post'], 'inherit', 'image/jpeg', 'mdt-attached.jpg' ), + 'private_parent' => array( self::$user_ids['editor'], $posts['private_post'], 'inherit', 'image/jpeg', 'mdt-private-parent.jpg' ), + 'private' => array( self::$user_ids['editor'], 0, 'private', 'image/jpeg', 'mdt-private.jpg' ), + 'trashed' => array( self::$user_ids['editor'], 0, 'trash', 'image/jpeg', 'mdt-trashed.jpg' ), + 'pdf' => array( self::$user_ids['author'], 0, 'inherit', 'application/pdf', 'mdt-document.pdf' ), + 'audio' => array( self::$user_ids['author'], 0, 'inherit', 'audio/mpeg', 'mdt-sound.mp3' ), + 'editor_image' => array( self::$user_ids['editor'], 0, 'inherit', 'image/jpeg', 'mdt-editor-image.jpg' ), + ); + + foreach ( $attachments as $name => list( $author, $parent, $status, $mime_type, $file ) ) { + $posts[ $name ] = $factory->attachment->create_object( + array( + 'file' => '2026/01/' . $file, + 'post_author' => $author, + 'post_parent' => $parent, + 'post_status' => $status, + 'post_mime_type' => $mime_type, + 'post_title' => 'Fixture ' . $name, + ) + ); + } + + update_post_meta( $posts['trashed'], '_wp_trash_meta_status', 'inherit' ); + + self::$post_ids = $posts; + } + + /** + * Forgets the shared fixtures and removes the roles they added. + * + * @since 7.3.0 + */ + public static function wpTearDownAfterClass(): void { + foreach ( array_keys( self::ROLES ) as $role ) { + remove_role( $role ); + } + + self::$user_ids = array(); + self::$post_ids = array(); + } + + /** + * Unregisters the media abilities and registers the content category. + * + * @since 7.3.0 + */ + public function set_up(): void { + parent::set_up(); + + $this->unregister_media_abilities(); + + if ( ! wp_has_ability_category( 'content' ) ) { + global $wp_current_filter; + $wp_current_filter[] = 'wp_abilities_api_categories_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + wp_register_ability_category( + 'content', + array( + 'label' => 'Content', + 'description' => 'Content.', + ) + ); + } + } + + /** + * Unregisters the media abilities and the category, removes the files a test added to the + * uploads folder, and resets the post types. + * + * @since 7.3.0 + */ + public function tear_down(): void { + global $wpdb; + + $this->unregister_media_abilities(); + + if ( wp_has_ability_category( 'content' ) ) { + wp_unregister_ability_category( 'content' ); + } + + $wpdb->suppress_errors( false ); + + $this->remove_added_uploads(); + + /* + * A test may turn off `show_in_abilities` on the attachment or post type, and the next class's + * wpSetUpBeforeClass() runs before the next set_up() resets the post types. + */ + $this->reset_post_types(); + + parent::tear_down(); + } + + /** + * Unregisters the media abilities that are registered. + * + * @since 7.3.0 + */ + private function unregister_media_abilities(): void { + foreach ( self::MEDIA_ABILITIES as $ability_name ) { + if ( wp_has_ability( $ability_name ) ) { + wp_unregister_ability( $ability_name ); + } + } + } + + /** + * Registers the media abilities inside a faked init action. + * + * @since 7.3.0 + */ + protected function register_abilities(): void { + global $wp_current_filter; + $wp_current_filter[] = 'wp_abilities_api_init'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Faking the action context to register within it. + ( new WP_Abilities_Media() )->register(); + } + + /** + * Registers the media abilities and returns the permission callback of the ability under + * test. + * + * The callback calls private methods, so tests that reach the gate without the input + * checks capture it from the registration arguments. + * + * @since 7.3.0 + * + * @return callable The permission callback. + */ + protected function get_permission_callback(): callable { + $ability = static::ABILITY; + $callback = null; + + add_filter( + 'wp_register_ability_args', + static function ( array $args, string $name ) use ( &$callback, $ability ): array { + if ( $ability === $name ) { + $callback = $args['permission_callback']; + } + + return $args; + }, + 10, + 2 + ); + + $this->register_abilities(); + + $this->assertIsCallable( $callback, "The {$ability} ability should be registered with a permission callback." ); + + return $callback; + } + + /** + * Runs the registered ability under test with the given input. + * + * @since 7.3.0 + * + * @param mixed $input The ability input. + * @return mixed The ability result. + */ + protected function run_ability( $input ) { + $ability = static::ABILITY; + + $this->assertTrue( wp_has_ability( $ability ), "The {$ability} ability should be registered." ); + + return wp_get_ability( $ability )->execute( $input ); + } + + /** + * Logs in as the shared user with the given role or fixture name, or logs out for + * `logged_out`. + * + * @since 7.3.0 + * + * @param string $role The role or fixture name. + */ + protected function login_as( string $role ): void { + wp_set_current_user( 'logged_out' === $role ? 0 : self::$user_ids[ $role ] ); + } + + /** + * Makes every input pass schema validation. The input is still converted to the schema + * types. + * + * @since 7.3.0 + */ + protected function skip_input_validation(): void { + add_filter( 'wp_ability_validate_input', '__return_true' ); + } + + /** + * Makes the permission callback of every ability pass. + * + * @since 7.3.0 + */ + protected function force_permission(): void { + add_filter( 'wp_ability_permission_result', '__return_true' ); + } + + /** + * Grants a capability to every user. + * + * @since 7.3.0 + * + * @param string $cap The capability. + */ + protected function grant_cap( string $cap ): void { + add_filter( + 'map_meta_cap', + static function ( array $caps, string $requested ) use ( $cap ): array { + return $cap === $requested ? array( 'exist' ) : $caps; + }, + 10, + 2 + ); + } + + /** + * Makes every save of a post fail, as an empty post or with a database error. + * + * @since 7.3.0 + * + * @param bool $database_error Whether the save fails with a database error. + */ + protected function make_saves_fail( bool $database_error ): void { + global $wpdb; + + if ( ! $database_error ) { + add_filter( 'wp_insert_post_empty_content', '__return_true' ); + return; + } + + $wpdb->suppress_errors( true ); + + add_filter( + 'query', + static function ( string $query ) use ( $wpdb ): string { + if ( preg_match( '/^\s*(INSERT\s+INTO|UPDATE)\s+`?' . preg_quote( $wpdb->posts, '/' ) . '`?\s/i', $query ) ) { + return str_replace( $wpdb->posts, $wpdb->prefix . 'mdt_missing_table', $query ); + } + + return $query; + } + ); + } + + /** + * Returns the files under the uploads folder, sorted. + * + * @since 7.3.0 + * + * @return list The file paths. + */ + protected function list_upload_files(): array { + $basedir = wp_upload_dir()['basedir']; + + if ( ! is_dir( $basedir ) ) { + return array(); + } + + $files = $this->files_in_dir( $basedir ); + sort( $files ); + + return $files; + } + + /** + * Takes a snapshot of the stored media: the number of posts per type and status, the + * number of meta rows, the files under the uploads folder and, when a post is given, the + * row and meta of that post. + * + * @since 7.3.0 + * + * @param int|null $post_id Optional. The post ID. Default null. + * @return array The snapshot. + */ + protected function snapshot( ?int $post_id = null ): array { + global $wpdb; + + $snapshot = array( + 'posts' => $wpdb->get_results( "SELECT post_type, post_status, COUNT(*) AS total FROM {$wpdb->posts} GROUP BY post_type, post_status ORDER BY post_type, post_status", ARRAY_A ), + 'meta' => (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->postmeta}" ), + 'files' => $this->list_upload_files(), + ); + + if ( null !== $post_id ) { + $snapshot['post'] = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id ), ARRAY_A ); + $snapshot['post_meta'] = $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $post_id ), ARRAY_A ); + } + + return $snapshot; + } + + /** + * Asserts that a result is an error with the given code and status. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $code The expected error code. + * @param int $status The expected error status. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_error( $result, string $code, int $status, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( $code, $result->get_error_code(), "{$context}: the error code should be {$code}." ); + + $data = $result->get_error_data(); + $this->assertIsArray( $data, "{$context}: the error should carry data." ); + $this->assertSame( $status, $data['status'] ?? null, "{$context}: the error status should be {$status}." ); + } + + /** + * Asserts that a result is the error of an input the schema rejects. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_invalid_input( $result, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code(), "{$context}: the schema should reject the input." ); + } + + /** + * Asserts that a result is an error with the given code and status and one `params` + * entry, keyed by the given input path, with a reason as its value. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $code The expected error code. + * @param string $path The expected input path. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_error_with_params( $result, string $code, string $path, string $context ): void { + $this->assert_error( $result, $code, 400, $context ); + + $params = $result->get_error_data()['params'] ?? null; + $this->assertIsArray( $params, "{$context}: the error should carry params." ); + $this->assertSame( array( $path ), array_keys( $params ), "{$context}: the params should hold only the input path {$path}." ); + $this->assertIsString( $params[ $path ], "{$context}: the params entry should hold the reason." ); + $this->assertNotSame( '', $params[ $path ], "{$context}: the reason should not be empty." ); + } + + /** + * Asserts the message of an error result. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $message The expected message. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_error_message( $result, string $message, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail before its message is read." ); + $this->assertSame( $message, $result->get_error_message(), "{$context}: the error message should be the fixed message." ); + } + + /** + * Asserts that a result is the error of a call that the permission callback refused. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_refused( $result, string $context ): void { + $this->assertWPError( $result, "{$context}: the call should fail." ); + $this->assertSame( 'ability_invalid_permissions', $result->get_error_code(), "{$context}: the permission callback should refuse the call." ); + } + + /** + * Asserts that a result is the not-found error. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + */ + protected function assert_not_found( $result, string $context ): void { + $this->assert_error( $result, 'media_not_found', 404, $context ); + $this->assertSame( 'The requested media was not found.', $result->get_error_message(), "{$context}: the message should be the not-found message." ); + } + + /** + * Asserts that a value is an empty object. + * + * @since 7.3.0 + * + * @param mixed $value The value. + * @param string $message The assertion message. + */ + protected function assert_empty_object( $value, string $message ): void { + $this->assertSame( '{}', wp_json_encode( $value ), $message ); + } + + /** + * Asserts the shape of an object schema: no other properties, the required keys, and + * the property names in order. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + * @param list $required The required keys. + * @param list $properties The property names, in order. + * @param string $context What the schema is, for the messages. + */ + protected function assert_object_schema( $schema, array $required, array $properties, string $context ): void { + $this->assertIsArray( $schema, "{$context} should be a schema." ); + $this->assertSame( 'object', $schema['type'] ?? null, "{$context} should be an object." ); + $this->assertFalse( $schema['additionalProperties'] ?? null, "{$context} should allow no other properties." ); + $this->assertSame( $required, $schema['required'] ?? array(), "{$context} should require these keys." ); + $this->assertSame( $properties, array_keys( $schema['properties'] ?? array() ), "{$context} should have these properties." ); + } + + /** + * Asserts the output schema of one attachment. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + */ + protected function assert_item_schema( $schema ): void { + $names = array_values( array_filter( self::FIELDS, static fn( string $field ): bool => ! str_contains( $field, '.' ) ) ); + + $this->assert_object_schema( $schema, array( 'id' ), $names, 'The item schema' ); + $this->assertSame( array( 'image', 'file' ), $schema['properties']['media_type']['enum'] ?? null, 'The media_type field should be image or file.' ); + $this->assertSame( array( 'string', 'null' ), $schema['properties']['date']['properties']['gmt']['type'] ?? null, 'A date should be nullable.' ); + $this->assertSame( array( 'width', 'height', 'mime_type', 'source_url' ), $schema['properties']['media_details']['properties']['sizes']['additionalProperties']['required'] ?? null, 'A size should require its four keys.' ); + } + + /** + * Asserts the schema of the `fields` input. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + */ + protected function assert_fields_schema( $schema ): void { + $this->assertTrue( $schema['uniqueItems'] ?? null, 'The fields should be unique.' ); + $this->assertSame( self::FIELDS, $schema['items']['enum'] ?? null, 'The fields input should take every field path.' ); + } + + /** + * Asserts the schema of the attributes upload and update take. + * + * @since 7.3.0 + * + * @param mixed $schema The `data` schema. + * @param list $before The property names in front of the attributes. + */ + protected function assert_attributes_schema( $schema, array $before ): void { + $names = array_merge( $before, array( 'title', 'caption', 'description', 'alt_text', 'slug', 'date', 'author', 'post' ) ); + + $this->assert_object_schema( $schema, $before, $names, 'The data schema' ); + $this->assertSame( 1, $schema['properties']['author']['minimum'] ?? null, 'The author should be at least 1.' ); + $this->assertSame( 0, $schema['properties']['post']['minimum'] ?? null, 'The post should be at least 0.' ); + $this->assertSame( 1, $schema['properties']['date']['minProperties'] ?? null, 'The date should need site or gmt.' ); + } + + /** + * Asserts the schema of a `where` that names one attachment by ID. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + */ + protected function assert_where_id_schema( $schema ): void { + $this->assert_object_schema( $schema, array( 'id' ), array( 'id' ), 'The where schema' ); + $this->assertSame( 1, $schema['properties']['id']['minimum'] ?? null, 'The ID should be at least 1.' ); + } + + /** + * Asserts the registration of the ability under test: label, category, `public` meta and + * annotations. + * + * @since 7.3.0 + * + * @param string $label The expected label. + * @param bool $read_only The expected `readonly` annotation. + * @param bool $destructive The expected `destructive` annotation. + * @param bool $idempotent The expected `idempotent` annotation. + */ + protected function assert_registration( string $label, bool $read_only, bool $destructive, bool $idempotent ): void { + $this->register_abilities(); + + $ability = wp_get_ability( static::ABILITY ); + + $this->assertInstanceOf( WP_Ability::class, $ability, 'The ability should be registered.' ); + $this->assertSame( $label, $ability->get_label(), 'The label should match.' ); + $this->assertSame( 'content', $ability->get_category(), 'The ability should be in the content category.' ); + $this->assertTrue( $ability->get_meta_item( 'public', false ), 'The ability should be marked public.' ); + + $annotations = $ability->get_meta_item( 'annotations', array() ); + $this->assertSame( $read_only, $annotations['readonly'] ?? null, 'The readonly annotation should match.' ); + $this->assertSame( $destructive, $annotations['destructive'] ?? null, 'The destructive annotation should match.' ); + $this->assertSame( $idempotent, $annotations['idempotent'] ?? null, 'The idempotent annotation should match.' ); + } + + /** + * Returns authors the author may not set. + * + * @return array The authors, as fixture names. + */ + public static function data_other_authors(): array { + return array( + 'another user' => array( 'editor' ), + 'missing user' => array( 'missing' ), + ); + } + + /** + * Returns dates, with the stored local and GMT dates in New York in winter. + * + * @return array, local: string, gmt: string}> The cases. + */ + public static function data_dates(): array { + return array( + 'site date' => array( array( 'site' => '2099-01-15T10:00:00' ), '2099-01-15 10:00:00', '2099-01-15 15:00:00' ), + 'GMT date' => array( array( 'gmt' => '2099-01-15T15:00:00' ), '2099-01-15 10:00:00', '2099-01-15 15:00:00' ), + 'both' => array( + array( + 'site' => '2099-01-15T10:00:00', + 'gmt' => '2099-01-20T00:00:00', + ), + '2099-01-15 10:00:00', + '2099-01-15 15:00:00', + ), + ); + } + + /** + * Returns save failures with the status of their error. + * + * @return array The cases. + */ + public static function data_save_failures(): array { + return array( + 'empty post' => array( false, 400 ), + 'database error' => array( true, 500 ), + ); + } + + /** + * Returns callers who may upload media and edit an attachment of the author, with whether + * their markup is kept. On single site the editor has `unfiltered_html`; on multisite only + * a super admin has it. + * + * @return array The cases. + */ + public static function data_markup_roles(): array { + if ( is_multisite() ) { + return array( + 'editor' => array( 'editor', false ), + 'author' => array( 'author', false ), + 'super admin' => array( 'administrator', true, true ), + ); + } + + return array( + 'editor' => array( 'editor', true ), + 'author' => array( 'author', false ), + ); + } + + /** + * Returns texts that hold backslashes. + * + * @return array The texts. + */ + public static function data_texts_with_backslashes(): array { + return array( + 'single backslashes' => array( 'C:\\mdt\\x' ), + 'double backslash' => array( 'a\\\\b' ), + ); + } + + /** + * Returns parents of a type that cannot hold attachments. Both belong to the editor, so + * the author may not edit them. + * + * @return array The posts, as fixture names. + */ + public static function data_parents_of_an_invalid_type(): array { + return array( + 'revision' => array( 'revision' ), + 'attachment' => array( 'editor_image' ), + ); + } + + /** + * Returns attributes outside the input schema. + * + * @return array}> The attributes. + */ + public static function data_attributes_outside_the_schema(): array { + return array( + 'author of zero' => array( array( 'author' => 0 ) ), + 'negative author' => array( array( 'author' => -1 ) ), + 'negative post' => array( array( 'post' => -1 ) ), + 'empty date' => array( array( 'date' => array() ) ), + 'ID key' => array( array( 'ID' => 1 ) ), + 'status key' => array( array( 'status' => 'private' ) ), + 'post_mime_type key' => array( array( 'post_mime_type' => 'text/html' ) ), + 'meta_input key' => array( array( 'meta_input' => array( 'mdt_key' => 'value' ) ) ), + ); + } +} diff --git a/tests/phpunit/tests/abilities-api/testcase-media-item-ability.php b/tests/phpunit/tests/abilities-api/testcase-media-item-ability.php new file mode 100644 index 0000000000000..c9ad151060a15 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-media-item-ability.php @@ -0,0 +1,329 @@ + $where The `where` value. + * @return array The input. + */ + abstract protected function build_input( array $where ): array; + + /** + * Creates an attachment row without a file whose author is the shared user with the + * given role or fixture name. + * + * @since 7.3.0 + * + * @param string $role The role or fixture name. + * @return int The attachment ID. + */ + protected function create_attachment_of( string $role ): int { + return self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-own-' . $role . '.jpg', + 'post_author' => self::$user_ids[ $role ], + 'post_status' => 'inherit', + 'post_mime_type' => 'image/jpeg', + 'post_title' => 'Own ' . $role, + ) + ); + } + + /** + * Returns posts that are not attachments, and an ID that names nothing. + * + * @return array The posts, as fixture names. + */ + public static function data_ids_that_name_no_attachment(): array { + return array( + 'post' => array( 'post' ), + 'page' => array( 'page' ), + 'revision' => array( 'revision' ), + 'missing' => array( 'missing' ), + ); + } + + /** + * Returns `where.id` values in forms the integer type accepts, as names for id_in_form(). + * + * @return array The forms. + */ + public static function data_accepted_id_forms(): array { + return array( + 'integer' => array( 'integer' ), + 'integer string' => array( 'string' ), + 'zero-padded string' => array( 'padded' ), + 'float without a part' => array( 'float' ), + ); + } + + /** + * Returns an ID in one of the forms of data_accepted_id_forms(). + * + * @since 7.3.0 + * + * @param int $id The ID. + * @param string $form The form. + * @return int|string|float The ID in that form. + */ + protected function id_in_form( int $id, string $form ) { + switch ( $form ) { + case 'string': + return (string) $id; + case 'padded': + return '00' . $id; + case 'float': + return (float) $id; + default: + return $id; + } + } + + /** + * Returns `where` values the update and delete gates return false for. + * + * @return array The inputs. + */ + public static function data_inputs_without_a_usable_id(): array { + return array( + 'no input' => array( null ), + 'no where' => array( array() ), + 'where string' => array( array( 'where' => 'x' ) ), + 'no ID' => array( array( 'where' => array() ) ), + 'true' => array( array( 'where' => array( 'id' => true ) ) ), + 'letters' => array( array( 'where' => array( 'id' => 'abc' ) ) ), + 'fraction' => array( array( 'where' => array( 'id' => 1.5 ) ) ), + 'fraction string' => array( array( 'where' => array( 'id' => '1.5' ) ) ), + 'list' => array( array( 'where' => array( 'id' => array( 1 ) ) ) ), + 'zero' => array( array( 'where' => array( 'id' => 0 ) ) ), + 'zero string' => array( array( 'where' => array( 'id' => '0' ) ) ), + 'zero-padded zero string' => array( array( 'where' => array( 'id' => '000' ) ) ), + 'zero float' => array( array( 'where' => array( 'id' => 0.0 ) ) ), + 'negative' => array( array( 'where' => array( 'id' => -1 ) ) ), + 'negative float' => array( array( 'where' => array( 'id' => -1.0 ) ) ), + 'float above 2 to the 53' => array( array( 'where' => array( 'id' => 9007199254740994.0 ) ) ), + 'float in exponent format' => array( array( 'where' => array( 'id' => 1e20 ) ) ), + ); + } + + /** + * Returns callers with whether the gate lets them act on an attachment of the author, or + * on their own attachment. + * + * @return array The cases. + */ + public static function data_gate_roles(): array { + return array( + 'logged out' => array( 'logged_out', false ), + 'subscriber' => array( 'subscriber', false ), + 'contributor' => array( 'contributor', false ), + 'no caps' => array( 'no_caps', false ), + 'read and upload' => array( 'uploader', false ), + 'read and upload, own attachment' => array( 'uploader', false, true ), + 'own author' => array( 'author', true ), + 'editor' => array( 'editor', true ), + 'administrator' => array( 'administrator', true ), + ); + } + + /** + * Returns the callers the gate refuses, with the status they get. + * + * @return array The cases. + */ + public static function data_callers_without_the_capability(): array { + $cases = array(); + + foreach ( self::data_gate_roles() as $name => $row ) { + if ( ! $row[1] ) { + $cases[ $name ] = array( $row[0], 'logged_out' === $row[0] ? 401 : 403, $row[2] ?? false ); + } + } + + return $cases; + } + + /** + * The permission callback needs the capability of the ability on the target: `edit_post` + * for an update and `delete_post` for a deletion. + * + * @ticket 66719 + * @dataProvider data_gate_roles + * @since 7.3.0 + * + * @param string $role The role. + * @param bool $expected Whether the gate passes. + * @param bool $own Optional. Whether the target is the caller's own attachment. Default false. + */ + public function test_permission_callback_needs_the_capability( string $role, bool $expected, bool $own = false ): void { + $id = $own ? $this->create_attachment_of( $role ) : self::$post_ids['unattached']; + + $this->login_as( $role ); + $this->register_abilities(); + + $this->assertSame( $expected, wp_get_ability( static::ABILITY )->check_permissions( $this->build_input( array( 'id' => $id ) ) ), 'The gate should follow the capability on the target.' ); + } + + /** + * The permission callback refuses an administrator when the attachment type has + * `show_in_abilities` off, and the call is refused with the generic error. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_permission_callback_refuses_when_attachments_are_hidden(): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + + get_post_type_object( 'attachment' )->show_in_abilities = false; + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $input = $this->build_input( array( 'id' => self::$post_ids['unattached'] ) ); + + $this->assertFalse( wp_get_ability( static::ABILITY )->check_permissions( $input ), 'The administrator should be refused.' ); + $this->assert_refused( $this->run_ability( $input ), 'A call while attachments are hidden' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'Nothing should change.' ); + } + + /** + * A refused caller gets the generic error and nothing changes. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_refused_caller_gets_the_generic_error(): void { + $this->login_as( 'contributor' ); + $this->register_abilities(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + + $this->assert_refused( $this->run_ability( $this->build_input( array( 'id' => self::$post_ids['unattached'] ) ) ), 'A call by a contributor' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'Nothing should change.' ); + } + + /** + * The permission callback passes when the ID names no attachment, so that the call + * answers that nothing was found, and nothing changes. + * + * @ticket 66719 + * @dataProvider data_ids_that_name_no_attachment + * @since 7.3.0 + * + * @param string $post The post, as a fixture name. + */ + public function test_id_that_names_no_attachment_is_not_found( string $post ): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $input = $this->build_input( array( 'id' => self::$post_ids[ $post ] ?? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ) ); + $before = $this->snapshot(); + + $this->assertTrue( wp_get_ability( static::ABILITY )->check_permissions( $input ), 'The gate should pass.' ); + $this->assert_not_found( $this->run_ability( $input ), 'A call for something that is not an attachment' ); + $this->assertSame( $before, $this->snapshot(), 'Nothing should change.' ); + } + + /** + * The permission callback returns false for input without a usable ID. + * + * @ticket 66719 + * @dataProvider data_inputs_without_a_usable_id + * @since 7.3.0 + * + * @param mixed $input The input. + */ + public function test_permission_callback_refuses_input_without_a_usable_id( $input ): void { + $this->login_as( 'administrator' ); + $permission = $this->get_permission_callback(); + + $this->assertFalse( call_user_func( $permission, $input ), 'The gate should refuse input without a usable ID.' ); + } + + /** + * The permission callback returns false for the ID of an attachment the caller may act on + * followed by letters. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_permission_callback_refuses_an_id_followed_by_letters(): void { + $this->login_as( 'administrator' ); + $permission = $this->get_permission_callback(); + + $input = $this->build_input( array( 'id' => self::$post_ids['unattached'] . 'abc' ) ); + + $this->assertFalse( call_user_func( $permission, $input ), 'The gate should refuse an ID followed by letters.' ); + } + + /** + * The permission callback accepts the ID in any form the integer type accepts. + * + * @ticket 66719 + * @dataProvider data_accepted_id_forms + * @since 7.3.0 + * + * @param string $form The form of the ID. + */ + public function test_permission_callback_accepts_id_forms( string $form ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $input = $this->build_input( array( 'id' => $this->id_in_form( self::$post_ids['unattached'], $form ) ) ); + + $this->assertTrue( wp_get_ability( static::ABILITY )->check_permissions( $input ), 'The gate should accept the ID form.' ); + } + + /** + * Returns IDs that are missing or below 1. + * + * @return array}> The `where` values. + */ + public static function data_unusable_ids(): array { + return array( + 'missing' => array( array() ), + 'zero' => array( array( 'id' => 0 ) ), + 'negative' => array( array( 'id' => -1 ) ), + ); + } + + /** + * With the gate and the validation skipped, an ID that is missing or below 1 is not found, + * also when the global post is an attachment the caller may change, and that attachment + * does not change. + * + * @ticket 66719 + * @dataProvider data_unusable_ids + * @since 7.3.0 + * + * @param array $where The `where` value. + */ + public function test_unusable_id_is_not_found( array $where ): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + $this->skip_input_validation(); + $this->force_permission(); + + $GLOBALS['post'] = get_post( self::$post_ids['unattached'] ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- The lookup should not fall back to it. + + $before = $this->snapshot( self::$post_ids['unattached'] ); + + $this->assert_not_found( $this->run_ability( $this->build_input( $where ) ), 'A call with an unusable ID' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'The global post should not change.' ); + } +} diff --git a/tests/phpunit/tests/abilities-api/trait-media-attribute-tests.php b/tests/phpunit/tests/abilities-api/trait-media-attribute-tests.php new file mode 100644 index 0000000000000..1520c48d9576f --- /dev/null +++ b/tests/phpunit/tests/abilities-api/trait-media-attribute-tests.php @@ -0,0 +1,419 @@ + $data The attributes. + * @param string[]|null $fields Optional. The fields. Default null. + * @return mixed The ability result. + */ + abstract protected function write( array $data, ?array $fields = null ); + + /** + * Asserts that a write succeeded and returns the ID of the attachment. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $context What the call was, for the assertion messages. + * @return int The attachment ID. + */ + abstract protected function assert_written( $result, string $context ): int; + + /** + * Takes a snapshot before a write. + * + * @since 7.3.0 + * + * @return array The snapshot. + */ + abstract protected function snapshot_write(): array; + + /** + * Asserts that a refused write changed nothing. + * + * @since 7.3.0 + * + * @param array $before The snapshot before the call. + * @param string $context What the call was, for the assertion messages. + */ + abstract protected function assert_unchanged( array $before, string $context ): void; + + /** + * The attributes are checked in the order author, post, date, slug. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attribute_checks_run_in_order(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $data = array( + 'author' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER, + 'post' => self::$post_ids['revision'], + 'date' => array(), + 'slug' => '!!!', + ); + + foreach ( array( 'author', 'post', 'date', 'slug' ) as $attribute ) { + $this->assert_error_with_params( $this->write( $data ), 'media_invalid_attribute', "data[{$attribute}]", "An invalid {$attribute} first" ); + unset( $data[ $attribute ] ); + } + } + + /** + * The caller's own ID is allowed as the author. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_own_author_id_is_allowed(): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $id = $this->assert_written( $this->write( array( 'author' => self::$user_ids['author'] ) ), 'A write with the own author' ); + $this->assertSame( self::$user_ids['author'], (int) get_post_field( 'post_author', $id ), 'The caller should be the author.' ); + } + + /** + * Another author needs `edit_others_posts`, checked before the user is looked up. + * + * @ticket 66719 + * @dataProvider data_other_authors + * @since 7.3.0 + * + * @param string $author The author, as a fixture name. + */ + public function test_other_author_needs_edit_others_posts( string $author ): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $before = $this->snapshot_write(); + $result = $this->write( array( 'author' => self::$user_ids[ $author ] ?? REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ) ); + + $this->assert_error( $result, 'media_cannot_edit_others', 403, 'A write as another author' ); + $this->assert_error_message( $result, static::OTHER_AUTHOR_MESSAGE, 'A write as another author' ); + $this->assert_unchanged( $before, 'A write as another author' ); + } + + /** + * An author that names no user is an invalid author for a caller who may set authors; + * another existing user is stored. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_author_for_a_caller_who_may_set_authors(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->write( array( 'author' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ) ); + $this->assert_error_with_params( $result, 'media_invalid_attribute', 'data[author]', 'A missing author' ); + $this->assert_error_message( $result, 'Invalid author ID.', 'A missing author' ); + + $id = $this->assert_written( $this->write( array( 'author' => self::$user_ids['author'] ) ), 'A write as another author' ); + $this->assertSame( self::$user_ids['author'], (int) get_post_field( 'post_author', $id ), 'The author sent should be stored.' ); + } + + /** + * A new parent needs `edit_post` on it, checked before it is looked up. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_new_parent_needs_edit_post(): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $before = $this->snapshot_write(); + + foreach ( array( self::$post_ids['post'], REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ) as $post ) { + $result = $this->write( array( 'post' => $post ) ); + + $this->assert_error( $result, 'media_cannot_attach', 403, 'A write to a forbidden parent' ); + $this->assert_error_message( $result, static::ATTACH_MESSAGE, 'A write to a forbidden parent' ); + } + + $this->assert_unchanged( $before, 'A write to a forbidden parent' ); + } + + /** + * A revision or an attachment cannot be the parent. + * + * @ticket 66719 + * @dataProvider data_parents_of_an_invalid_type + * @since 7.3.0 + * + * @param string $post The post, as a fixture name. + */ + public function test_parent_of_an_invalid_type( string $post ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->write( array( 'post' => self::$post_ids[ $post ] ) ); + + $this->assert_error_with_params( $result, 'media_invalid_attribute', 'data[post]', 'A parent of an invalid type' ); + $this->assert_error_message( $result, 'Invalid parent type.', 'A parent of an invalid type' ); + } + + /** + * A parent of an invalid type that the caller may not edit is refused as a missing post + * is, before its type is checked. + * + * @ticket 66719 + * @dataProvider data_parents_of_an_invalid_type + * @since 7.3.0 + * + * @param string $post The post, as a fixture name. + */ + public function test_parent_capability_is_checked_before_the_type( string $post ): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $missing = $this->write( array( 'post' => REST_TESTS_IMPOSSIBLY_HIGH_NUMBER ) ); + $result = $this->write( array( 'post' => self::$post_ids[ $post ] ) ); + + $this->assert_error( $result, 'media_cannot_attach', 403, 'A write to a forbidden parent of an invalid type' ); + $this->assertSame( $missing->get_error_message(), $result->get_error_message(), 'The message should be the one of a missing post.' ); + $this->assertSame( $missing->get_error_data(), $result->get_error_data(), 'The error data should be the one of a missing post.' ); + } + + /** + * The site date is read in the site's time zone and the GMT date in UTC; the site date + * wins when both are sent. + * + * @ticket 66719 + * @dataProvider data_dates + * @since 7.3.0 + * + * @param array $date The date input. + * @param string $local The expected stored local date. + * @param string $gmt The expected stored GMT date. + */ + public function test_date( array $date, string $local, string $gmt ): void { + update_option( 'timezone_string', 'America/New_York' ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $id = $this->assert_written( $this->write( array( 'date' => $date ) ), 'A write with a date' ); + + $this->assertSame( $local, get_post_field( 'post_date', $id ), 'The local date should be stored.' ); + $this->assertSame( $gmt, get_post_field( 'post_date_gmt', $id ), 'The GMT date should be stored.' ); + } + + /** + * A date Core cannot parse is an invalid date. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_unparsable_date_is_invalid(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $this->assert_error_with_params( $this->write( array( 'date' => array( 'gmt' => 'not a date' ) ) ), 'media_invalid_attribute', 'data[date]', 'An unparsable date' ); + } + + /** + * A slug with nothing left after sanitizing is invalid; a taken slug is made unique. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_slug(): void { + self::factory()->post->create( array( 'post_name' => 'mdt-taken-slug' ) ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_error_with_params( $this->write( array( 'slug' => '!!!' ) ), 'media_invalid_attribute', 'data[slug]', 'A slug with nothing left' ); + + $id = $this->assert_written( $this->write( array( 'slug' => 'MDT-Taken-Slug' ) ), 'A write with a taken slug' ); + $slug = get_post_field( 'post_name', $id ); + + $this->assertNotSame( 'mdt-taken-slug', $slug, 'The taken slug should be made unique.' ); + $this->assertStringStartsWith( 'mdt-taken-slug', $slug, 'The unique slug should start with the sanitized slug.' ); + } + + /** + * The alt text is sanitized as a text field, a listener after the save sees it, and an + * empty one is saved as an empty text. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_alt_text(): void { + $seen = array(); + add_action( + 'wp_after_insert_post', + static function ( int $post_id, WP_Post $post ) use ( &$seen ): void { + if ( 'attachment' === $post->post_type ) { + $seen[] = get_post_meta( $post_id, '_wp_attachment_image_alt', true ); + } + }, + 10, + 2 + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $id = $this->assert_written( $this->write( array( 'alt_text' => "MDT\n alt " ) ), 'A write with markup in the alt text' ); + $this->assertSame( array( sanitize_text_field( "MDT\n alt " ) ), $seen, 'The listener should run once and see the sanitized alt text.' ); + $this->assertSame( $seen[0], get_post_meta( $id, '_wp_attachment_image_alt', true ), 'The alt text should be sanitized as a text field.' ); + + $result = $this->write( array( 'alt_text' => '' ), array( 'alt_text' ) ); + $id = $this->assert_written( $result, 'A write with an empty alt text' ); + $this->assertSame( '', $result['alt_text'], 'The output alt text should be empty.' ); + $this->assertSame( '', get_post_meta( $id, '_wp_attachment_image_alt', true ), 'The stored alt text should be empty.' ); + } + + /** + * Markup in the title, caption and description is kept for a caller with + * `unfiltered_html` and filtered for one without it. + * + * @ticket 66719 + * @dataProvider data_markup_roles + * @since 7.3.0 + * + * @param string $role The role. + * @param bool $kept Whether the markup is kept. + * @param bool $super_admin Optional. Whether the caller is a super admin. Default false. + */ + public function test_markup_follows_unfiltered_html( string $role, bool $kept, bool $super_admin = false ): void { + if ( $super_admin ) { + grant_super_admin( self::$user_ids[ $role ] ); + } + + $this->login_as( $role ); + $this->register_abilities(); + + $markup = 'MDT '; + $id = $this->assert_written( + $this->write( + array( + 'title' => $markup, + 'caption' => $markup, + 'description' => $markup, + ) + ), + 'A write with markup' + ); + + foreach ( array( 'post_title', 'post_excerpt', 'post_content' ) as $field ) { + $this->assertSame( $kept, str_contains( get_post_field( $field, $id, 'raw' ), '