post([$this, 'handleUpload']) ->auth(PermissionHandler::combine(['nonce'])) ->rateLimit(30) ->register(); Route::for('uploads/groups') ->post([$this, 'handleGroupingRequest']) ->auth(PermissionHandler::combine(['nonce'])) ->rateLimit(30) ->args([ 'id' => 'string|required', 'content' => 'string|required', ]) ->register(); Route::for('uploads/meta') ->post([$this, 'handleMetadataUpdate']) ->auth(PermissionHandler::combine(['nonce'])) ->rateLimit(30) ->args([ 'items' => 'array|required', 'id' => 'string' ]) ->register(); } /** * Build the main $context for UploadManager from the $request params * @param WP_REST_Request $request * @return array * @throws Exception * @throws Exception */ protected function buildUploadArgs(WP_REST_Request $request):array { $data = $request->get_params(); $args = []; $registrar = Registrar::getInstance($data['content']??''); foreach ($data as $key => $value) { switch ($key) { case 'depends_on': if (is_string($value) && !empty($value)) { $args['depends_on'] = sanitize_text_field($value); } break; case 'item_id': if (is_numeric($value)) { $args['item_id'] = absint($value); if ($registrar) { switch ($registrar->getType()) { case 'post': $args['post_id'] = absint($value); break; case 'term': $args['term_id'] = absint($value); break; case 'user': $args['user_id'] = absint($value); break; } } } break; // Post Type/Taxonomy case 'content': $value = str_replace('-', '_', $value); if ($value === 'options' || $registrar) { $args['content'] = $value; } break; case 'destination': if (in_array($value, ['meta', 'post', 'post_group'])) { $args['destination'] = sanitize_text_field($value); if (in_array($value, ['post', 'post_group']) && empty($data['content'])) { throw new Exception("Content type required for destination: {$value}"); } } break; // User ID case 'user': if (!array_key_exists('post_id', $args) && !array_key_exists('post_id', $data) && !array_key_exists('term_id', $data) && !array_key_exists('item_id', $data)) { $args['post_id'] = (int)get_user_meta((int) $value, BASE.'profile_link', true); } break; // Operation ID case 'id': if (is_string($value)) { $value = sanitize_text_field($value); $args['id'] = $value; $args['upload'] = $value.'_upload'; } break; // Post ID case 'post_id': if (is_numeric($value)) { $args['post_id'] = absint($value); } break; // Term ID case 'term_id': if (is_numeric($value)) { $args['term_id'] = absint($value); } break; // Field Name, as defined for Meta.php case 'field_name': if (is_string($value)) { $args['field_name'] = sanitize_text_field($value); } break; // Upload Mode case 'mode': if (in_array($value, ['direct', 'selection'])) { $args['mode'] = sanitize_text_field($value); } break; case 'upload_ids': if (is_string($value)) { // Parse JSON array $decoded = json_decode($value, true); if (is_array($decoded)) { $args['upload_ids'] = $decoded; } } elseif (is_array($value)) { // Already an array (shouldn't happen with FormData JSON, but handle it) $args['upload_ids'] = $value; } break; case 'metadata': if (!empty($value)) { $metadata = is_string($value) ? json_decode($value, true) : $value; if (is_array($metadata)) { foreach ($metadata as $k => $v) { if (in_array($k, ['title', 'caption', 'alt', 'depends_on'])) { $args['metadata'][$k] = sanitize_text_field($v); } } } } break; case 'posts': if (is_string($value)) { $decoded = json_decode($value, true); if (is_array($decoded)) { $args['posts'] = $decoded; } } break; case 'group_titles': if (is_string($value)) { $decoded = json_decode($value, true); if (is_array($decoded)) { $args['group_titles'] = array_map('sanitize_text_field', $decoded); } } break; // Other field info case 'field_key': case 'field_type': case 'subtype': case 'context': if (is_string($value)) { $args[$key] = sanitize_text_field($value); } break; } $args['user'] = get_current_user_id(); } return $args; } /** * Handle upload request with immediate feedback */ /** * @param WP_REST_Request $request * * @return WP_REST_Response */ public function handleUpload(WP_REST_Request $request): WP_REST_Response { try { $files = $request->get_file_params(); $args = $this->buildUploadArgs($request); $userID = get_current_user_id(); if (!$userID) { return $this->unauthorized(); } if (!$args['content']) { return $this->validationError(['message' => 'Missing content']); } // Step 1: Secure all uploaded files $secured_files = $this->secureFiles($files, $args); if (empty($secured_files)) { $this->logError('No valid files to upload'); return $this->error('No valid files to upload'); } // Step 2: Queue for processing via OperationQueue $operation_id = $this->queueProcessing($secured_files, $args); return $this->queued($operation_id, 'Files secured and queued for processing'); } catch (Exception $e) { // Error handling... Errors::getInstance()->log( '[UploadRoutes]:handleUploadRequest', $e->getMessage(), [ 'request_data' => $request->get_params(), 'files_info' => $this->getFilesInfo($_FILES), 'trace' => $e->getTraceAsString() ] ); return $this->error($e->getMessage()); } } /** * Secure uploaded files to temporary storage */ protected function secureFiles(array $files, array $args): array { $uploader = UploadManager::getInstance(); $secured_files = []; $errors = []; $context = $args; unset($context['upload_ids']); $file_array = $files['files'] ?? $files; if (!is_array($file_array['tmp_name'])) { $file_array = [ 'name' => [$file_array['name']], 'type' => [$file_array['type']], 'tmp_name' => [$file_array['tmp_name']], 'error' => [$file_array['error']], 'size' => [$file_array['size']] ]; } $tmp_names = $file_array['tmp_name'] ?? []; foreach ($tmp_names as $index => $tmp_name) { $file_data = [ 'name' => $file_array['name'][$index], 'type' => $file_array['type'][$index], 'tmp_name' => $tmp_name, 'error' => $file_array['error'][$index], 'size' => $file_array['size'][$index] ]; if ($file_data['error'] !== UPLOAD_ERR_OK) { $errors[$index] = $this->getUploadErrorMessage($file_data['error']); continue; } try { $secured = $uploader->secureUploadedFile($file_data, $context); if (empty($secured)) { throw new Exception('Failed to secure file'); } // Embed upload_id directly in the secured file data $secured['upload_id'] = $args['upload_ids'][$index] ?? 'upload_' . $index; $secured_files[] = $secured; } catch (Exception $e) { $errors[$index] = $e->getMessage(); } } return [ 'files' => $secured_files, 'errors' => $errors ]; } protected function getUploadErrorMessage(int $error_code): string { return match($error_code) { UPLOAD_ERR_INI_SIZE => 'File exceeds maximum upload size', UPLOAD_ERR_FORM_SIZE => 'File exceeds form maximum size', UPLOAD_ERR_PARTIAL => 'File was only partially uploaded', UPLOAD_ERR_NO_FILE => 'No file was uploaded', UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder', UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk', UPLOAD_ERR_EXTENSION => 'Upload stopped by extension', default => 'Unknown upload error' }; } /** * Queue files for processing */ protected function queueProcessing(array $secured_data, array $args): string { $operation_type = $this->determineOperationType($secured_data['files'][0] ?? []); $chunkSize = 5; if ($operation_type === 'video') { $chunkSize = 1; } elseif ($operation_type === 'document') { $chunkSize = 10; } error_log('Queueing Operation: '.print_r($operation_type, true)); error_log('With ID: '.print_r($args['upload'], true)); $queuedProcessing = Queue::getInstance()->queueOperation( $operation_type, get_current_user_id(), array_merge( ['secured_files' => $secured_data['files']], $args ), [ 'operation_id' => $args['upload'], 'chunk_key' => 'secured_files', 'chunk_size' => $chunkSize ] ); error_log('queuedProcessing operation: '.print_r($queuedProcessing, true)); $uploadOpId = $queuedProcessing['operation_id']; if ($args['mode'] !== 'selection') { // Only create attach_upload_to_content if the upload was NOT merged. // When merged, the original upload's attach_upload_to_content // will handle all files after the merged image_upload completes. if (!$queuedProcessing['updated_existing']) { Queue::getInstance()->queueOperation( 'attach_upload_to_content', get_current_user_id(), $args, [ 'priority' => 'high', 'operation_id' => $args['id'], 'depends_on' => [$uploadOpId] ] ); } } return $args['id']; } /** * Determine operation type from file data */ protected function determineOperationType(array $file): string { $file_type = $file['file_type'] ?? 'image'; return match($file_type) { 'video' => 'video_upload', 'document' => 'document_upload', default => 'image_upload' }; } /** * Update field value with new attachment IDs */ protected function updateFieldValue(array $data, array $results): void { if ((!array_key_exists('post_id', $data) && !array_key_exists('term_id', $data) && !array_key_exists('user', $data)) && !array_key_exists('field_name', $data)) { return; } $attachment_ids = array_column($results, 'attachment_id'); if (array_key_exists('post_id', $data)) { $meta = Meta::forPost($data['post_id']); } elseif (array_key_exists('term_id', $data)) { $meta = Meta::forTerm($data['term_id']); } else { $link = (int)get_user_meta($data['user'], BASE.'profile_link'); $meta = Meta::forPost($link); } // Get existing value $existing = $meta->get($data['field_name']); $existing_ids = !empty($existing) ? explode(',', $existing) : []; // Merge with new IDs $all_ids = array_unique(array_merge($existing_ids, $attachment_ids)); // Update with comma-separated string $meta->set($data['field_name'], implode(',', $all_ids)); } /** * Handle metadata update requests */ public function handleMetadataUpdate(WP_REST_Request $request): WP_REST_Response { try { $data = $request->get_params(); error_log('Received data for meta change: '.print_r($data, true)); $items = $data['items']??false; if (!$items) { return $this->sendResponse( true, [ ], 'No items to update' ); } $pending = []; $attachments = array_filter($items, function ($item) { return array_key_exists('attachmentId', $item) || array_key_exists('uploadId', $item); }); if (!empty($attachments)) { error_log('Attachments: '.print_r($attachments, true)); return $this->queueMetaUpdate($attachments, absint($data['user']), sanitize_text_field($data['id']??'')); } return $this->sendResponse( false, ['error_code' => 'missing_identifiers'], 'Must provide either attachment_ids or operation_id' ); } catch (Exception $e) { Errors::getInstance()->log( '[UploadRoutes]:handleMetadataUpdate', $e->getMessage(), [ 'request_data' => $request->get_params(), 'trace' => $e->getTraceAsString() ] ); return $this->sendResponse( false, ['error_code' => 'metadata_update_failed'], 'Metadata update failed: ' . $e->getMessage() ); } } /** * Update metadata directly on completed attachments */ protected function updateMeta(array $data, int $user): WP_REST_Response { $updated_count = 0; $errors = []; $ids = []; foreach ($data as $info) { try { $attachment_id = $info['attachmentId']; error_log('Updating attachment ID:'.print_r($attachment_id,true)); $ids[] = $attachment_id; unset($info['attachmentId']); // Verify attachment exists and user has permission if (!$this->verifyAttachmentAccess($attachment_id, $user)) { $errors[] = "No permission to edit attachment {$attachment_id}"; continue; } $this->applyMeta($attachment_id, $info); $updated_count++; } catch (Exception $e) { $errors[] = "Failed to update attachment {$attachment_id}: " . $e->getMessage(); } } return $this->sendResponse( $updated_count > 0, [ 'updated_count' => $updated_count, 'errors' => $errors, 'attachment_ids' => $ids ], $updated_count > 0 ? "Updated metadata for {$updated_count} attachment(s)" : 'No attachments were updated' ); } /** * Queue metadata update with dependency on upload operation */ protected function queueMetaUpdate(array $data, int $user, ?string $operationId = null): WP_REST_Response { $queue = Queue::getInstance(); $depends_on = []; $errors = []; $original = count($data); foreach ($data as $uploadID => $info) { if (array_key_exists('depends_on', $info) && !in_array($info['depends_on'], $depends_on)) { $depends_on[] = $info['depends_on']; } } $queueData = [ 'depends_on' => $depends_on, ]; if ($operationId) { $queueData['operation_id'] = $operationId; } $operationID = $queue->queueOperation( 'update_image_meta', $user, $data, $queueData ); return $this->sendResponse( true, [ 'operation_id' => $operationID['operation_id']??$operationId, 'message' => "Successfully queued ".count($data)." of {$original} meta updates" ], 'Metadata update queued - will apply after upload completes' ); } protected function applyMeta(int $attachment_id, array $metadata): void { // Update alt text if (!empty($metadata['image-alt-text'])) { update_post_meta($attachment_id, '_wp_attachment_image_alt', sanitize_text_field($metadata['image-alt-text'])); } $postUpdates = []; // Update title if (!empty($metadata['image-title'])) { $postUpdates['post_title'] = $metadata['image-title']; } // Update caption if (!empty($metadata['image-caption'])) { $postUpdates['post_excerpt'] = sanitize_textarea_field($metadata['image-caption']); } if (!empty($postUpdates)) { $postUpdates['ID'] = $attachment_id; wp_update_post($postUpdates); } } /** * @param int $attachment_id * @param int $user_id * @return bool */ protected function verifyAttachmentAccess(int $attachment_id, int $user_id): bool { $attachment = get_post($attachment_id); if (!$attachment || $attachment->post_type !== 'attachment') { return false; } // Check if user owns the attachment or has admin privileges return ($attachment->post_author == $user_id) || current_user_can('manage_options'); } /** * Get files info for error logging * @param array $files * @return array */ protected function getFilesInfo(array $files): array { return [ 'files_count' => is_array($files['name']) ? count($files['name']) : 1, 'total_size' => is_array($files['size']) ? array_sum($files['size']) : $files['size'], 'file_types' => is_array($files['type']) ? array_unique($files['type']) : [$files['type']] ]; } protected function sendResponse(bool $success, array $data = [], string $message = '', string $operation_id = ''): WP_REST_Response { $response = [ 'success' => $success, 'message' => $message, 'data' => $data, 'timestamp' => current_time('mysql') ]; if ($operation_id) { $response['operation_id'] = $operation_id; } return $this->success($response); } public function handleGroupingRequest(WP_REST_Request $request): WP_REST_Response { try { $files = $request->get_file_params(); $args = $this->buildUploadArgs($request); if (!$args['user']) { return $this->unauthorized(); } if (!array_key_exists('content', $args) || empty($args['content'])) { return $this->validationError(['message'=>'Missing required content']); } if (!array_key_exists('posts', $args) || empty($args['posts'])) { return $this->validationError(['message' => 'Missing posts required']); } // Secure files to temporary storage $secured_files = $this->secureFiles($files, $args); if (empty($secured_files['files'])) { return $this->error('No valid files to upload'); } // Queue file upload operation $operation_type = $this->determineOperationType($secured_files['files'][0] ?? []); $chunkSize = 5; if ($operation_type === 'video') { $chunkSize = 1; } elseif ($operation_type === 'document') { $chunkSize = 10; } Queue::getInstance()->queueOperation( $operation_type, $args['user'], array_merge( ['secured_files' => $secured_files['files']], $args ), [ 'operation_id' => $args['upload'], 'chunk_key' => 'secured_files', 'chunk_size' => $chunkSize ] ); $ID = Queue::getInstance()->queueOperation( 'process_upload_groups', $args['user'], $args, [ 'operation_id' => $args['id'], 'depends_on' => [$args['upload']], 'priority' => 'high', 'chunk_key' => 'posts' ] ); return $this->queued($ID['operation_id'], 'Files uploaded and posts queued for creation'); } catch (Exception $e) { Errors::getInstance()->log( '[UploadRoutes]:handleGroupingRequest', $e->getMessage(), [ 'request_data' => $request->get_params(), 'trace' => $e->getTraceAsString() ] ); return $this->error('Grouping operation failed: '.$e->getMessage()); } } }