filter.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  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. * @version 0.22
  11. */
  12. namespace PrivateBin;
  13. use Exception;
  14. use PrivateBin\i18n;
  15. /**
  16. * filter
  17. *
  18. * Provides data filtering functions.
  19. */
  20. class filter
  21. {
  22. /**
  23. * strips slashes deeply
  24. *
  25. * @access public
  26. * @static
  27. * @param mixed $value
  28. * @return mixed
  29. */
  30. public static function stripslashes_deep($value)
  31. {
  32. return is_array($value) ?
  33. array_map('PrivateBin\\filter::stripslashes_deep', $value) :
  34. stripslashes($value);
  35. }
  36. /**
  37. * format a given time string into a human readable label (localized)
  38. *
  39. * accepts times in the format "[integer][time unit]"
  40. *
  41. * @access public
  42. * @static
  43. * @param string $time
  44. * @throws Exception
  45. * @return string
  46. */
  47. public static function time_humanreadable($time)
  48. {
  49. if (preg_match('/^(\d+) *(\w+)$/', $time, $matches) !== 1) {
  50. throw new Exception("Error parsing time format '$time'", 30);
  51. }
  52. switch ($matches[2]) {
  53. case 'sec':
  54. $unit = 'second';
  55. break;
  56. case 'min':
  57. $unit = 'minute';
  58. break;
  59. default:
  60. $unit = rtrim($matches[2], 's');
  61. }
  62. return i18n::_(array('%d ' . $unit, '%d ' . $unit . 's'), (int) $matches[1]);
  63. }
  64. /**
  65. * format a given number of bytes in IEC 80000-13:2008 notation (localized)
  66. *
  67. * @access public
  68. * @static
  69. * @param int $size
  70. * @return string
  71. */
  72. public static function size_humanreadable($size)
  73. {
  74. $iec = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB');
  75. $i = 0;
  76. while (($size / 1024) >= 1) {
  77. $size = $size / 1024;
  78. $i++;
  79. }
  80. return number_format($size, ($i ? 2 : 0), '.', ' ') . ' ' . i18n::_($iec[$i]);
  81. }
  82. /**
  83. * fixed time string comparison operation to prevent timing attacks
  84. * https://crackstation.net/hashing-security.htm?=rd#slowequals
  85. *
  86. * @access public
  87. * @static
  88. * @param string $a
  89. * @param string $b
  90. * @return bool
  91. */
  92. public static function slow_equals($a, $b)
  93. {
  94. $diff = strlen($a) ^ strlen($b);
  95. for ($i = 0; $i < strlen($a) && $i < strlen($b); $i++) {
  96. $diff |= ord($a[$i]) ^ ord($b[$i]);
  97. }
  98. return $diff === 0;
  99. }
  100. }