Filter.php 2.6 KB

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