wp_generate_uuid4(), 'expires_at' => time() + 120 ); if ( self::insert( $key, $record ) ) { return array( 'key' => $key, 'record' => $record ); } global $wpdb; $raw = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $key ) ); $previous = null === $raw ? null : maybe_unserialize( $raw ); if ( ! is_array( $previous ) || empty( $previous['owner'] ) || ! isset( $previous['expires_at'] ) || ! is_int( $previous['expires_at'] ) || $previous['expires_at'] > time() + 120 || $previous['expires_at'] <= time() ) { self::release( array( 'key' => $key, 'record' => $previous ) ); if ( self::insert( $key, $record ) ) { return array( 'key' => $key, 'record' => $record ); } } return null; } /** add_option uses an upsert after a cache check and cannot arbitrate overlapping owners. */ private static function insert( $key, $record ) { global $wpdb; $inserted = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $key, maybe_serialize( $record ) ) ); wp_cache_delete( $key, 'options' ); return 1 === $inserted; } /** Renew only the current unexpired owner before derived effects/cache publication. */ public static function renew( &$claim ) { global $wpdb; if ( $claim['record']['expires_at'] <= time() ) { return false; } $next = $claim['record']; $next['expires_at'] = time() + 120; if ( $next === $claim['record'] ) { return maybe_serialize( $claim['record'] ) === $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $claim['key'] ) ); } $updated = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", maybe_serialize( $next ), $claim['key'], maybe_serialize( $claim['record'] ) ) ); wp_cache_delete( $claim['key'], 'options' ); if ( 1 !== $updated ) { return false; } $claim['record'] = $next; return true; } public static function release( $claim ) { global $wpdb; $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", $claim['key'], maybe_serialize( $claim['record'] ) ) ); wp_cache_delete( $claim['key'], 'options' ); } public static function deactivate() { global $wpdb; $keys = $wpdb->get_col( $wpdb->prepare( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( 'affiai_refresh_v1_' ) . '%' ) ); foreach ( $keys as $key ) { $wpdb->delete( $wpdb->options, array( 'option_name' => $key ) ); wp_cache_delete( $key, 'options' ); } } }