Combu Server  3.1.1
PHP API Documentation
Utils.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Combu;
4 
5 class Utils {
6 
7  public static function IsIPv4($ip) {
8  return !empty($ip) && (FALSE !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4));
9  }
10 
11  public static function IsIPv6($ip) {
12  return !empty($ip) && (FALSE !== filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6));
13  }
14 
15  public static function DownloadUrl($url, $saveTo = NULL) {
16  set_time_limit(0); // unlimited max execution time
17  $result = "";
18  try {
19  if (function_exists("curl_init")) {
20  $options = array(
21  CURLOPT_TIMEOUT => 28800, // set this to 8 hours so we dont timeout on big files
22  CURLOPT_URL => $url,
23  CURLOPT_RETURNTRANSFER => 1
24  );
25  $ch = curl_init();
26  curl_setopt_array($ch, $options);
27  $result = curl_exec($ch);
28  curl_close($ch);
29  } else if (ini_get('allow_url_fopen')) {
30  $file = fopen($url, 'rb');
31  if ($file) {
32  while (!feof($file)) {
33  $result .= fread($file, 8192);
34  }
35  }
36  fclose($file);
37  } else {
38  $result = file_get_contents($url);
39  }
40  } catch (Exception $ex) {
41  $result = "";
42  }
43  if ($result && $saveTo && is_writable(dirname($saveTo))) {
44  try {
45  file_put_contents($saveTo, $result);
46  } catch (Exception $ex) {
47  }
48  }
49  return $result;
50  }
51 
52  public static function GetAllFiles($root, $trimRoot = FALSE, $level = 0) {
53  $handle = NULL;
54  if (file_exists($root) && is_readable($root)) {
55  $handle = opendir($root);
56  }
57  $dirs = array();
58  $files = array();
59  while ($handle && false !== ($entry = readdir($handle))) {
60  if ($entry == "." || $entry == ".." || strcasecmp($entry, ".DS_Store") == 0 || strcasecmp($entry, "thumbs.db") == 0) {
61  continue;
62  }
63  $entryPath = self::CombinePath($root, $entry);
64  if (is_dir($entryPath)) {
65  $dirs[] = $entryPath;
66  } else {
67  $files[] = $entryPath;
68  }
69  }
70  ++$level;
71  foreach ($dirs as $dir) {
72  $files = array_merge(self::GetAllFiles($dir, FALSE, $level), $files);
73  }
74  if ($level == 0 && $trimRoot) {
75  for ($i = 0; $i < count($files); ++$i) {
76  $files[$i] = str_replace($root, "", $files[$i]);
77  if (Utils::StartsWith($files[$i], "/")) {
78  $files[$i] = substr($files[$i], 1);
79  }
80  }
81  }
82  return $files;
83  }
84 
85  public static function GetAllFolders($root, $recursive = FALSE, $trimRoot = FALSE, $level = 0) {
86  $handle = NULL;
87  if (file_exists($root) && is_dir($root) && is_readable($root)) {
88  $handle = opendir($root);
89  }
90  $dirs = array();
91  if ($handle) {
92  while (false !== ($entry = readdir($handle))) {
93  if (self::StartsWith($entry, ".") || is_file($entry)) {
94  continue;
95  }
96  $dir = self::CombinePath($root, $entry);
97  $dirs[] = $dir;
98  if ($recursive) {
99  $dirs = array_merge($dirs, self::GetAllFolders($dir, TRUE, $trimRoot, $level + 1));
100  }
101  }
102  if ($level == 0 && $trimRoot) {
103  for ($i = 0; $i < count($dirs); ++$i) {
104  $dirs[$i] = str_replace($root, "", $dirs[$i]);
105  }
106  }
107  }
108  return $dirs;
109  }
110 
111  public static function HttpErrorCode($code = 401, $message = NULL) {
112  ob_clean();
113  http_response_code($code);
114  if (!empty($message)) {
115  echo $message;
116  }
117  exit();
118  }
119 
120  public static function GetServerName() {
121  $serverName = filter_input(INPUT_SERVER, "SERVER_NAME");
122  if (empty($serverName) && isset($_SERVER["SERVER_NAME"])) {
123  $serverName = $_SERVER["SERVER_NAME"];
124  }
125  return $serverName;
126  }
127 
128  public static function GetServerUrl($url = "") {
129  $protocol = "http";
130  if (!empty(filter_input(INPUT_SERVER, "HTTPS")) || (isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]))) {
131  $protocol .= "s";
132  }
133  $serverPort = filter_input(INPUT_SERVER, "SERVER_PORT");
134  if (empty($serverPort) && isset($_SERVER["SERVER_PORT"])) {
135  $serverPort = $_SERVER["SERVER_PORT"];
136  }
137  if (!empty($serverPort) && $serverPort != 80) {
138  $serverPort = ":" . $serverPort;
139  } else {
140  $serverPort = "";
141  }
142  return self::CombineUrl($protocol . "://" . self::GetServerName() . $serverPort, self::CombineUrl(URL_ROOT, $url));
143  }
144 
145  public static function GetUploadUrl($url = "") {
146  return self::GetServerUrl(self::CombineUrl(URL_UPLOAD, $url));
147  }
148 
149  public static function CombineUrl($path1, $path2) {
150  return self::CombinePath($path1, $path2, "/");
151  }
152 
153  public static function CombinePath($path1, $path2, $separator = DIRECTORY_SEPARATOR) {
154  $path = $path1;
155  if (!empty($path2)) {
156  if ($separator && self::EndsWith($path, $separator)) {
157  $path = substr($path, 0, strlen($path) - 1);
158  }
159  $path .= ($separator && !self::StartsWith($path2, $separator) ? $separator : "") . $path2;
160  }
161  return $path;
162  }
163 
164  public static function GetDateTimeZoneUTC() {
165  return new \DateTimeZone("Etc/UTC");
166  }
167 
168  public static function GetCurrentDateTime($timezone = NULL) {
169  if (!$timezone) {
170  $timezone = self::GetDateTimeZoneUTC();
171  }
172  return new \DateTime("now", $timezone);
173  }
174 
175  public static function GetCurrentDateTimeFormat($format = "Y-m-d H:i:s", $timezone = NULL) {
176  $now = self::GetCurrentDateTime($timezone);
177  return $now->format($format);
178  }
179 
180  public static function GetClientIP() {
181  $ip = filter_input(INPUT_SERVER, "REMOTE_ADDR");
182  if (empty($ip) && isset($_SERVER["REMOTE_ADDR"])) {
183  $ip = $_SERVER["REMOTE_ADDR"];
184  }
185  return $ip;
186  }
187 
194  public static function TicksToTime($ticks) {
195  $mktime = (($ticks - 621355968000000000) / 10000000);
196  $mktime -= 60 * 120;
197  return $mktime;
198  }
204  public static function TimeToTicks($time) {
205  $time += 60 * 120;
206  return number_format(($time * 10000000) + 621355968000000000 , 0, '.', '');
207  }
215  public static function StringToTicks($str) {
216  return time_to_ticks(strtotime($str));
217  }
218 
219  public static function NewGUID() {
220  return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
221  // 32 bits for "time_low"
222  mt_rand(0, 0xffff), mt_rand(0, 0xffff),
223  // 16 bits for "time_mid"
224  mt_rand(0, 0xffff),
225  // 16 bits for "time_hi_and_version",
226  // four most significant bits holds version number 4
227  mt_rand(0, 0x0fff) | 0x4000,
228  // 16 bits, 8 bits for "clk_seq_hi_res",
229  // 8 bits for "clk_seq_low",
230  // two most significant bits holds zero and one for variant DCE1.1
231  mt_rand(0, 0x3fff) | 0x8000,
232  // 48 bits for "node"
233  mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
234  );
235  }
236 
237  public static function RedirectTo ($url = "") {
238  global $Database;
239  $Database->CloseConnection();
240  if (!$url)
241  $url = $_SERVER["PHP_SELF"];
242  header("Location: $url");
243  exit();
244  }
245  public static function RedirectToSelf () {
246  global $Database;
247  $Database->CloseConnection();
248  $url = $_SERVER["PHP_SELF"];
249  $queryString = "";
250  foreach ($_GET as $key => $value) {
251  $queryString .= ($queryString ? "&" : "") . "$key=" . urlencode($value);
252  }
253  $url .= "?" . $queryString;
254  header("Location: $url");
255  exit();
256  }
257 
258  public static function ServerResponseRequired() {
259  return (defined("RESPONSE_ENCRYPTED") && RESPONSE_ENCRYPTED === TRUE);
260  }
261 
262  public static function EchoJson($text, $encodeJson = FALSE, $encryptResponse = FALSE) {
263  global $Database;
264  $Database->CloseConnection();
265  if ($encodeJson === TRUE) {
266  $text = json_encode($text);
267  }
268  ob_clean();
269  header("Access-Control-Allow-Credentials:true");
270  header("Access-Control-Allow-Headers:Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
271  header("Access-Control-Allow-Methods:GET, POST, OPTIONS");
272  header("Access-Control-Allow-Origin:*");
273  header("Content-Type:text/json");
274  if ($encryptResponse && self::ServerResponseRequired()) {
275  echo json_encode(array( "t" => self::GetCurrentDateTimeFormat(), "d" => clientEncrypt($text) ));
276  } else {
277  echo $text;
278  }
279  exit();
280  }
281 
282  public static function EchoXml($xml, $encryptResponse = FALSE) {
283  global $Database;
284  $Database->CloseConnection();
285  ob_clean();
286  header("Access-Control-Allow-Credentials:true");
287  header("Access-Control-Allow-Headers:Accept, X-Access-Token, X-Application-Name, X-Request-Sent-Time");
288  header("Access-Control-Allow-Methods:GET, POST, OPTIONS");
289  header("Access-Control-Allow-Origin:*");
290  header("Content-Type:text/xml");
291  if ($encryptResponse && self::ServerResponseRequired()) {
292  echo sprintf("<response><t>%s</t><d>%s</d></response>", htmlentities(self::GetCurrentDateTimeFormat()), htmlentities(clientEncrypt($xml)));
293  } else {
294  echo $xml;
295  }
296  exit();
297  }
298 
299  public static function EchoUnauthorized($text = "") {
300  if (!$text) {
301  $text = ErrorMessage::Get(ERROR_UNAUTHORIZED_REQUEST);
302  }
303  ob_clean();
304  http_response_code(401);
305  echo $text;
306  exit();
307  }
308 
309  public static function StartsWith($text, $search, $ignoreCase = false) {
310  $s = substr($text, 0, strlen($search));
311  if ($ignoreCase === true) {
312  return (strtolower($s) == strtolower($search));
313  }
314  return ($s == $search);
315  }
316 
317  public static function EndsWith($text, $search, $ignoreCase = false) {
318  $s = substr($text, -strlen($search));
319  if ($ignoreCase === true) {
320  return (strtolower($s) == strtolower($search));
321  }
322  return ($s == $search);
323  }
324 
333  public static function GetTimestamp($data, $add_days = 0) {
334  if (strpos($data, " ") === false) {
335  $a_data = $data;
336  $a_time = "00:00";
337  } else {
338  $a_data = substr($data, 0, strpos($data, " "));
339  $a_time = substr($data, strpos($data, " ") + 1);
340  }
341  $a_data = explode("/", str_replace("-", "/", $a_data));
342  $a_time = explode(":", str_replace(".", ":", $a_time));
343  if (strlen($a_data[0]) == 4) {
344  // From ISO format (YYYY/MM/DD)
345  $timestamp = mktime($a_time[0], $a_time[1], count($a_time) == 3 ? $a_time[2] : 0, $a_data[1], $add_days + $a_data[2], $a_data[0]);
346  } else {
347  // From ITA format (DD/MM/YYYY)
348  $timestamp = mktime($a_time[0], $a_time[1], count($a_time) == 3 ? $a_time[2] : 0, $a_data[1], $add_days + $a_data[0], $a_data[2]);
349  }
350  return $timestamp;
351  }
352 
353  public static function IsValidDate($text) {
354  $datebit = "";
355  if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $text, $datebit)) {
356  return checkdate($datebit[2], $datebit[3], $datebit[1]);
357  }
358  return false;
359  }
360 
361  public static function IsValidTime($text) {
362  $datebit = "";
363  if (preg_match('/^(\d{2}):(\d{2})$/', $text, $datebit)) {
364  return ($datebit[1] >= 0 && $datebit[1] <= 59) && ($datebit[2] >= 0 && $datebit[2] <= 59);
365  } else if (preg_match('/^(\d{2}):(\d{2}):(\d{2})$/', $text, $datebit)) {
366  return ($datebit[1] >= 0 && $datebit[1] <= 59) && ($datebit[2] >= 0 && $datebit[2] <= 59) && ($datebit[3] >= 0 && $datebit[3] <= 59);
367  }
368  return false;
369  }
370 
371  public static function ConvertSizeFromBytes($bytes, $to = NULL) {
372  $float = floatval($bytes);
373  switch ($to) {
374  case 'Kb' : // Kilobit
375  $float = ( $float * 8 ) / 1024;
376  break;
377  case 'b' : // bit
378  $float *= 8;
379  break;
380  case 'GB' : // Gigabyte
381  $float /= 1024;
382  case 'MB' : // Megabyte
383  $float /= 1024;
384  case 'KB' : // Kilobyte
385  $float /= 1024;
386  default : // byte
387  }
388  unset($bytes, $to);
389  return round($float, 1);
390  }
391 
392  public static function ExtractSearchKeywords($searchText) {
393  $keys = array();
394  $text = preg_replace("/\s{2,}/", " ", $searchText);
395  $multiple = array();
396  preg_match_all("|\"[^\"]+\"|", $text, $multiple);
397  foreach ($multiple[0] as $key) {
398  $text = str_replace($key, "", $text);
399  $keys[] = str_replace('"', '', $key);
400  }
401  $arr_text = explode(" ", $text);
402  foreach ($arr_text as $s) {
403  if (!empty($s) && !in_array($s, $keys)) {
404  $keys[] = $s;
405  }
406  }
407  return $keys;
408  }
409 
410  public static function CalcPercentage($total, $count) {
411  if ($total == 0 || $count == 0) {
412  return 0;
413  }
414  $perc = number_format((floatval($count) / floatval($total)) * 100, 2);
415  if (substr($perc, -2) == "00") {
416  return substr($perc, 0, strlen($perc) - 3);
417  }
418  if (substr($perc, -1) == "0") {
419  return substr($perc, 0, strlen($perc) - 1);
420  }
421  return $perc;
422  }
423 
424  public static function GetPageOffset($page, $limit) {
425  if ($page > 1) {
426  return $limit * ($page - 1);
427  }
428  return 0;
429  }
430 
431  public static function GetPagesCount($count, $limit) {
432  if ($limit > 0) {
433  return ceil($count / $limit);
434  }
435  return 0;
436  }
437 
445  public static function GetValidFilename($oldName, $newExt = "") {
446  $newName = "";
447  $name = $oldName;
448  $ext = Utils::GetFilenameExtension($name);
449  if ($ext != "") {
450  $name = substr($name, 0, strlen($name) - strlen($ext));
451  }
452  for ($i = 0; $i < strlen($name); $i++) {
453  $char = substr($name, $i, 1);
454  if (!preg_match("/^[a-zA-Z0-9._-]$/", $char)) {
455  $char = "_";
456  }
457  $newName .= $char;
458  }
459  $newName .= ($newExt != "" ? $newExt : $ext);
460  return $newName;
461  }
462 
469  public static function GetFilenameExtension($filename) {
470  $i = strrpos($filename, ".");
471  if ($i === false) {
472  return "";
473  }
474  return substr($filename, $i);
475  }
476 
482  public static function GetTempname($fileExt = ".tmp") {
483  $tmp_name = md5(microtime()) . $fileExt;
484  return $tmp_name;
485  }
486 
493  public static function GenerateRandomCode($length = 0) {
494  if ($length <= 0) {
495  if (defined("RANDOM_CODE_LENGTH") && RANDOM_CODE_LENGTH > 0) {
496  $length = intval(RANDOM_CODE_LENGTH);
497  } else {
498  $length = 10;
499  }
500  }
501  $code = "";
502  if (defined("RANDOM_CODE_CHARS") && RANDOM_CODE_CHARS) {
503  $chars = RANDOM_CODE_CHARS;
504  } else {
505  $chars = "bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ0123456789";
506  }
507  while (strlen($code) < $length) {
508  $code .= substr($chars, rand(0, strlen($chars) - 1), 1);
509  }
510  return $code;
511  }
512 
518  public static function IsValidEmail($email) {
519  $regex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i';
520  return preg_match($regex, $email);
521  }
522 
529  public static function JsonEncodeRowsMessage($rows, $count, $pagesCount = NULL, $extraParams = NULL) {
530  if (count($rows) > 0 && $rows[0] !== NULL && is_subclass_of($rows[0], "DataClass")) {
531  $temp = array();
532  foreach ($rows as $r) {
533  $temp[] = $r->ToArray();
534  }
535  $rows = $temp;
536  }
537  for ($i = 0; $i < count($rows); $i++) {
538  foreach ($rows[$i] as $k => $v) {
539  if (is_array($v) || is_object($v)) {
540  continue;
541  }
542  if (is_numeric($v) || is_bool($v)) {
543  continue;
544  } elseif ($v == null || $v == "NULL") {
545  $rows[$i][$k] = "";
546  } elseif (substr($v, 0, 10) == "00/00/0000" || substr($v, 0, 10) == "0000-00-00") {
547  $rows[$i][$k] = "";
548  }
549  }
550  }
551  $result = array("total" => $count, "results" => $rows);
552  if ($pagesCount !== NULL) {
553  $result["pages"] = $pagesCount;
554  }
555  if ($extraParams !== NULL && is_array($extraParams)) {
556  $result = array_merge($result, $extraParams);
557  }
558  return json_encode($result);
559  }
560 
569  public static function JsonEncodeSuccessMessage($success = true, $message = "", $errors = array()) {
570  return json_encode(array("success" => $success, "message" => $message, "errors" => $errors));
571  }
572 
578  public static function FillObjectFromRequest(&$obj) {
579  $props = array_keys(get_class_vars(get_class($obj)));
580  foreach ($props as $prop) {
581  $requestValue = filter_input(INPUT_POST, $prop);
582  if (is_null($requestValue)) {
583  $requestValue = filter_input(INPUT_GET, $prop);
584  }
585  if (!is_null($requestValue)) {
586  $obj->$prop = $requestValue;
587  }
588  }
589  }
590 
599  public static function FillObjectFromRow(&$obj, $row, $stripSlashes = false, $callbackOnExists = false) {
600  $props = get_class_vars(get_class($obj));
601  foreach ($props as $prop => $value) {
602  if (array_key_exists($prop, $row)) {
603  if (!$callbackOnExists) {
604  $value = ($stripSlashes ? trim(stripslashes($row[$prop])) : $row[$prop]);
605  /* if ($stripSlashes && self::IsUtf8($value)) {
606  $value = utf8_decode($value);
607  } */
608  $obj->$prop = $value;
609  } else {
610  $obj->$callbackOnExists($prop, $row[$prop]);
611  }
612  }
613  }
614  }
615 
623  public static function ObjectToArray($obj) {
624  $array = array();
625  if (is_a($obj, "stdClass")) {
626  $variables = get_object_vars($obj);
627  $keys = array_keys($variables);
628  foreach ($keys as $k) {
629  $array[$k] = $obj->$k;
630  }
631  } else {
632  $props = get_class_vars(get_class($obj));
633  foreach ($props as $prop => $value) {
634  $array[$prop] = $obj->$prop;
635  }
636  }
637  return $array;
638  }
639 }
static ConvertSizeFromBytes($bytes, $to=NULL)
Definition: Utils.php:371
static EchoUnauthorized($text="")
Definition: Utils.php:299
static JsonEncodeSuccessMessage($success=true, $message="", $errors=array())
Definition: Utils.php:569
static IsIPv6($ip)
Definition: Utils.php:11
static GenerateRandomCode($length=0)
Definition: Utils.php:493
static CalcPercentage($total, $count)
Definition: Utils.php:410
static TimeToTicks($time)
Definition: Utils.php:204
static IsIPv4($ip)
Definition: Utils.php:7
static GetClientIP()
Definition: Utils.php:180
static NewGUID()
Definition: Utils.php:219
static GetCurrentDateTimeFormat($format="Y-m-d H:i:s", $timezone=NULL)
Definition: Utils.php:175
static TicksToTime($ticks)
Definition: Utils.php:194
static EndsWith($text, $search, $ignoreCase=false)
Definition: Utils.php:317
static GetUploadUrl($url="")
Definition: Utils.php:145
static ObjectToArray($obj)
Definition: Utils.php:623
static JsonEncodeRowsMessage($rows, $count, $pagesCount=NULL, $extraParams=NULL)
Definition: Utils.php:529
static IsValidEmail($email)
Definition: Utils.php:518
static FillObjectFromRow(&$obj, $row, $stripSlashes=false, $callbackOnExists=false)
Definition: Utils.php:599
static GetFilenameExtension($filename)
Definition: Utils.php:469
static FillObjectFromRequest(&$obj)
Definition: Utils.php:578
static GetServerName()
Definition: Utils.php:120
static GetPagesCount($count, $limit)
Definition: Utils.php:431
static GetCurrentDateTime($timezone=NULL)
Definition: Utils.php:168
static ExtractSearchKeywords($searchText)
Definition: Utils.php:392
static HttpErrorCode($code=401, $message=NULL)
Definition: Utils.php:111
Definition: Account.php:3
static ServerResponseRequired()
Definition: Utils.php:258
static EchoJson($text, $encodeJson=FALSE, $encryptResponse=FALSE)
Definition: Utils.php:262
static StringToTicks($str)
Definition: Utils.php:215
static EchoXml($xml, $encryptResponse=FALSE)
Definition: Utils.php:282
static CombineUrl($path1, $path2)
Definition: Utils.php:149
static GetPageOffset($page, $limit)
Definition: Utils.php:424
static GetAllFolders($root, $recursive=FALSE, $trimRoot=FALSE, $level=0)
Definition: Utils.php:85
static GetTempname($fileExt=".tmp")
Definition: Utils.php:482
static IsValidTime($text)
Definition: Utils.php:361
static StartsWith($text, $search, $ignoreCase=false)
Definition: Utils.php:309
static RedirectTo($url="")
Definition: Utils.php:237
static GetServerUrl($url="")
Definition: Utils.php:128
static GetAllFiles($root, $trimRoot=FALSE, $level=0)
Definition: Utils.php:52
static IsValidDate($text)
Definition: Utils.php:353
static GetDateTimeZoneUTC()
Definition: Utils.php:164
static GetValidFilename($oldName, $newExt="")
Definition: Utils.php:445
static GetTimestamp($data, $add_days=0)
Definition: Utils.php:333
static DownloadUrl($url, $saveTo=NULL)
Definition: Utils.php:15
static RedirectToSelf()
Definition: Utils.php:245
static CombinePath($path1, $path2, $separator=DIRECTORY_SEPARATOR)
Definition: Utils.php:153