Filter.php 2.3 KB

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