trafficlimiter.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. * 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. * @return bool
  48. */
  49. public static function canPass($ip)
  50. {
  51. // disable limits if set to less then 1
  52. if (self::$_limit < 1) return true;
  53. $file = 'traffic_limiter.php';
  54. if (!self::_exists($file))
  55. {
  56. self::_store(
  57. $file,
  58. '<?php' . PHP_EOL .
  59. '$GLOBALS[\'traffic_limiter\'] = array();' . PHP_EOL
  60. );
  61. }
  62. $path = self::getPath($file);
  63. require $path;
  64. $now = time();
  65. $tl = $GLOBALS['traffic_limiter'];
  66. // purge file of expired IPs to keep it small
  67. foreach($tl as $key => $time)
  68. {
  69. if ($time + self::$_limit < $now)
  70. {
  71. unset($tl[$key]);
  72. }
  73. }
  74. if (array_key_exists($ip, $tl) && ($tl[$ip] + self::$_limit >= $now))
  75. {
  76. $result = false;
  77. } else {
  78. $tl[$ip] = time();
  79. $result = true;
  80. }
  81. self::_store(
  82. $file,
  83. '<?php' . PHP_EOL .
  84. '$GLOBALS[\'traffic_limiter\'] = ' .
  85. var_export($tl, true) . ';' . PHP_EOL
  86. );
  87. return $result;
  88. }
  89. }