prefix . 'aieo_search_demand_daily'; } public static function ensure_table() { global $wpdb; if (!AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION)) { return; } $table = self::table(); $charset_collate = aieo_get_charset_collate(); $wpdb->query("CREATE TABLE IF NOT EXISTS {$table} ( `day` date NOT NULL, `provider` varchar(16) NOT NULL, `phrase_raw` varchar(255) NOT NULL DEFAULT '', `phrase_norm` varchar(255) COLLATE utf8mb4_bin NOT NULL, `term_stem_key` varchar(255) DEFAULT NULL, `searches` int unsigned NOT NULL DEFAULT 0, `zero_results` int unsigned NOT NULL DEFAULT 0, PRIMARY KEY (`day`, `provider`, `phrase_norm`), KEY `day` (`day`) ) {$charset_collate}"); if (!class_exists('AIEO_Analytics_Collation')) { require_once __DIR__ . '/sql/class-aieo-analytics-collation.php'; } AIEO_Analytics_Collation::ensure_binary_columns($table, array('phrase_norm' => 'varchar(255) COLLATE utf8mb4_bin NOT NULL')); update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION, false); } private static function maybe_ensure() { if (self::$ensured) { return; } self::$ensured = true; if (get_option(self::SCHEMA_OPTION) !== self::SCHEMA_VERSION) { self::ensure_table(); } } public static function bootstrap() { add_action('template_redirect', array(__CLASS__, 'capture_core_search'), 9); if (function_exists('DGWT_WCAS') && null !== DGWT_WCAS()) { add_action('dgwt/wcas/analytics/after_searching', array(__CLASS__, 'fibosearch_listener'), 20, 3); } add_action('admin_init', array(__CLASS__, 'admin_maintenance'), 30); add_filter('rooster/search/popular', array(__CLASS__, 'answer_popular'), 10, 2); } public static function admin_maintenance() { $cap = defined('AIEO_CAPABILITY') ? AIEO_CAPABILITY : 'manage_options'; if (!current_user_can($cap)) { return; } self::maybe_ensure(); self::maybe_install_shim(); self::backfill_from_fibosearch(); } public static function capture_core_search() { if (is_admin() || !is_search()) { return; } if (is_paged() || isset($_GET['rooster_part'])) { return; } if (did_action('dgwt/wcas/analytics/after_searching')) { return; } $phrase = (string) get_search_query(false); if ('' === trim($phrase)) { return; } global $wp_query; $found = ($wp_query instanceof WP_Query) ? (int) $wp_query->found_posts : 0; self::record('core', $phrase, $found); } public static function fibosearch_listener($phrase, $hits = 0, $lang = '') { if (defined('AIEO_SEARCH_SIGNAL_SHIM')) { return; } $raw = ''; if (isset($_GET['s'])) { $raw = sanitize_text_field(wp_unslash((string) $_GET['s'])); } elseif (isset($_REQUEST['s'])) { $raw = sanitize_text_field(wp_unslash((string) $_REQUEST['s'])); } if ('' === trim($raw)) { $raw = (string) $phrase; } self::record('fibosearch', $raw, (int) $hits); } public static function normalize_phrase($phrase) { $phrase = (string) $phrase; if (class_exists('AIEO_Semantic_Normalizer')) { if (method_exists('AIEO_Semantic_Normalizer', 'normalize_text')) { return AIEO_Semantic_Normalizer::normalize_text($phrase); } return AIEO_Semantic_Normalizer::normalize($phrase); } return trim(mb_strtolower($phrase, 'UTF-8')); } private static function allowed($provider, $phrase_raw) { $default = true; if (class_exists('AIEO_Session_Tracker') && method_exists('AIEO_Session_Tracker', 'is_consent_blocking_writes')) { $default = !AIEO_Session_Tracker::is_consent_blocking_writes(); } return (bool) apply_filters('aieo_search_signal_allowed', $default, $provider, $phrase_raw); } public static function record($provider, $phrase_raw, $hits) { global $wpdb; $phrase_raw = trim((string) $phrase_raw); if ('' === $phrase_raw) { return false; } $phrase_raw = mb_substr($phrase_raw, 0, 255); $norm = mb_substr(self::normalize_phrase($phrase_raw), 0, 255); if ('' === $norm) { return false; } if (!self::allowed($provider, $phrase_raw)) { return false; } if (class_exists('AIEO_Speculative') && AIEO_Speculative::request()) { return false; } self::maybe_ensure(); $table = self::table(); $zero = (0 === (int) $hits) ? 1 : 0; $done = $wpdb->query($wpdb->prepare( "INSERT INTO {$table} (`day`, `provider`, `phrase_raw`, `phrase_norm`, `searches`, `zero_results`) VALUES (%s, %s, %s, %s, 1, %d) ON DUPLICATE KEY UPDATE `searches` = `searches` + 1, `zero_results` = `zero_results` + VALUES(`zero_results`)", gmdate('Y-m-d'), substr((string) $provider, 0, 16), $phrase_raw, $norm, $zero )); return false !== $done; } const POPULAR_CACHE = 'aieo_search_popular_'; public static function popular($limit = 5, $days = 90) { global $wpdb; $limit = max(1, min(20, (int) $limit)); $days = max(1, min(365, (int) $days)); $key = self::POPULAR_CACHE . $limit . '_' . $days; $hit = get_transient($key); if (is_array($hit)) { return $hit; } $phrases = array(); if (get_option(self::SCHEMA_OPTION)) { $table = self::table(); $min = max(1, (int) apply_filters('aieo_search_popular_min', 3)); $rows = $wpdb->get_results($wpdb->prepare( "SELECT SUBSTRING_INDEX(GROUP_CONCAT(`phrase_raw` ORDER BY `searches` DESC, `day` DESC SEPARATOR '\n'), '\n', 1) AS phrase, SUM(`searches`) AS searched, SUM(`zero_results`) AS failed FROM {$table} WHERE `day` >= %s GROUP BY `phrase_norm` HAVING searched > failed AND searched >= %d ORDER BY searched DESC, `phrase_norm` ASC LIMIT %d", gmdate('Y-m-d', time() - $days * DAY_IN_SECONDS), $min, $limit * 3 ), ARRAY_A); foreach ((array) $rows as $row) { $phrase = trim(wp_strip_all_tags((string) ($row['phrase'] ?? ''))); if ('' === $phrase || mb_strlen($phrase, 'UTF-8') > 40 || preg_match('~@|://|www\.|\d{6,}~i', $phrase)) { continue; } $phrases[] = $phrase; if (count($phrases) >= $limit) { break; } } } $phrases = array_values(array_filter(array_map('strval', (array) apply_filters('aieo_search_popular', $phrases, $limit, $days)), 'strlen')); set_transient($key, $phrases, 12 * HOUR_IN_SECONDS); return $phrases; } public static function answer_popular($phrases, $limit = 5) { $phrases = (array) $phrases; return array() !== $phrases ? $phrases : self::popular(max(1, (int) $limit)); } public static function info() { $detected = function_exists('DGWT_WCAS') && null !== DGWT_WCAS(); $info = array( 'detected' => $detected, 'edition' => '', 'version' => defined('DGWT_WCAS_VERSION') ? (string) DGWT_WCAS_VERSION : '', 'endpoint_mode' => '', 'analytics_enabled' => false, 'shim_state' => (string) get_option(self::SHIM_STATE_OPT, ''), 'backfilled' => (bool) get_option(self::BACKFILL_OPTION), ); if (!$detected) { return $info; } $info['edition'] = defined('DGWT_WCAS_SEARCH_PRO_ACTION') ? 'pro' : 'free'; try { $info['endpoint_mode'] = (string) DGWT_WCAS()->getInfo('search_endpoint'); } catch (\Throwable $e) { $info['endpoint_mode'] = ''; } $settings = get_option('dgwt_wcas_settings', array()); $info['analytics_enabled'] = is_array($settings) && isset($settings['analytics_enabled']) && 'on' === $settings['analytics_enabled']; return $info; } public static function maybe_install_shim() { $info = self::info(); if (!$info['detected']) { return; } $needed = ('pro' === $info['edition']) && false !== strpos($info['endpoint_mode'], 'Endpoints/search.php'); $target = trailingslashit(WP_CONTENT_DIR) . 'fibosearch.php'; $state = (string) get_option(self::SHIM_STATE_OPT, ''); if (!$needed) { if ('' === $state || 'installed' === $state) { update_option(self::SHIM_STATE_OPT, file_exists($target) ? 'installed' : 'not_needed', false); } return; } $candidates = array('fibosearch.php', 'asfw-filters.php', 'ajax-search-for-woocommerce.php', 'ajax-search-filters.php'); foreach ($candidates as $file) { $path = trailingslashit(WP_CONTENT_DIR) . $file; if (!file_exists($path)) { continue; } $head = (string) file_get_contents($path, false, null, 0, 8192); if (false !== strpos($head, self::SHIM_MARKER)) { update_option(self::SHIM_STATE_OPT, 'installed', false); return; } update_option(self::SHIM_STATE_OPT, 'foreign', false); return; } $source = AIEO_DIR . 'includes/data/fibosearch-shim.php'; if (!file_exists($source)) { update_option(self::SHIM_STATE_OPT, 'source_missing', false); return; } $copied = @copy($source, $target); update_option(self::SHIM_STATE_OPT, $copied ? 'installed' : 'copy_failed', false); } public static function backfill_from_fibosearch() { global $wpdb; if (get_option(self::BACKFILL_OPTION)) { return; } if (!function_exists('DGWT_WCAS') || null === DGWT_WCAS()) { return; } $stats = $wpdb->prefix . 'dgwt_wcas_stats'; if (class_exists('\\DgoraWcas\\Analytics\\Database') && method_exists('\\DgoraWcas\\Analytics\\Database', 'getTableName')) { $stats = (string) \DgoraWcas\Analytics\Database::getTableName(); } if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $stats)) !== $stats) { update_option(self::BACKFILL_OPTION, gmdate('Y-m-d H:i:s'), false); return; } self::maybe_ensure(); $rows = $wpdb->get_results( "SELECT DATE(created_at) AS d, phrase, COUNT(*) AS c, SUM(hits = 0) AS z FROM {$stats} WHERE DATE(created_at) < UTC_DATE() GROUP BY DATE(created_at), phrase LIMIT 20000" ); $table = self::table(); foreach ((array) $rows as $r) { $raw = mb_substr(trim((string) $r->phrase), 0, 255); if ('' === $raw) { continue; } $norm = mb_substr(self::normalize_phrase($raw), 0, 255); if ('' === $norm) { continue; } $wpdb->query($wpdb->prepare( "INSERT INTO {$table} (`day`, `provider`, `phrase_raw`, `phrase_norm`, `searches`, `zero_results`) VALUES (%s, 'fibosearch', %s, %s, %d, %d) ON DUPLICATE KEY UPDATE `searches` = `searches` + VALUES(`searches`), `zero_results` = `zero_results` + VALUES(`zero_results`)", (string) $r->d, $raw, $norm, (int) $r->c, (int) $r->z )); } update_option(self::BACKFILL_OPTION, gmdate('Y-m-d H:i:s'), false); } }