normal-functions.php 27 KB

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