Connection IDs holding this instance's advisory locks. */ private $lock_owners = array(); public function register() { if ( self::$registered ) { return; } self::$registered = true; add_action( self::CLEANUP_HOOK, array( $this, 'expire_upload' ) ); } public static function tool_names() { return array( 'divi_powers_get_media_upload_limits', 'divi_powers_upload_media' ); } public function operation_definitions() { return array( array( 'name' => 'divi_powers_get_media_upload_limits', 'description' => 'Read this site\'s raster-upload limits before sending image bytes. Requires an authenticated editor. Uploading creates a publicly accessible WordPress Media Library attachment; it does not place it on a page.', 'inputSchema' => array( 'type' => 'object', 'properties' => new stdClass(), 'additionalProperties' => false ), 'accessLevel' => 'read', 'annotations' => array( 'readOnlyHint' => true, 'destructiveHint' => false, 'idempotentHint' => true, 'openWorldHint' => false ), ), array( 'name' => 'divi_powers_upload_media', 'description' => 'Upload user-approved JPEG, PNG, or WebP bytes to this site\'s public Media Library. Send strict base64 (no data URL), the source SHA-256, and a unique idempotency key; retry the exact same request/key after a timeout. Keys are scoped to this user/site and retained at least 24 hours. Requires a read/write connection, upload_files, and edit_post for post_id. Images are decoded and re-encoded, so the stored checksum can differ. Returns attachment ID, URL, MIME, dimensions and source/stored SHA-256. Does not change page content; use divi_powers_save_page_layout or divi_powers_create_page_draft for placement. No SVG, URL imports, or local file paths.', 'inputSchema' => array( 'type' => 'object', 'additionalProperties' => false, 'properties' => array( 'post_id' => array( 'type' => 'integer', 'minimum' => 1 ), 'filename' => array( 'type' => 'string', 'minLength' => 1, 'maxLength' => 120 ), 'mime_type' => array( 'type' => 'string', 'enum' => array( 'image/jpeg', 'image/png', 'image/webp' ) ), 'data_base64' => array( 'type' => 'string', 'minLength' => 4, 'maxLength' => 5592408 ), 'sha256' => array( 'type' => 'string', 'pattern' => '^[a-f0-9]{64}$' ), 'idempotency_key' => array( 'type' => 'string', 'pattern' => '^[A-Za-z0-9_-]{16,128}$' ), 'alt_text' => array( 'type' => 'string', 'maxLength' => 1000 ), ), 'required' => array( 'post_id', 'filename', 'mime_type', 'data_base64', 'sha256', 'idempotency_key' ), ), 'accessLevel' => 'write', 'annotations' => array( 'readOnlyHint' => false, 'destructiveHint' => false, 'idempotentHint' => true, 'openWorldHint' => false ), ), ); } public function dispatch_operation( $tool, array $args ) { if ( 'divi_powers_get_media_upload_limits' === $tool ) { if ( ! get_current_user_id() || ! current_user_can( 'edit_posts' ) ) { return $this->error( 'access_denied', 'An authenticated editor is required.' ); } return $this->limits(); } if ( 'divi_powers_upload_media' !== $tool ) { return $this->error( 'unknown_tool', 'Unknown media operation.' ); } // Do not depend on catalog filtering: stale clients and compatibility calls // must fail closed before decoding bytes or writing any files/options. $settings = get_option( 'fived_site_bridge_settings', array() ); $settings = is_array( $settings ) ? $settings : array(); $enabled = $settings['customer_connection_enabled'] ?? ( $settings['enabled'] ?? false ); $role = $settings['customer_mcp_role'] ?? ( $settings['mcp_role'] ?? 'readonly' ); if ( ! $enabled || ! in_array( $role, array( 'readwrite', 'admin' ), true ) || ! get_current_user_id() || ! current_user_can( 'upload_files' ) ) { return $this->error( 'access_denied', 'A read/write connection and WordPress upload_files capability are required.' ); } if ( ! isset( $args['post_id'] ) || ! is_int( $args['post_id'] ) || $args['post_id'] < 1 || ! get_post( $args['post_id'] ) || ! current_user_can( 'edit_post', $args['post_id'] ) ) { return $this->error( 'post_denied', 'An editable target post_id is required.' ); } return $this->upload( $args ); } private function limits() { $bytes = min( self::MAX_BYTES, (int) wp_max_upload_size() ); // JSON/base64 adds 4/3 overhead. Reserve room for metadata and RPC envelope. $post_max = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ); if ( $post_max > 0 ) { $bytes = min( $bytes, max( 0, (int) floor( ( $post_max - 16384 ) * 3 / 4 ) ) ); } return array( 'max_bytes' => max( 0, $bytes ), 'max_base64_characters' => 4 * (int) ceil( max( 0, $bytes ) / 3 ), 'mime_types' => array( 'image/jpeg', 'image/png', 'image/webp' ), 'max_dimension' => self::MAX_DIMENSION, 'max_pixels' => self::MAX_PIXELS, 'idempotency_retention_seconds' => self::RETENTION, 'public_attachment' => true, 'page_placement' => 'existing_stage_and_apply', 'transport' => 'single_request_base64', 'animation_supported' => false, 'decoder' => 'WordPress GD single-frame editor', ); } private function upload( array $args ) { $allowed = array( 'post_id', 'filename', 'mime_type', 'data_base64', 'sha256', 'idempotency_key', 'alt_text' ); if ( array_diff( array_keys( $args ), $allowed ) ) { return $this->error( 'invalid_arguments', 'Unknown upload argument.' ); } foreach ( array( 'filename', 'mime_type', 'data_base64', 'sha256', 'idempotency_key' ) as $field ) { if ( ! isset( $args[ $field ] ) || ! is_string( $args[ $field ] ) ) { return $this->error( 'invalid_arguments', 'Required upload fields must be strings.' ); } } if ( ! preg_match( '/\A[A-Za-z0-9_-]{16,128}\z/D', $args['idempotency_key'] ) || ! preg_match( '/\A[a-f0-9]{64}\z/D', $args['sha256'] ) ) { return $this->error( 'invalid_arguments', 'Invalid idempotency key or SHA-256.' ); } $mimes = array( 'image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp' ); if ( ! isset( $mimes[ $args['mime_type'] ] ) ) { return $this->error( 'unsupported_type', 'Only JPEG, PNG, and WebP images are accepted.' ); } if ( strlen( $args['filename'] ) > 120 || ! preg_match( '/\A[A-Za-z0-9][A-Za-z0-9 _.-]*\.(jpe?g|png|webp)\z/Di', $args['filename'] ) || false !== strpos( $args['filename'], '..' ) ) { return $this->error( 'invalid_filename', 'Use a simple image filename without paths or special characters.' ); } $filename = sanitize_file_name( $args['filename'] ); $extension = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ); if ( ( 'jpeg' === $extension ? 'jpg' : $extension ) !== $mimes[ $args['mime_type'] ] ) { return $this->error( 'mime_mismatch', 'Filename extension and declared MIME must match.' ); } $site_type = wp_check_filetype( $filename, get_allowed_mime_types() ); if ( ( $site_type['type'] ?? '' ) !== $args['mime_type'] ) { return $this->error( 'unsupported_type', 'This image type is disabled by the WordPress upload policy.' ); } if ( isset( $args['alt_text'] ) && ( ! is_string( $args['alt_text'] ) || strlen( $args['alt_text'] ) > 1000 ) ) { return $this->error( 'invalid_arguments', 'alt_text must be a string of at most 1000 bytes.' ); } $alt = sanitize_text_field( $args['alt_text'] ?? '' ); $limits = $this->limits(); $encoded = $args['data_base64']; if ( ! $limits['max_bytes'] || ! strlen( $encoded ) || strlen( $encoded ) > $limits['max_base64_characters'] || strlen( $encoded ) % 4 || preg_match( '/[^A-Za-z0-9+\/=]/', $encoded ) ) { return $this->error( 'invalid_data', 'Image bytes are missing, too large, or not strict base64.' ); } $bytes = base64_decode( $encoded, true ); if ( false === $bytes || ! strlen( $bytes ) || strlen( $bytes ) > $limits['max_bytes'] || base64_encode( $bytes ) !== $encoded ) { return $this->error( 'invalid_data', 'Image bytes are too large or not canonical base64.' ); } if ( ! hash_equals( $args['sha256'], hash( 'sha256', $bytes ) ) ) { return $this->error( 'checksum_mismatch', 'Source SHA-256 does not match the uploaded bytes.' ); } if ( $this->is_animated( $bytes, $args['mime_type'] ) ) { return $this->error( 'unsupported_type', 'Animated PNG and WebP images are not supported.' ); } $size = @getimagesizefromstring( $bytes ); if ( ! $this->valid_image_size( $size, $args['mime_type'] ) ) { return $this->error( 'invalid_image', 'Image MIME or dimensions are invalid or exceed the upload limits.' ); } $scope = hash_hmac( 'sha256', get_current_blog_id() . '|' . home_url( '/' ) . '|' . get_current_user_id() . '|' . $args['idempotency_key'], wp_salt( 'auth' ) ); $key = self::OPTION_PREFIX . $scope; $fingerprint = hash( 'sha256', wp_json_encode( array( $args['post_id'], $filename, $args['mime_type'], $args['sha256'], $alt ) ) ); if ( ! $this->lock( $key ) ) { return $this->error( 'upload_busy', 'This upload is processing or safe database locking is unavailable. Retry the same request and key.' ); } $record = null; try { $record = get_option( $key, null ); if ( is_array( $record ) ) { if ( $record['fingerprint'] !== $fingerprint || (int) $record['user_id'] !== get_current_user_id() || (int) $record['blog_id'] !== get_current_blog_id() ) { return $this->error( 'idempotency_conflict', 'This idempotency key belongs to a different upload request.' ); } $completed = $this->completed_result( $record ); if ( is_array( $completed ) ) { return $completed; } if ( $this->must_preserve_retry( $record ) ) { return $this->error( 'attachment_missing', 'The original attachment is no longer available. Use a new key only if a new upload is intended.' ); } $this->assert_lock( $key ); $this->clean_partial( $record ); } // Completed retries must succeed even when the first upload exhausted quota. if ( is_multisite() && strlen( $bytes ) > get_upload_space_available() ) { return $this->error( 'quota_exceeded', 'The site does not have enough upload quota for this image.' ); } $attempt = str_replace( '-', '', wp_generate_uuid4() ); $record = array( 'fingerprint' => $fingerprint, 'user_id' => get_current_user_id(), 'blog_id' => get_current_blog_id(), 'created' => time(), 'slug' => 'dp-media-' . substr( $scope, 0, 32 ) . '-' . $attempt, 'attachment_id' => 0, 'source' => '', 'canonical' => '', 'destination' => '', 'complete' => false ); $this->save_record( $key, $record ); // Schedule before filesystem work, so a killed request is still cleaned. if ( ! wp_next_scheduled( self::CLEANUP_HOOK, array( $key ) ) && ! wp_schedule_single_event( time() + HOUR_IN_SECONDS, self::CLEANUP_HOOK, array( $key ) ) ) { throw new RuntimeException( 'Unable to schedule interrupted-upload cleanup.' ); } require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $directory = $this->private_temp_directory(); if ( is_wp_error( $directory ) ) { throw new RuntimeException( $directory->get_error_message() ); } $record['source'] = wp_tempnam( 'dp-media-', trailingslashit( $directory ) ); if ( ! $record['source'] || dirname( $record['source'] ) !== $directory || is_link( $record['source'] ) || ! chmod( $record['source'], 0600 ) ) { throw new RuntimeException( 'Unable to create a private temporary file.' ); } $record['canonical'] = $record['source'] . '.' . $mimes[ $args['mime_type'] ]; $this->save_record( $key, $record ); if ( strlen( $bytes ) !== file_put_contents( $record['source'], $bytes, LOCK_EX ) ) { throw new RuntimeException( 'Unable to write image bytes.' ); } unset( $bytes ); if ( ! function_exists( 'wp_get_image_editor' ) ) { require_once ABSPATH . 'wp-admin/includes/image.php'; } $checked = wp_check_filetype_and_ext( $record['source'], $filename, array( 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp' ) ); if ( ( $checked['type'] ?? '' ) !== $args['mime_type'] || empty( $checked['ext'] ) ) { throw new RuntimeException( 'WordPress rejected the image type.' ); } // Decode and re-encode before public storage; this strips trailing payloads // and avoids treating a matching file signature alone as validation. // GD decodes one bounded raster. Imagick may read every frame before // selecting the first, so it is deliberately unavailable on this path. $single_frame_editor = static function () { return array( 'WP_Image_Editor_GD' ); }; add_filter( 'wp_image_editors', $single_frame_editor, PHP_INT_MAX ); try { $editor = wp_get_image_editor( $record['source'] ); } finally { remove_filter( 'wp_image_editors', $single_frame_editor, PHP_INT_MAX ); } if ( is_wp_error( $editor ) ) { throw new RuntimeException( 'The server cannot safely decode this image.' ); } $preserve_format = static function () { return array(); }; add_filter( 'image_editor_output_format', $preserve_format, PHP_INT_MAX ); try { $saved = $editor->save( $record['canonical'], $args['mime_type'] ); } finally { remove_filter( 'image_editor_output_format', $preserve_format, PHP_INT_MAX ); } unset( $editor ); // Account for an unexpected editor path without ever deleting outside // this attempt's private, random temporary basename. if ( is_array( $saved ) && is_string( $saved['path'] ?? null ) && $saved['path'] !== $record['canonical'] && dirname( $saved['path'] ) === $directory && 0 === strpos( $saved['path'], $record['source'] . '.' ) && ! is_link( $saved['path'] ) ) { wp_delete_file( $saved['path'] ); } if ( is_wp_error( $saved ) || ! is_array( $saved ) || ( $saved['path'] ?? '' ) !== $record['canonical'] || ! is_file( $record['canonical'] ) || filesize( $record['canonical'] ) > $limits['max_bytes'] || ! $this->valid_image_size( @getimagesize( $record['canonical'] ), $args['mime_type'] ) ) { throw new RuntimeException( 'The server could not produce a valid bounded image.' ); } if ( is_multisite() && filesize( $record['canonical'] ) > get_upload_space_available() ) { throw new RuntimeException( 'The site does not have enough upload quota for the decoded image.' ); } $upload_time = current_time( 'mysql' ); $uploads = wp_upload_dir( $upload_time ); if ( ! empty( $uploads['error'] ) ) { throw new RuntimeException( 'WordPress uploads storage is unavailable.' ); } $stored_name = 'dp-' . substr( $scope, 0, 12 ) . '-' . $attempt . '-' . $filename; $record['destination'] = trailingslashit( $uploads['path'] ) . $stored_name; if ( file_exists( $record['destination'] ) ) { throw new RuntimeException( 'The reserved upload filename already exists.' ); } $this->save_record( $key, $record ); // Reserve the attachment before moving the image. Its deterministic slug // allows recovery if PHP stops between insertion and saving its ID. $this->assert_lock( $key ); $id = wp_insert_attachment( array( 'post_title' => sanitize_text_field( pathinfo( $filename, PATHINFO_FILENAME ) ), 'post_name' => $record['slug'], 'post_mime_type' => $args['mime_type'], 'post_status' => 'inherit', 'post_author' => $record['user_id'] ), $record['destination'], $args['post_id'], true ); $this->assert_lock( $key ); if ( is_wp_error( $id ) || ! $id ) { throw new RuntimeException( 'WordPress could not create the attachment.' ); } $record['attachment_id'] = (int) $id; $this->save_record( $key, $record ); require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; $file_array = array( 'name' => $stored_name, 'tmp_name' => $record['canonical'], 'size' => filesize( $record['canonical'] ), 'error' => 0, 'type' => $args['mime_type'] ); $this->assert_lock( $key ); $file = wp_handle_sideload( $file_array, array( 'test_form' => false, 'mimes' => array( 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp' ), 'unique_filename_callback' => static function () use ( $stored_name ) { return $stored_name; } ), $upload_time ); $this->assert_lock( $key ); if ( ! empty( $file['error'] ) || ( $file['file'] ?? '' ) !== $record['destination'] ) { throw new RuntimeException( 'WordPress could not store the image at its reserved destination.' ); } update_attached_file( $id, $record['destination'] ); $this->assert_lock( $key ); $metadata = wp_generate_attachment_metadata( $id, $record['destination'] ); $this->assert_lock( $key ); if ( ! is_array( $metadata ) || empty( $metadata['width'] ) || empty( $metadata['height'] ) ) { throw new RuntimeException( 'WordPress could not generate attachment metadata.' ); } wp_update_attachment_metadata( $id, $metadata ); $this->assert_lock( $key ); update_post_meta( $id, '_wp_attachment_image_alt', $alt ); $stored_file = get_attached_file( $id ); $stored_size = @getimagesize( $stored_file ); if ( ! $this->valid_image_size( $stored_size, $args['mime_type'] ) ) { throw new RuntimeException( 'The stored attachment failed final validation.' ); } $result = array( 'attachment_id' => (int) $id, 'url' => wp_get_attachment_url( $id ), 'mime_type' => $stored_size['mime'], 'width' => $stored_size[0], 'height' => $stored_size[1], 'bytes' => filesize( $stored_file ), 'sha256' => hash_file( 'sha256', $stored_file ), 'source_sha256' => $args['sha256'], 'post_id' => $args['post_id'] ); if ( ! $result['url'] || ! $result['sha256'] ) { throw new RuntimeException( 'The stored attachment is incomplete.' ); } $this->assert_lock( $key ); if ( ! update_post_meta( $id, self::RESULT_META, array( 'fingerprint' => $fingerprint, 'result' => $result ) ) ) { throw new RuntimeException( 'Unable to save the idempotent upload result.' ); } $record['complete'] = true; $this->save_record( $key, $record ); return $result; } catch ( Throwable $error ) { if ( $this->owns_lock( $key ) && is_array( $record ) && empty( $record['complete'] ) && ! is_array( $this->completed_result( $record ) ) ) { $rollback_id = $this->attachment( $record ); $this->clean_partial( $record ); if ( $rollback_id && ! get_post( $rollback_id ) ) { // Record our own successful rollback so an ordinary failure can // retry. An externally removed ID stays ambiguous and fails closed. $record['attachment_id'] = 0; try { $this->save_record( $key, $record ); } catch ( Throwable $rollback_error ) { // If persistence failed, retain the conservative original record. } } } return $this->error( 'upload_failed', $error->getMessage() ); } finally { if ( $this->owns_lock( $key ) && is_array( $record ) ) { $this->clean_temporary_files( $record ); } $this->unlock( $key ); } } /** Reject animation control chunks before handing the bytes to a decoder. */ private function is_animated( $bytes, $mime ) { $length = strlen( $bytes ); if ( 'image/png' === $mime ) { for ( $offset = 8; $offset + 12 <= $length; ) { $size = unpack( 'Nsize', substr( $bytes, $offset, 4 ) )['size']; $type = substr( $bytes, $offset + 4, 4 ); if ( in_array( $type, array( 'acTL', 'fcTL', 'fdAT' ), true ) ) { return true; } if ( $size > $length - $offset - 12 ) { break; } $offset += 12 + $size; } } elseif ( 'image/webp' === $mime ) { for ( $offset = 12; $offset + 8 <= $length; ) { $type = substr( $bytes, $offset, 4 ); $size = unpack( 'Vsize', substr( $bytes, $offset + 4, 4 ) )['size']; if ( 'ANIM' === $type || 'ANMF' === $type || ( 'VP8X' === $type && $size > 0 && $offset + 8 < $length && ( ord( $bytes[ $offset + 8 ] ) & 2 ) ) ) { return true; } if ( $size > $length - $offset - 8 ) { break; } $offset += 8 + $size + ( $size % 2 ); } } return false; } private function valid_image_size( $size, $mime ) { return is_array( $size ) && ( $size['mime'] ?? '' ) === $mime && $size[0] > 0 && $size[1] > 0 && $size[0] <= self::MAX_DIMENSION && $size[1] <= self::MAX_DIMENSION && $size[0] * $size[1] <= self::MAX_PIXELS; } private function save_record( $key, array $record ) { $this->assert_lock( $key ); if ( false === get_option( $key, false ) ) { add_option( $key, $record, '', false ); } else { update_option( $key, $record, false ); } $this->assert_lock( $key ); if ( get_option( $key, null ) !== $record ) { throw new RuntimeException( 'Unable to persist upload recovery state.' ); } } private function attachment( array $record ) { $id = (int) ( $record['attachment_id'] ?? 0 ); if ( ! $id ) { $ids = get_posts( array( 'post_type' => 'attachment', 'post_status' => 'any', 'name' => $record['slug'], 'author' => $record['user_id'], 'posts_per_page' => 1, 'fields' => 'ids', 'suppress_filters' => true ) ); $id = $ids ? (int) $ids[0] : 0; } $post = $id ? get_post( $id ) : null; return $post && 'attachment' === $post->post_type && (int) $post->post_author === (int) $record['user_id'] && $post->post_name === $record['slug'] ? $id : 0; } private function completed_result( array $record ) { $id = $this->attachment( $record ); $saved = $id ? get_post_meta( $id, self::RESULT_META, true ) : null; if ( is_array( $saved ) && ( $saved['fingerprint'] ?? '' ) === $record['fingerprint'] && is_array( $saved['result'] ?? null ) && is_file( get_attached_file( $id ) ) ) { return $saved['result']; } return null; } private function has_completed_attachment( array $record ) { // Slug and author are mutable; protection must use the durable ID first. $id = (int) ( $record['attachment_id'] ?? 0 ) ?: $this->attachment( $record ); $saved = $id ? get_post_meta( $id, self::RESULT_META, true ) : null; return $id && is_array( $saved ) && is_array( $saved['result'] ?? null ) && (int) ( $saved['result']['attachment_id'] ?? 0 ) === $id; } private function must_preserve_retry( array $record ) { // The retention promise survives user edits, missing files, and deletion. // A persisted ID that no longer matches is ambiguous, never a fresh upload. return ! empty( $record['complete'] ) || $this->has_completed_attachment( $record ) || ( ! empty( $record['attachment_id'] ) && ! $this->attachment( $record ) ); } private function private_temp_directory() { // Do not use an uploads fallback: unvalidated source bytes must never be // placed under the document root, even if WP_TEMP_DIR points there. $base = realpath( sys_get_temp_dir() ); $root = realpath( ABSPATH ); $document_root = ! empty( $_SERVER['DOCUMENT_ROOT'] ) ? realpath( $_SERVER['DOCUMENT_ROOT'] ) : false; if ( ! $base || ! is_writable( $base ) || ( $root && 0 === strpos( trailingslashit( $base ), trailingslashit( $root ) ) ) || ( $document_root && 0 === strpos( trailingslashit( $base ), trailingslashit( $document_root ) ) ) ) { return $this->error( 'unsafe_temp', 'A writable temporary directory outside WordPress is required.' ); } $path = $base . '/divi-powers-media-' . substr( hash_hmac( 'sha256', ABSPATH . '|' . get_current_blog_id(), wp_salt( 'auth' ) ), 0, 20 ); if ( is_link( $path ) || ( ! is_dir( $path ) && ! mkdir( $path, 0700 ) ) || ! is_writable( $path ) ) { return $this->error( 'unsafe_temp', 'Private upload staging is unavailable.' ); } if ( ! chmod( $path, 0700 ) ) { return $this->error( 'unsafe_temp', 'Private upload staging permissions could not be secured.' ); } return $path; } private function clean_temporary_files( array $record ) { $directory = $this->private_temp_directory(); if ( is_wp_error( $directory ) ) { return; } foreach ( array( 'source', 'canonical' ) as $field ) { $path = $record[ $field ] ?? ''; if ( $path && dirname( $path ) === $directory && ! is_link( $path ) && is_file( $path ) ) { wp_delete_file( $path ); } } } private function clean_partial( array $record ) { $recorded_id = (int) ( $record['attachment_id'] ?? 0 ); $id = $this->attachment( $record ); // A completed attachment remains the user's even if its file was later // removed or edited outside this operation. Never clean it as a partial. if ( $this->has_completed_attachment( $record ) ) { return; } // An existing row with changed ownership is ambiguous, even if result // metadata is absent. Do not sweep files out from under an adopted row. if ( $recorded_id && get_post( $recorded_id ) && $id !== $recorded_id ) { return; } if ( $id ) { wp_delete_attachment( $id, true ); } // Core may create a thumbnail immediately before persisting its metadata. // Clean only this random attempt's filename prefix inside this site's // uploads tree, including derivatives not yet known to the attachment. $destination = $record['destination'] ?? ''; $directory = $destination ? realpath( dirname( $destination ) ) : false; $uploads = wp_get_upload_dir(); $base = ! empty( $uploads['basedir'] ) ? realpath( $uploads['basedir'] ) : false; if ( $directory && $base && 0 === strpos( trailingslashit( $directory ), trailingslashit( $base ) ) && preg_match( '/\Adp-[a-f0-9]{12}-[a-f0-9]{32}-/', basename( $destination ), $match ) ) { foreach ( glob( $directory . '/' . $match[0] . '*' ) ?: array() as $path ) { if ( ! is_link( $path ) && is_file( $path ) && dirname( $path ) === $directory ) { wp_delete_file( $path ); } } } $this->clean_temporary_files( $record ); } /** Scheduled cleanup never deletes completed attachments. */ public function expire_upload( $key ) { if ( ! is_string( $key ) || ! preg_match( '/\Adivi_powers_media_[a-f0-9]{64}\z/D', $key ) ) { return; } if ( ! $this->lock( $key ) ) { wp_schedule_single_event( time() + 300, self::CLEANUP_HOOK, array( $key ) ); return; } try { $record = get_option( $key, null ); if ( ! is_array( $record ) || (int) ( $record['blog_id'] ?? 0 ) !== get_current_blog_id() ) { return; } if ( $this->must_preserve_retry( $record ) && time() < $record['created'] + self::RETENTION ) { wp_schedule_single_event( $record['created'] + self::RETENTION, self::CLEANUP_HOOK, array( $key ) ); return; } $this->assert_lock( $key ); if ( empty( $record['complete'] ) ) { $this->clean_partial( $record ); } $this->clean_temporary_files( $record ); $this->assert_lock( $key ); delete_option( $key ); } catch ( Throwable $error ) { wp_schedule_single_event( time() + 300, self::CLEANUP_HOOK, array( $key ) ); } finally { $this->unlock( $key ); } } // Connection-scoped MySQL/MariaDB locks release automatically if PHP dies. // Recheck the owner connection before/after mutations: wpdb can reconnect. private function lock_name( $key ) { global $wpdb; return 'dp-media-' . substr( hash( 'sha256', $wpdb->prefix . $key ), 0, 48 ); } private function lock( $key ) { global $wpdb; $owner = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT IF(GET_LOCK(%s, 0) = 1, CONNECTION_ID(), 0)', $this->lock_name( $key ) ) ); if ( $owner > 0 ) { $this->lock_owners[ $key ] = $owner; return true; } return false; } private function owns_lock( $key ) { global $wpdb; if ( empty( $this->lock_owners[ $key ] ) ) { return false; } return '1' === (string) $wpdb->get_var( $wpdb->prepare( 'SELECT IF(IS_USED_LOCK(%s) = CONNECTION_ID() AND CONNECTION_ID() = %d, 1, 0)', $this->lock_name( $key ), $this->lock_owners[ $key ] ) ); } private function assert_lock( $key ) { if ( ! $this->owns_lock( $key ) ) { throw new RuntimeException( 'Upload database lock was lost. Retry the same request and key.' ); } } private function unlock( $key ) { global $wpdb; if ( $this->owns_lock( $key ) ) { $wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $this->lock_name( $key ) ) ); } unset( $this->lock_owners[ $key ] ); } private function error( $code, $message ) { return new WP_Error( 'divi_powers_media_' . $code, $message ); } }