4
0

normal-functions.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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 = (isset($digest['host']) ? $digest['host'] : '');
  415. // Port
  416. $port = (isset($digest['port']) ? ':' . $digest['port'] : '');
  417. // Path
  418. $path = (isset($digest['path']) ? $digest['path'] : '');
  419. // Query
  420. $query = (isset($digest['query']) ? '?' . $digest['query'] : '');
  421. // Output
  422. $array = array(
  423. 'scheme' => $scheme,
  424. 'host' => $host,
  425. 'port' => $port,
  426. 'path' => $path,
  427. 'query' => $query
  428. );
  429. return ($return) ? $array : $scheme . '://' . $host . $port . $path . $query;
  430. }
  431. public function getServer($over = false)
  432. {
  433. if ($over) {
  434. if ($this->config['PHPMAILER-domain'] !== '') {
  435. return $this->config['PHPMAILER-domain'];
  436. }
  437. }
  438. return isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"];
  439. }
  440. public function getServerPath($over = false)
  441. {
  442. if ($over) {
  443. if ($this->config['PHPMAILER-domain'] !== '') {
  444. return $this->config['PHPMAILER-domain'];
  445. }
  446. }
  447. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  448. $protocol = "https://";
  449. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  450. $protocol = "https://";
  451. } else {
  452. $protocol = "http://";
  453. }
  454. $domain = '';
  455. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  456. $domain = $_SERVER['SERVER_NAME'];
  457. } elseif (isset($_SERVER['HTTP_HOST'])) {
  458. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  459. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  460. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  461. if ($port !== "80" && $port !== "443") {
  462. $domain = $_SERVER['HTTP_HOST'];
  463. }
  464. } else {
  465. $domain = $_SERVER['HTTP_HOST'];
  466. }
  467. }
  468. $path = str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  469. $path = ($path !== '.') ? $path : '';
  470. $url = $protocol . $domain . $path;
  471. if (strpos($url, '/api') !== false) {
  472. $url = explode('/api', $url);
  473. return $url[0] . '/';
  474. } else {
  475. return $url;
  476. }
  477. }
  478. public function convertIPToRange($ip)
  479. {
  480. if (strpos($ip, '/') !== false) {
  481. $explodeIP = explode('/', $ip);
  482. $prefix = $explodeIP[1];
  483. $start_ip = $explodeIP[0];
  484. $ip_count = 1 << (32 - $prefix);
  485. $start_ip_long = long2ip(ip2long($start_ip));
  486. $last_ip_long = long2ip(ip2long($start_ip) + $ip_count - 1);
  487. } elseif (substr_count($ip, '.') == 3) {
  488. $start_ip_long = long2ip(ip2long($ip));
  489. $last_ip_long = long2ip(ip2long($ip));
  490. } else {
  491. return false;
  492. }
  493. return [
  494. 'from' => $start_ip_long,
  495. 'to' => $last_ip_long
  496. ];
  497. }
  498. public function localIPRanges()
  499. {
  500. $mainArray = array(
  501. array(
  502. 'from' => '10.0.0.0',
  503. 'to' => '10.255.255.255'
  504. ),
  505. array(
  506. 'from' => '172.16.0.0',
  507. 'to' => '172.31.255.255'
  508. ),
  509. array(
  510. 'from' => '192.168.0.0',
  511. 'to' => '192.168.255.255'
  512. ),
  513. array(
  514. 'from' => '127.0.0.1',
  515. 'to' => '127.255.255.255'
  516. ),
  517. );
  518. if (isset($this->config['localIPList'])) {
  519. if ($this->config['localIPList'] !== '') {
  520. $ipListing = explode(',', $this->config['localIPList']);
  521. if (count($ipListing) > 0) {
  522. foreach ($ipListing as $ip) {
  523. $ipInfo = $this->convertIPToRange($ip);
  524. if ($ipInfo) {
  525. array_push($mainArray, $ipInfo);
  526. }
  527. }
  528. }
  529. }
  530. }
  531. /*
  532. if ($this->config['localIPFrom']) {
  533. $from = trim($this->config['localIPFrom']);
  534. $override = true;
  535. }
  536. if ($this->config['localIPTo']) {
  537. $to = trim($this->config['localIPTo']);
  538. }
  539. if ($override) {
  540. $newArray = array(
  541. 'from' => $from,
  542. 'to' => (isset($to)) ? $to : $from
  543. );
  544. array_push($mainArray, $newArray);
  545. }
  546. */
  547. return $mainArray;
  548. }
  549. public function isLocal($checkIP = null)
  550. {
  551. $isLocal = false;
  552. $userIP = ($checkIP) ? ip2long($checkIP) : ip2long($this->userIP());
  553. $range = $this->localIPRanges();
  554. foreach ($range as $ip) {
  555. $low = ip2long($ip['from']);
  556. $high = ip2long($ip['to']);
  557. if ($userIP <= $high && $low <= $userIP) {
  558. $isLocal = true;
  559. }
  560. }
  561. return $isLocal;
  562. }
  563. public function isLocalOrServer()
  564. {
  565. $isLocalOrServer = false;
  566. $isLocal = $this->isLocal();
  567. if (!$isLocal) {
  568. if ($this->userIP() == $this->serverIP()) {
  569. $isLocalOrServer = true;
  570. }
  571. } else {
  572. $isLocalOrServer = true;
  573. }
  574. return $isLocalOrServer;
  575. }
  576. public function human_filesize($bytes, $dec = 2)
  577. {
  578. $bytes = number_format($bytes, 0, '.', '');
  579. $size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
  580. $factor = floor((strlen($bytes) - 1) / 3);
  581. return sprintf("%.{$dec}f %s", $bytes / (1024 ** $factor), $size[$factor]);
  582. }
  583. public function apiResponseFormatter($response)
  584. {
  585. if (is_array($response)) {
  586. return $response;
  587. }
  588. if (empty($response) || $response == '') {
  589. return ['api_response' => 'No data'];
  590. }
  591. if ($this->json_validator($response)) {
  592. return json_decode($response, true);
  593. }
  594. return ['api_response' => 'No data'];
  595. }
  596. public function json_validator($data = null)
  597. {
  598. if (!empty($data)) {
  599. @json_decode($data);
  600. return (json_last_error() === JSON_ERROR_NONE);
  601. }
  602. return false;
  603. }
  604. public function replace_first($search_str, $replacement_str, $src_str)
  605. {
  606. return (false !== ($pos = strpos($src_str, $search_str))) ? substr_replace($src_str, $replacement_str, $pos, strlen($search_str)) : $src_str;
  607. }
  608. /**
  609. * Check if an array is a multidimensional array.
  610. *
  611. * @param array $arr The array to check
  612. * @return boolean Whether the the array is a multidimensional array or not
  613. */
  614. public function is_multi_array($x)
  615. {
  616. if (count(array_filter($x, 'is_array')) > 0) return true;
  617. return false;
  618. }
  619. /**
  620. * Convert an object to an array.
  621. *
  622. * @param array $object The object to convert
  623. * @return array The converted array
  624. */
  625. public function object_to_array($object)
  626. {
  627. if (!is_object($object) && !is_array($object)) return $object;
  628. return array_map(array($this, 'object_to_array'), (array)$object);
  629. }
  630. /**
  631. * Check if a value exists in the array/object.
  632. *
  633. * @param mixed $needle The value that you are searching for
  634. * @param mixed $haystack The array/object to search
  635. * @param boolean $strict Whether to use strict search or not
  636. * @return boolean Whether the value was found or not
  637. */
  638. public function search_for_value($needle, $haystack, $strict = true)
  639. {
  640. $haystack = $this->object_to_array($haystack);
  641. if (is_array($haystack)) {
  642. if ($this->is_multi_array($haystack)) { // Multidimensional array
  643. foreach ($haystack as $subhaystack) {
  644. if ($this->search_for_value($needle, $subhaystack, $strict)) {
  645. return true;
  646. }
  647. }
  648. } elseif (array_keys($haystack) !== range(0, count($haystack) - 1)) { // Associative array
  649. foreach ($haystack as $key => $val) {
  650. if ($needle == $val && !$strict) {
  651. return true;
  652. } elseif ($needle === $val && $strict) {
  653. return true;
  654. }
  655. }
  656. return false;
  657. } else { // Normal array
  658. if ($needle == $haystack && !$strict) {
  659. return true;
  660. } elseif ($needle === $haystack && $strict) {
  661. return true;
  662. }
  663. }
  664. }
  665. return false;
  666. }
  667. public function makeDir($dirPath, $mode = 0777)
  668. {
  669. return is_dir($dirPath) || @mkdir($dirPath, $mode, true);
  670. }
  671. }
  672. // Leave for deluge class
  673. function getCert()
  674. {
  675. $url = 'http://curl.haxx.se/ca/cacert.pem';
  676. $file = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert.pem';
  677. $file2 = __DIR__ . DIRECTORY_SEPARATOR . 'cert' . DIRECTORY_SEPARATOR . 'cacert-initial.pem';
  678. $useCert = (file_exists($file)) ? $file : $file2;
  679. $context = stream_context_create(
  680. array(
  681. 'ssl' => array(
  682. 'verify_peer' => true,
  683. 'cafile' => $useCert
  684. )
  685. )
  686. );
  687. if (!file_exists($file)) {
  688. file_put_contents($file, fopen($url, 'r', false, $context));
  689. } elseif (file_exists($file) && time() - 2592000 > filemtime($file)) {
  690. file_put_contents($file, fopen($url, 'r', false, $context));
  691. }
  692. return $file;
  693. }
  694. // Leave for deluge class
  695. function localURL($url, $force = false)
  696. {
  697. if ($force) {
  698. return true;
  699. }
  700. if (strpos($url, 'https') !== false) {
  701. preg_match("/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/", $url, $result);
  702. $result = (!empty($result) ? true : false);
  703. return $result;
  704. }
  705. return false;
  706. }
  707. // Maybe use later?
  708. function curl($curl, $url, $headers = array(), $data = array())
  709. {
  710. // Initiate cURL
  711. $curlReq = curl_init($url);
  712. if (in_array(trim(strtoupper($curl)), ["GET", "POST", "PUT", "DELETE"])) {
  713. curl_setopt($curlReq, CURLOPT_CUSTOMREQUEST, trim(strtoupper($curl)));
  714. } else {
  715. return null;
  716. }
  717. curl_setopt($curlReq, CURLOPT_RETURNTRANSFER, true);
  718. curl_setopt($curlReq, CURLOPT_CAINFO, getCert());
  719. curl_setopt($curlReq, CURLOPT_CONNECTTIMEOUT, 5);
  720. if (localURL($url)) {
  721. curl_setopt($curlReq, CURLOPT_SSL_VERIFYHOST, 0);
  722. curl_setopt($curlReq, CURLOPT_SSL_VERIFYPEER, 0);
  723. }
  724. // Format Headers
  725. $cHeaders = array();
  726. foreach ($headers as $k => $v) {
  727. $cHeaders[] = $k . ': ' . $v;
  728. }
  729. if (count($cHeaders)) {
  730. curl_setopt($curlReq, CURLOPT_HTTPHEADER, $cHeaders);
  731. }
  732. // Format Data
  733. switch (isset($headers['Content-Type']) ? $headers['Content-Type'] : '') {
  734. case 'application/json':
  735. curl_setopt($curlReq, CURLOPT_POSTFIELDS, json_encode($data));
  736. break;
  737. case 'application/x-www-form-urlencoded':
  738. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  739. break;
  740. default:
  741. $headers['Content-Type'] = 'application/x-www-form-urlencoded';
  742. curl_setopt($curlReq, CURLOPT_POSTFIELDS, http_build_query($data));
  743. }
  744. // Execute
  745. $result = curl_exec($curlReq);
  746. $httpcode = curl_getinfo($curlReq);
  747. // Close
  748. curl_close($curlReq);
  749. // Return
  750. return array('content' => $result, 'http_code' => $httpcode);
  751. }
  752. // Maybe use later?
  753. function getHeaders($url)
  754. {
  755. $ch = curl_init($url);
  756. curl_setopt($ch, CURLOPT_NOBODY, true);
  757. curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
  758. curl_setopt($ch, CURLOPT_HEADER, false);
  759. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  760. curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
  761. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  762. if (localURL($url)) {
  763. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  764. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  765. }
  766. curl_exec($ch);
  767. $headers = curl_getinfo($ch);
  768. curl_close($ch);
  769. return $headers;
  770. }
  771. // Maybe use later?
  772. function download($url, $path)
  773. {
  774. ini_set('max_execution_time', 0);
  775. set_time_limit(0);
  776. $ch = curl_init($url);
  777. curl_setopt($ch, CURLOPT_HEADER, 1);
  778. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  779. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  780. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  781. curl_setopt($ch, CURLOPT_CAINFO, getCert());
  782. if (localURL($url)) {
  783. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  784. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  785. }
  786. $raw_file_data = curl_exec($ch);
  787. curl_close($ch);
  788. file_put_contents($path, $raw_file_data);
  789. return (filesize($path) > 0) ? true : false;
  790. }
  791. // swagger
  792. function getServerPath($over = false)
  793. {
  794. if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == "https") {
  795. $protocol = "https://";
  796. } elseif (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
  797. $protocol = "https://";
  798. } else {
  799. $protocol = "http://";
  800. }
  801. $domain = '';
  802. if (isset($_SERVER['SERVER_NAME']) && strpos($_SERVER['SERVER_NAME'], '.') !== false) {
  803. $domain = $_SERVER['SERVER_NAME'];
  804. } elseif (isset($_SERVER['HTTP_HOST'])) {
  805. if (strpos($_SERVER['HTTP_HOST'], ':') !== false) {
  806. $domain = explode(':', $_SERVER['HTTP_HOST'])[0];
  807. $port = explode(':', $_SERVER['HTTP_HOST'])[1];
  808. if ($port !== "80" && $port !== "443") {
  809. $domain = $_SERVER['HTTP_HOST'];
  810. }
  811. } else {
  812. $domain = $_SERVER['HTTP_HOST'];
  813. }
  814. }
  815. $url = $protocol . $domain . str_replace("\\", "/", dirname($_SERVER['REQUEST_URI']));
  816. if (strpos($url, '/api') !== false) {
  817. $url = explode('/api', $url);
  818. return $url[0] . '/';
  819. } else {
  820. return $url;
  821. }
  822. }
  823. // used for api return
  824. function safe_json_encode($value, $options = 0, $depth = 512)
  825. {
  826. $encoded = json_encode($value, $options, $depth);
  827. if ($encoded === false && $value && json_last_error() == JSON_ERROR_UTF8) {
  828. $encoded = json_encode(utf8ize($value), $options, $depth);
  829. }
  830. return $encoded;
  831. }
  832. // used for api return
  833. function utf8ize($mixed)
  834. {
  835. if (is_array($mixed)) {
  836. foreach ($mixed as $key => $value) {
  837. $mixed[$key] = utf8ize($value);
  838. }
  839. } elseif (is_string($mixed)) {
  840. return mb_convert_encoding($mixed, "UTF-8", "UTF-8");
  841. }
  842. return $mixed;
  843. }