state( $bucket, $window ); if ( $state['count'] >= $limit ) { return false; } $this->save( $bucket, $state['count'] + 1, $state['reset'] ); return true; } /** * Whether the limit is already reached, without counting. * * @since 0.1.0 * * @param string $bucket Name. * @param int $limit Hits allowed per window. * @param int $window Window in seconds. * @return bool */ public function blocked( string $bucket, int $limit, int $window ): bool { return $this->state( $bucket, $window )['count'] >= $limit; } /** * Counts a hit without checking the limit (used to count only failures). * * @since 0.1.0 * * @param string $bucket Name. * @param int $window Window in seconds. * @return void */ public function record( string $bucket, int $window ): void { $state = $this->state( $bucket, $window ); $this->save( $bucket, $state['count'] + 1, $state['reset'] ); } /** * Transient key for a bucket and the current visitor. * * @param string $bucket Bucket. * @return string */ private function key( string $bucket ): string { return 'interviewnea_rl_' . substr( hash_hmac( 'sha256', $bucket . '|' . Helpers::client_ip(), wp_salt( 'nonce' ) ), 0, 32 ); } /** * Current counter. * * @param string $bucket Bucket. * @param int $window Window in seconds. * @return array{count:int,reset:int} */ private function state( string $bucket, int $window ): array { $stored = get_transient( $this->key( $bucket ) ); if ( is_array( $stored ) && isset( $stored['count'], $stored['reset'] ) && (int) $stored['reset'] > time() ) { return array( 'count' => (int) $stored['count'], 'reset' => (int) $stored['reset'], ); } return array( 'count' => 0, 'reset' => time() + $window, ); } /** * Stores the counter until the window ends. * * @param string $bucket Bucket. * @param int $count Hits so far. * @param int $reset Unix time the window ends. * @return void */ private function save( string $bucket, int $count, int $reset ): void { set_transient( $this->key( $bucket ), array( 'count' => $count, 'reset' => $reset, ), max( 1, $reset - time() ) ); } }