'GET', 'callback' => array( __CLASS__, 'list_sources' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), ), array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'create_source' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/sources/preview', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'preview_source' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/sources/(?P\d+)', array( array( 'methods' => 'PUT', 'callback' => array( __CLASS__, 'update_source' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), array( 'methods' => 'DELETE', 'callback' => array( __CLASS__, 'delete_source' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/sources/(?P\d+)/refresh', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'refresh_source' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/sources/(?P\d+)/check-product', array( array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'check_product' ), 'permission_callback' => array( __CLASS__, 'check_permissions_read' ), 'args' => self::idArgs(), ), ) ); register_rest_route( 'aipt/v1', '/content-structure/sources/(?P\d+)/impact', array( array( 'methods' => 'GET', 'callback' => array( __CLASS__, 'get_impact' ), 'permission_callback' => array( __CLASS__, 'check_permissions_manage' ), 'args' => self::idArgs(), ), ) ); } /** * @return array */ private static function idArgs(): array { return array( 'id' => array( 'required' => true, 'sanitize_callback' => 'absint' ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public static function list_sources( WP_REST_Request $request ): WP_REST_Response { $filters = array(); $scope_type = (string) $request->get_param( 'scopeType' ); $scope_id = $request->get_param( 'scopeId' ); if ( '' !== $scope_type ) { $filters['scopeType'] = sanitize_key( $scope_type ); } if ( null !== $scope_id && is_numeric( $scope_id ) ) { $filters['scopeId'] = (int) $scope_id; } $blueprint_id = (int) $request->get_param( 'blueprintId' ); $sources = ( new SourceStore() )->list( $filters, 200 ); if ( $blueprint_id > 0 ) { $sources = array_values( array_filter( $sources, static function ( array $source ) use ( $blueprint_id ): bool { return 'blueprint' !== $source['scopeType'] || $source['scopeId'] === $blueprint_id; } ) ); } $blueprints = new BlueprintStore(); $shaped = array_map( static function ( array $source ) use ( $blueprints ): array { return self::sourceShape( $source, $blueprints ); }, $sources ); return self::success( $shaped ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function preview_source( WP_REST_Request $request ) { $service = self::webSourceService(); if ( null === $service ) { return self::webSourcesPlanRequiredError(); } $rate_error = self::guardFetchRateLimit(); if ( null !== $rate_error ) { return $rate_error; } $body = (array) $request->get_json_params(); $url = isset( $body['url'] ) ? trim( (string) $body['url'] ) : ''; if ( '' === $url ) { return self::error( 'aipt_blueprint_invalid_request', __( 'A URL is required.', 'ai-product-tools' ), 400 ); } $allowed_domains = is_array( $body['allowedDomains'] ?? null ) ? array_map( 'strval', $body['allowedDomains'] ) : array(); $result = $service->preview( $url, array( 'allowedHosts' => $allowed_domains, 'userId' => get_current_user_id() ) ); return self::success( array( 'previewToken' => (string) $result['previewToken'], 'status' => (string) $result['status'], 'statusMessage' => (string) $result['statusMessage'], 'extracted' => $result['extracted'], 'contentType' => (string) $result['contentType'], 'finalUrl' => (string) $result['finalUrl'], 'httpStatus' => (int) ( $result['httpStatus'] ?? 0 ), ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function create_source( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $name = sanitize_text_field( trim( (string) ( $body['name'] ?? '' ) ) ); if ( '' === $name ) { return self::error( 'aipt_blueprint_invalid_request', __( 'A name is required.', 'ai-product-tools' ), 400 ); } if ( mb_strlen( $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $scope_error = self::validateScopeTarget( $body ); if ( null !== $scope_error ) { return $scope_error; } $service = self::webSourceService(); if ( null === $service ) { return self::webSourcesPlanRequiredError(); } $preview_token = isset( $body['previewToken'] ) ? (string) $body['previewToken'] : ''; $user_id = get_current_user_id(); if ( '' !== $preview_token ) { $row = $service->createFromPreview( $preview_token, $body, $user_id ); if ( null === $row ) { return self::error( 'aipt_blueprint_preview_expired', __( 'This preview has expired. Preview the URL again.', 'ai-product-tools' ), 400 ); } if ( false === $row ) { return self::error( 'aipt_blueprint_create_failed', __( 'This source could not be saved. Try again.', 'ai-product-tools' ), 500 ); } return self::success( self::sourceShape( $row, new BlueprintStore() ), 201 ); } $url_field = isset( $body['urlField'] ) ? (string) $body['urlField'] : ''; if ( '' === $url_field || ! ( new FieldCatalog() )->isValidRef( $url_field, 'product' ) ) { return self::error( 'aipt_blueprint_invalid_field_ref', __( 'Choose a valid product field for the URL.', 'ai-product-tools' ), 400 ); } $row = $service->createProductUrlSource( $body, $user_id ); if ( null === $row ) { return self::error( 'aipt_blueprint_invalid_request', __( 'This source could not be created.', 'ai-product-tools' ), 400 ); } return self::success( self::sourceShape( $row, new BlueprintStore() ), 201 ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function update_source( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $store = new SourceStore(); $current = $store->get( $id ); if ( null === $current ) { return self::error( 'aipt_blueprint_source_not_found', __( 'This source no longer exists.', 'ai-product-tools' ), 404 ); } $body = (array) $request->get_json_params(); $expected_version = isset( $body['expectedVersion'] ) ? (int) $body['expectedVersion'] : 0; if ( array_key_exists( 'scopeType', $body ) || array_key_exists( 'scopeId', $body ) ) { $scope_error = self::validateScopeTarget( array( 'scopeType' => array_key_exists( 'scopeType', $body ) ? $body['scopeType'] : $current['scopeType'], 'scopeId' => array_key_exists( 'scopeId', $body ) ? $body['scopeId'] : $current['scopeId'], ) ); if ( null !== $scope_error ) { return $scope_error; } } $name_given = array_key_exists( 'name', $body ); $name = $name_given ? sanitize_text_field( trim( (string) $body['name'] ) ) : null; if ( $name_given && '' === $name ) { return self::error( 'aipt_blueprint_invalid_request', __( 'A name is required.', 'ai-product-tools' ), 400 ); } if ( $name_given && mb_strlen( (string) $name ) > self::NAME_MAX_LENGTH ) { return self::nameTooLongError(); } $data = array(); foreach ( array( 'name', 'enabled', 'scopeType', 'scopeId', 'staleAfterDays' ) as $key ) { if ( ! array_key_exists( $key, $body ) ) { continue; } switch ( $key ) { case 'name': $data[ $key ] = $name; break; case 'enabled': $data[ $key ] = rest_sanitize_boolean( $body[ $key ] ); break; case 'scopeType': $data[ $key ] = sanitize_key( (string) $body[ $key ] ); break; default: $data[ $key ] = max( 0, (int) $body[ $key ] ); } } $result = $store->update( $id, $data, $expected_version ); if ( ! $result['ok'] ) { return self::error( 'aipt_blueprint_source_version_conflict', __( 'This source changed since it was loaded. Reload and try again.', 'ai-product-tools' ), 409, array( 'current' => null !== $result['current'] ? self::sourceShape( $result['current'], new BlueprintStore() ) : null ) ); } return self::success( self::sourceShape( $result['current'], new BlueprintStore() ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function refresh_source( WP_REST_Request $request ) { $service = self::webSourceService(); if ( null === $service ) { return self::webSourcesPlanRequiredError(); } $rate_error = self::guardFetchRateLimit(); if ( null !== $rate_error ) { return $rate_error; } $row = $service->refresh( (int) $request->get_param( 'id' ) ); if ( null === $row ) { return self::error( 'aipt_blueprint_source_not_found', __( 'This source could not be refreshed.', 'ai-product-tools' ), 404 ); } return self::success( self::sourceShape( $row, new BlueprintStore() ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function check_product( WP_REST_Request $request ) { $body = (array) $request->get_json_params(); $product_id = isset( $body['productId'] ) ? (int) $body['productId'] : 0; if ( $product_id <= 0 || ! current_user_can( 'edit_post', $product_id ) ) { return self::error( 'rest_forbidden', __( 'You do not have permission to check this product.', 'ai-product-tools' ), 403 ); } $service = self::webSourceService(); if ( null === $service ) { return self::webSourcesPlanRequiredError(); } $rate_error = self::guardFetchRateLimit(); if ( null !== $rate_error ) { return $rate_error; } $result = $service->checkProduct( (int) $request->get_param( 'id' ), $product_id ); return self::success( array( 'status' => (string) $result['status'], 'statusMessage' => (string) $result['statusMessage'], 'extracted' => $result['extracted'], 'url' => (string) $result['url'], 'contentVersion' => 0, ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function get_impact( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); if ( null === ( new SourceStore() )->get( $id ) ) { return self::error( 'aipt_blueprint_source_not_found', __( 'This source no longer exists.', 'ai-product-tools' ), 404 ); } return self::success( self::computeImpact( $id ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public static function delete_source( WP_REST_Request $request ) { $id = (int) $request->get_param( 'id' ); $store = new SourceStore(); if ( null === $store->get( $id ) ) { return self::error( 'aipt_blueprint_source_not_found', __( 'This source no longer exists.', 'ai-product-tools' ), 404 ); } $impact = self::computeImpact( $id ); $given_hash = (string) $request->get_param( 'impactHash' ); if ( '' === $given_hash || $given_hash !== $impact['impactHash'] ) { return self::error( 'aipt_blueprint_impact_changed', __( 'This source\'s impact changed. Reload and try again.', 'ai-product-tools' ), 409, array( 'current' => $impact ) ); } $ref = 'src:' . $id; $blueprints = new BlueprintStore(); $updated_ids = array(); foreach ( $impact['blueprints'] as $entry ) { if ( self::detachSourceFromBlueprint( $blueprints, (int) $entry['id'], $ref ) ) { $updated_ids[] = (int) $entry['id']; } } $store->delete( $id ); ( new SourceCacheStore() )->deleteForSource( $id ); return self::success( array( 'deleted' => true, 'updatedBlueprints' => $updated_ids ) ); } /** * Remove `$ref` from one Blueprint's `sources.items` and every section's * (or FAQ group's) local `sources.refs`, switching to `inherit: true` * when a section's local selection becomes empty, retrying once on a * revision race. * * @param BlueprintStore $blueprints Blueprint store. * @param int $blueprint_id Blueprint id. * @param string $ref Source ref ('src:'). * @return bool Whether the blueprint was updated. */ private static function detachSourceFromBlueprint( BlueprintStore $blueprints, int $blueprint_id, string $ref ): bool { for ( $attempt = 0; $attempt < 2; $attempt++ ) { $blueprint = $blueprints->get( $blueprint_id ); if ( null === $blueprint ) { return false; } $definition = self::removeRefFromDefinition( is_array( $blueprint['definition'] ) ? $blueprint['definition'] : array(), $ref ); $result = $blueprints->update( $blueprint_id, array( 'definition' => $definition, 'definitionHash' => DefinitionHasher::hash( $definition ), 'updatedBy' => get_current_user_id(), ), (int) $blueprint['revision'] ); if ( $result['ok'] ) { return true; } } return false; } /** * @param array $definition BlueprintDefinition. * @param string $ref Source ref to remove. * @return array Updated definition. */ private static function removeRefFromDefinition( array $definition, string $ref ): array { if ( isset( $definition['sources']['items'] ) && is_array( $definition['sources']['items'] ) ) { $definition['sources']['items'] = array_values( array_filter( $definition['sources']['items'], static function ( $item ) use ( $ref ): bool { return ! ( is_array( $item ) && ( $item['ref'] ?? '' ) === $ref ); } ) ); } if ( isset( $definition['structure']['sections'] ) && is_array( $definition['structure']['sections'] ) ) { $definition['structure']['sections'] = array_map( static function ( $section ) use ( $ref ) { return self::detachRefFromUnit( $section, $ref ); }, $definition['structure']['sections'] ); } if ( isset( $definition['structure']['groups'] ) && is_array( $definition['structure']['groups'] ) ) { $definition['structure']['groups'] = array_map( static function ( $group ) use ( $ref ) { return self::detachRefFromUnit( $group, $ref ); }, $definition['structure']['groups'] ); } return $definition; } /** * @param mixed $unit BlueprintSection or FaqGroup. * @param string $ref Source ref to remove. * @return mixed */ private static function detachRefFromUnit( $unit, string $ref ) { if ( ! is_array( $unit ) || ! isset( $unit['sources'] ) || ! is_array( $unit['sources'] ) ) { return $unit; } $refs = is_array( $unit['sources']['refs'] ?? null ) ? array_values( array_diff( $unit['sources']['refs'], array( $ref ) ) ) : array(); $unit['sources']['refs'] = $refs; if ( empty( $refs ) ) { $unit['sources']['inherit'] = true; } return $unit; } /** * @param int $source_id Source id. * @return array{blueprints:array}>,impactHash:string} */ private static function computeImpact( int $source_id ): array { $ref = 'src:' . $source_id; $blueprints = ( new BlueprintStore() )->listReferencingSource( $source_id ); $entries = array(); foreach ( $blueprints as $blueprint ) { $entries[] = array( 'id' => (int) $blueprint['id'], 'name' => (string) $blueprint['name'], 'sections' => self::affectedUnits( $blueprint['definition'], $ref ), ); } return array( 'blueprints' => $entries, 'impactHash' => hash( 'sha256', (string) wp_json_encode( $entries ) ), ); } /** * @param array $definition BlueprintDefinition. * @param string $ref Source ref. * @return array */ private static function affectedUnits( array $definition, string $ref ): array { $units = array(); foreach ( array( 'sections', 'groups' ) as $key ) { $list = isset( $definition['structure'][ $key ] ) && is_array( $definition['structure'][ $key ] ) ? $definition['structure'][ $key ] : array(); foreach ( $list as $unit ) { if ( ! is_array( $unit ) || ! isset( $unit['sources'] ) || ! is_array( $unit['sources'] ) ) { continue; } $inherits = ! empty( $unit['sources']['inherit'] ); $refs = is_array( $unit['sources']['refs'] ?? null ) ? $unit['sources']['refs'] : array(); if ( $inherits || in_array( $ref, $refs, true ) ) { $units[] = array( 'id' => (string) ( $unit['id'] ?? '' ), 'name' => (string) ( $unit['name'] ?? '' ) ); } } } return $units; } /** * @param array $source SourceStore row. * @param BlueprintStore $blueprints Blueprint store (for usage + scopeLabel on a blueprint scope). * @return array BlueprintSource. */ private static function sourceShape( array $source, BlueprintStore $blueprints ): array { $usage = array_map( static function ( array $blueprint ): array { return array( 'id' => (int) $blueprint['id'], 'name' => (string) $blueprint['name'] ); }, $blueprints->listReferencingSource( (int) $source['id'] ) ); $shape = array( 'id' => (int) $source['id'], 'name' => (string) $source['name'], 'kind' => (string) $source['kind'], 'url' => (string) $source['url'], 'urlField' => (string) $source['urlField'], 'scopeType' => (string) $source['scopeType'], 'scopeId' => (int) $source['scopeId'], 'scopeLabel' => self::scopeLabel( (string) $source['scopeType'], (int) $source['scopeId'], $blueprints ), 'enabled' => (bool) $source['enabled'], 'status' => (string) $source['status'], 'statusMessage' => '' !== $source['errorMessage'] ? (string) $source['errorMessage'] : '', 'contentType' => (string) $source['contentType'], 'extracted' => is_array( $source['extracted'] ) ? array( 'title' => (string) ( $source['extracted']['title'] ?? '' ), 'excerpt' => (string) ( $source['extracted']['excerpt'] ?? '' ), 'facts' => is_array( $source['extracted']['facts'] ?? null ) ? $source['extracted']['facts'] : array(), ) : null, 'contentVersion' => (int) $source['contentVersion'], 'lastCheckedAt' => null !== $source['lastCheckedAt'] ? self::isoDate( (string) $source['lastCheckedAt'] ) : null, 'staleAfterDays' => (int) $source['staleAfterDays'], 'version' => (int) $source['version'], 'usage' => array( 'blueprints' => $usage ), ); if ( 'product_url_field' === $source['kind'] ) { $shape['productCoverage'] = self::productCoverage( $source ); } return $shape; } /** * @param string $scope_type 'store'|'category'|'blueprint'|'product'. * @param int $scope_id Scope target id. * @param BlueprintStore $blueprints Blueprint store (for a 'blueprint' scope's label). * @return string */ private static function scopeLabel( string $scope_type, int $scope_id, BlueprintStore $blueprints ): string { switch ( $scope_type ) { case 'store': return __( 'Store-wide', 'ai-product-tools' ); case 'category': $term = function_exists( 'get_term' ) ? get_term( $scope_id, 'product_cat' ) : null; return ( $term instanceof \WP_Term ) ? (string) $term->name : ''; case 'product': $product = function_exists( 'wc_get_product' ) ? wc_get_product( $scope_id ) : false; return ( $product instanceof \WC_Product ) ? (string) $product->get_name() : ''; case 'blueprint': $blueprint = $blueprints->get( $scope_id ); return null !== $blueprint ? (string) $blueprint['name'] : ''; default: return ''; } } /** * Bounded count of products (within this source's scope) that currently * have a non-empty value for its mapped URL field. * * @param array $source SourceStore row (kind='product_url_field'). * @return array{withUrl:int,total:int} */ private static function productCoverage( array $source ): array { if ( ! function_exists( 'wc_get_products' ) ) { return array( 'withUrl' => 0, 'total' => 0 ); } $args = array( 'limit' => self::COVERAGE_SCAN_LIMIT, 'return' => 'ids', 'status' => array( 'publish' ) ); if ( 'product' === $source['scopeType'] ) { $args = array( 'include' => array( (int) $source['scopeId'] ), 'return' => 'ids' ); } elseif ( 'category' === $source['scopeType'] ) { $term = function_exists( 'get_term' ) ? get_term( (int) $source['scopeId'], 'product_cat' ) : null; if ( $term instanceof \WP_Term ) { $args['category'] = array( $term->slug ); } } $ids = array_map( 'intval', (array) wc_get_products( $args ) ); $fields = new FieldCatalog(); $with_url = 0; foreach ( $ids as $id ) { $product = wc_get_product( $id ); if ( ! ( $product instanceof \WC_Product ) ) { continue; } $value = $fields->productValue( $product, (string) $source['urlField'] ); if ( empty( $value['empty'] ) ) { $with_url++; } } return array( 'withUrl' => $with_url, 'total' => count( $ids ) ); } /** * @param array $body Request body. * @return WP_Error|null */ private static function validateScopeTarget( array $body ): ?WP_Error { $scope_type = (string) ( $body['scopeType'] ?? 'store' ); if ( 'store' === $scope_type ) { return null; } $scope_id = (int) ( $body['scopeId'] ?? 0 ); if ( $scope_id <= 0 ) { return self::error( 'aipt_blueprint_invalid_scope', __( 'Choose a scope target.', 'ai-product-tools' ), 400 ); } $exists = false; if ( 'category' === $scope_type ) { $exists = function_exists( 'get_term' ) && ( get_term( $scope_id, 'product_cat' ) instanceof \WP_Term ); } elseif ( 'product' === $scope_type ) { $exists = function_exists( 'wc_get_product' ) && ( wc_get_product( $scope_id ) instanceof \WC_Product ); } elseif ( 'blueprint' === $scope_type ) { $exists = null !== ( new BlueprintStore() )->get( $scope_id ); } else { return self::error( 'aipt_blueprint_invalid_scope', __( 'Invalid scope type.', 'ai-product-tools' ), 400 ); } return $exists ? null : self::error( 'aipt_blueprint_invalid_scope', __( 'This scope target could not be found.', 'ai-product-tools' ), 400 ); } /** * The web page source service, when this site's plan lets a web page * source (a fixed URL, or a per-product URL field) actually fetch and * read a page and the Business build supplies one. Free keeps * product-field sources only. Same {@see EntitlementPolicy} every * generator run already clamps through * ({@see \AIPT\Api\ContentStructure\Engine\Policy\SourcesPolicy}), so a * create/preview/refresh/check this gate allows is never later silently * dropped by the run-time clamp, and the reverse never happens either. * * @return WebSourceServiceInterface|null Null refuses the route. */ private static function webSourceService(): ?WebSourceServiceInterface { if ( ! ( new EntitlementPolicy() )->webSourcesAllowed() ) { return null; } return WebSourceServices::get(); } /** * The reason-aware 403 for a web-page-fetching source route without * {@see webSourceService()}. Mirrors * {@see BrandAssistController}'s own 'aipt_blueprint_plan_required' shape. * * @return WP_Error */ private static function webSourcesPlanRequiredError(): WP_Error { $reason = PlanDenial::reason( 'contentStructureWebSources', PlanDenial::PLAN_PAID ); return self::error( 'aipt_blueprint_plan_required', PlanDenial::message( $reason, __( 'Web page sources are part of the Business plan.', 'ai-product-tools' ) ), 403, array( 'reason' => $reason ) ); } /** * A name past {@see NAME_MAX_LENGTH} (the `aipt_blueprint_sources.name` * varchar(190) column width), using the same error code as the "name * required" check above so the client's existing handling covers it * with no new case. * * @since 2.8.1 * @return WP_Error */ private static function nameTooLongError(): WP_Error { return self::error( 'aipt_blueprint_invalid_request', __( 'Use a name of 190 characters or fewer.', 'ai-product-tools' ), 400 ); } /** * @return WP_Error|null */ private static function guardFetchRateLimit(): ?WP_Error { $rate_check = self::checkRateLimitStatic( get_current_user_id(), self::FETCH_RATE_LIMIT_SCOPE, self::FETCH_RATE_LIMIT_MAX, self::FETCH_RATE_LIMIT_WINDOW ); return $rate_check['allowed'] ? null : self::rateLimitErrorStatic( $rate_check ); } }