0) { self::$role_pricing_suspended--; } } public static function role_pricing_suppressed() { return self::$role_pricing_suspended > 0 || self::is_back_office_request(); } public static function is_back_office_request() { if (null !== self::$back_office_memo) { return self::$back_office_memo; } $is = false; $final = true; if (is_admin() && !wp_doing_ajax()) { $is = true; } elseif (wp_doing_ajax()) { $referer = function_exists('wp_get_raw_referer') ? (string) wp_get_raw_referer() : ''; $path = '' !== $referer ? (string) wp_parse_url($referer, PHP_URL_PATH) : ''; $is = '' !== $path && false !== strpos($path, '/wp-admin/'); } elseif (defined('REST_REQUEST') && REST_REQUEST) { $route = ''; if (isset($GLOBALS['wp']) && is_object($GLOBALS['wp']) && isset($GLOBALS['wp']->query_vars['rest_route'])) { $route = (string) $GLOBALS['wp']->query_vars['rest_route']; } $is = (bool) preg_match('#^/(wc/v\d+|wc-admin|wc-analytics)(/|$)#', $route); } elseif (!did_action('parse_request')) { $final = false; } $is = (bool) apply_filters('aieo_role_pricing_back_office_request', $is); if ($final) { self::$back_office_memo = $is; } return $is; } public function get_effective_price($product_id, $user_id = null, $base = null) { $product_id = (int) $product_id; if ($product_id <= 0) { return $base !== null ? (float) $base : 0.0; } if ($user_id === null) { $user_id = get_current_user_id(); } $user_id = (int) $user_id; $ctx_key = AIEO_DMM_Cache::user_context_key($user_id) . ':' . $product_id; $memo = AIEO_DMM_Cache::get_l1('prices', $ctx_key); if ($memo !== null) { return (float) $memo; } $answer = $this->price_for($product_id, $user_id, $base); $price = (float) $answer['price']; AIEO_DMM_Cache::put_l1('prices', $ctx_key, $price); return $price; } public function apply_recipe_only($base_after_role, $product_id, $user_id = null) { $product_id = (int) $product_id; if ($product_id <= 0 || !is_numeric($base_after_role)) { return is_numeric($base_after_role) ? (float) $base_after_role : 0.0; } $base_after_role = (float) $base_after_role; if ($base_after_role <= 0) { return $base_after_role; } if ($user_id === null) { $user_id = get_current_user_id(); } $user_id = (int) $user_id; $ctx_key = 'recipe_only:' . $product_id . ':' . AIEO_DMM_Cache::user_context_key($user_id) . ':' . number_format($base_after_role, 4, '.', ''); $memo = AIEO_DMM_Cache::get_l1('prices', $ctx_key); if ($memo !== null) { return (float) $memo; } $settings = AIEO_DMM_Settings::get_all(); $recipe = isset($settings['recipe']) ? (array) $settings['recipe'] : array(); $mode = isset($settings['pricing_mode']) ? (string) $settings['pricing_mode'] : 'reactive'; $force_reactive = !empty($GLOBALS['aieo_dmm_force_reactive']); if (!$force_reactive && $mode === 'precomputed' && class_exists('AIEO_DMM_Product_FP') && class_exists('AIEO_DMM_User_FP')) { $price = $this->recipe_only_precomputed($base_after_role, $product_id, $user_id, $recipe); } else { $price = $this->recipe_only_reactive($base_after_role, $product_id, $user_id, $recipe); } if ($price < 0) { $price = 0.0; } AIEO_DMM_Cache::put_l1('prices', $ctx_key, (float) $price); return (float) $price; } public function price_for($product_id, $user_id = null, $regular = null, $as_viewer = false) { $product_id = (int) $product_id; if ($user_id === null) { $user_id = get_current_user_id(); } $user_id = (int) $user_id; $memo_key = 'price_for:' . $product_id . ':' . AIEO_DMM_Cache::user_context_key($user_id) . ':' . ($as_viewer ? 'v' : 'c') . ':' . ($regular === null ? '' : number_format((float) $regular, 4, '.', '')); $memo = AIEO_DMM_Cache::get_l1('prices', $memo_key); if (is_array($memo)) { return $memo; } $answer = $this->work_out_price($product_id, $user_id, $regular, $as_viewer); AIEO_DMM_Cache::put_l1('prices', $memo_key, $answer); return $answer; } private function work_out_price($product_id, $user_id, $regular, $as_viewer, $product = null) { $settings = AIEO_DMM_Settings::get_all(); $mode = AIEO_DMM_Settings::discounts_combine($settings); $nothing = array('price' => 0.0, 'winner' => 'regular', 'id' => null, 'applied' => array(), 'alone' => 0.0, 'combined' => null, 'regular' => 0.0, 'mode' => $mode); if ($product_id <= 0) { return $nothing; } $recipe = isset($settings['recipe']) ? (array) $settings['recipe'] : array(); if (!$product && function_exists('wc_get_product')) { $product = wc_get_product($product_id); } if ($product && $product->is_type('variable')) { $lowest = null; foreach ((array) $product->get_visible_children() as $child_id) { $child = $this->price_for((int) $child_id, $user_id, null, $as_viewer); if ($child['price'] > 0 && ($lowest === null || $child['price'] < $lowest['price'])) { $lowest = $child; } } return $lowest !== null ? $lowest : $nothing; } $regular = $regular === null ? 0.0 : (float) $regular; if ($regular <= 0 && $product) { $stored = $product->get_regular_price('edit'); $regular = is_numeric($stored) ? (float) $stored : 0.0; if ($regular <= 0 && $as_viewer) { $own = $product->get_price('edit'); $regular = is_numeric($own) ? (float) $own : 0.0; } } if ($regular <= 0) { if (isset($recipe['role_pricing']) && $recipe['role_pricing'] === 'active' && !($as_viewer && self::role_pricing_suppressed())) { $role_price = $this->lookup_role_price($product_id, $user_id, isset($settings['enabled_roles']) ? (array) $settings['enabled_roles'] : array()); if ($role_price !== null && $role_price > 0) { $role = AIEO_DMM_Price_Candidates::price('role', (float) $role_price, AIEO_DMM_Settings::role_prices_combine($settings)); $price = self::to_price_decimals((float) $role_price); return array('price' => $price, 'winner' => 'role', 'id' => null, 'applied' => array($role), 'alone' => $price, 'combined' => null, 'regular' => 0.0, 'mode' => $mode); } } return $nothing; } $combines = array( 'offers' => 'cascade' === $mode, 'role' => AIEO_DMM_Settings::role_prices_combine($settings), 'sale' => AIEO_DMM_Settings::sale_price_combines($settings), ); $candidates = array(); $own = self::offers_own_words(); $own_inputs = array('discount' => 0.0, 'class' => 0.0); if ($product && !$product->is_type('variable') && $product->is_on_sale('edit')) { $sale = $product->get_sale_price('edit'); if (is_numeric($sale) && (float) $sale > 0 && (float) $sale < $regular) { $candidates[] = AIEO_DMM_Price_Candidates::price('sale', (float) $sale, $combines['sale']); } } if (isset($recipe['role_pricing']) && $recipe['role_pricing'] === 'active' && !($as_viewer && self::role_pricing_suppressed())) { $role_price = $this->lookup_role_price($product_id, $user_id, isset($settings['enabled_roles']) ? (array) $settings['enabled_roles'] : array()); if ($role_price !== null && $role_price > 0) { $candidates[] = AIEO_DMM_Price_Candidates::price('role', (float) $role_price, $combines['role']); } } $precomputed = empty($GLOBALS['aieo_dmm_force_reactive']) && isset($settings['pricing_mode']) && $settings['pricing_mode'] === 'precomputed' && class_exists('AIEO_DMM_Product_FP') && class_exists('AIEO_DMM_User_FP'); $fp = $precomputed ? AIEO_DMM_Product_FP::get($product_id) : null; if (!$fp) { $precomputed = false; } if ($own && !empty($recipe['brand_discount']) && $recipe['brand_discount'] !== 'off') { $reading = $precomputed && is_callable(array('AIEO_DMM_Product_FP', 'reading')) ? AIEO_DMM_Product_FP::reading($product_id) : null; $best = array(1 => array(0.0, null), 0 => array(0.0, null)); foreach ($this->matching_offers_as_rules($product_id, $reading) as $rule) { $word = empty($rule['exclusive']) ? 0 : 1; if ($rule['percent'] > $best[$word][0]) { $best[$word] = array((float) $rule['percent'], (int) $rule['id']); } } foreach (array(1, 0) as $word) { if ($best[$word][0] > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('discount', $best[$word][0], 0 === $word, $best[$word][1]); } } $own_inputs['discount'] = $best[0][0]; } elseif (!empty($recipe['brand_discount']) && $recipe['brand_discount'] !== 'off') { $discount_pct = 0.0; $discount_id = null; if ($precomputed) { $discount_pct = (float) ($fp['effective_combined_pct'] ?? 0); } else { foreach ($this->matching_discount_rules($product_id) as $rule) { if ($rule['percent'] > $discount_pct) { $discount_pct = (float) $rule['percent']; $discount_id = (int) $rule['id']; } } } if ($discount_pct > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('discount', $discount_pct, $combines['offers'], $discount_id); } } $schedule_pct = $precomputed ? (float) ($fp['active_schedule_pct'] ?? 0) : (float) $this->lookup_schedule_percent($product_id); if ($schedule_pct > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('schedule', $schedule_pct, $combines['offers']); } if ($own && $user_id > 0 && !empty($recipe['loyalty_class']) && $recipe['loyalty_class'] !== 'off') { $sums = array(1 => 0.0, 0 => 0.0); foreach ($this->loyalty_by_class($user_id) as $class_id => $class_pct) { $word = isset($own['class']['lc:' . (int) $class_id]) ? $own['class']['lc:' . (int) $class_id] : ($combines['offers'] ? 0 : 1); $sums[$word] += (float) $class_pct; } $ufp = $precomputed ? AIEO_DMM_User_FP::get($user_id) : null; if (is_array($ufp)) { $personal = (float) ($ufp['personal_extra_pct'] ?? 0); $seq_expires = isset($ufp['sequence_expires_at']) ? (string) $ufp['sequence_expires_at'] : ''; if (!empty($ufp['sequence_pct']) && $seq_expires !== '' && strtotime($seq_expires) > time()) { $personal += (float) $ufp['sequence_pct']; } $sums[$combines['offers'] ? 0 : 1] += $personal; if (!empty($ufp['brand_overrides']) && is_array($ufp['brand_overrides'])) { foreach ((array) ($fp['brand_term_ids'] ?? array()) as $brand_id) { if (isset($ufp['brand_overrides'][$brand_id]) && (float) $ufp['brand_overrides'][$brand_id] > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('personal', (float) $ufp['brand_overrides'][$brand_id], $combines['offers'], (int) $brand_id); } } } } foreach (array(1, 0) as $word) { if ($sums[$word] > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('class', $sums[$word], 0 === $word); } } $own_inputs['class'] = $sums[0]; } elseif ($user_id > 0 && !empty($recipe['loyalty_class']) && $recipe['loyalty_class'] !== 'off') { if ($precomputed) { $ufp = AIEO_DMM_User_FP::get($user_id); if (is_array($ufp)) { $class_pct = (float) ($ufp['loyalty_extra_pct_sum'] ?? 0) + (float) ($ufp['personal_extra_pct'] ?? 0); $seq_expires = isset($ufp['sequence_expires_at']) ? (string) $ufp['sequence_expires_at'] : ''; if (!empty($ufp['sequence_pct']) && $seq_expires !== '' && strtotime($seq_expires) > time()) { $class_pct += (float) $ufp['sequence_pct']; } if ($class_pct > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('class', $class_pct, $combines['offers']); } if (!empty($ufp['brand_overrides']) && is_array($ufp['brand_overrides'])) { foreach ((array) ($fp['brand_term_ids'] ?? array()) as $brand_id) { if (isset($ufp['brand_overrides'][$brand_id]) && (float) $ufp['brand_overrides'][$brand_id] > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('personal', (float) $ufp['brand_overrides'][$brand_id], $combines['offers'], (int) $brand_id); } } } } } else { $class_pct = (float) $this->get_loyalty_extra_percent($user_id); if ($class_pct > 0) { $candidates[] = AIEO_DMM_Price_Candidates::percent('class', $class_pct, $combines['offers']); } } } $engine = $this; $cascade = static function ($base, array $percents) use ($engine, $product_id, $user_id) { return $engine->apply_recipe_only($base, $product_id, $user_id); }; if ($own) { $cascade = function ($base, array $percents) use ($product_id, $recipe, $own_inputs) { return $this->recipe_on($base, $product_id, $own_inputs['discount'], $own_inputs['class'], $recipe, $percents); }; } $answer = AIEO_DMM_Price_Candidates::resolve($regular, $candidates, $cascade); $answer['price'] = self::to_price_decimals($answer['price']); $answer['regular'] = $regular; $answer['mode'] = $mode; return $answer; } public static function to_price_decimals($price) { $price = (float) $price; $decimals = function_exists('wc_get_price_decimals') ? (int) wc_get_price_decimals() : 2; return $price > 0 ? round(round($price, $decimals + 4), $decimals) : $price; } public static function price_string($price) { $decimals = function_exists('wc_get_price_decimals') ? max(0, (int) wc_get_price_decimals()) : 2; return number_format(self::to_price_decimals((float) $price), $decimals, '.', ''); } public static function scheduled_price_now($product) { if (!is_object($product) || !is_a($product, 'WC_Product') || $product->is_type('variable')) { return null; } $sale = $product->get_sale_price('edit'); if ('' === (string) $sale || !is_numeric($sale)) { return null; } $from = $product->get_date_on_sale_from('edit'); $to = $product->get_date_on_sale_to('edit'); if (!$from && !$to) { return null; } $regular = $product->get_regular_price('edit'); if ('' === (string) $regular || !is_numeric($regular) || (float) $regular <= (float) $sale) { return null; } $stored = $product->get_price('edit'); $now = time(); $within = !(($from && $from->getTimestamp() > $now) || ($to && $to->getTimestamp() < $now)); if (!$within && (float) $stored === (float) $sale) { return (string) $regular; } if ($within && (float) $stored === (float) $regular) { return (string) $sale; } return null; } public static function getter_answer($incoming, $ours) { if (!is_numeric($ours)) { return $incoming; } $answer = self::price_string($ours); if (is_numeric($incoming) && self::price_string($incoming) === $answer) { return $incoming; } return $answer; } public function getter_price($incoming, $product, $is_sale_getter = false) { $incoming = (float) $incoming; $product_id = is_object($product) && method_exists($product, 'get_id') ? (int) $product->get_id() : 0; if ($product_id <= 0 || $incoming <= 0) { return $incoming; } if (method_exists($product, 'is_type') && $product->is_type('variable')) { if ($is_sale_getter) { return $incoming; } $range = $product->get_variation_prices(false); $lowest = !empty($range['price']) ? (float) min(array_map('floatval', (array) $range['price'])) : 0.0; return $lowest > 0 ? self::to_price_decimals($lowest) : $incoming; } $settings = AIEO_DMM_Settings::get_all(); if ('cascade' === AIEO_DMM_Settings::discounts_combine($settings) && AIEO_DMM_Settings::role_prices_combine($settings) && AIEO_DMM_Settings::sale_price_combines($settings) && null === self::offers_own_words()) { return self::to_price_decimals($this->apply_recipe_only($incoming, $product_id)); } $memo_key = 'getter:' . $product_id . ':' . AIEO_DMM_Cache::user_context_key() . ':' . ($is_sale_getter ? 's' : 'p') . ':' . number_format($incoming, 4, '.', ''); $memo = AIEO_DMM_Cache::get_l1('prices', $memo_key); if ($memo !== null) { return (float) $memo; } $answer = $this->work_out_price($product_id, (int) get_current_user_id(), null, true, $product); $computed = (float) $answer['price']; $answered = $incoming; if ($computed > 0) { if ($is_sale_getter) { $stored = $product->get_sale_price('edit'); } else { $stored = $product->is_on_sale('edit') ? $product->get_sale_price('edit') : $product->get_regular_price('edit'); if (!is_numeric($stored) || (float) $stored <= 0) { $stored = $product->get_price('edit'); } } $stored = is_numeric($stored) ? (float) $stored : 0.0; if ($stored > 0 && abs($incoming - $stored) > 0.005) { $role = $this->get_role_price($product_id); if ($role === null || abs($incoming - (float) $role) > 0.005) { $computed = $incoming * min(1.0, $computed / $stored); } } if ($computed < $incoming) { $answered = self::to_price_decimals($computed); } } AIEO_DMM_Cache::put_l1('prices', $memo_key, $answered); return $answered; } private function recipe_only_precomputed($base_after_role, $product_id, $user_id, array $recipe) { $fp = AIEO_DMM_Product_FP::get($product_id); $ufp = AIEO_DMM_User_FP::get($user_id); if (!$fp) { return $this->recipe_only_reactive($base_after_role, $product_id, $user_id, $recipe); } $price = (float) $base_after_role; $role_adjusted = $price; $brand_pct = (float) ($fp['effective_combined_pct'] ?? 0); if ($brand_pct > 0 && !empty($recipe['brand_discount']) && $recipe['brand_discount'] !== 'off') { switch ($recipe['brand_discount']) { case 'stack_multiplicative': $price = $price * (1.0 - ($brand_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($brand_pct / 100.0)); break; case 'replace_role': $price = (float) ($fp['base_regular'] ?? $base_after_role) * (1.0 - ($brand_pct / 100.0)); break; } } $sched_pct = (float) ($fp['active_schedule_pct'] ?? 0); if ($sched_pct > 0) { $price = $price * (1.0 - ($sched_pct / 100.0)); } if ($user_id > 0 && is_array($ufp) && !empty($recipe['loyalty_class']) && $recipe['loyalty_class'] !== 'off') { $loyal_pct = (float) ($ufp['loyalty_extra_pct_sum'] ?? 0) + (float) ($ufp['personal_extra_pct'] ?? 0); $seq_expires = isset($ufp['sequence_expires_at']) ? (string) $ufp['sequence_expires_at'] : ''; if (!empty($ufp['sequence_pct']) && $seq_expires !== '' && strtotime($seq_expires) > time()) { $loyal_pct += (float) $ufp['sequence_pct']; } if ($loyal_pct > 0) { switch ($recipe['loyalty_class']) { case 'stack_multiplicative': $price = $price * (1.0 - ($loyal_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($loyal_pct / 100.0)); break; case 'replace_all': $price = (float) ($fp['base_regular'] ?? $base_after_role) * (1.0 - ($loyal_pct / 100.0)); break; } } if (!empty($ufp['brand_overrides']) && is_array($ufp['brand_overrides'])) { $brand_ids = isset($fp['brand_term_ids']) ? (array) $fp['brand_term_ids'] : array(); foreach ($brand_ids as $bid) { if (isset($ufp['brand_overrides'][$bid])) { $bo = (float) $ufp['brand_overrides'][$bid]; if ($bo > 0) { $price = $price * (1.0 - ($bo / 100.0)); } } } } } return $price; } private function recipe_only_reactive($base_after_role, $product_id, $user_id, array $recipe) { $price = (float) $base_after_role; $role_adjusted = $price; $brand_pct = $this->lookup_brand_discount_percent($product_id); if ($brand_pct > 0 && !empty($recipe['brand_discount']) && $recipe['brand_discount'] !== 'off') { $base = (float) $this->lookup_base_price($product_id); switch ($recipe['brand_discount']) { case 'stack_multiplicative': $price = $price * (1.0 - ($brand_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($brand_pct / 100.0)); break; case 'replace_role': $price = $base * (1.0 - ($brand_pct / 100.0)); break; } } $sched_pct = $this->lookup_schedule_percent($product_id); if ($sched_pct > 0) { $price = $price * (1.0 - ($sched_pct / 100.0)); } if ($user_id > 0 && !empty($recipe['loyalty_class']) && $recipe['loyalty_class'] !== 'off') { $loyal_pct = $this->get_loyalty_extra_percent($user_id); if ($loyal_pct > 0) { $base = (float) $this->lookup_base_price($product_id); switch ($recipe['loyalty_class']) { case 'stack_multiplicative': $price = $price * (1.0 - ($loyal_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($loyal_pct / 100.0)); break; case 'replace_all': $price = $base * (1.0 - ($loyal_pct / 100.0)); break; } } } return $price; } public function is_excluded_from_free_shipping($product_id) { $product_id = (int) $product_id; if ($product_id <= 0) { return false; } $mode = class_exists('AIEO_DMM_Settings') ? AIEO_DMM_Settings::get('pricing_mode', 'reactive') : 'reactive'; if ($mode === 'precomputed' && class_exists('AIEO_DMM_Product_FP')) { $fp = AIEO_DMM_Product_FP::get($product_id); if (is_array($fp) && array_key_exists('nfs_excluded', $fp)) { return !empty($fp['nfs_excluded']); } } $set = $this->get_no_free_shipping_set(); if (isset($set[$product_id])) { return true; } $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0 && isset($set[$parent])) { return true; } return false; } public function get_loyalty_class_ids_for_user($user_id) { $user_id = (int) $user_id; if ($user_id <= 0) { return array(); } if (!isset($this->loyalty_cache[$user_id])) { $this->loyalty_cache[$user_id] = $this->load_loyalty_for_user($user_id); } return array_keys($this->loyalty_cache[$user_id]); } public function get_loyalty_extra_percent($user_id) { $user_id = (int) $user_id; if ($user_id <= 0) { return 0.0; } if (!isset($this->loyalty_cache[$user_id])) { $this->loyalty_cache[$user_id] = $this->load_loyalty_for_user($user_id); } return (float) array_sum($this->loyalty_cache[$user_id]); } public function preload_role_prices(array $product_ids) { global $wpdb; $ids = array_filter(array_map('intval', $product_ids)); $ids = array_unique($ids); $ids = array_diff($ids, array_keys($this->role_price_cache)); if (empty($ids)) { return; } $table = $wpdb->prefix . 'aieo_dmm_role_prices'; if (!$this->table_has_rows_column($table)) { return; } $placeholders = implode(',', array_fill(0, count($ids), '%d')); $sql = "SELECT * FROM {$table} WHERE product_id IN ({$placeholders}) OR parent_id IN ({$placeholders})"; $args = array_merge(array_values($ids), array_values($ids)); $rows = $wpdb->get_results($wpdb->prepare($sql, $args), ARRAY_A); if (!is_array($rows)) { return; } foreach ($rows as $row) { $this->role_price_cache[(int) $row['product_id']] = $this->row_to_role_prices($row); } foreach ($ids as $id) { $this->role_price_families_loaded[$id] = true; $this->role_price_ids_covered[$id] = true; if (!isset($this->role_price_cache[$id])) { $this->role_price_cache[$id] = array(); } } } private function row_to_role_prices(array $row) { $prices = array(); foreach ($row as $col => $val) { if (strpos($col, 'role_') !== 0 || $col === 'role_prices') { continue; } if ($val === null || $val === '') { continue; } $price = (float) $val; if ($price > 0) { $prices[substr($col, 5)] = $price; } } return $prices; } private function warm_role_prices_for($product_id) { $product_id = (int) $product_id; if ($product_id <= 0 || array_key_exists($product_id, $this->role_price_cache)) { return; } if (isset($this->role_price_ids_covered[$product_id])) { $this->role_price_cache[$product_id] = array(); return; } $parent = (int) wp_get_post_parent_id($product_id); $root = $parent > 0 ? $parent : $product_id; if (isset($this->role_price_families_loaded[$root])) { $this->load_role_prices_by_ids(array($product_id)); } else { $this->load_role_price_family($root, array($product_id)); } if (isset($this->role_price_ids_covered[$product_id]) && !array_key_exists($product_id, $this->role_price_cache)) { $this->role_price_cache[$product_id] = array(); } } private function load_role_price_family($root, array $also_ids = array()) { global $wpdb; $root = (int) $root; $table = $wpdb->prefix . 'aieo_dmm_role_prices'; if (!$this->table_has_rows_column($table)) { return; } $ids = array_values(array_unique(array_filter(array_map('intval', array_merge(array($root), $also_ids))))); $ph = implode(',', array_fill(0, count($ids), '%d')); $rows = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table} WHERE product_id IN ({$ph}) OR parent_id = %d", array_merge($ids, array($root)) ), ARRAY_A); if ('' !== $wpdb->last_error) { return; } $this->role_price_families_loaded[$root] = true; foreach ($ids as $id) { $this->role_price_ids_covered[$id] = true; } foreach ((array) $rows as $row) { $this->role_price_cache[(int) $row['product_id']] = $this->row_to_role_prices($row); } if (!array_key_exists($root, $this->role_price_cache)) { $this->role_price_cache[$root] = array(); } } private function load_role_prices_by_ids(array $ids) { global $wpdb; $ids = array_values(array_unique(array_filter(array_map('intval', $ids)))); if (empty($ids)) { return; } $table = $wpdb->prefix . 'aieo_dmm_role_prices'; if (!$this->table_has_rows_column($table)) { return; } $ph = implode(',', array_fill(0, count($ids), '%d')); $rows = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$table} WHERE product_id IN ({$ph})", $ids ), ARRAY_A); if ('' !== $wpdb->last_error) { return; } foreach ($ids as $id) { $this->role_price_ids_covered[$id] = true; } foreach ((array) $rows as $row) { $this->role_price_cache[(int) $row['product_id']] = $this->row_to_role_prices($row); } } public function warm_role_price_family($parent_id, array $child_ids = array()) { $parent_id = (int) $parent_id; if ($parent_id <= 0) { return; } $pending = array(); foreach ($child_ids as $cid) { $cid = (int) $cid; if ($cid > 0 && !isset($this->role_price_ids_covered[$cid]) && !array_key_exists($cid, $this->role_price_cache)) { $pending[] = $cid; } } if (isset($this->role_price_families_loaded[$parent_id]) && empty($pending)) { return; } $this->load_role_price_family($parent_id, $pending); if (!isset($this->role_price_families_loaded[$parent_id])) { return; } foreach ($pending as $cid) { if (!array_key_exists($cid, $this->role_price_cache)) { $this->role_price_cache[$cid] = array(); } } } public function get_cached_role_prices($product_id) { $product_id = (int) $product_id; if ($product_id <= 0) { return array(); } $this->warm_role_prices_for($product_id); return array_key_exists($product_id, $this->role_price_cache) ? $this->role_price_cache[$product_id] : null; } private function lookup_base_price($product_id) { if (!function_exists('wc_get_product')) { return 0.0; } $product = wc_get_product($product_id); if (!$product) { return 0.0; } $price = $product->get_regular_price('edit'); return is_numeric($price) ? (float) $price : 0.0; } public static function role_price_applies($role_price, $public_price) { if (!is_numeric($role_price) || (float) $role_price <= 0) { return false; } if (!self::is_public_price($public_price)) { return true; } return (float) $role_price < (float) $public_price; } public static function is_public_price($price) { return is_numeric($price) && (float) $price > 0; } public static function has_no_public_price($product) { if (!is_object($product) || !is_a($product, 'WC_Product')) { return false; } if ($product->is_type('variable')) { return false; } if (self::is_gift_line_product($product)) { return false; } return !self::is_public_price($product->get_regular_price('edit')); } public static function is_gift_line_product($product) { if (!function_exists('WC') || !WC()->cart || !is_array(WC()->cart->cart_contents)) { return false; } foreach (WC()->cart->cart_contents as $item) { if (!empty($item['_aieo_dmm_gift_offer_id']) && isset($item['data']) && $item['data'] === $product) { return true; } } return false; } public function get_role_price($product_id, $user_id = null) { $product_id = (int) $product_id; if ($product_id <= 0) { return null; } if ($user_id === null) { if (self::role_pricing_suppressed()) { return null; } $user_id = get_current_user_id(); } $enabled_roles = AIEO_DMM_Settings::get('enabled_roles', array()); if (!is_array($enabled_roles) || empty($enabled_roles)) { return null; } return $this->lookup_role_price($product_id, (int) $user_id, $enabled_roles); } public function get_role_entry($product_id, $user_id) { $product_id = (int) $product_id; if ($product_id <= 0) { return null; } $enabled_roles = AIEO_DMM_Settings::get('enabled_roles', array()); if (!is_array($enabled_roles) || empty($enabled_roles)) { return null; } $role = ''; $price = $this->lookup_role_price($product_id, (int) $user_id, $enabled_roles, $role); return null === $price ? null : array('price' => (float) $price, 'role' => $role); } public function get_role_entry_for_roles($product_id, array $roles) { $product_id = (int) $product_id; if ($product_id <= 0) { return null; } $enabled_roles = AIEO_DMM_Settings::get('enabled_roles', array()); if (!is_array($enabled_roles) || empty($enabled_roles)) { return null; } $role = ''; $price = $this->lowest_role_price($product_id, array_values(array_intersect(array_map('strval', $roles), $enabled_roles)), $role); return null === $price ? null : array('price' => (float) $price, 'role' => $role); } private function lookup_role_price($product_id, $user_id, array $enabled_roles, &$which = '') { $which = ''; if (empty($enabled_roles)) { return null; } $user_roles = array(); if ($user_id > 0) { $user = get_userdata($user_id); if ($user && !empty($user->roles)) { $user_roles = array_values(array_intersect($user->roles, $enabled_roles)); } } return $this->lowest_role_price($product_id, $user_roles, $which); } private function lowest_role_price($product_id, array $roles, &$which = '') { $which = ''; if (empty($roles)) { return null; } $this->warm_role_prices_for($product_id); $map = isset($this->role_price_cache[$product_id]) ? $this->role_price_cache[$product_id] : array(); if (empty($map)) { return null; } $best = null; foreach ($roles as $role) { $col = $this->sanitize_role_column_name($role); if (isset($map[$col]) && $map[$col] > 0) { if ($best === null || $map[$col] < $best) { $best = (float) $map[$col]; $which = (string) $role; } } } return $best; } private function sanitize_role_column_name($role) { $clean = strtolower(preg_replace('/[^a-z0-9_]/', '_', $role)); if ($clean === '') { return 'r'; } if (preg_match('/^[0-9]/', $clean)) { $clean = 'r_' . $clean; } return $clean; } private function lookup_brand_discount_percent($product_id) { $max = 0.0; foreach ($this->matching_discount_rules((int) $product_id) as $rule) { if ($rule['percent'] > $max) { $max = (float) $rule['percent']; } } return $max; } public function matching_discount_rules(int $product_id, ?array $ctx = null): array { if ($product_id <= 0) { return array(); } if (self::reads_the_one_table()) { return $this->matching_offers_as_rules($product_id); } $rules = $this->get_brand_discount_rules(); if (empty($rules)) { return array(); } if ($ctx === null) { $ctx = $this->discount_context($product_id); } else { foreach (array('brand', 'cat', 'need', 'self') as $key) { $ctx[$key] = isset($ctx[$key]) ? array_map('intval', (array) $ctx[$key]) : array(); } } $out = array(); foreach ($rules as $rule) { if (self::rule_matches($rule, $ctx)) { $out[] = $rule; } } return $out; } private static function offers_own_words() { if (!class_exists('AIEO_DMM_Offer_Store') || !AIEO_DMM_Offer_Store::own_words_possible() || !AIEO_DMM_Offer_Store::reads_unified() || AIEO_DMM_Offer_Store::forced()) { return null; } $memo = AIEO_DMM_Cache::get_l1('brands', 'offers_own_words'); if (is_array($memo)) { return $memo['words']; } $default = AIEO_DMM_Offer_Store::default_exclusive(); $words = array('discount' => array(), 'class' => array()); $differs = false; foreach (array('discount' => 'discount', 'customer_pricing' => 'class') as $kind => $as) { foreach (AIEO_DMM_Offer_Matcher::active_offers($kind) as $row) { list($store, $id) = AIEO_DMM_Offer_Matcher::store_id($row); $word = isset($row['exclusive']) && 0 === (int) $row['exclusive'] ? 0 : 1; $words[$as][$store . ':' . $id] = $word; if ($word !== $default) { $differs = true; } } } $answer = $differs ? $words : null; AIEO_DMM_Cache::put_l1('brands', 'offers_own_words', array('words' => $answer)); return $answer; } private function loyalty_by_class($user_id) { $user_id = (int) $user_id; if ($user_id <= 0) { return array(); } if (!isset($this->loyalty_cache[$user_id])) { $this->loyalty_cache[$user_id] = $this->load_loyalty_for_user($user_id); } return $this->loyalty_cache[$user_id]; } private function recipe_on($base_after_role, $product_id, $brand_pct, $loyal_pct, array $recipe, array $percents = array()) { $price = (float) $base_after_role; $role_adjusted = $price; if ($brand_pct > 0 && !empty($recipe['brand_discount']) && $recipe['brand_discount'] !== 'off') { switch ($recipe['brand_discount']) { case 'stack_multiplicative': $price = $price * (1.0 - ($brand_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($brand_pct / 100.0)); break; case 'replace_role': $price = (float) $this->lookup_base_price($product_id) * (1.0 - ($brand_pct / 100.0)); break; } } if ($loyal_pct > 0 && !empty($recipe['loyalty_class']) && $recipe['loyalty_class'] !== 'off') { switch ($recipe['loyalty_class']) { case 'stack_multiplicative': $price = $price * (1.0 - ($loyal_pct / 100.0)); break; case 'stack_additive': $price = $price - ($role_adjusted * ($loyal_pct / 100.0)); break; case 'replace_all': $price = (float) $this->lookup_base_price($product_id) * (1.0 - ($loyal_pct / 100.0)); break; } } foreach ($percents as $percent) { if (isset($percent['k'], $percent['pct']) && 'personal' === $percent['k'] && (float) $percent['pct'] > 0) { $price = $price * (1.0 - ((float) $percent['pct'] / 100.0)); } } return $price < 0 ? 0.0 : $price; } private static function reads_the_one_table() { return class_exists('AIEO_DMM_Offer_Store') && AIEO_DMM_Offer_Store::reads_unified(); } private function matching_offers_as_rules($product_id, $reading = null) { $matches = AIEO_DMM_Offer_Matcher::matching((int) $product_id, 'discount', null, $reading); if (!$matches) { return array(); } $rows = array(); foreach (AIEO_DMM_Offer_Matcher::active_offers('discount') as $row) { $rows[(int) $row['id']] = $row; } $list = static function ($value) { if (is_string($value)) { $value = json_decode($value, true); } return is_array($value) ? array_values($value) : array(); }; $out = array(); foreach ($matches as $match) { if ('percent' !== $match['e'] || (float) $match['value'] <= 0) { continue; } $row = isset($rows[(int) $match['id']]) ? $rows[(int) $match['id']] : array(); $out[] = array( 'id' => (int) $match['rid'], 's' => (string) $match['s'], 'offer_id' => (int) $match['id'], 'percent' => (float) $match['value'], 'exclusive' => isset($row['exclusive']) && 0 === (int) $row['exclusive'] ? 0 : 1, 'label' => isset($row['label']) ? (string) $row['label'] : '', 'date_from' => !empty($row['start_date']) ? (string) $row['start_date'] : '', 'created_at' => isset($row['created_at']) ? (string) $row['created_at'] : '', 'starts_at' => !empty($row['starts_at']) ? (string) $row['starts_at'] : null, 'created_ts' => isset($row['created_ts']) ? (int) $row['created_ts'] : 0, 'operator' => (isset($row['rule_operator']) && strtoupper((string) $row['rule_operator']) === 'OR') ? 'OR' : 'AND', 'brand_term_ids' => array_map('intval', $list($row['brand_term_ids'] ?? array())), 'category_term_ids' => array_map('intval', $list($row['category_term_ids'] ?? array())), 'need_term_ids' => array_map('intval', $list($row['need_term_ids'] ?? array())), 'product_ids' => array_map('intval', $list($row['product_ids'] ?? array())), 'code_patterns' => array_map('strval', $list($row['code_patterns'] ?? array())), 'w' => (int) $match['w'], 'start' => (string) $match['start'], 'tb' => (string) $match['tb'], ); } usort($out, static function (array $a, array $b) { return $a['id'] <=> $b['id']; }); return $out; } private function discount_context($product_id) { $brand_terms = $this->get_product_brand_term_ids($product_id); $cat_terms = $this->get_product_category_term_ids($product_id); $need_terms = taxonomy_exists('pa_need') ? $this->object_term_ids($product_id, 'pa_need') : array(); $self_ids = array((int) $product_id); $parent_pid = (int) wp_get_post_parent_id($product_id); if ($parent_pid > 0) { $self_ids[] = $parent_pid; } return array('brand' => $brand_terms, 'cat' => $cat_terms, 'need' => $need_terms, 'self' => $self_ids); } public static function rule_matches(array $rule, array $ctx): bool { $brand_terms = isset($ctx['brand']) ? (array) $ctx['brand'] : array(); $cat_terms = isset($ctx['cat']) ? (array) $ctx['cat'] : array(); $need_terms = isset($ctx['need']) ? (array) $ctx['need'] : array(); $self_ids = isset($ctx['self']) ? (array) $ctx['self'] : array(); if ((float) (isset($rule['min_subtotal']) ? $rule['min_subtotal'] : 0) > 0) { return false; } if (!empty($rule['product_ids'])) { return false; } if (!empty($rule['excluded_brand_ids']) && !empty($brand_terms) && array_intersect($brand_terms, $rule['excluded_brand_ids'])) { return false; } if (!empty($rule['excluded_category_ids']) && !empty($cat_terms) && array_intersect($cat_terms, $rule['excluded_category_ids'])) { return false; } if (!empty($rule['excluded_need_ids']) && !empty($need_terms) && array_intersect($need_terms, $rule['excluded_need_ids'])) { return false; } if (!empty($rule['excluded_product_ids']) && array_intersect($self_ids, $rule['excluded_product_ids'])) { return false; } list($has_code_filter, $code_hit, $code_excluded) = self::rule_codes($rule, $self_ids, isset($ctx['codes']) && is_array($ctx['codes']) ? $ctx['codes'] : null); if ($code_excluded) { return false; } $rule_need_ids = isset($rule['need_term_ids']) && is_array($rule['need_term_ids']) ? $rule['need_term_ids'] : array(); $has_brand_filter = !empty($rule['brand_term_id']); $has_cat_filter = !empty($rule['category_term_ids']); $has_need_filter = !empty($rule_need_ids); if ($rule['operator'] === 'OR') { $match = ($has_brand_filter && in_array((int) $rule['brand_term_id'], $brand_terms, true)) || ($has_cat_filter && !empty($cat_terms) && array_intersect($rule['category_term_ids'], $cat_terms)) || ($has_need_filter && !empty($need_terms) && array_intersect($rule_need_ids, $need_terms)) || ($has_code_filter && $code_hit); if (!$has_brand_filter && !$has_cat_filter && !$has_need_filter && !$has_code_filter) { $match = false; } } else { $brand_match = !$has_brand_filter || (!empty($brand_terms) && in_array((int) $rule['brand_term_id'], $brand_terms, true)); $cat_match = !$has_cat_filter || (!empty($cat_terms) && array_intersect($rule['category_term_ids'], $cat_terms)); $need_match = !$has_need_filter || (!empty($need_terms) && array_intersect($rule_need_ids, $need_terms)); $code_match = !$has_code_filter || $code_hit; $match = $brand_match && $cat_match && $need_match && $code_match; } return (bool) $match; } private function object_term_ids($product_id, $taxonomy) { $cached = get_object_term_cache($product_id, $taxonomy); if (is_array($cached)) { return array_map(static function ($term) { return (int) $term->term_id; }, $cached); } $ids = wp_get_object_terms($product_id, $taxonomy, array('fields' => 'ids')); return (is_wp_error($ids) || !is_array($ids)) ? array() : array_map('intval', $ids); } private function get_product_brand_term_ids($product_id) { $taxonomy = class_exists('AIEO_DMM_Brand_Discounts') ? AIEO_DMM_Brand_Discounts::get_brand_taxonomy() : 'product_brand'; if (!$taxonomy) { $taxonomy = 'product_brand'; } $terms = $this->object_term_ids($product_id, $taxonomy); if (empty($terms)) { $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0) { $terms = $this->object_term_ids($parent, $taxonomy); } } return $terms; } private function get_product_category_term_ids($product_id) { $terms = $this->object_term_ids($product_id, 'product_cat'); if (empty($terms)) { $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0) { $terms = $this->object_term_ids($parent, 'product_cat'); } } return $terms; } public static function forget_rules() { $engine = self::instance(); $engine->brand_discount_snapshot = null; $engine->discount_schedule_snapshot = null; $engine->loyalty_cache = array(); AIEO_DMM_Cache::forget('brands', 'active_rules_v2'); AIEO_DMM_Cache::forget('prices', 'schedule_snapshot'); AIEO_DMM_Cache::forget_request(); foreach (array('AIEO_DMM_Product_FP', 'AIEO_DMM_User_FP') as $fingerprints) { if (class_exists($fingerprints, false) && is_callable(array($fingerprints, 'clear_memo'))) { $fingerprints::clear_memo(); } } } private function get_brand_discount_rules() { if ($this->brand_discount_snapshot !== null) { return $this->brand_discount_snapshot; } $this->brand_discount_snapshot = AIEO_DMM_Cache::remember( 'brands', 'active_rules_v2', array($this, 'load_brand_discount_rules'), AIEO_DMM_Cache::TTL_SHORT ); return $this->brand_discount_snapshot; } public function load_brand_discount_rules() { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_brand_discounts'; if (!$this->table_exists($table)) { return array(); } if (function_exists('aieo_dmm_table_columns')) { $cols = aieo_dmm_table_columns($table); } else { $cols = $wpdb->get_col("SHOW COLUMNS FROM {$table}"); } $cols = is_array($cols) ? $cols : array(); $select_cols = array('id', 'brand_term_id', 'category_term_ids', 'rule_operator', 'percent', 'date_from', 'created_at'); foreach (array('need_term_ids', 'min_subtotal', 'min_subtotal_scope', 'application_scope', 'excluded_brand_ids', 'excluded_category_ids', 'excluded_need_ids', 'product_ids', 'excluded_product_ids', 'code_patterns', 'excluded_code_patterns', 'label') as $opt_col) { if (in_array($opt_col, $cols, true)) { $select_cols[] = $opt_col; } } $select = 'SELECT ' . implode(', ', $select_cols) . ', UNIX_TIMESTAMP(created_at) AS created_ts'; $today = current_time('Y-m-d'); $rows = $wpdb->get_results($wpdb->prepare( "{$select} FROM {$table} WHERE enabled = 1 AND (date_from IS NULL OR date_from <= %s) AND (date_to IS NULL OR date_to >= %s)", $today, $today ), ARRAY_A); $decode_ids = static function ($val) { if (empty($val)) { return array(); } $d = json_decode((string) $val, true); return is_array($d) ? array_values(array_filter(array_map('intval', $d))) : array(); }; $decode_patterns = static function ($val) { if (empty($val) || !class_exists('AIEO_DMM_Pattern_Match')) { return array(); } $d = json_decode((string) $val, true); return is_array($d) ? AIEO_DMM_Pattern_Match::parse($d) : array(); }; $out = array(); if (is_array($rows)) { foreach ($rows as $row) { $out[] = array( 'id' => (int) $row['id'], 'date_from' => isset($row['date_from']) ? (string) $row['date_from'] : '', 'created_at' => isset($row['created_at']) ? (string) $row['created_at'] : '', 'created_ts' => isset($row['created_ts']) ? (int) $row['created_ts'] : 0, 'label' => isset($row['label']) ? (string) $row['label'] : '', 'brand_term_id' => (int) $row['brand_term_id'], 'category_term_ids' => $decode_ids(isset($row['category_term_ids']) ? $row['category_term_ids'] : ''), 'need_term_ids' => $decode_ids(isset($row['need_term_ids']) ? $row['need_term_ids'] : ''), 'operator' => (isset($row['rule_operator']) && strtoupper($row['rule_operator']) === 'OR') ? 'OR' : 'AND', 'percent' => (float) $row['percent'], 'min_subtotal' => isset($row['min_subtotal']) ? (float) $row['min_subtotal'] : 0.0, 'min_subtotal_scope' => isset($row['min_subtotal_scope']) ? (string) $row['min_subtotal_scope'] : 'targeted', 'application_scope' => isset($row['application_scope']) ? (string) $row['application_scope'] : 'matching', 'excluded_brand_ids' => $decode_ids(isset($row['excluded_brand_ids']) ? $row['excluded_brand_ids'] : ''), 'excluded_category_ids' => $decode_ids(isset($row['excluded_category_ids']) ? $row['excluded_category_ids'] : ''), 'excluded_need_ids' => $decode_ids(isset($row['excluded_need_ids']) ? $row['excluded_need_ids'] : ''), 'product_ids' => $decode_ids(isset($row['product_ids']) ? $row['product_ids'] : ''), 'excluded_product_ids' => $decode_ids(isset($row['excluded_product_ids']) ? $row['excluded_product_ids'] : ''), 'code_patterns' => $decode_patterns(isset($row['code_patterns']) ? $row['code_patterns'] : ''), 'excluded_code_patterns' => $decode_patterns(isset($row['excluded_code_patterns']) ? $row['excluded_code_patterns'] : ''), ); } } if (class_exists('AIEO_DMM_Offers_Held')) { $found_now = array(); if (in_array('code_patterns', $cols, true)) { $found_now[] = AIEO_DMM_Offers_Held::seed('bd_pattern_or', 'bd', static function () use ($wpdb, $table, $decode_ids, $decode_patterns) { $held = array(); $found = $wpdb->get_results("SELECT id, category_term_ids, need_term_ids, code_patterns FROM {$table} WHERE brand_term_id = 0 AND rule_operator = 'OR'", ARRAY_A); foreach ((array) $found as $row) { if (!$decode_ids($row['category_term_ids']) && !$decode_ids($row['need_term_ids']) && $decode_patterns($row['code_patterns'])) { $held[] = (int) $row['id']; } } return $held; }); } $cart_cols = array_values(array_intersect(array('min_subtotal', 'product_ids'), $cols)); if ($cart_cols) { $found_now[] = AIEO_DMM_Offers_Held::seed('bd_cart_conditions', 'bd', static function () use ($wpdb, $table, $cart_cols, $decode_ids) { $held = array(); $found = $wpdb->get_results('SELECT id, ' . implode(', ', $cart_cols) . " FROM {$table}", ARRAY_A); foreach ((array) $found as $row) { if ((float) ($row['min_subtotal'] ?? 0) > 0 || $decode_ids($row['product_ids'] ?? '')) { $held[] = (int) $row['id']; } } return $held; }); } $held = AIEO_DMM_Offers_Held::ids('bd'); foreach ($found_now as $ids) { $held = array_merge($held, array_map('intval', (array) $ids)); } if ($held) { $out = array_values(array_filter($out, static function ($rule) use ($held) { return !in_array((int) $rule['id'], $held, true); })); } } return $out; } public static function rule_codes(array $rule, array $self_ids, $codes = null) { $patterns = isset($rule['code_patterns']) && is_array($rule['code_patterns']) ? $rule['code_patterns'] : array(); $excluded = isset($rule['excluded_code_patterns']) && is_array($rule['excluded_code_patterns']) ? $rule['excluded_code_patterns'] : array(); if ((!$patterns && !$excluded) || !class_exists('AIEO_DMM_Pattern_Match') || !class_exists('AIEO_DMM_Offer_Matcher')) { return array(false, false, false); } if (!is_array($codes)) { $codes = AIEO_DMM_Offer_Matcher::product_codes($self_ids); } return array( (bool) $patterns, $patterns && AIEO_DMM_Pattern_Match::any_matches_any($codes, $patterns), $excluded && AIEO_DMM_Pattern_Match::any_matches_any($codes, $excluded), ); } public function load_brand_discount_snapshot() { $rules = $this->load_brand_discount_rules(); $out = array(); foreach ($rules as $r) { $tid = (int) $r['brand_term_id']; if ($tid > 0 && $r['percent'] > 0 && (!isset($out[$tid]) || $r['percent'] > $out[$tid])) { $out[$tid] = (float) $r['percent']; } } return $out; } private function lookup_schedule_percent($product_id) { if (self::reads_the_one_table()) { return 0.0; } $snap = $this->get_discount_schedule_snapshot(); return isset($snap[$product_id]) ? (float) $snap[$product_id] : 0.0; } private function get_discount_schedule_snapshot() { if ($this->discount_schedule_snapshot !== null) { return $this->discount_schedule_snapshot; } $this->discount_schedule_snapshot = AIEO_DMM_Cache::remember( 'prices', 'schedule_snapshot', array($this, 'load_discount_schedule_snapshot'), AIEO_DMM_Cache::TTL_SHORT ); return $this->discount_schedule_snapshot; } public function load_discount_schedule_snapshot() { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_discount_schedules'; if (!$this->table_exists($table)) { return array(); } $today = current_time('Y-m-d'); $rows = $wpdb->get_results($wpdb->prepare( "SELECT product_id, percent FROM {$table} WHERE active = 1 AND (date_from IS NULL OR date_from <= %s) AND (date_to IS NULL OR date_to >= %s)", $today, $today ), ARRAY_A); $out = array(); if (is_array($rows)) { foreach ($rows as $row) { $pid = (int) $row['product_id']; $pct = (float) $row['percent']; if ($pid > 0 && $pct > 0 && (!isset($out[$pid]) || $pct > $out[$pid])) { $out[$pid] = $pct; } } } return $out; } private function get_no_free_shipping_set() { if ($this->no_free_shipping_set !== null) { return $this->no_free_shipping_set; } $cached = wp_cache_get('om_no_free_shipping_ids', 'om_shipping', false, $found); if ($found && is_array($cached)) { $this->no_free_shipping_set = $cached; return $cached; } $out = $this->load_no_free_shipping_set(); wp_cache_set('om_no_free_shipping_ids', $out, 'om_shipping', AIEO_DMM_Cache::TTL_MEDIUM); $this->no_free_shipping_set = $out; return $out; } public function load_no_free_shipping_set() { global $wpdb; $out = array(); $candidates = array( $wpdb->prefix . 'aieo_dmm_no_free_shipping', $wpdb->prefix . 'om_no_free_shipping', ); foreach ($candidates as $table) { if (!$this->table_exists($table)) { continue; } $ids = $wpdb->get_col("SELECT product_id FROM {$table}"); foreach ((array) $ids as $pid) { $out[(int) $pid] = true; } } return $out; } private function load_loyalty_for_user($user_id) { global $wpdb; $assign = $wpdb->prefix . 'aieo_dmm_loyalty_assignments'; $defs = $wpdb->prefix . 'aieo_dmm_loyalty_classes'; if (!$this->table_exists($assign) || !$this->table_exists($defs)) { return array(); } $one_table = self::reads_the_one_table(); $today = AIEO_DMM_Schedule::today(); $key = 'user:' . $user_id . ':' . $today . ($one_table ? ':of' : ''); $person = $one_table && class_exists('AIEO_DMM_User_FP') ? AIEO_DMM_User_FP::person_facts($user_id) : array(); if ($person) { $key .= ':' . substr(md5((string) wp_json_encode($person)), 0, 12); } return AIEO_DMM_Cache::remember('loyalty', $key, function () use ($wpdb, $assign, $defs, $user_id, $today, $one_table, $person) { list($window_sql, $window_args) = AIEO_DMM_Loyalty_Window::clause('d', $today); $rows = $wpdb->get_results($wpdb->prepare( "SELECT d.id, d.extra_percent FROM {$assign} a INNER JOIN {$defs} d ON d.id = a.class_id WHERE a.user_id = %d AND d.enabled = 1{$window_sql}", array_merge(array($user_id), $window_args) ), ARRAY_A); $out = array(); if (is_array($rows)) { foreach ($rows as $row) { $out[(int) $row['id']] = (float) $row['extra_percent']; } } if ($one_table && $out) { $given = array_fill_keys(array_keys($out), 0.0); foreach (AIEO_DMM_Offer_Matcher::matching(0, 'customer_pricing', array('user_id' => $user_id, 'class_ids' => array_keys($out)) + $person) as $match) { if ('lc' === $match['s'] && 'percent' === $match['e'] && isset($given[(int) $match['rid']])) { $given[(int) $match['rid']] += (float) $match['value']; } } return $given; } return $out; }, AIEO_DMM_Cache::TTL_MEDIUM); } private function table_exists($table) { global $wpdb; static $cache = array(); if (isset($cache[$table])) { return $cache[$table]; } if (function_exists('aieo_dmm_table_exists')) { $cache[$table] = (bool) aieo_dmm_table_exists($table); return $cache[$table]; } $found = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s", $table )); $cache[$table] = ((int) $found) > 0; return $cache[$table]; } private function table_has_rows_column($table) { global $wpdb; static $cache = array(); if (isset($cache[$table])) { return $cache[$table]; } if (!$this->table_exists($table)) { return $cache[$table] = false; } $col = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = %s AND COLUMN_NAME = 'product_id'", $table )); return $cache[$table] = ((int) $col) > 0; } public function register_preload_hooks() { add_action('woocommerce_before_shop_loop', array($this, 'preload_archive'), 1); add_action('woocommerce_before_main_content', array($this, 'preload_archive'), 1); add_filter('the_posts', array($this, 'preload_queried_products'), 10, 2); } public function preload_queried_products($posts, $query = null) { if (is_admin() || !is_array($posts) || count($posts) < 2) { return $posts; } if (!$this->viewer_has_priced_role()) { return $posts; } $ids = array(); foreach ($posts as $post) { if (isset($post->ID, $post->post_type) && 'product' === $post->post_type) { $ids[] = (int) $post->ID; } } if (count($ids) > 1) { $this->preload_role_prices_with_children($ids); } return $posts; } private function viewer_has_priced_role() { if (self::role_pricing_suppressed()) { return false; } if (null !== $this->viewer_priced_role) { return $this->viewer_priced_role; } $enabled = AIEO_DMM_Settings::get('enabled_roles', array()); if (!is_array($enabled) || empty($enabled) || !is_user_logged_in()) { return $this->viewer_priced_role = false; } $user = wp_get_current_user(); $roles = ($user && !empty($user->roles)) ? (array) $user->roles : array(); return $this->viewer_priced_role = !empty(array_intersect($roles, $enabled)); } private function preload_role_prices_with_children(array $parent_ids) { global $wpdb; $parent_ids = array_values(array_unique(array_filter(array_map('intval', $parent_ids)))); $parent_ids = array_values(array_diff($parent_ids, array_keys($this->role_price_children_expanded))); if (empty($parent_ids)) { return; } foreach ($parent_ids as $pid) { $this->role_price_children_expanded[$pid] = true; } $ph = implode(',', array_fill(0, count($parent_ids), '%d')); $children = $wpdb->get_col($wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_parent IN ({$ph}) AND post_type = 'product_variation'", $parent_ids )); $ids = $parent_ids; if ('' === $wpdb->last_error) { foreach ((array) $children as $cid) { $ids[] = (int) $cid; } } foreach (array_chunk($ids, self::ROLE_PRICE_PRELOAD_CHUNK) as $chunk) { $this->preload_role_prices($chunk); } } public function preload_archive() { if (is_admin() || !$this->viewer_has_priced_role()) { return; } global $wp_query; if (!$wp_query || empty($wp_query->posts)) { return; } $ids = array(); foreach ($wp_query->posts as $post) { if (isset($post->ID)) { $ids[] = (int) $post->ID; } } if (!empty($ids)) { $this->preload_role_prices_with_children($ids); } } }