'GET', 'callback' => array( __CLASS__, 'get_snapshots' ), 'permission_callback' => array( __CLASS__, 'check_permissions' ), 'args' => array( 'product_id' => array( 'required' => true, 'sanitize_callback' => 'absint', ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-history', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_content_history' ), 'permission_callback' => array( __CLASS__, 'check_permissions' ), 'args' => self::historyArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-history/stack', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_content_history_stack' ), 'permission_callback' => array( __CLASS__, 'check_permissions' ), 'args' => array( 'product_id' => array( 'required' => false, 'sanitize_callback' => 'absint', ), 'term_id' => array( 'required' => false, 'sanitize_callback' => 'absint', ), 'taxonomy' => array( 'required' => false, 'sanitize_callback' => 'sanitize_key', ), 'field_type' => array( 'required' => true, 'sanitize_callback' => 'sanitize_key', ), 'subject_id' => array( 'required' => false, 'sanitize_callback' => 'absint', ), ), ), ) ); register_rest_route( 'aipt/v1', '/content-snapshots/restore', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'restore_required' ), 'permission_callback' => array( __CLASS__, 'check_permissions_restore_stub' ), ), ) ); register_rest_route( 'aipt/v1', '/content-history/restore', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'restore_required' ), 'permission_callback' => array( __CLASS__, 'check_permissions_restore_stub' ), ), ) ); register_rest_route( 'aipt/v1', '/content-history/bulk-restore', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'bulk_restore_required' ), 'permission_callback' => array( __CLASS__, 'check_permissions_restore_stub' ), ), ) ); register_rest_route( 'aipt/v1', '/content-history/toggle', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'toggle_content_history' ), 'permission_callback' => array( __CLASS__, 'check_settings_permissions' ), 'args' => array( 'enabled' => array( 'required' => true, 'type' => 'boolean', 'sanitize_callback' => 'rest_sanitize_boolean', ), ), ), ) ); } /** * Read permission: manage_woocommerce only. * * Every route gated on this callback is GET-only, so no nonce is * required: a read is never the cross-site write a nonce protects * against, and requiring one anyway permanently 403'd any * Application-Password/Basic-Auth REST client, which has no way to * obtain one (@see \AIPT\Utils\RestNonceGuard). * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_permissions( $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' ), array( 'status' => 403 ) ); } return true; } public static function get_snapshots( $request ) { $product_id = absint( $request->get_param( 'product_id' ) ); if ( $product_id <= 0 ) { return new WP_Error( 'invalid_params', __( 'A valid product_id is required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( ! 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' ), array( 'status' => 403 ) ); } $product = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : null; if ( ! $product ) { return new WP_Error( 'product_not_found', __( 'The product could not be found.', 'ai-product-tools' ), array( 'status' => 404 ) ); } $snapshots = array_map( static function ( array $snapshot ) use ( $product, $product_id ): array { $subject = SnapshotSubject::fromRow( $snapshot ); if ( $subject->isAttachment() ) { $snapshot['current_token'] = self::attachmentToken( $subject->postId() ); } else { $snapshot['current_token'] = self::currentToken( $product, $product_id ); } return $snapshot; }, ( new SnapshotStore() )->history( $product_id ) ); return new WP_REST_Response( array( 'success' => true, 'data' => array( 'product_id' => $product_id, 'current_token' => self::currentToken( $product, $product_id ), 'snapshots' => array_values( $snapshots ), ), ), 200 ); } /** * Serve the plugin-wide content history timeline. * * @param WP_REST_Request $request REST request. * @return WP_REST_Response */ public static function get_content_history( $request ) { $filters = self::historyFilters( $request ); $cursor = self::sanitizeHistoryCursor( $request->get_param( 'cursor' ) ); $limit = max( 1, min( 100, absint( $request->get_param( 'limit' ) ?: 25 ) ) ); if ( isset( $filters['product_id'] ) && $filters['product_id'] > 0 ) { if ( ! current_user_can( 'edit_post', $filters['product_id'] ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to view this product\'s history.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } if ( isset( $filters['term_id'] ) && $filters['term_id'] > 0 ) { if ( ! current_user_can( 'edit_term', $filters['term_id'] ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to view this term\'s history.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } $store = new SnapshotStore(); $items = $store->list( $filters, $cursor, $limit + 1 ); $has_more = count( $items ) > $limit; if ( $has_more ) { $items = array_slice( $items, 0, $limit ); } $items = self::addCurrentTokens( $items ); $items = self::addProductIdentity( $items ); $next_cursor = null; if ( $has_more && ! empty( $items ) ) { $last = $items[ count( $items ) - 1 ]; $next_cursor = array( 'created_at' => (string) $last['created_at'], 'id' => (int) $last['id'], ); } return new WP_REST_Response( array( 'success' => true, 'data' => array( 'items' => array_values( $items ), 'next_cursor' => $next_cursor, 'summary' => $store->summary( $filters ), ), ), 200 ); } /** * Serve one product-field-subject snapshot stack. * * @param WP_REST_Request $request REST request. * @return WP_REST_Response|WP_Error */ public static function get_content_history_stack( $request ) { $product_id = absint( $request->get_param( 'product_id' ) ); $term_id = absint( $request->get_param( 'term_id' ) ); $taxonomy = sanitize_key( (string) $request->get_param( 'taxonomy' ) ); $field_type = sanitize_key( (string) $request->get_param( 'field_type' ) ); $subject_id = absint( $request->get_param( 'subject_id' ) ); if ( '' === $field_type || ( $product_id <= 0 && $term_id <= 0 ) ) { return new WP_Error( 'invalid_params', __( 'A valid product_id or term_id, and field_type, are required.', 'ai-product-tools' ), array( 'status' => 400 ) ); } $is_term = $term_id > 0; if ( $is_term ) { if ( '' === $taxonomy ) { return new WP_Error( 'invalid_params', __( 'A valid taxonomy is required for a term.', 'ai-product-tools' ), array( 'status' => 400 ) ); } if ( ! current_user_can( 'edit_term', $term_id ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to edit this term.', 'ai-product-tools' ), array( 'status' => 403 ) ); } } else { if ( ! 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' ), array( 'status' => 403 ) ); } } $store = new SnapshotStore(); $items = $is_term ? $store->stack( 0, $field_type, $term_id, $taxonomy ) : $store->stack( $product_id, $field_type, $subject_id > 0 ? $subject_id : null ); $items = self::addCurrentTokens( $items ); $items = self::addProductIdentity( $items ); $slugs_seen = array(); $current_by_slug = array(); foreach ( $items as $item ) { $slug = isset( $item['plugin_slug'] ) ? (string) $item['plugin_slug'] : ''; if ( isset( $slugs_seen[ $slug ] ) ) { continue; } $slugs_seen[ $slug ] = true; try { $current_by_slug[ $slug ] = $is_term ? $store->readCurrentFieldValue( 0, $field_type, $term_id, null, $taxonomy ) : $store->readCurrentFieldValue( $product_id, $field_type, $subject_id > 0 ? $subject_id : null, '' !== $slug ? $slug : null ); } catch ( \RuntimeException $e ) { $current_by_slug[ $slug ] = null; } } foreach ( $items as &$item ) { $slug = isset( $item['plugin_slug'] ) ? (string) $item['plugin_slug'] : ''; $item['current_value'] = $current_by_slug[ $slug ] ?? null; } unset( $item ); $current_value = isset( $items[0]['current_value'] ) ? $items[0]['current_value'] : null; return new WP_REST_Response( array( 'success' => true, 'data' => array( 'items' => array_values( $items ), 'current_value' => $current_value, ), ), 200 ); } /** @return array> */ private static function historyArgs(): array { return array( 'source' => array( 'sanitize_callback' => array( __CLASS__, 'sanitizeHistorySource' ) ), 'field_type' => array( 'sanitize_callback' => 'sanitize_key' ), 'product_id' => array( 'sanitize_callback' => 'absint' ), 'term_id' => array( 'sanitize_callback' => 'absint' ), 'taxonomy' => array( 'sanitize_callback' => 'sanitize_key' ), 'actor' => array( 'sanitize_callback' => array( __CLASS__, 'sanitizeHistoryActor' ) ), 'date_from' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'date_to' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'cursor' => array( 'sanitize_callback' => array( __CLASS__, 'sanitizeHistoryCursor' ) ), 'limit' => array( 'default' => 25, 'sanitize_callback' => 'absint' ), ); } /** @return array */ private static function historyFilters( $request ): array { $filters = array( 'source' => self::sanitizeHistorySource( $request->get_param( 'source' ) ), 'field_type' => sanitize_key( (string) $request->get_param( 'field_type' ) ), 'product_id' => absint( $request->get_param( 'product_id' ) ), 'term_id' => absint( $request->get_param( 'term_id' ) ), 'taxonomy' => sanitize_key( (string) $request->get_param( 'taxonomy' ) ), 'actor' => self::sanitizeHistoryActor( $request->get_param( 'actor' ) ), 'date_from' => sanitize_text_field( (string) $request->get_param( 'date_from' ) ), 'date_to' => sanitize_text_field( (string) $request->get_param( 'date_to' ) ), ); $filters = array_filter( $filters, static function ( $value ): bool { return '' !== $value && 0 !== $value; } ); return $filters; } /** @param mixed $value Raw source. */ public static function sanitizeHistorySource( $value ): string { $value = sanitize_key( (string) $value ); return in_array( $value, array( 'description', 'title', 'faq', 'seo_meta', 'image_alt', 'tags', 'automation', 'product_editor', 'restore', 'taxonomy', 'csv_import' ), true ) ? $value : ''; } /** @param mixed $value Raw actor. */ public static function sanitizeHistoryActor( $value ): string { $value = sanitize_key( (string) $value ); return in_array( $value, array( 'manual', 'automation' ), true ) ? $value : ''; } /** * @param mixed $value Raw array or JSON cursor. * @return array|null */ public static function sanitizeHistoryCursor( $value ): ?array { if ( is_string( $value ) ) { $value = json_decode( $value, true ); } if ( ! is_array( $value ) || empty( $value['created_at'] ) || empty( $value['id'] ) ) { return null; } return array( 'created_at' => sanitize_text_field( (string) $value['created_at'] ), 'id' => absint( $value['id'] ), ); } /** * @param array> $items Snapshot rows. * @return array> */ private static function addCurrentTokens( array $items ): array { $products = array(); foreach ( $items as &$item ) { $subject = SnapshotSubject::fromRow( $item ); if ( $subject->isTerm() ) { $item['current_token'] = $subject->token(); continue; } if ( $subject->isAttachment() ) { $item['current_token'] = self::attachmentToken( $subject->postId() ); continue; } $product_id = $subject->postId(); if ( ! array_key_exists( $product_id, $products ) ) { $products[ $product_id ] = function_exists( 'wc_get_product' ) ? wc_get_product( $product_id ) : null; } $item['current_token'] = self::currentToken( $products[ $product_id ], $product_id ); } unset( $item ); return $items; } /** * Enrich items with the product identity (name, SKU, thumbnail) their row * needs to render more than "Product #123". * * A batch resolve over the DISTINCT product ids in this response, not one * lookup per item — identical to how {@see addCurrentTokens()} dedupes its * own WC_Product reads above. * * @param array> $items Snapshot rows, each carrying `product_id`. * @return array> */ private static function addProductIdentity( array $items ): array { $product_ids = array(); foreach ( $items as $item ) { $subject_type = isset( $item['subject_type'] ) ? (string) $item['subject_type'] : 'product'; if ( 'term' !== $subject_type && isset( $item['product_id'] ) ) { $product_ids[] = (int) $item['product_id']; } } $identities = ( new ProductIdentityResolver() )->resolve( $product_ids ); foreach ( $items as &$item ) { $subject_type = isset( $item['subject_type'] ) ? (string) $item['subject_type'] : 'product'; if ( 'term' === $subject_type ) { $item = self::applyTermIdentity( $item ); continue; } $product_id = isset( $item['product_id'] ) ? (int) $item['product_id'] : 0; $identity = $identities[ $product_id ] ?? array( 'name' => '', 'sku' => '', 'thumbnail_url' => null, ); $item['product_name'] = $identity['name']; $item['product_sku'] = $identity['sku']; $item['thumbnail_url'] = $identity['thumbnail_url']; } unset( $item ); return $items; } /** * Replace a term row's product-shaped identity fields with its term * identity: the term's decoded, tag-stripped name and the taxonomy's * singular label (falling back to the slug when either cannot be * resolved — a term can outlive the snapshot that recorded it). * * @since 2.8.0 * @param array $item Snapshot row, already subject_type='term'. * @return array */ private static function applyTermIdentity( array $item ): array { $term_id = isset( $item['subject_id'] ) ? (int) $item['subject_id'] : 0; $taxonomy = isset( $item['taxonomy'] ) ? (string) $item['taxonomy'] : ''; $term_name = ''; $taxonomy_label = $taxonomy; if ( $term_id > 0 && '' !== $taxonomy ) { $term = function_exists( 'get_term' ) ? get_term( $term_id, $taxonomy ) : null; if ( $term && ! ( function_exists( 'is_wp_error' ) && is_wp_error( $term ) ) && isset( $term->name ) ) { $decoded = function_exists( 'html_entity_decode' ) ? html_entity_decode( (string) $term->name, ENT_QUOTES ) : (string) $term->name; $term_name = function_exists( 'wp_strip_all_tags' ) ? (string) wp_strip_all_tags( $decoded ) : $decoded; } $tax_object = function_exists( 'get_taxonomy' ) ? get_taxonomy( $taxonomy ) : null; if ( $tax_object && isset( $tax_object->labels->singular_name ) && '' !== $tax_object->labels->singular_name ) { $taxonomy_label = (string) $tax_object->labels->singular_name; } } $item['taxonomy'] = $taxonomy; $item['term_name'] = $term_name; $item['taxonomy_label'] = $taxonomy_label; $item['product_id'] = 0; $item['product_name'] = ''; $item['product_sku'] = ''; $item['thumbnail_url'] = null; return $item; } private static function attachmentToken( int $attachment_id ): string { return ProductEditorConcurrencyToken::for_post_id( $attachment_id ); } private static function currentToken( $product, int $product_id ): string { $date = ( is_object( $product ) && is_callable( array( $product, 'get_date_modified' ) ) ) ? $product->get_date_modified() : null; $post_modified = ( is_object( $date ) && method_exists( $date, 'date' ) ) ? (string) $date->date( 'Y-m-d H:i:s' ) : ''; return ProductEditorConcurrencyToken::for_product_id( $product_id, $post_modified ); } /** * Permission callback for /content-history/toggle — same manage_aipt_settings * gate as the Settings page (admins always hold it; opted-in Shop Managers * gain it via the settings-access toggle), since this writes the same * aipt_content_history_enabled option the Settings page's own toggle does. * * @param WP_REST_Request $request REST request. * @return true|WP_Error */ public static function check_settings_permissions( $request ) { if ( ! current_user_can( 'manage_aipt_settings' ) ) { return new WP_Error( 'rest_forbidden', __( 'You do not have permission to change this setting.', 'ai-product-tools' ), array( 'status' => 403 ) ); } return \AIPT\Utils\RestNonceGuard::check( $request, __( 'Invalid or missing security nonce.', 'ai-product-tools' ) ); } /** * POST /aipt/v1/content-history/toggle — flip content_history_enabled. * * Canonicalizes to int 0/1 in wp_options, matching how * SettingsService::updateSettings() stores every other BOOLEAN_FIELDS * entry, so SnapshotStore::capture()'s rest_sanitize_boolean() read is * unaffected by which of the two write paths a given install used. * * @param WP_REST_Request $request REST request. * @return WP_REST_Response */ public static function toggle_content_history( $request ) { $enabled = (int) rest_sanitize_boolean( $request->get_param( 'enabled' ) ); update_option( 'aipt_content_history_enabled', $enabled ); return new WP_REST_Response( array( 'success' => true, 'data' => array( 'content_history_enabled' => (bool) $enabled, ), ), 200 ); } /** * Write-permission gate for the restore stub routes above: * manage_woocommerce + a valid REST nonce, matching the real * Premium\Rollback\SnapshotRestController::check_permissions_write() * gate these routes defer to once that controller overrides them. Kept * as its own copy, rather than a shared call, because that Premium * class does not exist in a build where this stub is the one actually * answering the request. * * @param WP_REST_Request $request Request object. * @return true|WP_Error */ public static function check_permissions_restore_stub( $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' ), array( 'status' => 403 ) ); } return \AIPT\Utils\RestNonceGuard::check( $request, __( 'Invalid or missing security nonce.', 'ai-product-tools' ) ); } /** * Always-shipped stub for `content-snapshots/restore` and * `content-history/restore`. * * @param WP_REST_Request $request Request object. * @return WP_Error */ public static function restore_required( $request ) { return PlanDenial::error( 'unifiedRollback', PlanDenial::PLAN_BUSINESS, __( 'Restoring a previous version requires a Business plan.', 'ai-product-tools' ) ); } /** * Always-shipped stub for `content-history/bulk-restore`. * * @param WP_REST_Request $request Request object. * @return WP_Error */ public static function bulk_restore_required( $request ) { return PlanDenial::error( 'unifiedRollback', PlanDenial::PLAN_BUSINESS, __( 'Restoring previous versions requires a Business plan.', 'ai-product-tools' ) ); } }