storeApiCartItemKey) { $this->storeApiCartItemKey = null; $this->storeApiQuantityAddition = null; } $product = WC()->cart->get_cart_item($key)['data'] ?? wc_get_product($variationId ?: $productId); $this->recordAddition($product, $quantity, $key); } public function beforeStoreApiCartChange(mixed $response, array $handler, \WP_REST_Request $request): mixed { if (! preg_match('~^/wc/store/(?:v1/)?cart/(add-item|update-item|items(?:/[\w-]{32})?)$~D', rtrim($request->get_route(), '/'), $route)) { return $response; } $method = $request->get_method(); $updatesItemByKey = str_starts_with($route[1], 'items/'); if ('POST' !== $method && ! ($updatesItemByKey && in_array($method, ['PUT', 'PATCH'], true))) { return $response; } $key = null; $quantity = null; if ($updatesItemByKey || 'update-item' === $route[1]) { $key = $request->get_param('key'); $quantity = $request->get_param('quantity'); if (! is_string($key) || '' === $key || ! is_numeric($quantity)) { return $response; } } $this->storeApiCartRequest = $request; $this->storeApiCartItemKey = $key; $this->storeApiRequestedQuantity = null === $quantity ? null : (int) $quantity; $this->captureStoreApiCartItemKey = false; $this->storeApiQuantityAddition = null; return $response; } public function afterStoreApiCartChange(mixed $response, array $handler, \WP_REST_Request $request): mixed { if ($request !== $this->storeApiCartRequest) { return $response; } $addition = $this->storeApiQuantityAddition; $key = $this->storeApiCartItemKey; $this->storeApiCartRequest = null; $this->storeApiCartItemKey = null; $this->storeApiRequestedQuantity = null; $this->captureStoreApiCartItemKey = false; $this->storeApiQuantityAddition = null; if (null !== $addition && null !== $key && $response instanceof \WP_REST_Response && $response->get_status() >= 200 && $response->get_status() < 300) { [$product, $quantity] = $addition; $this->recordAddition($product, $quantity, $key); } return $response; } public function beforeCartItemKeyGenerated(mixed $data): mixed { // WooCommerce has loaded and normalized the cart before preparing the actual add. if (null !== $this->storeApiCartRequest && null === $this->storeApiRequestedQuantity && null === $this->storeApiCartItemKey) { $this->captureStoreApiCartItemKey = true; } return $data; } public function onCartItemKeyGenerated(mixed $key): mixed { if ($this->captureStoreApiCartItemKey) { $this->storeApiCartItemKey = is_string($key) ? $key : null; $this->captureStoreApiCartItemKey = false; } return $key; } public function onStoreApiQuantityUpdate(string $key, int $quantity, int $oldQuantity, \WC_Cart $cart): void { if ($key !== $this->storeApiCartItemKey) { return; } if (null !== $this->storeApiRequestedQuantity) { if ($quantity !== $this->storeApiRequestedQuantity) { return; } } elseif (null !== $this->storeApiQuantityAddition) { return; } // The Store API updates an existing line directly, without woocommerce_add_to_cart. $this->storeApiQuantityAddition = $quantity > $oldQuantity ? [$cart->get_cart_item($key)['data'] ?? null, $quantity - $oldQuantity] : null; } private function recordAddition(mixed $product, int $quantity, string $key): void { if (! $product instanceof \WC_Product || $quantity <= 0) { return; } $currency = get_woocommerce_currency(); $eventId = apply_filters('aivie_wc_cart_addition_event_id', '', $product, $quantity, $key); if (! is_string($eventId) || '' === trim($eventId) || mb_strlen($eventId) > 191 || trim($eventId) !== $eventId) { $eventId = wp_generate_uuid4(); } $addition = [ 'eventId' => $eventId, 'product' => $this->mapProduct($product), 'quantity' => $quantity, 'unitAmount' => MoneyAmount::toMinorUnits($product->get_price(), $currency), 'occurredAt' => gmdate('Y-m-d\TH:i:s\Z'), ]; $this->additions[] = $addition + $this->metaBrowserContext(); do_action('aivie_wc_cart_item_added', $eventId, $addition, $currency); $this->onCartTouched(); } private function metaBrowserContext(): array { $allowed = ! function_exists('wp_has_consent') || wp_has_consent('marketing'); if (! $allowed || ! apply_filters('aivie_wc_cart_meta_tracking_enabled', true)) { return []; } $userAgent = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? '')); // Use the peer address rather than accepting a visitor-supplied forwarded IP. $ip = filter_var(wp_unslash($_SERVER['REMOTE_ADDR'] ?? ''), FILTER_VALIDATE_IP); return array_filter([ 'clientUserAgent' => mb_substr($userAgent, 0, 1024), 'clientIpAddress' => $ip, ]); } public function onCartTouched(): void { $this->changed = true; } public function onClassicCheckoutUpdate(string $serialized): void { wp_parse_str($serialized, $data); $this->captureEmail($data['billing_email'] ?? null); } public function onBlockCheckoutUpdate(): void { $this->captureEmail(WC()->customer?->get_billing_email()); } public function onBlockCheckoutOrderUpdate(\WC_Order $order): void { $this->captureEmail($order->get_billing_email()); } public function onBlockCustomerUpdate(\WC_Customer $customer): void { $this->captureEmail($customer->get_billing_email()); } public function onClassicCheckoutOrder(int $orderId, array $data, \WC_Order $order): void { $this->onOrder($order); } public function onOrder(\WC_Order $order): void { $this->orderId = $order->get_id(); $this->captureEmail($order->get_billing_email()); $this->onCartTouched(); } public function queueSnapshot(): void { if (! $this->changed || ! WC()->session || ! WC()->cart) { return; } $connections = new ConnectionManager(); if (! $connections->isConfigured()) { return; } $destination = $connections->baseUrl(); $session = WC()->session; $sessionId = (string) $session->get(self::REPLAY_SESSION_KEY, $session->get_customer_id()); if ('' === $sessionId) { return; } // Keep the same replay scope when WooCommerce migrates a guest session to a user. $session->set(self::REPLAY_SESSION_KEY, $sessionId); $replayed = $this->migratePendingSnapshots($session, $sessionId, $destination) && CartSyncScheduler::replaySnapshots($sessionId, $destination); $state = (array) $session->get(self::SESSION_KEY, []); if ($destination !== ($state['destination'] ?? null)) { $state = []; } $items = []; $currency = get_woocommerce_currency(); foreach (WC()->cart->get_cart() as $line) { $product = $line['data'] ?? null; if (! $product instanceof \WC_Product || (int) $line['quantity'] <= 0) { continue; } $items[] = [ 'product' => $product, 'quantity' => (int) $line['quantity'], 'unitAmount' => MoneyAmount::toMinorUnits($product->get_price(), $currency), ]; } if (! empty($state['converted'])) { // Checkout can leave the cart populated while the customer is paying. if ([] === $this->additions) { if ([] === $items) { $session->set(self::SESSION_KEY, null); } return; } $state = []; } if ([] === $items && [] === $this->additions && empty($state['id'])) { return; } $email = $this->email ?? (is_user_logged_in() ? sanitize_email(wp_get_current_user()->user_email) : null); $device = $this->readDeviceId(); $orderReference = null === $this->orderId ? null : (string) $this->orderId; $lines = array_map(static fn (array $item): array => [$item['product']->get_id(), $item['quantity'], $item['unitAmount']], $items); $hash = hash('sha256', (string) wp_json_encode([$lines, $email, $device, $orderReference, $currency])); if ([] === $this->additions && $hash === ($state['hash'] ?? null)) { return; } foreach ($items as &$item) { $item['product'] = $this->mapProduct($item['product']); } unset($item); $id = $state['id'] ?? wp_generate_uuid4(); $revision = max((int) (microtime(true) * 1000000), 1 + (int) ($state['revision'] ?? 0)); $payload = [ 'source' => Options::getString(Options::SOURCE) ?: 'woocommerce', 'sourceCartId' => $id, 'revision' => $revision, 'currency' => $currency, 'lastActivityAt' => gmdate('Y-m-d\TH:i:s\Z'), 'deviceId' => $device, 'contactEmail' => $email ?: null, 'orderReferenceId' => $orderReference, 'items' => $items, 'additions' => $this->additions, ]; $queued = $replayed && CartSyncScheduler::enqueue($payload, $destination); if (! $queued && ! CartSyncScheduler::retainSnapshot($sessionId, $payload, $destination)) { return; } $session->set(self::SESSION_KEY, [] !== $items ? [ 'id' => $id, 'hash' => $hash, 'revision' => $revision, 'destination' => $destination, 'converted' => null !== $this->orderId, ] : null); } private function migratePendingSnapshots(object $session, string $sessionId, string $destination): bool { $pending = (array) $session->get(self::LEGACY_PENDING_SESSION_KEY, []); if ($destination === ($pending['destination'] ?? null)) { foreach ($pending['snapshots'] ?? [] as $snapshot) { if (! CartSyncScheduler::retainSnapshot($sessionId, $snapshot, $destination)) { return false; } } } $session->set(self::LEGACY_PENDING_SESSION_KEY, null); return true; } private function captureEmail(mixed $value): void { if (! is_string($value) || ! is_email($value)) { return; } $this->email = sanitize_email($value); $this->onCartTouched(); } private function readDeviceId(): ?string { if (! Options::getBool(Options::USE_TRACKING_CONTACT_ID) || ! isset($_COOKIE['mautic_device_id']) || ! is_string($_COOKIE['mautic_device_id'])) { return null; } $value = sanitize_text_field(wp_unslash($_COOKIE['mautic_device_id'])); return preg_match('/^[a-zA-Z0-9]{23}$/D', $value) ? $value : null; } private function mapProduct(\WC_Product $product): array { $id = $product->get_id(); if (! isset($this->products[$id])) { $payload = ObjectSerializer::toArray((new ProductMapper())->mapForCart($product, get_woocommerce_currency())); $payload['title'] = mb_substr($payload['title'], 0, 255); if (isset($payload['sku'])) { $sku = mb_substr(trim($payload['sku']), 0, 191); $payload['sku'] = '' === $sku ? null : $sku; } $this->products[$id] = $payload; } return $this->products[$id]; } }