trafficlimiter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. /**
  3. * ZeroBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link http://sebsauvage.net/wiki/doku.php?id=php:zerobin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license http://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. * @version 0.19
  11. */
  12. /**
  13. * trafficlimiter
  14. *
  15. * Handles traffic limiting, so no user does more than one call per 10 seconds.
  16. */
  17. class trafficlimiter extends persistence
  18. {
  19. /**
  20. * @access private
  21. * @static
  22. * @var int
  23. */
  24. private static $_limit = 10;
  25. /**
  26. * set the time limit in seconds
  27. *
  28. * @access public
  29. * @static
  30. * @param int $limit
  31. * @return void
  32. */
  33. public static function setLimit($limit)
  34. {
  35. self::$_limit = $limit;
  36. }
  37. /**
  38. * traffic limiter
  39. *
  40. * Make sure the IP address makes at most 1 request every 10 seconds.
  41. *
  42. * @access public
  43. * @static
  44. * @param string $ip
  45. * @return bool
  46. */
  47. public static function canPass($ip)
  48. {
  49. // disable limits if set to less then 1
  50. if (self::$_limit < 1) return true;
  51. $file = 'traffic_limiter.php';
  52. if (!self::_exists($file))
  53. {
  54. self::_store(
  55. $file,
  56. '<?php' . PHP_EOL .
  57. '$GLOBALS[\'traffic_limiter\'] = array();' . PHP_EOL
  58. );
  59. }
  60. $path = self::getPath($file);
  61. require $path;
  62. $now = time();
  63. $tl = $GLOBALS['traffic_limiter'];
  64. // purge file of expired IPs to keep it small
  65. foreach($tl as $key => $time)
  66. {
  67. if ($time + self::$_limit < $now)
  68. {
  69. unset($tl[$key]);
  70. }
  71. }
  72. if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now))
  73. {
  74. $result = false;
  75. } else {
  76. $tl[$ip] = time();
  77. $result = true;
  78. }
  79. self::_store(
  80. $file,
  81. '<?php' . PHP_EOL .
  82. '$GLOBALS[\'traffic_limiter\'] = ' .
  83. var_export($tl, true) . ';' . PHP_EOL
  84. );
  85. return $result;
  86. }
  87. }