false, 'show_ui' => false, 'show_in_rest' => false, 'exclude_from_search' => true, 'can_export' => false, 'supports' => array())); } public static function menu() { add_submenu_page('seo-ai-connector', 'Cloud proposals', 'Cloud proposals', 'manage_options', 'ai4ranks-cloud-proposals', array(__CLASS__, 'render')); } public static function url() { return admin_url('admin.php?page=ai4ranks-cloud-proposals'); } private static function error($message, $status = 409) { return new WP_Error('ai4ranks_cloud_approval', $message, array('status' => $status)); } private static function routes() { $connector = SEO_AI_Connector::get_instance(); return array( '/seo-ai/v1/create-post' => array($connector, 'rest_create_post'), '/seo-ai/v1/apply-seo' => array($connector, 'rest_apply_seo'), '/seo-ai/v1/editorial' => 'ai4ranks_editorial_request', '/seo-ai/v1/link-repair' => 'ai4ranks_link_repair', '/seo-ai/v1/redirects' => 'ai4ranks_redirect_request', '/seo-ai/v1/solutions' => array('AI4Ranks_Solutions', 'request'), '/seo-ai/v1/agent-drafts' => array('AI4Ranks_Agent_Drafts', 'request'), ); } private static function read_only($route, $params) { if ($route === '/seo-ai/v1/editorial' || $route === '/seo-ai/v1/link-repair') return in_array($params['mode'] ?? null, array('read', 'preview'), true); if ($route === '/seo-ai/v1/redirects') return ($params['mode'] ?? null) === 'inspect'; if ($route === '/seo-ai/v1/solutions') return ($params['action'] ?? null) === 'inspect'; if ($route === '/seo-ai/v1/agent-drafts') return ($params['action'] ?? null) === 'capabilities'; return false; } private static function binding() { $token = get_option('seoai_site_token', ''); if (!is_string($token) || $token === '') return ''; $epoch = get_option('ai4ranks_connection_epoch', ''); if (!is_string($epoch) || $epoch === '') { add_option('ai4ranks_connection_epoch', wp_generate_uuid4(), '', false); $epoch = get_option('ai4ranks_connection_epoch', ''); } return is_string($epoch) && $epoch !== '' ? hash('sha256', get_current_blog_id() . ':' . $epoch . ':' . $token) : ''; } /** Validate all stored leaves. Reject altered values instead of approving a different payload. */ private static function clean_tree($value, $key, $depth, &$budget, $field) { if ($depth > 12 || --$budget < 0) return self::error('Proposal is too complex.', 422); if (is_array($value)) { $clean = array(); foreach ($value as $child_key => $child) { if (is_string($child_key) && (sanitize_key($child_key) !== $child_key || strlen($child_key) > 80)) return self::error('Invalid proposal field.', 422); $clean[$child_key] = self::clean_tree($child, is_string($child_key) ? $child_key : $key, $depth + 1, $budget, $field); if (is_wp_error($clean[$child_key])) return $clean[$child_key]; } return $clean; } if ($value === null || is_bool($value) || is_int($value) || (is_float($value) && is_finite($value))) return $value; if (!is_string($value) || strlen($value) > 500000) return self::error('Invalid proposal value.', 422); if (in_array($key, array('content_html', 'seo_paragraph', 'body'), true) || ($key === 'value' && in_array($field, array('content', 'short_description'), true))) $clean = wp_kses_post($value); elseif (in_array($key, array('source', 'target', 'canonical_url', 'cta_url', 'replacement', 'href'), true)) $clean = esc_url_raw($value, array('http', 'https')); elseif (in_array($key, array('title', 'meta_title', 'name', 'field', 'mode', 'action', 'operation', 'post_status'), true)) $clean = sanitize_text_field($value); else $clean = sanitize_textarea_field($value); return $clean === $value ? $clean : self::error('Proposal contains values that require sanitization. Prepare a fresh preview.', 422); } private static function normalize($route, $params) { $schemas = array( '/seo-ai/v1/create-post' => array('title', 'content_html', 'content', 'excerpt', 'tags', 'meta', 'post_status', 'status', 'slug', 'featured_image', 'category', 'author'), '/seo-ai/v1/apply-seo' => array('wp_post_id', 'seo_data', 'expected_version', 'expected_cms_revision', 'operation', 'content_html', 'post_status'), '/seo-ai/v1/editorial' => array('post_id', 'field', 'mode', 'image_id', 'value', 'revision', 'after_hash'), '/seo-ai/v1/link-repair' => array('post_id', 'mode', 'href', 'replacement', 'before_hash', 'after_hash'), '/seo-ai/v1/redirects' => array('source', 'mode', 'target', 'code', 'mapping_operation_id'), '/seo-ai/v1/solutions' => array('solution_id', 'action', 'expected_remote_version', 'source_version', 'config'), '/seo-ai/v1/agent-drafts' => array('action', 'draft_id', 'title', 'content_html', 'excerpt'), ); if (!isset($schemas[$route]) || !is_array($params) || array_diff(array_keys($params), array_merge($schemas[$route], array('operation_id')))) return self::error('Unsupported proposal fields.', 422); if (!is_string($params['operation_id'] ?? null) || !preg_match('/^[a-f0-9]{64}$/D', $params['operation_id'])) return self::error('Invalid operation ID.', 422); if ($route === '/seo-ai/v1/create-post') { // Older clients include fields this draft-only handler never uses. // Validate their shape, then retain only values the operation applies. foreach (array('status', 'slug', 'featured_image', 'category', 'author') as $ignored) { if (isset($params[$ignored]) && !is_scalar($params[$ignored])) return self::error('Invalid legacy draft field.', 422); unset($params[$ignored]); } if (isset($params['content_html']) && is_string($params['content_html']) && $params['content_html'] !== '') unset($params['content']); if (isset($params['post_status']) && !is_string($params['post_status'])) return self::error('Invalid draft status.', 422); $params['post_status'] = 'draft'; } foreach (array('title', 'content_html', 'content', 'excerpt', 'post_status', 'expected_cms_revision', 'operation', 'field', 'mode', 'value', 'revision', 'before_hash', 'after_hash', 'href', 'replacement', 'source', 'target', 'mapping_operation_id', 'solution_id', 'action', 'draft_id') as $key) { if (array_key_exists($key, $params) && !is_string($params[$key])) return self::error('Proposal text fields must be strings.', 422); } foreach (array('seo_data', 'tags', 'meta', 'config') as $key) { if (array_key_exists($key, $params) && !is_array($params[$key])) return self::error('Invalid proposal structure.', 422); } foreach (array('expected_version', 'expected_remote_version', 'source_version', 'code') as $key) { if (isset($params[$key]) && ((!is_int($params[$key]) && !is_string($params[$key])) || false === filter_var($params[$key], FILTER_VALIDATE_INT, array('options' => array('min_range' => 0))))) return self::error('Invalid proposal version or redirect code.', 422); } if ($route === '/seo-ai/v1/solutions' && (!is_string($params['solution_id'] ?? null) || !preg_match('/^sol_[a-f0-9]{32}$/D', $params['solution_id']))) return self::error('Invalid solution identity.', 422); if ($route === '/seo-ai/v1/apply-seo' && isset($params['post_status']) && !in_array($params['post_status'], array('', 'publish'), true)) return self::error('This operation cannot change a post to a different unpublished status.', 422); $budget = 1500; $clean = self::clean_tree($params, '', 0, $budget, $params['field'] ?? ''); if (is_wp_error($clean)) return $clean; foreach (array('wp_post_id', 'post_id', 'image_id') as $key) { if (isset($clean[$key]) && ((!is_int($clean[$key]) && !is_string($clean[$key])) || false === filter_var($clean[$key], FILTER_VALIDATE_INT, array('options' => array('min_range' => 0))))) return self::error('Invalid target ID.', 422); } return $clean; } public static function intercept($result, $request, $route, $handler) { if ($result !== null || !isset(self::routes()[$route])) return $result; $attributes = $request->get_attributes(); if (($attributes['ai4ranks_signed_write_verified'] ?? false) !== true || self::binding() === '') return self::error('Connect the service and authenticate the request first.', 401); $params = $request->get_json_params(); if (!is_array($params)) return self::error('A JSON object is required.', 400); if (self::read_only($route, $params)) return $result; if (strlen($request->get_body()) > 750000) return self::error('Proposal is too large.', 413); $clean = self::normalize($route, $params); if (is_wp_error($clean)) return $clean; return self::queue($route, $clean); } private static function seal($envelope) { return hash_hmac('sha256', wp_json_encode($envelope), wp_salt('auth')); } private static function queue($route, $params) { $binding = self::binding(); if ($binding === '') return self::error('Service disconnected.', 401); $hash = hash('sha256', $route . ':' . wp_json_encode($params)); $key = 'ai4ranks_proposal_' . hash('sha256', $binding . ':' . $route . ':' . $params['operation_id']); $existing = get_option($key, null); if ($existing !== null) { if (!is_array($existing) || ($existing['hash'] ?? '') !== $hash || empty($existing['id'])) return self::error('This operation is already claimed or has different values. Inspect Cloud proposals.'); $id = absint($existing['id']); if (get_post_meta($id, '_ai4ranks_cloud_state', true) === 'applied') { $stored = get_post_meta($id, '_ai4ranks_cloud_response', true); if (!is_array($stored) || !is_array($stored['receipt'] ?? null) || !is_string($stored['seal'] ?? null) || !hash_equals(self::seal($stored['receipt']), $stored['seal'])) return self::error('The completed result needs local inspection.'); $receipt = $stored['receipt']; if (!is_int($receipt['status'] ?? null) || $receipt['status'] < 200 || $receipt['status'] >= 300 || !is_array($receipt['data'] ?? null)) return self::error('The completed result is invalid.'); $receipt['data']['idempotent_replay'] = true; return new WP_REST_Response($receipt['data'], $receipt['status']); } } else { $pending = get_posts(array('post_type' => self::TYPE, 'post_status' => 'private', 'fields' => 'ids', 'numberposts' => 100, 'meta_key' => '_ai4ranks_cloud_state', 'meta_value' => 'pending')); $live = 0; foreach ($pending as $pending_id) if (!is_wp_error(self::load($pending_id))) $live++; if ($live >= 50) return self::error('Review the pending Cloud proposals before sending more.', 429); if (!add_option($key, array('hash' => $hash, 'id' => 0), '', false)) return self::error('Proposal is already being saved. Inspect Cloud proposals.'); $envelope = array('route' => $route, 'params' => $params, 'binding' => $binding, 'blog_id' => get_current_blog_id(), 'expires' => time() + HOUR_IN_SECONDS, 'target_state' => self::target_state($route, $params)); $id = wp_insert_post(array('post_type' => self::TYPE, 'post_status' => 'private', 'post_title' => 'AI4Ranks cloud proposal'), true); if (is_wp_error($id)) return $id; $record = array('envelope' => $envelope, 'seal' => self::seal($envelope)); update_post_meta($id, self::META, wp_slash_strings_only($record)); if (get_post_meta($id, self::META, true) !== $record) return self::error('Proposal storage could not be confirmed.', 500); update_post_meta($id, '_ai4ranks_cloud_state', 'pending'); update_option($key, array('hash' => $hash, 'id' => $id), false); } return new WP_Error('ai4ranks_approval_required', 'No website change was made. A WordPress administrator must review this operation in AI4Ranks > Cloud proposals: ' . self::url(), array('status' => 409, 'proposal_id' => $id, 'approval_url' => self::url(), 'requires_wordpress_approval' => true)); } private static function load($id) { $post = get_post($id); if (!$post || $post->post_type !== self::TYPE || $post->post_status !== 'private') return self::error('Proposal not found.', 404); $record = get_post_meta($id, self::META, true); if (!is_array($record) || !is_array($record['envelope'] ?? null) || !is_string($record['seal'] ?? null) || !hash_equals(self::seal($record['envelope']), $record['seal'])) return self::error('Proposal integrity check failed.'); $e = $record['envelope']; if (($e['blog_id'] ?? null) !== get_current_blog_id() || !is_int($e['expires'] ?? null) || $e['expires'] <= time() || self::binding() === '' || !hash_equals(self::binding(), $e['binding'] ?? '')) return self::error('Proposal expired or the service connection changed. Prepare a new proposal.'); if (!isset(self::routes()[$e['route'] ?? ''])) return self::error('Unsupported operation.'); $clean = self::normalize($e['route'], $e['params'] ?? null); if (is_wp_error($clean)) return $clean; return $e; } private static function target_state($route, $params) { $ids = array(absint($params['wp_post_id'] ?? ($params['post_id'] ?? 0)), absint($params['image_id'] ?? 0)); if ($route === '/seo-ai/v1/solutions') { $matches = get_posts(array('post_type' => 'page', 'post_status' => 'any', 'fields' => 'ids', 'numberposts' => 2, 'meta_key' => '_ai4ranks_solution_id', 'meta_value' => $params['solution_id'] ?? '')); $ids = array_merge($ids, $matches); } if ($route === '/seo-ai/v1/redirects' && is_string($params['target'] ?? null)) $ids[] = url_to_postid($params['target']); $state = array(); foreach (array_unique(array_filter($ids)) as $id) { $post = get_post($id); $state[$id] = $post ? array($post->post_title, $post->post_content, $post->post_excerpt, $post->post_status, $post->post_author, $post->post_modified_gmt, get_post_meta($id)) : null; } return hash('sha256', wp_json_encode($state)); } public static function target_unchanged($request) { $attributes = $request->get_attributes(); $expected = $attributes['ai4ranks_local_target_state'] ?? null; return is_string($expected) && hash_equals($expected, self::target_state($request->get_route(), $request->get_json_params())); } private static function permissions($e) { if (!current_user_can('manage_options')) return false; $p = $e['params']; $route = $e['route']; $id = absint($p['wp_post_id'] ?? ($p['post_id'] ?? 0)); if ($route === '/seo-ai/v1/solutions') { $matches = get_posts(array('post_type' => 'page', 'post_status' => 'any', 'numberposts' => 2, 'meta_key' => '_ai4ranks_solution_id', 'meta_value' => $p['solution_id'] ?? '')); if (count($matches) > 1) return false; $id = $matches ? $matches[0]->ID : 0; } if (in_array($route, array('/seo-ai/v1/editorial', '/seo-ai/v1/link-repair', '/seo-ai/v1/apply-seo'), true) && !$id) return false; if ($id && (!get_post($id) || !in_array(get_post($id)->post_type, array('post', 'page', 'product'), true) || !current_user_can('edit_post', $id))) return false; if (!empty($p['image_id']) && !current_user_can('edit_post', absint($p['image_id']))) return false; $type = get_post_type_object($route === '/seo-ai/v1/solutions' ? 'page' : ($id ? get_post($id)->post_type : 'post')); if (!$type) return false; if (!$id && in_array($route, array('/seo-ai/v1/create-post', '/seo-ai/v1/agent-drafts', '/seo-ai/v1/solutions'), true) && !current_user_can($type->cap->create_posts ?? $type->cap->edit_posts)) return false; if ($route === '/seo-ai/v1/apply-seo' && ($p['post_status'] ?? '') === 'publish' && !current_user_can($type->cap->publish_posts)) return false; return true; } public static function decide($id, $decision) { if (!current_user_can('manage_options')) return self::error('Administrator permission is required.', 403); $e = self::load($id); if (is_wp_error($e)) return $e; if (!in_array($decision, array('apply', 'reject'), true)) return self::error('Invalid decision.', 400); if ($decision === 'apply' && !self::permissions($e)) return self::error('You cannot edit or publish this target.', 403); if ($decision === 'apply' && !hash_equals($e['target_state'], self::target_state($e['route'], $e['params']))) return self::error('The target changed after this proposal was received. Prepare a fresh proposal.'); if (get_post_meta($id, '_ai4ranks_cloud_state', true) !== 'pending' || !add_option('ai4ranks_proposal_claim_' . $id, get_current_user_id(), '', false)) return self::error('This proposal has already been handled. Inspect the target before retrying.'); update_post_meta($id, '_ai4ranks_cloud_state', $decision === 'reject' ? 'rejected' : 'executing'); update_post_meta($id, '_ai4ranks_cloud_actor', get_current_user_id()); if ($decision === 'reject') return true; // Reload the connection and capabilities after the durable single-use claim. $e = self::load($id); if (is_wp_error($e) || !self::permissions($e) || !hash_equals($e['target_state'], self::target_state($e['route'], $e['params']))) { update_post_meta($id, '_ai4ranks_cloud_state', 'blocked'); return is_wp_error($e) ? $e : self::error('Permissions changed.', 403); } $request = new WP_REST_Request('POST', $e['route']); $request->set_header('Content-Type', 'application/json'); $request->set_body(wp_json_encode($e['params'])); $request->set_attributes(array('ai4ranks_signed_write_verified' => true, 'ai4ranks_local_target_state' => $e['target_state'])); try { $response = call_user_func(self::routes()[$e['route']], $request); } catch (Throwable $error) { $response = self::error('Execution was interrupted. Inspect the target before retrying.', 500); } $response = rest_ensure_response($response); $failed = is_wp_error($response) || $response->get_status() >= 400; if (!$failed) { $receipt = array('status' => $response->get_status(), 'data' => $response->get_data()); $stored = array('receipt' => $receipt, 'seal' => self::seal($receipt)); update_post_meta($id, '_ai4ranks_cloud_response', wp_slash_strings_only($stored)); if (get_post_meta($id, '_ai4ranks_cloud_response', true) !== $stored) { update_post_meta($id, '_ai4ranks_cloud_state', 'needs_inspection'); return self::error('The operation result could not be recorded. Inspect the target before retrying.', 500); } } update_post_meta($id, '_ai4ranks_cloud_state', $failed ? 'needs_inspection' : 'applied'); return $response; } public static function handle_decision() { if (!current_user_can('manage_options')) wp_die(esc_html__('Administrator permission is required.', 'ai4ranks-seo')); $id = isset($_POST['proposal_id']) && is_string($_POST['proposal_id']) ? absint(wp_unslash($_POST['proposal_id'])) : 0; if (!$id || !isset($_POST['_wpnonce']) || !is_string($_POST['_wpnonce'])) wp_die(esc_html__('Invalid proposal.', 'ai4ranks-seo')); check_admin_referer('ai4ranks_cloud_decision_' . $id); $decision = isset($_POST['decision']) && is_string($_POST['decision']) ? sanitize_key(wp_unslash($_POST['decision'])) : ''; $result = self::decide($id, $decision); if (is_wp_error($result)) wp_die(esc_html($result->get_error_message())); if ($result instanceof WP_REST_Response && $result->get_status() >= 400) wp_die(esc_html__('The operation was not confirmed. Inspect the target and proposal before retrying.', 'ai4ranks-seo')); wp_safe_redirect(self::url()); exit; } private static function show_values($value, $depth = 0) { if ($depth > 12) return; if (is_array($value)) { echo '
' . esc_html($text) . ''; } } public static function render() { if (!current_user_can('manage_options')) return; echo '
AI4Ranks can propose changes, but cannot apply them automatically. Review every proposed value before applying. Draft creation remains draft-only. Applying a publish request may make the target public.
Only an administrator with the required edit and publish permissions can apply a proposal. Proposals expire after one hour and become invalid after disconnecting or reconnecting.
'; $posts = get_posts(array('post_type' => self::TYPE, 'post_status' => 'private', 'numberposts' => 50)); if (!$posts) echo 'No cloud proposals have been received.
'; foreach ($posts as $post) { $state = get_post_meta($post->ID, '_ai4ranks_cloud_state', true); if (!is_string($state)) $state = 'needs_inspection'; $e = self::load($post->ID); echo '' . esc_html($e->get_error_message()) . '
Target: ' . esc_html(get_the_title($target_id)) . ' (#' . esc_html($target_id) . ')
'; self::show_values($e['params']); if ($state === 'pending') { echo ''; } echo ''; } echo '