PurgeLimiter.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin\Persistence;
  12. use PrivateBin\Configuration;
  13. /**
  14. * PurgeLimiter
  15. *
  16. * Handles purge limiting, so purging is not triggered too frequently.
  17. */
  18. class PurgeLimiter extends AbstractPersistence
  19. {
  20. /**
  21. * time limit in seconds, defaults to 300s
  22. *
  23. * @access private
  24. * @static
  25. * @var int
  26. */
  27. private static $_limit = 300;
  28. /**
  29. * set the time limit in seconds
  30. *
  31. * @access public
  32. * @static
  33. * @param int $limit
  34. */
  35. public static function setLimit($limit)
  36. {
  37. self::$_limit = $limit;
  38. }
  39. /**
  40. * set configuration options of the traffic limiter
  41. *
  42. * @access public
  43. * @static
  44. * @param Configuration $conf
  45. */
  46. public static function setConfiguration(Configuration $conf)
  47. {
  48. self::setLimit($conf->getKey('limit', 'purge'));
  49. }
  50. /**
  51. * check if the purge can be performed
  52. *
  53. * @access public
  54. * @static
  55. * @return bool
  56. */
  57. public static function canPurge()
  58. {
  59. // disable limits if set to less then 1
  60. if (self::$_limit < 1) {
  61. return true;
  62. }
  63. $now = time();
  64. $pl = (int) self::$_store->getValue('purge_limiter');
  65. if ($pl + self::$_limit >= $now) {
  66. return false;
  67. }
  68. $hasStored = self::$_store->setValue((string) $now, 'purge_limiter');
  69. if (!$hasStored) {
  70. error_log('failed to store the purge limiter, skipping purge cycle to avoid getting stuck in a purge loop');
  71. }
  72. return $hasStored;
  73. }
  74. }