| 1 |
<?php |
| 2 |
/** |
| 3 |
* Rate Limiter Service |
| 4 |
* |
| 5 |
* Rate-limiting via WordPress Transients for opt-in creation. |
| 6 |
* |
| 7 |
* @package Forge12\DoubleOptIn\Service |
| 8 |
* @since 3.3.0 |
| 9 |
*/ |
| 10 |
|
| 11 |
namespace Forge12\DoubleOptIn\Service; |
| 12 |
|
| 13 |
if ( ! defined( 'ABSPATH' ) ) { |
| 14 |
exit; |
| 15 |
} |
| 16 |
|
| 17 |
/** |
| 18 |
* Class RateLimiter |
| 19 |
* |
| 20 |
* Provides rate-limiting functionality using WordPress transients. |
| 21 |
*/ |
| 22 |
class RateLimiter { |
| 23 |
|
| 24 |
/** |
| 25 |
* Check if an action is allowed within the rate limit. |
| 26 |
* |
| 27 |
* @param string $type The type of limit (e.g., 'ip', 'email'). |
| 28 |
* @param string $identifier The identifier to limit (e.g., IP address, email). |
| 29 |
* @param int $maxAttempts Maximum number of attempts allowed. |
| 30 |
* @param int $windowMinutes Time window in minutes. |
| 31 |
* |
| 32 |
* @return bool True if the action is allowed. |
| 33 |
*/ |
| 34 |
public function isAllowed( string $type, string $identifier, int $maxAttempts, int $windowMinutes ): bool { |
| 35 |
if ( $maxAttempts <= 0 ) { |
| 36 |
return true; |
| 37 |
} |
| 38 |
|
| 39 |
$key = 'doi_rate_' . $type . '_' . md5( $identifier ); |
| 40 |
$current = (int) get_transient( $key ); |
| 41 |
|
| 42 |
if ( $current >= $maxAttempts ) { |
| 43 |
return false; |
| 44 |
} |
| 45 |
|
| 46 |
set_transient( $key, $current + 1, $windowMinutes * 60 ); |
| 47 |
|
| 48 |
return true; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Get the number of remaining attempts. |
| 53 |
* |
| 54 |
* @param string $type The type of limit. |
| 55 |
* @param string $identifier The identifier. |
| 56 |
* @param int $maxAttempts Maximum number of attempts allowed. |
| 57 |
* |
| 58 |
* @return int The remaining attempts. |
| 59 |
*/ |
| 60 |
public function getRemainingAttempts( string $type, string $identifier, int $maxAttempts ): int { |
| 61 |
$key = 'doi_rate_' . $type . '_' . md5( $identifier ); |
| 62 |
$current = (int) get_transient( $key ); |
| 63 |
|
| 64 |
return max( 0, $maxAttempts - $current ); |
| 65 |
} |
| 66 |
} |
| 67 |
|