'attachment', 'post_parent' => $post->ID, 'post_mime_type' => 'image', 'fields' => 'ids', 'numberposts' => 20))); $ids[] = (int) get_post_thumbnail_id($post->ID); $ids = array_merge($ids, array_map('intval', explode(',', (string) get_post_meta($post->ID, '_product_image_gallery', true)))); return array_slice(array_values(array_unique(array_filter($ids))), 0, 30); } function ai4ranks_editorial_snapshot($post, $field, $image_id) { $target = (int) $post->ID; $key = ''; if ($field === 'content') $value = $post->post_content; elseif ($field === 'short_description') $value = $post->post_excerpt; else { $keys = array('focus_keyword' => '_ai4ranks_focus_keyword', 'structured_data' => '_ai4ranks_editorial_schema', 'alt_text' => '_wp_attachment_image_alt'); $key = $keys[$field]; if ($field === 'alt_text') $target = $image_id; $values = get_post_meta($target, $key, false); if (count($values) > 1) return new WP_Error('duplicate', 'Duplicate metadata requires manual cleanup'); $value = count($values) ? (string) $values[0] : ''; } return array('value' => $value, 'target_id' => $target, 'meta_key' => $key, 'revision' => hash('sha256', wp_json_encode(array($post->ID, $field, $image_id, $post->post_content, $post->post_excerpt, $post->post_modified_gmt, $value)))); } function ai4ranks_editorial_clear_cache($post_id, $target_id) { clean_post_cache($post_id); if ($target_id !== $post_id) clean_post_cache($target_id); wp_cache_delete($target_id, 'post_meta'); } function ai4ranks_editorial_request($request) { // Route authentication binds this id to the exact JSON body and consumes // its nonce. Keep the handler strict if it is ever dispatched directly. $params = $request->get_json_params(); if (!is_array($params)) { return new WP_REST_Response(array('message' => 'A JSON request body is required'), 400); } foreach (array('operation_id', 'field', 'mode', 'revision', 'after_hash') as $key) { if (array_key_exists($key, $params) && !is_string($params[$key])) { return new WP_REST_Response(array('message' => 'Editorial request fields must be strings'), 400); } } foreach (array('post_id', 'image_id') as $key) { if (!array_key_exists($key, $params)) continue; $id_value = $params[$key]; if (is_string($id_value) && preg_match('/^[0-9]+$/D', $id_value)) { $id_value = ltrim($id_value, '0'); if ($id_value === '') $id_value = '0'; } elseif (!is_int($id_value)) { return new WP_REST_Response(array('message' => 'Editorial IDs must be non-negative integers'), 400); } if (false === filter_var($id_value, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) { return new WP_REST_Response(array('message' => 'Editorial IDs must be non-negative integers'), 400); } $params[$key] = (int) $id_value; } $operation_id = strtolower((string) ($params['operation_id'] ?? '')); if (!preg_match('/^[a-f0-9]{64}$/D', $operation_id)) { return new WP_REST_Response(array('message' => 'A signed operation_id is required'), 401); } $id = absint($params['post_id'] ?? 0); $post = get_post($id); $field = (string) ($params['field'] ?? ''); $mode = (string) ($params['mode'] ?? ''); $image_id = absint($params['image_id'] ?? 0); $allowed = array('content', 'short_description', 'focus_keyword', 'structured_data', 'alt_text'); if (!$post || $post->post_status !== 'publish' || !in_array($post->post_type, array('page', 'post', 'product'), true) || !in_array($field, $allowed, true) || !in_array($mode, array('read', 'preview', 'apply'), true)) { return new WP_REST_Response(array('message' => 'Unsupported editorial resource or field'), 409); } if (get_post_meta($id, '_elementor_edit_mode', true) || strpos($post->post_content, '[vc_') !== false || strlen($post->post_content) > 500000) { return new WP_REST_Response(array('message' => 'Use the native editor for builder-managed or oversized content'), 409); } $images = ai4ranks_editorial_images($post); if ($field === 'alt_text' && (!in_array($image_id, $images, true) || !wp_attachment_is_image($image_id))) { return new WP_REST_Response(array('message' => 'Select an image belonging to this resource'), 409); } $snapshot = ai4ranks_editorial_snapshot($post, $field, $image_id); if (is_wp_error($snapshot)) return new WP_REST_Response(array('message' => $snapshot->get_error_message()), 409); $result = array('editorial_version' => 1, 'post_id' => $id, 'field' => $field, 'image_id' => $image_id, 'before' => $snapshot['value'], 'revision' => $snapshot['revision'], 'url' => get_permalink($id), 'images' => array_map(function($image) { return array('id' => $image, 'url' => wp_get_attachment_url($image), 'alt' => (string) get_post_meta($image, '_wp_attachment_image_alt', true)); }, $images)); if ($mode === 'read') return new WP_REST_Response($result, 200); $value = $params['value'] ?? null; if (!is_string($value) || strlen($value) > 500000) return new WP_REST_Response(array('message' => 'Invalid editorial value'), 422); if (in_array($field, array('content', 'short_description'), true)) $value = wp_kses_post($value); elseif ($field === 'structured_data' && $value !== '') { $json = json_decode($value, true); if (!is_array($json) || ($json['@context'] ?? '') !== 'https://schema.org' || empty($json['@type']) || strlen($value) > 30000) { return new WP_REST_Response(array('message' => 'Use one JSON-LD object with https://schema.org context and a type'), 422); } $value = wp_json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } else { $value = sanitize_text_field($value); if (strlen($value) > 500) return new WP_REST_Response(array('message' => 'Text field is too long'), 422); } $result['after'] = $value; $result['after_hash'] = hash('sha256', $value); if ($mode === 'preview') return new WP_REST_Response($result, 200); if (!hash_equals($snapshot['revision'], (string) ($params['revision'] ?? '')) || !hash_equals($result['after_hash'], (string) ($params['after_hash'] ?? ''))) { return new WP_REST_Response(array('message' => 'Preview changed; nothing overwritten'), 409); } global $wpdb; // Metadata insert/update requires transactional tables and a range lock. foreach (array($wpdb->posts, $wpdb->postmeta) as $table) { $engine = $wpdb->get_var($wpdb->prepare('SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s', $table)); if (strtoupper((string) $engine) !== 'INNODB') return new WP_REST_Response(array('message' => 'Transactional WordPress tables required'), 409); } wp_save_post_revision($id); if ($wpdb->query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE') === false || $wpdb->query('START TRANSACTION') === false) return new WP_REST_Response(array('message' => 'Could not start conditional write'), 409); try { // These reads must reach the database: a cached value cannot acquire // the row/range locks that make the subsequent write conditional. $locked_post = $wpdb->get_row($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d FOR UPDATE", $id)); if (!$locked_post || (int) $locked_post->ID !== $id) throw new Exception('Could not lock resource'); if ($snapshot['target_id'] !== $id) { $locked_target = $wpdb->get_row($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE ID = %d FOR UPDATE", $snapshot['target_id'])); if (!$locked_target || (int) $locked_target->ID !== $snapshot['target_id']) throw new Exception('Could not lock image'); } $meta_rows = array(); if ($snapshot['meta_key']) { $meta_rows = $wpdb->get_results($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = %s FOR UPDATE", $snapshot['target_id'], $snapshot['meta_key'])); // wpdb can return an empty array on a failed SELECT as well as // when metadata is absent, so check the query error explicitly. if (!is_array($meta_rows) || !empty($wpdb->last_error) || count($meta_rows) > 1) throw new Exception('Could not lock unique metadata'); } ai4ranks_editorial_clear_cache($id, $snapshot['target_id']); $current_post = get_post($id); if (!$current_post || $current_post->post_status !== 'publish' || !in_array($current_post->post_type, array('page', 'post', 'product'), true)) throw new Exception('Resource changed while saving'); if ($field === 'alt_text' && (!in_array($image_id, ai4ranks_editorial_images($current_post), true) || !wp_attachment_is_image($image_id))) throw new Exception('Image ownership changed'); $current = ai4ranks_editorial_snapshot($current_post, $field, $image_id); if (is_wp_error($current) || !hash_equals($snapshot['revision'], $current['revision'])) throw new Exception('Content changed while saving'); if ($snapshot['meta_key']) { $ok = $meta_rows ? $wpdb->update($wpdb->postmeta, array('meta_value' => $value), array('meta_id' => (int) $meta_rows[0]->meta_id)) : $wpdb->insert($wpdb->postmeta, array('post_id' => $snapshot['target_id'], 'meta_key' => $snapshot['meta_key'], 'meta_value' => $value)); } else { $column = $field === 'content' ? 'post_content' : 'post_excerpt'; $ok = $wpdb->update($wpdb->posts, array($column => $value, 'post_modified' => current_time('mysql'), 'post_modified_gmt' => current_time('mysql', true)), array('ID' => $id)); } if ($ok === false || $wpdb->query('COMMIT') === false) throw new Exception('Conditional write could not be confirmed'); } catch (Throwable $error) { $wpdb->query('ROLLBACK'); // A failed COMMIT can have an uncertain outcome. Drop values loaded // inside the transaction so a later request reads the actual state. ai4ranks_editorial_clear_cache($id, $snapshot['target_id']); return new WP_REST_Response(array('message' => 'Conditional write failed; verify before retrying'), 409); } ai4ranks_editorial_clear_cache($id, $snapshot['target_id']); $updated = get_post($id); wp_save_post_revision($id); do_action('post_updated', $id, $updated, $post); do_action('save_post_' . $updated->post_type, $id, $updated, true); do_action('save_post', $id, $updated, true); do_action('wp_after_insert_post', $id, $updated, true, $post); return new WP_REST_Response(array('post_id' => $id, 'field' => $field, 'image_id' => $image_id, 'stored' => $value), 200); } add_action('wp_head', function() { if (!is_singular()) return; $schema = json_decode((string) get_post_meta(get_queried_object_id(), '_ai4ranks_editorial_schema', true), true); if (is_array($schema) && ($schema['@context'] ?? '') === 'https://schema.org' && !empty($schema['@type'])) { echo ''; } }, 40);