normal-functions.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  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 random_ascii_string($length)
  187. {
  188. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  189. $charactersLength = strlen($characters);
  190. $randomString = '';
  191. for ($i = 0; $i < $length; $i++) {
  192. $randomString .= $characters[rand(0, $charactersLength - 1)];
  193. }
  194. return $randomString;
  195. }
  196. // Generate Random string
  197. public function randString($length = 10, $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ')
  198. {
  199. $tmp = '';
  200. for ($i = 0; $i < $length; $i++) {
  201. $tmp .= substr(str_shuffle($chars), 0, 1);
  202. }
  203. return $tmp;
  204. }
  205. public function isEncrypted($password = null)
  206. {
  207. return ($password == null || $password == '') ? false : $this->decrypt($password);
  208. }
  209. public function fillString($string, $length)
  210. {
  211. $filler = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*';
  212. if (strlen($string) < $length) {
  213. $diff = $length - strlen($string);
  214. $filler = substr($filler, 0, $diff);
  215. return $string . $filler;
  216. } elseif (strlen($string) > $length) {
  217. return substr($string, 0, $length);
  218. } else {
  219. return $string;
  220. }
  221. }
  222. public function userIP()
  223. {
  224. if (isset($_SERVER['HTTP_CLIENT_IP'])) {
  225. $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
  226. } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  227. $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
  228. } elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
  229. $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
  230. } elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
  231. $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
  232. } elseif (isset($_SERVER['HTTP_FORWARDED'])) {
  233. $ipaddress = $_SERVER['HTTP_FORWARDED'];
  234. } elseif (isset($_SERVER['REMOTE_ADDR'])) {
  235. $ipaddress = $_SERVER['REMOTE_ADDR'];
  236. } else {
  237. $ipaddress = '127.0.0.1';
  238. }
  239. if (strpos($ipaddress, ',') !== false) {
  240. list($first, $last) = explode(",", $ipaddress);
  241. unset($last);
  242. return $first;
  243. } else {
  244. return $ipaddress;
  245. }
  246. }
  247. public function serverIP()
  248. {
  249. if (array_key_exists('SERVER_ADDR', $_SERVER)) {
  250. return $_SERVER['SERVER_ADDR'];
  251. }
  252. return '127.0.0.1';
  253. }
  254. public function parseDomain($value, $force = false)
  255. {
  256. $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');
  257. $Domain = $value;
  258. $Port = strpos($Domain, ':');
  259. if ($Port !== false) {
  260. $Domain = substr($Domain, 0, $Port);
  261. $value = $Domain;
  262. }
  263. $check = substr_count($Domain, '.');
  264. if ($check >= 3) {
  265. if (is_numeric($Domain[0])) {
  266. $Domain = '';
  267. } else {
  268. if (in_array(strtolower(explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3]), $badDomains)) {
  269. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3];
  270. } else {
  271. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2] . '.' . explode('.', $Domain)[3];
  272. }
  273. }
  274. } elseif ($check == 2) {
  275. if (in_array(strtolower(explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2]), $badDomains)) {
  276. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  277. } elseif (explode('.', $Domain)[0] == 'www') {
  278. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  279. } elseif (explode('.', $Domain)[1] == 'co') {
  280. $Domain = '.' . explode('.', $Domain)[0] . '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  281. } else {
  282. $Domain = '.' . explode('.', $Domain)[1] . '.' . explode('.', $Domain)[2];
  283. }
  284. } elseif ($check == 1) {
  285. $Domain = '.' . $Domain;
  286. } else {
  287. $Domain = '';
  288. }
  289. return ($force) ? $value : $Domain;
  290. }
  291. // Cookie Custom Function
  292. public function coookie($type, $name, $value = '', $days = -1, $http = true, $path = '/')
  293. {
  294. $days = ($days > 365) ? 365 : $days;
  295. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  296. $Secure = true;
  297. $HTTPOnly = true;
  298. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' && $_SERVER['HTTPS'] !== '') {
  299. $Secure = true;
  300. $HTTPOnly = true;
  301. } else {
  302. $Secure = false;
  303. $HTTPOnly = false;
  304. }
  305. if (!$http) {
  306. $HTTPOnly = false;
  307. }
  308. $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? '';
  309. $Domain = $this->parseDomain($_SERVER['HTTP_HOST']);
  310. $DomainTest = $this->parseDomain($_SERVER['HTTP_HOST'], true);
  311. if ($type == 'set') {
  312. $_COOKIE[$name] = $value;
  313. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  314. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
  315. . (empty($path) ? '' : '; path=' . $path)
  316. . (empty($Domain) ? '' : '; domain=' . $Domain)
  317. . (!$Secure ? '' : '; SameSite=None; Secure')
  318. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  319. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  320. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + (86400 * $days)) . ' GMT')
  321. . (empty($path) ? '' : '; path=' . $path)
  322. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  323. . (!$Secure ? '' : '; SameSite=None; Secure')
  324. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  325. } elseif ($type == 'delete') {
  326. unset($_COOKIE[$name]);
  327. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  328. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  329. . (empty($path) ? '' : '; path=' . $path)
  330. . (empty($Domain) ? '' : '; domain=' . $Domain)
  331. . (!$Secure ? '' : '; SameSite=None; Secure')
  332. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  333. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  334. . (empty($days) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  335. . (empty($path) ? '' : '; path=' . $path)
  336. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  337. . (!$Secure ? '' : '; SameSite=None; Secure')
  338. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  339. }
  340. }
  341. public function coookieSeconds($type, $name, $value = '', $ms = null, $http = true, $path = '/')
  342. {
  343. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  344. $Secure = true;
  345. $HTTPOnly = true;
  346. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' && $_SERVER['HTTPS'] !== '') {
  347. $Secure = true;
  348. $HTTPOnly = true;
  349. } else {
  350. $Secure = false;
  351. $HTTPOnly = false;
  352. }
  353. if (!$http) {
  354. $HTTPOnly = false;
  355. }
  356. $_SERVER['HTTP_HOST'] = $_SERVER['HTTP_HOST'] ?? '';
  357. $Domain = $this->parseDomain($_SERVER['HTTP_HOST']);
  358. $DomainTest = $this->parseDomain($_SERVER['HTTP_HOST'], true);
  359. if ($type == 'set') {
  360. $_COOKIE[$name] = $value;
  361. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  362. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + ($ms / 1000)) . ' GMT')
  363. . (empty($path) ? '' : '; path=' . $path)
  364. . (empty($Domain) ? '' : '; domain=' . $Domain)
  365. . (!$Secure ? '' : '; SameSite=None; Secure')
  366. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  367. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  368. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() + ($ms / 1000)) . ' GMT')
  369. . (empty($path) ? '' : '; path=' . $path)
  370. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  371. . (!$Secure ? '' : '; SameSite=None; Secure')
  372. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  373. } elseif ($type == 'delete') {
  374. unset($_COOKIE[$name]);
  375. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  376. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  377. . (empty($path) ? '' : '; path=' . $path)
  378. . (empty($Domain) ? '' : '; domain=' . $Domain)
  379. . (!$Secure ? '' : '; SameSite=None; Secure')
  380. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  381. header('Set-Cookie: ' . rawurlencode($name) . '=' . rawurlencode($value)
  382. . (empty($ms) ? '' : '; expires=' . gmdate('D, d-M-Y H:i:s', time() - 3600) . ' GMT')
  383. . (empty($path) ? '' : '; path=' . $path)
  384. . (empty($Domain) ? '' : '; domain=' . $DomainTest)
  385. . (!$Secure ? '' : '; SameSite=None; Secure')
  386. . (!$HTTPOnly ? '' : '; HttpOnly'), false);
  387. }
  388. }
  389. // Qualify URL
  390. public function qualifyURL($url, $return = false, $includeTrailing = false)
  391. {
  392. //local address?
  393. if (substr($url, 0, 1) == "/") {
  394. 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')) {
  395. $protocol = "https://";
  396. } else {
  397. $protocol = "http://";
  398. }
  399. $url = $protocol . $this->getServer() . $url;
  400. }
  401. // Get Digest
  402. $digest = $includeTrailing ? parse_url($url) : parse_url(rtrim(preg_replace('/\s+/', '', $url), '/'));
  403. // http/https
  404. if (!isset($digest['scheme'])) {
  405. $scheme = 'http';
  406. } else {
  407. $scheme = $digest['scheme'];
  408. }
  409. // Host
  410. $host = (isset($digest['host']) ? $digest['host'] : '');
  411. // Port
  412. $port = (isset($digest['port']) ? ':' . $digest['port'] : '');
  413. // Path
  414. $path = (isset($digest['path']) ? $digest['path'] : '');
  415. // Query
  416. $query = (isset($digest['query']) ? '?' . $digest['query'] : '');
  417. // Output
  418. $array = array(
  419. 'scheme' => $scheme,
  420. 'host' => $host,
  421. 'port' => $port,
  422. 'path' => $path,
  423. 'query' => $query
  424. );
  425. return ($return) ? $array : $scheme . '://' . $host . $port . $path . $query;
  426. }
  427. public function getServer($over = false)
  428. {
  429. if ($over) {
  430. if ($this->config['PHPMAILER-domain'] !== '') {
  431. return $this->config['PHPMAILER-domain'];
  432. }
  433. }
  434. return isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  435. }
  436. public function getServerPath($over = false)
  437. {
  438. if ($over) {
  439. if ($this->config['PHPMAILER-domain'] !== '') {
  440. return $this->config['PHPMAILER-domain'];
  441. }
  442. }
  443. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  444. $protocol = "https://";
  445. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  446. $protocol = "https://";
  447. } else {
  448. $protocol = "http://";
  449. }
  450. $domain = '';
  451. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  452. $domain = $_SERVER['SERVER_NAME'];
  453. } elseif (isset($_SERVER['HTTP_HOST'])) {
  454. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  455. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  456. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  457. if ($port !== "80" && $port !== "443") {
  458. $domain = $_SERVER['HTTP_HOST'];
  459. }
  460. } else {
  461. $domain = $_SERVER['HTTP_HOST'];
  462. }
  463. }
  464. $path = str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  465. $path = ($path !== '.') ? $path : '';
  466. $url = $protocol . $domain . $path;
  467. if (strpos($url, '/api') !== false) {
  468. $url = explode('/api', $url);
  469. return $url[0] . '/';
  470. } else {
  471. return $url;
  472. }
  473. }
  474. public function convertIPToRange($ip)
  475. {
  476. if (strpos($ip, '/') !== false) {
  477. $explodeIP = explode('/', $ip);
  478. $prefix = $explodeIP[1];
  479. $start_ip = $explodeIP[0];
  480. $ip_count = 1 << (32 - $prefix);
  481. $start_ip_long = long2ip(ip2long($start_ip));
  482. $last_ip_long = long2ip(ip2long($start_ip) + $ip_count - 1);
  483. } elseif (substr_count($ip, '.') == 3) {
  484. $start_ip_long = long2ip(ip2long($ip));
  485. $last_ip_long = long2ip(ip2long($ip));
  486. } else {
  487. return false;
  488. }
  489. return [
  490. 'from' => $start_ip_long,
  491. 'to' => $last_ip_long
  492. ];
  493. }
  494. public function localIPRanges()
  495. {
  496. $mainArray = array(
  497. array(
  498. 'from' => '10.0.0.0',
  499. 'to' => '10.255.255.255'
  500. ),
  501. array(
  502. 'from' => '172.16.0.0',
  503. 'to' => '172.31.255.255'
  504. ),
  505. array(
  506. 'from' => '192.168.0.0',
  507. 'to' => '192.168.255.255'
  508. ),
  509. array(
  510. 'from' => '127.0.0.1',
  511. 'to' => '127.255.255.255'
  512. ),
  513. );
  514. if (isset($this->config['localIPList'])) {
  515. if ($this->config['localIPList'] !== '') {
  516. $ipListing = explode(',', $this->config['localIPList']);
  517. if (count($ipListing) > 0) {
  518. foreach ($ipListing as $ip) {
  519. $ipInfo = $this->convertIPToRange($ip);
  520. if ($ipInfo) {
  521. array_push($mainArray, $ipInfo);
  522. }
  523. }
  524. }
  525. }
  526. }
  527. /*
  528. if ($this->config['localIPFrom']) {
  529. $from = trim($this->config['localIPFrom']);
  530. $override = true;
  531. }
  532. if ($this->config['localIPTo']) {
  533. $to = trim($this->config['localIPTo']);
  534. }
  535. if ($override) {
  536. $newArray = array(
  537. 'from' => $from,
  538. 'to' => (isset($to)) ? $to : $from
  539. );
  540. array_push($mainArray, $newArray);
  541. }
  542. */
  543. return $mainArray;
  544. }
  545. public function isLocal($checkIP = null)
  546. {
  547. $isLocal = false;
  548. $userIP = ($checkIP) ? ip2long($checkIP) : ip2long($this->userIP());
  549. $range = $this->localIPRanges();
  550. foreach ($range as $ip) {
  551. $low = ip2long($ip['from']);
  552. $high = ip2long($ip['to']);
  553. if ($userIP <= $high && $low <= $userIP) {
  554. $isLocal = true;
  555. }
  556. }
  557. return $isLocal;
  558. }
  559. public function isLocalOrServer()
  560. {
  561. $isLocalOrServer = false;
  562. $isLocal = $this->isLocal();
  563. if (!$isLocal) {
  564. if ($this->userIP() == $this->serverIP()) {
  565. $isLocalOrServer = true;
  566. }
  567. } else {
  568. $isLocalOrServer = true;
  569. }
  570. return $isLocalOrServer;
  571. }
  572. public function human_filesize($bytes, $dec = 2)
  573. {
  574. $bytes = number_format($bytes, 0, '.', '');
  575. $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  576. $factor = floor((strlen($bytes) - 1) / 3);
  577. return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
  578. }
  579. public function apiResponseFormatter($response)
  580. {
  581. if (is_array($response)) {
  582. return $response;
  583. }
  584. if (empty($response) || $response == '') {
  585. return ['api_response' => 'No data'];
  586. }
  587. if ($this->json_validator($response)) {
  588. return json_decode($response, true);
  589. }
  590. return ['api_response' => 'No data'];
  591. }
  592. public function json_validator($data = null)
  593. {
  594. if (!empty($data)) {
  595. @json_decode($data);
  596. return (json_last_error() === JSON_ERROR_NONE);
  597. }
  598. return false;
  599. }
  600. public function replace_first($search_str, $replacement_str, $src_str)
  601. {
  602. return (false !== ($pos = strpos($src_str, $search_str))) ? substr_replace($src_str, $replacement_str, $pos, strlen($search_str)) : $src_str;
  603. }
  604. /**
  605. * Check if an array is a multidimensional array.
  606. *
  607. * @param array $arr The array to check
  608. * @return boolean Whether the the array is a multidimensional array or not
  609. */
  610. public function is_multi_array($x)
  611. {
  612. if (count(array_filter($x, 'is_array')) > 0) return true;
  613. return false;
  614. }
  615. /**
  616. * Convert an object to an array.
  617. *
  618. * @param array $object The object to convert
  619. * @return array The converted array
  620. */
  621. public function object_to_array($object)
  622. {
  623. if (!is_object($object) && !is_array($object)) return $object;
  624. return array_map(array($this, 'object_to_array'), (array)$object);
  625. }
  626. /**
  627. * Check if a value exists in the array/object.
  628. *
  629. * @param mixed $needle The value that you are searching for
  630. * @param mixed $haystack The array/object to search
  631. * @param boolean $strict Whether to use strict search or not
  632. * @return boolean Whether the value was found or not
  633. */
  634. public function search_for_value($needle, $haystack, $strict = true)
  635. {
  636. $haystack = $this->object_to_array($haystack);
  637. if (is_array($haystack)) {
  638. if ($this->is_multi_array($haystack)) { // Multidimensional array
  639. foreach ($haystack as $subhaystack) {
  640. if ($this->search_for_value($needle, $subhaystack, $strict)) {
  641. return true;
  642. }
  643. }
  644. } elseif (array_keys($haystack) !== range(0, count($haystack) - 1)) { // Associative array
  645. foreach ($haystack as $key => $val) {
  646. if ($needle == $val && !$strict) {
  647. return true;
  648. } elseif ($needle === $val && $strict) {
  649. return true;
  650. }
  651. }
  652. return false;
  653. } else { // Normal array
  654. if ($needle == $haystack && !$strict) {
  655. return true;
  656. } elseif ($needle === $haystack && $strict) {
  657. return true;
  658. }
  659. }
  660. }
  661. return false;
  662. }
  663. public function makeDir($dirPath, $mode = 0777)
  664. {
  665. return is_dir($dirPath) || @mkdir($dirPath, $mode, true);
  666. }
  667. }
  668. // Leave for deluge class
  669. function getCert()
  670. {
  671. $url = 'http://curl.haxx.se/ca/cacert.pem';
  672. $file = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  673. $file2 = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  674. $useCert = (file_exists($file)) ? $file : $file2;
  675. $context = stream_context_create(
  676. array(
  677. 'ssl' => array(
  678. 'verify_peer' => true,
  679. 'cafile' => $useCert
  680. )
  681. )
  682. );
  683. if (!file_exists($file)) {
  684. file_put_contents($file, fopen($url, 'r', false, $context));
  685. } elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
  686. file_put_contents($file, fopen($url, 'r', false, $context));
  687. }
  688. return $file;
  689. }
  690. // Leave for deluge class
  691. function localURL($url, $force = false)
  692. {
  693. if ($force) {
  694. return true;
  695. }
  696. if (strpos($url, 'https') !== false) {
  697. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
  698. $result = (!empty($result) ? true : false);
  699. return $result;
  700. }
  701. return false;
  702. }
  703. // Maybe use later?
  704. function curl($curl, $url, $headers = array(), $data = array())
  705. {
  706. // Initiate cURL
  707. $curlReq = curl_init($url);
  708. if (in_array(trim(strtoupper($curl)), ["GET", "POST", "PUT", "DELETE"])) {
  709. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, trim(strtoupper($curl)));
  710. } else {
  711. return null;
  712. }
  713. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  714. curl_setopt($curlReq, CURLOPT_CAINFO, getCert());
  715. curl_setopt($curlReq, CURLOPT_CONNECTTIMEOUT, 5);
  716. if (localURL($url)) {
  717. curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 0);
  718. curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, 0);
  719. }
  720. // Format Headers
  721. $cHeaders = array();
  722. foreach ($headers as $k => $v) {
  723. $cHeaders[] = $k . ': ' . $v;
  724. }
  725. if (count($cHeaders)) {
  726. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  727. }
  728. // Format Data
  729. switch (isset($headers['Content-Type']) ? $headers['Content-Type'] : '') {
  730. case 'application/json':
  731. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  732. break;
  733. case 'application/x-www-form-urlencoded':
  734. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  735. break;
  736. default:
  737. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  738. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  739. }
  740. // Execute
  741. $result = curl_exec($curlReq);
  742. $httpcode = curl_getinfo($curlReq);
  743. // Close
  744. curl_close($curlReq);
  745. // Return
  746. return array('content' => $result, 'http_code' => $httpcode);
  747. }
  748. // Maybe use later?
  749. function getHeaders($url)
  750. {
  751. $ch = curl_init($url);
  752. curl_setopt($ch, CURLOPT_NOBODY, true);
  753. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  754. curl_setopt($ch, CURLOPT_HEADER, false);
  755. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  756. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  757. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  758. if (localURL($url)) {
  759. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  760. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  761. }
  762. curl_exec($ch);
  763. $headers = curl_getinfo($ch);
  764. curl_close($ch);
  765. return $headers;
  766. }
  767. // Maybe use later?
  768. function download($url, $path)
  769. {
  770. ini_set('max_execution_time', 0);
  771. set_time_limit(0);
  772. $ch = curl_init($url);
  773. curl_setopt($ch, CURLOPT_HEADER, 1);
  774. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  775. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  776. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  777. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  778. if (localURL($url)) {
  779. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  780. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  781. }
  782. $raw_file_data = curl_exec($ch);
  783. curl_close($ch);
  784. file_put_contents($path, $raw_file_data);
  785. return (filesize($path) > 0) ? true : false;
  786. }
  787. // swagger
  788. function getServerPath($over = false)
  789. {
  790. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  791. $protocol = "https://";
  792. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  793. $protocol = "https://";
  794. } else {
  795. $protocol = "http://";
  796. }
  797. $domain = '';
  798. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  799. $domain = $_SERVER['SERVER_NAME'];
  800. } elseif (isset($_SERVER['HTTP_HOST'])) {
  801. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  802. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  803. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  804. if ($port !== "80" && $port !== "443") {
  805. $domain = $_SERVER['HTTP_HOST'];
  806. }
  807. } else {
  808. $domain = $_SERVER['HTTP_HOST'];
  809. }
  810. }
  811. $url = $protocol . $domain . str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  812. if (strpos($url, '/api') !== false) {
  813. $url = explode('/api', $url);
  814. return $url[0] . '/';
  815. } else {
  816. return $url;
  817. }
  818. }
  819. // used for api return
  820. function safe_json_encode($value, $options = 0, $depth = 512)
  821. {
  822. $encoded = json_encode($value, $options, $depth);
  823. if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
  824. $encoded = json_encode(utf8ize($value), $options, $depth);
  825. }
  826. return $encoded;
  827. }
  828. // used for api return
  829. function utf8ize($mixed)
  830. {
  831. if (is_array($mixed)) {
  832. foreach ($mixed as $key => $value) {
  833. $mixed[$key] = utf8ize($value);
  834. }
  835. } elseif (is_string($mixed)) {
  836. return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
  837. }
  838. return $mixed;
  839. }