0 ? $parent_id : $product_id; self::invalidate_target($effective_id); if (class_exists('AIEO_Recompute_Queue')) { AIEO_Recompute_Queue::enqueue(AIEO_Recompute_Queue::SURFACE_RECOS, $effective_id, ''); } } public static function on_post_status_change($new_status, $old_status, $post) { if (!is_object($post) || !isset($post->post_type) || $post->post_type !== 'product') { return; } if ($new_status === $old_status) { return; } if ($old_status === 'publish' && $new_status !== 'publish') { self::invalidate_target((int) $post->ID); } elseif ($new_status === 'publish' && $old_status !== 'publish') { if (class_exists('AIEO_Recompute_Queue')) { AIEO_Recompute_Queue::enqueue(AIEO_Recompute_Queue::SURFACE_RECOS, (int) $post->ID, ''); } } } public static function on_before_delete($post_id) { $post_id = (int) $post_id; if ($post_id <= 0 || !self::table_exists()) { return; } $post = get_post($post_id); if (!$post || $post->post_type !== 'product') { return; } global $wpdb; $table = self::table_name(); $wpdb->query($wpdb->prepare( "DELETE FROM {$table} WHERE source_product_id = %d OR target_product_id = %d", $post_id, $post_id )); } public static function is_enabled() { return (bool) get_option('aieo_use_effective_recos', 0); } public static function get_top($source_product_id, $surface, $audience_key, $limit = 10) { global $wpdb; $source_product_id = (int) $source_product_id; $limit = max(1, (int) $limit); if ($source_product_id <= 0 || !in_array($surface, self::VALID_SURFACES, true)) { return array(); } if (!self::table_exists()) { return array(); } $table = self::table_name(); $rows = $wpdb->get_col($wpdb->prepare( "SELECT target_product_id FROM {$table} WHERE source_product_id = %d AND surface = %s AND audience_key = %s ORDER BY `rank` ASC LIMIT %d", $source_product_id, $surface, $audience_key, $limit )); if (empty($rows) && $audience_key !== 'guest') { $rows = $wpdb->get_col($wpdb->prepare( "SELECT target_product_id FROM {$table} WHERE source_product_id = %d AND surface = %s AND audience_key = 'guest' ORDER BY `rank` ASC LIMIT %d", $source_product_id, $surface, $limit )); } return is_array($rows) ? array_map('intval', $rows) : array(); } public static function get_top_full($source_product_id, $surface, $audience_key, $limit = 10) { global $wpdb; $source_product_id = (int) $source_product_id; $limit = max(1, (int) $limit); if ($source_product_id <= 0 || !in_array($surface, self::VALID_SURFACES, true)) { return array(); } if (!self::table_exists()) { return array(); } $table = self::table_name(); return (array) $wpdb->get_results($wpdb->prepare( "SELECT target_product_id, score, reason_code FROM {$table} WHERE source_product_id = %d AND surface = %s AND audience_key = %s ORDER BY `rank` ASC LIMIT %d", $source_product_id, $surface, $audience_key, $limit ), ARRAY_A); } public static function recompute($source_product_id, $audience_key) { global $wpdb; $source_product_id = (int) $source_product_id; if ($source_product_id <= 0 || !is_string($audience_key) || $audience_key === '') { return 0; } if (!function_exists('wc_get_product')) { return 0; } $product = wc_get_product($source_product_id); if (!$product) { return 0; } if (!self::table_exists()) { return 0; } if (!self::is_eligible_target($source_product_id)) { $table = self::table_name(); $wpdb->query($wpdb->prepare( "DELETE FROM {$table} WHERE source_product_id = %d AND audience_key = %s", $source_product_id, $audience_key )); return 0; } $table = self::table_name(); $written = 0; $sources = array( self::SURFACE_UPSELLS => $product->get_upsell_ids(), self::SURFACE_CROSSSELLS => $product->get_cross_sell_ids(), self::SURFACE_RELATED => self::related_ids_for($source_product_id), ); if (class_exists('AIEO_DMM_Reco_Penalty')) { foreach ($sources as $surface => $ids) { if (!empty($ids)) { $ids = array_values(array_map('intval', (array) $ids)); $sources[$surface] = (array) AIEO_DMM_Reco_Penalty::filter_candidates($ids, $ids); } } } $sem_scores = array(); $sem_enabled = false; if (class_exists('AIEO_Semantic_Settings')) { $sem_enabled = (bool) AIEO_Semantic_Settings::get('fusion.effective_recos_enabled', false); } if ($sem_enabled) { $sem_scores = self::semantic_pair_scores($source_product_id); } $beta = 0.5; if ($sem_enabled && class_exists('AIEO_Semantic_Settings')) { $beta = max(0.0, min(1.0, (float) AIEO_Semantic_Settings::get('fusion.beta', 0.5))); } $blend_surfaces = array(self::SURFACE_RELATED, self::SURFACE_CROSSSELLS); if ($sem_enabled && !empty($sem_scores)) { $n_obs = self::cocart_observation_count($source_product_id); foreach ($blend_surfaces as $surface) { $ids = array_values(array_unique(array_map('intval', (array) ($sources[$surface] ?? array())))); $lane_allowed = (self::SURFACE_RELATED === $surface); if (!empty($ids) || ($lane_allowed && $n_obs < self::COLD_THRESHOLD)) { $sources[$surface] = self::blend_surface_scores( $ids, $sem_scores, $beta, $n_obs, $lane_allowed, $source_product_id ); } } } $wpdb->query($wpdb->prepare( "DELETE FROM {$table} WHERE source_product_id = %d AND audience_key = %s", $source_product_id, $audience_key )); $now = current_time('mysql', true); foreach ($sources as $surface => $ids) { $rank = 1; foreach ((array) $ids as $entry) { $is_blend = is_array($entry); $tid = $is_blend ? (int) $entry['tid'] : (int) $entry; if ($tid <= 0 || $tid === $source_product_id) { continue; } if (!self::is_eligible_target($tid)) { continue; } if ($rank > 30) { break; } $reason = null; $score = 0; if ($is_blend) { $score = round((float) $entry['score'], 4); $reason = !empty($entry['cold']) ? 'semantic_cold_start' : (!empty($entry['sem']) ? 'semantic' : null); } $wpdb->insert( $table, array( 'source_product_id' => $source_product_id, 'surface' => $surface, 'audience_key' => $audience_key, 'rank' => $rank, 'target_product_id' => $tid, 'score' => $score, 'reason_code' => $reason, 'computed_at' => $now, ), array('%d', '%s', '%s', '%d', '%d', '%f', '%s', '%s') ); $rank++; $written++; } } if ($written > 0) { do_action('aieo_recos_recomputed', (int) $source_product_id, (string) $audience_key, (int) $written); } return $written; } private static function semantic_pair_scores($source_product_id) { global $wpdb; $table = $wpdb->prefix . 'aieo_sem_pairs'; if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) { return array(); } $rows = $wpdb->get_results($wpdb->prepare( "SELECT target_id, score FROM {$table} WHERE source_type = 'product' AND source_id = %d AND target_type = 'product' ORDER BY score DESC LIMIT 100", $source_product_id ), ARRAY_A); $map = array(); foreach ((array) $rows as $r) { $map[(int) $r['target_id']] = (float) $r['score']; } return $map; } private static function blend_surface_scores($ids, $sem_scores, $beta, $n_obs, $lane_allowed, $source_product_id) { $count = count($ids); $scored = array(); $bases = array(); foreach ($ids as $i => $tid) { $base = ($count - $i) / $count; $bases[] = $base; $sem = isset($sem_scores[$tid]) ? (float) $sem_scores[$tid] : 0.0; $boosted = $base * min(1.0 + $beta * $sem, 1.4); $scored[] = array('tid' => (int) $tid, 'score' => $boosted, 'sem' => $sem > 0, 'i' => $i); } if ($lane_allowed && $n_obs < self::COLD_THRESHOLD) { $n0 = self::COLD_N0; $w_beh = $n_obs / ($n_obs + $n0); $w_lane = $n0 / ($n_obs + $n0); $median = self::median($bases); foreach ($scored as &$row) { $sem = isset($sem_scores[$row['tid']]) ? (float) $sem_scores[$row['tid']] : 0.0; $row['score'] = $w_beh * $row['score'] + $w_lane * ($sem * $median); } unset($row); $have = array(); foreach ($scored as $row) { $have[$row['tid']] = true; } arsort($sem_scores); $i = count($scored); $appended = 0; foreach ($sem_scores as $tid => $sem) { if ($appended >= self::COLD_LANE_MAX) { break; } $tid = (int) $tid; if (isset($have[$tid]) || $tid === $source_product_id) { continue; } $scored[] = array('tid' => $tid, 'score' => $w_lane * ((float) $sem * $median), 'sem' => true, 'i' => $i, 'cold' => true); $have[$tid] = true; $i++; $appended++; } } usort($scored, static function ($a, $b) { if ($a['score'] !== $b['score']) { return ($a['score'] < $b['score']) ? 1 : -1; } return $a['i'] <=> $b['i']; }); return $scored; } private static function median($values) { $n = count($values); if (0 === $n) { return 0.5; } sort($values); $mid = (int) floor($n / 2); return (0 === $n % 2) ? ($values[$mid - 1] + $values[$mid]) / 2.0 : $values[$mid]; } private static function cocart_observation_count($source_product_id) { static $memo = array(); $source_product_id = (int) $source_product_id; if (isset($memo[$source_product_id])) { return $memo[$source_product_id]; } global $wpdb; $tbl = $wpdb->prefix . 'wc_order_product_lookup'; if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $tbl)) !== $tbl) { return $memo[$source_product_id] = 0; } $cutoff = (new DateTimeImmutable('now', wp_timezone())) ->modify('-56 days') ->format('Y-m-d H:i:s'); $n = (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(DISTINCT a.order_id) FROM {$tbl} a JOIN {$tbl} b ON b.order_id = a.order_id AND b.product_id <> a.product_id WHERE a.product_id = %d AND a.date_created >= %s", $source_product_id, $cutoff )); return $memo[$source_product_id] = $n; } private static function is_eligible_target($product_id) { static $memo = array(); $product_id = (int) $product_id; if (isset($memo[$product_id])) { return $memo[$product_id]; } $post = get_post($product_id); if (!$post || $post->post_type !== 'product' || $post->post_status !== 'publish') { return $memo[$product_id] = false; } if (!function_exists('wc_get_product')) { return $memo[$product_id] = true; } $product = wc_get_product($product_id); if (!$product) { return $memo[$product_id] = false; } if (!$product->is_in_stock()) { return $memo[$product_id] = false; } return $memo[$product_id] = true; } public static function invalidate_target($target_product_id) { global $wpdb; $target_product_id = (int) $target_product_id; if ($target_product_id <= 0 || !self::table_exists()) { return 0; } $table = self::table_name(); return (int) $wpdb->query($wpdb->prepare( "DELETE FROM {$table} WHERE target_product_id = %d", $target_product_id )); } public static function recompute_all_audiences($source_product_id) { $total = 0; $audiences = class_exists('AIEO_Identity_Bridge') ? AIEO_Identity_Bridge::known_audience_keys() : array('guest'); foreach ($audiences as $key) { $total += self::recompute($source_product_id, $key); } return $total; } private static function related_ids_for($product_id) { if (!function_exists('wc_get_related_products')) { return array(); } return (array) wc_get_related_products($product_id, 30); } public static function table_name() { global $wpdb; return $wpdb->prefix . self::TABLE_NAME; } public static function table_exists($fresh = false) { static $cached = null; if ($cached !== null && !$fresh) { return $cached; } global $wpdb; $found = (int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s", self::table_name() )); return $cached = ($found > 0); } public static function maybe_install() { $current = (int) get_option(self::SCHEMA_OPTION, 0); if ($current >= self::SCHEMA_VERSION) { if (!is_admin() && !wp_doing_cron()) { return; } if (self::table_exists()) { return; } } if (!AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION)) { return; } global $wpdb; $table = self::table_name(); $charset = aieo_get_charset_collate(); $sql = "CREATE TABLE {$table} ( source_product_id BIGINT(20) UNSIGNED NOT NULL, surface VARCHAR(20) NOT NULL, audience_key VARCHAR(64) NOT NULL, `rank` TINYINT(3) UNSIGNED NOT NULL, target_product_id BIGINT(20) UNSIGNED NOT NULL, score DECIMAL(8,4) NOT NULL DEFAULT 0, reason_code VARCHAR(32) DEFAULT NULL, computed_at DATETIME NOT NULL, PRIMARY KEY (source_product_id, surface, audience_key, `rank`), KEY ix_target (target_product_id), KEY ix_audience_surface (audience_key, surface) ) {$charset};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta($sql); if (self::table_exists(true)) { update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION, 'no'); } } }