'forbidden', 'message' => __( 'Administrator media upload capabilities are required.', 'actionpanel-ai' ), ), 403 ); } if ( ! $this->settings->get_allow_requests() ) { return new WP_REST_Response( array( 'error' => 'actionpanel_ai_requests_disabled', 'message' => __( 'Allow WordPress to send requests to ActionPanel AI before uploading chat images.', 'actionpanel-ai' ), ), 403 ); } $files = $request->get_file_params(); if ( empty( $files['file'] ) || ! is_array( $files['file'] ) ) { return new WP_REST_Response( array( 'error' => 'missing_file', 'message' => __( 'Attach one image file under the "file" field.', 'actionpanel-ai' ), ), 400 ); } $file = $files['file']; if ( isset( $file['size'] ) && (int) $file['size'] > self::MAX_IMAGE_BYTES ) { return new WP_REST_Response( array( 'error' => 'file_too_large', 'message' => __( 'Image attachments must be 12 MB or smaller.', 'actionpanel-ai' ), ), 413 ); } $tmp_name = isset( $file['tmp_name'] ) && is_string( $file['tmp_name'] ) ? $file['tmp_name'] : ''; $name = isset( $file['name'] ) && is_string( $file['name'] ) ? $file['name'] : ''; if ( '' === $tmp_name || '' === $name || ! is_uploaded_file( $tmp_name ) ) { return new WP_REST_Response( array( 'error' => 'invalid_file', 'message' => __( 'The uploaded image could not be validated.', 'actionpanel-ai' ), ), 400 ); } $type_check = wp_check_filetype_and_ext( $tmp_name, $name ); $mime = isset( $type_check['type'] ) && is_string( $type_check['type'] ) ? $type_check['type'] : ''; if ( ! in_array( $mime, self::IMAGE_MIME_TYPES, true ) ) { return new WP_REST_Response( array( 'error' => 'unsupported_image_type', 'message' => __( 'Only PNG, JPEG, WebP, and GIF images are supported.', 'actionpanel-ai' ), ), 415 ); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $attachment_id = media_handle_upload( 'file', 0 ); if ( is_wp_error( $attachment_id ) ) { return new WP_REST_Response( array( 'error' => 'upload_failed', 'message' => $attachment_id->get_error_message(), ), 500 ); } $meta = wp_get_attachment_metadata( $attachment_id ); $url = wp_get_attachment_url( $attachment_id ); return new WP_REST_Response( array( 'kind' => 'image', 'attachment_id' => (int) $attachment_id, 'name' => get_the_title( $attachment_id ), 'mime' => $mime, 'url' => $url ? $url : null, 'width' => is_array( $meta ) && isset( $meta['width'] ) ? absint( $meta['width'] ) : null, 'height' => is_array( $meta ) && isset( $meta['height'] ) ? absint( $meta['height'] ) : null, ), 201 ); } }