prefix . 'aieo_ratings'; } public static function stats_table() { global $wpdb; return $wpdb->prefix . 'aieo_rating_stats'; } public function maybe_install() { if (get_option(self::SCHEMA_OPTION, '') === self::SCHEMA_VERSION) { if (get_option(self::EXTERNAL_READY_OPTION, '0') !== '1' && false === get_transient(self::SCHEMA_RETRY_TRANSIENT) && (!class_exists('AIEO_Schema_Lock') || AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION))) { set_transient(self::SCHEMA_RETRY_TRANSIENT, 1, DAY_IN_SECONDS); self::install(); } return; } if (class_exists('AIEO_Schema_Lock') && !AIEO_Schema_Lock::acquire(self::SCHEMA_OPTION)) { return; } self::install(); update_option(self::SCHEMA_OPTION, self::SCHEMA_VERSION, false); } public static function install() { global $wpdb; $events = self::events_table(); $stats = self::stats_table(); $charset = function_exists('aieo_get_charset_collate') ? aieo_get_charset_collate() : $wpdb->get_charset_collate(); $sql_events = "CREATE TABLE {$events} ( id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, object_type varchar(20) NOT NULL DEFAULT 'product', product_id bigint(20) UNSIGNED NOT NULL, user_id bigint(20) UNSIGNED NOT NULL DEFAULT 0, session_token varchar(64) NOT NULL DEFAULT '', rating tinyint(4) NOT NULL DEFAULT 0, previous_rating tinyint(4) NOT NULL DEFAULT 0, source varchar(32) NOT NULL DEFAULT '', external_id varchar(64) DEFAULT NULL, variant varchar(16) NOT NULL DEFAULT '', options varchar(2048) NOT NULL DEFAULT '', page_url varchar(512) NOT NULL DEFAULT '', visitor_id varchar(64) NOT NULL DEFAULT '', invitee_id bigint(20) UNSIGNED NOT NULL DEFAULT 0, user_agent_hash char(16) NOT NULL DEFAULT '', ip_hash char(16) NOT NULL DEFAULT '', created_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY uniq_external (source, external_id), KEY idx_product (object_type, product_id, created_at), KEY idx_user (user_id, created_at), KEY idx_session (session_token, created_at), KEY idx_invitee (invitee_id) ) {$charset};"; $sql_stats = "CREATE TABLE {$stats} ( object_type varchar(20) NOT NULL DEFAULT 'product', product_id bigint(20) UNSIGNED NOT NULL, variant varchar(16) NOT NULL DEFAULT '', options varchar(2048) NOT NULL DEFAULT '', count_total int(10) UNSIGNED NOT NULL DEFAULT 0, sum_total int(10) UNSIGNED NOT NULL DEFAULT 0, n1 int(10) UNSIGNED NOT NULL DEFAULT 0, n2 int(10) UNSIGNED NOT NULL DEFAULT 0, n3 int(10) UNSIGNED NOT NULL DEFAULT 0, n4 int(10) UNSIGNED NOT NULL DEFAULT 0, n5 int(10) UNSIGNED NOT NULL DEFAULT 0, last_voted_at datetime NULL, PRIMARY KEY (object_type, product_id, variant), KEY idx_count (count_total) ) {$charset};"; if (!function_exists('dbDelta')) { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } if ((string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($stats))) === $stats) { self::ensure_v2_object_type_columns(); self::ensure_v4_vote_columns(); } dbDelta($sql_events); dbDelta($sql_stats); self::ensure_v2_object_type_columns(); $ready = self::ensure_v3_external_id_column(); update_option(self::EXTERNAL_READY_OPTION, $ready ? '1' : '0', true); self::ensure_v4_vote_columns(); if (class_exists('AIEO_Targets')) { AIEO_Targets::ensure(); } } private static function ensure_v4_vote_columns() { global $wpdb; $events = self::events_table(); $stats = self::stats_table(); $prev_suppress = isset($wpdb->suppress_errors) ? (bool) $wpdb->suppress_errors : false; $wpdb->suppress_errors(true); $columns = array( 'variant' => "VARCHAR(16) NOT NULL DEFAULT ''", 'options' => "VARCHAR(2048) NOT NULL DEFAULT ''", 'page_url' => "VARCHAR(512) NOT NULL DEFAULT ''", 'visitor_id' => "VARCHAR(64) NOT NULL DEFAULT ''", 'invitee_id' => 'BIGINT(20) UNSIGNED NOT NULL DEFAULT 0', ); $have = array_map('strtolower', (array) $wpdb->get_col("SHOW COLUMNS FROM `{$events}`")); $add = array(); foreach ($columns as $name => $type) { if (!in_array($name, $have, true)) { $add[] = "ADD COLUMN `{$name}` {$type}"; } } if ($add) { $wpdb->query("ALTER TABLE `{$events}` " . implode(', ', $add)); } if (!$wpdb->get_results("SHOW INDEX FROM `{$events}` WHERE Key_name = 'idx_invitee'")) { $wpdb->query("ALTER TABLE `{$events}` ADD KEY `idx_invitee` (`invitee_id`)"); } $have = array_map('strtolower', (array) $wpdb->get_col("SHOW COLUMNS FROM `{$stats}`")); $add = array(); foreach (array('variant' => $columns['variant'], 'options' => $columns['options']) as $name => $type) { if (!in_array($name, $have, true)) { $add[] = "ADD COLUMN `{$name}` {$type} AFTER `product_id`"; } } if ($add) { $wpdb->query("ALTER TABLE `{$stats}` " . implode(', ', $add)); } $pk = array_map(static function ($r) { return strtolower((string) $r['Column_name']); }, (array) $wpdb->get_results("SHOW INDEX FROM `{$stats}` WHERE Key_name = 'PRIMARY'", ARRAY_A)); if ($pk && !in_array('variant', $pk, true)) { $wpdb->query("ALTER TABLE `{$stats}` DROP PRIMARY KEY, ADD PRIMARY KEY (`object_type`, `product_id`, `variant`)"); } $wpdb->suppress_errors($prev_suppress); } private static function ensure_v3_external_id_column() { global $wpdb; $events = self::events_table(); $prev_suppress = isset($wpdb->suppress_errors) ? (bool) $wpdb->suppress_errors : false; $wpdb->suppress_errors(true); $col = $wpdb->get_var("SHOW COLUMNS FROM `{$events}` LIKE 'external_id'"); if (!$col) { $wpdb->query("ALTER TABLE `{$events}` ADD COLUMN `external_id` VARCHAR(64) DEFAULT NULL AFTER `source`"); $col = $wpdb->get_var("SHOW COLUMNS FROM `{$events}` LIKE 'external_id'"); } $has_idx = false; if ($col) { $idx = $wpdb->get_results("SHOW INDEX FROM `{$events}` WHERE Key_name = 'uniq_external'", ARRAY_A); if (empty($idx)) { $wpdb->query("ALTER TABLE `{$events}` ADD UNIQUE KEY `uniq_external` (`source`, `external_id`)"); $idx = $wpdb->get_results("SHOW INDEX FROM `{$events}` WHERE Key_name = 'uniq_external'", ARRAY_A); } if (is_array($idx) && count($idx) > 0) { $has_idx = ((int) $idx[0]['Non_unique'] === 0); } } $wpdb->suppress_errors($prev_suppress); return ($col && $has_idx); } public static function supports_external_ids() { static $ready = null; if ($ready === null) { $ready = (get_option(self::EXTERNAL_READY_OPTION, '0') === '1'); } return $ready; } private static function widget_scope_sql() { return self::supports_external_ids() ? ' AND external_id IS NULL' : ''; } private static function ensure_v2_object_type_columns() { global $wpdb; $events = self::events_table(); $stats = self::stats_table(); $prev_suppress = isset($wpdb->suppress_errors) ? (bool) $wpdb->suppress_errors : false; $wpdb->suppress_errors(true); $col = $wpdb->get_var("SHOW COLUMNS FROM `{$events}` LIKE 'object_type'"); if (!$col) { $wpdb->query("ALTER TABLE `{$events}` ADD COLUMN `object_type` VARCHAR(20) NOT NULL DEFAULT 'product' AFTER `id`"); } $idx = $wpdb->get_results("SHOW INDEX FROM `{$events}` WHERE Key_name = 'idx_product'", ARRAY_A); $needs_idx_rebuild = false; if (is_array($idx) && count($idx) > 0) { $cols_in_idx = array_map(function ($r) { return strtolower((string) $r['Column_name']); }, $idx); if (!in_array('object_type', $cols_in_idx, true)) { $needs_idx_rebuild = true; } } if ($needs_idx_rebuild) { $wpdb->query("ALTER TABLE `{$events}` DROP INDEX `idx_product`, ADD KEY `idx_product` (`object_type`, `product_id`, `created_at`)"); } $col = $wpdb->get_var("SHOW COLUMNS FROM `{$stats}` LIKE 'object_type'"); if (!$col) { $wpdb->query("ALTER TABLE `{$stats}` ADD COLUMN `object_type` VARCHAR(20) NOT NULL DEFAULT 'product' FIRST"); $wpdb->query("ALTER TABLE `{$stats}` DROP PRIMARY KEY, ADD PRIMARY KEY (`object_type`, `product_id`)"); } $wpdb->suppress_errors($prev_suppress); } public static function get_settings() { $stored = get_option(self::SETTINGS_OPTION, array()); if (!is_array($stored)) { $stored = array(); } return array_merge(self::defaults(), $stored); } public static function chosen_colours_css(array $settings) { $defaults = self::defaults(); $former = array('color_filled' => array('#f46767'), 'color_hover' => array('#f46767'), 'color_pre_rated' => array('#000000')); $chosen = ''; foreach (array('empty' => 'color_empty', 'filled' => 'color_filled', 'hover' => 'color_hover', 'pre-rated' => 'color_pre_rated') as $var => $key) { $value = sanitize_hex_color((string) ($settings[$key] ?? '')); if (!$value || 0 === strcasecmp($value, (string) $defaults[$key]) || in_array(strtolower($value), $former[$key] ?? array(), true)) { continue; } $chosen .= '--aieo-rating-' . $var . '-chosen:' . $value . ';'; } return '' === $chosen ? '' : ':root{' . $chosen . '}'; } public static function defaults() { return array( 'enabled' => 1, 'require_login' => 0, 'login_redirect_mode' => 'redirect', 'display_archive' => 1, 'display_single' => 1, 'archive_position' => 'under_title', 'single_position' => 'under_title', 'aggregate_only_archive' => 0, 'caption_format' => '%avg (%count)', 'caption_before_rated' => '', 'caption_read_only' => '', 'min_votes_for_display' => 0, 'display_full_until_rated' => 1, 'color_empty' => '#d4d4d8', 'color_filled' => '#F5B301', 'color_hover' => '#FFC93C', 'color_pre_rated' => '#F5B301', 'size' => 20, 'size_mobile' => 24, 'size_single' => 20, 'size_archive' => 16, 'gap_archive' => 4, 'gap_single' => 4, 'gap' => 2, 'gap_mobile' => 1, 'caption_size' => 13, 'caption_size_mobile' => 13, 'caption_size_archive' => 12, 'caption_size_archive_mobile' => 11, 'allow_clear' => 1, 'seo_schema_enabled' => 1, ); } private static $kinds = null; public static function kinds() { if (null !== self::$kinds) { return self::$kinds; } $built_in = array( 'product' => array('exists' => static function ($key) { if (!ctype_digit((string) $key)) { return false; } $type = get_post_type((int) $key); return 'product' === $type || 'product_variation' === $type; }), 'brand' => array('exists' => static function ($key) { return ctype_digit((string) $key) && (bool) term_exists((int) $key, 'product_brand'); }), ); $out = array(); foreach ((array) apply_filters('aieo_rating_kinds', $built_in) as $name => $kind) { $name = self::kind_name($name); if ('' === $name || !is_array($kind) || !isset($kind['exists']) || !is_callable($kind['exists'])) { continue; } $out[$name] = array( 'exists' => $kind['exists'], 'canon' => (isset($kind['canon']) && is_callable($kind['canon'])) ? $kind['canon'] : null, ); } if (did_action('wp_loaded')) { self::$kinds = $out; } return $out; } public static function look_kind($kinds) { if (function_exists('rooster_looks') && is_array($kinds) && !isset($kinds['look'])) { $kinds['look'] = array('exists' => static function ($key) { $looks = rooster_looks(); return is_string($key) && '' !== $key && isset($looks[$key]); }); } return $kinds; } private static function kind_name($kind) { if (class_exists('AIEO_Targets')) { return AIEO_Targets::clean_kind($kind); } $kind = strtolower(trim((string) $kind)); return preg_match('/^[a-z0-9_-]{1,20}$/', $kind) ? $kind : ''; } public static function kind($kind) { $name = self::kind_name($kind); return '' === $name ? 'product' : $name; } public static function target($kind, $key, $create = false) { if (!class_exists('AIEO_Targets')) { return null; } $kinds = self::kinds(); $kind = self::kind_name($kind); $key = class_exists('AIEO_Targets') ? AIEO_Targets::clean_key($key) : ''; if ('' === $kind || '' === $key || !isset($kinds[$kind])) { return null; } if ($kinds[$kind]['canon']) { $now = call_user_func($kinds[$kind]['canon'], $key); if (is_string($now) && '' !== AIEO_Targets::clean_key($now)) { $key = AIEO_Targets::clean_key($now); } } if (!call_user_func($kinds[$kind]['exists'], $key)) { return null; } $id = AIEO_Targets::id($kind, $key, $create); return array($kind, $key, $id); } public static function reset() { self::$kinds = null; if (null !== self::$instance) { self::$instance->viewer_rating_memo = array(); self::$instance->viewer_memo_sig = null; } if (class_exists('AIEO_Targets')) { AIEO_Targets::reset(); } } public static function voter_token($sid, $born = 0) { $sid = self::clean_sid($sid); $born = $born > 0 ? (int) $born : time(); return '' === $sid ? '' : self::VOTER_VERSION . '.' . $sid . '.' . base_convert((string) $born, 10, 36) . '.' . self::voter_signature($sid, $born); } public static function voter_parts($token) { $parts = explode('.', is_string($token) ? $token : ''); if (4 !== count($parts) || self::VOTER_VERSION !== $parts[0] || !preg_match('/^[0-9a-z]{1,8}$/', $parts[2])) { return null; } $sid = self::clean_sid($parts[1]); if ('' === $sid || $sid !== $parts[1]) { return null; } $born = (int) base_convert($parts[2], 36, 10); return hash_equals(self::voter_signature($sid, $born), $parts[3]) ? array($sid, $born) : null; } public static function voter_sid($token) { $parts = self::voter_parts($token); return ($parts && self::voter_alive($parts[1])) ? $parts[0] : ''; } public static function voter_alive($born) { $days = (int) apply_filters('aieo_rating_voter_days', self::VOTER_DAYS); return (int) $born > time() - max(1, $days) * DAY_IN_SECONDS && (int) $born <= time() + HOUR_IN_SECONDS; } public static function session_born($sid) { global $wpdb; $sid = self::clean_sid($sid); if ('' === $sid) { return 0; } $first = $wpdb->get_var($wpdb->prepare('SELECT MIN(created_at) FROM ' . self::events_table() . ' WHERE session_token = %s AND user_id = 0', $sid)); return $first ? (int) strtotime($first . ' UTC') : 0; } public static function request_voter($token, $mint = true) { $parts = self::voter_parts($token); if ($parts && self::voter_alive($parts[1])) { return $parts; } $sid = self::cookie_sid(); if ('' !== $sid && strlen($sid) >= 16 && (!$parts || $parts[0] !== $sid)) { $born = self::session_born($sid); if (0 === $born) { return array($sid, time()); } if (self::voter_alive($born)) { return array($sid, $born); } } return $mint ? array(self::new_sid(), time()) : array('', 0); } private static function voter_signature($sid, $born) { return substr(hash_hmac('sha256', 'aieo-rating-voter|' . $sid . '|' . (int) $born, wp_salt('auth')), 0, 24); } private static function clean_sid($sid) { $sid = is_string($sid) ? $sid : ''; return preg_match('/^[A-Za-z0-9]{16,64}$/', $sid) ? $sid : ''; } public static function new_sid() { return wp_generate_password(32, false, false); } public static function cookie_sid() { if (!isset($_COOKIE[self::COOKIE_NAME]) || !is_string($_COOKIE[self::COOKIE_NAME])) { return ''; } $raw = preg_replace('/[^a-z0-9]/i', '', (string) wp_unslash($_COOKIE[self::COOKIE_NAME])); return '' === $raw ? '' : substr($raw, 0, 64); } public static function keep_sid($sid) { $sid = self::clean_sid($sid); if ('' === $sid || self::cookie_sid() === $sid) { return; } if (!headers_sent()) { setcookie(self::COOKIE_NAME, $sid, array( 'expires' => time() + (self::COOKIE_DAYS * DAY_IN_SECONDS), 'path' => COOKIEPATH ? COOKIEPATH : '/', 'domain' => COOKIE_DOMAIN ? COOKIE_DOMAIN : '', 'secure' => is_ssl(), 'httponly' => true, 'samesite' => 'Lax', )); } $_COOKIE[self::COOKIE_NAME] = $sid; } private function read_session_token_no_create() { return self::cookie_sid(); } public static function clean_options($options, $kind = '', $key = '') { $pick = static function ($pairs) { $out = array(); foreach ((is_array($pairs) || is_object($pairs)) ? (array) $pairs : array() as $k => $v) { if (!is_string($k) || !preg_match('/^[a-z0-9_-]{1,32}$/', $k)) { continue; } if (!is_scalar($v) || is_bool($v) || !preg_match('/^[A-Za-z0-9_.-]{1,64}$/', (string) $v)) { continue; } $out[$k] = (string) $v; } ksort($out, SORT_STRING); return array_slice($out, 0, self::OPTIONS_MAX, true); }; return $pick(apply_filters('aieo_rating_options', $pick($options), (string) $kind, (string) $key)); } public static function variant_of(array $options) { if (!$options) { return ''; } ksort($options, SORT_STRING); $pairs = array(); foreach ($options as $k => $v) { $pairs[] = $k . '=' . $v; } return substr(md5(implode('&', $pairs)), 0, 12); } public static function origins() { $origins = array(); foreach (array(home_url('/'), site_url('/')) as $url) { $origin = self::origin_of($url); if ('' !== $origin) { $origins[] = $origin; } } $origins = (array) apply_filters('aieo_rating_origins', array_values(array_unique($origins))); return array_values(array_unique(array_filter(array_map(array(__CLASS__, 'origin_of'), $origins)))); } public static function origin_of($url) { $p = wp_parse_url(is_string($url) ? trim($url) : ''); if (empty($p['scheme']) || empty($p['host']) || !in_array(strtolower($p['scheme']), array('http', 'https'), true)) { return ''; } return strtolower($p['scheme'] . '://' . $p['host'] . (isset($p['port']) ? ':' . (int) $p['port'] : '')); } public static function clean_page($url) { $url = is_string($url) ? trim($url) : ''; if ('' === $url || !in_array(self::origin_of($url), self::origins(), true)) { return ''; } if (class_exists('AIEO_Url_Redaction')) { $url = (string) AIEO_Url_Redaction::clean($url); } $url = esc_url_raw($url); if (strlen($url) > 512) { $p = wp_parse_url($url); $url = self::origin_of($url) . (isset($p['path']) ? (string) $p['path'] : '/'); } return strlen($url) <= 512 ? $url : ''; } public static function request_visitor() { if (class_exists('AIEO_Signal_Envelope') && method_exists('AIEO_Signal_Envelope', 'cookie_visitor')) { return (string) AIEO_Signal_Envelope::cookie_visitor(); } $raw = isset($_COOKIE['aieo_attr_sid']) && is_string($_COOKIE['aieo_attr_sid']) ? trim((string) wp_unslash($_COOKIE['aieo_attr_sid'])) : ''; return preg_match('/^[A-Za-z0-9_-]{1,64}$/D', $raw) ? $raw : ''; } private static function short_hash($value) { return substr(md5((string) $value), 0, 16); } public function record_event(array $vote) { global $wpdb; $kind = self::kind($vote['kind'] ?? 'product'); $target = (int) ($vote['target'] ?? 0); $rating = max(0, min(5, (int) ($vote['rating'] ?? 0))); $user_id = max(0, (int) ($vote['user_id'] ?? 0)); $session = substr(preg_replace('/[^A-Za-z0-9]/', '', (string) ($vote['session'] ?? '')), 0, 64); $options = (isset($vote['options']) && is_array($vote['options'])) ? $vote['options'] : array(); ksort($options, SORT_STRING); $variant = self::variant_of($options); $json = $options ? (string) wp_json_encode($options) : ''; if ($target <= 0) { return $this->empty_stats() + array('variant' => $variant, 'previous' => 0); } $now = current_time('mysql', true); $ip_raw = isset($_SERVER['REMOTE_ADDR']) ? (string) wp_unslash($_SERVER['REMOTE_ADDR']) : ''; $ua_raw = isset($_SERVER['HTTP_USER_AGENT']) ? (string) wp_unslash($_SERVER['HTTP_USER_AGENT']) : ''; $voter = $user_id > 0 ? 'u' . $user_id : 's' . $session; $lock = class_exists('AIEO_Lock_Name') ? AIEO_Lock_Name::for_shop('aieo_rating:' . md5($kind . '|' . $target . '|' . $variant . '|' . $voter)) : ''; $locked = '' !== $lock && '1' === (string) $wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 3)', $lock)); try { $previous = $this->get_current_rating_for_viewer($target, $user_id, $session, $kind, $variant, false); $wpdb->insert( self::events_table(), array( 'object_type' => $kind, 'product_id' => $target, 'user_id' => $user_id, 'session_token' => $session, 'rating' => $rating, 'previous_rating' => (int) $previous, 'source' => substr(sanitize_key((string) ($vote['source'] ?? '')), 0, 32), 'variant' => $variant, 'options' => $json, 'page_url' => (string) ($vote['page_url'] ?? ''), 'visitor_id' => (string) ($vote['visitor_id'] ?? ''), 'invitee_id' => max(0, (int) ($vote['invitee_id'] ?? 0)), 'user_agent_hash' => self::short_hash($ua_raw), 'ip_hash' => self::short_hash($ip_raw), 'created_at' => $now, ), array('%s','%d','%d','%s','%d','%d','%s','%s','%s','%s','%s','%d','%s','%s','%s') ); $vote_id = (int) $wpdb->insert_id; $count_delta = ($rating > 0 ? 1 : 0) - ($previous > 0 ? 1 : 0); $sum_delta = $rating - (int) $previous; $bucket = array_fill(1, 5, 0); if ($previous > 0) { $bucket[(int) $previous] = -1; } if ($rating > 0) { $bucket[(int) $rating] += 1; } $seed = array_map(static function ($n) { return max(0, $n); }, $bucket); $stats_table = self::stats_table(); $wpdb->query($wpdb->prepare( "INSERT INTO {$stats_table} (object_type, product_id, variant, options, count_total, sum_total, n1, n2, n3, n4, n5, last_voted_at) VALUES (%s, %d, %s, %s, %d, %d, %d, %d, %d, %d, %d, %s) ON DUPLICATE KEY UPDATE count_total = GREATEST(0, CAST(count_total AS SIGNED) + %d), sum_total = GREATEST(0, CAST(sum_total AS SIGNED) + %d), n1 = GREATEST(0, CAST(n1 AS SIGNED) + %d), n2 = GREATEST(0, CAST(n2 AS SIGNED) + %d), n3 = GREATEST(0, CAST(n3 AS SIGNED) + %d), n4 = GREATEST(0, CAST(n4 AS SIGNED) + %d), n5 = GREATEST(0, CAST(n5 AS SIGNED) + %d), options = VALUES(options), last_voted_at = VALUES(last_voted_at)", $kind, $target, $variant, $json, max(0, $count_delta), max(0, $sum_delta), $seed[1], $seed[2], $seed[3], $seed[4], $seed[5], $now, $count_delta, $sum_delta, $bucket[1], $bucket[2], $bucket[3], $bucket[4], $bucket[5] )); } finally { if ($locked) { $wpdb->query($wpdb->prepare('SELECT RELEASE_LOCK(%s)', $lock)); } } if ($this->viewer_memo_sig === $kind . '|' . $user_id . '|' . $session) { $this->viewer_rating_memo[$kind . ':' . $target . ':' . $variant] = $rating; } wp_cache_delete(self::stats_cache_key($kind, $target, $variant), self::CACHE_GROUP); $fresh = $this->get_stats($target, $kind, $variant); if ('product' === $kind && '' === $variant) { $this->write_rating_to_vitals($target, $fresh); } do_action('aieo_rating_stats_changed', array($target), $kind, $variant); do_action('aieo_rating_recorded', array( 'id' => $vote_id, 'kind' => $kind, 'key' => (string) ($vote['key'] ?? (string) $target), 'target' => $target, 'variant' => $variant, 'options' => $options, 'rating' => $rating, 'previous' => (int) $previous, 'user_id' => $user_id, 'visitor_id' => (string) ($vote['visitor_id'] ?? ''), 'invitee_id' => max(0, (int) ($vote['invitee_id'] ?? 0)), 'page_url' => (string) ($vote['page_url'] ?? ''), 'source' => substr(sanitize_key((string) ($vote['source'] ?? '')), 0, 32), 'voted_at' => $now, )); return $fresh + array('variant' => $variant, 'previous' => (int) $previous); } private function write_rating_to_vitals($product_id, $stats) { global $wpdb; $product_id = (int) $product_id; if ($product_id <= 0) { return; } $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; static $has_cols = null; if ($has_cols === null) { $has_cols = ((int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = 'rating_value'", $vitals ))) > 0; } if (!$has_cols) { return; } $count = isset($stats['count']) ? (int) $stats['count'] : 0; $sum = isset($stats['sum']) ? (float) $stats['sum'] : null; $avg = ($count > 0 && null !== $sum) ? round($sum / $count, 2) : null; if (null === $avg && $count > 0 && isset($stats['avg'])) { $avg = round((float) $stats['avg'], 2); } if ($avg === null) { $wpdb->query($wpdb->prepare("UPDATE `{$vitals}` SET rating_value = NULL, rating_count = %d WHERE product_id = %d", $count, $product_id)); } else { $wpdb->query($wpdb->prepare("UPDATE `{$vitals}` SET rating_value = %f, rating_count = %d WHERE product_id = %d", $avg, $count, $product_id)); } } public static function sync_all_ratings_to_vitals() { global $wpdb; $vitals = $wpdb->prefix . 'aieo_core_product_vitals'; $stats = self::stats_table(); $has_cols = ((int) $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = 'rating_value'", $vitals ))) > 0; if (!$has_cols) { return; } $wpdb->query( "UPDATE `{$vitals}` v JOIN ( SELECT product_id, ROUND(sum_total / count_total, 2) AS avg_val, count_total FROM `{$stats}` WHERE object_type = 'product' AND variant = '' AND count_total > 0 ) s ON s.product_id = v.product_id SET v.rating_value = s.avg_val, v.rating_count = s.count_total" ); } public function record_external_event($source, $external_id, $product_id, $rating, $user_id, $created_at = '', $object_type = 'product') { global $wpdb; if (!self::supports_external_ids()) { return false; } $source = substr((string) $source, 0, 32); $external_id = substr((string) $external_id, 0, 64); $product_id = (int) $product_id; $rating = (int) $rating; $user_id = max(0, (int) $user_id); $object_type = self::kind($object_type); if ($source === '' || $external_id === '' || $product_id <= 0 || $rating < 1 || $rating > 5) { return false; } if ($created_at === '' || $created_at === '0000-00-00 00:00:00') { $created_at = current_time('mysql', true); } $events = self::events_table(); $prev_pid = (int) $wpdb->get_var($wpdb->prepare( "SELECT product_id FROM {$events} WHERE source = %s AND external_id = %s LIMIT 1", $source, $external_id )); $ok = $this->upsert_external_rows($source, $object_type, array(array( 'external_id' => $external_id, 'product_id' => $product_id, 'rating' => $rating, 'user_id' => $user_id, 'created_at' => $created_at, ))); if (!$ok) { return false; } $targets = array($product_id); if ($prev_pid > 0 && $prev_pid !== $product_id) { $targets[] = $prev_pid; } $this->recompute_stats($targets, $object_type); return true; } public function record_external_events_bulk($source, array $rows, $object_type = 'product') { global $wpdb; if (!self::supports_external_ids() || empty($rows)) { return 0; } $source = substr((string) $source, 0, 32); $object_type = self::kind($object_type); if ($source === '') { return 0; } $clean = array(); $ext_ids = array(); $products = array(); foreach ($rows as $r) { $eid = isset($r['external_id']) ? substr((string) $r['external_id'], 0, 64) : ''; $pid = isset($r['product_id']) ? (int) $r['product_id'] : 0; $rating = isset($r['rating']) ? (int) $r['rating'] : 0; if ($eid === '' || $pid <= 0 || $rating < 1 || $rating > 5) { continue; } $created = isset($r['created_at']) ? (string) $r['created_at'] : ''; if ($created === '' || $created === '0000-00-00 00:00:00') { $created = current_time('mysql', true); } $clean[] = array( 'external_id' => $eid, 'product_id' => $pid, 'rating' => $rating, 'user_id' => isset($r['user_id']) ? max(0, (int) $r['user_id']) : 0, 'created_at' => $created, ); $ext_ids[] = $eid; $products[$pid] = true; } if (empty($clean)) { return 0; } $events = self::events_table(); foreach (array_chunk($ext_ids, 500) as $chunk) { $ph = implode(',', array_fill(0, count($chunk), '%s')); $args = array_merge(array($source), $chunk); $olds = $wpdb->get_col($wpdb->prepare( "SELECT DISTINCT product_id FROM {$events} WHERE source = %s AND external_id IN ({$ph})", $args )); foreach ((array) $olds as $o) { $products[(int) $o] = true; } } $written = 0; foreach (array_chunk($clean, 500) as $chunk) { if ($this->upsert_external_rows($source, $object_type, $chunk)) { $written += count($chunk); } } $this->recompute_stats(array_keys($products), $object_type); return $written; } public function withdraw_external_events($source, array $external_ids, $object_type = 'product') { global $wpdb; if (!self::supports_external_ids() || empty($external_ids)) { return 0; } $source = substr((string) $source, 0, 32); $object_type = self::kind($object_type); if ($source === '') { return 0; } $ids = array(); foreach ($external_ids as $e) { $e = substr((string) $e, 0, 64); if ($e !== '') { $ids[$e] = true; } } $ids = array_keys($ids); if (empty($ids)) { return 0; } $events = self::events_table(); $deleted = 0; $products = array(); foreach (array_chunk($ids, 500) as $chunk) { $ph = implode(',', array_fill(0, count($chunk), '%s')); $args = array_merge(array($source), $chunk); $pids = $wpdb->get_col($wpdb->prepare( "SELECT DISTINCT product_id FROM {$events} WHERE source = %s AND external_id IN ({$ph})", $args )); foreach ((array) $pids as $p) { $products[(int) $p] = true; } if (empty($pids)) { continue; } $deleted += (int) $wpdb->query($wpdb->prepare( "DELETE FROM {$events} WHERE source = %s AND external_id IN ({$ph})", $args )); } if (!empty($products)) { $this->recompute_stats(array_keys($products), $object_type); } return $deleted; } private function upsert_external_rows($source, $object_type, array $rows) { global $wpdb; if (empty($rows)) { return false; } $events = self::events_table(); $tuples = array(); $args = array(); foreach ($rows as $r) { $tuples[] = '(%s, %d, %d, %s, %d, 0, %s, %s, %s)'; $args[] = $object_type; $args[] = (int) $r['product_id']; $args[] = (int) $r['user_id']; $args[] = ''; $args[] = (int) $r['rating']; $args[] = $source; $args[] = (string) $r['external_id']; $args[] = (string) $r['created_at']; } $values = implode(', ', $tuples); $sql = $wpdb->prepare( "INSERT INTO {$events} (object_type, product_id, user_id, session_token, rating, previous_rating, source, external_id, created_at) VALUES {$values} ON DUPLICATE KEY UPDATE previous_rating = rating, rating = VALUES(rating), object_type = VALUES(object_type), product_id = VALUES(product_id), user_id = VALUES(user_id), created_at = VALUES(created_at)", $args ); return ($wpdb->query($sql) !== false); } public function recompute_stats(array $product_ids, $object_type = 'product') { global $wpdb; $object_type = self::kind($object_type); $ids = array_values(array_unique(array_filter(array_map('intval', $product_ids), function ($x) { return $x > 0; }))); if (empty($ids)) { return 0; } $changed = array(); $events = self::events_table(); $stats = self::stats_table(); $identity = self::supports_external_ids() ? "CASE WHEN external_id IS NOT NULL THEN CONCAT('x:', source, ':', external_id) WHEN user_id > 0 THEN CONCAT('u:', user_id) ELSE CONCAT('s:', session_token) END" : "CASE WHEN user_id > 0 THEN CONCAT('u:', user_id) ELSE CONCAT('s:', session_token) END"; $done = 0; foreach (array_chunk($ids, 500) as $chunk) { $ph = implode(',', array_fill(0, count($chunk), '%d')); $args = array_merge(array($object_type), $chunk); $rows = $wpdb->get_results($wpdb->prepare( "SELECT t.product_id, t.variant, MAX(t.options) AS options, COUNT(*) AS cnt, SUM(t.rating) AS total, SUM(t.rating = 1) AS n1, SUM(t.rating = 2) AS n2, SUM(t.rating = 3) AS n3, SUM(t.rating = 4) AS n4, SUM(t.rating = 5) AS n5, MAX(t.created_at) AS last_voted_at FROM ( SELECT product_id, variant, options, rating, created_at, ROW_NUMBER() OVER ( PARTITION BY product_id, variant, {$identity} ORDER BY created_at DESC, id DESC ) AS rn FROM {$events} WHERE object_type = %s AND product_id IN ({$ph}) ) t WHERE t.rn = 1 AND t.rating > 0 GROUP BY t.product_id, t.variant", $args ), ARRAY_A); $before = (array) $wpdb->get_results($wpdb->prepare( "SELECT product_id, variant FROM {$stats} WHERE object_type = %s AND product_id IN ({$ph}) AND variant <> ''", $args ), ARRAY_A); $found = array(); foreach ($chunk as $pid) { $found[$pid . "\0"] = array('product_id' => $pid, 'variant' => '', 'options' => ''); } foreach ($before as $b) { $found[(int) $b['product_id'] . "\0" . (string) $b['variant']] = array('product_id' => (int) $b['product_id'], 'variant' => (string) $b['variant'], 'options' => null); } foreach ((array) $rows as $r) { $found[(int) $r['product_id'] . "\0" . (string) $r['variant']] = $r + array('aggregated' => true); } $tuples = array(); $uargs = array(); foreach ($found as $r) { $has = !empty($r['aggregated']); $lv = ($has && !empty($r['last_voted_at'])) ? '%s' : 'NULL'; $op = null === $r['options'] ? "''" : '%s'; $tuples[] = "(%s, %d, %s, {$op}, %d, %d, %d, %d, %d, %d, %d, {$lv})"; $uargs[] = $object_type; $uargs[] = (int) $r['product_id']; $uargs[] = (string) $r['variant']; if ('%s' === $op) { $uargs[] = (string) $r['options']; } $uargs[] = $has ? (int) $r['cnt'] : 0; $uargs[] = $has ? (int) $r['total'] : 0; $uargs[] = $has ? (int) $r['n1'] : 0; $uargs[] = $has ? (int) $r['n2'] : 0; $uargs[] = $has ? (int) $r['n3'] : 0; $uargs[] = $has ? (int) $r['n4'] : 0; $uargs[] = $has ? (int) $r['n5'] : 0; if ($lv === '%s') { $uargs[] = (string) $r['last_voted_at']; } } $values = implode(', ', $tuples); $wpdb->query($wpdb->prepare( "INSERT INTO {$stats} (object_type, product_id, variant, options, count_total, sum_total, n1, n2, n3, n4, n5, last_voted_at) VALUES {$values} ON DUPLICATE KEY UPDATE options = IF(VALUES(options) = '', options, VALUES(options)), count_total = VALUES(count_total), sum_total = VALUES(sum_total), n1 = VALUES(n1), n2 = VALUES(n2), n3 = VALUES(n3), n4 = VALUES(n4), n5 = VALUES(n5), last_voted_at = VALUES(last_voted_at)", $uargs )); foreach ($found as $r) { $has = !empty($r['aggregated']); $pid = (int) $r['product_id']; $variant = (string) $r['variant']; $count = $has ? (int) $r['cnt'] : 0; $sum = $has ? (int) $r['total'] : 0; $payload = array( 'count' => $count, 'sum' => $sum, 'avg' => $count > 0 ? (float) round($sum / $count, 1) : 0.0, 'distribution' => array( $has ? (int) $r['n1'] : 0, $has ? (int) $r['n2'] : 0, $has ? (int) $r['n3'] : 0, $has ? (int) $r['n4'] : 0, $has ? (int) $r['n5'] : 0, ), 'last_voted_at' => ($has && !empty($r['last_voted_at'])) ? (string) $r['last_voted_at'] : '', ); $ckey = self::stats_cache_key($object_type, $pid, $variant); wp_cache_delete($ckey, self::CACHE_GROUP); wp_cache_set($ckey, $payload, self::CACHE_GROUP, 5 * MINUTE_IN_SECONDS); if ('' !== $variant) { continue; } if ($object_type === 'product') { $this->write_rating_to_vitals($pid, $payload); } $done++; $changed[] = $pid; } } if (!empty($changed)) { do_action('aieo_rating_stats_changed', $changed, $object_type); } return $done; } private $viewer_rating_memo = array(); private $viewer_memo_sig = null; public function prime_loop_ratings($query) { if (is_admin()) { return; } if (!($query instanceof WP_Query)) { return; } $typed = in_array('product', (array) $query->get('post_type'), true); $ids = array(); foreach ((array) $query->posts as $p) { if (is_object($p) ? 'product' !== $p->post_type : !$typed) { continue; } $pid = is_object($p) ? (int) $p->ID : (int) $p; if ($pid > 0) { $ids[] = $pid; } } if (count($ids) < 2) { return; } $this->get_stats_batch($ids); $this->prime_viewer_ratings($ids); } private function prime_viewer_ratings(array $ids, $object_type = 'product') { $object_type = self::kind($object_type); $user_id = (int) get_current_user_id(); $token = (string) $this->read_session_token_no_create(); if ($this->viewer_memo_sig !== $object_type . '|' . $user_id . '|' . $token) { $this->viewer_rating_memo = array(); $this->viewer_memo_sig = $object_type . '|' . $user_id . '|' . $token; } $ids = array_values(array_unique(array_filter(array_map('intval', $ids), function ($x) { return $x > 0; }))); if (empty($ids)) { return; } if ($user_id <= 0 && $token === '') { foreach ($ids as $pid) { $this->viewer_rating_memo[$object_type . ':' . $pid . ':'] = 0; } return; } global $wpdb; $events = self::events_table(); $ph = implode(',', array_fill(0, count($ids), '%d')); if ($user_id > 0) { $args = array_merge(array($object_type), $ids, array($user_id)); $scope = 'user_id = %d'; } else { $args = array_merge(array($object_type), $ids, array($token)); $scope = 'user_id = 0 AND session_token = %s'; } $widget_only = self::widget_scope_sql(); $rows = $wpdb->get_results($wpdb->prepare( "SELECT product_id, rating FROM ( SELECT product_id, rating, ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY created_at DESC, id DESC) AS rn FROM {$events} WHERE object_type = %s AND product_id IN ({$ph}) AND variant = '' AND {$scope}{$widget_only} ) t WHERE rn = 1", $args ), ARRAY_A); $found = array(); foreach ((array) $rows as $r) { $found[(int) $r['product_id']] = (int) $r['rating']; } foreach ($ids as $pid) { $this->viewer_rating_memo[$object_type . ':' . $pid . ':'] = isset($found[$pid]) ? $found[$pid] : 0; } } public function get_current_rating_for_viewer($product_id, $user_id, $session_token, $object_type = 'product', $variant = '', $memo = true) { global $wpdb; $product_id = (int) $product_id; $user_id = (int) $user_id; $token = (string) $session_token; $object_type = self::kind($object_type); $variant = (string) $variant; if ($product_id <= 0) { return 0; } $memo_sig = $object_type . '|' . $user_id . '|' . $token; $memo_key = $object_type . ':' . $product_id . ':' . $variant; if ($memo && $this->viewer_memo_sig === $memo_sig && array_key_exists($memo_key, $this->viewer_rating_memo)) { return (int) $this->viewer_rating_memo[$memo_key]; } $events = self::events_table(); $widget_only = self::widget_scope_sql(); if ($user_id > 0) { $row = $wpdb->get_row($wpdb->prepare( "SELECT rating FROM {$events} WHERE object_type = %s AND product_id = %d AND variant = %s AND user_id = %d{$widget_only} ORDER BY created_at DESC, id DESC LIMIT 1", $object_type, $product_id, $variant, $user_id ), ARRAY_A); } elseif ($token !== '') { $row = $wpdb->get_row($wpdb->prepare( "SELECT rating FROM {$events} WHERE object_type = %s AND product_id = %d AND variant = %s AND user_id = 0 AND session_token = %s{$widget_only} ORDER BY created_at DESC, id DESC LIMIT 1", $object_type, $product_id, $variant, $token ), ARRAY_A); } else { return 0; } if (!$row) { return 0; } return (int) $row['rating']; } public function viewer_votes($kind, array $targets, $user_id, $session) { global $wpdb; $kind = self::kind($kind); $targets = array_values(array_unique(array_filter(array_map('intval', $targets)))); $user_id = (int) $user_id; $session = (string) $session; if (!$targets || ($user_id <= 0 && '' === $session)) { return array(); } $events = self::events_table(); $ph = implode(',', array_fill(0, count($targets), '%d')); $scope = $user_id > 0 ? 'user_id = %d' : 'user_id = 0 AND session_token = %s'; $args = array_merge(array($kind), $targets, array($user_id > 0 ? $user_id : $session)); $widget_only = self::widget_scope_sql(); $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT product_id, variant, options, rating, created_at FROM ( SELECT product_id, variant, options, rating, created_at, ROW_NUMBER() OVER (PARTITION BY product_id, variant ORDER BY created_at DESC, id DESC) AS rn FROM {$events} WHERE object_type = %s AND product_id IN ({$ph}) AND {$scope}{$widget_only} ) t WHERE rn = 1 AND rating > 0", $args ), ARRAY_A); $out = array(); foreach ($rows as $r) { $options = '' === (string) $r['options'] ? array() : json_decode((string) $r['options'], true); $out[(int) $r['product_id']][(string) $r['variant']] = array( 'rating' => (int) $r['rating'], 'options' => is_array($options) ? $options : array(), 'voted_at' => (string) $r['created_at'], ); } return $out; } public static function votes_in_force($kind, array $args = array()) { global $wpdb; $kind = self::kind($kind); $where = array('object_type = %s'); $vals = array($kind); if (!empty($args['keys']) && is_array($args['keys'])) { $ids = class_exists('AIEO_Targets') ? AIEO_Targets::ids($kind, $args['keys'], false) : array(); if (!$ids) { return array(); } $where[] = 'product_id IN (' . implode(',', array_fill(0, count($ids), '%d')) . ')'; $vals = array_merge($vals, array_values($ids)); } $widget_only = self::widget_scope_sql(); $events = self::events_table(); $identity = "CASE WHEN user_id > 0 THEN CONCAT('u:', user_id) ELSE CONCAT('s:', session_token) END"; $since = ''; if (!empty($args['since']) && preg_match('/^\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?$/', (string) $args['since'])) { $since = ' AND created_at >= %s'; $vals[] = (string) $args['since']; } $rows = (array) $wpdb->get_results($wpdb->prepare( "SELECT product_id, variant, options, rating, created_at, page_url, source, user_id, visitor_id, invitee_id FROM ( SELECT product_id, variant, options, rating, created_at, page_url, source, user_id, visitor_id, invitee_id, ROW_NUMBER() OVER (PARTITION BY product_id, variant, {$identity} ORDER BY created_at DESC, id DESC) AS rn FROM {$events} WHERE " . implode(' AND ', $where) . "{$widget_only} ) t WHERE rn = 1 AND rating > 0" . str_replace('created_at', 't.created_at', $since) . ' ORDER BY t.created_at, t.product_id', $vals ), ARRAY_A); $names = class_exists('AIEO_Targets') ? AIEO_Targets::keys($kind, array_map(static function ($r) { return (int) $r['product_id']; }, $rows)) : array(); $out = array(); foreach ($rows as $r) { $options = '' === (string) $r['options'] ? array() : json_decode((string) $r['options'], true); $out[] = array( 'key' => isset($names[(int) $r['product_id']]) ? $names[(int) $r['product_id']] : (string) $r['product_id'], 'variant' => (string) $r['variant'], 'options' => is_array($options) ? $options : array(), 'rating' => (int) $r['rating'], 'voted_at' => (string) $r['created_at'], 'page_url' => (string) $r['page_url'], 'source' => (string) $r['source'], 'user_id' => (int) $r['user_id'], 'visitor_id' => (string) $r['visitor_id'], 'invitee_id' => (int) $r['invitee_id'], ); } return $out; } private static function stats_cache_key($kind, $id, $variant = '') { return self::CACHE_PREFIX . $kind . ':' . (int) $id . ('' === (string) $variant ? '' : ':' . $variant); } public function get_stats($product_id, $object_type = 'product', $variant = '') { $product_id = (int) $product_id; $object_type = self::kind($object_type); $variant = (string) $variant; if ($product_id <= 0) { return $this->empty_stats(); } $cache_key = self::stats_cache_key($object_type, $product_id, $variant); $cached = wp_cache_get($cache_key, self::CACHE_GROUP); if (is_array($cached)) { return $cached; } global $wpdb; $row = $wpdb->get_row($wpdb->prepare( "SELECT count_total, sum_total, n1, n2, n3, n4, n5, last_voted_at FROM " . self::stats_table() . " WHERE object_type = %s AND product_id = %d AND variant = %s", $object_type, $product_id, $variant ), ARRAY_A); $payload = $row ? self::stats_payload($row) : $this->empty_stats(); wp_cache_set($cache_key, $payload, self::CACHE_GROUP, 5 * MINUTE_IN_SECONDS); $payload['object_type'] = $object_type; return $payload; } private static function stats_payload(array $row) { $count = (int) $row['count_total']; $sum = (int) $row['sum_total']; return array( 'count' => $count, 'sum' => $sum, 'avg' => (float) ($count > 0 ? round($sum / $count, 1) : 0.0), 'distribution' => array( (int) $row['n1'], (int) $row['n2'], (int) $row['n3'], (int) $row['n4'], (int) $row['n5'], ), 'last_voted_at' => !empty($row['last_voted_at']) ? (string) $row['last_voted_at'] : '', ); } public function get_stats_batch(array $ids, $object_type = 'product', $variant = '') { $object_type = self::kind($object_type); $variant = (string) $variant; $ids = array_values(array_unique(array_filter(array_map('intval', $ids), function ($x) { return $x > 0; }))); if (empty($ids)) { return array(); } $out = array(); $miss = array(); foreach ($ids as $pid) { $cached = wp_cache_get(self::stats_cache_key($object_type, $pid, $variant), self::CACHE_GROUP); if (is_array($cached)) { $out[$pid] = $cached; } else { $miss[] = $pid; } } if (!empty($miss)) { global $wpdb; $placeholders = implode(',', array_fill(0, count($miss), '%d')); $args = array_merge(array($object_type, $variant), $miss); $rows = $wpdb->get_results($wpdb->prepare( "SELECT product_id, count_total, sum_total, n1, n2, n3, n4, n5, last_voted_at FROM " . self::stats_table() . " WHERE object_type = %s AND variant = %s AND product_id IN ({$placeholders})", $args ), ARRAY_A); $by_pid = array(); foreach ((array) $rows as $r) { $by_pid[(int) $r['product_id']] = $r; } foreach ($miss as $pid) { $out[$pid] = isset($by_pid[$pid]) ? self::stats_payload($by_pid[$pid]) : $this->empty_stats(); wp_cache_set(self::stats_cache_key($object_type, $pid, $variant), $out[$pid], self::CACHE_GROUP, 5 * MINUTE_IN_SECONDS); } } return $out; } private function empty_stats() { return array( 'count' => 0, 'sum' => 0, 'avg' => 0.0, 'distribution' => array(0, 0, 0, 0, 0), 'last_voted_at' => '', ); } public function render_stars_html($product, $variant = 'single') { $product_id = $this->resolve_product_id($product); if ($product_id <= 0) { return ''; } $settings = self::get_settings(); if (empty($settings['enabled'])) { return ''; } $this->enqueue_assets(true); if ($variant === 'archive' && !empty($settings['aggregate_only_archive'])) { return $this->render_aggregate_html($product_id); } $stats = $this->get_stats($product_id); $current = $this->get_current_rating_for_viewer( $product_id, get_current_user_id(), $this->read_session_token_no_create() ); $pre_rated = !empty($settings['display_full_until_rated']) && $current === 0; $caption = $current > 0 ? $this->build_caption($stats, $settings) : self::caption_before_rated($settings); $root_classes = 'aieo-rating-stars aieo-rating-stars--' . sanitize_html_class($variant); if ('single' === $variant) { $root_classes .= ' rooster-order--rating ff-order--rating'; } if ($pre_rated) { $root_classes .= ' is-unrated-full'; } $stars_html = ''; for ($i = 1; $i <= 5; $i++) { $is_filled = $pre_rated ? true : ($current >= $i); $cls = 'aieo-rating-star'; if ($is_filled) { $cls .= ' is-filled'; } $stars_html .= ''; } $fit_attrs = ''; if ('single' === $variant && has_action('rooster/fit/enqueue')) { do_action('rooster/fit/enqueue'); $fit_attrs = ' data-wp-interactive="rooster/fit" data-wp-init---rooster-fit="rooster/fit::callbacks.init" data-rooster-fit-room'; } $caption_html = '' . esc_html($caption) . ''; $anchor = 'single' === $variant ? ' id="' . esc_attr(self::RATE_ANCHOR) . '"' : ''; return '' . '
' . $stars_html . '
' . $caption_html . ''; } public function render_aggregate_html($product, $link = true) { $product_id = $this->resolve_product_id($product); if ($product_id <= 0) { return ''; } $settings = self::get_settings(); if (empty($settings['enabled'])) { return ''; } $stats = $this->get_stats($product_id); $count = (int) $stats['count']; if ($count < max(1, (int) $settings['min_votes_for_display'])) { return ''; } $this->enqueue_assets(true); $current = $this->get_current_rating_for_viewer( $product_id, get_current_user_id(), $this->read_session_token_no_create() ); $gated = !empty($settings['display_full_until_rated']) && $current === 0; $go = ''; if ($link) { $name = wp_strip_all_tags(html_entity_decode((string) get_the_title($product_id), ENT_QUOTES, 'UTF-8')); $go = '' . esc_html(sprintf(__('Rate %s on its page', 'ai-eshop-optimizer'), $name)) . ''; } $star = ''; if ($gated) { $inner = $star . '' . esc_html(self::caption_read_only($settings)) . '' . ('' !== $go ? '. ' . $go . '' : ''); } else { $avg = number_format_i18n((float) $stats['avg'], 1); $inner = $star . '' . '' . esc_html(self::compact_label($avg, $count)) . '' . ('' !== $go ? '. ' . $go : '') . ''; } $tag = $link ? 'a' : 'div'; return '<' . $tag . ($link ? ' href="' . esc_url(get_permalink($product_id) . '#' . self::RATE_ANCHOR) . '"' : '') . ' class="aieo-rating-aggregate' . ($gated ? ' is-gated' : '') . '" data-rooster-ui="rooster-one/ratings_display"' . ' data-aieo-rating-kind="product" data-aieo-rating-key="' . esc_attr((string) $product_id) . '" data-aieo-rating-read-only' . ' data-aieo-rating-product="' . esc_attr((string) $product_id) . '"' . ' data-aieo-rating-current="' . esc_attr((string) $current) . '"' . ' data-aieo-rating-avg="' . esc_attr((string) $stats['avg']) . '"' . ' data-aieo-rating-sum="' . esc_attr((string) $stats['sum']) . '"' . ' data-aieo-rating-count="' . esc_attr((string) $count) . '"' . '>' . $inner . ''; } public static function compact_label($avg, $count) { return sprintf(self::compact_format((int) $count), (string) $avg, number_format_i18n((int) $count)); } public static function compact_format($count) { return _n('Rated %1$s out of 5 from %2$s vote', 'Rated %1$s out of 5 from %2$s votes', (int) $count, 'ai-eshop-optimizer'); } public static function render_for($kind, $key, array $args = array()) { $self = self::instance(); $settings = self::get_settings(); if (empty($settings['enabled'])) { return ''; } $found = self::target($kind, (string) $key, false); if (null === $found) { return ''; } list($kind, $key, $id) = $found; if ('product' === $kind && 'summary' !== ($args['display'] ?? 'stars')) { return $self->render_stars_html((int) $key, 'single'); } $display = 'summary' === ($args['display'] ?? 'stars') ? 'summary' : 'stars'; $source = substr(sanitize_key((string) ($args['source'] ?? $display)), 0, 32); $label = isset($args['label']) ? (string) $args['label'] : ''; $self->enqueue_assets(true); $stats = $id > 0 ? $self->get_stats($id, $kind) : $self->empty_stats(); $current = $id > 0 ? $self->get_current_rating_for_viewer($id, get_current_user_id(), $self->read_session_token_no_create(), $kind) : 0; $gated = !empty($settings['display_full_until_rated']) && 0 === $current; $data = ' data-aieo-rating-kind="' . esc_attr($kind) . '" data-aieo-rating-key="' . esc_attr($key) . '"' . ' data-aieo-rating-source="' . esc_attr($source) . '"' . ' data-aieo-rating-current="' . esc_attr((string) $current) . '"' . ' data-aieo-rating-avg="' . esc_attr((string) $stats['avg']) . '"' . ' data-aieo-rating-sum="' . esc_attr((string) $stats['sum']) . '"' . ' data-aieo-rating-count="' . esc_attr((string) $stats['count']) . '"'; $stars = ''; for ($i = 1; $i <= 5; $i++) { $filled = $gated ? true : ($current >= $i); $stars .= ''; } $caption = $current > 0 ? $self->build_caption($stats, $settings) : self::caption_before_rated($settings); $label_id = '' !== $label ? wp_unique_id('aieo-rating-label-') : ''; $stacked = 'stacked' === ($args['layout'] ?? '') ? ' aieo-rating-stars--stacked' : ''; $block = '
' . ('stars' === $display && '' !== $label ? '' . esc_html($label) . '' : '') . '
' . $stars . '
' . '' . esc_html($caption) . '' . '
'; if ('stars' === $display) { return str_replace('{{aieo-attrs}}', '', $block); } $panel = wp_unique_id('aieo-rating-five-'); $count = (int) $stats['count']; $shown = !$gated && $count >= max(1, (int) $settings['min_votes_for_display']); $prompt = '' !== $label ? $label : _x('Rate', 'a button that opens five stars', 'ai-eshop-optimizer'); if ($shown) { $avg = number_format_i18n((float) $stats['avg'], 1); $value = '' . '' . esc_html(self::compact_label($avg, $count)) . '. ' . esc_html($prompt) . ''; } else { $value = '' . esc_html($prompt) . ''; } return '
' . '' . str_replace('{{aieo-attrs}}', ' id="' . esc_attr($panel) . '" hidden', $block) . '
'; } public static function enqueue() { self::instance()->enqueue_assets(true); } public function card_html($product) { if (is_callable(array('aieo_display_recommendations', 'rail_card_recipe'))) { $shop_card = 'archive' === aieo_display_recommendations::rail_card_recipe(); } else { $cards = get_option('aieo_dmm_product_card_settings', array()); $source = is_array($cards) && isset($cards['design_source']) ? (string) $cards['design_source'] : 'theme'; $shop_card = (class_exists('AIEO_Card') && AIEO_Card::shop_grids()) && 'aieo' !== $source; } return $shop_card ? $this->render_stars_html($product, 'archive') : $this->render_aggregate_html($product, false); } private function build_caption($stats, $settings) { $count = (int) $stats['count']; if ($count <= 0) { return ''; } $fmt = (string) $settings['caption_format']; if ($fmt === '') { return ''; } $avg = number_format_i18n((float) $stats['avg'], 1); return strtr($fmt, array( '%avg5' => $avg . '/5', '%avg' => $avg, '%count' => (string) $count, )); } private static function star_svg($extra_class = '') { $cls = 'aieo-rating-star-icon' . ($extra_class !== '' ? ' ' . $extra_class : ''); return ''; } private function resolve_product_id($product) { if (is_a($product, 'WC_Product')) { return (int) $product->get_id(); } return (int) $product; } private static $placed_in_card = array(); private static $slot_filled = array(); private static function is_card_group($block) { if (!is_array($block) || empty($block['blockName']) || 'core/group' !== $block['blockName']) { return false; } $class = isset($block['attrs']['className']) ? (string) $block['attrs']['className'] : ''; if ('' === $class) { return false; } $names = array('rooster-product-card', 'ff-product-card'); if (class_exists('AIEO_Theme_Adapters') && method_exists('AIEO_Theme_Adapters', 'class_map')) { $map = AIEO_Theme_Adapters::class_map(); if (!empty($map['product_card'])) { $names = array_filter((array) $map['product_card']); } } foreach ($names as $n) { if (preg_match('/(^|\s)' . preg_quote($n, '/') . '(\s|$)/', $class)) { return true; } } return false; } public function mark_card_rating_slot($parsed, $source = array(), $parent = null) { if (!is_array($parsed) || !isset($parsed['blockName']) || 'woocommerce/product-rating' !== $parsed['blockName']) { return $parsed; } if (!$parent instanceof WP_Block || !self::is_card_group($parent->parsed_block)) { return $parsed; } $parsed['attrs']['aieoCardSlot'] = true; return $parsed; } public function fill_card_rating_slot($html, $block, $instance = null) { if (empty($block['attrs']['aieoCardSlot'])) { return $html; } $pid = ($instance instanceof WP_Block && !empty($instance->context['postId'])) ? (int) $instance->context['postId'] : 0; if ($pid <= 0) { return $html; } $widget = $this->render_stars_html($pid, 'archive'); if ('' === $widget) { return $html; } self::$slot_filled[$pid] = true; return $widget; } public function place_in_theme_card($html, $block) { if (!is_string($html) || '' === $html || !self::is_card_group($block)) { return $html; } if (class_exists('AIEO_Card', false) && method_exists('AIEO_Card', 'plain') && AIEO_Card::plain()) { return $html; } global $product; if (!$product || !is_a($product, 'WC_Product')) { return $html; } $pid = (int) $product->get_id(); if (!empty(self::$slot_filled[$pid])) { unset(self::$slot_filled[$pid]); self::$placed_in_card[$pid] = true; return $html; } $widget = $this->render_stars_html($product, 'archive'); if ('' === $widget) { return $html; } $pos = strrpos($html, ''); if (false === $pos) { return $html; } self::$placed_in_card[(int) $product->get_id()] = true; return substr($html, 0, $pos) . $widget . substr($html, $pos); } public function render_loop_widget() { global $product; if (!$product || !is_a($product, 'WC_Product')) { return; } $pid = (int) $product->get_id(); if (!empty(self::$placed_in_card[$pid])) { unset(self::$placed_in_card[$pid]); return; } echo $this->render_stars_html($product, 'archive'); } public function render_single_widget() { global $product; if (!$product || !is_a($product, 'WC_Product')) { return; } echo $this->render_stars_html($product, 'single'); } public function shortcode_stars($atts = array()) { $atts = shortcode_atts(array( 'product_id' => 0, 'variant' => 'single', ), $atts, 'aieo_rating_stars'); $pid = (int) $atts['product_id']; if ($pid <= 0) { global $product; if ($product && is_a($product, 'WC_Product')) { $pid = (int) $product->get_id(); } } if ($pid <= 0) { return ''; } return $this->render_stars_html($pid, sanitize_key((string) $atts['variant'])); } public function shortcode_aggregate($atts = array()) { $atts = shortcode_atts(array('product_id' => 0), $atts, 'aieo_rating_aggregate'); $pid = (int) $atts['product_id']; if ($pid <= 0) { global $product; if ($product && is_a($product, 'WC_Product')) { $pid = (int) $product->get_id(); } } if ($pid <= 0) { return ''; } return $this->render_aggregate_html($pid); } public static function inline_css(array $settings) { $size_default = (int) $settings['size']; $size_mobile = (int) ($settings['size_mobile'] ?? 0); $size_single = (int) ($settings['size_single'] ?? 0); $gap_default = max(0, min(20, (int) ($settings['gap'] ?? 2))); $gap_mobile = (int) ($settings['gap_mobile'] ?? 0); $cap_d = max(8, min(48, (int) ($settings['caption_size'] ?? 13))); $cap_m = max(8, min(48, (int) ($settings['caption_size_mobile'] ?? 0) ?: $cap_d)); $cap_arch_d = max(8, min(48, (int) ($settings['caption_size_archive'] ?? 12))); $cap_arch_m = max(8, min(48, (int) ($settings['caption_size_archive_mobile'] ?? 0) ?: $cap_arch_d)); $css = sprintf( ':root{--aieo-rating-empty:%s;--aieo-rating-filled:%s;--aieo-rating-hover:%s;--aieo-rating-pre-rated:%s;--aieo-rating-size:%dpx;--aieo-rating-gap:%dpx;--aieo-rating-cap-fs:%dpx;--aieo-rating-cap-fs-arch:%dpx;}', esc_attr((string) $settings['color_empty']), esc_attr((string) $settings['color_filled']), esc_attr((string) $settings['color_hover']), esc_attr((string) $settings['color_pre_rated']), $size_default, $gap_default, $cap_d, $cap_arch_d ); $css .= self::chosen_colours_css($settings); $css .= sprintf( '@media (max-width:768px){:root{--aieo-rating-cap-fs:%dpx;--aieo-rating-cap-fs-arch:%dpx;}}', $cap_m, $cap_arch_m ); if ($size_single > 0) { $css .= sprintf('body.single-product{--aieo-rating-size:%dpx;--aieo-rating-gap:%dpx;}', $size_single, max($gap_default, 24 - $size_single)); } if ($size_mobile > 0 && $size_mobile !== $size_default) { $css .= sprintf('@media (max-width:768px){:root{--aieo-rating-size:%dpx;}}', $size_mobile); } if ($gap_mobile > 0 && $gap_mobile !== $gap_default) { $gap_mobile = max(0, min(20, $gap_mobile)); $css .= sprintf('@media (max-width:768px){:root{--aieo-rating-gap:%dpx;}}', $gap_mobile); } if ($size_mobile > 0) { $gm = ($gap_mobile > 0) ? $gap_mobile : $gap_default; $css .= sprintf('@media (max-width:768px){body.single-product{--aieo-rating-gap:%dpx;}}', max($gm, 24 - $size_mobile)); } if ($size_single > 0) { $gap_single = max(0, min(20, (int) ($settings['gap_single'] ?? 4))); $css .= sprintf('.aieo-rating-stars--single,html[data-rooster-design="theme"] .aieo-rating-stars.aieo-rating-stars--single{--aieo-rating-size:%dpx;--aieo-rating-gap:%dpx;}', $size_single, $gap_single); } $size_archive = max(0, min(96, (int) ($settings['size_archive'] ?? 0))); if ($size_archive > 0) { $gap_archive = max(0, min(20, (int) ($settings['gap_archive'] ?? 4))); $css .= sprintf('.aieo-rating-stars--archive,.aieo-rating-aggregate,html[data-rooster-design="theme"] .aieo-rating-stars.aieo-rating-stars--archive,html[data-rooster-design="theme"] .aieo-rating-aggregate.aieo-rating-aggregate{--aieo-rating-size:%dpx;--aieo-rating-gap:%dpx;}', $size_archive, $gap_archive); } return $css; } public static function page_shows_products() { if (!function_exists('is_woocommerce') || is_admin()) { return false; } return is_singular('product') || is_shop() || is_product_taxonomy() || (is_search() && 'product' === get_query_var('post_type')); } public function enqueue_assets($force = false) { static $done = false; if ($done) { return; } if (!$force && !self::page_shows_products()) { return; } $done = true; if (is_admin()) { return; } $settings = self::get_settings(); if (empty($settings['enabled'])) { return; } $current_user_id = get_current_user_id(); $css_uri = ''; $css_path = ''; if (defined('AIEO_RUNTIME_URI') && defined('AIEO_RUNTIME_DIR')) { $candidate_path = AIEO_RUNTIME_DIR . 'assets/css/aieo-rating-stars.css'; if (file_exists($candidate_path)) { $css_uri = AIEO_RUNTIME_URI . 'assets/css/aieo-rating-stars.css'; $css_path = $candidate_path; } } if (!$css_path) { $candidate_path = AIEO_DIR . 'assets/css/aieo-rating-stars.css'; if (file_exists($candidate_path)) { $css_uri = AIEO_URI . 'assets/css/aieo-rating-stars.css'; $css_path = $candidate_path; } } $css_ver = $css_path ? (string) filemtime($css_path) : AIEO_VERSION; if ($css_uri && $css_path && file_exists($css_path)) { wp_enqueue_style('aieo-rating-stars', $css_uri, array(), $css_ver); wp_add_inline_style('aieo-rating-stars', self::inline_css($settings)); } $payload = array( 'routes' => array( 'vote' => esc_url_raw(rest_url('aieo/v1/ratings/vote')), 'mine' => esc_url_raw(rest_url('aieo/v1/ratings/mine')), 'batch' => esc_url_raw(rest_url('aieo/v1/ratings/batch')), ), 'restNonce' => $current_user_id > 0 ? wp_create_nonce('wp_rest') : '', 'isLoggedIn' => $current_user_id > 0, 'requireLogin' => !empty($settings['require_login']), 'loginUrl' => wp_login_url(), 'loginRedirectMode' => (string) $settings['login_redirect_mode'], 'allowClear' => !empty($settings['allow_clear']), 'captionFormat' => (string) $settings['caption_format'], 'captionBeforeRated' => self::caption_before_rated($settings), 'minVotesForDisplay' => (int) $settings['min_votes_for_display'], 'gated' => !empty($settings['display_full_until_rated']), 'compactOne' => self::compact_format(1), 'compactMany' => self::compact_format(2), ); $js_path = ''; $js_uri = ''; if (defined('AIEO_RUNTIME_DIR') && defined('AIEO_RUNTIME_URI')) { $cand = AIEO_RUNTIME_DIR . 'assets/js/aieo-rating-stars.js'; if (file_exists($cand)) { $js_path = $cand; $js_uri = AIEO_RUNTIME_URI . 'assets/js/aieo-rating-stars.js'; } } if (!$js_path) { $cand = AIEO_DIR . 'assets/js/aieo-rating-stars.js'; if (file_exists($cand)) { $js_path = $cand; $js_uri = AIEO_URI . 'assets/js/aieo-rating-stars.js'; } } if ($js_path) { wp_enqueue_script('aieo-rating-stars', $js_uri, array(), (string) filemtime($js_path), array('in_footer' => true, 'strategy' => 'defer')); wp_localize_script('aieo-rating-stars', 'aieoRatings', $payload); } } public static function person($email) { $email = strtolower(trim((string) $email)); $person = array('user' => 0, 'visitors' => array(), 'invitees' => array()); if ('' === $email || !is_email($email)) { return $person; } if (class_exists('AIEO_Signal_Privacy') && method_exists('AIEO_Signal_Privacy', 'person')) { $found = AIEO_Signal_Privacy::person($email); $person['user'] = (int) ($found['user'] ?? 0); $person['visitors'] = array_values(array_filter(array_map('strval', (array) ($found['visitor'] ?? array())))); } else { $user = get_user_by('email', $email); $person['user'] = $user ? (int) $user->ID : 0; } $person = (array) apply_filters('aieo_rating_person', $person, $email); return array( 'user' => max(0, (int) ($person['user'] ?? 0)), 'visitors' => array_slice(array_values(array_unique(array_filter(array_map('strval', (array) ($person['visitors'] ?? array()))))), 0, 500), 'invitees' => array_slice(array_values(array_unique(array_filter(array_map('intval', (array) ($person['invitees'] ?? array()))))), 0, 500), ); } private static function person_sql(array $person) { global $wpdb; $any = array(); if ($person['user'] > 0) { $any[] = $wpdb->prepare('user_id = %d', $person['user']); } if ($person['visitors']) { $any[] = $wpdb->prepare('visitor_id IN (' . implode(',', array_fill(0, count($person['visitors']), '%s')) . ')', $person['visitors']); } if ($person['invitees']) { $any[] = 'invitee_id IN (' . implode(',', array_map('intval', $person['invitees'])) . ')'; } return $any ? '(' . implode(' OR ', $any) . ')' : ''; } public static function register_exporter($exporters) { $exporters['aieo-ratings'] = array( 'exporter_friendly_name' => __('Star ratings (Rooster One)', 'ai-eshop-optimizer'), 'callback' => array(__CLASS__, 'export_votes'), ); return $exporters; } public static function register_eraser($erasers) { $erasers['aieo-ratings'] = array( 'eraser_friendly_name' => __('Star ratings (Rooster One)', 'ai-eshop-optimizer'), 'callback' => array(__CLASS__, 'erase_votes'), ); return $erasers; } public static function export_votes($email, $page = 1) { global $wpdb; $where = self::person_sql(self::person($email)); if ('' === $where) { return array('data' => array(), 'done' => true); } $per = 200; $offset = max(0, ((int) $page - 1) * $per); $rows = (array) $wpdb->get_results($wpdb->prepare("SELECT id, object_type, product_id, variant, options, rating, page_url, source, created_at FROM " . self::events_table() . " WHERE {$where} ORDER BY id LIMIT %d OFFSET %d", $per, $offset), ARRAY_A); $data = array(); foreach ($rows as $r) { $key = (string) $r['product_id']; if (!in_array((string) $r['object_type'], array('product', 'brand'), true) && class_exists('AIEO_Targets')) { $named = AIEO_Targets::key((int) $r['product_id']); $key = isset($named['key']) ? $named['key'] : $key; } $data[] = array( 'group_id' => 'aieo-ratings', 'group_label' => __('Star ratings', 'ai-eshop-optimizer'), 'item_id' => 'aieo-rating-' . (int) $r['id'], 'data' => array( array('name' => __('What was rated', 'ai-eshop-optimizer'), 'value' => (string) $r['object_type'] . ': ' . $key), array('name' => __('Stars', 'ai-eshop-optimizer'), 'value' => (string) (int) $r['rating']), array('name' => __('Options', 'ai-eshop-optimizer'), 'value' => (string) $r['options']), array('name' => __('Page', 'ai-eshop-optimizer'), 'value' => (string) $r['page_url']), array('name' => __('Date', 'ai-eshop-optimizer'), 'value' => (string) $r['created_at'] . ' UTC'), ), ); } return array('data' => $data, 'done' => count($rows) < $per); } public static function erase_votes($email, $page = 1) { global $wpdb; unset($page); $where = self::person_sql(self::person($email)); $out = array('items_removed' => false, 'items_retained' => false, 'messages' => array(), 'done' => true); if ('' === $where) { return $out; } $events = self::events_table(); $rows = (array) $wpdb->get_results("SELECT id, object_type, product_id FROM {$events} WHERE {$where} ORDER BY id LIMIT 500", ARRAY_A); if (!$rows) { return $out; } $ids = array_map(static function ($r) { return (int) $r['id']; }, $rows); $targets = array(); foreach ($rows as $r) { $targets[(string) $r['object_type']][(int) $r['product_id']] = true; } $wpdb->query("DELETE FROM {$events} WHERE id IN (" . implode(',', $ids) . ')'); foreach ($targets as $kind => $by) { self::instance()->recompute_stats(array_keys($by), $kind); } $out['items_removed'] = true; $out['done'] = count($rows) < 500; return $out; } } }