1
0

trafficlimiter.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 trafficlimiter
  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. // Create storage directory if it does not exist.
  68. if (!is_dir(self::$_path)) mkdir(self::$_path, 0705);
  69. // Create .htaccess file if it does not exist.
  70. if (!is_file(self::$_path . '/.htaccess'))
  71. {
  72. file_put_contents(
  73. self::$_path . '/.htaccess',
  74. 'Allow from none' . PHP_EOL .
  75. 'Deny from all'. PHP_EOL
  76. );
  77. }
  78. $file = self::$_path . '/traffic_limiter.php';
  79. if (!is_file($file))
  80. {
  81. file_put_contents(
  82. $file,
  83. '<?php' . PHP_EOL .
  84. '$GLOBALS[\'traffic_limiter\'] = array();' . PHP_EOL
  85. );
  86. chmod($file, 0705);
  87. }
  88. require $file;
  89. $tl = $GLOBALS['traffic_limiter'];
  90. // purge file of expired IPs to keep it small
  91. foreach($tl as $key => $time)
  92. {
  93. if ($time + 10 < time())
  94. {
  95. unset($tl[$key]);
  96. }
  97. }
  98. if (array_key_exists($ip, $tl) && ($tl[$ip] + 10 >= time()))
  99. {
  100. $result = false;
  101. } else {
  102. $tl[$ip] = time();
  103. $result = true;
  104. }
  105. file_put_contents(
  106. $file,
  107. '<?php' . PHP_EOL .
  108. '$GLOBALS[\'traffic_limiter\'] = ' .
  109. var_export($tl, true) . ';' . PHP_EOL
  110. );
  111. return $result;
  112. }
  113. }