prefix . 'aha_is_woocommerce_order_map'; } /** * Create or update the table. * * Note on `status`: it has 3 fixed values. The column is a VARCHAR(16) * because dbDelta does not parse an ENUM definition reliably and would run * an ALTER TABLE on every request. The three values are constants on this * class and nothing else writes the column. * * @return void */ public static function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table_name(); $collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, aha_order_id varchar(64) NOT NULL, wc_order_id bigint(20) unsigned DEFAULT NULL, status varchar(16) NOT NULL DEFAULT 'claimed', error_code varchar(64) DEFAULT NULL, error_message text DEFAULT NULL, http_status smallint(5) unsigned DEFAULT NULL, claimed_at datetime NOT NULL, created_at datetime NOT NULL, updated_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY aha_order_id (aha_order_id), KEY status_claimed_at (status,claimed_at) ) {$collate};"; dbDelta( $sql ); update_option( self::OPTION_SCHEMA_VERSION, self::SCHEMA_VERSION, false ); } /** * Run install() again when the layout version moved. * * @return void */ public static function maybe_upgrade() { if ( (string) get_option( self::OPTION_SCHEMA_VERSION, '' ) !== self::SCHEMA_VERSION ) { self::install(); } } /** * Try to claim an aha_order_id. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @return bool True when this request owns the claim. */ public static function claim( $aha_is_woocommerce_order_id ) { global $wpdb; $now = self::now(); // Let the UNIQUE key reject a duplicate instead of reading first. A read // then write would leave a race between the two statements. $suppress = $wpdb->suppress_errors( true ); $inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, the UNIQUE key is the atomic claim. self::table_name(), array( 'aha_order_id' => $aha_is_woocommerce_order_id, 'status' => self::STATUS_CLAIMED, 'claimed_at' => $now, 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%s', '%s' ) ); $wpdb->suppress_errors( $suppress ); return (bool) $inserted; } /** * Read a row. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @return array|null Row with claimed_at as a Unix time, or null. */ public static function get( $aha_is_woocommerce_order_id ) { global $wpdb; $table = esc_sql( self::table_name() ); $row = $wpdb->get_row( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, read must see the live claim state. $wpdb->prepare( "SELECT * FROM {$table} WHERE aha_order_id = %s", $aha_is_woocommerce_order_id ), // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is plugin-owned and esc_sql'd; values are prepared. ARRAY_A ); if ( ! $row ) { return null; } $row['claimed_at'] = self::to_unix( $row['claimed_at'] ); $row['wc_order_id'] = null === $row['wc_order_id'] ? null : (int) $row['wc_order_id']; $row['http_status'] = null === $row['http_status'] ? null : (int) $row['http_status']; return $row; } /** * Take over a stale claim. * * The WHERE clause repeats the claimed_at value that this request read, so * only one of two concurrent recoverers wins. The loser gets 0 rows and * answers 409. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @param int $seen_claimed_at Unix time this request read. * @return bool True when this request now owns the claim. */ public static function reclaim( $aha_is_woocommerce_order_id, $seen_claimed_at ) { global $wpdb; $table = esc_sql( self::table_name() ); $now = self::now(); $updated = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, atomic compare-and-set claim. $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is plugin-owned and esc_sql'd; values are prepared. "UPDATE {$table} SET claimed_at = %s, updated_at = %s WHERE aha_order_id = %s AND status = %s AND claimed_at = %s", $now, $now, $aha_is_woocommerce_order_id, self::STATUS_CLAIMED, self::to_mysql( $seen_claimed_at ) ) ); return $updated > 0; } /** * Mark a claim as created. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @param int $wc_order_id WooCommerce order id. * @return void */ public static function mark_created( $aha_is_woocommerce_order_id, $wc_order_id ) { global $wpdb; $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, write must hit the live row. self::table_name(), array( 'wc_order_id' => (int) $wc_order_id, 'status' => self::STATUS_CREATED, 'error_code' => null, 'error_message' => null, 'http_status' => null, 'updated_at' => self::now(), ), array( 'aha_order_id' => $aha_is_woocommerce_order_id ), array( '%d', '%s', '%s', '%s', '%d', '%s' ), array( '%s' ) ); } /** * Mark a claim as failed and store the error so a retry replays it. * * Only a permanent error is stored. A temporary error releases the claim * instead, so the next retry can try again. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @param string $code Error code from the Aha contract. * @param string $message Human readable text. * @param int $http_status HTTP status to replay. * @return void */ public static function mark_failed( $aha_is_woocommerce_order_id, $code, $message, $http_status ) { global $wpdb; $wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, write must hit the live row. self::table_name(), array( 'status' => self::STATUS_FAILED, 'error_code' => $code, 'error_message' => $message, 'http_status' => (int) $http_status, 'updated_at' => self::now(), ), array( 'aha_order_id' => $aha_is_woocommerce_order_id ), array( '%s', '%s', '%s', '%d', '%s' ), array( '%s' ) ); } /** * Delete a claim. * * Used when the plugin could not finish for a reason a retry can fix. The * next request then claims the id cleanly. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @return void */ public static function release( $aha_is_woocommerce_order_id ) { global $wpdb; $wpdb->delete( self::table_name(), array( 'aha_order_id' => $aha_is_woocommerce_order_id ), array( '%s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, releases the claim. } /** * Find an order by its aha_is_woocommerce_order_id meta, without meta_query. * * This code does not use meta_query: it is slow and it behaves differently * between the post store and HPOS. This reads the right meta table itself. * * @param string $aha_is_woocommerce_order_id Idempotency key. * @return int Order id, or 0 when nothing matches. */ public static function find_order_id_by_meta( $aha_is_woocommerce_order_id ) { global $wpdb; if ( self::hpos_enabled() ) { $table = esc_sql( $wpdb->prefix . 'wc_orders_meta' ); $found = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- WooCommerce HPOS meta table has no cached lookup by value. $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is $wpdb->prefix plus a literal, esc_sql'd; values are prepared. "SELECT order_id FROM {$table} WHERE meta_key = %s AND meta_value = %s ORDER BY order_id ASC LIMIT 1", Aha_Is_Woocommerce_Order_Factory::META_ORDER_ID, $aha_is_woocommerce_order_id ) ); if ( $found ) { return (int) $found; } // Fall through: a store can hold old orders in the post table. } $found = $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- postmeta lookup by value has no cached API. $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- $wpdb->postmeta is a core table name; values are prepared. "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s ORDER BY post_id ASC LIMIT 1", Aha_Is_Woocommerce_Order_Factory::META_ORDER_ID, $aha_is_woocommerce_order_id ) ); return $found ? (int) $found : 0; } /** * Most recently updated map rows, newest first. Read-only. * * @param int $limit Row limit. * @param string $status Optional status to filter by; only the known statuses are applied. * @return array[] Rows with aha_order_id, wc_order_id, status, updated_at. */ public static function recent( $limit = 20, $status = '' ) { global $wpdb; $limit = max( 1, (int) $limit ); $table = esc_sql( self::table_name() ); if ( in_array( $status, array( self::STATUS_CLAIMED, self::STATUS_CREATED, self::STATUS_FAILED ), true ) ) { $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, admin list must be live. $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table is plugin-owned and esc_sql'd; values are prepared. "SELECT aha_order_id, wc_order_id, status, error_code, updated_at FROM `{$table}` WHERE status = %s ORDER BY updated_at DESC, id DESC LIMIT %d", $status, $limit ), ARRAY_A ); } else { $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching -- own table, admin list must be live. $wpdb->prepare( // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table is plugin-owned and esc_sql'd; the limit is prepared. "SELECT aha_order_id, wc_order_id, status, error_code, updated_at FROM `{$table}` ORDER BY updated_at DESC, id DESC LIMIT %d", $limit ), ARRAY_A ); } return is_array( $rows ) ? $rows : array(); } /** * Whether the store keeps orders in the HPOS tables. * * @return bool */ public static function hpos_enabled() { if ( ! class_exists( '\Automattic\WooCommerce\Utilities\OrderUtil' ) ) { return false; // WC older than 6.5 has no HPOS at all. } if ( ! method_exists( '\Automattic\WooCommerce\Utilities\OrderUtil', 'custom_orders_table_usage_is_enabled' ) ) { return false; } return (bool) \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled(); } /** * Current time in MySQL format, UTC. * * @return string */ private static function now() { return gmdate( 'Y-m-d H:i:s' ); } /** * Convert a MySQL datetime to Unix time. * * @param string $value MySQL datetime in UTC. * @return int */ private static function to_unix( $value ) { $parsed = strtotime( $value . ' UTC' ); return false === $parsed ? 0 : $parsed; } /** * Convert a Unix time to MySQL format, UTC. * * @param int $unix Unix time. * @return string */ private static function to_mysql( $unix ) { return gmdate( 'Y-m-d H:i:s', (int) $unix ); } }