Product: {title}
Category: {CATEGORIES}
Specs: {ATTRIBUTES}
Price: {REGULAR_PRICE} | Sale: {SALE_PRICE}
Write 2-3 sentences that hook the reader:
1. Open with the main benefit (what problem does this solve?)
2. Include one specific spec that proves the benefit
3. Make them want to read the full description
';
private const LEGACY_FULL_SYSTEM_PROMPT = 'Write a product description in {language} using a {style} tone.
Apply the "So What?" test: for every feature, explain what it means for the customer.
Be specific—use actual details from the product data, not generic phrases.
Format: Use
for paragraphs,
- for feature lists, for key benefits.';
private const LEGACY_FULL_USER_PROMPT = '
Product: {title}
Category: {CATEGORIES}
Specs: {ATTRIBUTES}
Price: {REGULAR_PRICE}
Sale: {SALE_PRICE}
Write a complete product description:
1. Open with WHY someone would want this (benefit-first, not product name)
2. Cover key features—transform each into customer value
3. Include practical details (materials, dimensions, compatibility)
4. Close with confidence (no "whether you\'re..." clichés)
Before finishing: could a competitor use this exact text? If yes, add more specific details.
';
/**
* Defaults of the retired split prompt options, served by
* get_default_value() but never seeded.
*
* @var array
*/
private const LEGACY_PROMPT_DEFAULTS = [
'system_prompt' => '',
'user_prompt' => '',
'short_system_prompt' => self::LEGACY_SHORT_SYSTEM_PROMPT,
'short_user_prompt' => self::LEGACY_SHORT_USER_PROMPT,
'full_system_prompt' => self::LEGACY_FULL_SYSTEM_PROMPT,
'full_user_prompt' => self::LEGACY_FULL_USER_PROMPT,
];
/**
* Options that should NOT be autoloaded (autoload = false).
*
* These are only accessed on specific admin pages, during content generation,
* or during one-time migrations — never on every frontend page load.
* Keeping them out of the autoload query reduces memory and TTFB on every request.
*
* Options NOT in this list remain autoloaded because they are read on
* every page load (encryption checks, chatbot widget, AI provider config).
*
* @var string[]
*/
private static $non_autoload_options = [
'system_prompt',
'user_prompt',
'short_system_prompt',
'short_user_prompt',
'full_system_prompt',
'full_user_prompt',
'short_custom_prompt',
'full_custom_prompt',
'title_additional_prompt',
'faq_additional_prompt',
'seo_meta_additional_prompt',
'taxonomy_additional_prompt',
'brand_context',
'custom_variables',
'store_index_enabled',
'store_index_max_products',
'store_index_categories',
'store_index_stock_filter',
'store_index_date_filter_days',
'store_index_attributes',
'store_index_schedule',
'store_index_batch_size',
'store_index_status',
'store_index_build_progress',
'store_index_build_job_id',
'metabox_hidden',
'needs_setup',
'setup_completed',
'first_activation',
'first_run_completed',
'onboarding_dismissed',
'onboarding_snoozed_until',
'schema_version',
'db_version',
'version',
'previous_version',
'bulk_terms_accepted',
'enable_tooltip',
'prompt_priority',
'preserve_content_images',
'editor_clear_ai_mark_on_manual_edit',
'content_history_enabled',
'content_history_retention',
'faq_display_settings',
];
private static $default_values = [
'openai_api_key' => '',
'gemini_api_key' => '',
'api_provider' => 'openai',
'short_custom_prompt' => self::LEGACY_SHORT_SYSTEM_PROMPT . "\n\n" . self::LEGACY_SHORT_USER_PROMPT,
'full_custom_prompt' => self::LEGACY_FULL_SYSTEM_PROMPT . "\n\n" . self::LEGACY_FULL_USER_PROMPT,
'title_additional_prompt' => '',
'faq_additional_prompt' => '',
'seo_meta_additional_prompt' => '',
'taxonomy_additional_prompt' => '',
'language' => 'English',
'writing_style' => 'Professional',
'content_length_preset' => 'long',
'short_length_preset' => 'standard',
'max_tags_count' => '3',
'model' => 'gpt-5.6-terra',
'enable_tooltip' => true,
'metabox_hidden' => false,
'preserve_content_images' => true,
'editor_clear_ai_mark_on_manual_edit' => false,
'content_history_enabled' => true,
'content_history_retention' => 5,
'needs_setup' => true,
'setup_completed' => false,
'store_index_enabled' => false,
'store_index_max_products' => 10000,
'store_index_categories' => [],
'store_index_stock_filter' => 'all',
'store_index_date_filter_days' => 0,
'store_index_attributes' => [],
'store_index_schedule' => 'daily',
'store_index_batch_size' => 100,
];
public static function activate() {
global $wp_version;
if ( version_compare( $wp_version, AIPT_MIN_WP_VERSION, '<' ) ) {
deactivate_plugins( plugin_basename( AIPT_PLUGIN_DIR . 'ai-product-tools.php' ) );
wp_die(
sprintf(
/* translators: %s: minimum WordPress version */
esc_html__( 'AI Product Tools requires WordPress %s or higher. Please upgrade WordPress and try again.', 'ai-product-tools' ),
esc_html( AIPT_MIN_WP_VERSION )
),
esc_html__( 'Plugin Activation Error', 'ai-product-tools' ),
[ 'back_link' => true ]
);
}
if ( self::is_fresh_install( get_option( 'aipt_first_activation', true ), (string) get_option( 'aipt_version', '0' ) ) ) {
\AIPT\Core\FirstRun\FirstRunState::markEligible();
\AIPT\Core\FirstRun\FirstRunState::recordFirstInstalledVersion( defined( 'AIPT_VERSION' ) ? (string) AIPT_VERSION : '' );
}
if (!class_exists('WooCommerce')) {
return;
}
self::handle_version_conflicts();
try {
$is_first_activation = get_option('aipt_first_activation', true);
$previous_version = get_option('aipt_version', '0');
require_once AIPT_PLUGIN_DIR . 'src/Core/Database/Migration.php';
$migration = \AIPT\Core\Database\Migration::get_instance();
$migration->create_activation_tables();
if (defined('AIPT_VERSION')) {
update_option('aipt_schema_version', AIPT_VERSION, false);
}
try {
$log_cleaner = new JobLogCleaner();
$log_cleaner->schedule();
} catch (\Exception $e) {
}
try {
$review_cleaner = new ContentReviewCleaner();
$review_cleaner->schedule();
} catch (\Exception $e) {
}
try {
\AIPT\Core\ContentSnapshots\SnapshotStore::schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] SnapshotStore::schedule() failed during activation: %s',
$t->getMessage()
) );
}
try {
$pricing_hook = \AIPT\Core\Services\PricingFeedManager::CRON_HOOK;
if ( ! \wp_next_scheduled( $pricing_hook ) ) {
\wp_schedule_event( time() + 30, 'daily', $pricing_hook );
}
\wp_schedule_single_event( time() + 60, $pricing_hook );
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] PricingFeedManager activation scheduling failed: %s',
$t->getMessage()
) );
}
try {
$rate_limit_cleaner = new RateLimiterCleaner();
$rate_limit_cleaner->schedule();
} catch (\Throwable $t) {
error_log( sprintf(
'[AIPT] RateLimiterCleaner::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
$request_claim_cleaner = new RequestClaimCleaner();
$request_claim_cleaner->schedule();
} catch (\Throwable $t) {
error_log( sprintf(
'[AIPT] RequestClaimCleaner::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
( new McpAuditLogCleaner() )->schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] McpAuditLogCleaner::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
( new McpCredentialCleaner() )->schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] McpCredentialCleaner::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
( new McpOAuthClientGc() )->schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] McpOAuthClientGc::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
( new McpConnectionCapabilitySweeper() )->schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] McpConnectionCapabilitySweeper::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
( new BlueprintCleanup() )->schedule();
} catch ( \Throwable $t ) {
error_log( sprintf(
'[AIPT] BlueprintCleanup::schedule() failed during activation: %s in %s:%d',
$t->getMessage(),
$t->getFile(),
$t->getLine()
) );
}
try {
\AIPT\Core\Services\UsageTracker::record_milestone(
\AIPT\Core\Services\UsageTracker::MILESTONE_ACTIVATION,
array( 'version' => defined( 'AIPT_VERSION' ) ? AIPT_VERSION : '' )
);
\AIPT\Core\Services\UsageTracker::schedule();
} catch ( \Throwable $t ) {
}
try {
\AIPT\Api\AutomationJobs\JobScheduler::setupCronSchedules();
} catch (\Exception $e) {
}
try {
ChatbotJobWorker::scheduleStaleRecovery();
} catch ( \Throwable $throwable ) {
}
if ($is_first_activation) {
foreach (self::$default_values as $key => $value) {
if (get_option('aipt_' . $key) === false) {
$autoload = in_array($key, self::$non_autoload_options, true) ? false : null;
add_option('aipt_' . $key, $value, '', $autoload);
}
}
self::seed_default_templates();
self::seed_content_mode();
}
self::check_and_update_setup_status();
\AIPT\Utils\ApiKeyManager::migrate_keys_if_needed();
if ($is_first_activation) {
update_option('aipt_first_activation', false, false);
}
update_option('aipt_version', AIPT_VERSION, false);
if (version_compare($previous_version, '2.6.0', '<') && version_compare($previous_version, '0', '>')) {
self::migrate_to_optimized_prompts();
}
if ( version_compare( $previous_version, '0', '>' ) && get_option( 'aipt_quickstart_completed' ) === false ) {
update_option( 'aipt_quickstart_completed', true, false );
}
self::ensure_preset_defaults();
self::migrate_store_index_build_state();
self::optimize_autoload_settings();
} catch (\Exception $e) {
set_transient('aipt_database_error',
sprintf(
/* translators: %1$s: previous version, %2$s: current version, %3$s: error message */
__('Plugin upgrade from version %1$s to %2$s failed. Please try again or contact support if the problem persists. Error: %3$s', 'ai-product-tools'),
$previous_version,
AIPT_VERSION,
$e->getMessage()
),
60
);
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
deactivate_plugins(plugin_basename(AIPT_PLUGIN_DIR . 'ai-product-tools.php'));
if (isset($_GET['activate'])) {
unset($_GET['activate']);
}
}
}
public static function get_default_value($key) {
if (isset(self::$default_values[$key])) {
return self::$default_values[$key];
}
return self::LEGACY_PROMPT_DEFAULTS[$key] ?? '';
}
private static function ensure_preset_defaults() {
$content_preset = get_option('aipt_content_length_preset', '');
$short_preset = get_option('aipt_short_length_preset', '');
$valid_content_presets = array('short', 'medium', 'long', 'very_long');
$valid_short_presets = array('brief', 'standard', 'detailed');
if (empty($content_preset) || !in_array($content_preset, $valid_content_presets, true)) {
update_option('aipt_content_length_preset', 'long');
}
if (empty($short_preset) || !in_array($short_preset, $valid_short_presets, true)) {
update_option('aipt_short_length_preset', 'standard');
}
}
/**
* Whether the site never had this plugin before.
*
* Both signals come from data the plugin already stores: the
* `aipt_first_activation` option is absent until the first successful
* activation, and `aipt_version` is absent until the first migration
* stamps it. An upgrade or a reactivation of an existing install has at
* least one of them, so it is never fresh.
*
* @param mixed $is_first_activation Value of `aipt_first_activation` (default true when absent).
* @param string $previous_version Value of `aipt_version` before this activation ('0' when absent).
* @return bool
*/
public static function is_fresh_install( $is_first_activation, string $previous_version ): bool {
return true === $is_first_activation && '0' === $previous_version;
}
/**
* Setup durumunu kontrol et ve güncelle
* Her activation'da çağrılmalı
*/
public static function check_and_update_setup_status() {
$has_any_api_key = false;
if (class_exists('\AIPT\Utils\ApiKeyManager')) {
$has_any_api_key = \AIPT\Utils\ApiKeyManager::has_any_api_key();
} else {
$openai_api_key = get_option('aipt_openai_api_key', '');
$gemini_api_key = get_option('aipt_gemini_api_key', '');
$claude_api_key = get_option('aipt_claude_api_key', '');
$has_any_api_key = !empty($openai_api_key) || !empty($gemini_api_key) || !empty($claude_api_key);
}
$needs_setup = !$has_any_api_key;
$setup_completed = $has_any_api_key;
update_option('aipt_needs_setup', $needs_setup, false);
update_option('aipt_setup_completed', $setup_completed, false);
if (defined('WP_DEBUG') && WP_DEBUG) {
}
return $setup_completed;
}
/**
* Setup gerekip gerekmediğini kontrol et
*/
public static function requires_setup() {
self::check_and_update_setup_status();
$needs_setup = get_option('aipt_needs_setup', true);
$setup_completed = get_option('aipt_setup_completed', false);
if ($needs_setup === false && $setup_completed === true) {
return false;
}
if ($needs_setup === true || $setup_completed === false) {
return true;
}
if (class_exists('\AIPT\Utils\ApiKeyManager')) {
return !\AIPT\Utils\ApiKeyManager::has_any_api_key();
}
$openai_api_key = get_option('aipt_openai_api_key', '');
$gemini_api_key = get_option('aipt_gemini_api_key', '');
$claude_api_key = get_option('aipt_claude_api_key', '');
return empty($openai_api_key) && empty($gemini_api_key) && empty($claude_api_key);
}
/**
* Migrate AI Store Index build state for optimization update.
*
* Cancels any in-progress builds that use old OFFSET pagination
* and cleans up legacy transient storage.
*/
private static function migrate_store_index_build_state() {
if (function_exists('as_unschedule_all_actions')) {
as_unschedule_all_actions('aipt_build_store_index', [], 'aipt-store-index');
}
delete_transient('aipt_index_build_data');
$status = get_option('aipt_store_index_status', 'idle');
if ($status === 'building') {
update_option('aipt_store_index_status', 'idle', false);
update_option('aipt_store_index_build_progress', 0, false);
update_option('aipt_store_index_build_job_id', 0, false);
}
}
/**
* Migrate users to optimized prompt system (v2.6.0+)
*
* Clears old verbose default prompts if user hasn't customized them.
* This allows PromptFactory's optimized base prompts to take effect.
*/
private static function migrate_to_optimized_prompts() {
$old_defaults = [
'short_system_prompt' => [
'You are a professional product description writer specializing in e-commerce',
'Make it engaging and action-driven',
],
'short_user_prompt' => [
'Write a compelling short description in {language}',
'Focus on the product\'s key features and value',
],
'full_system_prompt' => [
'You are an expert product description writer for e-commerce',
'Begin with a compelling introduction that captures attention',
],
'full_user_prompt' => [
'Write a detailed product description in {language}',
'Introduction – Briefly introduce the product',
'Key Features – List important features',
],
];
foreach ($old_defaults as $option_key => $fingerprints) {
$current_value = get_option('aipt_' . $option_key, '');
if (empty($current_value)) {
continue;
}
$is_old_default = true;
foreach ($fingerprints as $fingerprint) {
if (strpos($current_value, $fingerprint) === false) {
$is_old_default = false;
break;
}
}
if ($is_old_default) {
$new_default = self::get_default_value($option_key);
update_option('aipt_' . $option_key, $new_default);
}
}
}
/**
* Handle version conflicts during activation
* Automatically deactivates conflicting versions
*/
private static function handle_version_conflicts() {
if (!function_exists('get_plugins')) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$current_plugin = plugin_basename(AIPT_PLUGIN_DIR . 'ai-product-tools.php');
$conflicting_plugins = [];
$possible_conflicts = [
'ai-product-tools/ai-product-tools.php',
'ai-product-tools-premium/ai-product-tools.php',
'ai-product-tools-pro/ai-product-tools.php'
];
foreach ($possible_conflicts as $plugin_path) {
if ($plugin_path !== $current_plugin && is_plugin_active($plugin_path)) {
$conflicting_plugins[] = $plugin_path;
}
}
if (!empty($conflicting_plugins)) {
foreach ($conflicting_plugins as $conflict_plugin) {
deactivate_plugins($conflict_plugin, true);
}
if (defined('WP_DEBUG') && WP_DEBUG) {
}
}
}
/**
* Seed default prompt templates on first activation.
*
* Inserts pre-built templates for description and standard generators
* so users have a starting point in the Prompt Templates tab.
*/
private static function seed_default_templates(): void {
global $wpdb;
$table_name = $wpdb->prefix . 'aipt_prompt_templates';
$table_exists = $wpdb->get_var(
$wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name )
);
if ( $table_exists !== $table_name ) {
return;
}
$existing_count = (int) $wpdb->get_var(
"SELECT COUNT(*) FROM {$table_name}"
);
if ( $existing_count > 0 ) {
return;
}
$now = current_time( 'mysql' );
$templates = [
[
'name' => 'Default Description Prompts',
'description' => 'Pre-configured prompts for the Advanced Bulk Description Generator.',
'generator_type' => 'description',
'prompt_data' => wp_json_encode( [
'custom_prompt' => self::get_default_value( 'short_custom_prompt' ),
] ),
'is_default' => 1,
'source' => 'local',
'created_at' => $now,
'updated_at' => $now,
],
];
foreach ( $templates as $template ) {
$wpdb->insert(
$table_name,
$template,
[ '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ]
);
}
}
/**
* Optimize autoload settings for existing options.
*
* Moves admin-only and rarely-used options out of the autoload query.
* Uses wp_set_option_autoload_values() on WP 6.6+, direct SQL on older versions.
* Idempotent — safe to call on every activation.
*/
private static function optimize_autoload_settings(): void {
$option_names = array_map(
static function ( $key ) {
return 'aipt_' . $key;
},
self::$non_autoload_options
);
if ( empty( $option_names ) ) {
return;
}
if ( function_exists( 'wp_set_option_autoload_values' ) ) {
$autoload_map = array_fill_keys( $option_names, false );
\wp_set_option_autoload_values( $autoload_map );
return;
}
global $wpdb;
$placeholders = implode( ',', array_fill( 0, count( $option_names ), '%s' ) );
$wpdb->query(
$wpdb->prepare(
"UPDATE {$wpdb->options} SET autoload = 'no' WHERE option_name IN ({$placeholders}) AND autoload != 'no'",
$option_names
)
);
wp_cache_delete( 'alloptions', 'options' );
}
/**
* Check if an option key should be autoloaded.
*
* @param string $key Option key without aipt_ prefix.
* @return bool True if the option should be autoloaded.
*/
public static function should_autoload( string $key ): bool {
return ! in_array( $key, self::$non_autoload_options, true );
}
/**
* Seed `aipt_content_mode` with Content Template Mode, but ONLY when the
* option does not already exist, so calling this again can never
* overwrite a mode the merchant already chose in Settings.
*
* @return void
*/
private static function seed_content_mode(): void {
if ( false !== get_option( ExecutionModeRegistry::OPTION ) ) {
return;
}
add_option(
ExecutionModeRegistry::OPTION,
ExecutionModeRegistry::BLUEPRINT,
'',
true
);
}
}