draft_manager = new DraftContentManager(); } /** * Register REST API routes */ public function register_routes() { register_rest_route('aipt/v1', '/draft-content', [ [ 'methods' => 'GET', 'callback' => [$this, 'get_draft_content'], 'permission_callback' => [$this, 'check_permissions'], 'args' => [ 'page' => [ 'default' => 1, 'type' => 'integer', 'minimum' => 1, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ], 'per_page' => [ 'default' => 20, 'type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'sanitize_callback' => 'absint', 'validate_callback' => 'rest_validate_request_arg', ], 'status' => [ 'default' => 'pending', 'sanitize_callback' => 'sanitize_text_field', ], 'job_id' => [ 'sanitize_callback' => 'absint', ], 'product_id' => [ 'sanitize_callback' => 'absint', ], 'content_type' => [ 'sanitize_callback' => 'sanitize_text_field', ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/(?P\d+)/current-value', [ [ 'methods' => 'GET', 'callback' => [$this, 'get_draft_current_value'], 'permission_callback' => [$this, 'check_permissions'], 'args' => [ 'id' => [ 'required' => true, 'sanitize_callback' => 'absint', ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/(?P\d+)/approve', [ [ 'methods' => 'POST', 'callback' => [$this, 'approve_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'sanitize_callback' => 'absint', ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/(?P\d+)/reject', [ [ 'methods' => 'POST', 'callback' => [$this, 'reject_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'sanitize_callback' => 'absint', ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/bulk-approve', [ [ 'methods' => 'POST', 'callback' => [$this, 'bulk_approve_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'ids' => [ 'required' => true, 'validate_callback' => function($param) { return is_array($param) && !empty($param); }, 'sanitize_callback' => function($param) { return array_map('absint', $param); }, ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/bulk-reject', [ [ 'methods' => 'POST', 'callback' => [$this, 'bulk_reject_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'ids' => [ 'required' => true, 'validate_callback' => function($param) { return is_array($param) && !empty($param); }, 'sanitize_callback' => function($param) { return array_map('absint', $param); }, ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/bulk-delete', [ [ 'methods' => 'POST', 'callback' => [$this, 'bulk_delete_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'ids' => [ 'required' => true, 'validate_callback' => function($param) { return is_array($param) && !empty($param); }, 'sanitize_callback' => function($param) { return array_map('absint', $param); }, ], ], ], ]); register_rest_route('aipt/v1', '/draft-content/(?P\d+)', [ [ 'methods' => 'DELETE', 'callback' => [$this, 'delete_draft_content'], 'permission_callback' => [$this, 'check_permissions_write'], 'args' => [ 'id' => [ 'required' => true, 'sanitize_callback' => 'absint', ], ], ], ]); } /** * Check permissions for API access * * @param WP_REST_Request $request Request object * @return bool|WP_Error Permission status */ public function check_permissions($request) { if (!current_user_can('manage_woocommerce')) { return new WP_Error( 'rest_forbidden', __('You do not have permission to access this resource.', 'ai-product-tools'), ['status' => 403] ); } $gate_result = $this->check_business_gate(); if ($gate_result instanceof WP_Error) { return $gate_result; } return true; } /** * Check the Business entitlement required by every draft-review route. * * @return WP_Error|null Error when access is denied, otherwise null. */ private function check_business_gate() { if (!apply_filters('aipt_draft_review_enabled', false)) { return PlanDenial::error( 'reviewPolicy', PlanDenial::PLAN_BUSINESS, __('Draft review requires a Business plan.', 'ai-product-tools') ); } return null; } /** * Check permissions for all Business-gated write operations. * * Requires manage_woocommerce, a valid REST nonce, the Business * draft-review gate, and per-product edit_post * authorization for every targeted draft. * * @param WP_REST_Request $request * @return bool|WP_Error */ public function check_permissions_write($request) { $auth_result = $this->check_auth_and_nonce($request); if (true !== $auth_result) { return $auth_result; } $gate_result = $this->check_business_gate(); if ($gate_result instanceof WP_Error) { return $gate_result; } return $this->check_draft_idor($request); } /** * Shared capability + nonce check for all write routes. * * @param WP_REST_Request $request * @return bool|WP_Error */ private function check_auth_and_nonce($request) { if (!current_user_can('manage_woocommerce')) { return new WP_Error( 'rest_forbidden', __('You do not have permission to perform this action.', 'ai-product-tools'), ['status' => 403] ); } return \AIPT\Utils\RestNonceGuard::check( $request, __('Invalid or missing security nonce.', 'ai-product-tools') ); } /** * Shared per-product IDOR guard for all write routes: preflight every * targeted draft before the first write. If any product is not editable * by the caller, return rest_forbidden with zero writes performed. * * @param WP_REST_Request $request * @return bool|WP_Error */ private function check_draft_idor($request) { $draft_ids = $this->resolve_draft_ids_from_request($request); if (!empty($draft_ids)) { foreach ($draft_ids as $draft_id) { $product_id = $this->get_draft_product_id($draft_id); if ($product_id > 0 && !current_user_can('edit_post', $product_id)) { return new WP_Error( 'rest_forbidden', __('You do not have permission to edit this product.', 'ai-product-tools'), ['status' => 403] ); } } } return true; } /** * Extract draft IDs from the request for the per-product IDOR preflight. * * @param WP_REST_Request $request Request object. * @return int[] */ private function resolve_draft_ids_from_request($request): array { $ids = []; $id = $request->get_param('id'); if (is_numeric($id) && (int) $id > 0) { $ids[] = (int) $id; } $bulk_ids = $request->get_param('ids'); if (is_array($bulk_ids) && !empty($bulk_ids)) { foreach ($bulk_ids as $bulk_id) { if (is_numeric($bulk_id) && (int) $bulk_id > 0) { $ids[] = (int) $bulk_id; } } } return $ids; } /** * Look up the product_id for a draft by its id. * * @param int $draft_id Draft content id. * @return int Product id, or 0 if not found. */ private function get_draft_product_id(int $draft_id): int { global $wpdb; $table = $wpdb->prefix . 'aipt_draft_content'; $product_id = $wpdb->get_var($wpdb->prepare( "SELECT product_id FROM {$table} WHERE id = %d", $draft_id )); return $product_id ? (int) $product_id : 0; } /** * Look up a draft row's id/product_id/content_type/generated_content by * its id — the fields {@see get_draft_current_value()} needs, without * pulling the whole row (job_id, status timestamps, ...) it doesn't. * * @param int $draft_id Draft content id. * @return array{id:int,product_id:int,content_type:string,generated_content:string}|null */ private function get_draft_row(int $draft_id): ?array { global $wpdb; $table = $wpdb->prefix . 'aipt_draft_content'; $row = $wpdb->get_row($wpdb->prepare( "SELECT id, product_id, content_type, generated_content FROM {$table} WHERE id = %d", $draft_id ), ARRAY_A); if (!is_array($row)) { return null; } return [ 'id' => (int) $row['id'], 'product_id' => (int) $row['product_id'], 'content_type' => (string) $row['content_type'], 'generated_content' => (string) $row['generated_content'], ]; } /** * Read the live field value(s) a pending draft would replace * (H3-drafts-bank). Mirrors ContentReviewController::get_current_value() * (H3-review-bank), adapted for two structural differences the Drafts * schema has that Review's does not: * * - a `seo_meta` draft carries BOTH meta fields in one JSON row (Review * stages them as two separate `seo_meta_title`/`seo_meta_description` * rows), so this reads both canonical field types and returns them as * one structured payload instead of a single string; * - an `image_alt` draft can carry MULTIPLE `{attachment_id, alt_text}` * pairs in one row (Review stages one row per attachment), so this * decodes the draft's own JSON and reads each attachment's live alt * text individually. * * Every other content_type (title/description/short_description/tags/ * faq) maps 1:1 onto {@see SnapshotStore::readCurrentFieldValue()} * exactly like Review's simple fields do. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_draft_current_value($request) { $id = absint($request->get_param('id')); $row = $this->get_draft_row($id); if (null === $row) { return new WP_Error( 'draft_not_found', __('That draft item could not be found.', 'ai-product-tools'), ['status' => 404] ); } $product_id = $row['product_id']; if ($product_id <= 0 || !current_user_can('edit_post', $product_id)) { return new WP_Error( 'rest_forbidden', __('You do not have permission to view this product\'s draft.', 'ai-product-tools'), ['status' => 403] ); } $store = new SnapshotStore(); $content_type = $row['content_type']; try { switch ($content_type) { case 'seo_meta': return new WP_REST_Response([ 'success' => true, 'data' => [ 'seo_meta' => [ 'meta_title' => $store->readCurrentFieldValue($product_id, 'seo_meta_title'), 'meta_description' => $store->readCurrentFieldValue($product_id, 'seo_meta_description'), 'focus_keyword' => $store->readCurrentFieldValue($product_id, 'seo_meta_focus_keyword'), ], ], ], 200); case 'image_alt': $decoded = json_decode($row['generated_content'], true); $items = []; if (is_array($decoded)) { foreach ($decoded as $entry) { if (!is_array($entry)) { continue; } $attachment_id = absint($entry['attachment_id'] ?? 0); if ($attachment_id <= 0) { continue; } $items[] = [ 'attachment_id' => $attachment_id, 'current_alt' => $store->readCurrentFieldValue($product_id, 'image_alt', $attachment_id), 'proposed_alt' => (string) ($entry['alt_text'] ?? ''), ]; } } return new WP_REST_Response([ 'success' => true, 'data' => ['image_alt' => ['items' => $items]], ], 200); case 'tags': $current_tags = $store->readCurrentFieldValue($product_id, 'tags'); $decoded_tags = json_decode((string) $current_tags, true); return new WP_REST_Response([ 'success' => true, 'data' => [ 'current_value' => is_array($decoded_tags) ? implode(', ', array_map('strval', $decoded_tags)) : $current_tags, ], ], 200); case 'title': case 'description': case 'short_description': case 'faq': return new WP_REST_Response([ 'success' => true, 'data' => ['current_value' => $store->readCurrentFieldValue($product_id, $content_type)], ], 200); default: return new WP_REST_Response([ 'success' => true, 'data' => ['current_value' => null], ], 200); } } catch (\RuntimeException $e) { return new WP_REST_Response([ 'success' => true, 'data' => ['current_value' => null], ], 200); } } /** * Get draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ /** * Enrich draft rows with SKU and thumbnail URL. * * `product_name` already reaches these rows via the SQL join in * DraftContentManager::getDraftContent() — this only adds the two fields * that join can't carry (SKU and the thumbnail live in postmeta, not on * the posts row it's already joining against). One batch resolve over the * distinct product ids on this page, not one lookup per row. * * @param object[] $rows Draft rows as returned by $wpdb->get_results() (stdClass, no ARRAY_A). * @return object[] */ private function addProductIdentity(array $rows): array { $product_ids = []; foreach ($rows as $row) { if (isset($row->product_id)) { $product_ids[] = (int) $row->product_id; } } $identities = (new ProductIdentityResolver())->resolve($product_ids); foreach ($rows as $row) { $product_id = isset($row->product_id) ? (int) $row->product_id : 0; $identity = $identities[$product_id] ?? [ 'sku' => '', 'thumbnail_url' => null, ]; $row->sku = $identity['sku']; $row->thumbnail_url = $identity['thumbnail_url']; } return $rows; } /** * Report draft timestamps in UTC. * * Automation tables store site time (current_time('mysql')), and * DraftContentManager compares these columns with other automation * timestamps, so the conversion happens here, at the REST boundary: * the Content Bank reads every created_at-style value as UTC. * * @param object[] $rows Draft rows. * @return object[] */ private function withUtcTimes(array $rows): array { foreach ($rows as $row) { foreach (['created_at', 'updated_at', 'approved_at'] as $column) { $value = isset($row->$column) ? (string) $row->$column : ''; if (1 === preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value) && '0000-00-00 00:00:00' !== $value) { $row->$column = get_gmt_from_date($value); } } } return $rows; } public function get_draft_content($request) { try { $page = $request->get_param('page'); $per_page = min($request->get_param('per_page'), 100); $offset = ($page - 1) * $per_page; $filters = []; if ($request->get_param('status')) { $filters['status'] = $request->get_param('status'); } if ($request->get_param('job_id')) { $filters['job_id'] = $request->get_param('job_id'); } if ($request->get_param('product_id')) { $filters['product_id'] = $request->get_param('product_id'); } if ($request->get_param('content_type')) { $filters['content_type'] = $request->get_param('content_type'); } $draft_content = $this->draft_manager->getDraftContent($filters, $per_page, $offset); $draft_content = $this->withUtcTimes($this->addProductIdentity((array) $draft_content)); $total_count = $this->draft_manager->getDraftContentCount($filters); return new WP_REST_Response([ 'success' => true, 'data' => [ 'items' => $draft_content, 'pagination' => [ 'page' => $page, 'per_page' => $per_page, 'total' => $total_count, 'total_pages' => ceil($total_count / $per_page), ], ], ], 200); } catch (\Exception $e) { return new WP_Error( 'draft_content_error', $e->getMessage(), ['status' => 500] ); } } /** * Approve draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function approve_draft_content($request) { try { $draft_id = $request->get_param('id'); $success = $this->draft_manager->approveDraftContent($draft_id); if ($success) { return new WP_REST_Response([ 'success' => true, 'message' => __('Draft content approved and applied to product successfully.', 'ai-product-tools'), ], 200); } else { $refusal = $this->draft_manager->getLastApprovalError(); if ($refusal instanceof WP_Error) { return $refusal; } return new WP_Error( 'approval_failed', __('Failed to approve draft content.', 'ai-product-tools'), ['status' => 500] ); } } catch (\Exception $e) { return new WP_Error( 'approval_error', $e->getMessage(), ['status' => 500] ); } } /** * Reject draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function reject_draft_content($request) { try { $draft_id = $request->get_param('id'); $success = $this->draft_manager->rejectDraftContent($draft_id); if ($success) { return new WP_REST_Response([ 'success' => true, 'message' => __('Draft content rejected successfully.', 'ai-product-tools'), ], 200); } else { $refusal = $this->draft_manager->getLastRejectionError(); if ($refusal instanceof WP_Error) { return $refusal; } return new WP_Error( 'rejection_failed', __('Failed to reject draft content.', 'ai-product-tools'), ['status' => 500] ); } } catch (\Exception $e) { return new WP_Error( 'rejection_error', $e->getMessage(), ['status' => 500] ); } } /** * Per-draft refusal reasons of the last bulk approve or reject. * * Only drafts the manager recorded a specific refusal for appear here; the * client falls back to a generic reason for any other failed id. * * @return array */ private function bulkSkippedList() { $skipped = []; foreach ($this->draft_manager->getLastBulkFailures() as $draft_id => $reason) { $skipped[] = ['id' => (int) $draft_id, 'reason' => (string) $reason]; } return $skipped; } /** * Bulk approve draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function bulk_approve_draft_content($request) { try { $draft_ids = $request->get_param('ids'); $results = $this->draft_manager->bulkApproveDraftContent($draft_ids); $success_count = count(array_filter($results)); $total_count = count($results); return new WP_REST_Response([ 'success' => true, 'message' => sprintf( /* translators: 1: Number of successfully approved items, 2: Total number of items */ __('Bulk approval completed: %1$d of %2$d items approved successfully.', 'ai-product-tools'), $success_count, $total_count ), 'data' => [ 'results' => $results, 'success_count' => $success_count, 'total_count' => $total_count, 'skipped' => $this->bulkSkippedList(), ], ], 200); } catch (\Exception $e) { return new WP_Error( 'bulk_approval_error', $e->getMessage(), ['status' => 500] ); } } /** * Bulk reject draft content * * Mirrors bulk_approve_draft_content() exactly for nonce, capability, * Business gate, per-product authorization, and response shape. * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function bulk_reject_draft_content($request) { try { $draft_ids = $request->get_param('ids'); $results = $this->draft_manager->bulkRejectDraftContent($draft_ids); $success_count = count(array_filter($results)); $total_count = count($results); return new WP_REST_Response([ 'success' => true, 'message' => sprintf( /* translators: 1: Number of successfully rejected items, 2: Total number of items */ __('Bulk rejection completed: %1$d of %2$d items rejected successfully.', 'ai-product-tools'), $success_count, $total_count ), 'data' => [ 'results' => $results, 'success_count' => $success_count, 'total_count' => $total_count, 'skipped' => $this->bulkSkippedList(), ], ], 200); } catch (\Exception $e) { return new WP_Error( 'bulk_rejection_error', $e->getMessage(), ['status' => 500] ); } } /** * Bulk delete draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function bulk_delete_draft_content($request) { try { $draft_ids = $request->get_param('ids'); $results = $this->draft_manager->bulkDeleteDraftContent($draft_ids); $success_count = count(array_filter($results)); $total_count = count($results); return new WP_REST_Response([ 'success' => true, 'message' => sprintf( /* translators: 1: Number of successfully deleted items, 2: Total number of items */ __('Bulk deletion completed: %1$d of %2$d items deleted successfully.', 'ai-product-tools'), $success_count, $total_count ), 'data' => [ 'results' => $results, 'success_count' => $success_count, 'total_count' => $total_count, ], ], 200); } catch (\Exception $e) { return new WP_Error( 'bulk_deletion_error', $e->getMessage(), ['status' => 500] ); } } /** * Delete draft content * * @param WP_REST_Request $request Request object * @return WP_REST_Response|WP_Error Response object */ public function delete_draft_content($request) { try { $draft_id = $request->get_param('id'); $success = $this->draft_manager->deleteDraftContent($draft_id); if ($success) { return new WP_REST_Response([ 'success' => true, 'message' => __('Draft content deleted successfully.', 'ai-product-tools'), ], 200); } else { return new WP_Error( 'deletion_failed', __('Failed to delete draft content.', 'ai-product-tools'), ['status' => 500] ); } } catch (\Exception $e) { return new WP_Error( 'deletion_error', $e->getMessage(), ['status' => 500] ); } } }