prefix . 'sofrah_board_submissions'; } /** * Creates or updates the submissions table. */ function sofrah_board_install_submissions_table() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( 'CREATE TABLE ' . sofrah_board_submissions_table() . " ( k char(64) NOT NULL, cart char(32) NOT NULL DEFAULT '', created int(10) unsigned NOT NULL, derived tinyint(1) NOT NULL DEFAULT 0, order_id bigint(20) unsigned NULL, done int(10) unsigned NULL, PRIMARY KEY (k) ) " . $wpdb->get_charset_collate() . ';' ); update_option( 'sofrah_board_db_version', SOFRAH_BOARD_VERSION ); } /** * The cart session behind a Store API request. * * @param WP_REST_Request $request Request. * @return array Customer ID ('' if unknown), hash of the stored cart, and whether the cart is empty. */ function sofrah_board_store_cart( WP_REST_Request $request ) { $customer = ''; $token = (string) $request->get_header( 'cart_token' ); $utils = '\Automattic\WooCommerce\StoreApi\Utilities\CartTokenUtils'; if ( $token && class_exists( $utils ) && $utils::validate_cart_token( $token ) ) { $payload = $utils::get_cart_token_payload( $token ); $customer = (string) ( $payload['user_id'] ?? '' ); } if ( ! $customer && class_exists( 'WC_Session_Handler' ) ) { // The Store API starts WooCommerce's session after this point, so read its cookie through WooCommerce, // which checks the cookie's signature: a forged customer ID is ignored. $cookie = ( new WC_Session_Handler() )->get_session_cookie(); if ( $cookie ) { $customer = (string) $cookie[0]; } } if ( ! $customer && is_user_logged_in() ) { $customer = (string) get_current_user_id(); } if ( ! $customer ) { return array( '', '', true ); } global $wpdb; $session = maybe_unserialize( (string) $wpdb->get_var( $wpdb->prepare( 'SELECT session_value FROM %i WHERE session_key = %s', $wpdb->prefix . 'woocommerce_sessions', $customer ) ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the cart as stored right now, before WooCommerce loads it. $cart = is_array( $session ) && isset( $session['cart'] ) ? (string) $session['cart'] : ''; $items = maybe_unserialize( $cart ); return array( $customer, md5( $cart ), empty( $items ) ); } /** * The response WooCommerce would have sent for an order already placed by this submission. * * @param int $order_id Order ID. * @return WP_REST_Response */ function sofrah_board_existing_checkout_response( $order_id ) { $o = wc_get_order( $order_id ); return new WP_REST_Response( array( 'order_id' => $o->get_id(), 'status' => $o->get_status(), 'order_key' => $o->get_order_key(), 'order_number' => $o->get_order_number(), 'customer_note' => '', 'customer_id' => $o->get_customer_id(), 'billing_address' => (object) $o->get_address( 'billing' ), 'shipping_address' => (object) $o->get_address( 'shipping' ), 'payment_method' => $o->get_payment_method(), 'payment_result' => array( 'payment_status' => 'success', 'payment_details' => array(), 'redirect_url' => $o->get_checkout_order_received_url(), ), 'additional_fields' => new stdClass(), 'extensions' => new stdClass(), ), 200 ); } add_filter( 'rest_pre_dispatch', function ( $result, $server, $request ) { if ( null !== $result || ! sofrah_board_is_store_checkout( $request ) ) { return $result; } global $wpdb; $table = sofrah_board_submissions_table(); list( $customer, $hash, $empty ) = sofrah_board_store_cart( $request ); $client = (string) $request->get_header( 'x_sofrah_submission' ); $derived = ! preg_match( '/^[A-Za-z0-9-]{16,64}$/', $client ); if ( $derived && ! $customer ) { return $result; // Nothing to tie the request to. } $key = hash( 'sha256', $derived ? 'd:' . $customer : 'k:' . $client ); $deadline = microtime( true ) + 10; while ( true ) { // A claim with no order after 60 s failed; a key derived from the cart session lasts 2 minutes. $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE k = %s AND ( ( order_id IS NULL AND created < %d ) OR ( derived = 1 AND created < %d ) )', $table, $key, time() - 60, time() - 120 ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. if ( 1 === (int) $wpdb->query( $wpdb->prepare( 'INSERT IGNORE INTO %i (k, cart, created, derived) VALUES (%s, %s, %d, %d)', $table, $key, $hash, time(), $derived ? 1 : 0 ) ) ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. $GLOBALS['sofrah_board_submission'] = $key; return $result; } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT cart, order_id, done FROM %i WHERE k = %s', $table, $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. if ( $row && $row->order_id ) { // WooCommerce empties the cart as it places the order. A cart that is full again (different contents, // or the same contents more than 3 seconds later) was filled again: that is a new order. if ( ! $empty && ( $hash !== $row->cart || ( $row->done && time() - (int) $row->done > 3 ) ) ) { $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE k = %s AND order_id = %d', $table, $key, $row->order_id ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. continue; } return sofrah_board_existing_checkout_response( (int) $row->order_id ); } if ( microtime( true ) > $deadline ) { return new WP_Error( 'sofrah_board_in_progress', __( 'Your order is already being placed. Please wait a moment and check your email.', 'sofrah-order-board' ), array( 'status' => 409 ) ); } usleep( 150000 ); } }, 5, 3 ); add_action( 'woocommerce_store_api_checkout_order_processed', function ( $order ) { if ( empty( $GLOBALS['sofrah_board_submission'] ) ) { return; } global $wpdb; $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table. sofrah_board_submissions_table(), array( 'order_id' => $order->get_id(), 'done' => time(), ), array( 'k' => $GLOBALS['sofrah_board_submission'] ) ); } ); add_filter( 'rest_post_dispatch', function ( $response, $server, $request ) { if ( empty( $GLOBALS['sofrah_board_submission'] ) ) { return $response; } global $wpdb; $key = $GLOBALS['sofrah_board_submission']; $table = sofrah_board_submissions_table(); unset( $GLOBALS['sofrah_board_submission'] ); $data = $response instanceof WP_REST_Response ? $response->get_data() : array(); if ( $response->get_status() < 300 && ! empty( $data['order_id'] ) ) { $wpdb->query( $wpdb->prepare( 'UPDATE %i SET order_id = %d, done = COALESCE(done, %d) WHERE k = %s', $table, (int) $data['order_id'], time(), $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. } else { $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE k = %s AND order_id IS NULL', $table, $key ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- failed: a retry may go ahead. } return $response; }, 10, 3 ); // The browser side: one key per checkout attempt, kept until the order is placed, sent with the checkout request. add_action( 'wp_enqueue_scripts', function () { if ( ! function_exists( 'is_checkout' ) || ! is_checkout() ) { return; } wp_register_script( 'sob-submission', '', array(), SOFRAH_BOARD_VERSION, false ); wp_enqueue_script( 'sob-submission' ); if ( function_exists( 'is_order_received_page' ) && is_order_received_page() ) { wp_add_inline_script( 'sob-submission', "try{localStorage.removeItem('sofrah_board_submission')}catch(e){}" ); return; } wp_add_inline_script( 'sob-submission', "(function(){var K='sofrah_board_submission';function mk(){return(window.crypto&&crypto.randomUUID)?crypto.randomUUID():Date.now().toString(36)+'-'+Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2);}" . "function key(){try{var k=localStorage.getItem(K);if(!k){k=mk();localStorage.setItem(K,k);}return k;}catch(e){return window.__sofrahBoardKey||(window.__sofrahBoardKey=mk());}}" . "var f=window.fetch;window.fetch=function(input,init){try{var url=typeof input==='string'?input:(input&&input.url)||'';var m=((init&&init.method)||(input&&input.method)||'GET').toUpperCase();" . "if(m==='POST'&&/wc\\/store\\/v1\\/checkout(\\?|&|$)/.test(decodeURIComponent(url))){init=init||{};var h=new Headers(init.headers||{});h.set('X-Sofrah-Submission',key());init.headers=h;" . "return f.call(window,input,init).catch(function(){return new Promise(function(r){setTimeout(r,1500);}).then(function(){return f.call(window,input,init);});});}}catch(e){}return f.call(this,input,init);};})();" ); } ); // Old keys are removed daily. add_action( 'init', function () { if ( ! wp_next_scheduled( 'sofrah_board_daily_cleanup' ) ) { wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'sofrah_board_daily_cleanup' ); } } ); add_action( 'sofrah_board_daily_cleanup', function () { global $wpdb; $table = sofrah_board_submissions_table(); $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE created < %d', $table, time() - DAY_IN_SECONDS ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the plugin's own table; an uncached, atomic read and write is the point. } );