|
| 1 | +<?php // phpcs:ignore WordPress.Files.FileName |
| 2 | + |
| 3 | +/** |
| 4 | + * Redux Rate Limiter Class |
| 5 | + * |
| 6 | + * @class Secure Token |
| 7 | + * @version 4.5.10 |
| 8 | + * @package Redux Framework/Classes |
| 9 | + */ |
| 10 | + |
| 11 | +defined( 'ABSPATH' ) || exit; |
| 12 | + |
| 13 | +if ( ! class_exists( 'Redux_Rate_Limiter', false ) ) { |
| 14 | + |
| 15 | + /** |
| 16 | + * Redux_Rate_Limiter. |
| 17 | + * |
| 18 | + * @since 4.5.10 |
| 19 | + */ |
| 20 | + class Redux_Rate_Limiter { |
| 21 | + |
| 22 | + /** |
| 23 | + * Limits for functions that require them. |
| 24 | + * |
| 25 | + * @var array[] |
| 26 | + */ |
| 27 | + private static array $limits = array( |
| 28 | + 'download_options' => array( |
| 29 | + 'max' => 5, |
| 30 | + 'window' => 300, |
| 31 | + ), // 5 per 5 minutes. |
| 32 | + 'color_schemes' => array( |
| 33 | + 'max' => 5, |
| 34 | + 'window' => 300, |
| 35 | + ), // 5 per 5 minutes. |
| 36 | + ); |
| 37 | + |
| 38 | + /** |
| 39 | + * Check for the rate limit. |
| 40 | + * |
| 41 | + * @param string $action Function to check. |
| 42 | + * |
| 43 | + * @return bool |
| 44 | + */ |
| 45 | + public static function check( string $action ): bool { |
| 46 | + if ( ! isset( self::$limits[ $action ] ) ) { |
| 47 | + return true; |
| 48 | + } |
| 49 | + |
| 50 | + $limit = self::$limits[ $action ]; |
| 51 | + |
| 52 | + $ip = self::get_client_ip(); |
| 53 | + $key = 'redux_rate_' . md5( $action . $ip ); |
| 54 | + |
| 55 | + $current = get_transient( $key ); |
| 56 | + |
| 57 | + if ( false === $current ) { |
| 58 | + set_transient( $key, 1, $limit['window'] ); |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + if ( $current >= $limit['max'] ) { |
| 63 | + return false; // Rate limited. |
| 64 | + } |
| 65 | + |
| 66 | + set_transient( $key, $current + 1, $limit['window'] ); |
| 67 | + return true; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Get the client's IP address. |
| 72 | + * |
| 73 | + * @return mixed|string |
| 74 | + */ |
| 75 | + private static function get_client_ip() { |
| 76 | + $ip = Redux_Core::$server['REMOTE_ADDR']; |
| 77 | + |
| 78 | + if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) { |
| 79 | + $ips = explode( ',', Redux_Core::$server['HTTP_X_FORWARDED_FOR'] ); |
| 80 | + $ip = trim( $ips[0] ); |
| 81 | + } |
| 82 | + |
| 83 | + return filter_var( $ip, FILTER_VALIDATE_IP ) ?? '0.0.0.0'; |
| 84 | + } |
| 85 | + } |
| 86 | +} |
0 commit comments