functions.inc.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. function format_html($str) {
  3. global $server;
  4. if (isset($server['charset']) && $server['charset']) {
  5. $res = mb_convert_encoding($str, 'utf-8', $server['charset']);
  6. } else {
  7. $res = $str;
  8. }
  9. $res = htmlentities($res, defined('ENT_SUBSTITUTE') ? (ENT_QUOTES | ENT_SUBSTITUTE) : ENT_QUOTES, 'utf-8');
  10. return ($res || !$str) ? $res : '(' . strlen($str) . ' bytes)';
  11. }
  12. function input_convert($str) {
  13. global $server;
  14. if (isset($server['charset']) && $server['charset']) {
  15. return mb_convert_encoding($str, $server['charset'], 'utf-8');
  16. } else {
  17. return $str;
  18. }
  19. }
  20. function format_ago($time, $ago = false) {
  21. $minute = 60;
  22. $hour = $minute * 60;
  23. $day = $hour * 24;
  24. $when = $time;
  25. if ($when >= 0)
  26. $suffix = 'ago';
  27. else {
  28. $when = -$when;
  29. $suffix = 'in the future';
  30. }
  31. if ($when > $day) {
  32. $when = round($when / $day);
  33. $what = 'day';
  34. } else if ($when > $hour) {
  35. $when = round($when / $hour);
  36. $what = 'hour';
  37. } else if ($when > $minute) {
  38. $when = round($when / $minute);
  39. $what = 'minute';
  40. } else {
  41. $what = 'second';
  42. }
  43. if ($when != 1) $what .= 's';
  44. if ($ago) {
  45. return "$when $what $suffix";
  46. } else {
  47. return "$when $what";
  48. }
  49. }
  50. function format_size($size) {
  51. $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  52. if ($size == 0) {
  53. return '0 B';
  54. } else {
  55. return round($size / pow(1024, ($i = floor(log($size, 1024)))), 1).' '.$sizes[$i];
  56. }
  57. }
  58. function str_rand($length) {
  59. $r = '';
  60. for (; $length > 0; --$length) {
  61. $r .= chr(rand(32, 126)); // 32 - 126 is the printable ascii range
  62. }
  63. return $r;
  64. }
  65. function encodeOrDecode($action, $key, $data) {
  66. global $server;
  67. if (isset($_GET['raw']) || !isset($server['serialization'])) {
  68. return $data;
  69. }
  70. foreach ($server['serialization'] as $pattern => $closures) {
  71. if (fnmatch($pattern, $key)) {
  72. return $closures[$action]($data);
  73. }
  74. }
  75. return $data;
  76. }