traffic_limiter.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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.15
  11. */
  12. /**
  13. * traffic_limiter
  14. *
  15. * Handles traffic limiting, so no user does more than one call per 10 seconds.
  16. */
  17. class traffic_limiter
  18. {
  19. /**
  20. * @access private
  21. * @static
  22. * @var int
  23. */
  24. private static $_limit = 10;
  25. /**
  26. * @access private
  27. * @static
  28. * @var string
  29. */
  30. private static $_path = 'data';
  31. /**
  32. * set the time limit in seconds
  33. *
  34. * @access public
  35. * @static
  36. * @param int $limit
  37. * @return void
  38. */
  39. public static function setLimit($limit)
  40. {
  41. self::$_limit = $limit;
  42. }
  43. /**
  44. * set the path
  45. *
  46. * @access public
  47. * @static
  48. * @param string $path
  49. * @return void
  50. */
  51. public static function setPath($path)
  52. {
  53. self::$_path = $path;
  54. }
  55. /**
  56. * traffic limiter
  57. *
  58. * Make sure the IP address makes at most 1 request every 10 seconds.
  59. *
  60. * @access public
  61. * @static
  62. * @param string $ip
  63. * @return bool
  64. */
  65. public static function canPass($ip)
  66. {
  67. if (!is_dir(self::$_path)) mkdir(self::$_path, 0705, true);
  68. $file = self::$_path . '/traffic_limiter.php';
  69. if (!is_file($file))
  70. {
  71. file_put_contents(
  72. $file,
  73. '<?php' . PHP_EOL .
  74. '$GLOBALS[\'traffic_limiter\'] = array();' . PHP_EOL
  75. );
  76. chmod($file, 0705);
  77. }
  78. require $file;
  79. $tl = $GLOBALS['traffic_limiter'];
  80. // purge file of expired IPs to keep it small
  81. foreach($tl as $key => $time)
  82. {
  83. if ($time + 10 < time())
  84. {
  85. unset($tl[$key]);
  86. }
  87. }
  88. if (array_key_exists($ip, $tl) && ($tl[$ip] + 10 >= time()))
  89. {
  90. $result = false;
  91. } else {
  92. $tl[$ip] = time();
  93. $result = true;
  94. }
  95. file_put_contents(
  96. $file,
  97. '<?php' . PHP_EOL .
  98. '$GLOBALS[\'traffic_limiter\'] = ' .
  99. var_export($tl, true) . ';' . PHP_EOL
  100. );
  101. return $result;
  102. }
  103. }