true, 'retry_after' => 0 ); } $now = time(); $start = $now - ( $now % $window ); $key = hash( 'sha256', $bucket ); $t = AgentAdapt_Schema::table( 'rate' ); // phpcs:disable WordPress.DB.DirectDatabaseQuery $wpdb->query( $wpdb->prepare( "INSERT INTO %i (bucket, window_start, hits) VALUES (%s, %d, 1) ON DUPLICATE KEY UPDATE hits = hits + 1", $t, $key, $start ) ); $hits = (int) $wpdb->get_var( $wpdb->prepare( "SELECT hits FROM %i WHERE bucket = %s AND window_start = %d", $t, $key, $start ) ); // phpcs:enable return array( 'allowed' => $hits <= $limit, 'retry_after' => $hits <= $limit ? 0 : max( 1, $start + $window - $now ), ); } /** * Delete windows older than a day. */ public static function purge(): void { global $wpdb; $t = AgentAdapt_Schema::table( 'rate' ); $wpdb->query( $wpdb->prepare( "DELETE FROM %i WHERE window_start < %d", $t, time() - DAY_IN_SECONDS ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery } }