prefix . self::TABLE; } /** * Активация плагина. При сетевой активации обходит все сайты. * * @param bool $network_wide Активация на всю сеть. * @return void */ public static function activate( $network_wide = false ): void { if ( $network_wide && is_multisite() ) { self::for_each_site( array( __CLASS__, 'install' ) ); return; } self::install(); } /** * Деактивация: снимаем cron. Данные не трогаем. * * @param bool $network_wide Деактивация на всю сеть. * @return void */ public static function deactivate( $network_wide = false ): void { if ( $network_wide && is_multisite() ) { self::for_each_site( array( __CLASS__, 'clear_cron' ) ); return; } self::clear_cron(); } /** * Установка для одного сайта. Идемпотентна: можно звать повторно при обновлении. * * @return void */ public static function install(): void { // Settings caches the option for the request. After switch_to_blog() that cache // still holds the previous site's values, and ensure_defaults() would then write // nothing for this site (no honeypot name until the first save). Read fresh. Settings::instance()->reload(); // First install only (no schema version yet): explain once what the plugin does. if ( false === get_option( self::DB_VERSION_OPTION, false ) ) { update_option( 'agentlane_welcome', 1, false ); } self::create_table(); Settings::ensure_defaults(); self::ensure_cron(); update_option( self::DB_VERSION_OPTION, AGENTLANE_VERSION, false ); /** * После установки или обновления схемы. */ do_action( 'agentlane_installed' ); } /** * Нужно ли прогнать install() заново (версия схемы отличается). * * @return bool */ public static function needs_upgrade(): bool { return get_option( self::DB_VERSION_OPTION, '' ) !== AGENTLANE_VERSION; } /** * Создаёт или обновляет таблицу через dbDelta. * * @return void */ public static function create_table(): void { if ( ! function_exists( 'dbDelta' ) ) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } dbDelta( self::schema() ); } /** * Схема таблицы (контракт 5.10). Единственный источник: Queue::schema_sql() (WP6). * Запасная копия ниже используется только если файл очереди отсутствует; держать * её идентичной. Формат под dbDelta: поле на строке, два пробела после PRIMARY KEY. * * @return string */ public static function schema(): string { global $wpdb; $table = self::table_name(); $collate = $wpdb->get_charset_collate(); if ( class_exists( '\\AgentLane\\Queue' ) && method_exists( '\\AgentLane\\Queue', 'schema_sql' ) ) { return Queue::schema_sql( $table, $collate ); } return "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, created_at datetime NOT NULL, form_source varchar(20) NOT NULL DEFAULT '', form_id varchar(100) NOT NULL DEFAULT '', class varchar(20) NOT NULL DEFAULT 'human', score tinyint(3) unsigned NOT NULL DEFAULT 0, action varchar(10) NOT NULL DEFAULT 'allow', agent_name varchar(100) NULL DEFAULT NULL, reasons longtext NULL, fields longtext NULL, ip varchar(45) NOT NULL DEFAULT '', ua text NULL, status varchar(20) NOT NULL DEFAULT 'held', fingerprint char(64) NOT NULL DEFAULT '', PRIMARY KEY (id), KEY status_created (status,created_at), KEY class_created (class,created_at), KEY fingerprint (fingerprint) ) {$collate};"; } /** * Существует ли таблица. * * @return bool */ public static function table_exists(): bool { global $wpdb; $table = self::table_name(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- existence check for the plugin's own table. return $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) === $table; } /** * Планирует ежедневную чистку, если ещё не запланирована. * * @return void */ public static function ensure_cron(): void { if ( ! wp_next_scheduled( Plugin::CRON_HOOK ) ) { wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', Plugin::CRON_HOOK ); } } /** * Снимает cron-событие. * * @return void */ public static function clear_cron(): void { wp_clear_scheduled_hook( Plugin::CRON_HOOK ); } /** * Новый сайт в сети при сетевой активации: ставим таблицу и настройки. * * @param \WP_Site|int $new_site Сайт. * @return void */ public static function on_new_site( $new_site ): void { if ( ! is_multisite() ) { return; } if ( ! function_exists( 'is_plugin_active_for_network' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } if ( ! is_plugin_active_for_network( AGENTLANE_PLUGIN_BASENAME ) ) { return; } $site_id = is_object( $new_site ) ? (int) $new_site->blog_id : (int) $new_site; if ( $site_id < 1 ) { return; } switch_to_blog( $site_id ); self::install(); restore_current_blog(); // Back on the original site: drop the other site's cached settings. Settings::instance()->reload(); } /** * Сайт удаляют из сети: WordPress сносит только таблицы из этого списка (ядро знает * лишь свои). Добавляем таблицу очереди сайта, иначе она остаётся навсегда вместе * с IP и User-Agent посетителей, и uninstall.php её уже не найдёт (сайта нет в get_sites). * * @param string[] $tables Таблицы, которые WordPress удалит. * @param int $site_id Id удаляемого сайта. * @return string[] */ public static function drop_site_table( $tables, $site_id = 0 ): array { global $wpdb; $tables = (array) $tables; $tables[] = $wpdb->get_blog_prefix( (int) $site_id ) . self::TABLE; return array_values( array_unique( $tables ) ); } /** * Выполняет callback на каждом сайте сети. * * @param callable $callback Что выполнить. * @return void */ private static function for_each_site( callable $callback ): void { $site_ids = get_sites( array( 'fields' => 'ids', 'number' => 0, ) ); foreach ( (array) $site_ids as $site_id ) { switch_to_blog( (int) $site_id ); call_user_func( $callback ); restore_current_blog(); } // Back on the original site: drop the last site's cached settings. Settings::instance()->reload(); } }