*/ private static $profile_cache = array(); /** * Table name for profiles. * * @var string */ private $table_name; /** * Submitted setting keys changed by plan-enforcement filters during the last update. * * @var string[] */ private $last_coerced_fields = array(); /** * Denial reason of the plan clamps applied during the last update, '' when none. * * @var string */ private $last_coerced_reason = ''; /** * Plan denial that rejected the last update, null when none. * * @var WP_Error|null */ private $last_plan_denial = null; /** * Changed paid settings the license could not be verified for in the current update. * * @var string[] */ private $unverified_fields = array(); /** * Feature and required plan of the first unverified paid change. * * @var array{0:string,1:string,2:string}|null */ private $unverified_denial = null; /** * Per-update memo of denial reasons, keyed by feature. * * @var array */ private $denial_reasons = array(); /** * Default settings values. * * @var array */ private static $defaults = array( 'enabled' => false, 'max_products' => 10000, 'categories' => array(), 'stock_filter' => 'all', 'date_filter_days' => 0, 'tags' => array(), 'batch_size' => 100, 'filter_mode' => 'all', 'attributes' => array(), 'scheduled_enabled' => false, 'schedule_frequency' => 'daily', 'included_fields' => null, ); /** * Default status values. * * @var array */ private static $status_defaults = array( 'status' => 'idle', 'last_build' => null, 'product_count' => 0, 'category_count' => 0, 'file_size' => 0, 'trimmed_count' => 0, 'shard_count' => 0, 'error' => null, 'error_code' => null, 'status_version' => 0, 'phase' => 'idle', 'build_progress' => 0, 'progress_percent' => 0, 'processed_product_count' => 0, 'estimated_total_products' => 0, 'effective_filter_summary' => array(), 'build_job_id' => 0, 'last_processed_id' => 0, 'profile_schema_version' => 0, ); /** * Validation rules for settings. * * @var array */ private static $validation_rules = array( 'max_products' => array( 'min' => 1, 'max' => 50000, ), 'date_filter_days' => array( 'min' => 0, 'max' => 365, ), 'batch_size' => array( 'min' => 50, 'max' => 500, ), 'stock_filter' => array( 'allowed' => array( 'all', 'instock', 'outofstock' ) ), 'filter_mode' => array( 'allowed' => array( 'all', 'any' ) ), 'schedule_frequency' => array( 'allowed' => array( 'hourly', 'two_hourly', 'six_hourly', 'daily' ) ), ); /** * Constructor. * * @param int $profile_id Profile ID. If 0, uses the active profile. */ public function __construct( int $profile_id = 0 ) { global $wpdb; $this->table_name = $wpdb->prefix . 'aipt_store_index_profiles'; if ( 0 === $profile_id ) { $profile_manager = new ProfileManager(); $active = $profile_manager->getActive(); if ( $active ) { $this->profile_id = (int) $active['id']; } else { $default = $profile_manager->getDefault(); $this->profile_id = $default ? (int) $default['id'] : 1; } } else { $this->profile_id = $profile_id; } } /** * Get the profile ID. * * @return int */ public function getProfileId(): int { return $this->profile_id; } /** * Load and cache profile data from database. * * Uses static cache keyed by profile_id to ensure all instances * for the same profile share the same cached data. * * @return array|null Profile data or null if not found. */ private function loadProfile(): ?array { if ( array_key_exists( $this->profile_id, self::$profile_cache ) ) { return self::$profile_cache[ $this->profile_id ]; } global $wpdb; $sql = "SELECT * FROM {$this->table_name} WHERE id = %d"; $profile = $wpdb->get_row($wpdb->prepare($sql, $this->profile_id), ARRAY_A); if ( ! $profile ) { self::$profile_cache[ $this->profile_id ] = null; return null; } self::$profile_cache[ $this->profile_id ] = array( 'id' => (int) $profile['id'], 'name' => $profile['name'], 'is_default' => (bool) $profile['is_default'], 'is_active' => (bool) $profile['is_active'], 'settings' => json_decode( $profile['settings'], true ) ?? array(), 'status' => json_decode( $profile['status'], true ) ?? array(), 'updated_at' => isset( $profile['updated_at'] ) ? (string) $profile['updated_at'] : null, ); return self::$profile_cache[ $this->profile_id ]; } /** * Clear the cached profile data for this profile. * * Clears the static cache entry for this profile_id, affecting * all IndexSettings instances that share this profile. * * @return void */ public function clearCache(): void { unset( self::$profile_cache[ $this->profile_id ] ); } /** * Clear all cached profile data. * * Use sparingly - typically only needed in tests or * when performing bulk operations across all profiles. * * @return void */ public static function clearAllCache(): void { self::$profile_cache = array(); } /** * Check if the feature is enabled. * * @return bool */ public function isEnabled(): bool { return (bool) $this->get( 'enabled', false ); } /** * Get all settings as array. * * @return array Settings with all keys and their values. */ public function getAll(): array { $profile = $this->loadProfile(); if ( ! $profile ) { return self::$defaults; } $settings = array(); foreach ( self::$defaults as $key => $default ) { $settings[ $key ] = $this->get( $key, $default ); } return $settings; } /** * Get a specific setting value. * * Global settings (enabled, max_products, batch_size, scheduled_enabled, schedule_frequency) * are always read from the default profile to ensure consistency across all profiles. * * @param string $key Setting key. * @param mixed $default Default value if not set. * @return mixed Setting value. */ public function get( string $key, $default = null ) { if ( null === $default && isset( self::$defaults[ $key ] ) ) { $default = self::$defaults[ $key ]; } if ( in_array( $key, ProfileManager::getGlobalSettingsKeys(), true ) ) { return $this->getGlobalSetting( $key, $default ); } if ( 'included_fields' === $key && null === $default ) { $default = ProfileManager::getDefaultIncludedFields(); } $profile = $this->loadProfile(); if ( ! $profile ) { return $default; } $value = $profile['settings'][ $key ] ?? $default; if ( in_array( $key, array( 'categories', 'tags', 'included_fields' ), true ) && ! is_array( $value ) ) { $value = ! empty( $value ) ? (array) $value : array(); } if ( in_array( $key, array( 'enabled', 'scheduled_enabled' ), true ) ) { $value = (bool) $value; } if ( in_array( $key, array( 'max_products', 'date_filter_days', 'batch_size' ), true ) ) { $value = (int) $value; } return $value; } /** * Get a global setting value from the default profile. * * Global settings are stored in the default profile and shared across all profiles. * This ensures consistency for settings like 'enabled', 'max_products', etc. * * @param string $key Setting key. * @param mixed $default Default value if not set. * @return mixed Setting value with proper type casting. */ private function getGlobalSetting( string $key, $default = null ) { $profile_manager = new ProfileManager(); $global_settings = $profile_manager->getGlobalSettings(); $value = $global_settings[ $key ] ?? $default; if ( in_array( $key, array( 'enabled', 'scheduled_enabled' ), true ) ) { $value = (bool) $value; } if ( in_array( $key, array( 'max_products', 'batch_size' ), true ) ) { $value = (int) $value; } return $value; } /** * Update settings from array. * * Global settings (enabled, max_products, batch_size, scheduled_enabled, schedule_frequency) * are automatically routed to ProfileManager to ensure consistency across all profiles. * * @param array $settings Partial or full settings array. * @return bool True on success. * @throws \InvalidArgumentException If validation fails. */ public function update( array $settings ): bool { $this->last_coerced_fields = array(); $this->last_coerced_reason = ''; $this->last_plan_denial = null; $this->unverified_fields = array(); $this->unverified_denial = null; $this->denial_reasons = array(); $settings = $this->validate( $settings ); if ( null !== $this->unverified_denial ) { $this->rejectUnverifiedChange(); return false; } $profile = $this->loadProfile(); if ( ! $profile ) { return false; } /** * Fires before index settings are written to the database. * * Lets extensions react to settings changes. At this point, $this->get() * still returns OLD values, while $settings contains the NEW values being * saved. This allows handlers to compare old vs new and take appropriate * action. * * The plugin itself no longer listens here: scheduled rebuilds react to * 'aipt_index_global_settings_updated', which ProfileManager fires after * the global settings of either save route were written. * * @since 2.5.0 * * @param array $settings The settings being updated (new values). * @param IndexSettings $index_settings This IndexSettings instance (old values via get()). */ $settings = apply_filters( 'aipt_index_settings_update', $settings, $this ); $global_settings_keys = ProfileManager::getGlobalSettingsKeys(); $global_settings = array(); $profile_settings = array(); foreach ( $settings as $key => $value ) { if ( ! array_key_exists( $key, self::$defaults ) ) { continue; } if ( in_array( $key, $global_settings_keys, true ) ) { $global_settings[ $key ] = $this->sanitize( $key, $value ); } else { $profile_settings[ $key ] = $this->sanitize( $key, $value ); } } $globals_were_written = false; if ( ! empty( $global_settings ) ) { try { $profile_manager = new ProfileManager(); $global_update_success = $profile_manager->updateGlobalSettings( $global_settings ); $this->mergeGlobalPlanOutcome( $profile_manager ); if ( null !== $this->last_plan_denial ) { return false; } if ( ! $global_update_success ) { return false; } $globals_were_written = true; } catch ( \RuntimeException $e ) { return false; } catch ( \InvalidArgumentException $e ) { return false; } } $result = true; if ( ! empty( $profile_settings ) ) { if ( $globals_were_written ) { $this->clearCache(); $reloaded = $this->loadProfile(); if ( ! is_array( $reloaded ) ) { error_log( '[AIPT] IndexSettings: profile ' . $this->profile_id . ' disappeared after the global settings write; profile-specific settings were not applied.' ); return false; } $profile = $reloaded; } $current_settings = $profile['settings']; foreach ( $profile_settings as $key => $value ) { $current_settings[ $key ] = $value; } global $wpdb; $db_result = $wpdb->update( $this->table_name, array( 'settings' => wp_json_encode( $current_settings ), 'updated_at' => current_time( 'mysql' ), ), array( 'id' => $this->profile_id ), array( '%s', '%s' ), array( '%d' ) ); $result = false !== $db_result; } $this->clearCache(); return $result; } /** * Get submitted fields changed by plan enforcement during the last update. * * @return string[] Setting keys. */ public function getLastCoercedFields(): array { return $this->last_coerced_fields; } /** * Get the denial reason of the plan clamps applied during the last update. * * @return string A PlanDenial reason, or '' when nothing was clamped. */ public function getLastCoercedReason(): string { return $this->last_coerced_reason; } /** * Get the plan denial that rejected the last update. * * @return WP_Error|null 403 premium_required error, or null. */ public function getLastPlanDenial(): ?WP_Error { return $this->last_plan_denial; } /** * Get index status metadata. * * @return array Status with keys: status, last_build, product_count, etc. */ public function getStatus(): array { $profile = $this->loadProfile(); if ( ! $profile ) { return array_merge( self::$status_defaults, array( 'enabled' => false, 'is_building' => false, ) ); } $status = $profile['status']; return array( 'enabled' => $this->isEnabled(), 'status' => $status['status'] ?? 'idle', 'last_build' => $status['last_build'] ?? null, 'product_count' => (int) ( $status['product_count'] ?? 0 ), 'category_count' => (int) ( $status['category_count'] ?? 0 ), 'file_size' => (int) ( $status['file_size'] ?? 0 ), 'trimmed_count' => (int) ( $status['trimmed_count'] ?? 0 ), 'shard_count' => (int) ( $status['shard_count'] ?? 0 ), 'error' => $status['error'] ?? null, 'error_code' => isset( $status['error_code'] ) ? (string) $status['error_code'] : null, 'build_progress' => (int) ( $status['build_progress'] ?? 0 ), 'is_building' => ( $status['status'] ?? 'idle' ) === 'building', 'progress_percent' => (int) ( $status['progress_percent'] ?? 0 ), 'processed_product_count' => (int) ( $status['processed_product_count'] ?? 0 ), 'estimated_total_products' => (int) ( $status['estimated_total_products'] ?? 0 ), 'effective_filter_summary' => isset( $status['effective_filter_summary'] ) && is_array( $status['effective_filter_summary'] ) ? $status['effective_filter_summary'] : array(), 'build_job_id' => (int) ( $status['build_job_id'] ?? 0 ), 'last_processed_id' => (int) ( $status['last_processed_id'] ?? 0 ), 'meta' => $this->buildStatusMeta( $profile, $status ), ); } /** * Build the `meta` sub-object surfaced by getStatus(). * * Kept in its own method so the ShardManager probe (which can be * relatively expensive when the map is first read in a request) is * lazy / isolated from the rest of the getStatus shape, and so unit * tests can override it via reflection. * * @param array $profile Raw profile row (from loadProfile()). * @param array $status Raw status JSON. * @return array */ protected function buildStatusMeta( array $profile, array $status ): array { $map_version = null; $index_health = null; $shard_manager = new ShardManager( $this->profile_id ); $map = $shard_manager->loadMap(); if ( is_array( $map ) ) { $map_version = isset( $map['meta']['map_version'] ) ? (int) $map['meta']['map_version'] : null; } else { $index_health = $shard_manager->getLastLoadError(); } $last_build = isset( $status['last_build'] ) ? (string) $status['last_build'] : null; $building = 'building' === ( $status['status'] ?? '' ); $profile_schema_version = (int) ( $status['profile_schema_version'] ?? 0 ); $profile_outdated = ! $building && ! empty( $last_build ) && $profile_schema_version < ProductProfileBuilder::PROFILE_SCHEMA_VERSION; if ( $building ) { $stale_product_count = 0; } elseif ( $profile_outdated ) { $stale_product_count = (int) ( $status['product_count'] ?? 0 ); } else { $stale_product_count = $this->countProductsModifiedSince( $last_build ); } return array( 'status_version' => (int) ( $status['status_version'] ?? 0 ), 'updated_at' => isset( $profile['updated_at'] ) ? (string) $profile['updated_at'] : null, 'map_version' => $map_version, 'profile_id' => (int) $this->profile_id, 'job_id' => (int) ( $status['build_job_id'] ?? 0 ), 'error_code' => isset( $status['error_code'] ) ? (string) $status['error_code'] : null, 'index_health' => $index_health, 'phase' => isset( $status['phase'] ) ? (string) $status['phase'] : 'idle', 'built_empty' => ( $status['status'] ?? '' ) === 'built_empty', 'effective_filter_summary' => isset( $status['effective_filter_summary'] ) && is_array( $status['effective_filter_summary'] ) ? $status['effective_filter_summary'] : array(), 'stale_product_count' => $stale_product_count, 'profile_schema_version' => $profile_schema_version, 'profile_outdated' => $profile_outdated, ); } /** * Count published products modified after the index's last completed * build, so the admin status can say honestly when the index no longer * reflects the current catalog instead of reporting "up to date" purely * because the last build job finished without error. * * @param string|null $last_build ISO 8601 timestamp of the last completed build (current_time('c')), or null if never built. * @return int Number of published products modified since $last_build (0 when never built). */ private function countProductsModifiedSince( ?string $last_build ): int { if ( empty( $last_build ) ) { return 0; } $timestamp = strtotime( $last_build ); if ( false === $timestamp ) { return 0; } global $wpdb; $cutoff = gmdate( 'Y-m-d H:i:s', $timestamp ); $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' AND post_modified_gmt > %s", $cutoff ) ); return (int) $count; } /** * Update status metadata. * * @param array $status Partial or full status array. * @return void */ public function updateStatus( array $status ): void { $profile = $this->loadProfile(); if ( ! $profile ) { return; } $allowed_keys = array( 'status', 'last_build', 'product_count', 'category_count', 'file_size', 'trimmed_count', 'shard_count', 'error', 'error_code', 'status_version', 'phase', 'build_progress', 'build_job_id', 'progress_percent', 'processed_product_count', 'estimated_total_products', 'effective_filter_summary', 'last_processed_id', 'profile_schema_version', ); $current_status = $profile['status']; foreach ( $status as $key => $value ) { if ( in_array( $key, $allowed_keys, true ) ) { $current_status[ $key ] = $value; } } if ( ! array_key_exists( 'status_version', $status ) ) { $current_status['status_version'] = (int) ( $current_status['status_version'] ?? 0 ) + 1; } global $wpdb; $wpdb->update( $this->table_name, array( 'status' => wp_json_encode( $current_status ), 'updated_at' => current_time( 'mysql' ), ), array( 'id' => $this->profile_id ), array( '%s', '%s' ), array( '%d' ) ); $this->clearCache(); } /** * Get included fields for this profile. * * Always includes mandatory fields (title, categories) regardless of settings. * * @return array List of field names to include in the index. */ public function getIncludedFields(): array { $fields = $this->get( 'included_fields', self::$defaults['included_fields'] ); $fields = apply_filters( 'aipt_index_validate_included_fields', $fields ); $fields = array_values( array_intersect( (array) $fields, ProfileManager::getAvailableFieldsForPlan() ) ); return ProfileManager::ensureMandatoryFields( $fields ); } /** * Category or tag filter terms the index build applies. * * Saves keep stored paid filters they did not change, so the build decides * whether a stored filter still applies, like getIncludedFields() does for * Business fields. An entitled site gets its stored terms. After a * definitive denial the build ignores them (they stay stored and apply * again when access returns), so a lapsed site is never left restricted by * a paid filter its plan hides. While the license cannot be verified the * stored terms are returned unchanged: IndexBuilder::start() refuses such a * build first (getBuildFilterDenial()), so an index is never widened for an * outage. * * @param string $key Setting key: 'categories' or 'tags'. * @return int[] Term IDs. */ public function getBuildFilterTerms( string $key ): array { $terms = array_values( array_filter( array_map( 'absint', (array) $this->get( $key, array() ) ) ) ); if ( empty( $terms ) || $this->canApplyStoredFilter( $key ) ) { return $terms; } $reason = PlanDenial::reason( 'storeIndexFilters', PlanDenial::PLAN_PAID ); return PlanDenial::isVerificationUnavailable( $reason ) ? $terms : array(); } /** * Plan denial that must stop an index build, or null. * * Non-null only while stored category or tag filters exist and the license * cannot be verified for them: building without them would widen the index, * and building with them would apply a paid restriction on unverified access. * * @return WP_Error|null 403 premium_required error with the stored filter keys in 'fields'. */ public function getBuildFilterDenial(): ?WP_Error { $fields = array(); foreach ( array( 'categories', 'tags' ) as $key ) { $terms = array_filter( array_map( 'absint', (array) $this->get( $key, array() ) ) ); if ( ! empty( $terms ) && ! $this->canApplyStoredFilter( $key ) ) { $fields[] = $key; } } if ( empty( $fields ) ) { return null; } $reason = PlanDenial::reason( 'storeIndexFilters', PlanDenial::PLAN_PAID ); if ( ! PlanDenial::isVerificationUnavailable( $reason ) ) { return null; } return PlanDenial::error( 'storeIndexFilters', PlanDenial::PLAN_PAID, __( 'Business plan adds category and tag filters to the Store Index.', 'ai-product-tools' ), 'premium_required', array( 'fields' => $fields ) ); } /** * Whether the plan allows a stored category or tag filter (G9 bridges). * * @param string $key Setting key: 'categories' or 'tags'. * @return bool */ private function canApplyStoredFilter( string $key ): bool { return 'categories' === $key ? (bool) ProfileManager::canFilterCategories() : (bool) ProfileManager::canFilterTags(); } /** * Check if a field is included in the index. * * @param string $field Field name. * @return bool True if field is included. */ public function isFieldIncluded( string $field ): bool { $included = $this->getIncludedFields(); return in_array( $field, $included, true ); } /** * Check a category or tag filter against the store's terms. * * A term deleted in WooCommerce stays in the stored profile and comes back * with every save of the form, so a stored id that no longer exists is * dropped instead of blocking the save. Only an id the save adds is refused. * * @param string $key Setting key: 'categories' or 'tags'. * @param string $taxonomy Term taxonomy for the key. * @param mixed $ids Requested term ids. * @param string $message Translated message with a %d placeholder for the refused id. * @return int[] Ids that exist, or were not changed by this save and are kept as is. * @throws \InvalidArgumentException If the save adds an id that does not exist. */ private function dropDeletedStoredTerms( string $key, string $taxonomy, $ids, string $message ): array { $stored = array_map( 'absint', (array) $this->get( $key ) ); $kept = array(); foreach ( (array) $ids as $term_id ) { $term_id = (int) $term_id; if ( term_exists( $term_id, $taxonomy ) ) { $kept[] = $term_id; continue; } if ( ! in_array( $term_id, $stored, true ) ) { throw new \InvalidArgumentException( sprintf( $message, $term_id ) ); } } return $kept; } /** * Validate settings against rules. * * @param array $settings Settings to validate. * @throws \InvalidArgumentException If validation fails. */ private function validate( array $settings ): array { foreach ( $settings as $key => $value ) { if ( ! isset( self::$validation_rules[ $key ] ) ) { continue; } $rules = self::$validation_rules[ $key ]; if ( isset( $rules['min'] ) && isset( $rules['max'] ) ) { $int_value = (int) $value; if ( $int_value < $rules['min'] || $int_value > $rules['max'] ) { throw new \InvalidArgumentException( sprintf( /* translators: 1: Setting key name, 2: Minimum value, 3: Maximum value */ __( '%1$s must be between %2$d and %3$d', 'ai-product-tools' ), $key, $rules['min'], $rules['max'] ) ); } } if ( isset( $rules['allowed'] ) ) { if ( ! in_array( $value, $rules['allowed'], true ) ) { throw new \InvalidArgumentException( sprintf( /* translators: 1: Setting key name, 2: Allowed values list */ __( '%1$s must be one of: %2$s', 'ai-product-tools' ), $key, implode( ', ', $rules['allowed'] ) ) ); } } } if ( isset( $settings['categories'] ) && ! empty( $settings['categories'] ) ) { $settings['categories'] = $this->resolvePaidFilter( 'categories', $settings['categories'] ); $settings['categories'] = $this->dropDeletedStoredTerms( 'categories', 'product_cat', $settings['categories'], /* translators: %d: Category term ID that does not exist */ __( 'Category %d does not exist. Remove it from the category filter and save again.', 'ai-product-tools' ) ); } if ( isset( $settings['tags'] ) && ! empty( $settings['tags'] ) ) { $settings['tags'] = $this->resolvePaidFilter( 'tags', $settings['tags'] ); $settings['tags'] = $this->dropDeletedStoredTerms( 'tags', 'product_tag', $settings['tags'], /* translators: %d: Tag term ID that does not exist */ __( 'Tag %d does not exist. Remove it from the tag filter and save again.', 'ai-product-tools' ) ); } if ( isset( $settings['included_fields'] ) ) { $settings['included_fields'] = $this->resolveIncludedFields( $settings['included_fields'] ); $available = ProfileManager::getAvailableFields(); foreach ( $settings['included_fields'] as $field ) { if ( ! in_array( $field, $available, true ) ) { throw new \InvalidArgumentException( sprintf( /* translators: %s: Invalid field name */ __( 'Invalid field: %s', 'ai-product-tools' ), $field ) ); } } } return $settings; } private function recordPlanCoercion( string $field, $requested, $filtered ): void { if ( $requested === $filtered ) { return; } $this->last_coerced_fields[] = $field; $this->last_coerced_fields = array_values( array_unique( $this->last_coerced_fields ) ); } /** * Apply the paid category or tag filter gate to a submitted, non-empty filter. * * Unchanged filters (same terms as stored) are kept without a plan check. * A changed filter needs the G9 bridge (false by default, so the free build * clamps too); a definitive denial clears it and reports why, and * license_unverified rejects the save (see update()). * * @param string $key Setting key: 'categories' or 'tags'. * @param mixed $raw Submitted term IDs. * @return mixed Term IDs to validate and persist. */ private function resolvePaidFilter( string $key, $raw ) { $requested = array_map( 'absint', (array) $raw ); $stored = array_map( 'absint', (array) $this->get( $key ) ); sort( $requested ); sort( $stored ); if ( $requested === $stored ) { return $raw; } $can_filter = 'categories' === $key ? ProfileManager::canFilterCategories() : ProfileManager::canFilterTags(); if ( $can_filter ) { $filtered = apply_filters( 'aipt_index_validate_' . $key, $raw ); $this->recordPlanCoercion( $key, $raw, $filtered ); return $filtered; } $reason = $this->planDenialReason( 'storeIndexFilters', PlanDenial::PLAN_PAID ); if ( PlanDenial::isVerificationUnavailable( $reason ) ) { $this->recordUnverifiedChange( $key, 'storeIndexFilters', PlanDenial::PLAN_PAID, __( 'Business plan adds category and tag filters to the Store Index.', 'ai-product-tools' ) ); return $raw; } $this->recordPlanCoercion( $key, $raw, array() ); $this->recordCoercionReason( $reason ); return array(); } /** * Apply the Business field gate to the Business fields a save adds. * * Business fields already stored for this profile stay: a save never * re-clamps them. Newly added ones need the plan's field set (Free fields * by default, so the free build clamps too); a definitive denial removes * only those and reports why, and license_unverified rejects the save. * * @param mixed $raw Submitted field list. * @return array Field list to validate and persist. */ private function resolveIncludedFields( $raw ): array { $requested = array_values( (array) $raw ); $business_fields = array_diff( ProfileManager::AVAILABLE_FIELDS, ProfileManager::FREE_TIER_FIELDS ); $added_business = array_intersect( array_diff( $requested, (array) $this->get( 'included_fields' ) ), $business_fields ); $denied = array_values( array_diff( $added_business, ProfileManager::getAvailableFieldsForPlan() ) ); if ( empty( $denied ) ) { return $requested; } $reason = $this->planDenialReason( 'storeIndexBusinessFields', PlanDenial::PLAN_BUSINESS ); if ( PlanDenial::isVerificationUnavailable( $reason ) ) { $this->recordUnverifiedChange( 'included_fields', 'storeIndexBusinessFields', PlanDenial::PLAN_BUSINESS, __( 'Business plan adds SKU, stock quantity and attributes to the Store Index.', 'ai-product-tools' ) ); return $requested; } $filtered = array_values( array_diff( $requested, $denied ) ); $this->recordPlanCoercion( 'included_fields', $requested, $filtered ); $this->recordCoercionReason( $reason ); return $filtered; } /** * Memoized denial reason for a feature within the current update. * * @param string $feature Feature key. * @param string $required_plan PlanDenial plan constant. * @return string */ private function planDenialReason( string $feature, string $required_plan ): string { if ( ! isset( $this->denial_reasons[ $feature ] ) ) { $this->denial_reasons[ $feature ] = PlanDenial::reason( $feature, $required_plan ); } return $this->denial_reasons[ $feature ]; } /** * Keep the most specific clamp reason: anything but plan_required wins. * * @param string $reason PlanDenial reason. * @return void */ private function recordCoercionReason( string $reason ): void { if ( '' === $this->last_coerced_reason || PlanDenial::REASON_PLAN_REQUIRED === $this->last_coerced_reason ) { $this->last_coerced_reason = $reason; } } /** * Record a paid change the license could not be verified for. * * @param string $field Setting key. * @param string $feature Feature key. * @param string $required_plan PlanDenial plan constant. * @param string $plan_message Translated plan copy. * @return void */ private function recordUnverifiedChange( string $field, string $feature, string $required_plan, string $plan_message ): void { $this->unverified_fields[] = $field; if ( null === $this->unverified_denial ) { $this->unverified_denial = array( $feature, $required_plan, $plan_message ); } } /** * Turn the recorded unverified change into the update's plan denial. * * @return void */ private function rejectUnverifiedChange(): void { $this->last_coerced_fields = array(); $this->last_coerced_reason = ''; $this->last_plan_denial = PlanDenial::error( $this->unverified_denial[0], $this->unverified_denial[1], $this->unverified_denial[2], 'premium_required', array( 'fields' => array_values( array_unique( $this->unverified_fields ) ) ) ); } /** * Carry the global settings save's plan clamps or denial into this update. * * @param ProfileManager $profile_manager Manager that saved the global settings. * @return void */ private function mergeGlobalPlanOutcome( ProfileManager $profile_manager ): void { $denial = $profile_manager->getLastPlanDenial(); if ( null !== $denial ) { $this->last_coerced_fields = array(); $this->last_coerced_reason = ''; $this->last_plan_denial = $denial; return; } foreach ( $profile_manager->getLastCoercedFields() as $field ) { $this->recordPlanCoercion( $field, true, false ); } if ( '' !== $profile_manager->getLastCoercedReason() ) { $this->recordCoercionReason( $profile_manager->getLastCoercedReason() ); } } /** * Sanitize a setting value based on its key. * * @param string $key Setting key. * @param mixed $value Value to sanitize. * @return mixed Sanitized value. */ private function sanitize( string $key, $value ) { switch ( $key ) { case 'enabled': case 'scheduled_enabled': return (bool) $value; case 'max_products': case 'date_filter_days': case 'batch_size': return absint( $value ); case 'categories': case 'tags': return array_map( 'absint', (array) $value ); case 'attributes': return array_values( array_unique( array_intersect( array_map( 'strval', array_filter( (array) $value, 'is_scalar' ) ), ProfileManager::getAvailableAttributeSlugs() ) ) ); case 'included_fields': $available = ProfileManager::getAvailableFields(); return array_values( array_intersect( (array) $value, $available ) ); case 'stock_filter': case 'filter_mode': case 'schedule_frequency': return sanitize_text_field( $value ); default: return $value; } } /** * Unschedule all index-related jobs (used on disable/deactivation). * * @return void */ public function unscheduleAllJobs(): void { if ( ! function_exists( 'as_unschedule_all_actions' ) ) { return; } as_unschedule_all_actions( 'aipt_scheduled_index_rebuild', array( 'profile_id' => $this->profile_id ), 'aipt-store-index' ); as_unschedule_all_actions( 'aipt_build_store_index', array( 'profile_id' => $this->profile_id ), 'aipt-store-index' ); } /** * Get default settings values. * * @return array */ public static function getDefaults(): array { return self::$defaults; } /** * Get default included fields. * * Delegates to ProfileManager::getDefaultIncludedFields() since the * defaults array stores null to allow runtime resolution. * * @return array Default included fields. */ public static function getDefaultIncludedFields(): array { return ProfileManager::getDefaultIncludedFields(); } }