Brak opisu

class-wc-rate-limiter.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. /**
  3. * Provide basic rate limiting functionality via WP Options API.
  4. *
  5. * Currently only provides a simple limit by delaying action by X seconds.
  6. *
  7. * Example usage:
  8. *
  9. * When an action runs, call set_rate_limit, e.g.:
  10. *
  11. * WC_Rate_Limiter::set_rate_limit( "{$my_action_name}_{$user_id}", $delay );
  12. *
  13. * This sets a timestamp for future timestamp after which action can run again.
  14. *
  15. *
  16. * Then before running the action again, check if the action is allowed to run, e.g.:
  17. *
  18. * if ( WC_Rate_Limiter::retried_too_soon( "{$my_action_name}_{$user_id}" ) ) {
  19. * add_notice( 'Sorry, too soon!' );
  20. * }
  21. *
  22. * @package WooCommerce\Classes
  23. * @version 3.9.0
  24. * @since 3.9.0
  25. */
  26. defined( 'ABSPATH' ) || exit;
  27. /**
  28. * Rate limit class.
  29. */
  30. class WC_Rate_Limiter {
  31. /**
  32. * Constructs Option name from action identifier.
  33. *
  34. * @param string $action_id Identifier of the action.
  35. * @return string
  36. */
  37. public static function storage_id( $action_id ) {
  38. return 'woocommerce_rate_limit_' . $action_id;
  39. }
  40. /**
  41. * Returns true if the action is not allowed to be run by the rate limiter yet, false otherwise.
  42. *
  43. * @param string $action_id Identifier of the action.
  44. * @return bool
  45. */
  46. public static function retried_too_soon( $action_id ) {
  47. $next_try_allowed_at = get_option( self::storage_id( $action_id ) );
  48. // No record of action running, so action is allowed to run.
  49. if ( false === $next_try_allowed_at ) {
  50. return false;
  51. }
  52. // Before the next run is allowed, retry forbidden.
  53. if ( time() <= $next_try_allowed_at ) {
  54. return true;
  55. }
  56. // After the next run is allowed, retry allowed.
  57. return false;
  58. }
  59. /**
  60. * Sets the rate limit delay in seconds for action with identifier $id.
  61. *
  62. * @param string $action_id Identifier of the action.
  63. * @param int $delay Delay in seconds.
  64. * @return bool True if the option setting was successful, false otherwise.
  65. */
  66. public static function set_rate_limit( $action_id, $delay ) {
  67. $option_name = self::storage_id( $action_id );
  68. $next_try_allowed_at = time() + $delay;
  69. return update_option( $option_name, $next_try_allowed_at );
  70. }
  71. }