upgrade-prompt attribution counters. Records WHICH gated * feature drove an upgrade prompt (keyed by the camelCase feature id, e.g. * "unifiedRollback"). Keys are normalized to [A-Za-z0-9_] so the store can * never accumulate PII. */ private const OPTION_ATTRIBUTION = 'aipt_usage_attribution'; public const MILESTONE_ACTIVATION = 'activation'; public const MILESTONE_FIRST_GENERATION = 'first_generation'; public const MILESTONE_FIRST_AUTOMATION = 'first_automation'; /** * Daily cron that prunes rolling monthly usage buckets * (aipt_usage_YYYY_MM) older than the retention window. Scheduled and * unscheduled through the standard Activator/Deactivator lifecycle * (mirrors HistoryCleaner / JobLogCleaner). */ public const CRON_HOOK = 'aipt_prune_usage_records'; /** * How many monthly buckets to retain (13 = a full year + the current * month, enough for YoY reads). The permanent cohort signal lives in the * never-pruned milestones option, so pruning buckets loses no cohort data. */ private const RETENTION_MONTHS = 13; /** Hard ceiling on deletions per cron tick so a backlog can't stall a request. */ private const MAX_DELETIONS_PER_TICK = 200; /** * In-request buffer of pending deltas keyed by current month. * * @var array */ private static $buffer = array(); /** * In-request ring buffer of new events to push on shutdown. * * @var array */ private static $recent_buffer = array(); /** * In-request API usage accumulator. Each `trackApiCall()` adds to this * snapshot; `record_event()` reads + resets it so every tool-event entry * carries the API cost it incurred. Zero DB calls — pure in-memory. * * Cost is stored in USD micros (USD × 1,000,000) so cheap models like * gpt-5-nano ($0.00006/call) don't round up to 1¢. * * @var array{calls:int,input_tokens:int,output_tokens:int,cost_micros:int,providers:array} */ private static $request_api_snapshot = array( 'calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, 'providers' => array(), ); /** * Whether the shutdown flush hook has already been registered. * * @var bool */ private static $shutdown_registered = false; /** * In-request cache of the milestones option (null = not yet loaded). * * @var array|null */ private static $milestones_cache = null; /** * In-request cache of the attribution option (null = not yet loaded). * * @var array|null */ private static $attribution_cache = null; /** * Increment a tool-level counter (generated / approved / rejected / applied / ...). * * Safe to call from any controller, service, or background job. * * @param string $tool Tool identifier (advanced_desc, standard_desc, title, ...). * @param string $event Event name (generated, approved, rejected, applied, messages). * @param int $count How many to add (default 1). * @return void */ public static function increment( string $tool, string $event, int $count = 1 ): void { if ( $count <= 0 || '' === $tool || '' === $event ) { return; } $month = self::current_month(); if ( ! isset( self::$buffer[ $month ] ) ) { self::$buffer[ $month ] = array( 'tools' => array(), 'api' => array() ); } if ( ! isset( self::$buffer[ $month ]['tools'][ $tool ] ) ) { self::$buffer[ $month ]['tools'][ $tool ] = array(); } if ( ! isset( self::$buffer[ $month ]['tools'][ $tool ][ $event ] ) ) { self::$buffer[ $month ]['tools'][ $tool ][ $event ] = 0; } self::$buffer[ $month ]['tools'][ $tool ][ $event ] += $count; self::register_shutdown_flush(); } /** * Record a discrete event and also push it onto the recent-events ring * buffer so it appears in the Toolkit dashboard's Recent Activity feed. * * Combines `increment()` with a buffer push so each callsite stays a * one-liner — the counter is incremented by $count (for the monthly * totals card) and a single feed entry is appended (regardless of * count, so a bulk run of 50 products is one feed row, not fifty). * * @param string $tool Tool identifier (advanced_desc, standard_desc, title, faq, seo_meta, image_alt, taxonomy, automation). * @param string $event Event name (generated, approved, rejected, applied). * @param int $count Items processed; used for the counter and the feed entry's `count` field. * @param array $context Optional. Only product_id (int) is persisted; every * other key (product_name, label, ...) is dropped so no * PII / product title can enter the feed or a support export. * @return void */ public static function record_event( string $tool, string $event, int $count = 1, array $context = array() ): void { if ( '' === $tool || '' === $event ) { return; } self::increment( $tool, $event, max( 1, $count ) ); if ( 'generated' === $event ) { self::record_milestone( self::MILESTONE_FIRST_GENERATION ); } $entry = array( 'tool' => $tool, 'event' => $event, 'count' => max( 1, $count ), 'product_id' => isset( $context['product_id'] ) ? (int) $context['product_id'] : 0, 'created_at' => gmdate( 'Y-m-d H:i:s' ), ); if ( self::$request_api_snapshot['calls'] > 0 ) { $entry['api'] = array( 'calls' => self::$request_api_snapshot['calls'], 'input_tokens' => self::$request_api_snapshot['input_tokens'], 'output_tokens' => self::$request_api_snapshot['output_tokens'], 'cost_micros' => self::$request_api_snapshot['cost_micros'], 'providers' => self::$request_api_snapshot['providers'], ); self::reset_request_api_snapshot(); } self::$recent_buffer[] = $entry; self::register_shutdown_flush(); } private static function reset_request_api_snapshot(): void { self::$request_api_snapshot = array( 'calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, 'providers' => array(), ); } /** * Return the most recent N events in reverse-chronological order. * * Reads from the persisted ring buffer and prepends any in-request * events that have not yet been flushed. * * @param int $limit Maximum number of entries to return (1..30). * @return array */ public static function get_recent_events( int $limit = 10 ): array { $limit = max( 1, min( self::RECENT_BUFFER_MAX, $limit ) ); $persisted = get_option( self::OPTION_RECENT, array() ); if ( ! is_array( $persisted ) ) { $persisted = array(); } $merged = array_merge( self::$recent_buffer, $persisted ); usort( $merged, static function ( $a, $b ) { $ta = isset( $a['created_at'] ) ? (string) $a['created_at'] : ''; $tb = isset( $b['created_at'] ) ? (string) $b['created_at'] : ''; return strcmp( $tb, $ta ); } ); return array_slice( $merged, 0, $limit ); } /** * Track a single AI provider API call. * * Pulls per-1M-token pricing from ApiPricing and accumulates token counts * plus an estimated cost (in USD cents) per provider for the current month. * * @param string $provider Provider id (openai, gemini, claude, openrouter). * @param string $model Model identifier as sent to the provider. * @param int $input_tokens Prompt/input tokens. * @param int $output_tokens Completion/output tokens. * @return void */ public static function trackApiCall( string $provider, string $model, int $input_tokens, int $output_tokens ): void { if ( '' === $provider ) { return; } $in_clamped = max( 0, $input_tokens ); $out_clamped = max( 0, $output_tokens ); $cost_micros = ApiPricing::calculate_cost_micros( $provider, $model, $in_clamped, $out_clamped ); $now = time(); $month = self::current_month( $now ); if ( ! isset( self::$buffer[ $month ] ) ) { self::$buffer[ $month ] = array( 'tools' => array(), 'api' => array() ); } if ( ! isset( self::$buffer[ $month ]['api'][ $provider ] ) ) { self::$buffer[ $month ]['api'][ $provider ] = array( 'calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, ); } $bucket = &self::$buffer[ $month ]['api'][ $provider ]; $bucket['calls'] += 1; $bucket['input_tokens'] += $in_clamped; $bucket['output_tokens'] += $out_clamped; $bucket['cost_micros'] += $cost_micros; unset( $bucket ); $day = gmdate( 'd', $now ); if ( ! isset( self::$buffer[ $month ]['days'] ) || ! is_array( self::$buffer[ $month ]['days'] ) ) { self::$buffer[ $month ]['days'] = array(); } if ( ! isset( self::$buffer[ $month ]['days'][ $day ] ) || ! is_array( self::$buffer[ $month ]['days'][ $day ] ) ) { self::$buffer[ $month ]['days'][ $day ] = array( 'api' => array() ); } if ( ! isset( self::$buffer[ $month ]['days'][ $day ]['api'] ) || ! is_array( self::$buffer[ $month ]['days'][ $day ]['api'] ) ) { self::$buffer[ $month ]['days'][ $day ]['api'] = array(); } if ( ! isset( self::$buffer[ $month ]['days'][ $day ]['api'][ $provider ] ) ) { self::$buffer[ $month ]['days'][ $day ]['api'][ $provider ] = array( 'calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, ); } $day_bucket = &self::$buffer[ $month ]['days'][ $day ]['api'][ $provider ]; $day_bucket['calls'] += 1; $day_bucket['input_tokens'] += $in_clamped; $day_bucket['output_tokens'] += $out_clamped; $day_bucket['cost_micros'] += $cost_micros; unset( $day_bucket ); self::$request_api_snapshot['calls'] += 1; self::$request_api_snapshot['input_tokens'] += $in_clamped; self::$request_api_snapshot['output_tokens'] += $out_clamped; self::$request_api_snapshot['cost_micros'] += $cost_micros; if ( ! isset( self::$request_api_snapshot['providers'][ $provider ] ) ) { self::$request_api_snapshot['providers'][ $provider ] = 0; } self::$request_api_snapshot['providers'][ $provider ] += 1; self::register_shutdown_flush(); } /** * Get usage payload for the current month (merged buffer + persisted). * * @return array */ public static function get_current_month(): array { return self::get_month( self::current_month() ); } /** * Get API usage for a supported rolling period. * * Month and invalid periods preserve the existing current-month payload. * Day and week use UTC daily buckets; year uses the existing monthly totals. * * @param string $period Period identifier (day, week, month, year). * @return array */ public static function get_range( string $period ): array { if ( ! in_array( $period, array( 'day', 'week', 'year' ), true ) ) { return self::get_current_month(); } if ( 'day' === $period ) { $now = time(); $current = self::get_month( self::current_month( $now ) ); $day = gmdate( 'd', $now ); $day_data = isset( $current['days'][ $day ] ) && is_array( $current['days'][ $day ] ) ? $current['days'][ $day ] : array(); $api = isset( $day_data['api'] ) && is_array( $day_data['api'] ) ? $day_data['api'] : array(); return self::build_api_usage( $api ); } $api = array(); if ( 'week' === $period ) { $now = time(); $year = (int) gmdate( 'Y', $now ); $month = (int) gmdate( 'n', $now ); $day = (int) gmdate( 'j', $now ); $months = array(); for ( $offset = 0; $offset < 7; $offset++ ) { $timestamp = gmmktime( 0, 0, 0, $month, $day - $offset, $year ); $month_key = gmdate( 'Y_m', $timestamp ); $day_key = gmdate( 'd', $timestamp ); if ( ! isset( $months[ $month_key ] ) ) { $months[ $month_key ] = self::get_month( $month_key ); } $day_data = isset( $months[ $month_key ]['days'][ $day_key ] ) && is_array( $months[ $month_key ]['days'][ $day_key ] ) ? $months[ $month_key ]['days'][ $day_key ] : array(); $day_api = isset( $day_data['api'] ) && is_array( $day_data['api'] ) ? $day_data['api'] : array(); $api = self::merge_api_buckets( $api, $day_api ); } return self::build_api_usage( $api ); } $now = time(); $current_month_index = ( (int) gmdate( 'Y', $now ) * 12 ) + ( (int) gmdate( 'n', $now ) - 1 ); for ( $offset = 0; $offset < 12; $offset++ ) { $month_index = $current_month_index - $offset; $month_key = sprintf( '%04d_%02d', intdiv( $month_index, 12 ), ( $month_index % 12 ) + 1 ); $month_usage = self::get_month( $month_key ); $month_api = isset( $month_usage['api'] ) && is_array( $month_usage['api'] ) ? $month_usage['api'] : array(); $api = self::merge_api_buckets( $api, $month_api ); } return self::build_api_usage( $api ); } /** * Get usage payload for a specific month key (YYYY_MM). * * @param string $month_key Month key, e.g. "2026_05". * @return array */ public static function get_month( string $month_key ): array { $persisted = get_option( self::OPTION_PREFIX . $month_key, array() ); if ( ! is_array( $persisted ) ) { $persisted = array(); } $persisted = self::ensure_shape( $persisted ); if ( ! empty( self::$buffer[ $month_key ] ) ) { $persisted = self::merge( $persisted, self::$buffer[ $month_key ] ); } $persisted['totals'] = self::compute_totals( $persisted ); return $persisted; } /** * Flush the in-request buffer to wp_options. Registered as a shutdown * callback the first time anything is tracked. * * @internal * @return void */ public static function flush(): void { if ( ! empty( self::$buffer ) ) { foreach ( self::$buffer as $month_key => $delta ) { $option_key = self::OPTION_PREFIX . $month_key; $current = get_option( $option_key, array() ); if ( ! is_array( $current ) ) { $current = array(); } $current = self::ensure_shape( $current ); $merged = self::merge( $current, $delta ); update_option( $option_key, $merged, false ); } self::$buffer = array(); } if ( ! empty( self::$recent_buffer ) ) { $persisted = get_option( self::OPTION_RECENT, array() ); if ( ! is_array( $persisted ) ) { $persisted = array(); } $merged = array_merge( self::$recent_buffer, $persisted ); if ( count( $merged ) > self::RECENT_BUFFER_MAX ) { $merged = array_slice( $merged, 0, self::RECENT_BUFFER_MAX ); } update_option( self::OPTION_RECENT, $merged, false ); self::$recent_buffer = array(); } } /** * Return current YYYY_MM key in site timezone-agnostic UTC. * * @return string */ private static function current_month( ?int $now = null ): string { $now = $now ?? time(); return gmdate( 'Y_m', $now ); } private static function register_shutdown_flush(): void { if ( self::$shutdown_registered ) { return; } self::$shutdown_registered = true; if ( function_exists( 'add_action' ) ) { add_action( 'shutdown', array( __CLASS__, 'flush' ), 99 ); } } private static function ensure_shape( array $data ): array { if ( ! isset( $data['tools'] ) || ! is_array( $data['tools'] ) ) { $data['tools'] = array(); } if ( ! isset( $data['api'] ) || ! is_array( $data['api'] ) ) { $data['api'] = array(); } if ( ! isset( $data['days'] ) || ! is_array( $data['days'] ) ) { $data['days'] = array(); } return $data; } /** * Merge per-provider API usage buckets by summing known counters. * * @param array $base Existing provider buckets. * @param array $delta Provider counter increments. * @return array */ private static function merge_api_buckets( array $base, array $delta ): array { foreach ( $delta as $provider => $bucket ) { if ( ! is_array( $bucket ) ) { continue; } if ( ! isset( $base[ $provider ] ) || ! is_array( $base[ $provider ] ) ) { $base[ $provider ] = array( 'calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, ); } foreach ( array( 'calls', 'input_tokens', 'output_tokens', 'cost_micros' ) as $field ) { if ( isset( $bucket[ $field ] ) ) { $base[ $provider ][ $field ] = (int) ( $base[ $provider ][ $field ] ?? 0 ) + (int) $bucket[ $field ]; } } } return $base; } /** * Build a normalized usage payload from API provider buckets. * * @param array $api Provider usage buckets. * @return array */ private static function build_api_usage( array $api ): array { $usage = self::ensure_shape( array( 'api' => $api ) ); $usage['totals'] = self::compute_totals( $usage ); return $usage; } /** * Deep-merge two usage payloads by summing numeric leaves. * * @param array $base Existing persisted snapshot. * @param array $delta Pending increments. * @return array */ private static function merge( array $base, array $delta ): array { $base = self::ensure_shape( $base ); $delta = self::ensure_shape( $delta ); foreach ( $delta['tools'] as $tool => $events ) { if ( ! is_array( $events ) ) { continue; } if ( ! isset( $base['tools'][ $tool ] ) || ! is_array( $base['tools'][ $tool ] ) ) { $base['tools'][ $tool ] = array(); } foreach ( $events as $event => $count ) { $prev = isset( $base['tools'][ $tool ][ $event ] ) ? (int) $base['tools'][ $tool ][ $event ] : 0; $base['tools'][ $tool ][ $event ] = $prev + (int) $count; } } $base['api'] = self::merge_api_buckets( $base['api'], $delta['api'] ); foreach ( $delta['days'] as $day => $day_data ) { if ( ! is_array( $day_data ) ) { continue; } if ( ! isset( $base['days'][ $day ] ) || ! is_array( $base['days'][ $day ] ) ) { $base['days'][ $day ] = array(); } $base_day_api = isset( $base['days'][ $day ]['api'] ) && is_array( $base['days'][ $day ]['api'] ) ? $base['days'][ $day ]['api'] : array(); $delta_day_api = isset( $day_data['api'] ) && is_array( $day_data['api'] ) ? $day_data['api'] : array(); $base['days'][ $day ]['api'] = self::merge_api_buckets( $base_day_api, $delta_day_api ); } return $base; } /** * Compute aggregate totals across all tools/providers. * * @param array $data Usage payload. * @return array */ private static function compute_totals( array $data ): array { $totals = array( 'generated' => 0, 'approved' => 0, 'rejected' => 0, 'applied' => 0, 'api_calls' => 0, 'input_tokens' => 0, 'output_tokens' => 0, 'cost_micros' => 0, ); foreach ( $data['tools'] as $events ) { if ( ! is_array( $events ) ) { continue; } foreach ( array( 'generated', 'approved', 'rejected', 'applied' ) as $k ) { if ( isset( $events[ $k ] ) ) { $totals[ $k ] += (int) $events[ $k ]; } } } foreach ( $data['api'] as $bucket ) { if ( ! is_array( $bucket ) ) { continue; } $totals['api_calls'] += (int) ( $bucket['calls'] ?? 0 ); $totals['input_tokens'] += (int) ( $bucket['input_tokens'] ?? 0 ); $totals['output_tokens'] += (int) ( $bucket['output_tokens'] ?? 0 ); $totals['cost_micros'] += (int) ( $bucket['cost_micros'] ?? 0 ); } return $totals; } /** * Record a one-time lifecycle milestone with first-touch semantics. * * Used for the activation / first-generation / first-automation cohort * markers. Stores ONLY a UTC timestamp plus, for activation, the plugin * version (so pre-credit / post-credit / post-pivot cohorts stay * separable). Any other context key is dropped — no PII, no product data * can ever land here. Once a milestone is set it is never overwritten. * * @param string $milestone Milestone id (see MILESTONE_* constants). * @param array $context Optional. Only a 'version' string is honored. * @return void */ public static function record_milestone( string $milestone, array $context = array() ): void { $milestone = self::normalize_token( $milestone ); if ( '' === $milestone ) { return; } if ( isset( self::load_milestones()[ $milestone ] ) ) { return; } $locked = self::acquire_usage_lock( self::OPTION_MILESTONES ); if ( ! $locked ) { return; } try { $milestones = get_option( self::OPTION_MILESTONES, array() ); $milestones = is_array( $milestones ) ? $milestones : array(); self::$milestones_cache = $milestones; if ( isset( $milestones[ $milestone ] ) ) { return; } $entry = array( 'at' => gmdate( 'Y-m-d H:i:s' ) ); if ( isset( $context['version'] ) && is_scalar( $context['version'] ) ) { $version = preg_replace( '/[^A-Za-z0-9._-]/', '', (string) $context['version'] ); if ( is_string( $version ) && '' !== $version ) { $entry['version'] = substr( $version, 0, 32 ); } } $milestones[ $milestone ] = $entry; self::$milestones_cache = $milestones; update_option( self::OPTION_MILESTONES, $milestones, false ); } finally { if ( $locked ) { self::release_usage_lock( self::OPTION_MILESTONES ); } } } /** * Record which gated feature triggered an upgrade prompt (attribution). * * Increments a per-feature counter keyed by the camelCase feature id * (e.g. "unifiedRollback"). The key is normalized to [A-Za-z0-9_] so the * store can never accumulate PII. This is the measurement primitive that * makes feature -> upgrade attribution readable; surfaces fire it via the * `aipt_upgrade_prompt_shown` action so callers stay decoupled (G4). * * @param string $feature Feature id that prompted the upgrade. * @return void */ public static function record_upgrade_trigger( string $feature ): void { $feature = self::normalize_token( $feature ); if ( '' === $feature ) { return; } $locked = self::acquire_usage_lock( self::OPTION_ATTRIBUTION ); if ( ! $locked ) { return; } try { $data = get_option( self::OPTION_ATTRIBUTION, array() ); $data = is_array( $data ) ? $data : array(); self::$attribution_cache = $data; if ( ! isset( $data[ $feature ] ) || ! is_array( $data[ $feature ] ) ) { $data[ $feature ] = array( 'count' => 0, 'first_seen' => gmdate( 'Y-m-d H:i:s' ), 'last_seen' => '', ); } $data[ $feature ]['count'] = (int) $data[ $feature ]['count'] + 1; $data[ $feature ]['last_seen'] = gmdate( 'Y-m-d H:i:s' ); self::$attribution_cache = $data; update_option( self::OPTION_ATTRIBUTION, $data, false ); } finally { if ( $locked ) { self::release_usage_lock( self::OPTION_ATTRIBUTION ); } } } /** * WordPress-action adapter for `aipt_upgrade_prompt_shown` — lets any * surface (frontend upgrade modal, onboarding nudge, backend gate) record * attribution with `do_action( 'aipt_upgrade_prompt_shown', $feature )` * without a hard dependency on this class. * * @param mixed $feature Feature id passed by the action. * @return void */ public static function on_upgrade_prompt_shown( $feature = '' ): void { if ( ! is_string( $feature ) || '' === $feature ) { return; } self::record_upgrade_trigger( $feature ); } /** * Read the persisted lifecycle milestones (merged with any in-request write). * * @return array */ public static function get_milestones(): array { return self::load_milestones(); } /** * Read the persisted feature -> upgrade attribution counters. * * @return array */ public static function get_attribution(): array { return self::load_attribution(); } /** * Cron callback: prune stale monthly usage buckets. Fail-safe — a pruning * error must never surface to the admin or break the request. * * @internal * @return void */ public static function cron_callback(): void { try { self::prune(); } catch ( \Throwable $e ) { } } /** * Delete rolling monthly buckets (aipt_usage_YYYY_MM) older than the * retention window. Only the strict `aipt_usage_<4digit>_<2digit>` pattern * is eligible, so the named keys (recent / milestones / attribution / * legacy summary) and the current-window months are left untouched. * Deletions are capped per tick. * * @param int|null $now Optional Unix timestamp for "now" (defaults to time()). * Injectable so the retention boundary is testable on a * fixed calendar day. * @return int Number of buckets deleted. */ public static function prune( ?int $now = null ): int { global $wpdb; if ( ! isset( $wpdb ) || ! is_object( $wpdb ) ) { return 0; } $cutoff = self::retentionCutoff( $now ); $like = $wpdb->esc_like( self::OPTION_PREFIX ) . '%'; $names = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) ); if ( empty( $names ) || ! is_array( $names ) ) { return 0; } $deleted = 0; foreach ( $names as $name ) { if ( $deleted >= self::MAX_DELETIONS_PER_TICK ) { break; } if ( ! preg_match( '/^aipt_usage_(\d{4})_(\d{2})$/', (string) $name, $m ) ) { continue; } $key_month = $m[1] . '_' . $m[2]; if ( strcmp( $key_month, $cutoff ) <= 0 ) { delete_option( (string) $name ); ++$deleted; } } return $deleted; } /** * Compute the retention cutoff month key (YYYY_MM), inclusive lower bound. * * Anchors on the CURRENT calendar month and subtracts RETENTION_MONTHS with * integer month-index arithmetic. `strtotime('-13 months')` is NOT used: on * days 29-31 it overflows the shorter target month (e.g. 2026-03-31 minus 13 * months resolves to 2025-03-03, not 2025-02-xx), which — with the `<=` prune * that deletes the cutoff month — would remove one bucket too many and leave * only 12 months instead of the documented 13. Month-index math never * overflows and, reading UTC parts via gmdate(), is timezone-safe. * * @param int|null $now Optional Unix timestamp for "now" (defaults to time()). * @return string Cutoff month key "YYYY_MM"; buckets `<=` this are pruned. */ private static function retentionCutoff( ?int $now = null ): string { $now = ( null === $now ) ? time() : $now; $year = (int) gmdate( 'Y', $now ); $month = (int) gmdate( 'n', $now ); $index = ( $year * 12 ) + ( $month - 1 ) - self::RETENTION_MONTHS; return sprintf( '%04d_%02d', intdiv( $index, 12 ), ( $index % 12 ) + 1 ); } /** * Schedule the daily prune cron (Activator lifecycle — HistoryCleaner pattern). * * @return void */ public static function schedule(): void { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_schedule_event' ) ) { return; } if ( ! \wp_next_scheduled( self::CRON_HOOK ) ) { \wp_schedule_event( time() + 300, 'daily', self::CRON_HOOK ); } } /** * Unschedule the daily prune cron (Deactivator lifecycle). * * @return void */ public static function unschedule(): void { if ( ! function_exists( 'wp_next_scheduled' ) || ! function_exists( 'wp_unschedule_event' ) ) { return; } $timestamp = \wp_next_scheduled( self::CRON_HOOK ); if ( $timestamp ) { \wp_unschedule_event( $timestamp, self::CRON_HOOK ); } } /** * Load + cache the milestones option for this request. * * @return array */ private static function load_milestones(): array { if ( null === self::$milestones_cache ) { $stored = get_option( self::OPTION_MILESTONES, array() ); self::$milestones_cache = is_array( $stored ) ? $stored : array(); } return self::$milestones_cache; } /** * Acquire a transient-based lock for serialising read-modify-write * operations on a usage option. The lock TTL is short (10s) to prevent * deadlocks — a mid-request crash will auto-expire the transient and * the next request will proceed. In the (extremely unlikely) event of a * concurrent race, the worst-case impact is a counter off by one or a * timestamp differing by seconds — acceptable for best-effort telemetry. * * @param string $option_name Option name to lock. * @return bool True when the lock was acquired successfully. */ private static function acquire_usage_lock( string $option_name ): bool { $lock_key = 'aipt_usage_lock_' . md5( $option_name ); if ( get_transient( $lock_key ) ) { return false; } return set_transient( $lock_key, true, 10 ); } /** * Release a transient-based usage lock. * * @param string $option_name Option name to unlock. * @return void */ private static function release_usage_lock( string $option_name ): void { $lock_key = 'aipt_usage_lock_' . md5( $option_name ); delete_transient( $lock_key ); } /** * Load + cache the attribution option for this request. * * @return array */ private static function load_attribution(): array { if ( null === self::$attribution_cache ) { $stored = get_option( self::OPTION_ATTRIBUTION, array() ); self::$attribution_cache = is_array( $stored ) ? $stored : array(); } return self::$attribution_cache; } /** * Normalize a milestone / feature token to a safe [A-Za-z0-9_] charset, * capped at 64 chars. Guarantees no PII can enter a milestone name or an * attribution key by construction. * * @param string $token Raw token. * @return string Normalized token ('' if nothing survives). */ private static function normalize_token( string $token ): string { $token = preg_replace( '/[^A-Za-z0-9_]/', '', $token ); if ( ! is_string( $token ) ) { return ''; } return substr( $token, 0, 64 ); } }