From 916a15375c06bcd15675cf64e7110fcb33d4bab0 Mon Sep 17 00:00:00 2001 From: Jorge Costa Date: Fri, 20 Nov 2026 18:13:59 +0000 Subject: [PATCH] Abilities API: Add the `core/media-query`, `core/media-upload`, `core/media-update` and `core/media-delete` abilities. Adds four abilities for attachments. `core/media-query` returns a page of attachments with the totals, filtered by IDs, slugs, status, media type, MIME type, parent post or author. `core/media-upload` stores a file, sent as base64 data or as the URL of an image to download, and creates its attachment. `core/media-update` changes the attributes of an attachment, and `core/media-delete` trashes it or deletes it permanently together with its files. The upload and update abilities return the attachment in the same form as the query. The abilities require a logged-in user, and each call checks the capabilities of the user for the attachment and for the values it sets. See #66719. --- src/wp-includes/abilities.php | 5 + .../abilities/class-wp-abilities-media.php | 2482 +++++++++++++++ .../abilities-api/testcase-media-ability.php | 1177 +++++++ .../wpRegisterCoreMediaAbility.php | 2224 +++++++++++++ .../wpRegisterCoreMediaDeleteAbility.php | 697 ++++ .../wpRegisterCoreMediaUpdateAbility.php | 1528 +++++++++ .../wpRegisterCoreMediaUploadAbility.php | 2821 +++++++++++++++++ .../wpRestAbilitiesMediaController.php | 497 +++ 8 files changed, 11431 insertions(+) create mode 100644 src/wp-includes/abilities/class-wp-abilities-media.php create mode 100644 tests/phpunit/tests/abilities-api/testcase-media-ability.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreMediaAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreMediaDeleteAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreMediaUpdateAbility.php create mode 100644 tests/phpunit/tests/abilities-api/wpRegisterCoreMediaUploadAbility.php create mode 100644 tests/phpunit/tests/rest-api/wpRestAbilitiesMediaController.php 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-media.php b/src/wp-includes/abilities/class-wp-abilities-media.php new file mode 100644 index 0000000000000..fed86f89ad767 --- /dev/null +++ b/src/wp-includes/abilities/class-wp-abilities-media.php @@ -0,0 +1,2482 @@ +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' ); + + /** + * The attributes an upload or an update can write. + * + * @since 7.3.0 + * @var list + */ + private const ATTRIBUTES = array( 'title', 'caption', 'description', 'alt_text', 'slug', 'date', 'author', 'post' ); + + /** + * 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(); + + 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(), + '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(), + '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(), + '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', + '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_rest` 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_rest; + } + + /** + * 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 ) && '' !== $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' ); + if ( empty( $statuses ) || ! empty( array_diff( $statuses, self::STATUSES ) ) ) { + return $this->invalid_filter_error( 'where[status]', __( 'The status filter must list one or more of the statuses inherit, private, and trash.' ) ); + } + + 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 ) ) { + $ids = array_values( array_unique( array_filter( $where['ids'], static fn( $id ) => $id > 0 ) ) ); + if ( empty( $ids ) ) { + return $this->invalid_filter_error( 'where[ids]', __( 'The ids filter must list one or more attachment IDs.' ) ); + } + $query_args['post__in'] = $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_filter_error( 'where[slugs]', __( 'The slugs filter must list one or more attachment slugs.' ) ); + } + $query_args['post_name__in'] = $slugs; + } + + /* + * Intentionally strict: a media type group or a MIME type that selects no type the + * current user may upload cannot be applied, so it is an error instead of matching + * nothing or being dropped. + */ + $allowed_types = array_values( get_allowed_mime_types() ); + $mime_types = array(); + if ( array_key_exists( 'media_type', $where ) ) { + if ( empty( $where['media_type'] ) ) { + return $this->invalid_filter_error( 'where[media_type]', __( 'The media_type filter must list one or more media types.' ) ); + } + foreach ( $where['media_type'] as $group ) { + $group_types = array_filter( $allowed_types, static fn( $type ) => str_starts_with( $type, $group . '/' ) ); + if ( empty( $group_types ) ) { + return $this->invalid_filter_error( 'where[media_type]', __( 'The media_type filter must list media types that have allowed MIME types.' ) ); + } + $mime_types = array_merge( $mime_types, $group_types ); + } + } + + if ( array_key_exists( 'mime_type', $where ) ) { + if ( empty( $where['mime_type'] ) ) { + return $this->invalid_filter_error( 'where[mime_type]', __( 'The mime_type filter must list one or more MIME types.' ) ); + } + foreach ( $where['mime_type'] as $mime_type ) { + if ( ! in_array( $mime_type, $allowed_types, true ) ) { + return $this->invalid_filter_error( 'where[mime_type]', __( 'The mime_type filter must list allowed MIME types.' ) ); + } + $mime_types[] = $mime_type; + } + } + + // With both filters, an attachment matches when it matches either. + 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 ) ) { + if ( $where['post'] < 0 ) { + return $this->invalid_filter_error( 'where[post]', __( 'The post filter must be a non-negative integer.' ) ); + } + $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. + */ + $author_id = null; + if ( array_key_exists( 'author', $where ) ) { + $author = $where['author']; + if ( ! isset( $author['id'] ) && ! isset( $author['slug'] ) ) { + return $this->invalid_filter_error( 'where[author]', __( 'The author filter must be an object with an id or a slug.' ) ); + } + + // An `id` is never looked up: it matches the stored author ID. + if ( isset( $author['id'] ) ) { + $author_id = $author['id']; + if ( $author_id < 1 ) { + return $this->invalid_filter_error( 'where[author][id]', __( 'The author ID must be a positive integer.' ) ); + } + } + + /* + * 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'] ) ) { + if ( '' === $author['slug'] ) { + return $this->invalid_filter_error( 'where[author][slug]', __( 'The author slug must be a non-empty string.' ) ); + } + + $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 = max( 1, $pagination['page'] ?? 1 ); + $per_page = $pagination['per_page'] ?? $default_per_page; + + $query_args['paged'] = $page; + $query_args['posts_per_page'] = $per_page < 1 ? $default_per_page : min( self::MAX_PER_PAGE, $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; + } + + if ( ! isset( $data['file'] ) ) { + return $this->invalid_file_error( 'data[file]', __( 'No data supplied.' ) ); + } + + 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 = isset( $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 ) ) { + $this->remove_stored_file( $stored ); + + 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. + * + * The name, the extension and the URL are checked before anything is requested. The + * only request is made by download_url(), to the URL that passed wp_http_validate_url(), + * and its response is limited to the maximum upload size plus one byte. + * + * @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]'; + $invalid = __( 'Invalid URL. Provide a valid, publicly reachable HTTP or HTTPS image URL.' ); + if ( '' === $url ) { + return $this->invalid_file_error( $param, $invalid ); + } + + // The name is taken from the URL's path as it is, without percent-decoding. + $url_path = (string) wp_parse_url( $url, PHP_URL_PATH ); + $filename = '' === $url_path ? '' : wp_basename( $url_path ); + if ( '' === $filename ) { + return $this->invalid_file_error( $param, __( 'Could not determine a filename from the provided URL.' ) ); + } + + $only_images = __( 'Only images can be uploaded from a URL.' ); + $filetype = wp_check_filetype( $filename ); + if ( ! $filetype['type'] || ! str_starts_with( $filetype['type'], 'image/' ) ) { + return $this->invalid_file_error( $param, $only_images ); + } + + if ( false === wp_http_validate_url( $url ) ) { + return $this->invalid_file_error( $param, $invalid ); + } + + // Intentionally strict: a site without upload space left is refused before any request. + if ( $this->is_space_checked() && get_upload_space_available() < 1 ) { + return new WP_Error( + 'media_quota_exceeded', + __( 'You have used your space quota. Please delete files before uploading.' ), + array( 'status' => 400 ) + ); + } + + /* + * Intentionally strict: a network whose maximum file size is below 1 KB lets no file + * through the size check, so the call is refused before any request. + */ + if ( $this->is_space_checked() ) { + $max_kilobytes = get_site_option( 'fileupload_maxk', 1500 ); + if ( (int) $max_kilobytes < 1 ) { + return $this->invalid_file_error( + $param, + /* translators: %s: Maximum allowed file size in kilobytes. */ + sprintf( __( 'This file is too big. Files must be less than %s KB in size.' ), $max_kilobytes ) + ); + } + } + + /* + * One byte over the maximum is enough to fail the size check below, 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 && is_array( $args ) ) { + $args['limit_response_size'] = $max_size + 1; + } + + return $args; + }; + + $tmp_file = null; + try { + 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 ); + } + + /* + * Intentionally strict: a failed download gives one fixed error, which holds + * nothing of the remote answer or of the error behind it. + */ + if ( is_wp_error( $tmp_file ) ) { + return new WP_Error( 'media_download_failed', __( 'Download failed.' ), array( 'status' => 500 ) ); + } + + $size_error = $this->check_file_size( (int) wp_filesize( $tmp_file ), $max_size, $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, $filename, get_allowed_mime_types() ); + if ( ! $checked['ext'] || ! $checked['type'] || ! str_starts_with( $checked['type'], 'image/' ) ) { + return $this->invalid_file_error( $param, $only_images ); + } + + return $this->store_file( $filename, $tmp_file, $time, $param ); + } finally { + // Of the temporary files, only the one download_url() returned is ever removed. + if ( is_string( $tmp_file ) && file_exists( $tmp_file ) ) { + 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_file_error( $param, __( 'The file data is not valid base64.' ) ); + } + + if ( '' === $bytes ) { + return $this->invalid_file_error( $param, __( 'File is empty. Please upload something more substantial.' ) ); + } + + $size_error = $this->check_file_size( strlen( $bytes ), (int) wp_max_upload_size(), $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 { + if ( file_exists( $tmp_file ) ) { + 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 int $max_size The maximum upload size in bytes, 0 for no limit. + * @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, int $max_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 ( $this->is_space_checked() ) { + $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_file_error( $param, sprintf( $too_big, $max_kilobytes ) ); + } + } + + // Intentionally strict: a file sent as base64 data is held to the maximum upload size too. + if ( $max_size > 0 && $size > $max_size ) { + return $this->invalid_file_error( $param, sprintf( $too_big, number_format( $max_size / KB_IN_BYTES ) ) ); + } + + return null; + } + + /** + * Checks whether the network checks the upload space of its sites. + * + * @since 7.3.0 + * + * @return bool Whether the upload space is checked. + */ + private function is_space_checked(): bool { + return is_multisite() && ! get_site_option( 'upload_space_check_disabled' ); + } + + /** + * 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. While it runs, a callback records whether the stored file is one this + * call created, which {@see self::remove_stored_file()} relies on. + * + * @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, with + * `removable` and `hash` for the cleanup, or a WP_Error. + */ + private function store_file( string $filename, string $tmp_file, ?string $time, string $type_param ) { + /* + * The facts start as those of a file this call did not create, so the file counts as + * removable only when the callback below recorded otherwise. + */ + $move = array( + 'path' => '', + 'existed' => true, + 'taken_over' => true, + 'hash' => '', + ); + + /* + * Records the path the upload handling chose, whether a file was there already, + * whether another callback took over the move, and the bytes that are moved. The + * filtered value is returned unchanged. + */ + $record_move = static function ( $move_new_file, $file, $new_file ) use ( &$move ) { + $move = array( + 'path' => $new_file, + 'existed' => file_exists( $new_file ), + 'taken_over' => null !== $move_new_file, + 'hash' => (string) hash_file( 'sha256', $file['tmp_name'] ), + ); + + return $move_new_file; + }; + + $upload = array( + 'name' => $filename, + 'tmp_name' => $tmp_file, + 'type' => '', + ); + + add_filter( 'pre_move_uploaded_file', $record_move, PHP_INT_MAX, 3 ); + try { + $stored = wp_handle_sideload( $upload, array( 'test_form' => false ), $time ); + } finally { + remove_filter( 'pre_move_uploaded_file', $record_move, PHP_INT_MAX ); + } + + if ( isset( $stored['error'] ) ) { + if ( __( 'Sorry, you are not allowed to upload this file type.' ) === $stored['error'] ) { + return $this->invalid_file_error( $type_param, $stored['error'] ); + } + + return new WP_Error( 'media_upload_failed', $stored['error'], array( 'status' => 500 ) ); + } + + $stored['removable'] = ! $move['existed'] && ! $move['taken_over'] && $move['path'] === $stored['file']; + $stored['hash'] = $move['hash']; + + return $stored; + } + + /** + * Removes a stored file after its attachment could not be saved. + * + * The file is removed only when this call created it: the path did not exist when the + * upload handling chose it, it is the path the upload handling returned, it lies inside + * the uploads folder, and it still holds the bytes this call stored. Otherwise, such as + * when a callback swapped the returned path for an existing file, nothing is removed. + * + * @since 7.3.0 + * + * @param array $stored The stored file from store_file(). + */ + private function remove_stored_file( array $stored ): void { + if ( ! $stored['removable'] || ! is_file( $stored['file'] ) || hash_file( 'sha256', $stored['file'] ) !== $stored['hash'] ) { + return; + } + + wp_delete_file_from_directory( $stored['file'], wp_get_upload_dir()['basedir'] ); + } + + /** + * 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(); + if ( empty( array_intersect_key( $data, array_flip( self::ATTRIBUTES ) ) ) ) { + return $this->invalid_attribute_error( 'data', __( 'The data must be an object with at least one attribute to write.' ) ); + } + + $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 ( true === ( $input['permanent'] ?? false ) ) { + 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, and that same integer is used for the lookup, the capability + * checks, 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; + if ( $id < 1 ) { + return null; + } + + $post = get_post( $id ); + + 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::ATTRIBUTES} 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']; + if ( $author_id < 1 ) { + return $this->invalid_attribute_error( 'author', __( 'Invalid author ID.' ) ); + } + + // 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_attribute_error( 'author', __( 'Invalid author ID.' ) ); + } + } + + $postarr['post_author'] = $author_id; + } + } + + if ( array_key_exists( 'post', $data ) ) { + $parent_id = $data['post']; + if ( $parent_id < ( $attachment ? 0 : 1 ) ) { + return $this->invalid_attribute_error( 'post', __( 'Invalid post ID.' ) ); + } + + // The stored parent sent again needs no capability, also when that post no longer exists. + $is_current = $attachment && (int) $attachment->post_parent === $parent_id; + + // On update, 0 detaches the attachment 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_attribute_error( 'post', __( 'Invalid parent type.' ) ); + } + } + + if ( ! $is_current ) { + $postarr['post_parent'] = $parent_id; + } + } + + if ( array_key_exists( 'date', $data ) ) { + $date = $data['date']; + $dates = null; + 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_attribute_error( 'date', __( 'Invalid date.' ) ); + } + + // On update, a date equal to the stored one counts as not sent. + if ( empty( $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_attribute_error( '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_rest` 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_rest && $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 ] ) ) { + $post_types = array_values( array_filter( get_post_types( array( 'show_in_abilities' => true ), 'names' ), '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 ); + } + 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; + } + + $source_url = wp_get_attachment_url( $post->ID ); + if ( $source_url && rest_is_field_included( 'source_url', $fields ) ) { + $data['source_url'] = $source_url; + } + + $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 = 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 ( $stored_sizes as $name => $size ) { + $name = (string) $name; + if ( ! $full_is_safe || ! $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 ) && $full_is_safe && $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 object without keys is an 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, + ), + ); + } + + /** + * Returns the attachment field definitions, keyed by field name in output order. + * + * The output schema uses the definitions directly, while 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 field definitions. + */ + private function get_item_properties(): 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( + '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', + 'description' => __( 'The kind of attachment: `image` or `file`.' ), + ), + '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 original 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 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. + * + * @since 7.3.0 + * + * @return array The attachment JSON Schema. + */ + private function get_item_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => $this->get_item_properties(), + ); + } + + /** + * Builds the schema of the `fields` input, shared by the query, upload and update abilities. + * + * @since 7.3.0 + * + * @return array The `fields` JSON Schema. + */ + private function get_fields_input_schema(): array { + $paths = array(); + foreach ( $this->get_item_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 + * + * @return array The input JSON Schema. + */ + private function get_query_input_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. A media type without any MIME type the current user may upload is an error.' ), + ), + 'mime_type' => array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'description' => __( 'Filter by one or more MIME types, such as `image/jpeg`. Each must be a MIME type the current user may upload. 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' => $this->get_fields_input_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 + * + * @param int $min_post The smallest `post` value: 1 on upload, 0 on update. + * @return array The attribute schemas, keyed by name. + */ + private function get_attribute_properties( int $min_post ): 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' => $min_post, + 'description' => 0 === $min_post + ? __( 'The ID of the post to attach the attachment to, or 0 to detach it. Requires the capability to edit that post.' ) + : __( 'The ID of the post to attach the attachment to. Requires the capability to edit that post.' ), + ), + ); + } + + /** + * Builds the input schema for the `core/media-upload` ability. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_upload_input_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( 1 ) ), + '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' => $this->get_fields_input_schema(), + ), + ); + } + + /** + * Builds the input schema for the `core/media-update` ability. + * + * @since 7.3.0 + * + * @return array The input JSON Schema. + */ + private function get_update_input_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( 0 ), + 'description' => __( 'The attributes to change. Attributes that are left out keep their stored values.' ), + ), + 'fields' => $this->get_fields_input_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 a filter that cannot be applied. + * + * @since 7.3.0 + * + * @param string $param The filter's input path, such as `where[ids]`. + * @param string $message The error message. + * @return WP_Error The invalid filter error. + */ + private function invalid_filter_error( string $param, string $message ): WP_Error { + return new WP_Error( + 'media_invalid_filter', + $message, + array( + 'status' => 400, + 'params' => array( $param => $message ), + ) + ); + } + + /** + * Builds the error for a `data` attribute that cannot be applied. + * + * @since 7.3.0 + * + * @param string $attribute The attribute name, such as `slug`, or `data` for the whole object. + * @param string $message The error message. + * @return WP_Error The invalid attribute error. + */ + private function invalid_attribute_error( string $attribute, string $message ): WP_Error { + $param = 'data' === $attribute ? 'data' : "data[{$attribute}]"; + + return new WP_Error( + 'media_invalid_attribute', + $message, + array( + 'status' => 400, + 'params' => array( $param => $message ), + ) + ); + } + + /** + * Builds the error for a file that cannot be stored. + * + * @since 7.3.0 + * + * @param string $param The file's input path, such as `data[file][url]`. + * @param string $message The error message. + * @return WP_Error The invalid file error. + */ + private function invalid_file_error( string $param, string $message ): WP_Error { + return new WP_Error( + 'media_invalid_file', + $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/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..3e03d4b3f7ab4 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/testcase-media-ability.php @@ -0,0 +1,1177 @@ + + */ + protected const MEDIA_ABILITIES = array( 'core/media-query', 'core/media-upload', 'core/media-update', 'core/media-delete' ); + + /** + * An ID that no post or user has. + * + * @since 7.3.0 + * + * @var int + */ + protected const MISSING_ID = 987654321; + + /** + * 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(); + + /** + * The requests the faked HTTP transport received, each with its URL and arguments. + * + * @since 7.3.0 + * + * @var list}> + */ + protected $requests = array(); + + /** + * The files in the temporary folder when the test started. + * + * @since 7.3.0 + * + * @var list + */ + private $temp_files_at_start = array(); + + /** + * Files in the temporary folder that tear_down() removes should a call leave them. + * + * @since 7.3.0 + * + * @var list + */ + protected $temp_files_to_remove = 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->requests = array(); + $this->temp_files_to_remove = array(); + + $temp_files = glob( get_temp_dir() . '*' ); + $this->temp_files_at_start = false === $temp_files ? array() : $temp_files; + + $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 or + * left in the temporary 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(); + + foreach ( $this->temp_files_to_remove as $file ) { + if ( file_exists( $file ) ) { + unlink( $file ); + } + } + + /* + * A test may turn off `show_in_rest` 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 callbacks of the ability under test. + * + * The callbacks call private methods, so tests that reach a check behind the permission + * callback capture them from the registration arguments. + * + * @since 7.3.0 + * + * @return array The permission and execute callbacks, keyed by argument name. + */ + protected function get_ability_callbacks(): array { + $ability = static::ABILITY; + $callbacks = array(); + + add_filter( + 'wp_register_ability_args', + static function ( array $args, string $name ) use ( &$callbacks, $ability ): array { + if ( $ability === $name ) { + $callbacks = array( + 'permission_callback' => $args['permission_callback'], + 'execute_callback' => $args['execute_callback'], + ); + } + + return $args; + }, + 10, + 2 + ); + + $this->register_abilities(); + + $this->assertArrayHasKey( 'execute_callback', $callbacks, "The {$ability} ability should be registered with callbacks." ); + + return $callbacks; + } + + /** + * 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 ] ); + } + + /** + * 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, + ) + ); + } + + /** + * 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 `unfiltered_upload` to every user. + * + * @since 7.3.0 + */ + protected function grant_unfiltered_upload(): void { + add_filter( + 'map_meta_cap', + static function ( array $caps, string $cap ): array { + return 'unfiltered_upload' === $cap ? array( 'exist' ) : $caps; + }, + 10, + 2 + ); + } + + /** + * Sets the maximum upload size, after Core's own callbacks on the filter. + * + * @since 7.3.0 + * + * @param int $bytes The maximum size in bytes; 0 means no limit. + */ + protected function set_max_upload_size( int $bytes ): void { + add_filter( + 'upload_size_limit', + static function () use ( $bytes ): int { + return $bytes; + }, + 20 + ); + } + + /** + * 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; + } + + /** + * Returns the temporary files made for a file name since the test started. + * + * @since 7.3.0 + * + * @param string $file_name The file name a test sends, with or without its extension. + * @return list The temporary file paths. + */ + protected function list_temp_files( string $file_name ): array { + $base = preg_replace( '/\.[^.]*$/', '', wp_basename( $file_name ) ); + $files = glob( get_temp_dir() . $base . '-*' ); + + return false === $files ? array() : array_values( array_diff( $files, $this->temp_files_at_start ) ); + } + + /** + * 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, the temporary files of a file + * name 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. + * @param string $file_name Optional. The file name of the call. Default empty. + * @return array The snapshot. + */ + protected function snapshot( ?int $post_id = null, string $file_name = '' ): 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 ( '' !== $file_name ) { + $snapshot['temp'] = $this->list_temp_files( $file_name ); + } + + 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; + } + + /** + * Returns a URL on the site's own host, which the URL check accepts without a lookup. + * + * @since 7.3.0 + * + * @param string $file_name The file name at the end of the path. + * @return string The URL. + */ + protected function remote_url( string $file_name ): string { + return 'http://' . wp_parse_url( home_url(), PHP_URL_HOST ) . '/mdt-remote/' . $file_name; + } + + /** + * Fakes the HTTP transport. Every request is recorded and answered without the network. + * + * Each response is keyed by URL and is a `WP_Error`, or an array with any of `file` (a + * fixture path written to the download), `body` (a string written to the download), + * `code` (default 200), `headers` (default none) and `during` (a callable run while the + * download runs). A request for any other URL gets an empty 200 response. + * + * @since 7.3.0 + * + * @param array> $responses The responses, keyed by URL. + */ + protected function fake_http( array $responses = array() ): void { + add_filter( + 'pre_http_request', + function ( $pre, $args, $url ) use ( $responses ) { + $this->requests[] = array( + 'url' => $url, + 'args' => $args, + ); + + $response = $responses[ $url ] ?? array(); + + if ( $response instanceof WP_Error ) { + return $response; + } + + if ( isset( $response['during'] ) ) { + call_user_func( $response['during'] ); + } + + $body = null; + if ( isset( $response['file'] ) ) { + $body = file_get_contents( $response['file'] ); + } elseif ( isset( $response['body'] ) ) { + $body = $response['body']; + } + + if ( null !== $body && ! empty( $args['stream'] ) && ! empty( $args['filename'] ) ) { + if ( ! empty( $args['limit_response_size'] ) ) { + $body = substr( $body, 0, (int) $args['limit_response_size'] ); + } + + file_put_contents( $args['filename'], $body ); + } + + $code = $response['code'] ?? 200; + + return array( + 'headers' => $response['headers'] ?? array(), + 'body' => '', + 'response' => array( + 'code' => $code, + 'message' => get_status_header_desc( $code ), + ), + 'cookies' => array(), + 'filename' => $args['filename'] ?? null, + ); + }, + 10, + 3 + ); + } + + /** + * Returns the requests the faked transport received for a URL. + * + * @since 7.3.0 + * + * @param string $url The URL. + * @return list> The arguments of each request. + */ + protected function requests_for( string $url ): array { + $found = array(); + + foreach ( $this->requests as $request ) { + if ( $url === $request['url'] ) { + $found[] = $request['args']; + } + } + + return $found; + } + + /** + * 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 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 ); + } + + /** + * Removes the `description` keywords of a schema at every depth, keeping a property + * named `description`, turns objects into arrays and sorts the keys of every map, so + * that two schemas compare by content. + * + * @since 7.3.0 + * + * @param mixed $schema The schema. + * @return mixed The normalized schema. + */ + protected function normalize_schema( $schema ) { + if ( is_object( $schema ) ) { + $schema = get_object_vars( $schema ); + } + + if ( ! is_array( $schema ) ) { + return $schema; + } + + if ( ! wp_is_numeric_array( $schema ) || array() === $schema ) { + if ( isset( $schema['description'] ) && is_string( $schema['description'] ) ) { + unset( $schema['description'] ); + } + ksort( $schema ); + } + + foreach ( $schema as $key => $value ) { + $schema[ $key ] = $this->normalize_schema( $value ); + } + + return $schema; + } + + /** + * Returns the schema of the `fields` input, which query, upload and update share. + * + * @since 7.3.0 + * + * @return array The schema. + */ + protected static function fields_schema(): array { + return array( + 'type' => 'array', + 'uniqueItems' => true, + 'items' => array( + 'type' => 'string', + 'enum' => self::FIELDS, + ), + ); + } + + /** + * Returns the schema of a `{ site, gmt }` date in the output. + * + * @since 7.3.0 + * + * @return array The schema. + */ + private static function output_date_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'site' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + ), + 'gmt' => array( + 'type' => array( 'string', 'null' ), + 'format' => 'date-time', + ), + ), + ); + } + + /** + * Returns the schema of a `{ raw, rendered }` text in the output. + * + * @since 7.3.0 + * + * @return array The schema. + */ + private static function output_text_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'raw' => array( 'type' => 'string' ), + 'rendered' => array( 'type' => 'string' ), + ), + ); + } + + /** + * Returns the schema of a media item in the output. + * + * @since 7.3.0 + * + * @return array The schema. + */ + protected static function item_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( 'type' => 'integer' ), + 'status' => array( 'type' => 'string' ), + 'date' => self::output_date_schema(), + 'modified' => self::output_date_schema(), + 'slug' => array( 'type' => 'string' ), + 'link' => array( + 'type' => 'string', + 'format' => 'uri', + ), + 'title' => self::output_text_schema(), + 'caption' => self::output_text_schema(), + 'description' => self::output_text_schema(), + 'alt_text' => array( 'type' => 'string' ), + 'media_type' => array( 'type' => 'string' ), + 'mime_type' => array( 'type' => 'string' ), + 'source_url' => array( + 'type' => 'string', + 'format' => 'uri', + ), + 'filename' => array( 'type' => 'string' ), + 'filesize' => array( 'type' => 'integer' ), + 'media_details' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'width' => array( 'type' => 'integer' ), + 'height' => array( 'type' => 'integer' ), + 'length' => array( 'type' => 'integer' ), + 'sizes' => array( + 'type' => 'object', + 'additionalProperties' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'width', 'height', 'mime_type', 'source_url' ), + 'properties' => array( + 'width' => array( 'type' => 'integer' ), + 'height' => array( 'type' => 'integer' ), + 'mime_type' => array( 'type' => 'string' ), + 'source_url' => array( + 'type' => 'string', + 'format' => 'uri', + ), + ), + ), + ), + ), + ), + 'post' => array( 'type' => 'integer' ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'id' => array( 'type' => 'integer' ), + 'name' => array( 'type' => array( 'string', 'null' ) ), + 'slug' => array( 'type' => array( 'string', 'null' ) ), + ), + ), + ), + ); + } + + /** + * Returns the schema of the attributes upload and update take. + * + * @since 7.3.0 + * + * @param int $post_minimum The minimum of `post`. + * @return array The schemas, keyed by attribute. + */ + protected static function attribute_schemas( int $post_minimum ): array { + return array( + 'title' => array( 'type' => 'string' ), + 'caption' => array( 'type' => 'string' ), + 'description' => array( 'type' => 'string' ), + 'alt_text' => array( 'type' => 'string' ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + ), + 'date' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'site' => array( + 'type' => 'string', + 'format' => 'date-time', + ), + 'gmt' => array( + 'type' => 'string', + 'format' => 'date-time', + ), + ), + ), + 'author' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + 'post' => array( + 'type' => 'integer', + 'minimum' => $post_minimum, + ), + ); + } + + /** + * Returns the schema of a `where` that names one attachment by ID. + * + * @since 7.3.0 + * + * @return array The schema. + */ + protected static function where_id_schema(): array { + return array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'id' ), + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 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 roles without `upload_files`. + * + * @return array The roles. + */ + public static function data_roles_without_upload_files(): array { + return array( + 'logged out' => array( 'logged_out' ), + 'subscriber' => array( 'subscriber' ), + 'contributor' => array( 'contributor' ), + 'no caps' => array( 'no_caps' ), + ); + } + + /** + * Returns roles with `upload_files`. + * + * @return array The roles. + */ + public static function data_roles_with_upload_files(): array { + return array( + 'author' => array( 'author' ), + 'editor' => array( 'editor' ), + 'administrator' => array( 'administrator' ), + 'read and upload' => array( 'uploader' ), + ); + } + + /** + * Returns every role of the matrix tests. + * + * @return array The roles. + */ + public static function data_all_roles(): array { + return array( + 'logged out' => array( 'logged_out' ), + 'subscriber' => array( 'subscriber' ), + 'contributor' => array( 'contributor' ), + 'author' => array( 'author' ), + 'editor' => array( 'editor' ), + 'administrator' => array( 'administrator' ), + 'read and upload' => array( 'uploader' ), + ); + } + + /** + * 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 whether the site can move attachments to the Trash. + * + * @since 7.3.0 + * + * @return bool Whether attachments can be trashed. + */ + protected static function site_can_trash_attachments(): bool { + return EMPTY_TRASH_DAYS >= 1 && MEDIA_TRASH; + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaAbility.php new file mode 100644 index 0000000000000..f31286d8362bc --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaAbility.php @@ -0,0 +1,2224 @@ +> + */ + private const EMPTY_RESULT = array( + 'items' => array(), + 'pagination' => array( + 'total' => 0, + 'total_pages' => 0, + ), + ); + + /** + * Creates the shared fixtures, and the attachments of the order and paging tests. + * + * @since 7.3.0 + * + * @param WP_UnitTest_Factory $factory The unit test factory. + */ + public static function wpSetUpBeforeClass( WP_UnitTest_Factory $factory ): void { + self::create_shared_fixtures( $factory ); + + $order_parent = $factory->post->create( array( 'post_author' => self::$user_ids['editor'] ) ); + $dates = array( + 'order_a' => '2022-02-02 10:00:00', + 'order_b' => '2022-02-02 10:00:00', + 'order_c' => '2022-03-03 10:00:00', + 'order_d' => '2022-01-01 10:00:00', + ); + + self::$post_ids['order_parent'] = $order_parent; + foreach ( $dates as $name => $date ) { + self::$post_ids[ $name ] = $factory->attachment->create_object( + array( + 'file' => "2026/01/mdt-{$name}.jpg", + 'post_parent' => $order_parent, + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['editor'], + 'post_date' => $date, + ) + ); + } + + $paging_parent = $factory->post->create( array( 'post_author' => self::$user_ids['editor'] ) ); + self::$post_ids['paging_parent'] = $paging_parent; + for ( $i = 1; $i <= 11; $i++ ) { + self::$post_ids[ "paging_{$i}" ] = $factory->attachment->create_object( + array( + 'file' => "2026/01/mdt-paging-{$i}.jpg", + 'post_parent' => $paging_parent, + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['editor'], + ) + ); + } + + self::$post_ids['no_posts_author_image'] = $factory->attachment->create_object( + array( + 'file' => '2026/01/mdt-no-posts-author.jpg', + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['author_without_posts'], + ) + ); + } + + /** + * Runs the query and returns the IDs of the items. + * + * @since 7.3.0 + * + * @param array $input The input. + * @return list The item IDs. + */ + private function query_ids( array $input ): array { + $input['fields'] = array( 'id' ); + $result = $this->run_ability( $input ); + + $this->assertIsArray( $result, 'The query should succeed.' ); + + return wp_list_pluck( $result['items'], 'id' ); + } + + /** + * Returns the item of one attachment, with the given fields. + * + * @since 7.3.0 + * + * @param int $id The attachment ID. + * @param list|null $fields The fields, or null for the defaults. + * @param list $status Optional. The statuses to query. Default `inherit`. + * @return array The item. + */ + private function query_item( int $id, ?array $fields, array $status = array( 'inherit' ) ): array { + $input = array( + 'where' => array( + 'ids' => array( $id ), + 'status' => $status, + ), + ); + + if ( null !== $fields ) { + $input['fields'] = $fields; + } + + $result = $this->run_ability( $input ); + + $this->assertIsArray( $result, 'The query should succeed.' ); + $this->assertCount( 1, $result['items'], 'The query should return the attachment.' ); + + return $result['items'][0]; + } + + /** + * The ability is registered with its label, category, meta and annotations. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_registers_the_query_ability(): void { + $this->assert_registration( 'Query Media', true, false, true ); + } + + /** + * The input schema is the published one. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_input_schema(): void { + $this->register_abilities(); + + $list = static function ( array $items, ?int $max_items = null ): array { + $schema = array( + 'type' => 'array', + 'uniqueItems' => true, + 'minItems' => 1, + 'items' => $items, + ); + + if ( null !== $max_items ) { + $schema['maxItems'] = $max_items; + } + + return $schema; + }; + + $expected = array( + 'type' => 'object', + 'default' => array(), + 'additionalProperties' => false, + 'properties' => array( + 'where' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'ids' => $list( + array( + 'type' => 'integer', + 'minimum' => 1, + ), + 100 + ), + 'slugs' => $list( + array( + 'type' => 'string', + 'minLength' => 1, + ), + 100 + ), + 'status' => $list( + array( + 'type' => 'string', + 'enum' => array( 'inherit', 'private', 'trash' ), + ) + ), + 'media_type' => $list( + array( + 'type' => 'string', + 'enum' => array( 'application', 'audio', 'image', 'text', 'video' ), + ) + ), + 'mime_type' => $list( + array( + 'type' => 'string', + 'minLength' => 1, + ) + ), + 'post' => array( + 'type' => 'integer', + 'minimum' => 0, + ), + 'author' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => array( + 'id' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + 'slug' => array( + 'type' => 'string', + 'minLength' => 1, + ), + ), + ), + ), + ), + 'fields' => self::fields_schema(), + 'pagination' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'properties' => array( + 'page' => array( + 'type' => 'integer', + 'minimum' => 1, + ), + 'per_page' => array( + 'type' => 'integer', + 'minimum' => 1, + 'maximum' => 100, + ), + ), + ), + ), + ); + + $this->assertSame( + $this->normalize_schema( $expected ), + $this->normalize_schema( wp_get_ability( self::ABILITY )->get_input_schema() ), + 'The input schema should match.' + ); + } + + /** + * The output schema is the published one. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_output_schema(): void { + $this->register_abilities(); + + $expected = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'items', 'pagination' ), + 'properties' => array( + 'items' => array( + 'type' => 'array', + 'items' => self::item_schema(), + ), + 'pagination' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'total', 'total_pages' ), + 'properties' => array( + 'total' => array( 'type' => 'integer' ), + 'total_pages' => array( 'type' => 'integer' ), + ), + ), + ), + ); + + $this->assertSame( + $this->normalize_schema( $expected ), + $this->normalize_schema( wp_get_ability( self::ABILITY )->get_output_schema() ), + 'The output schema should match.' + ); + } + + /** + * Returns logged-in roles. + * + * @return array The roles. + */ + public static function data_logged_in_roles(): array { + $roles = self::data_all_roles(); + unset( $roles['logged out'] ); + $roles['role without capabilities'] = array( 'no_caps' ); + + return $roles; + } + + /** + * The permission callback passes for every logged-in caller, whatever the status filter. + * + * @ticket 66719 + * @dataProvider data_logged_in_roles + * @since 7.3.0 + * + * @param string $role The role. + */ + public function test_permission_callback_passes_for_a_logged_in_caller( string $role ): void { + $this->login_as( $role ); + $this->register_abilities(); + + $ability = wp_get_ability( self::ABILITY ); + + $this->assertTrue( $ability->check_permissions( array() ), 'The permission callback should pass without input.' ); + $this->assertTrue( $ability->check_permissions( array( 'where' => array( 'status' => array( 'trash' ) ) ) ), 'The permission callback should not look at the status filter.' ); + } + + /** + * The permission callback refuses a logged-out caller, and a call when the attachment type + * has `show_in_rest` off. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_permission_callback_refuses_logged_out_callers_and_hidden_attachments(): void { + $this->register_abilities(); + $ability = wp_get_ability( self::ABILITY ); + + $this->login_as( 'logged_out' ); + $this->assertFalse( $ability->check_permissions( array() ), 'A logged-out caller should be refused.' ); + + $this->login_as( 'administrator' ); + get_post_type_object( 'attachment' )->show_in_rest = false; + $this->assertFalse( $ability->check_permissions( array() ), 'An administrator should be refused when the attachment type has show_in_rest off.' ); + } + + /** + * A logged-out call is refused with the generic error, and input the schema refuses is + * answered before the permission callback. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_generic_errors(): void { + $this->login_as( 'logged_out' ); + $this->register_abilities(); + + $this->assert_refused( $this->run_ability( array() ), 'A logged-out query' ); + + $invalid = $this->run_ability( array( 'pagination' => array( 'per_page' => 0 ) ) ); + $this->assertWPError( $invalid, 'An invalid query should fail.' ); + $this->assertSame( 'ability_invalid_input', $invalid->get_error_code(), 'Invalid input should be answered before the permission callback.' ); + } + + /** + * Without a status filter only attachments in the `inherit` status are listed. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_default_status_is_inherit(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['private'], self::$post_ids['trashed'] ), + ), + ) + ); + + $this->assertSame( array( self::$post_ids['unattached'] ), $ids, 'Only the attachment in the inherit status should be listed.' ); + } + + /** + * Returns status filters with the roles that may and may not use them. + * + * @return array, allowed: bool}> The cases. + */ + public static function data_status_filters(): array { + return array( + 'subscriber, inherit' => array( 'subscriber', array( 'inherit' ), true ), + 'subscriber, private' => array( 'subscriber', array( 'private' ), false ), + 'subscriber, trash' => array( 'subscriber', array( 'trash' ), false ), + 'subscriber, inherit, private' => array( 'subscriber', array( 'inherit', 'private' ), false ), + 'read and upload, private' => array( 'uploader', array( 'private' ), false ), + 'read and upload, trash' => array( 'uploader', array( 'trash' ), false ), + 'contributor, private' => array( 'contributor', array( 'private' ), true ), + 'contributor, trash' => array( 'contributor', array( 'trash' ), true ), + 'author, inherit, private' => array( 'author', array( 'inherit', 'private' ), true ), + 'editor, all statuses' => array( 'editor', array( 'inherit', 'private', 'trash' ), true ), + 'administrator, trash' => array( 'administrator', array( 'trash' ), true ), + ); + } + + /** + * A status filter needs `read_private_posts` or `edit_posts` for `private` and + * `edit_posts` for `trash`; one status the caller may not use refuses the call, and a + * caller who may use a status gets the attachments in that status. + * + * @ticket 66719 + * @dataProvider data_status_filters + * @since 7.3.0 + * + * @param string $role The role. + * @param list $status The status filter. + * @param bool $allowed Whether the caller may use it. + */ + public function test_status_filter_capabilities( string $role, array $status, bool $allowed ): void { + $own = array(); + if ( $allowed ) { + foreach ( $status as $own_status ) { + $own[] = self::factory()->attachment->create_object( + array( + 'file' => "2026/01/mdt-own-{$own_status}.jpg", + 'post_status' => $own_status, + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids[ $role ], + ) + ); + } + } + + $this->login_as( $role ); + $this->register_abilities(); + + $result = $this->run_ability( + array( + 'where' => array( + 'status' => $status, + 'ids' => array() === $own ? array( self::$post_ids['unattached'] ) : $own, + ), + ) + ); + + if ( $allowed ) { + $this->assertIsArray( $result, 'The caller should be allowed to filter by these statuses.' ); + $this->assertSameSets( $own, wp_list_pluck( $result['items'], 'id' ), 'The attachments in the allowed statuses should be listed.' ); + return; + } + + $this->assert_error( $result, 'media_cannot_filter_by_status', 403, 'A forbidden status filter' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to filter media by this status.', 'A forbidden status filter' ); + } + + /** + * The status filter lists the attachments in the requested statuses. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_status_filter_selects_statuses(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = array( self::$post_ids['unattached'], self::$post_ids['private'], self::$post_ids['trashed'] ); + + $this->assertSame( + array( self::$post_ids['trashed'] ), + $this->query_ids( + array( + 'where' => array( + 'ids' => $ids, + 'status' => array( 'trash' ), + ), + ) + ), + 'The trash filter should list only the trashed attachment.' + ); + $this->assertSameSets( + array( self::$post_ids['unattached'], self::$post_ids['private'] ), + $this->query_ids( + array( + 'where' => array( + 'ids' => $ids, + 'status' => array( 'inherit', 'private' ), + ), + ) + ), + 'The inherit and private filter should list both attachments.' + ); + } + + /** + * Returns status lists that hold a value outside the status set. + * + * @return array}> The cases. + */ + public static function data_statuses_outside_the_set(): array { + return array( + 'subscriber, publish' => array( 'subscriber', array( 'publish' ) ), + 'subscriber, trash and bogus' => array( 'subscriber', array( 'trash', 'mdt_bogus' ) ), + 'editor, bogus' => array( 'editor', array( 'mdt_bogus' ) ), + 'editor, inherit and draft' => array( 'editor', array( 'inherit', 'draft' ) ), + ); + } + + /** + * A status outside the status set is an invalid filter for every caller, before the + * capabilities are checked. + * + * @ticket 66719 + * @dataProvider data_statuses_outside_the_set + * @since 7.3.0 + * + * @param string $role The role. + * @param list $status The status filter. + */ + public function test_status_outside_the_set_is_an_invalid_filter( string $role, array $status ): void { + $this->login_as( $role ); + $this->register_abilities(); + $this->skip_input_validation(); + + $result = $this->run_ability( array( 'where' => array( 'status' => $status ) ) ); + + $this->assert_error_with_params( $result, 'media_invalid_filter', 'where[status]', 'A status outside the set' ); + } + + /** + * The status filter is checked before any other filter. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_status_is_checked_before_other_filters(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $forbidden = $this->run_ability( + array( + 'where' => array( + 'status' => array( 'trash' ), + 'mime_type' => array( 'mdt/not-allowed' ), + ), + ) + ); + $this->assert_error( $forbidden, 'media_cannot_filter_by_status', 403, 'A forbidden status next to an invalid MIME type' ); + + $invalid = $this->run_ability( + array( + 'where' => array( + 'status' => array( 'mdt_bogus' ), + 'ids' => array(), + ), + ) + ); + $this->assert_error_with_params( $invalid, 'media_invalid_filter', 'where[status]', 'A status outside the set next to an empty ID list' ); + } + + /** + * IDs select attachments; an ID of another post type or of nothing matches nothing. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_ids_select_attachments_only(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['pdf'], self::$post_ids['post'], self::$post_ids['page'], self::MISSING_ID ), + ), + ) + ); + + $this->assertSameSets( array( self::$post_ids['unattached'], self::$post_ids['pdf'] ), $ids, 'Only the attachments should be listed.' ); + } + + /** + * Slugs are sanitized as post slugs; a slug of nothing matches nothing. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_slugs_are_sanitized_as_post_slugs(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-team-photo.jpg', + 'post_name' => 'mdt-team-photo', + 'post_mime_type' => 'image/jpeg', + ) + ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( array( $id ), $this->query_ids( array( 'where' => array( 'slugs' => array( 'MDT-Team-Photo', 'mdt-no-such-slug' ) ) ) ), 'The slug should match after sanitizing.' ); + $this->assertSame( self::EMPTY_RESULT, $this->run_ability( array( 'where' => array( 'slugs' => array( 'mdt-no-such-slug' ) ) ) ), 'A slug of nothing should match nothing.' ); + } + + /** + * A media type selects the allowed types of its group, and several groups add up. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_type_selects_groups(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = array( self::$post_ids['unattached'], self::$post_ids['pdf'], self::$post_ids['audio'] ); + + $this->assertSame( + array( self::$post_ids['pdf'] ), + $this->query_ids( + array( + 'where' => array( + 'ids' => $ids, + 'media_type' => array( 'application' ), + ), + ) + ), + 'The application group should select the PDF.' + ); + $this->assertSameSets( + array( self::$post_ids['unattached'], self::$post_ids['audio'] ), + $this->query_ids( + array( + 'where' => array( + 'ids' => $ids, + 'media_type' => array( 'image', 'audio' ), + ), + ) + ), + 'The image and audio groups should select the image and the audio file.' + ); + } + + /** + * A media type group without any allowed type is an invalid filter. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_type_without_allowed_types_is_an_invalid_filter(): void { + add_filter( + 'upload_mimes', + static function ( array $mimes ): array { + return array_filter( + $mimes, + static function ( string $mime ): bool { + return ! str_starts_with( $mime, 'video/' ); + } + ); + } + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->run_ability( array( 'where' => array( 'media_type' => array( 'image', 'video' ) ) ) ); + + $this->assert_error_with_params( $result, 'media_invalid_filter', 'where[media_type]', 'A media type without allowed types' ); + } + + /** + * A MIME type selects attachments of exactly that type. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_mime_type_selects_exact_types(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['pdf'], self::$post_ids['audio'] ), + 'mime_type' => array( 'application/pdf', 'audio/mpeg' ), + ), + ) + ); + + $this->assertSameSets( array( self::$post_ids['pdf'], self::$post_ids['audio'] ), $ids, 'The MIME types should select the PDF and the audio file.' ); + } + + /** + * Returns MIME types that are not exactly one of the allowed types. + * + * @return array The MIME types. + */ + public static function data_mime_types_that_are_not_allowed(): array { + return array( + 'alias' => array( 'image/jpg' ), + 'group only' => array( 'image' ), + 'wildcard' => array( 'image/*' ), + 'not allowed' => array( 'application/x-php' ), + 'upper case' => array( 'IMAGE/JPEG' ), + ); + } + + /** + * A MIME type that is not exactly one of the allowed types is an invalid filter. + * + * @ticket 66719 + * @dataProvider data_mime_types_that_are_not_allowed + * @since 7.3.0 + * + * @param string $mime_type The MIME type. + */ + public function test_mime_type_that_is_not_allowed_is_an_invalid_filter( string $mime_type ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->run_ability( array( 'where' => array( 'mime_type' => array( 'image/jpeg', $mime_type ) ) ) ); + + $this->assert_error_with_params( $result, 'media_invalid_filter', 'where[mime_type]', 'A MIME type that is not allowed' ); + } + + /** + * A media type and a MIME type together select the attachments that match either. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_type_and_mime_type_together_are_a_union(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['pdf'], self::$post_ids['audio'] ), + 'media_type' => array( 'audio' ), + 'mime_type' => array( 'application/pdf' ), + ), + ) + ); + + $this->assertSameSets( array( self::$post_ids['pdf'], self::$post_ids['audio'] ), $ids, 'Either filter should select an attachment.' ); + } + + /** + * A post filter selects the attachments of that post, and 0 selects unattached ones. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_post_filter_selects_the_attachments_of_a_post(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( array( self::$post_ids['attached'] ), $this->query_ids( array( 'where' => array( 'post' => self::$post_ids['post'] ) ) ), 'The post filter should select the attachment of the post.' ); + + $unattached = $this->query_ids( + array( + 'where' => array( + 'post' => 0, + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['attached'] ), + ), + ) + ); + $this->assertSame( array( self::$post_ids['unattached'] ), $unattached, 'A post filter of 0 should select the unattached attachment.' ); + } + + /** + * Returns post filters that list nothing, with the totals they give. + * + * @return array The posts, as fixture names, and the totals. + */ + public static function data_post_filters_that_select_nothing(): array { + return array( + 'missing post' => array( + 'missing', + array( + 'total' => 0, + 'total_pages' => 0, + ), + ), + 'post without attachments' => array( + 'page', + array( + 'total' => 0, + 'total_pages' => 0, + ), + ), + 'private post' => array( + 'private_post', + array( + 'total' => 1, + 'total_pages' => 1, + ), + ), + 'attachment' => array( + 'unattached', + array( + 'total' => 0, + 'total_pages' => 0, + ), + ), + ); + } + + /** + * A post that does not exist, has no attachments or whose attachments the caller cannot + * read lists no attachment and no error, with the given totals. + * + * @ticket 66719 + * @dataProvider data_post_filters_that_select_nothing + * @since 7.3.0 + * + * @param string $post The post, as a fixture name. + * @param array{total: int, total_pages: int} $pagination The expected totals. + */ + public function test_post_filter_that_selects_nothing( string $post, array $pagination ): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $result = $this->run_ability( + array( + 'where' => array( 'post' => self::$post_ids[ $post ] ?? self::MISSING_ID ), + 'fields' => array( 'id' ), + ) + ); + + $this->assertIsArray( $result, 'The query should succeed.' ); + $this->assertSame( array(), $result['items'], 'No attachment should be listed.' ); + $this->assertSame( $pagination['total'], $result['pagination']['total'] ?? null, "The total should be {$pagination['total']}." ); + $this->assertSame( $pagination['total_pages'], $result['pagination']['total_pages'] ?? null, "The total pages should be {$pagination['total_pages']}." ); + } + + /** + * An author filter with an ID matches the stored author, without a lookup of the user. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_author_id_filter(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $ids = array( self::$post_ids['unattached'], self::$post_ids['editor_image'] ); + + $this->assertSame( + array( self::$post_ids['editor_image'] ), + $this->query_ids( + array( + 'where' => array( + 'ids' => $ids, + 'author' => array( 'id' => self::$user_ids['editor'] ), + ), + ) + ), + 'The author ID should select the attachment of that user.' + ); + $this->assertSame( + self::EMPTY_RESULT, + $this->run_ability( array( 'where' => array( 'author' => array( 'id' => self::MISSING_ID ) ) ) ), + 'The ID of no user should match nothing.' + ); + } + + /** + * An author filter with a slug matches the attachments of a user the caller may see. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_author_slug_filter_for_a_visible_user(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['editor_image'] ), + 'author' => array( 'slug' => get_userdata( self::$user_ids['editor'] )->user_nicename ), + ), + ) + ); + + $this->assertSame( array( self::$post_ids['editor_image'] ), $ids, 'The slug of a user with published posts should select that user\'s attachment.' ); + } + + /** + * Returns author filters that match nothing for a subscriber. + * + * @return array The filters, as cases. + */ + public static function data_author_filters_that_match_nothing(): array { + return array( + 'slug of no user' => array( 'slug_of_nobody' ), + 'slug of a user the caller may not see' => array( 'slug_of_invisible_user' ), + 'ID and slug of different users' => array( 'id_and_other_slug' ), + ); + } + + /** + * A slug of no user or of a user the caller may not see, and an ID and a slug of + * different users, match nothing and give zeros. + * + * @ticket 66719 + * @dataProvider data_author_filters_that_match_nothing + * @since 7.3.0 + * + * @param string $filter The filter, as a case name. + */ + public function test_author_filter_that_matches_nothing( string $filter ): void { + $filters = array( + 'slug_of_nobody' => array( 'slug' => 'mdt-nobody' ), + 'slug_of_invisible_user' => array( 'slug' => get_userdata( self::$user_ids['author_without_posts'] )->user_nicename ), + 'id_and_other_slug' => array( + 'id' => self::$user_ids['editor'], + 'slug' => get_userdata( self::$user_ids['author'] )->user_nicename, + ), + ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( self::EMPTY_RESULT, $this->run_ability( array( 'where' => array( 'author' => $filters[ $filter ] ) ) ), 'The author filter should match nothing.' ); + } + + /** + * Filters combine with AND. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_filters_combine_with_and(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'ids' => array( self::$post_ids['unattached'], self::$post_ids['pdf'], self::$post_ids['editor_image'] ), + 'media_type' => array( 'image' ), + 'author' => array( 'id' => self::$user_ids['author'] ), + ), + ) + ); + + $this->assertSame( array( self::$post_ids['unattached'] ), $ids, 'Only the attachment that matches every filter should be listed.' ); + } + + /** + * Items are ordered by date, newest first, then by ID, highest first, also across pages. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_order_is_date_then_id_descending(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $expected = array( self::$post_ids['order_c'], self::$post_ids['order_b'], self::$post_ids['order_a'], self::$post_ids['order_d'] ); + $where = array( 'post' => self::$post_ids['order_parent'] ); + + $this->assertSame( $expected, $this->query_ids( array( 'where' => $where ) ), 'The items should be ordered by date, then ID.' ); + + $page_1 = $this->query_ids( + array( + 'where' => $where, + 'pagination' => array( + 'per_page' => 2, + 'page' => 1, + ), + ) + ); + $page_2 = $this->query_ids( + array( + 'where' => $where, + 'pagination' => array( + 'per_page' => 2, + 'page' => 2, + ), + ) + ); + + $this->assertSame( array_slice( $expected, 0, 2 ), $page_1, 'The first page should hold the first two items.' ); + $this->assertSame( array_slice( $expected, 2, 2 ), $page_2, 'The second page should hold the next two items.' ); + } + + /** + * Attachments of the same date are ordered by ID, highest first, also when the query + * holds more than one status. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_same_date_is_ordered_by_id_descending(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( + array( + 'where' => array( + 'status' => array( 'inherit', 'private' ), + 'post' => self::$post_ids['order_parent'], + ), + ) + ); + + $this->assertSame( + array( self::$post_ids['order_c'], self::$post_ids['order_b'], self::$post_ids['order_a'], self::$post_ids['order_d'] ), + $ids, + 'Attachments of the same date should be ordered by ID, highest first.' + ); + } + + /** + * Rows of another post type that another callback adds to the rows of the query are + * never listed. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_rows_of_another_post_type_are_never_listed(): void { + $page = get_post( self::$post_ids['page'] ); + add_filter( + 'the_posts', + static function ( array $posts ) use ( $page ): array { + $posts[] = $page; + return $posts; + } + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $ids = $this->query_ids( array( 'where' => array( 'post' => self::$post_ids['order_parent'] ) ) ); + + $this->assertNotContains( self::$post_ids['page'], $ids, 'The added page should not be listed.' ); + $this->assertSame( array( 'attachment' ), array_values( array_unique( array_map( 'get_post_type', $ids ) ) ), 'Only attachments should be listed.' ); + } + + /** + * A page holds 10 items by default, and 100 when IDs or slugs are sent. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_per_page_defaults(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $all = array(); + for ( $i = 1; $i <= 11; $i++ ) { + $all[] = self::$post_ids[ "paging_{$i}" ]; + } + + $result = $this->run_ability( + array( + 'where' => array( 'post' => self::$post_ids['paging_parent'] ), + 'fields' => array( 'id' ), + ) + ); + + $this->assertCount( 10, $result['items'], 'A page should hold 10 items by default.' ); + $this->assertSame( + array( + 'total' => 11, + 'total_pages' => 2, + ), + $result['pagination'], + 'The pagination should count every match.' + ); + + $this->assertCount( 11, $this->query_ids( array( 'where' => array( 'ids' => $all ) ) ), 'A page should hold up to 100 items when IDs are sent.' ); + + $slugs = array_map( + static function ( int $id ): string { + return get_post_field( 'post_name', $id ); + }, + $all + ); + $this->assertCount( 11, $this->query_ids( array( 'where' => array( 'slugs' => $slugs ) ) ), 'A page should hold up to 100 items when slugs are sent.' ); + } + + /** + * Returns attachments with the roles that may and may not read them. + * + * @return array The cases. + */ + public static function data_row_check(): array { + return array( + 'unattached, subscriber' => array( 'unattached', 'subscriber', true ), + 'attached to a published post, subscriber' => array( 'attached', 'subscriber', true ), + 'attached to a published post, no capabilities' => array( 'attached', 'no_caps', true ), + 'attached to a private post, subscriber' => array( 'private_parent', 'subscriber', false ), + 'attached to a private post, contributor' => array( 'private_parent', 'contributor', false ), + 'attached to a private post, editing role' => array( 'private_parent', 'other_editor', false ), + 'attached to a private post, editor' => array( 'private_parent', 'editor', true ), + ); + } + + /** + * The row check lists an attachment only when the caller may read it. + * + * @ticket 66719 + * @dataProvider data_row_check + * @since 7.3.0 + * + * @param string $attachment The attachment, as a fixture name. + * @param string $role The role. + * @param bool $readable Whether the caller may read it. + */ + public function test_row_check( string $attachment, string $role, bool $readable ): void { + $this->login_as( $role ); + $this->register_abilities(); + + $ids = $this->query_ids( array( 'where' => array( 'ids' => array( self::$post_ids[ $attachment ] ) ) ) ); + + $this->assertSame( $readable ? array( self::$post_ids[ $attachment ] ) : array(), $ids, 'The attachment should be listed only when the caller may read it.' ); + } + + /** + * A private attachment is listed for its author and for a caller with + * `read_private_posts`, and not for another contributor. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_private_attachments_are_listed_for_callers_who_may_read_them(): void { + $own = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-own-private.jpg', + 'post_status' => 'private', + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['contributor'], + ) + ); + + $this->register_abilities(); + $input = array( + 'where' => array( + 'ids' => array( $own, self::$post_ids['private'] ), + 'status' => array( 'private' ), + ), + 'fields' => array( 'id' ), + ); + + $this->login_as( 'contributor' ); + $contributor = $this->run_ability( $input ); + + $this->assertSame( array( $own ), wp_list_pluck( $contributor['items'], 'id' ), 'The contributor should see only their own private attachment.' ); + $this->assertSame( 1, $contributor['pagination']['total'], 'The total should leave out the private attachment of another user.' ); + + $this->login_as( 'editor' ); + $editor = $this->run_ability( $input ); + + $this->assertSameSets( array( $own, self::$post_ids['private'] ), wp_list_pluck( $editor['items'], 'id' ), 'The editor should see both private attachments.' ); + $this->assertSame( 2, $editor['pagination']['total'], 'The total should count both private attachments for the editor.' ); + } + + /** + * An attachment whose parent no longer exists counts as unattached and is listed. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attachment_whose_parent_no_longer_exists_is_listed(): void { + global $wpdb; + + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-orphan.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + $wpdb->update( $wpdb->posts, array( 'post_parent' => self::MISSING_ID ), array( 'ID' => $id ) ); + clean_post_cache( $id ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( array( $id ), $this->query_ids( array( 'where' => array( 'ids' => array( $id ) ) ) ), 'An attachment of a missing parent should be listed.' ); + } + + /** + * An attachment whose parent has a public status other than `publish` is listed for a + * caller without any capability. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attachment_of_a_parent_in_a_public_custom_status_is_listed(): void { + register_post_status( + 'mdt_public_archive', + array( + 'label' => 'Public archive', + 'public' => true, + ) + ); + + $parent = self::factory()->post->create( + array( + 'post_status' => 'mdt_public_archive', + 'post_author' => self::$user_ids['editor'], + ) + ); + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-public-archive.jpg', + 'post_parent' => $parent, + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['editor'], + ) + ); + + $this->login_as( 'no_caps' ); + $this->register_abilities(); + + $ids = $this->query_ids( array( 'where' => array( 'ids' => array( $id ) ) ) ); + + _unregister_post_status( 'mdt_public_archive' ); + + $this->assertSame( array( $id ), $ids, 'An attachment of a parent in a public status should be listed.' ); + } + + /** + * An attachment of a published post is listed for a caller without any capability only + * while the parent's type has `show_in_rest` on. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attachment_of_a_published_post_needs_the_parent_type_shown(): void { + $this->login_as( 'no_caps' ); + $this->register_abilities(); + + $input = array( 'where' => array( 'ids' => array( self::$post_ids['attached'] ) ) ); + + $this->assertSame( array( self::$post_ids['attached'] ), $this->query_ids( $input ), 'The attachment should be listed while the post type has show_in_rest on.' ); + + get_post_type_object( 'post' )->show_in_rest = false; + + $this->assertSame( array(), $this->query_ids( $input ), 'The attachment should not be listed while the post type has show_in_rest off.' ); + } + + /** + * Two attachments that are each other's parent end the query without an error and are + * not listed. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attachments_in_a_parent_loop_are_not_listed(): void { + global $wpdb; + + $first = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-loop-1.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + $second = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-loop-2.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + $wpdb->update( $wpdb->posts, array( 'post_parent' => $second ), array( 'ID' => $first ) ); + $wpdb->update( $wpdb->posts, array( 'post_parent' => $first ), array( 'ID' => $second ) ); + clean_post_cache( $first ); + clean_post_cache( $second ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $result = $this->run_ability( + array( + 'where' => array( 'ids' => array( $first, $second ) ), + 'fields' => array( 'id' ), + ) + ); + + $this->assertNotWPError( $result, 'A parent loop should not make the query fail.' ); + $this->assertSame( array(), $result['items'], 'No attachment of the loop should be listed.' ); + } + + /** + * An attachment that is its own parent counts as unattached and is listed. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_attachment_that_is_its_own_parent_is_listed(): void { + global $wpdb; + + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-self-parent.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + $wpdb->update( $wpdb->posts, array( 'post_parent' => $id ), array( 'ID' => $id ) ); + clean_post_cache( $id ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( array( $id ), $this->query_ids( array( 'where' => array( 'ids' => array( $id ) ) ) ), 'An attachment that is its own parent should be listed.' ); + } + + /** + * The total counts an attachment the row check withholds, so a page can hold fewer items + * than the total. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_total_counts_a_withheld_attachment(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $result = $this->run_ability( + array( + 'where' => array( 'ids' => array( self::$post_ids['private_parent'], self::$post_ids['unattached'] ) ), + 'fields' => array( 'id' ), + ) + ); + + $this->assertSame( array( self::$post_ids['unattached'] ), wp_list_pluck( $result['items'], 'id' ), 'Only the readable attachment should be listed.' ); + $this->assertSame( + array( + 'total' => 2, + 'total_pages' => 1, + ), + $result['pagination'], + 'The total should count the withheld attachment.' + ); + } + + /** + * When nothing matches every page is empty; a page past the last one is an error when + * something matches. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_pages_past_the_end(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $this->assertSame( + self::EMPTY_RESULT, + $this->run_ability( + array( + 'where' => array( 'ids' => array( self::MISSING_ID ) ), + 'pagination' => array( 'page' => 3 ), + ) + ), + 'Every page of a query that matches nothing should be empty.' + ); + + $result = $this->run_ability( + array( + 'where' => array( 'ids' => array( self::$post_ids['unattached'] ) ), + 'pagination' => array( 'page' => 2 ), + ) + ); + + $this->assert_error( $result, 'media_invalid_page_number', 404, 'A page past the last one' ); + $this->assert_error_message( $result, 'The page number requested is larger than the number of pages available.', 'A page past the last one' ); + } + + /** + * Returns `where` values that a callback receives only when validation is skipped, with + * the path of the error. + * + * @return array, path: string}> The cases. + */ + public static function data_unusable_filter_values(): array { + return array( + 'empty ID list' => array( array( 'ids' => array() ), 'where[ids]' ), + 'ID list of zero' => array( array( 'ids' => array( 0 ) ), 'where[ids]' ), + 'empty slug list' => array( array( 'slugs' => array() ), 'where[slugs]' ), + 'slug list of nothing' => array( array( 'slugs' => array( '' ) ), 'where[slugs]' ), + 'empty status list' => array( array( 'status' => array() ), 'where[status]' ), + 'empty media type list' => array( array( 'media_type' => array() ), 'where[media_type]' ), + 'empty MIME type list' => array( array( 'mime_type' => array() ), 'where[mime_type]' ), + 'post below zero' => array( array( 'post' => -1 ), 'where[post]' ), + 'empty author' => array( array( 'author' => array() ), 'where[author]' ), + 'author ID of zero' => array( array( 'author' => array( 'id' => 0 ) ), 'where[author][id]' ), + 'empty author slug' => array( array( 'author' => array( 'slug' => '' ) ), 'where[author][slug]' ), + ); + } + + /** + * With validation skipped, a filter value that cannot be applied is an invalid filter. + * + * @ticket 66719 + * @dataProvider data_unusable_filter_values + * @since 7.3.0 + * + * @param array $where The filters. + * @param string $path The path of the error. + */ + public function test_unusable_filter_value_is_an_invalid_filter( array $where, string $path ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $this->assert_error_with_params( $this->run_ability( array( 'where' => $where ) ), 'media_invalid_filter', $path, 'An unusable filter value' ); + } + + /** + * Returns `fields` values that select the default fields. + * + * @return array|null}> The values. + */ + public static function data_default_field_inputs(): array { + return array( + 'no fields' => array( null ), + 'empty fields' => array( array() ), + ); + } + + /** + * Without fields, an item holds the default fields, with only the rendered title; an + * empty field list counts as not sent. + * + * @ticket 66719 + * @dataProvider data_default_field_inputs + * @since 7.3.0 + * + * @param list|null $fields The fields, or null to send none. + */ + public function test_default_fields( ?array $fields ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $id = self::$post_ids['unattached']; + $item = $this->query_item( $id, $fields ); + + $this->assertSameSets( self::DEFAULT_KEYS, array_keys( $item ), 'The item should hold the default fields.' ); + $this->assertSame( array( 'rendered' ), array_keys( $item['title'] ), 'The title should hold only the rendered value.' ); + $this->assertSame( $id, $item['id'], 'The ID should be the attachment ID.' ); + $this->assertSame( 'inherit', $item['status'], 'The status should be the stored one.' ); + $this->assertSame( 'image', $item['media_type'], 'The media type should be image.' ); + $this->assertSame( 'image/jpeg', $item['mime_type'], 'The MIME type should be the stored one.' ); + $this->assertSame( wp_get_attachment_url( $id ), $item['source_url'], 'The source URL should be the attachment URL.' ); + } + + /** + * Returns field lists with the keys and sub-keys they select for an editor. + * + * @return array, expected: array|null>}> The cases. + */ + public static function data_field_selections(): array { + return array( + 'ID only' => array( array( 'id' ), array( 'id' => null ) ), + 'title' => array( + array( 'title' ), + array( + 'id' => null, + 'title' => array( 'raw', 'rendered' ), + ), + ), + 'raw title' => array( + array( 'title.raw' ), + array( + 'id' => null, + 'title' => array( 'raw' ), + ), + ), + 'dates' => array( + array( 'date.gmt', 'modified' ), + array( + 'id' => null, + 'date' => array( 'gmt' ), + 'modified' => array( 'site', 'gmt' ), + ), + ), + 'author slug' => array( + array( 'author.slug', 'post' ), + array( + 'id' => null, + 'author' => array( 'slug' ), + 'post' => null, + ), + ), + 'every top-level key' => array( + array( 'link', 'caption', 'description', 'alt_text', 'filename', 'author' ), + array( + 'id' => null, + 'link' => null, + 'caption' => array( 'raw', 'rendered' ), + 'description' => array( 'raw', 'rendered' ), + 'alt_text' => null, + 'filename' => null, + 'author' => array( 'id', 'name', 'slug' ), + ), + ), + ); + } + + /** + * `fields` selects exactly the keys and sub-keys asked for, next to the ID. + * + * @ticket 66719 + * @dataProvider data_field_selections + * @since 7.3.0 + * + * @param list $fields The fields. + * @param array|null> $expected The expected keys, with their sub-keys. + */ + public function test_fields_select_exact_keys( array $fields, array $expected ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( self::$post_ids['unattached'], $fields ); + + $this->assertSameSets( array_keys( $expected ), array_keys( $item ), 'The item should hold exactly the selected keys.' ); + foreach ( $expected as $key => $sub_keys ) { + if ( null !== $sub_keys ) { + $this->assertSameSets( $sub_keys, array_keys( $item[ $key ] ), "The {$key} key should hold exactly the selected sub-keys." ); + } + } + } + + /** + * Raw values need `edit_post` on the item; an object left without any sub-field is left + * out. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_raw_values_need_edit_post(): void { + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $id = self::$post_ids['editor_image']; + + $item = $this->query_item( $id, array( 'title', 'caption', 'description' ) ); + $this->assertSame( array( 'rendered' ), array_keys( $item['title'] ), 'The title should hold only the rendered value.' ); + $this->assertSame( array( 'rendered' ), array_keys( $item['caption'] ), 'The caption should hold only the rendered value.' ); + $this->assertSame( array( 'rendered' ), array_keys( $item['description'] ), 'The description should hold only the rendered value.' ); + + $this->assertSame( array( 'id' ), array_keys( $this->query_item( $id, array( 'title.raw' ) ) ), 'A title left without a sub-field should be left out.' ); + } + + /** + * Rendered values: the title without a status prefix, an empty caption as an excerpt of + * the description, and the description through the content filters, with the global post + * the same after the call. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_rendered_values(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-rendered.jpg', + 'post_status' => 'private', + 'post_mime_type' => 'image/jpeg', + 'post_author' => self::$user_ids['editor'], + 'post_title' => 'Secret title', + 'post_excerpt' => '', + 'post_content' => 'Description words.', + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $GLOBALS['post'] = get_post( self::$post_ids['post'] ); + $global_before = $GLOBALS['post']; + + $item = $this->query_item( $id, array( 'title.rendered', 'caption.rendered', 'description.rendered' ), array( 'private' ) ); + + $this->assertSame( $global_before, $GLOBALS['post'], 'The global post should be the same after the call.' ); + $this->assertSame( 'Secret title', $item['title']['rendered'], 'The rendered title should have no status prefix.' ); + $this->assertStringContainsString( 'Description words.', $item['caption']['rendered'], 'An empty caption should render an excerpt of the description.' ); + + $rendered = $item['description']['rendered']; + $this->assertStringContainsString( '

', $rendered, 'The rendered description should hold the attachment markup.' ); + $this->assertLessThan( strpos( $rendered, 'Description words.' ), strpos( $rendered, '

' ), 'The attachment markup should come before the text.' ); + } + + /** + * Core's title prefixes work as before after a call that returns rendered titles. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_title_prefixes_work_after_the_call(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $private_before = has_filter( 'private_title_format' ); + $protected_before = has_filter( 'protected_title_format' ); + + $this->query_item( self::$post_ids['private'], array( 'title.rendered' ), array( 'private' ) ); + + $this->assertSame( $private_before, has_filter( 'private_title_format' ), 'The private title format filter should have the callbacks it had before.' ); + $this->assertSame( $protected_before, has_filter( 'protected_title_format' ), 'The protected title format filter should have the callbacks it had before.' ); + $this->assertStringStartsWith( 'Private: ', get_the_title( self::$post_ids['private_post'] ), 'The title of a private post should still have the prefix.' ); + } + + /** + * Stored values are returned as stored: status, slug, MIME type, link, alt text, parent + * and the media type. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_stored_values(): void { + update_post_meta( self::$post_ids['attached'], '_wp_attachment_image_alt', 'Stored alt' ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $fields = array( 'status', 'slug', 'mime_type', 'link', 'alt_text', 'post', 'media_type' ); + $attached = $this->query_item( self::$post_ids['attached'], $fields ); + $pdf = $this->query_item( self::$post_ids['pdf'], $fields ); + + $this->assertSame( 'inherit', $attached['status'], 'The status should be the stored one.' ); + $this->assertSame( get_post_field( 'post_name', self::$post_ids['attached'] ), $attached['slug'], 'The slug should be the stored one.' ); + $this->assertSame( get_permalink( self::$post_ids['attached'] ), $attached['link'], 'The link should be the permalink.' ); + $this->assertSame( 'Stored alt', $attached['alt_text'], 'The alt text should be the stored one.' ); + $this->assertSame( self::$post_ids['post'], $attached['post'], 'The post should be the parent ID.' ); + $this->assertSame( 'image', $attached['media_type'], 'An image should have the media type image.' ); + $this->assertSame( 'application/pdf', $pdf['mime_type'], 'The MIME type should be the stored one.' ); + $this->assertSame( '', $pdf['alt_text'], 'A missing alt text should be an empty string.' ); + $this->assertSame( 0, $pdf['post'], 'An unattached attachment should have the post 0.' ); + $this->assertSame( 'file', $pdf['media_type'], 'A PDF should have the media type file.' ); + } + + /** + * The file name and file size are left out when the attachment has no file, and the + * source URL is then the attachment's GUID. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_file_keys_are_left_out_without_a_file(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '', + 'post_mime_type' => 'image/jpeg', + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( $id, array( 'source_url', 'filename', 'filesize' ) ); + + $this->assertSameSets( array( 'id', 'source_url' ), array_keys( $item ), 'The file name and file size should be left out.' ); + $this->assertNotEmpty( get_the_guid( $id ), 'The attachment should have a GUID.' ); + $this->assertSame( get_the_guid( $id ), $item['source_url'], 'The source URL should be the GUID.' ); + $this->assertSame( wp_get_attachment_url( $id ), $item['source_url'], 'The source URL should be the attachment URL.' ); + } + + /** + * The source URL is left out when the attachment URL is false. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_source_url_is_left_out_when_the_attachment_url_is_false(): void { + add_filter( 'wp_get_attachment_url', '__return_empty_string' ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assertFalse( wp_get_attachment_url( self::$post_ids['unattached'] ), 'The attachment URL should be false.' ); + + $item = $this->query_item( self::$post_ids['unattached'], array( 'source_url' ) ); + + $this->assertSame( array( 'id' ), array_keys( $item ), 'The source URL should be left out.' ); + } + + /** + * The media details hold only the width, height, length and sizes, as integers, with a + * full size next to the sub-sizes; a size that lacks a value is left out. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_details_from_the_stored_metadata(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-meta.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + wp_update_attachment_metadata( + $id, + array( + 'width' => '640', + 'height' => 480, + 'length' => '12', + 'file' => '2026/01/mdt-meta.jpg', + 'filesize' => 1234, + 'sizes' => array( + 'thumbnail' => array( + 'file' => 'mdt-meta-150x150.jpg', + 'width' => 150, + 'height' => 150, + 'mime-type' => 'image/jpeg', + ), + 'broken' => array( + 'file' => 'mdt-meta-broken.jpg', + 'width' => 10, + 'mime-type' => 'image/jpeg', + ), + ), + 'image_meta' => array( 'title' => 'Not returned' ), + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $details = $this->query_item( $id, array( 'media_details' ) )['media_details']; + + $this->assertSameSets( array( 'width', 'height', 'length', 'sizes' ), array_keys( $details ), 'The media details should hold only the width, height, length and sizes.' ); + $this->assertSame( 640, $details['width'], 'The width should be an integer.' ); + $this->assertSame( 480, $details['height'], 'The height should be an integer.' ); + $this->assertSame( 12, $details['length'], 'The length should be an integer.' ); + $this->assertSameSets( array( 'thumbnail', 'full' ), array_keys( (array) $details['sizes'] ), 'The sizes should hold the complete sub-size and the full size.' ); + + $sizes = (array) $details['sizes']; + $this->assertSame( + array( + 'width' => 150, + 'height' => 150, + 'mime_type' => 'image/jpeg', + 'source_url' => dirname( wp_get_attachment_url( $id ) ) . '/mdt-meta-150x150.jpg', + ), + (array) $sizes['thumbnail'], + 'The sub-size should hold its width, height, MIME type and URL.' + ); + $this->assertSame( + array( + 'width' => 640, + 'height' => 480, + 'mime_type' => 'image/jpeg', + 'source_url' => wp_get_attachment_url( $id ), + ), + (array) $sizes['full'], + 'The full size should hold the width, height, MIME type and URL of the file.' + ); + } + + /** + * A stored sub-size without a file is left out, and the call succeeds without a PHP + * warning or notice. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_sub_size_without_a_file_is_left_out(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-meta-no-file.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + wp_update_attachment_metadata( + $id, + array( + 'width' => 640, + 'height' => 480, + 'file' => '2026/01/mdt-meta-no-file.jpg', + 'sizes' => array( + 'thumbnail' => array( + 'file' => 'mdt-meta-no-file-150x150.jpg', + 'width' => 150, + 'height' => 150, + 'mime-type' => 'image/jpeg', + ), + 'medium' => array( + 'width' => 300, + 'height' => 225, + 'mime-type' => 'image/jpeg', + ), + ), + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $details = $this->query_item( $id, array( 'media_details' ) )['media_details']; + + $this->assertSameSets( array( 'thumbnail', 'full' ), array_keys( (array) $details['sizes'] ), 'The sub-size without a file should be left out.' ); + } + + /** + * When the only stored sub-size is incomplete, it is left out and the full size is still + * added, without a PHP warning or notice. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_full_size_is_added_when_the_only_sub_size_is_left_out(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-meta-only-broken.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + wp_update_attachment_metadata( + $id, + array( + 'width' => 640, + 'height' => 480, + 'file' => '2026/01/mdt-meta-only-broken.jpg', + 'sizes' => array( + 'thumbnail' => array( + 'file' => 'mdt-meta-only-broken-150x150.jpg', + 'width' => 150, + 'mime-type' => 'image/jpeg', + ), + ), + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $details = $this->query_item( $id, array( 'media_details' ) )['media_details']; + + $this->assertSame( array( 'full' ), array_keys( (array) $details['sizes'] ), 'The sizes should hold exactly the full size.' ); + } + + /** + * For a file that is not an image, every size is left out when the stored full size + * lacks its height, and the call succeeds without a PHP warning or notice. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_sizes_of_a_file_whose_full_size_lacks_a_height_are_left_out(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-meta-document.pdf', + 'post_mime_type' => 'application/pdf', + ) + ); + wp_update_attachment_metadata( + $id, + array( + 'filesize' => 7175, + 'sizes' => array( + 'full' => array( + 'file' => 'mdt-meta-document-pdf.jpg', + 'width' => 1088, + 'mime-type' => 'image/jpeg', + ), + 'thumbnail' => array( + 'file' => 'mdt-meta-document-pdf-116x150.jpg', + 'width' => 116, + 'height' => 150, + 'mime-type' => 'image/jpeg', + ), + ), + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $details = $this->query_item( $id, array( 'media_details' ) )['media_details']; + + $this->assertArrayHasKey( 'sizes', (array) $details, 'The media details should hold the sizes.' ); + $this->assert_empty_object( $details['sizes'], 'Every size should be left out.' ); + } + + /** + * The sizes are an empty object without sub-sizes, and the media details are an empty + * object without metadata. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_details_without_sizes_or_metadata(): void { + $with_meta = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-no-sizes.jpg', + 'post_mime_type' => 'image/jpeg', + ) + ); + wp_update_attachment_metadata( + $with_meta, + array( + 'width' => 10, + 'height' => 10, + 'file' => '2026/01/mdt-no-sizes.jpg', + 'sizes' => array(), + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $details = $this->query_item( $with_meta, array( 'media_details' ) )['media_details']; + $this->assert_empty_object( $details['sizes'], 'The sizes should be an empty object without sub-sizes.' ); + + $without = $this->query_item( self::$post_ids['unattached'], array( 'media_details' ) ); + $this->assert_empty_object( $without['media_details'], 'The media details should be an empty object without metadata.' ); + } + + /** + * Without metadata, the media details asked for only through a sub-path are left out. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_media_details_asked_for_through_a_sub_path_are_left_out_without_metadata(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( self::$post_ids['unattached'], array( 'media_details.sizes' ) ); + + $this->assertSame( array( 'id' ), array_keys( $item ), 'The item should hold only the ID.' ); + } + + /** + * Dates are returned as a site date and a GMT date. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_dates(): void { + $id = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-dates.jpg', + 'post_mime_type' => 'image/jpeg', + 'post_date' => '2021-03-04 05:06:07', + 'post_date_gmt' => '2021-03-04 10:06:07', + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( $id, array( 'date' ) ); + + $this->assertStringStartsWith( '2021-03-04T05:06:07', $item['date']['site'], 'The site date should be the stored date.' ); + $this->assertStringStartsWith( '2021-03-04T10:06:07', $item['date']['gmt'], 'The GMT date should be the stored GMT date.' ); + } + + /** + * Returns the date fields with their columns. + * + * @return array The cases. + */ + public static function data_date_columns(): array { + return array( + 'date' => array( 'date', 'post_date', 'post_date_gmt' ), + 'modified' => array( 'modified', 'post_modified', 'post_modified_gmt' ), + ); + } + + /** + * Without a stored GMT date, the GMT date is derived from the site date. + * + * @ticket 66719 + * @dataProvider data_date_columns + * @since 7.3.0 + * + * @param string $field The output field. + * @param string $column The site date column. + * @param string $gmt_column The GMT date column. + */ + public function test_gmt_date_is_derived_from_the_site_date( string $field, string $column, string $gmt_column ): void { + global $wpdb; + + update_option( 'timezone_string', '' ); + update_option( 'gmt_offset', 2 ); + + $id = self::factory()->attachment->create_object( + array( + 'file' => "2026/01/mdt-derived-{$field}.jpg", + 'post_mime_type' => 'image/jpeg', + ) + ); + $wpdb->update( + $wpdb->posts, + array( + $column => '2021-03-04 05:06:07', + $gmt_column => '0000-00-00 00:00:00', + ), + array( 'ID' => $id ) + ); + clean_post_cache( $id ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( $id, array( $field ) ); + + $this->assertStringStartsWith( '2021-03-04T05:06:07', $item[ $field ]['site'], 'The site date should be the stored site date.' ); + $this->assertStringStartsWith( '2021-03-04T03:06:07', $item[ $field ]['gmt'], 'The GMT date should be derived from the site date.' ); + } + + /** + * Without either stored column, the site and GMT dates are null. + * + * @ticket 66719 + * @dataProvider data_date_columns + * @since 7.3.0 + * + * @param string $field The output field. + * @param string $column The site date column. + * @param string $gmt_column The GMT date column. + */ + public function test_dates_are_null_without_a_stored_date( string $field, string $column, string $gmt_column ): void { + global $wpdb; + + $id = self::factory()->attachment->create_object( + array( + 'file' => "2026/01/mdt-no-{$field}.jpg", + 'post_mime_type' => 'image/jpeg', + ) + ); + $wpdb->update( + $wpdb->posts, + array( + $column => '0000-00-00 00:00:00', + $gmt_column => '0000-00-00 00:00:00', + ), + array( 'ID' => $id ) + ); + clean_post_cache( $id ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $item = $this->query_item( $id, array( $field ) ); + + $this->assertSame( + array( + 'site' => null, + 'gmt' => null, + ), + $item[ $field ], + 'The site and GMT dates should be null without a stored date.' + ); + } + + /** + * Returns viewers and authors, with whether the viewer may see the author. + * + * @return array The cases. + */ + public static function data_author_visibility(): array { + return array( + 'subscriber, user with published posts' => array( 'subscriber', 'editor_image', 'editor', true ), + 'subscriber, user without posts' => array( 'subscriber', 'no_posts_author_image', 'author_without_posts', false ), + 'administrator, user without posts' => array( 'administrator', 'no_posts_author_image', 'author_without_posts', true ), + 'the user themself' => array( 'author_without_posts', 'no_posts_author_image', 'author_without_posts', true ), + ); + } + + /** + * The author's ID is always returned; the name and slug only when the caller may see the + * user. + * + * @ticket 66719 + * @dataProvider data_author_visibility + * @since 7.3.0 + * + * @param string $viewer The role of the caller. + * @param string $attachment The attachment, as a fixture name. + * @param string $author The author, as a fixture name. + * @param bool $visible Whether the caller may see the author. + */ + public function test_author_visibility( string $viewer, string $attachment, string $author, bool $visible ): void { + $this->login_as( $viewer ); + $this->register_abilities(); + + $user = get_userdata( self::$user_ids[ $author ] ); + $expected = array( + 'id' => $user->ID, + 'name' => $visible ? $user->display_name : null, + 'slug' => $visible ? $user->user_nicename : null, + ); + + $item = $this->query_item( self::$post_ids[ $attachment ], array( 'author' ) ); + + $this->assertSame( $expected, $item['author'], 'The author should be named only when the caller may see the user.' ); + } + + /** + * Returns post types the only published post of an author can be in without making the + * author visible. + * + * @return array}> The post type arguments. + */ + public static function data_post_types_that_do_not_show_the_author(): array { + return array( + 'public, not exposed to abilities' => array( + array( + 'public' => true, + 'show_in_abilities' => false, + ), + ), + 'exposed to abilities, not viewable' => array( + array( + 'public' => false, + 'show_in_abilities' => true, + ), + ), + ); + } + + /** + * A published post in a post type that is not exposed to abilities or not viewable does + * not make its author visible. + * + * @ticket 66719 + * @dataProvider data_post_types_that_do_not_show_the_author + * @since 7.3.0 + * + * @param array $args The post type arguments. + */ + public function test_author_of_a_post_type_that_does_not_show_the_author( array $args ): void { + register_post_type( 'mdt_author_type', $args ); + + $author = self::factory()->user->create( array( 'role' => 'author' ) ); + self::factory()->post->create( + array( + 'post_type' => 'mdt_author_type', + 'post_status' => 'publish', + 'post_author' => $author, + ) + ); + $attachment = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-author-type.jpg', + 'post_mime_type' => 'image/jpeg', + 'post_author' => $author, + ) + ); + + $this->login_as( 'subscriber' ); + $this->register_abilities(); + + $item = $this->query_item( $attachment, array( 'author' ) ); + + $this->assertSame( + array( + 'id' => $author, + 'name' => null, + 'slug' => null, + ), + $item['author'], + 'The author should not be named.' + ); + } + + /** + * Whether the author is visible is worked out for each caller, also in the same request. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_author_visibility_is_worked_out_for_each_caller(): void { + $author = self::factory()->user->create( array( 'role' => 'author' ) ); + self::factory()->post->create( + array( + 'post_status' => 'private', + 'post_author' => $author, + ) + ); + $attachment = self::factory()->attachment->create_object( + array( + 'file' => '2026/01/mdt-private-post-author.jpg', + 'post_mime_type' => 'image/jpeg', + 'post_author' => $author, + ) + ); + $user = get_userdata( $author ); + + $input = array( + 'where' => array( 'ids' => array( $attachment ) ), + 'fields' => array( 'author' ), + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $editor_result = $this->run_ability( $input ); + + $this->login_as( 'subscriber' ); + $subscriber_result = $this->run_ability( $input ); + + $this->assertIsArray( $editor_result, 'The query of the editor should succeed.' ); + $this->assertIsArray( $subscriber_result, 'The query of the subscriber should succeed.' ); + $this->assertSame( + array( + 'id' => $author, + 'name' => $user->display_name, + 'slug' => $user->user_nicename, + ), + $editor_result['items'][0]['author'] ?? null, + 'An editor should see the author of a private post.' + ); + $this->assertSame( + array( + 'id' => $author, + 'name' => null, + 'slug' => null, + ), + $subscriber_result['items'][0]['author'] ?? null, + 'A subscriber should not see the author of a private post only.' + ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaDeleteAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaDeleteAbility.php new file mode 100644 index 0000000000000..8054b3f1424f9 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaDeleteAbility.php @@ -0,0 +1,697 @@ + The input. + */ + private function delete_input( string $attachment, ?bool $permanent = null ): array { + $input = array( 'where' => array( 'id' => self::$post_ids[ $attachment ] ?? self::MISSING_ID ) ); + + if ( null !== $permanent ) { + $input['permanent'] = $permanent; + } + + return $input; + } + + /** + * Skips the test unless the site can move attachments to the Trash. + * + * @since 7.3.0 + */ + private function require_trash(): void { + if ( ! self::site_can_trash_attachments() ) { + $this->markTestSkipped( 'The site cannot move attachments to the Trash.' ); + } + } + + /** + * Returns the `permanent` values that ask for the Trash. + * + * @return array The values, null for a missing key. + */ + public static function data_trash_requests(): array { + return array( + 'false' => array( false ), + 'missing' => array( null ), + ); + } + + /** + * The ability is registered with its label, category, meta and annotations. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_registers_the_delete_ability(): void { + $this->assert_registration( 'Delete Media', false, true, true ); + } + + /** + * The input and output schemas are the published ones. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_schemas(): void { + $this->register_abilities(); + $ability = wp_get_ability( self::ABILITY ); + + $expected_input = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where' ), + 'properties' => array( + 'where' => self::where_id_schema(), + 'permanent' => array( 'type' => 'boolean' ), + ), + ); + $expected_output = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'outcome' ), + 'properties' => array( + 'outcome' => array( 'type' => 'string' ), + ), + ); + + $this->assertSame( $this->normalize_schema( $expected_input ), $this->normalize_schema( $ability->get_input_schema() ), 'The input schema should match.' ); + $this->assertSame( $this->normalize_schema( $expected_output ), $this->normalize_schema( $ability->get_output_schema() ), 'The output schema should match.' ); + } + + /** + * Returns callers with whether the gate lets them delete an attachment of the author, or + * 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 ), + ); + } + + /** + * The permission callback needs `delete_post` on the target. + * + * @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_delete_post( 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(); + + $input = array( + 'where' => array( 'id' => $id ), + 'permanent' => true, + ); + + $this->assertSame( $expected, wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The gate should follow delete_post on the target.' ); + } + + /** + * The permission callback refuses an administrator when the attachment type has + * `show_in_rest` off, and nothing is deleted. + * + * @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_rest = false; + + $input = $this->delete_input( 'unattached', true ); + $this->assertFalse( wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The administrator should be refused.' ); + $this->assert_refused( $this->run_ability( $input ), 'A deletion while attachments are hidden' ); + $this->assertInstanceOf( WP_Post::class, get_post( self::$post_ids['unattached'] ), 'The attachment should still exist.' ); + } + + /** + * A refused caller gets the generic error and nothing is deleted. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_refused_caller_gets_the_generic_error(): void { + $this->login_as( 'contributor' ); + $this->register_abilities(); + + $this->assert_refused( $this->run_ability( $this->delete_input( 'unattached', true ) ), 'A deletion by a contributor' ); + $this->assertInstanceOf( WP_Post::class, get_post( self::$post_ids['unattached'] ), 'The attachment should still exist.' ); + } + + /** + * The permission callback passes when the ID names no attachment, so that the call + * answers that nothing was found, and nothing is deleted. + * + * @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->delete_input( $post, true ); + $before = $this->snapshot(); + + $this->assertTrue( wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The gate should pass.' ); + $this->assert_not_found( $this->run_ability( $input ), 'A deletion of something that is not an attachment' ); + $this->assertSame( $before['posts'], $this->snapshot()['posts'], 'Nothing should be deleted.' ); + } + + /** + * 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' ); + $callbacks = $this->get_ability_callbacks(); + + $this->assertFalse( call_user_func( $callbacks['permission_callback'], $input ), 'The gate should refuse input without a usable ID.' ); + } + + /** + * The permission callback returns false for the ID of an attachment the caller may delete + * 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' ); + $callbacks = $this->get_ability_callbacks(); + + $input = array( + 'where' => array( 'id' => self::$post_ids['unattached'] . 'abc' ), + 'permanent' => true, + ); + + $this->assertFalse( call_user_func( $callbacks['permission_callback'], $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 = array( + 'where' => array( 'id' => $this->id_in_form( self::$post_ids['unattached'], $form ) ), + 'permanent' => true, + ); + + $this->assertTrue( wp_get_ability( self::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. + * + * @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(); + + $this->assert_not_found( + $this->run_ability( + array( + 'where' => $where, + 'permanent' => true, + ) + ), + 'A deletion with an unusable ID' + ); + } + + /** + * A permanent deletion with an ID of 0 is not found, also when the global post is an + * attachment the caller may delete, and that attachment is kept unchanged. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_lookup_never_uses_the_global_post(): 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'] ); + $result = $this->run_ability( + array( + 'where' => array( 'id' => 0 ), + 'permanent' => true, + ) + ); + $after = $this->snapshot( self::$post_ids['unattached'] ); + + $this->assert_not_found( $result, 'A permanent deletion with an ID of 0' ); + $this->assertSame( $before['post'], $after['post'], 'The attachment row should not change.' ); + $this->assertSame( $before['post_meta'], $after['post_meta'], 'The attachment meta should not change.' ); + $this->assertSame( $before['posts'], $after['posts'], 'No post should be removed.' ); + } + + /** + * Returns the callers the gate refuses, with the status they get. + * + * @return array The cases. + */ + public static function data_callers_without_delete_post(): 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; + } + + /** + * Without `delete_post` the callback refuses the call and nothing is deleted. + * + * @ticket 66719 + * @dataProvider data_callers_without_delete_post + * @since 7.3.0 + * + * @param string $role The role. + * @param int $status The expected status. + * @param bool $own Whether the target is the caller's own attachment. + */ + public function test_callback_refuses_without_delete_post( string $role, int $status, bool $own ): void { + $id = $own ? $this->create_attachment_of( $role ) : self::$post_ids['unattached']; + + $this->login_as( $role ); + $this->register_abilities(); + $this->force_permission(); + + $before = $this->snapshot( $id ); + $result = $this->run_ability( + array( + 'where' => array( 'id' => $id ), + 'permanent' => true, + ) + ); + + $this->assert_error( $result, 'media_cannot_delete', $status, 'A deletion without delete_post' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to delete this post.', 'A deletion without delete_post' ); + $this->assertSame( $before, $this->snapshot( $id ), 'Nothing should change.' ); + } + + /** + * Returns keys that are not part of the input, and where they are sent. + * + * @return array The cases. + */ + public static function data_keys_outside_the_allow_list(): array { + return array( + 'force' => array( null, 'force', true ), + 'ID' => array( null, 'ID', 1 ), + 'where status' => array( 'where', 'status', 'trash' ), + 'where ID' => array( 'where', 'ID', 1 ), + ); + } + + /** + * A key outside the allow-list fails input validation, and nothing is deleted. + * + * @ticket 66719 + * @dataProvider data_keys_outside_the_allow_list + * @since 7.3.0 + * + * @param string|null $location Where the key is sent, or null for the top level. + * @param string $key The key. + * @param mixed $value The value. + */ + public function test_key_outside_the_allow_list_fails_input_validation( ?string $location, string $key, $value ): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $input = $this->delete_input( 'unattached', true ); + if ( null === $location ) { + $input[ $key ] = $value; + } else { + $input[ $location ][ $key ] = $value; + } + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $result = $this->run_ability( $input ); + + $this->assertWPError( $result, 'The call should fail.' ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the key.' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'Nothing should be written.' ); + } + + /** + * The lookup and the capability come before the Trash checks. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_lookup_and_capability_come_first(): void { + $this->login_as( 'contributor' ); + $this->register_abilities(); + $this->force_permission(); + + $this->assert_not_found( $this->run_ability( $this->delete_input( 'missing' ) ), 'A trash request for a missing attachment' ); + $this->assert_error( $this->run_ability( $this->delete_input( 'trashed' ) ), 'media_cannot_delete', 403, 'A trash request for a trashed attachment without delete_post' ); + } + + /** + * Returns attachments of every status. + * + * @return array The attachments, as fixture names. + */ + public static function data_attachments_of_every_status(): array { + return array( + 'inherit' => array( 'unattached' ), + 'private' => array( 'private' ), + 'trashed' => array( 'trashed' ), + ); + } + + /** + * A permanent deletion removes the attachment whatever its status. + * + * @ticket 66719 + * @dataProvider data_attachments_of_every_status + * @since 7.3.0 + * + * @param string $attachment The attachment, as a fixture name. + */ + public function test_permanent_deletion( string $attachment ): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'deleted' ), $this->run_ability( $this->delete_input( $attachment, true ) ), 'The outcome should be deleted.' ); + $this->assertNull( get_post( self::$post_ids[ $attachment ] ), 'The attachment should no longer exist.' ); + } + + /** + * A permanent deletion removes the stored file and its sub-sizes. + * + * @ticket 66719 + * @requires extension gd + * @since 7.3.0 + */ + public function test_permanent_deletion_removes_the_files(): void { + $id = self::factory()->attachment->create_upload_object( DIR_TESTDATA . '/images/canola.jpg' ); + $file = get_attached_file( $id ); + $sizes = wp_get_attachment_metadata( $id )['sizes'] ?? array(); + + $this->assertFileExists( $file, 'The stored file should exist before the deletion.' ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $this->assertSame( + array( 'outcome' => 'deleted' ), + $this->run_ability( + array( + 'where' => array( 'id' => $id ), + 'permanent' => true, + ) + ), + 'The outcome should be deleted.' + ); + $this->assertNull( get_post( $id ), 'The attachment should no longer exist.' ); + $this->assertFileDoesNotExist( $file, 'The stored file should be removed.' ); + + foreach ( $sizes as $name => $size ) { + $this->assertFileDoesNotExist( dirname( $file ) . '/' . $size['file'], "The {$name} sub-size {$size['file']} should be removed." ); + } + } + + /** + * When the site cannot trash attachments, a trash request is refused and nothing is + * deleted. + * + * @ticket 66719 + * @dataProvider data_trash_requests + * @since 7.3.0 + * + * @param bool|null $permanent The `permanent` value, null for a missing key. + */ + public function test_trash_not_supported( ?bool $permanent ): void { + if ( self::site_can_trash_attachments() ) { + $this->markTestSkipped( 'The site can move attachments to the Trash.' ); + } + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $result = $this->run_ability( $this->delete_input( 'unattached', $permanent ) ); + + $this->assert_error( $result, 'media_trash_not_supported', 501, 'A trash request' ); + $this->assert_error_message( $result, self::TRASH_NOT_SUPPORTED, 'A trash request' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'Nothing should change.' ); + } + + /** + * When the site cannot trash attachments, a trash request for a trashed attachment is + * refused as unsupported, before the Trash state is read. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_trash_not_supported_comes_before_already_trashed(): void { + if ( self::site_can_trash_attachments() ) { + $this->markTestSkipped( 'The site can move attachments to the Trash.' ); + } + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $this->assert_error( $this->run_ability( $this->delete_input( 'trashed' ) ), 'media_trash_not_supported', 501, 'A trash request for a trashed attachment' ); + $this->assertSame( 'trash', get_post( self::$post_ids['trashed'] )->post_status, 'The attachment should stay in the Trash.' ); + } + + /** + * When the site can trash attachments, a trash request moves the attachment to the Trash. + * + * @ticket 66719 + * @dataProvider data_trash_requests + * @since 7.3.0 + * + * @param bool|null $permanent The `permanent` value, null for a missing key. + */ + public function test_trash( ?bool $permanent ): void { + $this->require_trash(); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'trashed' ), $this->run_ability( $this->delete_input( 'unattached', $permanent ) ), 'The outcome should be trashed.' ); + $this->assertSame( 'trash', get_post( self::$post_ids['unattached'] )->post_status, 'The attachment should be in the Trash.' ); + } + + /** + * When the site can trash attachments, a trash request for a trashed attachment is + * refused and nothing changes. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_already_trashed(): void { + $this->require_trash(); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $before = $this->snapshot( self::$post_ids['trashed'] ); + $result = $this->run_ability( $this->delete_input( 'trashed' ) ); + + $this->assert_error( $result, 'media_already_trashed', 410, 'A trash request for a trashed attachment' ); + $this->assert_error_message( $result, 'The attachment has already been trashed.', 'A trash request for a trashed attachment' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['trashed'] ), 'Nothing should change.' ); + } + + /** + * When a filter makes Core skip the permanent deletion, the call fails and the attachment + * stays. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_skipped_deletion_fails(): void { + add_filter( 'pre_delete_attachment', '__return_false' ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->delete_input( 'unattached', true ) ); + + $this->assert_error( $result, 'media_delete_failed', 500, 'A skipped deletion' ); + $this->assert_error_message( $result, self::DELETE_FAILED, 'A skipped deletion' ); + $this->assertInstanceOf( WP_Post::class, get_post( self::$post_ids['unattached'] ), 'The attachment should still exist.' ); + } + + /** + * When a filter makes Core skip the move to the Trash, the call fails and the attachment + * keeps its status. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_skipped_trash_fails(): void { + $this->require_trash(); + + add_filter( 'pre_trash_post', '__return_false' ); + + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->delete_input( 'unattached', false ) ); + + $this->assert_error( $result, 'media_delete_failed', 500, 'A skipped move to the Trash' ); + $this->assert_error_message( $result, self::DELETE_FAILED, 'A skipped move to the Trash' ); + $this->assertSame( 'inherit', get_post( self::$post_ids['unattached'] )->post_status, 'The attachment should keep its status.' ); + } + + /** + * The own author deletes an own attachment. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_own_author_deletes_an_own_attachment(): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'deleted' ), $this->run_ability( $this->delete_input( 'pdf', true ) ), 'The outcome should be deleted.' ); + $this->assertNull( get_post( self::$post_ids['pdf'] ), 'The attachment should no longer exist.' ); + } + + /** + * A listener on the permanent deletion sees the caller as the current user. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_permanent_deletion_runs_as_the_caller(): void { + $deleted_by = array(); + add_action( + 'delete_attachment', + static function () use ( &$deleted_by ): void { + $deleted_by[] = get_current_user_id(); + } + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assertSame( array( 'outcome' => 'deleted' ), $this->run_ability( $this->delete_input( 'editor_image', true ) ), 'The outcome of the deletion by the editor should be deleted.' ); + $this->assertSame( array( self::$user_ids['editor'] ), $deleted_by, 'The listener should see the caller as the current user.' ); + } +} diff --git a/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaUpdateAbility.php b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaUpdateAbility.php new file mode 100644 index 0000000000000..dfecacff21c11 --- /dev/null +++ b/tests/phpunit/tests/abilities-api/wpRegisterCoreMediaUpdateAbility.php @@ -0,0 +1,1528 @@ + $data The attributes. + * @param string[]|null $fields Optional. The fields. Default null. + * @return array The input. + */ + private function update_input( string $attachment, array $data, ?array $fields = null ): array { + $input = array( + 'where' => array( 'id' => self::$post_ids[ $attachment ] ?? self::MISSING_ID ), + 'data' => $data, + ); + + if ( null !== $fields ) { + $input['fields'] = $fields; + } + + return $input; + } + + /** + * Asserts that a call succeeded and returned the item of the attachment. + * + * @since 7.3.0 + * + * @param mixed $result The ability result. + * @param string $attachment The attachment, as a fixture name. + * @param string $context What the call was, for the assertion messages. + */ + private function assert_updated( $result, string $attachment, string $context ): void { + $this->assertNotWPError( $result, "{$context}: the update should succeed." ); + $this->assertIsArray( $result, "{$context}: the update should return the item." ); + $this->assertSame( self::$post_ids[ $attachment ], $result['id'], "{$context}: the item should be the attachment." ); + } + + /** + * Asserts that the row and meta of an attachment are the same as in a snapshot. + * + * @since 7.3.0 + * + * @param array $before The snapshot before the call. + * @param string $context What the call was, for the assertion messages. + */ + private function assert_unchanged( array $before, string $context ): void { + $after = $this->snapshot( (int) $before['post']['ID'] ); + + $this->assertSame( $before['post'], $after['post'], "{$context}: the attachment row should not change." ); + $this->assertSame( $before['post_meta'], $after['post_meta'], "{$context}: the attachment meta should not change." ); + $this->assertSame( $before['posts'], $after['posts'], "{$context}: no post should be added or removed." ); + } + + /** + * Sets a column of a shared attachment directly. + * + * @since 7.3.0 + * + * @param string $attachment The attachment, as a fixture name. + * @param array $columns The columns and their values. + */ + private function set_columns( string $attachment, array $columns ): void { + global $wpdb; + + $wpdb->update( $wpdb->posts, $columns, array( 'ID' => self::$post_ids[ $attachment ] ) ); + clean_post_cache( self::$post_ids[ $attachment ] ); + } + + /** + * The ability is registered with its label, category, meta and annotations. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_registers_the_update_ability(): void { + $this->assert_registration( 'Update Media', false, false, true ); + } + + /** + * The input and output schemas are the published ones. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_schemas(): void { + $this->register_abilities(); + $ability = wp_get_ability( self::ABILITY ); + + $expected_input = array( + 'type' => 'object', + 'additionalProperties' => false, + 'required' => array( 'where', 'data' ), + 'properties' => array( + 'where' => self::where_id_schema(), + 'data' => array( + 'type' => 'object', + 'additionalProperties' => false, + 'minProperties' => 1, + 'properties' => self::attribute_schemas( 0 ), + ), + 'fields' => self::fields_schema(), + ), + ); + + $this->assertSame( $this->normalize_schema( $expected_input ), $this->normalize_schema( $ability->get_input_schema() ), 'The input schema should match.' ); + $this->assertSame( $this->normalize_schema( self::item_schema() ), $this->normalize_schema( $ability->get_output_schema() ), 'The output schema should match.' ); + } + + /** + * Returns callers with whether the gate lets them update an attachment of the author, or + * 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 ), + ); + } + + /** + * The permission callback needs `edit_post` on the target. + * + * @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_edit_post( 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(); + + $input = array( + 'where' => array( 'id' => $id ), + 'data' => array( 'title' => 'MDT' ), + ); + + $this->assertSame( $expected, wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The gate should follow edit_post on the target.' ); + } + + /** + * The permission callback refuses an administrator when the attachment type has + * `show_in_rest` 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_rest = false; + + $input = $this->update_input( 'unattached', array( 'title' => 'MDT hidden' ) ); + $this->assertFalse( wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The administrator should be refused.' ); + $this->assert_refused( $this->run_ability( $input ), 'An update while attachments are hidden' ); + } + + /** + * 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->update_input( 'unattached', array( 'title' => 'MDT refused' ) ) ), 'An update by a contributor' ); + $this->assert_unchanged( $before, 'An update by a contributor' ); + } + + /** + * The permission callback passes when the ID names no attachment, so that the call + * answers that nothing was found. + * + * @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->update_input( $post, array( 'title' => 'MDT not found' ) ); + + $this->assertTrue( wp_get_ability( self::ABILITY )->check_permissions( $input ), 'The gate should pass.' ); + $this->assert_not_found( $this->run_ability( $input ), 'An update of something that is not an attachment' ); + } + + /** + * 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' ); + $callbacks = $this->get_ability_callbacks(); + + $this->assertFalse( call_user_func( $callbacks['permission_callback'], $input ), 'The gate should refuse input without a usable ID.' ); + } + + /** + * The permission callback returns false for the ID of an attachment the caller may edit + * 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' ); + $callbacks = $this->get_ability_callbacks(); + + $input = array( + 'where' => array( 'id' => self::$post_ids['unattached'] . 'abc' ), + 'data' => array( 'title' => 'MDT letters' ), + ); + + $this->assertFalse( call_user_func( $callbacks['permission_callback'], $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 = array( + 'where' => array( 'id' => $this->id_in_form( self::$post_ids['unattached'], $form ) ), + 'data' => array( 'title' => 'MDT form' ), + ); + + $this->assertTrue( wp_get_ability( self::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. + * + * @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(); + + $this->assert_not_found( + $this->run_ability( + array( + 'where' => $where, + 'data' => array( 'title' => 'MDT unusable' ), + ) + ), + 'An update with an unusable ID' + ); + } + + /** + * Returns update inputs without a usable ID. + * + * @return array}> The inputs. + */ + public static function data_updates_without_a_usable_id(): array { + return array( + 'ID of zero' => array( + array( + 'where' => array( 'id' => 0 ), + 'data' => array( 'title' => 'MDT global post' ), + ), + ), + 'no where' => array( + array( 'data' => array( 'title' => 'MDT global post' ) ), + ), + ); + } + + /** + * Without a usable ID the update is not found, also when the global post is an attachment + * the caller may edit, and that attachment does not change. + * + * @ticket 66719 + * @dataProvider data_updates_without_a_usable_id + * @since 7.3.0 + * + * @param array $input The input. + */ + public function test_lookup_never_uses_the_global_post( array $input ): 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( $input ), 'An update without a usable ID' ); + $this->assert_unchanged( $before, 'An update without a usable ID' ); + } + + /** + * Returns the callers the gate refuses, with the status they get. + * + * @return array The cases. + */ + public static function data_callers_without_edit_post(): 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; + } + + /** + * Without `edit_post` the callback refuses the call before any attribute is checked, and + * nothing changes. + * + * @ticket 66719 + * @dataProvider data_callers_without_edit_post + * @since 7.3.0 + * + * @param string $role The role. + * @param int $status The expected status. + * @param bool $own Whether the target is the caller's own attachment. + */ + public function test_callback_refuses_without_edit_post( string $role, int $status, bool $own ): void { + $id = $own ? $this->create_attachment_of( $role ) : self::$post_ids['unattached']; + + $this->login_as( $role ); + $this->register_abilities(); + $this->force_permission(); + $this->skip_input_validation(); + + $before = $this->snapshot( $id ); + $result = $this->run_ability( + array( + 'where' => array( 'id' => $id ), + 'data' => array( + 'author' => 0, + 'title' => 'MDT cannot edit', + ), + ) + ); + + $this->assert_error( $result, 'media_cannot_edit', $status, 'An update without edit_post' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to edit this post.', 'An update without edit_post' ); + $this->assert_unchanged( $before, 'An update without edit_post' ); + } + + /** + * The lookup comes before everything else. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_lookup_comes_first(): void { + $this->login_as( 'contributor' ); + $this->register_abilities(); + $this->force_permission(); + $this->skip_input_validation(); + + $this->assert_not_found( $this->run_ability( $this->update_input( 'missing', array( 'author' => 0 ) ) ), 'An update of a missing attachment with an invalid author' ); + } + + /** + * Data without any attribute is an invalid attribute. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_data_without_attributes(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', array() ) ), 'media_invalid_attribute', 'data', 'Empty data' ); + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', array( 'status' => 'private' ) ) ), 'media_invalid_attribute', 'data', 'Data with only a key outside the attributes' ); + $this->assert_unchanged( $before, 'Data without attributes' ); + } + + /** + * 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' => 0, + 'post' => -1, + 'date' => array(), + 'slug' => '!!!', + ); + + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', $data ) ), 'media_invalid_attribute', 'data[author]', 'Every attribute invalid' ); + + unset( $data['author'] ); + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', $data ) ), 'media_invalid_attribute', 'data[post]', 'Post, date and slug invalid' ); + + unset( $data['post'] ); + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', $data ) ), 'media_invalid_attribute', 'data[date]', 'Date and slug invalid' ); + + unset( $data['date'] ); + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', $data ) ), 'media_invalid_attribute', 'data[slug]', 'Slug invalid' ); + } + + /** + * 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(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'author' => self::$user_ids['author'] ) ) ), 'unattached', 'An update with the own author' ); + } + + /** + * The stored author sent again is not checked, also when that user no longer exists. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_stored_author_sent_again_is_not_checked(): void { + $this->set_columns( 'editor_image', array( 'post_author' => self::MISSING_ID ) ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( + $this->run_ability( + $this->update_input( + 'editor_image', + array( + 'author' => self::MISSING_ID, + 'title' => 'MDT stored author', + ) + ) + ), + 'editor_image', + 'An update with the stored author' + ); + $this->assertSame( self::MISSING_ID, (int) get_post_field( 'post_author', self::$post_ids['editor_image'] ), 'The author should stay.' ); + } + + /** + * 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' ), + ); + } + + /** + * 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( self::$post_ids['unattached'] ); + $result = $this->run_ability( $this->update_input( 'unattached', array( 'author' => self::$user_ids[ $author ] ?? self::MISSING_ID ) ) ); + + $this->assert_error( $result, 'media_cannot_edit_others', 403, 'An update to another author' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to update posts as this user.', 'An update to another author' ); + $this->assert_unchanged( $before, 'An update to 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->run_ability( $this->update_input( 'editor_image', array( 'author' => self::MISSING_ID ) ) ); + $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' ); + + $this->assert_updated( $this->run_ability( $this->update_input( 'editor_image', array( 'author' => self::$user_ids['author'] ) ) ), 'editor_image', 'An update to another author' ); + $this->assertSame( self::$user_ids['author'], (int) get_post_field( 'post_author', self::$post_ids['editor_image'] ), 'The new author should be stored.' ); + } + + /** + * A parent of 0 detaches the attachment without any capability on the old parent. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_parent_of_zero_detaches(): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( 'attached', array( 'post' => 0 ), array( 'post' ) ) ); + + $this->assert_updated( $result, 'attached', 'A detach' ); + $this->assertSame( 0, $result['post'], 'The output should show the attachment detached.' ); + $this->assertSame( 0, get_post( self::$post_ids['attached'] )->post_parent, 'The attachment should be detached.' ); + } + + /** + * The current parent sent again needs no capability, also when that post no longer exists. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_current_parent_sent_again_needs_no_capability(): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $this->assert_updated( + $this->run_ability( + $this->update_input( + 'attached', + array( + 'post' => self::$post_ids['post'], + 'title' => 'MDT same parent', + ) + ) + ), + 'attached', + 'An update with the current parent' + ); + + $this->set_columns( 'unattached', array( 'post_parent' => self::MISSING_ID ) ); + + $this->assert_updated( + $this->run_ability( + $this->update_input( + 'unattached', + array( + 'post' => self::MISSING_ID, + 'title' => 'MDT missing parent', + ) + ) + ), + 'unattached', + 'An update with a current parent that no longer exists' + ); + $this->assertSame( self::MISSING_ID, get_post( self::$post_ids['unattached'] )->post_parent, 'The parent should stay.' ); + } + + /** + * Returns parents the author may not attach to. + * + * @return array The posts, as fixture names. + */ + public static function data_parents_the_author_may_not_use(): array { + return array( + 'page of another user' => array( 'page' ), + 'missing post' => array( 'missing' ), + ); + } + + /** + * A new parent needs `edit_post` on it, checked before it is looked up. + * + * @ticket 66719 + * @dataProvider data_parents_the_author_may_not_use + * @since 7.3.0 + * + * @param string $post The post, as a fixture name. + */ + public function test_new_parent_needs_edit_post( string $post ): void { + $this->login_as( 'author' ); + $this->register_abilities(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $result = $this->run_ability( $this->update_input( 'unattached', array( 'post' => self::$post_ids[ $post ] ?? self::MISSING_ID ) ) ); + + $this->assert_error( $result, 'media_cannot_attach', 403, 'An update to a forbidden parent' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to attach media to this post.', 'An update to a forbidden parent' ); + $this->assert_unchanged( $before, 'An update to a forbidden parent' ); + } + + /** + * Returns parents of a type that cannot hold attachments. + * + * @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' ), + ); + } + + /** + * A revision or an attachment cannot be the parent, also when it is the current 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(); + + $data = array( 'post' => self::$post_ids[ $post ] ); + $result = $this->run_ability( $this->update_input( 'unattached', $data ) ); + + $this->assert_error_with_params( $result, 'media_invalid_attribute', 'data[post]', 'A new parent of an invalid type' ); + $this->assert_error_message( $result, 'Invalid parent type.', 'A new parent of an invalid type' ); + + $this->set_columns( 'unattached', array( 'post_parent' => self::$post_ids[ $post ] ) ); + + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', $data ) ), 'media_invalid_attribute', 'data[post]', 'A current parent of an invalid type' ); + } + + /** + * Returns authors below 1. + * + * @return array The authors. + */ + public static function data_authors_below_one(): array { + return array( + 'zero' => array( 0 ), + 'negative' => array( -1 ), + ); + } + + /** + * An author below 1 is invalid before the capability to set another author is checked. + * + * @ticket 66719 + * @dataProvider data_authors_below_one + * @since 7.3.0 + * + * @param int $author The author. + */ + public function test_author_below_one_is_invalid_before_the_capability_check( int $author ): void { + $this->login_as( 'author' ); + $this->register_abilities(); + $this->skip_input_validation(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $result = $this->run_ability( $this->update_input( 'unattached', array( 'author' => $author ) ) ); + + $this->assert_error_with_params( $result, 'media_invalid_attribute', 'data[author]', 'An author below 1' ); + $this->assert_unchanged( $before, 'An author below 1' ); + } + + /** + * Returns posts of another user of a type that cannot hold attachments. + * + * @return array The posts, as fixture names. + */ + public static function data_other_users_parents_of_an_invalid_type(): array { + return array( + 'revision of a post of another user' => array( 'revision' ), + 'attachment of another user' => array( 'editor_image' ), + ); + } + + /** + * A new 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_other_users_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(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $missing = $this->run_ability( $this->update_input( 'unattached', array( 'post' => self::MISSING_ID ) ) ); + $result = $this->run_ability( $this->update_input( 'unattached', array( 'post' => self::$post_ids[ $post ] ) ) ); + + $this->assert_error( $missing, 'media_cannot_attach', 403, 'An update to a missing post' ); + $this->assert_error( $result, 'media_cannot_attach', 403, 'An update to a forbidden parent of an invalid type' ); + $this->assert_error_message( $result, 'Sorry, you are not allowed to attach media to this post.', 'An update 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.' ); + $this->assert_unchanged( $before, 'An update to a forbidden parent of an invalid type' ); + } + + /** + * A post the caller may edit becomes the parent. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_new_parent_is_stored(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'post' => self::$post_ids['author_post'] ) ) ), 'unattached', 'An update to a new parent' ); + $this->assertSame( self::$post_ids['author_post'], get_post( self::$post_ids['unattached'] )->post_parent, 'The new parent should be stored.' ); + } + + /** + * 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', + ), + ); + } + + /** + * 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(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'date' => $date ) ) ), 'unattached', 'An update with a date' ); + + $this->assertSame( $local, get_post_field( 'post_date', self::$post_ids['unattached'] ), 'The local date should be stored.' ); + $this->assertSame( $gmt, get_post_field( 'post_date_gmt', self::$post_ids['unattached'] ), 'The GMT date should be stored.' ); + } + + /** + * Returns dates equal to a stored one. + * + * @return array}> The cases. + */ + public static function data_dates_equal_to_the_stored_one(): array { + return array( + 'site date equal to the stored site date' => array( array( 'site' => '2099-01-15T10:00:00' ) ), + 'GMT date equal to the stored GMT date' => array( array( 'gmt' => '2099-01-20T00:00:00' ) ), + ); + } + + /** + * A site date equal to the stored site date, or a GMT date alone equal to the stored GMT + * date, counts as not sent: the call succeeds and neither stored date changes. + * + * @ticket 66719 + * @dataProvider data_dates_equal_to_the_stored_one + * @since 7.3.0 + * + * @param array $date The date input. + */ + public function test_date_equal_to_the_stored_one_counts_as_not_sent( array $date ): void { + update_option( 'timezone_string', 'America/New_York' ); + + /* + * The stored columns disagree, so a date that is applied would change the other + * column. + */ + $this->set_columns( + 'unattached', + array( + 'post_date' => '2099-01-15 10:00:00', + 'post_date_gmt' => '2099-01-20 00:00:00', + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'date' => $date ) ) ), 'unattached', 'An update with a date equal to the stored one' ); + + $post = get_post( self::$post_ids['unattached'] ); + + $this->assertSame( '2099-01-15 10:00:00', $post->post_date, 'The stored site date should stay.' ); + $this->assertSame( '2099-01-20 00:00:00', $post->post_date_gmt, 'The stored GMT date should stay.' ); + } + + /** + * A listener on the update sees the caller as the current user, and a callback on the + * attachment data runs during the update and stays registered. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_update_runs_as_the_caller(): void { + $updated_by = array(); + $data_calls = 0; + $listener = static function () use ( &$updated_by ): void { + $updated_by[] = get_current_user_id(); + }; + $callback = static function ( array $data ) use ( &$data_calls ): array { + ++$data_calls; + return $data; + }; + add_action( 'attachment_updated', $listener ); + add_filter( 'wp_insert_attachment_data', $callback ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'editor_image', array( 'title' => 'MDT caller update' ) ) ), 'editor_image', 'An update by the editor' ); + + $this->assertSame( array( self::$user_ids['editor'] ), array_unique( $updated_by ), 'The listener should see the caller as the current user.' ); + $this->assertGreaterThan( 0, $data_calls, 'The attachment data callback should run during the update.' ); + $this->assertNotFalse( has_filter( 'wp_insert_attachment_data', $callback ), 'The attachment data callback should stay registered.' ); + } + + /** + * 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->run_ability( $this->update_input( 'unattached', 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-update-slug' ) ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_error_with_params( $this->run_ability( $this->update_input( 'unattached', array( 'slug' => '!!!' ) ) ), 'media_invalid_attribute', 'data[slug]', 'A slug with nothing left' ); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'slug' => 'MDT-Taken-Update-Slug' ) ) ), 'unattached', 'An update with a taken slug' ); + $slug = get_post_field( 'post_name', self::$post_ids['unattached'] ); + + $this->assertNotSame( 'mdt-taken-update-slug', $slug, 'The taken slug should be made unique.' ); + $this->assertStringStartsWith( 'mdt-taken-update-slug', $slug, 'The unique slug should start with the sanitized slug.' ); + } + + /** + * Only the attributes that were sent change, and every update changes the modified date. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_only_sent_attributes_change(): void { + $this->set_columns( + 'unattached', + array( + 'post_modified' => '2020-01-01 00:00:00', + 'post_modified_gmt' => '2020-01-01 00:00:00', + 'post_excerpt' => 'MDT old caption', + 'post_content' => 'MDT old description', + ) + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $result = $this->run_ability( $this->update_input( 'unattached', array( 'alt_text' => 'MDT new alt' ), array( 'alt_text', 'title.raw', 'caption.raw', 'description.raw' ) ) ); + $post = get_post( self::$post_ids['unattached'] ); + + $this->assert_updated( $result, 'unattached', 'An update of the alt text' ); + $this->assertSame( 'MDT new alt', $result['alt_text'], 'The alt text should be the new one.' ); + $this->assertSame( 'Fixture unattached', $result['title']['raw'], 'The title should not change.' ); + $this->assertSame( 'MDT old caption', $result['caption']['raw'], 'The caption should not change.' ); + $this->assertSame( 'MDT old description', $result['description']['raw'], 'The description should not change.' ); + $this->assertNotSame( '2020-01-01 00:00:00', $post->post_modified_gmt, 'The modified date should change.' ); + } + + /** + * A value equal to the stored one is no error. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_value_equal_to_the_stored_one(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $post = get_post( self::$post_ids['unattached'] ); + + $this->assert_updated( + $this->run_ability( + $this->update_input( + 'unattached', + array( + 'title' => $post->post_title, + 'slug' => $post->post_name, + 'author' => (int) $post->post_author, + ) + ) + ), + 'unattached', + 'An update with the stored values' + ); + $this->assertSame( $post->post_name, get_post_field( 'post_name', self::$post_ids['unattached'] ), 'The slug should stay.' ); + } + + /** + * A listener after the save sees the new alt text. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_listener_after_the_save_sees_the_alt_text(): void { + $target = self::$post_ids['unattached']; + $seen = array(); + add_action( + 'wp_after_insert_post', + static function ( int $post_id ) use ( &$seen, $target ): void { + if ( $target === $post_id ) { + $seen[] = get_post_meta( $post_id, '_wp_attachment_image_alt', true ); + } + } + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'alt_text' => 'MDT listener alt' ) ) ), 'unattached', 'An update of the alt text' ); + + $this->assertCount( 1, $seen, 'The listener should run once for the attachment.' ); + $this->assertSame( 'MDT listener alt', end( $seen ), 'The last call of the listener should see the new alt text.' ); + } + + /** + * Returns attributes, each sent alone, with the column that stores it, the value sent + * and the value stored. For `author` and `post` the value is a fixture name, and the + * stored value is its ID. + * + * @return array The cases. + */ + public static function data_attributes_sent_alone(): array { + return array( + 'title' => array( 'title', 'post_title', 'MDT listener title', 'MDT listener title' ), + 'caption' => array( 'caption', 'post_excerpt', 'MDT listener caption', 'MDT listener caption' ), + 'description' => array( 'description', 'post_content', 'MDT listener description', 'MDT listener description' ), + 'slug' => array( 'slug', 'post_name', 'mdt-listener-slug', 'mdt-listener-slug' ), + 'date' => array( 'date', 'post_date', array( 'site' => '2020-01-02T03:04:05' ), '2020-01-02 03:04:05' ), + 'author' => array( 'author', 'post_author', 'editor', null ), + 'post' => array( 'post', 'post_parent', 'post', null ), + ); + } + + /** + * A listener after the save runs once for the attachment, as an update, after the sent + * value is stored, and gets the attachment as it was before the call. + * + * @ticket 66719 + * @dataProvider data_attributes_sent_alone + * @since 7.3.0 + * + * @param string $attribute The attribute. + * @param string $column The column that stores it. + * @param mixed $value The value sent, or a fixture name for `author` and `post`. + * @param string|null $stored The value stored, or null for the ID of the fixture. + */ + public function test_listener_after_the_save_runs_once_after_the_value_is_stored( string $attribute, string $column, $value, ?string $stored ): void { + global $wpdb; + + if ( 'author' === $attribute ) { + $value = self::$user_ids[ $value ]; + } elseif ( 'post' === $attribute ) { + $value = self::$post_ids[ $value ]; + } + + $stored ??= (string) $value; + $target = self::$post_ids['unattached']; + $previous = get_post( $target ); + $calls = array(); + + $this->assertNotSame( $stored, (string) $previous->$column, 'The value sent should differ from the stored one.' ); + + add_action( + 'wp_after_insert_post', + static function ( int $post_id, WP_Post $post, bool $update, ?WP_Post $post_before ) use ( &$calls, $target, $wpdb ): void { + if ( $target === $post_id ) { + $calls[] = array( + 'update' => $update, + 'before' => $post_before, + 'row' => $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id ), ARRAY_A ), + ); + } + }, + 10, + 4 + ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( $attribute => $value ) ) ), 'unattached', "An update of the {$attribute}" ); + + $this->assertCount( 1, $calls, 'The listener should run once for the attachment.' ); + $this->assertTrue( $calls[0]['update'], 'The listener should be told that this is an update.' ); + $this->assertSame( $stored, $calls[0]['row'][ $column ], "The {$attribute} should be stored when the listener runs." ); + $this->assertInstanceOf( WP_Post::class, $calls[0]['before'], 'The listener should get the attachment as it was before.' ); + $this->assertSame( $previous->$column, $calls[0]['before']->$column, "The attachment the listener gets should hold the {$attribute} from before the call." ); + } + + /** + * 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 ), + ); + } + + /** + * When the save fails nothing changes, the alt text included. + * + * @ticket 66719 + * @dataProvider data_save_failures + * @since 7.3.0 + * + * @param bool $database_error Whether the save fails with a database error. + * @param int $status The expected status. + */ + public function test_failed_save_changes_nothing( bool $database_error, int $status ): void { + update_post_meta( self::$post_ids['unattached'], '_wp_attachment_image_alt', 'MDT old alt' ); + + $this->login_as( 'editor' ); + $this->register_abilities(); + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $this->make_saves_fail( $database_error ); + + $result = $this->run_ability( + $this->update_input( + 'unattached', + array( + 'title' => 'MDT failed title', + 'alt_text' => 'MDT failed alt', + ) + ) + ); + + $this->assert_error( $result, 'media_save_failed', $status, 'A failed save' ); + $this->assert_unchanged( $before, 'A failed save' ); + } + + /** + * Returns attachments of a status other than `inherit`. + * + * @return array The cases. + */ + public static function data_attachments_with_a_status(): array { + return array( + 'private' => array( 'private', 'private' ), + 'trashed' => array( 'trashed', 'trash' ), + ); + } + + /** + * A private or trashed attachment is updated and keeps its status. + * + * @ticket 66719 + * @dataProvider data_attachments_with_a_status + * @since 7.3.0 + * + * @param string $attachment The attachment, as a fixture name. + * @param string $status The stored status. + */ + public function test_status_never_changes( string $attachment, string $status ): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( $attachment, array( 'title' => 'MDT kept status' ) ) ), $attachment, 'An update of an attachment with a status' ); + + $post = get_post( self::$post_ids[ $attachment ] ); + $this->assertSame( $status, $post->post_status, 'The status should stay.' ); + $this->assertSame( 'MDT kept status', $post->post_title, 'The title should change.' ); + } + + /** + * Returns keys that are not part of the input, and where they are sent. + * + * @return array The cases. + */ + public static function data_keys_outside_the_allow_list(): array { + return array( + 'data ID' => array( 'data', 'ID', 1 ), + 'data import_id' => array( 'data', 'import_id', 7654321 ), + 'data status' => array( 'data', 'status', 'private' ), + 'data post_status' => array( 'data', 'post_status', 'private' ), + 'data post_type' => array( 'data', 'post_type', 'post' ), + 'data mime_type' => array( 'data', 'mime_type', 'text/html' ), + 'data post_mime_type' => array( 'data', 'post_mime_type', 'text/html' ), + 'data guid' => array( 'data', 'guid', 'https://example.org/forged' ), + 'data password' => array( 'data', 'password', 'secret' ), + 'data post_password' => array( 'data', 'post_password', 'secret' ), + 'data comment_status' => array( 'data', 'comment_status', 'closed' ), + 'data ping_status' => array( 'data', 'ping_status', 'closed' ), + 'data menu_order' => array( 'data', 'menu_order', 5 ), + 'data meta' => array( 'data', 'meta', array( 'mdt_key' => 'value' ) ), + 'data meta_input' => array( 'data', 'meta_input', array( 'mdt_key' => 'value' ) ), + 'data tax_input' => array( 'data', 'tax_input', array( 'category' => array( 1 ) ) ), + 'data post_author' => array( 'data', 'post_author', 1 ), + 'data post_parent' => array( 'data', 'post_parent', 1 ), + 'data modified' => array( 'data', 'modified', '2001-01-01T00:00:00' ), + 'where status' => array( 'where', 'status', 'inherit' ), + 'where ID' => array( 'where', 'ID', 1 ), + ); + } + + /** + * A key outside the allow-list fails input validation, and nothing is written. + * + * @ticket 66719 + * @dataProvider data_keys_outside_the_allow_list + * @since 7.3.0 + * + * @param string $location Where the key is sent. + * @param string $key The key. + * @param mixed $value The value. + */ + public function test_key_outside_the_allow_list_fails_input_validation( string $location, string $key, $value ): void { + $this->login_as( 'administrator' ); + $this->register_abilities(); + + $input = $this->update_input( 'unattached', array( 'title' => 'MDT extra key' ) ); + + $input[ $location ][ $key ] = $value; + + $before = $this->snapshot( self::$post_ids['unattached'] ); + $result = $this->run_ability( $input ); + + $this->assertWPError( $result, 'The call should fail.' ); + $this->assertSame( 'ability_invalid_input', $result->get_error_code(), 'The schema should reject the key.' ); + $this->assertSame( $before, $this->snapshot( self::$post_ids['unattached'] ), 'Nothing should be written.' ); + } + + /** + * The same call twice gives the same stored values and no error. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_same_call_twice(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $input = $this->update_input( + 'unattached', + array( + 'title' => 'MDT twice', + 'slug' => 'mdt-twice', + 'post' => self::$post_ids['author_post'], + 'alt_text' => 'MDT twice alt', + ), + array( 'title.raw', 'slug', 'post', 'alt_text' ) + ); + + $first = $this->run_ability( $input ); + $second = $this->run_ability( $input ); + + $this->assert_updated( $first, 'unattached', 'The first call' ); + $this->assert_updated( $second, 'unattached', 'The second call' ); + $this->assertSame( $first, $second, 'The stored values should be the same.' ); + } + + /** + * The output holds the default fields when none are sent, and the selected ones otherwise. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_output_fields(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $default = $this->run_ability( $this->update_input( 'unattached', array( 'title' => 'MDT default' ) ) ); + $this->assert_updated( $default, 'unattached', 'An update without fields' ); + $this->assertSameSets( self::DEFAULT_KEYS, array_keys( $default ), 'The item should hold the default fields.' ); + $this->assertSame( 'MDT default', $default['title']['rendered'], 'The rendered title should be the new one.' ); + + $selected = $this->run_ability( + $this->update_input( + 'unattached', + array( + 'caption' => 'October 2026', + 'alt_text' => 'The team on the office roof', + ), + array( 'caption', 'alt_text' ) + ) + ); + $this->assert_updated( $selected, 'unattached', 'An update with fields' ); + $this->assertSameSets( array( 'id', 'caption', 'alt_text' ), array_keys( $selected ), 'The item should hold the selected fields.' ); + $this->assertSame( 'October 2026', $selected['caption']['raw'], 'The raw caption should be the new one.' ); + $this->assertSame( 'The team on the office roof', $selected['alt_text'], 'The alt text should be the new one.' ); + } + + /** + * The alt text is sanitized as a text field, and an empty one is saved as an empty text. + * + * @ticket 66719 + * @since 7.3.0 + */ + public function test_alt_text(): void { + $this->login_as( 'editor' ); + $this->register_abilities(); + + $this->assert_updated( $this->run_ability( $this->update_input( 'unattached', array( 'alt_text' => "MDT\n alt " ) ) ), 'unattached', 'An update with markup in the alt text' ); + $this->assertSame( sanitize_text_field( "MDT\n alt " ), get_post_meta( self::$post_ids['unattached'], '_wp_attachment_image_alt', true ), 'The alt text should be sanitized as a text field.' ); + + $result = $this->run_ability( $this->update_input( 'unattached', array( 'alt_text' => '' ), array( 'alt_text' ) ) ); + $this->assert_updated( $result, 'unattached', 'An update with an empty alt text' ); + $this->assertSame( '', $result['alt_text'], 'The output alt text should be empty.' ); + $this->assertSame( '', get_post_meta( self::$post_ids['unattached'], '_wp_attachment_image_alt', true ), 'The stored alt text should be empty.' ); + } + + /** + * Returns callers who may 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 ), + ); + } + + /** + * 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 '; + $this->assert_updated( + $this->run_ability( + $this->update_input( + 'unattached', + array( + 'title' => $markup, + 'caption' => $markup, + 'description' => $markup, + ) + ) + ), + 'unattached', + 'An update with markup' + ); + + if ( $super_admin ) { + revoke_super_admin( self::$user_ids[ $role ] ); + } + + $post = get_post( self::$post_ids['unattached'] ); + + foreach ( array( 'post_title', 'post_excerpt', 'post_content' ) as $field ) { + $this->assertSame( $kept, str_contains( $post->$field, ''; + $id = $this->assert_uploaded( + $this->run_ability( + $this->base64_input( + 'images/codeispoetry.png', + "mdt-markup-{$role}.png", + array( + 'title' => $markup, + 'caption' => $markup, + 'description' => $markup, + ) + ) + ), + 'An upload with markup' + ); + + if ( $super_admin ) { + revoke_super_admin( self::$user_ids[ $role ] ); + } + + $post = get_post( $id ); + + foreach ( array( 'post_title', 'post_excerpt', 'post_content' ) as $field ) { + $this->assertSame( $kept, str_contains( $post->$field, '