normal-functions.php 26 KB

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