array(), 'category_term_ids' => array(), 'need_term_ids' => array(), ); $context[$key] = array($term_id); return self::filter($offers, $context); } public static function for_cart(array $cart_items, array $offers, array $args = array()) { if (empty($offers)) { return array(); } $by_price = isset($args['sum']) && 'price' === $args['sum']; if ($by_price) { foreach ($cart_items as $key => $item) { if (!empty($item['_aieo_dmm_gift_offer_id'])) { unset($cart_items[$key]); } } } $line_terms = array(); $amounts = array(); $cart_total = 0.0; $cart_qty = 0; foreach ($cart_items as $key => $item) { $pid = !empty($item['variation_id']) ? (int) $item['variation_id'] : (int) ($item['product_id'] ?? 0); $resolve_id = !empty($item['product_id']) ? (int) $item['product_id'] : $pid; $line_terms[$key] = self::line_context($resolve_id, $pid); if ($by_price) { $product = isset($item['data']) && is_object($item['data']) && method_exists($item['data'], 'get_price') ? $item['data'] : null; $amounts[$key] = $product ? (float) $product->get_price() * (int) ($item['quantity'] ?? 0) : 0.0; } else { $amounts[$key] = (float) ($item['line_subtotal'] ?? 0); } $cart_total += $amounts[$key]; $cart_qty += (int) ($item['quantity'] ?? 0); } $matched = array(); foreach ($offers as $offer) { if (!is_array($offer)) { continue; } $definition = self::definition_of($offer); if (null !== $definition) { $lines = array(); foreach ($cart_items as $key => $item) { $lines[] = $line_terms[$key] + array('quantity' => (int) ($item['quantity'] ?? 0), 'amount' => $amounts[$key]); } $answer = self::cart_by_definition($offer, $definition, $lines, $args); if (null !== $answer) { $matched[] = $answer; } continue; } $req_products = self::ids($offer, 'product_ids'); $targeted_subtotal = 0.0; $targeted_qty = 0; $any_line_matches = false; $vetoed = false; $has_required_prod = empty($req_products); foreach ($cart_items as $key => $item) { $ctx = isset($line_terms[$key]) ? $line_terms[$key] : array(); if (self::offer_excludes($offer, $ctx)) { $vetoed = true; } if (!empty($req_products)) { $lp = isset($ctx['product_ids']) ? (array) $ctx['product_ids'] : array(); if (!empty($lp) && array_intersect($lp, $req_products)) { $has_required_prod = true; } } if (!self::offer_targets($offer, $ctx)) { continue; } if (self::offer_excludes($offer, $ctx)) { continue; } $any_line_matches = true; $targeted_subtotal += isset($amounts[$key]) ? $amounts[$key] : 0.0; $targeted_qty += (int) ($item['quantity'] ?? 0); } $has_targeting = !empty(self::ids($offer, 'brand_term_ids')) || !empty(self::ids($offer, 'category_term_ids')) || !empty(self::ids($offer, 'need_term_ids')) || !empty($req_products) || !empty(self::patterns($offer, 'code_patterns')); if ($has_targeting && !$any_line_matches) { continue; } $threshold = (float) ($offer['min_subtotal'] ?? 0); $scope = isset($offer['min_subtotal_scope']) ? (string) $offer['min_subtotal_scope'] : 'targeted'; $check_value = ($scope === 'cart_total') ? $cart_total : $targeted_subtotal; $threshold_passed = ($threshold <= 0) || ($check_value >= $threshold); $min_qty = (int) ($offer['min_quantity'] ?? 0); $qty_scope = isset($offer['min_quantity_scope']) ? (string) $offer['min_quantity_scope'] : 'targeted'; $check_qty = ($qty_scope === 'cart_total') ? $cart_qty : $targeted_qty; $qty_passed = ($min_qty <= 0) || ($check_qty >= $min_qty); $offer['_targeted_subtotal'] = $targeted_subtotal; $offer['_vetoed'] = $vetoed; $offer['_qualified'] = !$vetoed && $has_required_prod && $threshold_passed && $qty_passed; $matched[] = $offer; } return $matched; } public static function offer_excludes(array $offer, array $context) { if (null !== self::definition_of($offer)) { return false; } $ex_brand = self::ids($offer, 'excluded_brand_ids'); $ex_cat = self::ids($offer, 'excluded_category_ids'); $ex_need = self::ids($offer, 'excluded_need_ids'); $ex_product = self::ids($offer, 'excluded_product_ids'); $ex_codes = self::patterns($offer, 'excluded_code_patterns'); if (empty($ex_brand) && empty($ex_cat) && empty($ex_need) && empty($ex_product) && empty($ex_codes)) { return false; } $ctx_brand = isset($context['brand_term_ids']) ? (array) $context['brand_term_ids'] : array(); $ctx_cat = isset($context['category_term_ids']) ? (array) $context['category_term_ids'] : array(); $ctx_need = isset($context['need_term_ids']) ? (array) $context['need_term_ids'] : array(); $ctx_product = isset($context['product_ids']) ? (array) $context['product_ids'] : array(); if (!empty($ex_brand) && !empty($ctx_brand) && array_intersect($ctx_brand, $ex_brand)) { return true; } if (!empty($ex_cat) && !empty($ctx_cat) && array_intersect($ctx_cat, $ex_cat)) { return true; } if (!empty($ex_need) && !empty($ctx_need) && array_intersect($ctx_need, $ex_need)) { return true; } if (!empty($ex_product) && !empty($ctx_product) && array_intersect($ctx_product, $ex_product)) { return true; } if (self::code_hit($context, $ex_codes)) { return true; } return false; } public static function offer_targets(array $offer, array $context) { $definition = self::definition_of($offer); if (null !== $definition) { $needs = isset($offer['_needs']) && is_array($offer['_needs']) ? $offer['_needs'] : self::needs_of($definition); return AIEO_DMM_Offer_Conditions::matches($definition['target'], array('product' => self::conditions_product($context, $needs))); } $brand_ids = self::ids($offer, 'brand_term_ids'); $category_ids = self::ids($offer, 'category_term_ids'); $need_ids = self::ids($offer, 'need_term_ids'); $product_ids = self::ids($offer, 'product_ids'); $operator = (isset($offer['rule_operator']) && strtoupper((string) $offer['rule_operator']) === 'OR') ? 'OR' : 'AND'; $ctx_brand = isset($context['brand_term_ids']) ? (array) $context['brand_term_ids'] : array(); $ctx_cat = isset($context['category_term_ids']) ? (array) $context['category_term_ids'] : array(); $ctx_need = isset($context['need_term_ids']) ? (array) $context['need_term_ids'] : array(); $ctx_product = isset($context['product_ids']) ? (array) $context['product_ids'] : array(); $code_patterns = self::patterns($offer, 'code_patterns'); $code_hit = self::code_hit($context, $code_patterns); if (empty($brand_ids) && empty($category_ids) && empty($need_ids)) { if (!empty($product_ids)) { $picked = !empty($ctx_product) && (bool) array_intersect($ctx_product, $product_ids); return $code_patterns ? ($picked || $code_hit) : $picked; } if ($code_patterns) { return $code_hit; } return true; } if ($operator === 'OR') { return ( (!empty($brand_ids) && !empty($ctx_brand) && array_intersect($ctx_brand, $brand_ids)) || (!empty($category_ids) && !empty($ctx_cat) && array_intersect($ctx_cat, $category_ids)) || (!empty($need_ids) && !empty($ctx_need) && array_intersect($ctx_need, $need_ids)) || ($code_patterns && $code_hit) ); } $brand_match = empty($brand_ids) || (!empty($ctx_brand) && array_intersect($ctx_brand, $brand_ids)); $cat_match = empty($category_ids) || (!empty($ctx_cat) && array_intersect($ctx_cat, $category_ids)); $need_match = empty($need_ids) || (!empty($ctx_need) && array_intersect($ctx_need, $need_ids)); $code_match = empty($code_patterns) || $code_hit; return $brand_match && $cat_match && $need_match && $code_match; } const WIDTH = array( 'product' => 1, 'code' => 2, 'need' => 3, 'category' => 4, 'brand' => 5, 'all' => 6, ); const WIDTH_ORDER_FILTER = 'aieo_dmm_offer_width_order'; private static $ranks = null; public static function width_order() { return array_keys(self::width_ranks()); } public static function width_ranks() { if (null === self::$ranks) { $default = array_keys(self::WIDTH); $given = function_exists('apply_filters') ? apply_filters(self::WIDTH_ORDER_FILTER, $default) : $default; $ranks = array(); foreach (self::width_order_of($given) as $i => $kind) { $ranks[$kind] = $i + 1; } self::$ranks = $ranks; } return self::$ranks; } public static function width_order_of($given) { $order = array(); if (is_array($given)) { foreach ($given as $kind) { if (is_string($kind) && isset(self::WIDTH[$kind]) && 'all' !== $kind && !in_array($kind, $order, true)) { $order[] = $kind; } } } foreach (array_keys(self::WIDTH) as $kind) { if ('all' !== $kind && !in_array($kind, $order, true)) { $order[] = $kind; } } $order[] = 'all'; return $order; } public static function width_order_is_default() { return array_keys(self::WIDTH) === self::width_order(); } public static function width_kinds($narrower, $wider) { if (self::width_order_is_default()) { return ''; } $kinds = array_flip(self::width_ranks()); $one = $kinds[(int) $narrower] ?? ''; $two = $kinds[(int) $wider] ?? ''; return '' !== $one && '' !== $two ? $one . '<' . $two : ''; } public static function width_of_row(array $row) { $filled = static function ($key) use ($row) { foreach (self::ids($row, $key) as $id) { if ($id > 0) { return true; } } return false; }; $rank = self::width_ranks(); $widths = array(); if ($filled('brand_term_ids') || (isset($row['brand_term_id']) && is_numeric($row['brand_term_id']) && (int) $row['brand_term_id'] > 0)) { $widths[] = $rank['brand']; } if ($filled('category_term_ids')) { $widths[] = $rank['category']; } if ($filled('need_term_ids')) { $widths[] = $rank['need']; } $has_patterns = (bool) self::patterns($row, 'code_patterns'); if (!$widths) { $has_products = $filled('product_ids'); if (!$has_products && !$has_patterns) { return $rank['all']; } if ($has_products && $has_patterns) { return max($rank['code'], $rank['product']); } return $has_patterns ? $rank['code'] : $rank['product']; } if ($has_patterns) { $widths[] = $rank['code']; } $operator = isset($row['rule_operator']) ? $row['rule_operator'] : (isset($row['operator']) ? $row['operator'] : 'AND'); return 'OR' === strtoupper((string) $operator) ? max($widths) : min($widths); } public static function start_of_row(array $row) { $instant = '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/'; if (isset($row['starts_at']) && is_string($row['starts_at']) && preg_match($instant, $row['starts_at']) && 0 !== strpos($row['starts_at'], '0000-')) { return $row['starts_at']; } foreach (array('date_from', 'start_date') as $key) { if (!isset($row[$key]) || !is_string($row[$key])) { continue; } $day = substr($row[$key], 0, 10); if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $day) || 0 === strpos($day, '0000-')) { continue; } try { $midnight = new DateTimeImmutable($day . ' 00:00:00', wp_timezone()); } catch (\Throwable $e) { continue; } return $midnight->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s'); } if (isset($row['created_ts']) && is_numeric($row['created_ts']) && (int) $row['created_ts'] > 0) { return gmdate('Y-m-d H:i:s', (int) $row['created_ts']); } if (isset($row['created_at']) && is_string($row['created_at']) && preg_match($instant, $row['created_at']) && 0 !== strpos($row['created_at'], '0000-')) { return $row['created_at']; } return ''; } public static function compare(array $a, array $b, $unit_price) { return self::compared($a, $b, (float) $unit_price)[0]; } public static function rank(array $offers, $unit_price) { $unit_price = (float) $unit_price; $offers = array_values(array_filter($offers, 'is_array')); usort($offers, static function ($a, $b) use ($unit_price) { return self::compared($a, $b, $unit_price)[0]; }); $tb = 'none'; if (count($offers) > 1) { $tb = self::compared($offers[0], $offers[1], $unit_price)[1]; if ('none' === $tb || 'store' === $tb) { $tb = 'id'; } } $best = $offers ? self::reduction($offers[0], $unit_price) : 0.0; $second = count($offers) > 1 ? self::reduction($offers[1], $unit_price) : 0.0; foreach ($offers as $i => $offer) { $alone = self::reduction($offer, $unit_price); $offers[$i]['role'] = 0 === $i ? 'applied' : ($alone === $best ? 'equal' : 'outbid'); $offers[$i]['alone'] = $alone; $offers[$i]['marg'] = 0 === $i ? round($best - $second, 4) : 0.0; } $out = array('offers' => $offers, 'tb' => $tb); if ('width' === $tb) { $kinds = self::width_kinds($offers[0]['w'] ?? self::WIDTH['all'], $offers[1]['w'] ?? self::WIDTH['all']); if ('' !== $kinds) { $out['tbk'] = $kinds; } } return $out; } public static function priority_of(array $offer) { return isset($offer['priority']) && is_numeric($offer['priority']) ? (int) $offer['priority'] : 100; } private static function reduction(array $offer, $unit_price) { $pct = isset($offer['pct']) && is_numeric($offer['pct']) ? (float) $offer['pct'] : 0.0; return round($unit_price * $pct / 100, 4); } private static function compared(array $a, array $b, $unit_price) { $by = self::reduction($b, $unit_price) <=> self::reduction($a, $unit_price); if (0 !== $by) { return array($by, 'value'); } $by = self::priority_of($a) <=> self::priority_of($b); if (0 !== $by) { return array($by, 'priority'); } $width = static function (array $offer) { return isset($offer['w']) && is_numeric($offer['w']) ? (int) $offer['w'] : self::WIDTH['all']; }; $by = $width($a) <=> $width($b); if (0 !== $by) { return array($by, 'width'); } $start_a = isset($a['start']) ? (string) $a['start'] : ''; $start_b = isset($b['start']) ? (string) $b['start'] : ''; if ($start_a !== $start_b) { if ('' === $start_a) { return array(1, 'start'); } if ('' === $start_b) { return array(-1, 'start'); } return array(strcmp($start_a, $start_b) < 0 ? -1 : 1, 'start'); } $by = (isset($a['id']) ? (int) $a['id'] : 0) <=> (isset($b['id']) ? (int) $b['id'] : 0); if (0 !== $by) { return array($by, 'id'); } $by = strcmp(isset($a['s']) ? (string) $a['s'] : '', isset($b['s']) ? (string) $b['s'] : ''); return array($by < 0 ? -1 : ($by > 0 ? 1 : 0), 0 === $by ? 'none' : 'store'); } const STORES = array( 'aieo_dmm_brand_discounts' => 'bd', 'aieo_dmm_brand_gift_offers' => 'go', 'aieo_dmm_loyalty_classes' => 'lc', ); private static $active = array(); public static function active_offers($kind) { if (!class_exists('AIEO_DMM_Schedule', false)) { require_once __DIR__ . '/class-aieo-dmm-schedule.php'; } $kind = (string) $kind; $today = AIEO_DMM_Schedule::today(); $memo = self::window_memo($today) . '|' . $kind; if (isset(self::$active[$memo])) { return self::$active[$memo]; } $by_kind = self::enabled_offers(); $rows = isset($by_kind[$kind]) ? $by_kind[$kind] : array(); if ($rows && !class_exists('AIEO_DMM_Offers_Held', false) && is_readable(__DIR__ . '/class-aieo-dmm-offers-held.php')) { require_once __DIR__ . '/class-aieo-dmm-offers-held.php'; } $held = $rows && class_exists('AIEO_DMM_Offers_Held', false) ? AIEO_DMM_Offers_Held::all() : array(); $reached = $rows ? self::reached_only_by_access() : array(); $running = array(); foreach ($rows as $row) { if (!self::runs_now($row, $today) || self::compared_without($row)) { continue; } if ($held) { list($store, $id) = self::store_id($row); if (in_array($store . ':' . $id, $held, true)) { continue; } } if (isset($reached[(int) $row['id']])) { continue; } $running[] = $row; } return self::$active[$memo] = $running; } private static function runs_now(array $row, $today) { if (AIEO_DMM_Schedule::on_the_clock()) { return AIEO_DMM_Schedule::runs_at($row); } return AIEO_DMM_Schedule::in_window($row['start_date'] ?? null, $row['end_date'] ?? null, $today); } private static function window_memo($today) { return AIEO_DMM_Schedule::on_the_clock() ? 'at:' . gmdate('Y-m-d H:i') : (string) $today; } public static function matching($product_id, $kind, $customer = null, $context = null) { $product_id = (int) $product_id; $kind = (string) $kind; $offers = self::active_offers($kind); if (!$offers) { return array(); } self::load_definition_classes(); $nobody = array('user_id' => 0, 'roles' => array(), 'class_ids' => array()); $customer = is_array($customer) ? $customer + $nobody : $nobody; $priced = null; if ($product_id > 0) { $priced = is_array($context) ? $context + array('brand_term_ids' => array(), 'category_term_ids' => array(), 'need_term_ids' => array(), 'product_ids' => array($product_id), 'code_ids' => array($product_id)) : self::priced_context($product_id); } $on_cart = in_array($kind, AIEO_DMM_Offer_Definition::CART_KINDS, true); $now = gmdate('Y-m-d H:i:s'); $matches = array(); $orders = array(); foreach ($offers as $row) { $definition = self::definition_of($row); if (null === $definition) { continue; } $needs = isset($row['_needs']) && is_array($row['_needs']) && isset($row['_needs']['cart']) ? $row['_needs'] : self::needs_of($definition); if (null === $priced) { if (array('all' => array()) !== $definition['target']) { continue; } $product = array(); } else { $product = self::conditions_product($priced, $needs); if (!AIEO_DMM_Offer_Conditions::matches($definition['target'], array('product' => $product))) { continue; } } if (!$on_cart) { if (!empty($needs['cart'])) { continue; } if (!AIEO_DMM_Offer_Conditions::matches($definition['when'], array('product' => $product, 'customer' => $customer, 'now' => $now))) { continue; } } elseif (AIEO_DMM_Offer_Definition::names_the_customer($definition['when'])) { continue; } list($store, $record) = self::store_id($row); $effect = isset($definition['effect']) && is_array($definition['effect']) ? $definition['effect'] : array(); $word = isset($effect['e']) ? (string) $effect['e'] : ''; $value = isset($effect['value']) && is_numeric($effect['value']) ? (float) $effect['value'] : 0.0; $matches[] = array( 'id' => (int) $row['id'], 's' => $store, 'rid' => $record, 'kind' => $kind, 'e' => $word, 'value' => $value, 'pct' => 'percent' === $word ? $value : 0.0, 'w' => AIEO_DMM_Offer_Definition::width($definition['target']), 'start' => self::start_of_row($row), ); $orders[count($matches) - 1] = self::priority_of($row); } if (!$matches) { return array(); } $ranked = self::rank( array_map( static function (array $match, $order) { return array('id' => $match['rid'], 'priority' => $order, '_match' => $match) + $match; }, $matches, $orders ), 100.0 ); $out = array(); foreach ($ranked['offers'] as $offer) { $out[] = $offer['_match'] + array('tb' => $ranked['tb']) + (isset($ranked['tbk']) ? array('tbk' => $ranked['tbk']) : array()); } return $out; } private static function priced_context($product_id) { $context = self::product_context($product_id); $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0) { if (!$context['brand_term_ids']) { $context['brand_term_ids'] = array_map('intval', (array) self::object_term_ids($parent, self::brand_taxonomy())); } if (!$context['category_term_ids']) { $context['category_term_ids'] = array_map('intval', (array) self::object_term_ids($parent, 'product_cat')); } } return $context; } private static function reached_only_by_access() { if (!class_exists('AIEO_DMM_Offer_Access', false) && is_readable(__DIR__ . '/class-aieo-dmm-offer-access.php')) { require_once __DIR__ . '/class-aieo-dmm-offer-access.php'; } return class_exists('AIEO_DMM_Offer_Access', false) ? AIEO_DMM_Offer_Access::only_by_access_ids() : array(); } public static function forget_request() { self::$active = array(); self::$ranks = null; } public static function store_id(array $row) { $legacy = isset($row['legacy_table']) ? (string) $row['legacy_table'] : ''; if (isset(self::STORES[$legacy]) && !empty($row['legacy_id'])) { return array(self::STORES[$legacy], (int) $row['legacy_id']); } return array('of', isset($row['id']) ? (int) $row['id'] : 0); } private static function enabled_offers() { $load = static function () { $by_kind = array(); foreach ((array) self::load_rows("type <> 'free_shipping'") as $row) { $by_kind[(string) $row['type']][] = $row; } if (isset($by_kind['gift'])) { usort($by_kind['gift'], static function (array $a, array $b) { $by = self::priority_of($a) <=> self::priority_of($b); if (0 !== $by) { return $by; } $one = !empty($a['legacy_id']) ? (int) $a['legacy_id'] : (int) $a['id']; $two = !empty($b['legacy_id']) ? (int) $b['legacy_id'] : (int) $b['id']; return $two <=> $one; }); } return $by_kind; }; if (!class_exists('AIEO_DMM_Cache')) { return $load(); } $counters = (int) get_option('aieo_dmm_cache_v_gifts', 1) . ':' . (int) get_option('aieo_dmm_cache_v_loyalty', 1); return AIEO_DMM_Cache::remember('brands', 'active_offers_v4:' . $counters, $load, AIEO_DMM_Cache::TTL_SHORT); } public static function readable_offers(array $ids = array()) { $ids = array_values(array_unique(array_filter(array_map('intval', $ids)))); return self::load_rows($ids ? 'id IN (' . implode(', ', $ids) . ')' : ''); } private static function load_rows($and) { global $wpdb; $table = $wpdb->prefix . 'aieo_dmm_offers'; if (function_exists('aieo_dmm_table_exists') && !aieo_dmm_table_exists($table)) { return array(); } if (!class_exists('AIEO_DMM_Schema_Gate', false)) { require_once __DIR__ . '/class-aieo-dmm-schema-gate.php'; } if (!AIEO_DMM_Schema_Gate::ready(AIEO_DMM_Schema_Gate::OFFERS, 'matcher')) { return null; } $and = '' !== $and ? ' AND ' . $and : ''; $suppress = $wpdb->suppress_errors(true); $rows = $wpdb->get_results("SELECT *, UNIX_TIMESTAMP(created_at) AS created_ts FROM {$table} WHERE enabled = 1 AND state <> 'archived'" . self::not_stopped() . "{$and} ORDER BY id ASC", ARRAY_A); $failed = AIEO_DMM_Schema_Gate::failed('matcher'); $wpdb->suppress_errors($suppress); if ($failed || !is_array($rows)) { return null; } $held = class_exists('AIEO_DMM_Offers_Held') ? AIEO_DMM_Offers_Held::all() : array(); $out = array(); foreach ($rows as $row) { list($store, $id) = self::store_id($row); if ($held && in_array($store . ':' . $id, $held, true)) { continue; } self::load_definition_classes(); $definition = AIEO_DMM_Offer_Definition::for_row($row); if (null === $definition) { continue; } $row['_definition'] = $definition; $row['_needs'] = self::needs_of($definition); $out[] = $row; } return $out; } private static function not_stopped() { return " AND state NOT IN ('exhausted', 'draft')"; } private static function compared_without(array $row) { if (!class_exists('AIEO_DMM_Offer_Store', false) || !AIEO_DMM_Offer_Store::forced()) { return false; } $definition = isset($row['_definition']) && is_array($row['_definition']) ? $row['_definition'] : array(); if (!empty($definition['limits']) || !empty($definition['parameters']) || !empty($definition['display'])) { return true; } return $definition && class_exists('AIEO_DMM_Offer_Writer') && AIEO_DMM_Offer_Writer::has_no_old_row(array('definition' => $definition) + $row); } private static function definition_of(array $offer) { if (!isset($offer['_definition']) || !is_array($offer['_definition']) || !isset($offer['_definition']['target'], $offer['_definition']['when'])) { return null; } self::load_definition_classes(); return $offer['_definition']; } private static function load_definition_classes() { foreach (array('AIEO_DMM_Offer_Registry' => 'registry', 'AIEO_DMM_Offer_Conditions' => 'conditions', 'AIEO_DMM_Offer_Definition' => 'definition') as $class => $file) { if (!class_exists($class, false)) { require_once __DIR__ . '/class-aieo-dmm-offer-' . $file . '.php'; } } } public static function needs_of(array $definition) { $needs = array('codes' => false, 'taxes' => array(), 'cart' => false); $walk = static function ($tree) use (&$walk, &$needs) { if (!is_array($tree)) { return; } if (isset($tree['p'])) { if (0 === strpos((string) $tree['p'], 'cart.')) { $needs['cart'] = true; } if ('product.code' === $tree['p']) { $needs['codes'] = true; } if ('product.term' === $tree['p'] && isset($tree['tax'])) { $needs['taxes'][(string) $tree['tax']] = (string) $tree['tax']; } if (isset($tree['tree'])) { $walk($tree['tree']); } return; } foreach (array('all', 'any') as $list) { foreach ((array) ($tree[$list] ?? array()) as $child) { $walk($child); } } if (isset($tree['not'])) { $walk($tree['not']); } }; $walk($definition['target'] ?? array()); $walk($definition['when'] ?? array()); $needs['taxes'] = array_values($needs['taxes']); return $needs; } private static function conditions_product(array $context, array $needs) { if (!empty($needs['codes']) && !isset($context['codes'])) { $ids = isset($context['code_ids']) ? (array) $context['code_ids'] : array(); if (!$ids && isset($context['product_ids'])) { $ids = (array) $context['product_ids']; } $context['codes'] = $ids ? self::product_codes($ids) : array(); } foreach ((array) ($needs['taxes'] ?? array()) as $taxonomy) { if (isset($context['terms'][$taxonomy])) { continue; } $terms = array(); if (taxonomy_exists($taxonomy)) { foreach ((array) ($context['terms_of'] ?? $context['product_ids'] ?? array()) as $id) { foreach (self::object_term_ids((int) $id, $taxonomy) as $term_id) { $terms[$term_id] = $term_id; } } } $context['terms'][$taxonomy] = array_values($terms); } return $context; } private static function cart_by_definition(array $offer, array $definition, array $lines, array $args) { $needs = isset($offer['_needs']) && is_array($offer['_needs']) ? $offer['_needs'] : self::needs_of($definition); foreach ($lines as $i => $line) { $lines[$i] = self::conditions_product($line, $needs); } $matched = array(); $subtotal = 0.0; foreach ($lines as $line) { if (AIEO_DMM_Offer_Conditions::matches($definition['target'], array('product' => $line))) { $matched[] = $line; $subtotal += (float) $line['amount']; } } if (!$matched && AIEO_DMM_Offer_Definition::names_a_product($definition['target'])) { return null; } $context = array( 'lines' => $lines, 'matched' => $matched, 'customer' => isset($args['customer']) && is_array($args['customer']) ? $args['customer'] : self::current_customer($definition), 'now' => isset($args['now']) ? (string) $args['now'] : gmdate('Y-m-d H:i:s'), 'grants' => isset($args['grants']) && is_array($args['grants']) ? $args['grants'] : array(), 'offer_id' => (int) ($offer['id'] ?? 0), ); $vetoed = false; foreach ((array) ($definition['when']['all'] ?? array()) as $child) { if (is_array($child) && isset($child['not']['p']) && 'cart.contains' === $child['not']['p'] && AIEO_DMM_Offer_Conditions::matches($child['not'], $context)) { $vetoed = true; } } $offer['_targeted_subtotal'] = $subtotal; $offer['_vetoed'] = $vetoed; $offer['_qualified'] = AIEO_DMM_Offer_Conditions::matches($definition['when'], $context); return $offer; } private static function current_customer(array $definition) { if (!AIEO_DMM_Offer_Definition::names_the_customer($definition['when'] ?? array())) { return self::customer_of(0); } return self::customer_of(function_exists('get_current_user_id') ? (int) get_current_user_id() : 0); } public static function customer_of($user_id) { $user_id = (int) $user_id; if ($user_id > 0) { if (!class_exists('AIEO_DMM_Price_Resolver', false)) { require_once __DIR__ . '/class-aieo-dmm-price-resolver.php'; } $customer = AIEO_DMM_Price_Resolver::customer($user_id); if (is_array($customer)) { return $customer; } } return array('user_id' => 0, 'roles' => array(), 'class_ids' => array(), 'audiences' => array(), 'key' => 'guest'); } public static function holds_but_the_cart(array $when, array $customer) { self::load_definition_classes(); try { return AIEO_DMM_Offer_Conditions::matches(self::cart_taken_as_met($when), array('product' => array(), 'lines' => array(), 'matched' => array(), 'customer' => $customer, 'now' => gmdate('Y-m-d H:i:s'), 'grants' => array())); } catch (\Throwable $e) { return false; } } private static function cart_taken_as_met($tree) { if (!is_array($tree)) { return $tree; } if (isset($tree['p'])) { return 0 === strpos((string) $tree['p'], 'cart.') ? array('all' => array()) : $tree; } if (isset($tree['not'])) { $needs = self::needs_of(array('when' => $tree['not'])); return !empty($needs['cart']) ? array('all' => array()) : $tree; } foreach (array('all', 'any') as $list) { if (isset($tree[$list]) && is_array($tree[$list])) { $tree[$list] = array_map(array(__CLASS__, 'cart_taken_as_met'), $tree[$list]); } } return $tree; } public static function prime_object_terms(array $object_ids, array $taxonomies = array()) { $object_ids = array_values(array_unique(array_filter(array_map('intval', $object_ids)))); if (!$object_ids) { return; } $taxes = array_merge(array(self::brand_taxonomy(), 'product_cat', 'pa_need'), array_map('strval', $taxonomies)); $taxes = array_values(array_unique(array_filter($taxes, 'taxonomy_exists'))); $missing = array(); foreach ($taxes as $taxonomy) { foreach ($object_ids as $id) { if (false === wp_cache_get($id, $taxonomy . '_relationships')) { $missing[$taxonomy][$id] = true; } } } if (!$missing) { return; } $ids = array(); foreach ($missing as $by_id) { $ids += $by_id; } $terms = wp_get_object_terms(array_keys($ids), array_keys($missing), array('fields' => 'all_with_object_id', 'update_term_meta_cache' => false)); if (is_wp_error($terms)) { return; } $found = array(); foreach ((array) $terms as $term) { $found[$term->taxonomy][(int) $term->object_id][] = (int) $term->term_id; } foreach ($missing as $taxonomy => $by_id) { foreach (array_keys($by_id) as $id) { wp_cache_add($id, $found[$taxonomy][$id] ?? array(), $taxonomy . '_relationships'); } } } public static function object_term_ids($product_id, $taxonomy) { $cached = get_object_term_cache($product_id, $taxonomy); if (is_array($cached)) { return array_map(static function ($t) { return (int) $t->term_id; }, $cached); } $ids = wp_get_object_terms($product_id, $taxonomy, array('fields' => 'ids')); return is_wp_error($ids) ? array() : array_map('intval', (array) $ids); } private static $contexts = array(); private static $codes = array(); public static function line_context($product_id, $own_id = 0) { $product_id = (int) $product_id; $own_id = (int) $own_id > 0 ? (int) $own_id : $product_id; $ctx = self::product_context($product_id); $ids = $own_id !== $product_id ? array($own_id, $product_id) : array($product_id); $ctx['product_ids'] = $ids; $ctx['code_ids'] = $ids; $ctx['terms_of'] = array($product_id); return $ctx; } public static function product_context($product_id) { $product_id = (int) $product_id; if ($product_id <= 0) { return array('brand_term_ids' => array(), 'category_term_ids' => array(), 'need_term_ids' => array(), 'product_ids' => array()); } if (isset(self::$contexts[$product_id])) { return self::$contexts[$product_id]; } self::watch_products(); $brand_terms = self::object_term_ids($product_id, self::brand_taxonomy()); $cat_terms = self::object_term_ids($product_id, 'product_cat'); $need_terms = taxonomy_exists('pa_need') ? self::object_term_ids($product_id, 'pa_need') : array(); $self_ids = array($product_id); $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0) { $self_ids[] = $parent; } return self::$contexts[$product_id] = array( 'brand_term_ids' => array_map('intval', (array) $brand_terms), 'category_term_ids' => array_map('intval', (array) $cat_terms), 'need_term_ids' => array_map('intval', (array) $need_terms), 'product_ids' => array_map('intval', $self_ids), 'code_ids' => array_map('intval', $self_ids), ); } public static function product_codes(array $ids) { $out = array(); foreach ($ids as $id) { $id = (int) $id; if ($id <= 0) { continue; } if (!isset(self::$codes[$id])) { $codes = array(); foreach (array('_sku', '_global_unique_id') as $key) { $v = (string) get_post_meta($id, $key, true); if ('' !== $v) { $codes[] = $v; } } if (!$codes) { continue; } self::watch_products(); self::$codes[$id] = $codes; } foreach (self::$codes[$id] as $code) { $out[$code] = true; } } return array_map('strval', array_keys($out)); } public static function watch_products() { if (!function_exists('add_action') || false !== has_action('set_object_terms', array(__CLASS__, 'forget_written'))) { return; } foreach (array('set_object_terms', 'deleted_term_relationships') as $hook) { add_action($hook, array(__CLASS__, 'forget_written'), 1, 1); } add_action('clean_post_cache', array(__CLASS__, 'forget_cleaned'), 1, 2); foreach (array('woocommerce_new_product', 'woocommerce_update_product', 'woocommerce_new_product_variation', 'woocommerce_update_product_variation') as $hook) { add_action($hook, array(__CLASS__, 'forget_product'), 1, 1); } foreach (array('added_post_meta', 'updated_post_meta', 'deleted_post_meta') as $hook) { add_action($hook, array(__CLASS__, 'forget_code'), 1, 3); } } public static function forget_cleaned($post_id, $post = null) { $type = is_object($post) && isset($post->post_type) ? (string) $post->post_type : (string) get_post_type((int) $post_id); if (in_array($type, array('product', 'product_variation'), true)) { self::forget_product((int) $post_id); } } public static function forget_code($meta_ids, $object_id, $meta_key) { if (!in_array((string) $meta_key, array('_sku', '_global_unique_id'), true)) { return; } $id = (int) $object_id; if ($id > 0 && (isset(self::$codes[$id]) || isset(self::$contexts[$id]) || in_array((string) get_post_type($id), array('product', 'product_variation'), true))) { self::forget_product($id); } } public static function forget_written($object_id) { $id = (int) $object_id; if ($id <= 0 || !in_array((string) get_post_type($id), array('product', 'product_variation'), true)) { return; } self::forget_product($id); } public static function forget_product($product_id) { $id = (int) $product_id; unset(self::$contexts[$id], self::$codes[$id]); if (class_exists('AIEO_DMM_Offers_Now', false)) { AIEO_DMM_Offers_Now::forget_products(); } if (class_exists('AIEO_DMM_Price_Resolver', false)) { AIEO_DMM_Price_Resolver::forget_memo(); } } private static function patterns(array $offer, $key) { if (!isset($offer[$key]) || !class_exists('AIEO_DMM_Pattern_Match')) { return array(); } $raw = $offer[$key]; if (is_string($raw)) { $decoded = json_decode($raw, true); $raw = is_array($decoded) ? $decoded : array(); } return AIEO_DMM_Pattern_Match::parse((array) $raw); } private static function code_hit(array $context, array $patterns) { if (!$patterns) { return false; } $ids = isset($context['code_ids']) ? (array) $context['code_ids'] : array(); if (!$ids && isset($context['product_ids'])) { $ids = (array) $context['product_ids']; } if (!$ids) { return false; } return AIEO_DMM_Pattern_Match::any_matches_any(self::product_codes($ids), $patterns); } private static function filter(array $offers, array $context) { $matched = array(); foreach ($offers as $offer) { if (!is_array($offer)) { continue; } if (self::offer_targets($offer, $context)) { $matched[] = $offer; } } return $matched; } private static function ids(array $offer, $key) { if (!isset($offer[$key])) { return array(); } $val = $offer[$key]; if (is_string($val)) { $val = json_decode($val, true); } if (!is_array($val)) { return array(); } return array_values(array_filter(array_map('intval', $val))); } public static function resolve_product_tokens($blob) { global $wpdb; if (!is_string($blob) || trim($blob) === '') { return array(); } $tokens = preg_split('/[,;\s]+/', trim($blob), -1, PREG_SPLIT_NO_EMPTY); if (empty($tokens)) { return array(); } $resolved = array(); foreach ($tokens as $token) { $token = trim($token); if ($token === '') { continue; } $product_id = 0; if (ctype_digit($token)) { $candidate = (int) $token; $type = get_post_type($candidate); if ($type === 'product' || $type === 'product_variation') { $product_id = $candidate; } } if ($product_id === 0 && function_exists('wc_get_product_id_by_sku')) { $by_sku = (int) wc_get_product_id_by_sku($token); if ($by_sku > 0) { $product_id = $by_sku; } } if ($product_id === 0) { $by_barcode = (int) $wpdb->get_var($wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_global_unique_id' AND meta_value = %s LIMIT 1", $token )); if ($by_barcode > 0) { $type = get_post_type($by_barcode); if ($type === 'product' || $type === 'product_variation') { $product_id = $by_barcode; } } } if ($product_id <= 0) { continue; } if (get_post_type($product_id) === 'product_variation') { $parent = (int) wp_get_post_parent_id($product_id); if ($parent > 0) { $product_id = $parent; } } $resolved[$product_id] = true; } return array_keys($resolved); } public static function format_product_tokens(array $ids) { $lines = array(); foreach ($ids as $pid) { $pid = (int) $pid; if ($pid <= 0) { continue; } $title = get_the_title($pid); $sku = function_exists('get_post_meta') ? (string) get_post_meta($pid, '_sku', true) : ''; $line = (string) $pid; if ($sku !== '') { $line .= ' — ' . $sku; } if ($title !== '') { $line .= ' — ' . $title; } $lines[] = $line; } return implode("\n", $lines); } public static function product_cost($product_id) { global $wpdb; $product_id = (int) $product_id; if ($product_id <= 0) { return array(0.0, 'unknown_proxy'); } $vitals_table = $wpdb->prefix . 'aieo_core_product_vitals'; $has_vitals = class_exists('AIEO_DMM_Cache') ? AIEO_DMM_Cache::get_l1('schema', 'vitals_table') : null; if (null === $has_vitals) { $has_vitals = function_exists('aieo_dmm_table_exists') ? (bool) aieo_dmm_table_exists($vitals_table) : true; if (class_exists('AIEO_DMM_Cache')) { AIEO_DMM_Cache::put_l1('schema', 'vitals_table', $has_vitals); } } $cost = 0.0; if ($has_vitals) { $cost = (float) $wpdb->get_var($wpdb->prepare( "SELECT cost FROM {$vitals_table} WHERE product_id = %d LIMIT 1", $product_id )); } if ($cost > 0) { return array($cost, 'cogs'); } $meta = get_post_meta($product_id, '_cogs_total_value', true); $cost = class_exists('AIEO_DMM_Stored_Price') ? (float) AIEO_DMM_Stored_Price::read($meta) : (float) str_replace(',', '.', (string) $meta); if ($cost > 0) { return array($cost, 'cogs'); } $meta = get_post_meta($product_id, '_wc_cog_cost', true); $cost = class_exists('AIEO_DMM_Stored_Price') ? (float) AIEO_DMM_Stored_Price::read($meta) : (float) str_replace(',', '.', (string) $meta); if ($cost > 0) { return array($cost, 'cogs'); } $custom = apply_filters('aieo_dmm_product_cost', null, $product_id); if ($custom !== null && (float) $custom > 0) { return array((float) $custom, 'cogs'); } $retail = 0.0; if (function_exists('wc_get_product')) { $product = wc_get_product($product_id); if ($product) { $retail = (float) $product->get_regular_price(); } } return array($retail, 'unknown_proxy'); } private static function brand_taxonomy() { if (class_exists('AIEO_DMM_Brand_Discounts') && method_exists('AIEO_DMM_Brand_Discounts', 'get_brand_taxonomy')) { $tax = AIEO_DMM_Brand_Discounts::get_brand_taxonomy(); if ($tax) { return $tax; } } return 'product_brand'; } }