'POST', 'callback' => array(__CLASS__, 'request'), 'permission_callback' => array(__CLASS__, 'permission'))); }); add_shortcode('ai4ranks_solution', array(__CLASS__, 'render')); } public static function permission($request) { if (!class_exists('SEO_AI_Connector')) return new WP_Error('ai4ranks_solution', 'Connector unavailable', array('status' => 503)); return SEO_AI_Connector::get_instance()->rest_signed_write_permission($request); } private static function verified($request) { if (!is_object($request) || !method_exists($request, 'get_attributes')) return false; $attributes = $request->get_attributes(); return is_array($attributes) && ($attributes['ai4ranks_signed_write_verified'] ?? null) === true; } private static function error($message, $status = 422) { return new WP_Error('ai4ranks_solution', $message, array('status' => $status)); } public static function validate_config($config) { if (!is_array($config)) return self::error('Configuration required'); $enums = array('schema_version' => array(1), 'template_id' => array('renovation'), 'locale' => array('en-GB','en-US','sq-AL','de-DE','fr-FR','it-IT'), 'currency' => array('EUR','USD','GBP','CHF','ALL'), 'unit_system' => array('metric','imperial')); $texts = array('name' => 120, 'description' => 1000, 'keyword' => 300, 'rate_source' => 300, 'cta_label' => 80, 'cta_url' => 2000, 'seo_title' => 160, 'meta_description' => 320); $numbers = array('rate' => array(0,1000000), 'fixed_cost' => array(0,1000000), 'coverage' => array(0,10000), 'waste_percent' => array(0,100), 'uncertainty_percent' => array(0,100)); $allowed = array_merge(array_keys($enums), array_keys($texts), array_keys($numbers)); if (array_diff(array_keys($config), $allowed) || array_diff($allowed, array_keys($config))) return self::error('Unsupported or missing configuration fields'); foreach ($enums as $key => $values) if (!in_array($config[$key], $values, true)) return self::error('Unsupported configuration version or option'); foreach ($texts as $key => $max) { if (!is_string($config[$key]) || strlen($config[$key]) > $max * 4) return self::error('Invalid text value'); } if (trim($config['name']) === '' || trim($config['rate_source']) === '') return self::error('Name and rate source are required'); foreach ($numbers as $key => $range) { $value = $config[$key]; if ($key === 'coverage' && $value === null) continue; if ((!is_int($value) && !is_float($value)) || !is_finite((float)$value) || $value < $range[0] || $value > $range[1]) return self::error('Invalid numeric value'); } if ($config['rate'] <= 0 || ($config['coverage'] !== null && $config['coverage'] <= 0)) return self::error('Rate and supplied coverage must be positive'); if ($config['cta_url'] !== '') { $url = wp_parse_url($config['cta_url']); if (!$url || ($url['scheme'] ?? '') !== 'https' || empty($url['host']) || isset($url['user']) || isset($url['pass']) || preg_match('/[\s<>\\\\]/', $config['cta_url'])) return self::error('CTA must use HTTPS without credentials'); } return $config; } private static function find_post($id) { $matches = get_posts(array('post_type' => 'page', 'post_status' => array('draft','publish','private','pending','future','trash'), 'meta_key' => '_ai4ranks_solution_id', 'meta_value' => $id, 'numberposts' => 2)); if (count($matches) > 1) return self::error('Multiple pages claim this solution', 409); if ($matches) return $matches[0]; // A stable slug prevents creation of a second post after an interrupted request. return get_page_by_path('ai4ranks-' . $id, OBJECT, 'page'); } private static function state($id, $post, $stored) { return array('schema_version' => 1, 'solution_id' => $id, 'remote_version' => $stored ? $stored['version'] : 0, 'source_version' => $stored ? $stored['source_version'] : null, 'post_status' => $post ? $post->post_status : 'missing', 'wp_post_id' => $post ? (int)$post->ID : null, 'edit_url' => $post ? admin_url('post.php?post=' . (int)$post->ID . '&action=edit') : '', 'preview_url' => $post ? add_query_arg(array('page_id' => (int)$post->ID, 'preview' => 'true'), home_url('/')) : '', 'operation_id' => $stored ? $stored['operation_id'] : null); } public static function request($request) { if (!self::verified($request)) return self::error('Invalid, expired or replayed write signature', 401); if (strlen($request->get_body()) > 24000) return self::error('Request too large'); $params = $request->get_json_params(); if (!is_array($params)) return self::error('A JSON request body is required', 400); $id = $params['solution_id'] ?? null; $action = $params['action'] ?? null; if (!is_string($id) || !preg_match('/^sol_[a-f0-9]{32}$/D', $id) || !in_array($action, array('inspect','sync','rollback'), true)) return self::error('Invalid solution request'); global $wpdb; $lock = 'ai4ranks_sol_' . substr(hash('sha256', get_current_blog_id() . ':' . $id), 0, 40); if ((string)$wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)', $lock)) !== '1') return self::error('Another solution operation is running', 409); try { return self::locked_request($params, $id, $action); } finally { $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $lock)); } } private static function locked_request($params, $id, $action) { $post = self::find_post($id); if (is_wp_error($post)) return $post; $stored = $post ? get_post_meta($post->ID, '_ai4ranks_solution_state', true) : null; if ($post && (!is_array($stored) || ($stored['solution_id'] ?? '') !== $id)) return self::error('This page is not managed by this solution', 409); if ($action === 'inspect') return rest_ensure_response(self::state($id, $post, $stored)); // This release never edits a published page, or replaces owner-written content. if ($post && ($post->post_status !== 'draft' || trim($post->post_content) !== '[ai4ranks_solution]')) return self::error('Only unchanged, managed drafts can be updated', 409); $expected = $params['expected_remote_version'] ?? null; $operation = $params['operation_id'] ?? null; $source = $params['source_version'] ?? null; if (!is_int($expected) || $expected < 0 || $expected >= 100 || !is_int($source) || $source < 1 || $source > 100 || !is_string($operation) || !preg_match('/^[a-f0-9]{64}$/D', $operation)) return self::error('Invalid revision request'); $fingerprint = hash('sha256', wp_json_encode(array($id, $action, $expected, $source, $params['config'] ?? null))); if ($stored && $stored['operation_id'] === $operation) { if (!hash_equals($stored['fingerprint'], $fingerprint)) return self::error('Operation key reused with different data', 409); return rest_ensure_response(self::state($id, $post, $stored)); } $version = $stored ? $stored['version'] : 0; if ($expected !== $version) return self::error('WordPress revision changed', 409); if ($action === 'rollback') { if (!$stored || count($stored['history']) < 2) return self::error('No earlier WordPress revision', 409); $previous = $stored['history'][count($stored['history']) - 2]; $config = self::validate_config($previous['config']); $source = $previous['source_version']; } else $config = self::validate_config($params['config'] ?? null); if (is_wp_error($config)) return $config; $history = $stored ? $stored['history'] : array(); $history[] = array('version' => $version + 1, 'source_version' => $source, 'config' => $config); $next = array('solution_id' => $id, 'version' => $version + 1, 'source_version' => $source, 'config' => $config, 'operation_id' => $operation, 'fingerprint' => $fingerprint, 'history' => $history); if (!$post) { $post_id = wp_insert_post(array('post_type' => 'page', 'post_status' => 'draft', 'post_name' => 'ai4ranks-' . $id, 'post_title' => wp_slash(sanitize_text_field($config['name'])), 'post_content' => '[ai4ranks_solution]', 'meta_input' => array('_ai4ranks_solution_id' => $id, '_ai4ranks_solution_state' => wp_slash($next))), true); if (is_wp_error($post_id)) return self::error('WordPress could not create the draft', 500); $post = get_post($post_id); } else { // Guard status/content in the write itself: a simultaneous editor publish // or content edit must not turn a draft operation into a live-page update. // Compare bytes so a case-insensitive database collation cannot accept // a changed shortcode or serialized state as the approved version. global $wpdb; $changed = $wpdb->query($wpdb->prepare( "UPDATE {$wpdb->postmeta} AS m INNER JOIN {$wpdb->posts} AS p ON p.ID = m.post_id SET m.meta_value = %s WHERE p.ID = %d AND p.post_status = 'draft' AND BINARY p.post_content = BINARY %s AND m.meta_key = '_ai4ranks_solution_state' AND BINARY m.meta_value = BINARY %s", maybe_serialize($next), $post->ID, '[ai4ranks_solution]', maybe_serialize($stored) )); if ($changed !== 1) return self::error('The draft changed while saving; inspect before retrying', 409); wp_cache_delete($post->ID, 'post_meta'); clean_post_cache($post->ID); } $actual = get_post_meta($post->ID, '_ai4ranks_solution_state', true); if (!is_array($actual) || ($actual['operation_id'] ?? '') !== $operation) return self::error('Draft save was not confirmed; inspect before retrying', 500); return rest_ensure_response(self::state($id, $post, $actual)); } public static function render() { $post = get_post(); if (!$post) return ''; $stored = get_post_meta($post->ID, '_ai4ranks_solution_state', true); if (!is_array($stored)) return ''; $config = self::validate_config($stored['config'] ?? null); if (is_wp_error($config)) return '

Solution configuration is unavailable.

'; wp_enqueue_script('ai4ranks-solution-runtime', plugins_url('assets/solutions.js', dirname(__DIR__) . '/ai4ranks-seo.php'), array(), '1.0.0', true); $input_id = wp_unique_id('ai4ranks-area-'); $area = $config['unit_system'] === 'imperial' ? 'ft²' : 'm²'; ob_start(); ?>


How it works

Estimate = floor area × owner rate + fixed cost. The range applies the owner's uncertainty percentage. This is an estimate, not a binding quote.

Rate: . Fixed cost: .

Source (owner supplied):