1
0

trafficlimiter.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.21
  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. * time limit in seconds, defaults to 10s
  21. *
  22. * @access private
  23. * @static
  24. * @var int
  25. */
  26. private static $_limit = 10;
  27. /**
  28. * set the time limit in seconds
  29. *
  30. * @access public
  31. * @static
  32. * @param int $limit
  33. * @return void
  34. */
  35. public static function setLimit($limit)
  36. {
  37. self::$_limit = $limit;
  38. }
  39. /**
  40. * traffic limiter
  41. *
  42. * Make sure the IP address makes at most 1 request every 10 seconds.
  43. *
  44. * @access public
  45. * @static
  46. * @param string $ip
  47. * @throws Exception
  48. * @return bool
  49. */
  50. public static function canPass($ip)
  51. {
  52. // disable limits if set to less then 1
  53. if (self::$_limit < 1) return true;
  54. $file = 'traffic_limiter.php';
  55. if (!self::_exists($file))
  56. {
  57. self::_store(
  58. $file,
  59. '<?php' . PHP_EOL .
  60. '$GLOBALS[\'traffic_limiter\'] = array();' . PHP_EOL
  61. );
  62. }
  63. $path = self::getPath($file);
  64. require $path;
  65. $now = time();
  66. $tl = $GLOBALS['traffic_limiter'];
  67. // purge file of expired IPs to keep it small
  68. foreach($tl as $key => $time)
  69. {
  70. if ($time + self::$_limit < $now)
  71. {
  72. unset($tl[$key]);
  73. }
  74. }
  75. if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now))
  76. {
  77. $result = false;
  78. } else {
  79. $tl[$ip] = time();
  80. $result = true;
  81. }
  82. self::_store(
  83. $file,
  84. '<?php' . PHP_EOL .
  85. '$GLOBALS[\'traffic_limiter\'] = ' .
  86. var_export($tl, true) . ';' . PHP_EOL
  87. );
  88. return $result;
  89. }
  90. }