get_id() . '.' . $exp . '.' . self::direct_signature($order, $exp); } private static function direct_signature($order, $exp) { return hash_hmac( 'sha256', implode('|', array( (int) $order->get_id(), strtolower((string) $order->get_billing_email()), (int) $exp, )), wp_salt('auth') ); } private static function read_direct_token($raw) { $p = self::parse_direct_token($raw); return ($p['order'] && !$p['expired']) ? $p['order'] : null; } private static function parse_direct_token($raw) { $none = array('order' => null, 'expired' => false); $parts = explode('.', (string) $raw); if (count($parts) !== 3) { return $none; } list($oid, $exp, $sig) = $parts; $oid = (int) $oid; $exp = (int) $exp; if ($oid <= 0 || $exp <= 0) { return $none; } $order = wc_get_order($oid); if (!is_a($order, 'WC_Order')) { return $none; } if (!hash_equals(self::direct_signature($order, $exp), (string) $sig)) { return $none; } return array('order' => $order, 'expired' => ($exp <= time())); } public static function render($atts = array()) { if (!AIEO_Withdrawal::is_enabled()) { return ''; } $token = isset($_GET[self::CONFIRM_ARG]) ? sanitize_text_field(wp_unslash($_GET[self::CONFIRM_ARG])) : ''; if ($token !== '') { return self::render_confirm($token); } if (isset($_POST['aieo_wd_request_nonce'])) { return self::handle_request(); } if (!empty($_GET[self::DIRECT_ARG])) { $parsed = self::parse_direct_token(sanitize_text_field(wp_unslash($_GET[self::DIRECT_ARG]))); if ($parsed['order']) { return self::render_request_form( __('That link has expired. Press Continue and we will send you a fresh one.', 'ai-eshop-optimizer'), 'error', (string) $parsed['order']->get_billing_email() ); } return self::render_request_form( __('That link is no longer valid. Confirm your email below and we will send you a fresh one.', 'ai-eshop-optimizer'), 'error' ); } return self::render_request_form(); } private static function render_request_sent($message) { if (class_exists("AIEO_Withdrawal_Account")) { AIEO_Withdrawal_Account::styles(); } ob_start(); ?>


' . AIEO_Withdrawal_Account::status_html($order, $row, true) . ''; } private static function render_done($message, array $account = array()) { if (class_exists('AIEO_Withdrawal_Account')) { AIEO_Withdrawal_Account::styles(); } $lines = array(); if (!empty($account['created']) && class_exists('AIEO_Withdrawal_Account')) { $lines = AIEO_Withdrawal_Account::account_created_lines( (int) ($account['linked'] ?? 1), !empty($account['magic_link']) ); } $html = '
'; $html .= '

' . esc_html($message) . '

'; if (!empty($lines)) { $html .= '
'; $html .= '

' . esc_html(array_shift($lines)) . '

'; foreach ($lines as $line) { $html .= '

' . esc_html($line) . '

'; } if (function_exists('wc_get_page_permalink')) { $html .= '

' . esc_html__('View my orders', 'ai-eshop-optimizer') . '

'; } $html .= '
'; } if (class_exists('AIEO_Withdrawal_Account')) { $html .= AIEO_Withdrawal_Account::contact_block(); } $html .= '
'; return $html; } private static function handle_request() { $nonce = sanitize_text_field(wp_unslash($_POST['aieo_wd_request_nonce'])); if (!wp_verify_nonce($nonce, 'aieo_wd_request')) { return self::render_request_form( __('That form expired. Please try again.', 'ai-eshop-optimizer'), 'error' ); } if (self::is_rate_limited()) { return self::render_request_form( __('Too many attempts. Please try again in a few minutes.', 'ai-eshop-optimizer'), 'error' ); } self::bump_rate(); $order_no = isset($_POST['aieo_wd_order']) ? sanitize_text_field(wp_unslash($_POST['aieo_wd_order'])) : ''; $email = isset($_POST['aieo_wd_email']) ? sanitize_email(wp_unslash($_POST['aieo_wd_email'])) : ''; $uniform = __('If those details match an order, we have emailed you a link to confirm your withdrawal. Please check your inbox and your spam folder.', 'ai-eshop-optimizer'); if ($order_no === '' || !is_email($email)) { return self::render_request_sent($uniform); } $order = self::find_order($order_no, $email); if ($order) { $existing = AIEO_Withdrawal::latest_declaration($order->get_id()); if ($existing) { return self::render_status($order, $existing); } $eval = AIEO_Withdrawal::evaluate($order); if ($eval['tier'] !== AIEO_Withdrawal::TIER_NONE) { $token = self::issue_token($order); if ($token !== '') { self::send_verification_email($order, $token); } } else { self::send_ineligible_email($order, $eval); } } return self::render_request_sent($uniform); } private static function find_order($order_no, $email) { $digits = preg_replace('/[^0-9]/', '', $order_no); if ($digits === '') { return null; } $order = wc_get_order((int) $digits); if (!$order instanceof WC_Order) { return null; } $want = strtolower(trim($email)); $have = strtolower(trim((string) $order->get_billing_email())); if ($have === '' || !hash_equals($have, $want)) { return null; } $display = (string) $order->get_order_number(); if ($display !== '' && preg_replace('/[^0-9]/', '', $display) !== $digits && (int) $order->get_id() !== (int) $digits) { return null; } return $order; } private static function issue_token($order) { try { $raw = bin2hex(random_bytes(24)); } catch (Exception $e) { return ''; } $ttl = (int) apply_filters('aieo_withdrawal_guest_token_ttl', self::TOKEN_TTL, $order); if ($ttl < MINUTE_IN_SECONDS) { $ttl = self::TOKEN_TTL; } $tokens = self::token_store(); $tokens[self::token_key($raw)] = array( 'order_id' => $order->get_id(), 'email' => strtolower((string) $order->get_billing_email()), 'issued' => time(), 'expires' => time() + $ttl, ); return self::save_token_store($tokens) ? $raw : ''; } private static function token_store() { $raw = get_option(self::TOKEN_STORE, array()); if (!is_array($raw)) { return array(); } $now = time(); $live = array(); foreach ($raw as $key => $row) { if (!is_array($row) || empty($row['order_id'])) { continue; } $exp = isset($row['expires']) ? (int) $row['expires'] : ((int) (isset($row['issued']) ? $row['issued'] : 0) + HOUR_IN_SECONDS); if ($exp > $now) { $live[$key] = $row; } } return $live; } private static function save_token_store(array $tokens) { if (count($tokens) > self::TOKEN_MAX) { uasort($tokens, static function ($a, $b) { return ((int) (isset($a['issued']) ? $a['issued'] : 0)) <=> ((int) (isset($b['issued']) ? $b['issued'] : 0)); }); $tokens = array_slice($tokens, -self::TOKEN_MAX, null, true); } if (false === get_option(self::TOKEN_STORE, false)) { return add_option(self::TOKEN_STORE, $tokens, '', 'no'); } return update_option(self::TOKEN_STORE, $tokens, 'no') || get_option(self::TOKEN_STORE) === $tokens; } private static function token_key($raw) { return 'aieo_wd_tok_' . hash_hmac('sha256', $raw, wp_salt('auth')); } private static function read_token($raw) { $tokens = self::token_store(); $key = self::token_key($raw); $data = isset($tokens[$key]) ? $tokens[$key] : null; return is_array($data) && !empty($data['order_id']) ? $data : null; } private static function burn_token($raw) { $tokens = self::token_store(); $key = self::token_key($raw); if (isset($tokens[$key])) { unset($tokens[$key]); self::save_token_store($tokens); } } private static function render_confirm($token) { if (class_exists("AIEO_Withdrawal_Account")) { AIEO_Withdrawal_Account::styles(); } $data = self::read_token($token); if (!$data) { return self::render_request_form( __('That link has expired or has already been used — each one works once. Confirm your email below and we will send you a fresh one.', 'ai-eshop-optimizer'), 'error' ); } $order = wc_get_order((int) $data['order_id']); if (!$order instanceof WC_Order) { self::burn_token($token); return self::render_request_form(__('Order not found.', 'ai-eshop-optimizer'), 'error'); } if (isset($_POST['aieo_wd_confirm_nonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['aieo_wd_confirm_nonce'])), 'aieo_wd_confirm')) { $item_ids = isset($_POST['aieo_withdraw_items']) && is_array($_POST['aieo_withdraw_items']) ? array_map('absint', wp_unslash($_POST['aieo_withdraw_items'])) : array(); $note = isset($_POST['aieo_withdraw_note']) ? sanitize_textarea_field(wp_unslash($_POST['aieo_withdraw_note'])) : ''; $item_qty = array(); if (isset($_POST["aieo_withdraw_qty"]) && is_array($_POST["aieo_withdraw_qty"])) { foreach (wp_unslash($_POST["aieo_withdraw_qty"]) as $k => $v) { $item_qty[(int) $k] = (int) $v; } } $wants_account = !empty($_POST['aieo_wd_create_account']) && !self::has_account($order); $result = AIEO_Withdrawal::execute($order, array( 'item_ids' => $item_ids, 'item_qty' => $item_qty, 'channel' => 'guest', 'note' => $note, 'actor_id' => 0, 'defer_ack' => $wants_account, )); self::burn_token($token); if (is_wp_error($result)) { return self::render_request_form($result->get_error_message(), 'error'); } $message = $result['cancelled'] ? __('Your order has been cancelled. We have emailed you a confirmation.', 'ai-eshop-optimizer') : __('Your withdrawal has been registered. We have emailed you a confirmation with the date and time it was submitted.', 'ai-eshop-optimizer'); $account = array('created' => false, 'linked' => 0, 'magic_link' => false); if ($wants_account) { $created = self::create_account_for($order); if (!is_wp_error($created)) { $account = array( 'created' => true, 'linked' => (int) $created['linked'], 'magic_link' => !empty($created['magic_link']), ); self::adopt_declarations((int) $created['user_id'], $order); } if (class_exists('AIEO_Withdrawal_Emails')) { AIEO_Withdrawal_Emails::send_acknowledgement( (int) $result['declaration_id'], $order, array( 'tier' => $result['tier'], 'is_full' => $result['is_full'], 'items' => $result['items'], 'cancelled' => $result['cancelled'], 'channel' => 'guest', 'account' => $account, ) ); } } return self::render_done($message, $account); } $eval = AIEO_Withdrawal::evaluate($order); if ($eval['tier'] === AIEO_Withdrawal::TIER_NONE) { self::burn_token($token); $html = '

' . esc_html($eval['message']) . '

'; $html .= class_exists('AIEO_Withdrawal_Account') ? AIEO_Withdrawal_Account::contact_block() : ''; $html .= '
'; return $html; } ob_start(); ?>

get_order_number()) ); ?>

1) : ?>

1) : ?>

get_customer_id() > 0) { return true; } $email = (string) $order->get_billing_email(); return $email !== '' && (bool) get_user_by('email', $email); } private static function adopt_declarations($user_id, $order) { global $wpdb; $user_id = (int) $user_id; $email = (string) $order->get_billing_email(); if ($user_id <= 0 || '' === $email) { return 0; } $table = $wpdb->prefix . 'aieo_dmm_withdrawal_declarations'; if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $table)) !== $table) { return 0; } return (int) $wpdb->query($wpdb->prepare( "UPDATE `{$table}` SET user_id = %d WHERE user_id = 0 AND billing_email = %s", $user_id, mb_substr($email, 0, 190) )); } private static function create_account_for($order) { $email = (string) $order->get_billing_email(); if (!is_email($email)) { return new WP_Error('aieo_wd_no_email', 'no billing email'); } if (self::has_account($order)) { return new WP_Error('aieo_wd_exists', 'account exists'); } $username = function_exists('wc_create_new_customer_username') ? wc_create_new_customer_username($email) : sanitize_user(current(explode('@', $email)), true); $use_magic_link = self::magic_link_available(); $suppress = static function () { return false; }; if ($use_magic_link) { add_filter('woocommerce_email_enabled_customer_new_account', $suppress, 99); } $user_id = wc_create_new_customer($email, $username, '', array( 'first_name' => $order->get_billing_first_name(), 'last_name' => $order->get_billing_last_name(), )); if ($use_magic_link) { remove_filter('woocommerce_email_enabled_customer_new_account', $suppress, 99); } if (is_wp_error($user_id)) { return $user_id; } $fields = array('first_name','last_name','company','address_1','address_2','city','state','postcode','country','phone'); foreach ($fields as $f) { $getter = 'get_billing_' . $f; if (method_exists($order, $getter)) { update_user_meta($user_id, 'billing_' . $f, $order->$getter()); } } update_user_meta($user_id, 'billing_email', $email); foreach ($fields as $f) { $ship_getter = 'get_shipping_' . $f; $bill_getter = 'get_billing_' . $f; $value = ''; if (method_exists($order, $ship_getter)) { $value = (string) $order->$ship_getter(); } if ($value === '' && method_exists($order, $bill_getter)) { $value = (string) $order->$bill_getter(); } if ($value === '') { continue; } update_user_meta($user_id, 'shipping_' . $f, $value); } $linked = 0; $order->set_customer_id($user_id); $order->save(); $linked++; $limit = (int) apply_filters('aieo_withdrawal_adopt_orders_limit', 50); $others = wc_get_orders(array( 'limit' => $limit, 'billing_email' => $email, 'customer_id' => 0, 'return' => 'ids', 'exclude' => array($order->get_id()), )); foreach ((array) $others as $oid) { $o = wc_get_order($oid); if (!$o || (int) $o->get_customer_id() > 0) { continue; } if (strtolower((string) $o->get_billing_email()) !== strtolower($email)) { continue; } $o->set_customer_id($user_id); $o->save(); $linked++; } $magic_sent = false; if ($use_magic_link) { $user = get_user_by('id', $user_id); if ($user) { $magic_sent = (bool) call_user_func( array(self::magic_link_class(), 'issue_for_user'), $user, wc_get_endpoint_url('orders', '', wc_get_page_permalink('myaccount')) ); } } if ($use_magic_link && !$magic_sent) { wp_new_user_notification($user_id, null, 'user'); } do_action('aieo_withdrawal_guest_converted', $user_id, $order, $linked); return array('user_id' => (int) $user_id, 'linked' => $linked, 'magic_link' => $magic_sent); } private static function magic_link_class() { foreach (array('AIEO_Runtime_Magic_Link', 'AIEO_Magic_Link') as $cls) { if (class_exists($cls) && method_exists($cls, 'issue_for_user')) { return $cls; } } return ''; } private static function magic_link_available() { return self::magic_link_class() !== ''; } private static function send_verification_email($order, $token) { self::in_shop_language(static function () use ($order, $token) { self::build_verification_email($order, $token); }); } private static function build_verification_email($order, $token) { $url = add_query_arg( array( self::CONFIRM_ARG => rawurlencode($token), 'o' => (int) $order->get_id(), ), self::form_url() ); $subject = sprintf( __('Confirm your withdrawal — order %s', 'ai-eshop-optimizer'), $order->get_order_number() ); $body = '

' . esc_html__('We received a request to withdraw from your order.', 'ai-eshop-optimizer') . '

'; $body .= '

' . esc_html(sprintf( __('Click the button below to choose the items and confirm. The link works once and stays valid for %s.', 'ai-eshop-optimizer'), human_time_diff(0, (int) apply_filters('aieo_withdrawal_guest_token_ttl', self::TOKEN_TTL, null)) )) . '

'; $body .= AIEO_Email_Frame::button($url, __('Confirm withdrawal', 'ai-eshop-optimizer')); $body .= AIEO_Email_Frame::p(esc_html__('If you did not ask for this, you can ignore this email — nothing has been cancelled.', 'ai-eshop-optimizer'), 'muted'); self::mail($order->get_billing_email(), $subject, $body); } private static function send_ineligible_email($order, array $eval) { self::in_shop_language(static function () use ($order, $eval) { self::build_ineligible_email($order, $eval); }); } private static function build_ineligible_email($order, array $eval) { $subject = sprintf( __('About your withdrawal request — order %s', 'ai-eshop-optimizer'), $order->get_order_number() ); $body = '

' . esc_html($eval['message']) . '

'; if (class_exists('AIEO_Withdrawal_Account')) { $body .= AIEO_Withdrawal_Account::contact_block(); } self::mail($order->get_billing_email(), $subject, $body); } public static function mail($to, $subject, $body_html) { if (!function_exists('WC') || !WC()->mailer()) { return; } AIEO_Email_Frame::send($to, $subject, $body_html, array('id' => 'aieo_withdrawal', 'heading' => $subject)); } public static function in_shop_language(callable $build) { $locale = (string) apply_filters('aieo_withdrawal_email_locale', get_locale()); $switched = false; if ($locale !== '' && function_exists('determine_locale') && $locale !== determine_locale()) { if (function_exists('wc_switch_to_site_locale') && $locale === get_locale()) { wc_switch_to_site_locale(); $switched = 'wc'; } elseif (function_exists('switch_to_locale')) { $switched = switch_to_locale($locale) ? 'wp' : false; } } try { call_user_func($build); } finally { if ('wc' === $switched && function_exists('wc_restore_locale')) { wc_restore_locale(); } elseif ('wp' === $switched && function_exists('restore_previous_locale')) { restore_previous_locale(); } } } public static function form_url() { $settings = AIEO_Withdrawal::settings(); $page_id = (int) $settings['guest_form_page_id']; if ($page_id > 0) { $url = get_permalink($page_id); if ($url) { return $url; } } return home_url('/'); } public static function form_url_for_order($order) { $url = self::form_url(); if (!is_a($order, 'WC_Order')) { return $url; } $args = array(); $number = (string) $order->get_order_number(); if ($number !== '' && ctype_digit($number)) { $args['o'] = $number; } if ((int) $order->get_customer_id() > 0) { $args[self::ACCOUNT_HINT_ARG] = 1; } if ((string) $order->get_billing_email() !== '') { $args[self::DIRECT_ARG] = self::direct_token($order); } return empty($args) ? $url : add_query_arg($args, $url); } private static function rate_key() { $ip = ''; if (!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) { $ip = wp_unslash($_SERVER['HTTP_CF_CONNECTING_IP']); } elseif (!empty($_SERVER['REMOTE_ADDR'])) { $ip = wp_unslash($_SERVER['REMOTE_ADDR']); } $ip = filter_var(trim((string) $ip), FILTER_VALIDATE_IP) ? trim((string) $ip) : 'unknown'; return 'aieo_wd_rl_' . md5($ip); } private static function is_rate_limited() { return (int) get_transient(self::rate_key()) >= self::RATE_MAX; } private static function bump_rate() { $key = self::rate_key(); set_transient($key, (int) get_transient($key) + 1, self::RATE_WINDOW); } } }