query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $option, $value ) ); if ( $inserted ) { return $value; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- read past the options cache on purpose. $held = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $option ) ); if ( ! is_string( $held ) || (int) $held > time() ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- compare-and-set: only one request replaces the expired value. $taken = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_value = %s WHERE option_name = %s AND option_value = %s", $value, $option, $held ) ); return $taken ? $value : false; } /** * Releases a lock this request holds. * * @since 1.0.0 * * @param string $name The lock's name. * @param string $token The token acquire() gave. * @return void */ public static function release( $name, $token ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- the row was written past the cache, and is removed the same way. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", self::option( $name ), (string) $token ) ); } /** * The option a lock lives in. * * @param string $name The lock's name. * @return string */ private static function option( $name ) { return 'thirddraft_lock_' . preg_replace( '/[^a-z0-9_]/', '', strtolower( (string) $name ) ); } }