prefix . $name; } /** * Core tables (without prefix). The aeoora Cloud queue table is separate: * it exists only while connected. * * @return string[] */ public static function tables() { return array( self::TABLE_HITS, self::TABLE_DAILY, self::TABLE_REFERRALS, self::TABLE_SUGGESTIONS, self::TABLE_CACHE ); } /** * Every WP-Cron hook the plugin uses (recurring and single events). * * @return string[] */ public static function cron_hooks() { return array( 'aeoora_daily', 'aeoora_prune', 'aeoora_send_report', 'aeoora_regenerate_llms', 'aeoora_suggestions_run', 'aeoora_queue', 'aeoora_warm_render', 'aeoora_score_post', 'aeoora_cloud_send', 'aeoora_llms_refresh', 'aeoora_scan_site' ); } /** * Are the tables in place (installed at least once, and verified)? * Writers check this so a site whose tables could not be created does not * log a database error on every crawler visit. * * @return bool */ public static function ready() { return false !== get_option( 'aeoora_db_version' ); } /** * Run a callback for every site of the network, for at most $budget seconds. * Sites not reached install or clean up lazily (see maybe_upgrade()). * * @param callable $callback Callback, run inside switch_to_blog(). * @param int $budget Seconds. */ private static function each_site( $callback, $budget = 20 ) { $start = microtime( true ); $offset = 0; do { $sites = get_sites( array( 'fields' => 'ids', 'number' => 100, 'offset' => $offset, ) ); foreach ( $sites as $site_id ) { switch_to_blog( $site_id ); Aeoora_Settings::flush(); call_user_func( $callback ); restore_current_blog(); if ( microtime( true ) - $start > $budget ) { break 2; } } $offset += 100; } while ( 100 === count( $sites ) ); Aeoora_Settings::flush(); } /** * Activation hook. * * @param bool $network_wide Network activation. */ public static function activate( $network_wide = false ) { if ( is_multisite() && $network_wide ) { self::each_site( array( __CLASS__, 'install' ) ); return; } self::install(); } /** * Install (or upgrade) the current site. The database version is only * recorded once every table is verified to exist, so a failed install is * retried instead of being forgotten. * * @return bool Whether the tables are in place. */ public static function install() { global $wpdb; self::create_tables(); $missing = self::missing_tables(); if ( $missing ) { update_option( 'aeoora_install_error', array( 'at' => time(), 'tables' => $missing, 'error' => (string) $wpdb->last_error, ), false ); return false; } delete_option( 'aeoora_install_error' ); self::migrate( get_option( 'aeoora_db_version' ) ); update_option( 'aeoora_db_version', AEOORA_DB_VERSION, true ); if ( false === get_option( 'aeoora_installed_at' ) ) { update_option( 'aeoora_installed_at', time(), false ); update_option( 'aeoora_show_welcome', 1, false ); } // Read on every request by the bot detector: keep it autoloaded (it is small). if ( false === get_option( 'aeoora_custom_bots' ) ) { add_option( 'aeoora_custom_bots', array(), '', true ); } elseif ( function_exists( 'wp_set_option_autoload' ) ) { wp_set_option_autoload( 'aeoora_custom_bots', true ); } self::ensure_cron(); if ( class_exists( 'Aeoora_Compat' ) ) { Aeoora_Compat::refresh_cache_config(); } // Regenerate llms.txt shortly after activation. if ( ! wp_next_scheduled( 'aeoora_regenerate_llms' ) ) { wp_schedule_single_event( time() + 30, 'aeoora_regenerate_llms' ); } // Score every page in the background (the daily job keeps new ones covered). if ( ! wp_next_scheduled( 'aeoora_scan_site' ) ) { wp_schedule_single_event( time() + 120, 'aeoora_scan_site' ); } return true; } /** * Tables that do not exist. * * @return string[] Full table names. */ private static function missing_tables() { global $wpdb; $missing = array(); foreach ( self::tables() as $t ) { $name = self::table( $t ); if ( $name !== $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $name ) ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $missing[] = $name; } } return $missing; } /** * Data migrations between database versions. * * @param string|false $from Previous version (false on a fresh install). */ private static function migrate( $from ) { global $wpdb; if ( false === $from ) { return; } if ( version_compare( (string) $from, '3', '<' ) ) { // 2 → 3: the content cache moved from files in uploads/aeoora/cache/ // to the aeoora_cache table. Remove the old folder. Aeoora_Cache::remove_file_cache(); } if ( version_compare( (string) $from, '2', '>=' ) ) { return; } // 1 → 2: Markdown, rendered-page and rate-limit caches moved out of // wp_options (into files / the object cache). Drop the old rows in batches. $start = microtime( true ); do { $deleted = (int) $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- one-time cleanup of our own rows. $wpdb->prepare( 'DELETE FROM %i WHERE option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s OR option_name LIKE %s LIMIT 5000', $wpdb->options, $wpdb->esc_like( '_transient_aeoora_md_' ) . '%', $wpdb->esc_like( '_transient_timeout_aeoora_md_' ) . '%', $wpdb->esc_like( '_transient_aeoora_r_' ) . '%', $wpdb->esc_like( '_transient_timeout_aeoora_r_' ) . '%', $wpdb->esc_like( '_transient_aeoora_rl_' ) . '%', $wpdb->esc_like( '_transient_timeout_aeoora_rl_' ) . '%' ) ); } while ( $deleted && microtime( true ) - $start < 10 ); wp_cache_delete( 'alloptions', 'options' ); } /** * Settings migrations between plugin versions. 1.2.0 removed the page * caps: values still at the old defaults (300 links in llms.txt, 100 * pages and 5 MB in llms-full.txt, 3 suggestions a day) move to the new * ones; values the owner chose stay. Admin, WP-Cron and WP-CLI only. */ public static function migrate_settings() { if ( version_compare( (string) get_option( 'aeoora_settings_version', '0' ), '1.2.0', '>=' ) ) { return; } if ( ! ( is_admin() || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) ) { return; } $llms = array(); foreach ( array( 'max_items' => 300, 'full_max_items' => 100, 'full_max_kb' => 5120, ) as $key => $old ) { if ( $old === (int) Aeoora_Settings::get( 'llms', $key, 0 ) ) { $llms[ $key ] = 0; } } $update = $llms ? array( 'llms' => $llms ) : array(); if ( 3 === (int) Aeoora_Settings::get( 'suggestions', 'per_day', 10 ) ) { $update['suggestions'] = array( 'per_day' => 10 ); } if ( $update ) { Aeoora_Settings::update( $update, false ); if ( class_exists( 'Aeoora_Llms' ) ) { Aeoora_Llms::schedule( 60 ); // Rebuild with every page. } } update_option( 'aeoora_settings_version', '1.2.0', false ); } /** * Deactivation hook. * * @param bool $network_deactivating Network deactivation. */ public static function deactivate( $network_deactivating = false ) { remove_filter( 'rocket_cache_reject_ua', array( 'Aeoora_Tracker', 'rocket_reject_ua' ) ); remove_filter( 'rocket_cache_reject_uri', array( 'Aeoora_Compat', 'rocket_reject_uri' ) ); if ( is_multisite() && $network_deactivating ) { self::each_site( array( __CLASS__, 'deactivate_site' ) ); return; } self::deactivate_site(); } /** * Stop everything scheduled on the current site and drop generated files. */ public static function deactivate_site() { // wp_unschedule_hook() also removes per-post events that carry arguments. // aeoora Cloud's sender is rescheduled on the next request after reactivation, if still connected. foreach ( self::cron_hooks() as $hook ) { wp_unschedule_hook( $hook ); } if ( class_exists( 'Aeoora_Compat' ) ) { Aeoora_Compat::refresh_cache_config(); } if ( class_exists( 'Aeoora_Llms' ) ) { Aeoora_Llms::remove_static_files(); } } /** * Upgrade on version change (also creates tables for new multisite sites * lazily). Schema work never runs in visitors' or crawlers' requests: only * in the admin, in WP-Cron and in WP-CLI, one process at a time. */ public static function maybe_upgrade() { if ( AEOORA_DB_VERSION === get_option( 'aeoora_db_version' ) ) { return; } $allowed = ( is_admin() && ! wp_doing_ajax() ) || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ); if ( ! $allowed ) { return; } $error = get_option( 'aeoora_install_error' ); if ( is_array( $error ) && isset( $error['at'] ) && time() - (int) $error['at'] < 10 * MINUTE_IN_SECONDS ) { return; // Retry a failed install every ten minutes at most. } if ( ! Aeoora_Util::lock( 'upgrade', 10 * MINUTE_IN_SECONDS ) ) { return; } try { self::install(); } finally { Aeoora_Util::unlock( 'upgrade' ); } } /** * A site was added to the network: install there when network-active. * * @param WP_Site $site Site. */ public static function initialize_site( $site ) { if ( ! function_exists( 'is_plugin_active_for_network' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } if ( ! is_object( $site ) || empty( $site->blog_id ) || ! is_plugin_active_for_network( AEOORA_BASENAME ) ) { return; } switch_to_blog( (int) $site->blog_id ); Aeoora_Settings::flush(); self::install(); restore_current_blog(); Aeoora_Settings::flush(); } /** * Drop a site's tables with it when the site is deleted. * * @param string[] $tables Table names. * @param int $site_id Site ID. * @return string[] */ public static function drop_site_tables( $tables, $site_id ) { global $wpdb; $prefix = $wpdb->get_blog_prefix( (int) $site_id ); foreach ( array_merge( self::tables(), array( 'aeoora_cloud_queue' ) ) as $t ) { $tables[] = $prefix . $t; } return $tables; } /** * Make sure the daily cron is scheduled. */ public static function ensure_cron() { if ( ! wp_next_scheduled( 'aeoora_daily' ) ) { // Run at roughly 03:15 site time. $tz = wp_timezone(); $next = new DateTime( 'tomorrow 03:15', $tz ); wp_schedule_event( $next->getTimestamp(), 'daily', 'aeoora_daily' ); } } /** * Create or update tables. */ private static function create_tables() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $charset = $wpdb->get_charset_collate(); $hits = self::table( self::TABLE_HITS ); $daily = self::table( self::TABLE_DAILY ); $referrals = self::table( self::TABLE_REFERRALS ); $suggestions = self::table( self::TABLE_SUGGESTIONS ); $cache = self::table( self::TABLE_CACHE ); dbDelta( "CREATE TABLE {$hits} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, ts datetime NOT NULL, bot varchar(64) NOT NULL, category varchar(20) NOT NULL DEFAULT '', path varchar(255) NOT NULL DEFAULT '', post_id bigint(20) unsigned NOT NULL DEFAULT 0, resource varchar(16) NOT NULL DEFAULT 'html', status smallint(5) unsigned NOT NULL DEFAULT 200, ip varchar(45) NOT NULL DEFAULT '', ua varchar(512) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY ts (ts), KEY bot_ts (bot,ts), KEY category_ts (category,ts), KEY path (path(191)) ) {$charset};" ); dbDelta( "CREATE TABLE {$daily} ( day date NOT NULL, kind varchar(8) NOT NULL, item varchar(64) NOT NULL, category varchar(20) NOT NULL DEFAULT '', hits int(10) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (day,kind,item), KEY kind_day (kind,day) ) {$charset};" ); dbDelta( "CREATE TABLE {$referrals} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, ts datetime NOT NULL, source varchar(40) NOT NULL, host varchar(191) NOT NULL DEFAULT '', utm varchar(64) NOT NULL DEFAULT '', path varchar(255) NOT NULL DEFAULT '', post_id bigint(20) unsigned NOT NULL DEFAULT 0, device varchar(10) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY ts (ts), KEY source_ts (source,ts), KEY post_id (post_id) ) {$charset};" ); dbDelta( "CREATE TABLE {$suggestions} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, post_id bigint(20) unsigned NOT NULL DEFAULT 0, type varchar(32) NOT NULL, status varchar(16) NOT NULL DEFAULT 'pending', title text NULL, current longtext NULL, suggestion longtext NULL, rationale text NULL, source varchar(64) NOT NULL DEFAULT '', created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id), KEY post_status (post_id,status), KEY status_created (status,created_at) ) {$charset};" ); dbDelta( "CREATE TABLE {$cache} ( cache_key char(32) NOT NULL, bucket varchar(20) NOT NULL DEFAULT '', value longtext NOT NULL, expires int(10) unsigned NOT NULL DEFAULT 0, PRIMARY KEY (cache_key), KEY expires (expires) ) {$charset};" ); } /** * Drop all tables (uninstall). */ public static function drop_tables() { global $wpdb; foreach ( array_merge( self::tables(), array( 'aeoora_cloud_queue' ) ) as $t ) { $name = self::table( $t ); $wpdb->query( $wpdb->prepare( 'DROP TABLE IF EXISTS %i', $name ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.DirectDatabaseQuery.SchemaChange -- our own tables, on uninstall. } } }