array('action' => 'woocommerce_single_product_summary', 'priority' => 4),
'after_title' => array('action' => 'woocommerce_single_product_summary', 'priority' => 6),
'after_price' => array('action' => 'woocommerce_single_product_summary', 'priority' => 11),
'after_excerpt' => array('action' => 'woocommerce_single_product_summary', 'priority' => 21),
'after_add_to_cart' => array('action' => 'woocommerce_single_product_summary', 'priority' => 35),
'after_meta' => array('action' => 'woocommerce_single_product_summary', 'priority' => 41),
'before_add_to_cart' => array('action' => 'woocommerce_before_add_to_cart_form', 'priority' => 10),
'after_add_to_cart_btn' => array('action' => 'woocommerce_after_add_to_cart_button', 'priority' => 10),
);
}
public static function get_table_name() {
global $wpdb;
return $wpdb->prefix . 'aieo_wishlist';
}
public function maybe_install() {
$installed = get_option(self::SCHEMA_OPTION, '');
if ($installed === self::SCHEMA_VERSION) {
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;
$table = self::get_table_name();
$charset = function_exists('aieo_get_charset_collate') ? aieo_get_charset_collate() : $wpdb->get_charset_collate();
$sql = "CREATE TABLE {$table} (
id bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
user_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
session_id varchar(64) NOT NULL DEFAULT '',
item_id bigint(20) UNSIGNED NOT NULL,
item_type varchar(20) NOT NULL DEFAULT 'product',
source_type varchar(50) NOT NULL DEFAULT '',
source_id bigint(20) UNSIGNED NOT NULL DEFAULT 0,
source_name varchar(255) NOT NULL DEFAULT '',
date_added datetime NOT NULL,
price_at_wishlist decimal(10,2) NULL DEFAULT NULL,
PRIMARY KEY (id),
KEY user_id (user_id),
KEY session_id (session_id),
KEY item_id (item_id),
UNIQUE KEY user_item (user_id, session_id, item_id, item_type)
) {$charset};";
if (!function_exists('dbDelta')) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
dbDelta($sql);
$col = $wpdb->get_var("SHOW COLUMNS FROM {$table} LIKE 'price_at_wishlist'");
if (!$col) {
$wpdb->query("ALTER TABLE {$table} ADD COLUMN price_at_wishlist DECIMAL(10,2) NULL DEFAULT NULL AFTER date_added");
}
}
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) {
if (is_admin()) {
return;
}
$aieo_ver = defined('AIEO_VERSION') ? AIEO_VERSION : (defined('AIEO_RUNTIME_VERSION') ? AIEO_RUNTIME_VERSION : '0.0.0');
$aieo_file = defined('AIEO_FILE') ? AIEO_FILE : (defined('AIEO_RUNTIME_FILE') ? AIEO_RUNTIME_FILE : __FILE__);
$payload = array(
'ajaxUrl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('aieo_wishlist'),
'cookie' => self::COOKIE_NAME,
'enabledTypes' => self::enabled_types_list(),
);
wp_register_script('aieo-wishlist-globals', '', array(), $aieo_ver, false);
wp_enqueue_script('aieo-wishlist-globals');
wp_add_inline_script(
'aieo-wishlist-globals',
'window.aieoWishlist = ' . wp_json_encode($payload) . ';',
'before'
);
static $assets_done = false;
if ($assets_done) { return; }
if (!$force && !self::page_shows_products()) { return; }
$assets_done = true;
$css_rel = 'assets/css/aieo-wishlist-heart.css';
$js_rel = 'assets/js/aieo-wishlist-heart.js';
$css_path = dirname($aieo_file) . '/' . $css_rel;
$js_path = dirname($aieo_file) . '/' . $js_rel;
$css_ver = file_exists($css_path) ? filemtime($css_path) : $aieo_ver;
$js_ver = file_exists($js_path) ? filemtime($js_path) : $aieo_ver;
wp_enqueue_style('aieo-wishlist-heart', plugins_url($css_rel, $aieo_file), array(), $css_ver);
$iapi_on = method_exists('AIEO_DMM', 'is_iapi_enabled') && AIEO_DMM::is_iapi_enabled('wishlist');
if ($iapi_on
&& defined('AIEO_RUNTIME_DIR')
&& file_exists(AIEO_RUNTIME_DIR . 'assets/js/aieo-wishlist-iapi.js')
) {
wp_register_script_module(
'@aieo/wishlist-iapi',
AIEO_Asset_Min::module_src(AIEO_RUNTIME_DIR . 'assets/js/aieo-wishlist-iapi.js', AIEO_RUNTIME_URI . 'assets/js/aieo-wishlist-iapi.js'),
array('@wordpress/interactivity', '@aieo/iapi-bootstrap'),
(string) filemtime(AIEO_RUNTIME_DIR . 'assets/js/aieo-wishlist-iapi.js'),
array( 'fetchpriority' => 'low' )
);
AIEO_Asset_Min::defer_module('@aieo/wishlist-iapi', AIEO_Asset_Min::module_src(AIEO_RUNTIME_DIR . 'assets/js/aieo-wishlist-iapi.js', AIEO_RUNTIME_URI . 'assets/js/aieo-wishlist-iapi.js'), (string) filemtime(AIEO_RUNTIME_DIR . 'assets/js/aieo-wishlist-iapi.js'));
} else {
wp_enqueue_script('aieo-wishlist-heart', plugins_url($js_rel, $aieo_file), array('jquery'), $js_ver, array('in_footer' => true, 'strategy' => 'defer'));
}
$d = self::get_display_settings();
list($filled, $hover) = self::heart_colours();
$size_desktop = (int) $d['size'];
$size_mobile = (int) ($d['size_mobile'] ?? 0);
wp_add_inline_style('aieo-wishlist-heart', sprintf(
'.aieo-wishlist-heart,.aieo-wishlist-heart-wrap{'
. '--aieo-wl-empty:%s;--aieo-wl-filled:%s;--aieo-wl-hover:%s;'
. '--aieo-wl-size:%dpx;--aieo-wl-card-box:%dpx;}',
esc_attr($d['color_empty']),
esc_attr($filled),
esc_attr($hover),
$size_desktop,
max(32, min(56, (int) ($d['card_box'] ?? 44)))
));
if ($size_mobile > 0 && $size_mobile !== $size_desktop) {
wp_add_inline_style('aieo-wishlist-heart', sprintf(
'@media (max-width:768px){.aieo-wishlist-heart{--aieo-wl-size:%dpx;}}',
$size_mobile
));
}
wp_add_inline_style('aieo-wishlist-heart',
'.aieo-sc-fav-section{margin:0 0 16px;}'
. '.aieo-sc-fav-section__title{margin:0 0 8px;font-size:11px;font-weight:600;letter-spacing:.08em;text-transform:uppercase;color:#9ca3af;}'
. '.aieo-sc-fav-brand-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px;}'
. '.aieo-sc-fav-brand{margin:0;}'
. '.aieo-sc-fav-brand__link{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid #e5e7eb;border-radius:8px;text-decoration:none;color:#1f2937;background:#fff;transition:border-color 120ms ease,transform 120ms ease;}'
. '.aieo-sc-fav-brand__link:hover{border-color:#F46767;transform:translateY(-1px);}'
. '.aieo-sc-fav-brand__logo{flex:0 0 40px;width:40px;height:40px;display:flex;align-items:center;justify-content:center;background:#f9fafb;border-radius:6px;overflow:hidden;font-weight:700;color:#F46767;font-size:18px;}'
. '.aieo-sc-fav-brand__logo img{max-width:100%;max-height:100%;object-fit:contain;}'
. '.aieo-sc-fav-brand__body{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1 1 auto;}'
. '.aieo-sc-fav-brand__name{font-weight:600;font-size:13px;text-overflow:ellipsis;overflow:hidden;white-space:nowrap;text-transform:uppercase;letter-spacing:.02em;}'
. '.aieo-sc-fav-brand__meta{font-size:11px;color:#6b7280;}'
);
$wishlist_url = !empty($d['wishlist_page_id'])
? (string) get_permalink((int) $d['wishlist_page_id'])
: '';
$heart_data = array(
'tooltipAdd' => (string) $d['tooltip_add'],
'tooltipRemove' => (string) $d['tooltip_remove'],
'showTooltip' => !empty($d['show_tooltip']) && $d['show_tooltip'] === 'yes',
'wishlistUrl' => $wishlist_url,
'archivePosition'=> (string) $d['archive_position'],
);
if ($iapi_on) {
add_action('wp_print_footer_scripts', static function () use ($heart_data) {
echo '' . "\n";
}, 5);
} else {
wp_localize_script('aieo-wishlist-heart', 'aieoWishlistHeart', $heart_data);
}
}
public static function get_display_settings($raw = false) {
$stored = get_option(self::DISPLAY_OPTION, array());
if (!is_array($stored)) { $stored = array(); }
$merged = array_merge(array(
'color_empty' => '#c0c4c9',
'color_filled' => '#dd1419',
'color_hover' => '#b3101a',
'size' => 22,
'size_mobile' => 18,
'tooltip_add' => '',
'tooltip_remove' => '',
'show_tooltip' => 'yes',
'show_on_single' => 'yes',
'show_on_archive' => 'yes',
'single_placement' => 'after_add_to_cart',
'archive_position' => 'top-right',
'ring' => 'no',
'fill' => 'page',
'card_box' => 44,
'line' => 'plain',
'wishlist_page_id' => 0,
'single_label_add' => '',
'single_label_view' => '',
'single_show_label' => 'yes',
'wishlist_type_product' => 'yes',
'wishlist_type_brand' => 'yes',
'wishlist_type_category' => 'yes',
'wishlist_type_need' => 'yes',
'wishlist_type_blogpost' => 'yes',
), $stored);
return $raw ? $merged : self::fill_i18n_defaults($merged);
}
private static function fill_i18n_defaults(array $s) {
if (!did_action('init')) { return $s; }
$i18n = array(
'tooltip_add' => __('Add to wishlist', 'ai-eshop-optimizer'),
'tooltip_remove' => __('Remove from wishlist', 'ai-eshop-optimizer'),
'single_label_add' => __('Add to your favourites', 'ai-eshop-optimizer'),
'single_label_view' => __('See your favourites', 'ai-eshop-optimizer'),
);
foreach ($i18n as $k => $v) {
if (!isset($s[$k]) || '' === trim((string) $s[$k])) { $s[$k] = $v; }
}
return $s;
}
public function render_single_heart() {
global $product;
if (!$product || !is_a($product, 'WC_Product')) { return; }
if ($this->in_title_row) { return; }
echo $this->build_heart_html($product, 'single_product');
}
private $in_title_row = false;
public function title_row_heart_html() {
$d = self::get_display_settings();
if (!self::is_type_enabled('product') || empty($d['show_on_single']) || $d['show_on_single'] !== 'yes') { return ''; }
$product = function_exists('wc_get_product') ? wc_get_product(get_the_ID()) : null;
if (!$product || !is_a($product, 'WC_Product')) { return ''; }
$this->in_title_row = true;
return ''
. $this->build_heart_html($product, 'single_product', false)
. '';
}
public function render_loop_heart() {
global $product;
if (!$product || !is_a($product, 'WC_Product')) { return; }
echo $this->build_heart_html($product, 'archive');
}
private $collections = array();
public function card_collection_enter($parsed) {
if (is_array($parsed) && 'woocommerce/product-collection' === ($parsed['blockName'] ?? '')) {
$this->collections[] = !empty($parsed['attrs']['query']['inherit']);
}
return $parsed;
}
public function card_collection_leave($html) {
array_pop($this->collections);
return $html;
}
public function card_picture_heart($html, $block, $instance = null) {
if (array() === $this->collections || end($this->collections)) {
return $html;
}
if (false === strpos((string) $html, 'data-is-descendent-of-query-loop="true"') || false !== strpos((string) $html, 'aieo-wishlist-heart')) {
return $html;
}
$pid = ($instance instanceof WP_Block && !empty($instance->context['postId'])) ? (int) $instance->context['postId'] : 0;
$product = $pid > 0 && function_exists('wc_get_product') ? wc_get_product($pid) : null;
if (!$product || !is_a($product, 'WC_Product')) {
return $html;
}
$at = strrpos((string) $html, '');
if (false === $at) {
return $html;
}
return substr((string) $html, 0, $at) . $this->build_heart_html($product, 'archive') . substr((string) $html, $at);
}
private function build_heart_html($product, $source_type, $with_label = true) {
$this->enqueue_assets(true);
$pid = (int) $product->get_id();
$ids = $this->get_items_for_viewer(get_current_user_id(), 'product');
$in_list = in_array($pid, array_map('intval', (array) $ids), true);
$cookie = $this->cookie_ids();
if (!$in_list && in_array($pid, $cookie, true)) { $in_list = true; }
return $this->heart_html((string) $pid, $in_list, $source_type, $with_label);
}
public function archive_heart_template() {
$d = self::get_display_settings();
if (!self::is_type_enabled('product') || empty($d['show_on_archive']) || 'yes' !== $d['show_on_archive'] || !self::archive_cards_ours()) {
return '';
}
$this->enqueue_assets(true);
return $this->heart_html('{id}', false, 'archive', false);
}
private static function heart_svg($d, $stroke) {
return '';
}
private function heart_html($pid, $in_list, $source_type, $with_label) {
$d = self::get_display_settings();
$classes = 'aieo-wishlist-heart';
$classes .= ' aieo-wishlist-heart--' . $source_type;
if ($source_type === 'archive') {
$classes .= ' aieo-wishlist-pos-' . sanitize_html_class($d['archive_position']);
}
if ('yes' === (string) $d['ring']) { $classes .= ' aieo-wishlist-heart--ring'; }
if (in_array((string) $d['fill'], array('theme', 'white', 'page'), true)) { $classes .= ' aieo-wishlist-heart--fill-' . $d['fill']; }
if ('embossed' === (string) ($d['line'] ?? 'plain')) { $classes .= ' aieo-wishlist-heart--embossed'; }
if ($in_list) { $classes .= ' is-in-list'; }
$tooltip = $in_list ? (string) $d['tooltip_remove'] : (string) $d['tooltip_add'];
$btn = '';
if ($source_type !== 'single_product' || !$with_label) {
return $btn;
}
if (empty($d['single_show_label']) || $d['single_show_label'] !== 'yes') {
return $btn;
}
$label_text = $in_list ? (string) $d['single_label_view'] : (string) $d['single_label_add'];
$label_html = ''
. esc_html($label_text)
. '';
return '
'
. $btn . $label_html
. '
';
}
public function ajax_toggle() {
check_ajax_referer('aieo_wishlist', 'nonce');
$item_id = isset($_POST['item_id']) ? absint(wp_unslash($_POST['item_id'])) : 0;
if (!$item_id) {
$item_id = isset($_POST['product_id']) ? absint(wp_unslash($_POST['product_id'])) : 0;
}
if (!$item_id) {
wp_send_json_error(array('message' => __('Invalid item ID.', 'ai-eshop-optimizer')));
}
$item_type = isset($_POST['item_type']) ? sanitize_key((string) $_POST['item_type']) : 'product';
$valid_types = (array) apply_filters(
'aieo_wishlist_valid_item_types',
array('product', 'post', 'archive', 'page', 'brand', 'product_cat', 'pa-need')
);
if ($item_type !== '' && !self::is_type_enabled($item_type)) {
wp_send_json_error(array('message' => __('This wishlist type is disabled.', 'ai-eshop-optimizer')));
}
if (!in_array($item_type, $valid_types, true)) {
$item_type = 'product';
}
if ($item_type === 'product') {
$post_type = get_post_type($item_id);
if ($post_type !== 'product' && $post_type !== 'product_variation') {
wp_send_json_error(array('message' => __('Invalid product ID.', 'ai-eshop-optimizer')));
}
} elseif ($item_type === 'post') {
if ('post' !== get_post_type($item_id) || 'publish' !== get_post_status($item_id)) {
wp_send_json_error(array('message' => __('Invalid post ID.', 'ai-eshop-optimizer')));
}
} else {
$taxonomy = self::taxonomy_for_item_type($item_type);
if ($taxonomy !== '' && !term_exists($item_id, $taxonomy)) {
wp_send_json_error(array('message' => sprintf(
__('Invalid %s term ID.', 'ai-eshop-optimizer'),
$item_type
)));
}
}
$action_type = isset($_POST['wishlist_action']) ? sanitize_key((string) $_POST['wishlist_action']) : 'add';
if ($action_type !== 'add' && $action_type !== 'remove') {
$action_type = 'add';
}
$source_type = isset($_POST['source_type']) ? sanitize_key((string) $_POST['source_type']) : '';
$source_id = isset($_POST['source_id']) ? absint(wp_unslash($_POST['source_id'])) : 0;
$source_name = isset($_POST['source_name']) ? sanitize_text_field((string) wp_unslash($_POST['source_name'])) : '';
$user_id = get_current_user_id();
if ($action_type === 'add') {
$this->add_item($item_id, $item_type, $user_id, $source_type, $source_id, $source_name);
} else {
$this->remove_item($item_id, $item_type, $user_id);
}
if ($item_type === 'product') {
$cookie = $this->cookie_ids();
if ($action_type === 'add' && !in_array($item_id, $cookie, true)) {
$cookie[] = $item_id;
} elseif ($action_type === 'remove') {
$cookie = array_values(array_diff($cookie, array($item_id)));
}
$this->write_cookie($cookie);
wp_send_json_success(array(
'count' => count($cookie),
'action' => $action_type,
'in_list' => in_array($item_id, $cookie, true),
'item_type' => $item_type,
));
}
if ($user_id <= 0 && in_array($item_type, array('brand', 'product_cat', 'pa-need', 'post'), true)) {
$item = $item_type . '.' . $item_id;
$items = array_values(array_diff($this->fav_cookie_items(), array($item)));
if ($action_type === 'add') {
array_unshift($items, $item);
}
$this->write_fav_cookie($items);
}
wp_send_json_success(array(
'action' => $action_type,
'in_list' => $action_type === 'add',
'item_id' => $item_id,
'item_type' => $item_type,
));
}
public function ajax_get() {
check_ajax_referer('aieo_wishlist', 'nonce');
$item_type = isset($_POST['item_type']) ? sanitize_key((string) $_POST['item_type']) : 'product';
$user_id = get_current_user_id();
$ids = $this->get_items_for_viewer($user_id, $item_type);
wp_send_json_success(array(
'ids' => array_values($ids),
'count' => count($ids),
));
}
public static function taxonomy_for_item_type($item_type) {
switch ((string) $item_type) {
case 'brand': return 'product_brand';
case 'product_cat': return 'product_cat';
case 'pa-need': return 'pa_need';
}
return '';
}
public static function type_setting_key($item_type) {
switch ((string) $item_type) {
case 'product': return 'wishlist_type_product';
case 'brand': return 'wishlist_type_brand';
case 'product_cat': return 'wishlist_type_category';
case 'pa-need': return 'wishlist_type_need';
case 'post': return 'wishlist_type_blogpost';
}
return '';
}
public static function is_type_enabled($item_type) {
$key = self::type_setting_key($item_type);
if ($key === '') { return true; }
$d = self::get_display_settings();
return !isset($d[$key]) || $d[$key] === 'yes';
}
public static function enabled_types_list() {
$all = array('product', 'brand', 'product_cat', 'pa-need', 'post');
return array_values(array_filter($all, array(__CLASS__, 'is_type_enabled')));
}
public static function filter_enabled_types($types) {
return array_values(array_filter((array) $types, array(__CLASS__, 'is_type_enabled')));
}
public function ajax_get_followed_items() {
check_ajax_referer('aieo_wishlist', 'nonce');
$item_type = isset($_POST['item_type']) ? sanitize_key((string) $_POST['item_type']) : 'brand';
$valid = (array) apply_filters(
'aieo_wishlist_followed_items_types',
array('brand', 'product_cat', 'pa-need', 'post')
);
if (!in_array($item_type, $valid, true)) {
wp_send_json_error(array('message' => __('Unsupported item_type.', 'ai-eshop-optimizer')));
}
$user_id = get_current_user_id();
$ids = $this->get_items_for_viewer($user_id, $item_type);
$items = self::shape_items_for_type($item_type, $ids);
wp_send_json_success(array(
'item_type' => $item_type,
'items' => $items,
'count' => count($items),
));
}
public function ajax_get_followed_brands() {
check_ajax_referer('aieo_wishlist', 'nonce');
$user_id = get_current_user_id();
$ids = $this->get_items_for_viewer($user_id, 'brand');
$brands = self::shape_items_for_type('brand', $ids);
wp_send_json_success(array('brands' => $brands, 'count' => count($brands)));
}
public static function shape_items_for_type($item_type, array $ids) {
$ids = array_values(array_filter(array_map('intval', $ids), function ($v) { return $v > 0; }));
if (empty($ids)) { return array(); }
if ($item_type === 'brand' && class_exists('AIEO_Core_Brand_Vitals')) {
$rows = AIEO_Core_Brand_Vitals::instance()->get_by_ids($ids);
$out = array();
foreach ($rows as $b) {
$out[] = array(
'id' => (int) $b['term_id'],
'name' => (string) $b['name'],
'permalink' => (string) $b['permalink'],
'logo_url' => (string) $b['logo_url'],
'count' => (int) $b['product_count'],
'item_type' => 'brand',
);
}
return apply_filters('aieo_wishlist_shape_items', $out, $item_type, $ids);
}
if ($item_type === 'post') {
$out = array();
foreach ($ids as $pid) {
$post = get_post($pid);
if (!$post || $post->post_status !== 'publish') { continue; }
$thumb = (string) get_the_post_thumbnail_url($pid, 'medium');
$excerpt = wp_strip_all_tags((string) get_the_excerpt($pid));
$out[] = array(
'id' => (int) $post->ID,
'name' => (string) get_the_title($pid),
'permalink' => (string) get_permalink($pid),
'logo_url' => $thumb,
'excerpt' => wp_trim_words($excerpt, 14),
'count' => 0,
'item_type' => 'post',
);
}
return apply_filters('aieo_wishlist_shape_items', $out, $item_type, $ids);
}
$taxonomy = self::taxonomy_for_item_type($item_type);
$out = array();
if ($taxonomy !== '') {
foreach ($ids as $tid) {
$term = get_term($tid, $taxonomy);
if (!$term || is_wp_error($term)) { continue; }
$thumb_id = (int) get_term_meta($tid, 'thumbnail_id', true);
$thumb = $thumb_id > 0 ? (string) wp_get_attachment_image_url($thumb_id, 'medium') : '';
$out[] = array(
'id' => (int) $term->term_id,
'name' => (string) $term->name,
'permalink' => is_wp_error(get_term_link($term)) ? '' : (string) get_term_link($term),
'logo_url' => $thumb,
'count' => (int) ($term->count ?? 0),
'item_type' => $item_type,
);
}
}
return apply_filters('aieo_wishlist_shape_items', $out, $item_type, $ids);
}
public function add_item($item_id, $item_type, $user_id, $source_type = '', $source_id = 0, $source_name = '') {
global $wpdb;
$this->viewer_rows = array();
$item_id = (int) $item_id;
if ($item_id <= 0) { return false; }
$session_id = $user_id ? '' : $this->get_or_create_session_id();
$exists = (int) $wpdb->get_var($wpdb->prepare(
"SELECT id FROM " . self::get_table_name() . "
WHERE user_id = %d AND session_id = %s AND item_id = %d AND item_type = %s
LIMIT 1",
$user_id, $session_id, $item_id, $item_type
));
if ($exists > 0) { return $exists; }
$price_at_wishlist = null;
if (function_exists('wc_get_product') && $item_type === 'product') {
$product = wc_get_product($item_id);
if ($product) {
$p = (float) $product->get_price();
if ($p > 0) { $price_at_wishlist = round($p, 2); }
}
}
$wpdb->insert(
self::get_table_name(),
array(
'user_id' => (int) $user_id,
'session_id' => (string) $session_id,
'item_id' => $item_id,
'item_type' => $item_type,
'source_type' => (string) $source_type,
'source_id' => (int) $source_id,
'source_name' => (string) $source_name,
'date_added' => current_time('mysql', true),
'price_at_wishlist' => $price_at_wishlist,
),
array('%d', '%s', '%d', '%s', '%s', '%d', '%s', '%s', '%f')
);
$insert_id = (int) $wpdb->insert_id;
self::flush_cache();
do_action('aieo_wishlist_item_added', $insert_id, $item_id, $item_type, (int) $user_id, $session_id);
return $insert_id;
}
public function remove_item($item_id, $item_type, $user_id) {
$this->viewer_rows = array();
global $wpdb;
$item_id = (int) $item_id;
if ($item_id <= 0) { return 0; }
$session_id = $user_id ? '' : $this->get_or_create_session_id();
$deleted = (int) $wpdb->delete(
self::get_table_name(),
array(
'user_id' => (int) $user_id,
'session_id' => (string) $session_id,
'item_id' => $item_id,
'item_type' => $item_type,
),
array('%d', '%s', '%d', '%s')
);
self::flush_cache();
return $deleted;
}
public function get_items_for_viewer($user_id, $item_type = 'product') {
global $wpdb;
$user_id = (int) $user_id;
$rows = array();
$session_id = $user_id > 0 ? '' : $this->get_or_create_session_id();
$memo = ($user_id > 0 ? 'u' . $user_id : 's' . $session_id) . '|' . $item_type;
if (isset($this->viewer_rows[$memo])) {
$rows = $this->viewer_rows[$memo];
} elseif ($user_id > 0) {
$rows = $this->user_item_ids($user_id, $item_type);
} else {
if ($session_id !== '') {
$rows = $wpdb->get_col($wpdb->prepare(
"SELECT item_id FROM " . self::get_table_name() . "
WHERE user_id = 0 AND session_id = %s AND item_type = %s
ORDER BY date_added DESC",
$session_id, $item_type
));
}
}
$rows = array_map('intval', (array) $rows);
$this->viewer_rows[$memo] = $rows;
if ($item_type === 'product' && $user_id <= 0) {
$cookie = $this->cookie_ids();
foreach ($cookie as $cid) {
if (!in_array($cid, $rows, true)) {
$rows[] = $cid;
}
}
}
return $rows;
}
private function user_item_ids($user_id, $item_type) {
global $wpdb;
$key = 'u' . (int) $user_id . '|' . $item_type . '|' . wp_cache_get_last_changed(self::CACHE_GROUP);
$ids = wp_cache_get($key, self::CACHE_GROUP);
if (!is_array($ids)) {
$ids = array_map('intval', (array) $wpdb->get_col($wpdb->prepare(
"SELECT item_id FROM " . self::get_table_name() . "
WHERE user_id = %d AND item_type = %s
ORDER BY date_added DESC",
(int) $user_id, $item_type
)));
wp_cache_set($key, $ids, self::CACHE_GROUP, 12 * HOUR_IN_SECONDS);
}
return $ids;
}
public static function flush_cache() {
wp_cache_delete('last_changed', self::CACHE_GROUP);
}
public function sync_cookie_for_customer() {
$user_id = get_current_user_id();
$owner = isset($_COOKIE[self::OWNER_COOKIE]) ? sanitize_text_field((string) wp_unslash($_COOKIE[self::OWNER_COOKIE])) : '';
if ($user_id <= 0) {
if ($owner !== '') {
$this->clear_account_cookie();
}
return;
}
$mark = self::owner_mark($user_id);
$cookie = $this->cookie_ids();
if ($owner === '' && $cookie) {
$account = $this->user_item_ids($user_id, 'product');
foreach (array_slice(array_values(array_diff($cookie, $account)), 0, 200) as $id) {
if (in_array(get_post_type((int) $id), array('product', 'product_variation'), true)) {
$this->add_item((int) $id, 'product', $user_id, 'guest_cookie');
}
}
}
$account = $this->user_item_ids($user_id, 'product');
$same = $account;
$held = $cookie;
sort($same);
sort($held);
if ($same !== $held) {
$this->write_cookie($account);
$this->write_owner_cookie($mark);
} elseif ($owner !== $mark) {
$this->write_owner_cookie($mark);
}
}
public function clear_account_cookie() {
$path = COOKIEPATH ? COOKIEPATH : '/';
if (!headers_sent()) {
setcookie(self::COOKIE_NAME, '', time() - HOUR_IN_SECONDS, $path, COOKIE_DOMAIN);
setcookie(self::OWNER_COOKIE, '', time() - HOUR_IN_SECONDS, $path, COOKIE_DOMAIN);
}
unset($_COOKIE[self::COOKIE_NAME], $_COOKIE[self::OWNER_COOKIE]);
}
private static function owner_mark($user_id) {
return substr(wp_hash('aieo_wishlist_owner|' . (int) $user_id), 0, 16);
}
private function write_owner_cookie($mark) {
$path = COOKIEPATH ? COOKIEPATH : '/';
if (!headers_sent()) {
setcookie(self::OWNER_COOKIE, $mark, time() + (self::COOKIE_DAYS * DAY_IN_SECONDS), $path, COOKIE_DOMAIN, is_ssl(), true);
}
$_COOKIE[self::OWNER_COOKIE] = $mark;
}
public function is_wishlisted($item_id, $item_type = 'product') {
$items = $this->get_items_for_viewer(get_current_user_id(), $item_type);
return in_array((int) $item_id, $items, true);
}
public function cookie_ids() {
if (!isset($_COOKIE[self::COOKIE_NAME])) { return array(); }
$raw = sanitize_text_field((string) wp_unslash($_COOKIE[self::COOKIE_NAME]));
if ($raw === '') { return array(); }
return array_values(array_filter(array_map('absint', explode(',', $raw))));
}
public function fav_cookie_items() {
if (empty($_COOKIE[self::FAVS_COOKIE])) { return array(); }
$raw = sanitize_text_field((string) wp_unslash($_COOKIE[self::FAVS_COOKIE]));
$out = array();
foreach (explode(',', $raw) as $item) {
if (preg_match('/^(brand|product_cat|pa-need|post)\.([1-9][0-9]{0,19})$/', trim($item), $m)) {
$out[] = $m[1] . '.' . $m[2];
}
}
return array_slice(array_values(array_unique($out)), 0, 200);
}
private function write_fav_cookie(array $items) {
$value = implode(',', array_slice($items, 0, 200));
$path = COOKIEPATH ? COOKIEPATH : '/';
if (!headers_sent()) {
setcookie(self::FAVS_COOKIE, $value, $value === '' ? time() - HOUR_IN_SECONDS : time() + (self::COOKIE_DAYS * DAY_IN_SECONDS), $path, COOKIE_DOMAIN);
}
$_COOKIE[self::FAVS_COOKIE] = $value;
}
public static function heart_colours() {
$d = self::get_display_settings();
$filled = (string) $d['color_filled'];
$hover = (string) $d['color_hover'];
if (function_exists('rooster_design_authority') && 'theme' === rooster_design_authority()) {
$filled = 'var(--wp--preset--color--accent-2,' . $filled . ')';
$hover = $filled;
}
return array($filled, $hover);
}
public function write_cookie(array $ids) {
$value = implode(',', array_map('intval', $ids));
$expires = time() + (self::COOKIE_DAYS * DAY_IN_SECONDS);
$path = COOKIEPATH ? COOKIEPATH : '/';
if (!headers_sent()) {
setcookie(self::COOKIE_NAME, $value, $expires, $path, COOKIE_DOMAIN);
}
$_COOKIE[self::COOKIE_NAME] = $value;
}
public function maybe_migrate_from_ppe() {
if (get_option(self::MIGRATION_OPTION) === '1') {
return;
}
global $wpdb;
$ppe_table = $wpdb->prefix . 'om_ppe_wishlist';
$exists = (string) $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $ppe_table));
if ($exists !== $ppe_table) {
update_option(self::MIGRATION_OPTION, '1', false);
return;
}
$aieo_table = self::get_table_name();
$wpdb->query("
INSERT IGNORE INTO {$aieo_table}
(user_id, session_id, item_id, item_type, source_type, source_id, source_name, date_added)
SELECT
user_id, session_id, item_id, item_type, source_type, source_id, source_name, date_added
FROM {$ppe_table}
");
$this->viewer_rows = array();
self::flush_cache();
update_option(self::MIGRATION_OPTION, '1', false);
}
public static function force_migrate_from_ppe() {
delete_option(self::MIGRATION_OPTION);
self::instance()->maybe_migrate_from_ppe();
}
public function render_wishlist_shortcode($atts = array()) {
AIEO_Favourites::enqueue();
return AIEO_Favourites::favourites_html('page');
}
private function get_or_create_session_id() {
if (function_exists('WC') && WC()->session && method_exists(WC()->session, 'get_customer_id')) {
$sid = (string) WC()->session->get_customer_id();
if ($sid !== '') { return $sid; }
}
$cookie = 'aieo_wishlist_sid';
if (isset($_COOKIE[$cookie]) && (string) $_COOKIE[$cookie] !== '') {
return sanitize_text_field((string) wp_unslash($_COOKIE[$cookie]));
}
$sid = wp_generate_password(32, false, false);
if (!headers_sent()) {
setcookie($cookie, $sid, time() + (180 * DAY_IN_SECONDS), COOKIEPATH ? COOKIEPATH : '/', COOKIE_DOMAIN);
}
$_COOKIE[$cookie] = $sid;
return $sid;
}
}