filter.php 2.6 KB

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