normal-functions.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. <?php
  2. trait NormalFunctions
  3. {
  4. public function formatSeconds($seconds)
  5. {
  6. $hours = 0;
  7. $milliseconds = str_replace("0.", '', $seconds - floor($seconds));
  8. if ($seconds > 3600) {
  9. $hours = floor($seconds / 3600);
  10. }
  11. $seconds = $seconds % 3600;
  12. $time = str_pad($hours, 2, '0', STR_PAD_LEFT)
  13. . gmdate(':i:s', $seconds)
  14. . ($milliseconds ? '.' . $milliseconds : '');
  15. $parts = explode(':', $time);
  16. $timeExtra = explode('.', $parts[2]);
  17. if ($parts[0] !== '00') { // hours
  18. return $time;
  19. } elseif ($parts[1] !== '00') { // mins
  20. return $parts[1] . 'min(s) ' . $timeExtra[0] . 's';
  21. } elseif ($timeExtra[0] !== '00') { // secs
  22. return substr($parts[2], 0, 5) . 's | ' . substr($parts[2], 0, 7) * 1000 . 'ms';
  23. } else {
  24. return substr($parts[2], 0, 7) * 1000 . 'ms';
  25. }
  26. //return $timeExtra[0] . 's ' . (number_format(('0.' . substr($timeExtra[1], 0, 4)), 4, '.', '') * 1000) . 'ms';
  27. //return (number_format(('0.' . substr($timeExtra[1], 0, 4)), 4, '.', '') * 1000) . 'ms';
  28. }
  29. public function getExtension($string)
  30. {
  31. return preg_replace("#(.+)?\.(\w+)(\?.+)?#", "$2", $string);
  32. }
  33. public function get_browser_name()
  34. {
  35. $user_agent = $_SERVER['HTTP_USER_AGENT'];
  36. if (strpos($user_agent, 'Opera') || strpos($user_agent, 'OPR/')) {
  37. return 'Opera';
  38. } elseif (strpos($user_agent, 'Edge')) {
  39. return 'Edge';
  40. } elseif (strpos($user_agent, 'Chrome')) {
  41. return 'Chrome';
  42. } elseif (strpos($user_agent, 'Safari')) {
  43. return 'Safari';
  44. } elseif (strpos($user_agent, 'Firefox')) {
  45. return 'Firefox';
  46. } elseif (strpos($user_agent, 'MSIE') || strpos($user_agent, 'Trident/7')) {
  47. return 'Internet Explorer';
  48. }
  49. return 'Other';
  50. }
  51. public function array_filter_key(array $array, $callback)
  52. {
  53. $matchedKeys = array_filter(array_keys($array), $callback);
  54. return array_intersect_key($array, array_flip($matchedKeys));
  55. }
  56. public function getOS()
  57. {
  58. if (PHP_SHLIB_SUFFIX == "dll") {
  59. return "win";
  60. } else {
  61. return "*nix";
  62. }
  63. }
  64. // Get Gravatar Email Image
  65. public function gravatar($email = '')
  66. {
  67. $email = md5(strtolower(trim($email)));
  68. return "https://www.gravatar.com/avatar/$email?s=100&d=mm";
  69. }
  70. // Clean Directory string
  71. public function cleanDirectory($path)
  72. {
  73. $path = str_replace(array('/', '\\'), '/', $path);
  74. if (substr($path, -1) != '/') {
  75. $path = $path . '/';
  76. }
  77. if ($path[0] != '/' && $path[1] != ':') {
  78. $path = '/' . $path;
  79. }
  80. return $path;
  81. }
  82. // Print output all purrty
  83. public function prettyPrint($v, $error = false)
  84. {
  85. if ($error) {
  86. $background = 'red';
  87. $border = 'black';
  88. $text = 'white';
  89. } else {
  90. $background = '#f2f2f2';
  91. $border = 'black';
  92. $text = 'black';
  93. }
  94. $trace = debug_backtrace()[0];
  95. echo '<pre style="white-space: pre; text-overflow: ellipsis; overflow: hidden; color: ' . $text . '; background-color: ' . $background . '; border: 2px solid ' . $border . '; border-radius: 5px; padding: 5px; margin: 5px;">' . $trace['file'] . ':' . $trace['line'] . ' ' . gettype($v) . "\n\n" . print_r($v, 1) . '</pre><br/>';
  96. }
  97. public function gen_uuid()
  98. {
  99. return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
  100. // 32 bits for "time_low"
  101. mt_rand(0, 0xffff), mt_rand(0, 0xffff),
  102. // 16 bits for "time_mid"
  103. mt_rand(0, 0xffff),
  104. // 16 bits for "time_hi_and_version",
  105. // four most significant bits holds version number 4
  106. mt_rand(0, 0x0fff) | 0x4000,
  107. // 16 bits, 8 bits for "clk_seq_hi_res",
  108. // 8 bits for "clk_seq_low",
  109. // two most significant bits holds zero and one for variant DCE1.1
  110. mt_rand(0, 0x3fff) | 0x8000,
  111. // 48 bits for "node"
  112. mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
  113. );
  114. }
  115. public function dbExtension($string)
  116. {
  117. return (substr($string, -3) == '.db') ? $string : $string . '.db';
  118. }
  119. public function removeDbExtension($string)
  120. {
  121. return substr($string, 0, -3);
  122. }
  123. public function cleanPath($path)
  124. {
  125. $path = preg_replace('/([^:])(\/{2,})/', '$1/', $path);
  126. $path = rtrim($path, '/');
  127. return $path;
  128. }
  129. public function searchArray($array, $field, $value)
  130. {
  131. foreach ($array as $key => $item) {
  132. if ($item[$field] === $value)
  133. return $key;
  134. }
  135. return false;
  136. }
  137. public function localURL($url, $force = false)
  138. {
  139. if ($force) {
  140. return true;
  141. }
  142. if (strpos($url, 'https') !== false) {
  143. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
  144. $result = !empty($result);
  145. return $result;
  146. }
  147. return false;
  148. }
  149. public function arrayIP($string)
  150. {
  151. if (strpos($string, ',') !== false) {
  152. $result = explode(",", $string);
  153. } else {
  154. $result = array($string);
  155. }
  156. foreach ($result as &$ip) {
  157. $ip = is_numeric(substr($ip, 0, 1)) ? $ip : gethostbyname($ip);
  158. }
  159. return $result;
  160. }
  161. public function timeExecution($previous = null)
  162. {
  163. if (!$previous) {
  164. return microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
  165. } else {
  166. return (microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]) - $previous;
  167. }
  168. }
  169. public function getallheaders()
  170. {
  171. if (!function_exists('getallheaders')) {
  172. function getallheaders()
  173. {
  174. $headers = array();
  175. foreach ($_SERVER as $name => $value) {
  176. if (substr($name, 0, 5) == 'HTTP_') {
  177. $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
  178. }
  179. }
  180. return $headers;
  181. }
  182. } else {
  183. return getallheaders();
  184. }
  185. }
  186. public function getallheadersi()
  187. {
  188. return array_change_key_case($this->getallheaders(), CASE_LOWER);
  189. }
  190. public function random_ascii_string($length)
  191. {
  192. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  193. $charactersLength = strlen($characters);
  194. $randomString = '';
  195. for ($i = 0; $i < $length; $i++) {
  196. $randomString .= $characters[rand(0, $charactersLength - 1)];
  197. }
  198. return $randomString;
  199. }
  200. // Generate Random string
  201. public function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
  202. {
  203. $tmp = '';
  204. for ($i = 0; $i < $length; $i++) {
  205. $tmp .= substr(str_shuffle($chars), 0, 1);
  206. }
  207. return $tmp;
  208. }
  209. public function isEncrypted($password = null)
  210. {
  211. return ($password == null || $password == '') ? false : $this->decrypt($password);
  212. }
  213. public function fillString($string, $length)
  214. {
  215. $filler = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*';
  216. if (strlen($string) < $length) {
  217. $diff = $length - strlen($string);
  218. $filler = substr($filler, 0, $diff);
  219. return $string . $filler;
  220. } elseif (strlen($string) > $length) {
  221. return substr($string, 0, $length);
  222. } else {
  223. return $string;
  224. }
  225. }
  226. public function userIP()
  227. {
  228. if (isset($_SERVER['HTTP_CLIENT_IP'])) {
  229. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  230. } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  231. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  232. } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
  233. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  234. } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
  235. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  236. } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
  237. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  238. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  239. $ipaddress = $_SERVER['REMOTE_ADDR'];
  240. } else {
  241. $ipaddress = '127.0.0.1';
  242. }
  243. if (strpos($ipaddress, ',') !== false) {
  244. list($first, $last) = explode(",", $ipaddress);
  245. unset($last);
  246. return $first;
  247. } else {
  248. return $ipaddress;
  249. }
  250. }
  251. public function serverIP()
  252. {
  253. if (array_key_exists('SERVER_ADDR', $_SERVER)) {
  254. return $_SERVER['SERVER_ADDR'];
  255. }
  256. return '127.0.0.1';
  257. }
  258. public function parseDomain($value, $force = false)
  259. {
  260. $badDomains = array('ddns.net', 'ddnsking.com', '3utilities.com', 'bounceme.net', 'freedynamicdns.net', 'freedynamicdns.org', 'gotdns.ch', 'hopto.org', 'myddns.me', 'myds.me', 'myftp.biz', 'myftp.org', 'myvnc.com', 'noip.com', 'onthewifi.com', 'redirectme.net', 'serveblog.net', 'servecounterstrike.com', 'serveftp.com', 'servegame.com', 'servehalflife.com', 'servehttp.com', 'serveirc.com', 'serveminecraft.net', 'servemp3.com', 'servepics.com', 'servequake.com', 'sytes.net', 'viewdns.net', 'webhop.me', 'zapto.org');
  261. $Domain = $value;
  262. $Port = strpos($Domain, ':');
  263. if ($Port !== false) {
  264. $Domain = substr($Domain, 0, $Port);
  265. $value = $Domain;
  266. }
  267. $check = substr_count($Domain, '.');
  268. if ($check >= 3) {
  269. if (is_numeric($Domain[0])) {
  270. $Domain = '';
  271. } else {
  272. if (in_array(strtolower(explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3]), $badDomains)) {
  273. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3];
  274. } else {
  275. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3];
  276. }
  277. }
  278. } elseif ($check == 2) {
  279. if (in_array(strtolower(explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2]), $badDomains)) {
  280. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  281. } elseif (explode('.', $Domain)[0] == 'www') {
  282. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  283. } elseif (explode('.', $Domain)[1] == 'co') {
  284. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  285. } else {
  286. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  287. }
  288. } elseif ($check == 1) {
  289. $Domain = '.' . $Domain;
  290. } else {
  291. $Domain = '';
  292. }
  293. return ($force) ? $value : $Domain;
  294. }
  295. // Cookie Custom Function
  296. public function coookie($type, $name, $value = '', $days = -1, $http = true, $path = '/')
  297. {
  298. $days = ($days > 365) ? 365 : $days;
  299. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  300. $Secure = true;
  301. $HTTPOnly = true;
  302. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' && $_SERVER['HTTPS'] !== '') {
  303. $Secure = true;
  304. $HTTPOnly = true;
  305. } else {
  306. $Secure = false;
  307. $HTTPOnly = false;
  308. }
  309. if (!$http) {
  310. $HTTPOnly = false;
  311. }
  312. $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? '';
  313. $Domain = $this->parseDomain($_SERVER['HTTP_HOST']);
  314. $DomainTest = $this->parseDomain($_SERVER['HTTP_HOST'], true);
  315. if ($type == 'set') {
  316. $_COOKIE[$name] = $value;
  317. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  318. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
  319. . (empty($path) ? '' : '; path=' . $path)
  320. . (empty($Domain) ? '' : '; domain=' . $Domain)
  321. . (!$Secure ? '' : '; SameSite=None; Secure')
  322. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  323. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  324. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
  325. . (empty($path) ? '' : '; path=' . $path)
  326. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  327. . (!$Secure ? '' : '; SameSite=None; Secure')
  328. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  329. } elseif ($type == 'delete') {
  330. unset($_COOKIE[$name]);
  331. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  332. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  333. . (empty($path) ? '' : '; path=' . $path)
  334. . (empty($Domain) ? '' : '; domain=' . $Domain)
  335. . (!$Secure ? '' : '; SameSite=None; Secure')
  336. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  337. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  338. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  339. . (empty($path) ? '' : '; path=' . $path)
  340. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  341. . (!$Secure ? '' : '; SameSite=None; Secure')
  342. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  343. }
  344. }
  345. public function coookieSeconds($type, $name, $value = '', $ms = null, $http = true, $path = '/')
  346. {
  347. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  348. $Secure = true;
  349. $HTTPOnly = true;
  350. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' && $_SERVER['HTTPS'] !== '') {
  351. $Secure = true;
  352. $HTTPOnly = true;
  353. } else {
  354. $Secure = false;
  355. $HTTPOnly = false;
  356. }
  357. if (!$http) {
  358. $HTTPOnly = false;
  359. }
  360. $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? '';
  361. $Domain = $this->parseDomain($_SERVER['HTTP_HOST']);
  362. $DomainTest = $this->parseDomain($_SERVER['HTTP_HOST'], true);
  363. if ($type == 'set') {
  364. $_COOKIE[$name] = $value;
  365. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  366. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + ($ms / 1000)) . ' GMT')
  367. . (empty($path) ? '' : '; path=' . $path)
  368. . (empty($Domain) ? '' : '; domain=' . $Domain)
  369. . (!$Secure ? '' : '; SameSite=None; Secure')
  370. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  371. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  372. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + ($ms / 1000)) . ' GMT')
  373. . (empty($path) ? '' : '; path=' . $path)
  374. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  375. . (!$Secure ? '' : '; SameSite=None; Secure')
  376. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  377. } elseif ($type == 'delete') {
  378. unset($_COOKIE[$name]);
  379. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  380. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  381. . (empty($path) ? '' : '; path=' . $path)
  382. . (empty($Domain) ? '' : '; domain=' . $Domain)
  383. . (!$Secure ? '' : '; SameSite=None; Secure')
  384. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  385. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  386. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  387. . (empty($path) ? '' : '; path=' . $path)
  388. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  389. . (!$Secure ? '' : '; SameSite=None; Secure')
  390. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  391. }
  392. }
  393. // Qualify URL
  394. public function qualifyURL($url, $return = false, $includeTrailing = false)
  395. {
  396. //local address?
  397. if (substr($url, 0, 1) == "/") {
  398. if ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] != 'off') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] != 'http')) {
  399. $protocol = "https://";
  400. } else {
  401. $protocol = "http://";
  402. }
  403. $url = $protocol . $this->getServer() . $url;
  404. }
  405. // Get Digest
  406. $digest = $includeTrailing ? parse_url($url) : parse_url(rtrim(preg_replace('/\s+/', '', $url), '/'));
  407. // http/https
  408. if (!isset($digest['scheme'])) {
  409. $scheme = 'http';
  410. } else {
  411. $scheme = $digest['scheme'];
  412. }
  413. // Host
  414. $host = ($digest['host'] ?? '');
  415. // Port
  416. $port = (isset($digest['port']) ? ':' . $digest['port'] : '');
  417. // Path
  418. $path = ($digest['path'] ?? '');
  419. // Query
  420. $query = (isset($digest['query']) ? '?' . $digest['query'] : '');
  421. // Fragment
  422. $fragment = (isset($digest['fragment']) ? '#' . $digest['fragment'] : '');
  423. // Output
  424. $array = [
  425. 'scheme' => $scheme,
  426. 'host' => $host,
  427. 'port' => $port,
  428. 'path' => $path,
  429. 'query' => $query,
  430. 'fragment' => $fragment,
  431. 'digest' => $digest
  432. ];
  433. return ($return) ? $array : $scheme . '://' . $host . $port . $path . $query . $fragment;
  434. }
  435. public function getServer($over = false)
  436. {
  437. if ($over) {
  438. if ($this->config['PHPMAILER-domain'] !== '') {
  439. return $this->config['PHPMAILER-domain'];
  440. }
  441. }
  442. return isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  443. }
  444. public function getServerPath($over = false)
  445. {
  446. if ($over) {
  447. if ($this->config['PHPMAILER-domain'] !== '') {
  448. return $this->config['PHPMAILER-domain'];
  449. }
  450. }
  451. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  452. $protocol = "https://";
  453. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  454. $protocol = "https://";
  455. } else {
  456. $protocol = "http://";
  457. }
  458. $domain = '';
  459. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  460. $domain = $_SERVER['SERVER_NAME'];
  461. } elseif (isset($_SERVER['HTTP_HOST'])) {
  462. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  463. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  464. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  465. if ($port !== "80" && $port !== "443") {
  466. $domain = $_SERVER['HTTP_HOST'];
  467. }
  468. } else {
  469. $domain = $_SERVER['HTTP_HOST'];
  470. }
  471. }
  472. $path = str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  473. $path = ($path !== '.') ? $path : '';
  474. $url = $protocol . $domain . $path;
  475. if (strpos($url, '/api') !== false) {
  476. $url = explode('/api', $url);
  477. return $url[0] . '/';
  478. } else {
  479. return $url;
  480. }
  481. }
  482. public function convertIPToRange($ip)
  483. {
  484. $ip = trim($ip);
  485. if (strpos($ip, '/') !== false) {
  486. $explodeIP = explode('/', $ip);
  487. $prefix = $explodeIP[1];
  488. $start_ip = $explodeIP[0];
  489. $explodeStart = explode('.', $start_ip);
  490. if (count($explodeStart) == 4) {
  491. $explodeStart[3] = $prefix == 32 ? $explodeStart[3] : 0;
  492. $start_ip = implode('.', $explodeStart);
  493. }
  494. $ip_count = 1 << (32 - $prefix);
  495. $start_ip_long = long2ip(ip2long($start_ip));
  496. $last_ip_long = long2ip(ip2long($start_ip) + $ip_count - 1);
  497. } elseif (substr_count($ip, '.') == 3) {
  498. $start_ip_long = long2ip(ip2long($ip));
  499. $last_ip_long = long2ip(ip2long($ip));
  500. } else {
  501. return false;
  502. }
  503. return [
  504. 'from' => $start_ip_long,
  505. 'to' => $last_ip_long
  506. ];
  507. }
  508. public function convertIPStringToRange($string = null)
  509. {
  510. $ips = [];
  511. if ($string) {
  512. $ipListing = explode(',', $string);
  513. if (count($ipListing) > 0) {
  514. foreach ($ipListing as $ip) {
  515. $ips[] = $this->convertIPToRange($ip);
  516. }
  517. }
  518. }
  519. return $ips;
  520. }
  521. public function localIPRanges()
  522. {
  523. $mainArray = [
  524. [
  525. 'from' => '10.0.0.0',
  526. 'to' => '10.255.255.255'
  527. ],
  528. [
  529. 'from' => '172.16.0.0',
  530. 'to' => '172.31.255.255'
  531. ],
  532. [
  533. 'from' => '192.168.0.0',
  534. 'to' => '192.168.255.255'
  535. ],
  536. [
  537. 'from' => '127.0.0.1',
  538. 'to' => '127.255.255.255'
  539. ],
  540. ];
  541. if (isset($this->config['localIPList'])) {
  542. if ($this->config['localIPList'] !== '') {
  543. $ipListing = explode(',', $this->config['localIPList']);
  544. if (count($ipListing) > 0) {
  545. foreach ($ipListing as $ip) {
  546. $ipInfo = $this->convertIPToRange($ip);
  547. if ($ipInfo) {
  548. array_push($mainArray, $ipInfo);
  549. }
  550. }
  551. }
  552. }
  553. }
  554. /*
  555. if ($this->config['localIPFrom']) {
  556. $from = trim($this->config['localIPFrom']);
  557. $override = true;
  558. }
  559. if ($this->config['localIPTo']) {
  560. $to = trim($this->config['localIPTo']);
  561. }
  562. if ($override) {
  563. $newArray = array(
  564. 'from' => $from,
  565. 'to' => (isset($to)) ? $to : $from
  566. );
  567. array_push($mainArray, $newArray);
  568. }
  569. */
  570. return $mainArray;
  571. }
  572. public function isLocal($checkIP = null)
  573. {
  574. $isLocal = false;
  575. $userIP = ($checkIP) ? ip2long($checkIP) : ip2long($this->userIP());
  576. $range = $this->localIPRanges();
  577. foreach ($range as $ip) {
  578. $low = ip2long($ip['from']);
  579. $high = ip2long($ip['to']);
  580. if ($userIP <= $high && $low <= $userIP) {
  581. $isLocal = true;
  582. }
  583. }
  584. return $isLocal;
  585. }
  586. public function isLocalOrServer()
  587. {
  588. $isLocalOrServer = false;
  589. $isLocal = $this->isLocal();
  590. if (!$isLocal) {
  591. if ($this->userIP() == $this->serverIP()) {
  592. $isLocalOrServer = true;
  593. }
  594. } else {
  595. $isLocalOrServer = true;
  596. }
  597. return $isLocalOrServer;
  598. }
  599. public function human_filesize($bytes, $dec = 2)
  600. {
  601. $bytes = number_format($bytes, 0, '.', '');
  602. $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  603. $factor = floor((strlen($bytes) - 1) / 3);
  604. return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
  605. }
  606. public function apiResponseFormatter($response)
  607. {
  608. if (is_array($response)) {
  609. return $response;
  610. }
  611. if (empty($response) || $response == '') {
  612. return ['api_response' => 'No data'];
  613. }
  614. if ($this->json_validator($response)) {
  615. return json_decode($response, true);
  616. }
  617. return ['api_response' => 'No data'];
  618. }
  619. public function json_validator($data = null)
  620. {
  621. if (!empty($data)) {
  622. @json_decode($data);
  623. return (json_last_error() === JSON_ERROR_NONE);
  624. }
  625. return false;
  626. }
  627. public function replace_first($search_str, $replacement_str, $src_str)
  628. {
  629. return (false !== ($pos = strpos($src_str, $search_str))) ? substr_replace($src_str, $replacement_str, $pos, strlen($search_str)) : $src_str;
  630. }
  631. /**
  632. * Check if an array is a multidimensional array.
  633. *
  634. * @param array $arr The array to check
  635. * @return boolean Whether the the array is a multidimensional array or not
  636. */
  637. public function is_multi_array($x)
  638. {
  639. if (count(array_filter($x, 'is_array')) > 0) return true;
  640. return false;
  641. }
  642. /**
  643. * Convert an object to an array.
  644. *
  645. * @param array $object The object to convert
  646. * @return array The converted array
  647. */
  648. public function object_to_array($object)
  649. {
  650. if (!is_object($object) && !is_array($object)) return $object;
  651. return array_map(array($this, 'object_to_array'), (array)$object);
  652. }
  653. /**
  654. * Check if a value exists in the array/object.
  655. *
  656. * @param mixed $needle The value that you are searching for
  657. * @param mixed $haystack The array/object to search
  658. * @param boolean $strict Whether to use strict search or not
  659. * @return boolean Whether the value was found or not
  660. */
  661. public function search_for_value($needle, $haystack, $strict = true)
  662. {
  663. $haystack = $this->object_to_array($haystack);
  664. if (is_array($haystack)) {
  665. if ($this->is_multi_array($haystack)) { // Multidimensional array
  666. foreach ($haystack as $subhaystack) {
  667. if ($this->search_for_value($needle, $subhaystack, $strict)) {
  668. return true;
  669. }
  670. }
  671. } elseif (array_keys($haystack) !== range(0, count($haystack) - 1)) { // Associative array
  672. foreach ($haystack as $key => $val) {
  673. if ($needle == $val && !$strict) {
  674. return true;
  675. } elseif ($needle === $val && $strict) {
  676. return true;
  677. }
  678. }
  679. return false;
  680. } else { // Normal array
  681. if ($needle == $haystack && !$strict) {
  682. return true;
  683. } elseif ($needle === $haystack && $strict) {
  684. return true;
  685. }
  686. }
  687. }
  688. return false;
  689. }
  690. public function makeDir($dirPath, $mode = 0777)
  691. {
  692. return is_dir($dirPath) || @mkdir($dirPath, $mode, true);
  693. }
  694. }
  695. // Leave for deluge class
  696. function getCert()
  697. {
  698. $url = 'http://curl.haxx.se/ca/cacert.pem';
  699. $file = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  700. $file2 = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  701. $useCert = (file_exists($file)) ? $file : $file2;
  702. $context = stream_context_create(
  703. array(
  704. 'ssl' => array(
  705. 'verify_peer' => true,
  706. 'cafile' => $useCert
  707. )
  708. )
  709. );
  710. if (!file_exists($file)) {
  711. file_put_contents($file, fopen($url, 'r', false, $context));
  712. } elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
  713. file_put_contents($file, fopen($url, 'r', false, $context));
  714. }
  715. return $file;
  716. }
  717. // Leave for deluge class
  718. function localURL($url, $force = false)
  719. {
  720. if ($force) {
  721. return true;
  722. }
  723. if (strpos($url, 'https') !== false) {
  724. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
  725. $result = (!empty($result) ? true : false);
  726. return $result;
  727. }
  728. return false;
  729. }
  730. // Maybe use later?
  731. function curl($curl, $url, $headers = array(), $data = array())
  732. {
  733. // Initiate cURL
  734. $curlReq = curl_init($url);
  735. if (in_array(trim(strtoupper($curl)), ["GET", "POST", "PUT", "DELETE"])) {
  736. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, trim(strtoupper($curl)));
  737. } else {
  738. return null;
  739. }
  740. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  741. curl_setopt($curlReq, CURLOPT_CAINFO, getCert());
  742. curl_setopt($curlReq, CURLOPT_CONNECTTIMEOUT, 5);
  743. if (localURL($url)) {
  744. curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 0);
  745. curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, 0);
  746. }
  747. // Format Headers
  748. $cHeaders = array();
  749. foreach ($headers as $k => $v) {
  750. $cHeaders[] = $k . ': ' . $v;
  751. }
  752. if (count($cHeaders)) {
  753. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  754. }
  755. // Format Data
  756. switch (isset($headers['Content-Type']) ? $headers['Content-Type'] : '') {
  757. case 'application/json':
  758. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  759. break;
  760. case 'application/x-www-form-urlencoded':
  761. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  762. break;
  763. default:
  764. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  765. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  766. }
  767. // Execute
  768. $result = curl_exec($curlReq);
  769. $httpcode = curl_getinfo($curlReq);
  770. // Close
  771. curl_close($curlReq);
  772. // Return
  773. return array('content' => $result, 'http_code' => $httpcode);
  774. }
  775. // Maybe use later?
  776. function getHeaders($url)
  777. {
  778. $ch = curl_init($url);
  779. curl_setopt($ch, CURLOPT_NOBODY, true);
  780. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  781. curl_setopt($ch, CURLOPT_HEADER, false);
  782. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  783. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  784. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  785. if (localURL($url)) {
  786. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  787. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  788. }
  789. curl_exec($ch);
  790. $headers = curl_getinfo($ch);
  791. curl_close($ch);
  792. return $headers;
  793. }
  794. // Maybe use later?
  795. function download($url, $path)
  796. {
  797. ini_set('max_execution_time', 0);
  798. set_time_limit(0);
  799. $ch = curl_init($url);
  800. curl_setopt($ch, CURLOPT_HEADER, 1);
  801. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  802. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  803. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  804. if (localURL($url)) {
  805. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  806. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  807. }
  808. $raw_file_data = curl_exec($ch);
  809. curl_close($ch);
  810. file_put_contents($path, $raw_file_data);
  811. return (filesize($path) > 0) ? true : false;
  812. }
  813. // swagger
  814. function getServerPath($over = false)
  815. {
  816. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  817. $protocol = "https://";
  818. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  819. $protocol = "https://";
  820. } else {
  821. $protocol = "http://";
  822. }
  823. $domain = '';
  824. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  825. $domain = $_SERVER['SERVER_NAME'];
  826. } elseif (isset($_SERVER['HTTP_HOST'])) {
  827. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  828. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  829. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  830. if ($port !== "80" && $port !== "443") {
  831. $domain = $_SERVER['HTTP_HOST'];
  832. }
  833. } else {
  834. $domain = $_SERVER['HTTP_HOST'];
  835. }
  836. }
  837. $url = $protocol . $domain . str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  838. if (strpos($url, '/api') !== false) {
  839. $url = explode('/api', $url);
  840. return $url[0] . '/';
  841. } else {
  842. return $url;
  843. }
  844. }
  845. // used for api return
  846. function safe_json_encode($value, $options = 0, $depth = 512)
  847. {
  848. $encoded = json_encode($value, $options, $depth);
  849. if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
  850. $encoded = json_encode(utf8ize($value), $options, $depth);
  851. }
  852. return $encoded;
  853. }
  854. // used for api return
  855. function utf8ize($mixed)
  856. {
  857. if (is_array($mixed)) {
  858. foreach ($mixed as $key => $value) {
  859. $mixed[$key] = utf8ize($value);
  860. }
  861. } elseif (is_string($mixed)) {
  862. return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
  863. }
  864. return $mixed;
  865. }