Tools.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Utils;
  4. use App\Models\Config;
  5. use App\Models\Link;
  6. use App\Models\User;
  7. use App\Services\GeoIP2;
  8. use GeoIp2\Exception\AddressNotFoundException;
  9. use MaxMind\Db\Reader\InvalidDatabaseException;
  10. use function array_diff;
  11. use function array_flip;
  12. use function base64_encode;
  13. use function bin2hex;
  14. use function closedir;
  15. use function count;
  16. use function date;
  17. use function explode;
  18. use function filter_var;
  19. use function floor;
  20. use function hash;
  21. use function in_array;
  22. use function is_numeric;
  23. use function json_decode;
  24. use function log;
  25. use function mb_strcut;
  26. use function opendir;
  27. use function openssl_random_pseudo_bytes;
  28. use function pow;
  29. use function range;
  30. use function readdir;
  31. use function round;
  32. use function shuffle;
  33. use function strlen;
  34. use function strpos;
  35. use function substr;
  36. use const FILTER_FLAG_IPV4;
  37. use const FILTER_FLAG_IPV6;
  38. use const FILTER_VALIDATE_EMAIL;
  39. use const FILTER_VALIDATE_INT;
  40. use const FILTER_VALIDATE_IP;
  41. final class Tools
  42. {
  43. /**
  44. * 查询IP归属
  45. *
  46. * @param string $ip
  47. */
  48. public static function getIpLocation(string $ip): string
  49. {
  50. $data = 'GeoIP2 服务未配置';
  51. $city = null;
  52. $country = null;
  53. if ($_ENV['maxmind_license_key'] !== '') {
  54. try {
  55. $geoip = new GeoIP2();
  56. } catch (InvalidDatabaseException $e) {
  57. return $data;
  58. }
  59. try {
  60. $city = $geoip->getCity($ip);
  61. } catch (AddressNotFoundException|InvalidDatabaseException $e) {
  62. $city = '未知城市';
  63. }
  64. try {
  65. $country = $geoip->getCountry($ip);
  66. } catch (AddressNotFoundException|InvalidDatabaseException $e) {
  67. $country = '未知国家';
  68. }
  69. }
  70. if ($country !== null) {
  71. $data = $country;
  72. }
  73. if ($city !== null) {
  74. $data = $city . ', ' . $country;
  75. }
  76. return $data;
  77. }
  78. /**
  79. * 根据流量值自动转换单位输出
  80. *
  81. * @param $size
  82. * @param int $precision
  83. */
  84. public static function autoBytes($size, int $precision = 2): string
  85. {
  86. if ($size <= 0) {
  87. return '0B';
  88. }
  89. if ($size > 1208925819614629174706176) {
  90. return '∞';
  91. }
  92. $base = log((float) $size, 1024);
  93. $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  94. return round(pow(1024, $base - floor($base)), $precision) . $units[floor($base)];
  95. }
  96. /**
  97. * 根据含单位的流量值转换 B 输出
  98. *
  99. * @param $size
  100. */
  101. public static function autoBytesR($size): ?int
  102. {
  103. if (is_numeric(substr($size, 0, -1))) {
  104. return (int) substr($size, 0, -1);
  105. }
  106. $suffix = substr($size, -2);
  107. $base = substr($size, 0, strlen($size) - 2);
  108. $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
  109. if ($base > 999 && $suffix === 'EB') {
  110. return -1;
  111. }
  112. return (int) ($base * pow(1024, array_flip($units)[$suffix]));
  113. }
  114. /**
  115. * 根据速率值自动转换单位输出
  116. *
  117. * @param $size
  118. * @param int $precision
  119. */
  120. public static function autoMbps($size, int $precision = 2): string
  121. {
  122. if ($size <= 0) {
  123. return '0Bps';
  124. }
  125. if ($size > 1000000000) {
  126. return '∞';
  127. }
  128. $base = log((float) $size, 1000);
  129. $units = ['Mbps', 'Gbps', 'Tbps'];
  130. return round(pow(1000, $base - floor($base)), $precision) . $units[floor($base)];
  131. }
  132. /**
  133. * 虽然名字是toMB,但是实际上功能是from MB to B
  134. *
  135. * @param $traffic
  136. */
  137. public static function toMB($traffic): int
  138. {
  139. return (int) $traffic * 1048576;
  140. }
  141. /**
  142. * 虽然名字是toGB,但是实际上功能是from GB to B
  143. *
  144. * @param $traffic
  145. */
  146. public static function toGB($traffic): int
  147. {
  148. return (int) $traffic * 1073741824;
  149. }
  150. /**
  151. * @param $traffic
  152. */
  153. public static function flowToMB($traffic): float
  154. {
  155. return round($traffic / 1048576, 2);
  156. }
  157. /**
  158. * @param $traffic
  159. */
  160. public static function flowToGB($traffic): float
  161. {
  162. return round($traffic / 1073741824, 2);
  163. }
  164. public static function genSubToken(): string
  165. {
  166. $token = self::genRandomChar($_ENV['sub_token_len']);
  167. $is_token_used = (new Link())->where('token', $token)->first();
  168. if ($is_token_used === null) {
  169. return $token;
  170. }
  171. return "couldn't alloc token";
  172. }
  173. public static function genRandomChar(int $length = 8): string
  174. {
  175. if ($length <= 2) {
  176. $length = 2;
  177. }
  178. return bin2hex(openssl_random_pseudo_bytes($length / 2));
  179. }
  180. public static function genSs2022UserPk($passwd, $len): string
  181. {
  182. $passwd_hash = hash('sha256', $passwd);
  183. $pk = match ($len) {
  184. 16 => mb_strcut($passwd_hash, 0, 16),
  185. 32 => mb_strcut($passwd_hash, 0, 32),
  186. default => $passwd_hash,
  187. };
  188. return base64_encode($pk);
  189. }
  190. public static function toDateTime(int $time): string
  191. {
  192. return date('Y-m-d H:i:s', $time);
  193. }
  194. public static function getSsPort(): int
  195. {
  196. $max_port = Config::obtain('max_port');
  197. $min_port = Config::obtain('min_port');
  198. if ($min_port >= 65535
  199. || $min_port <= 0
  200. || $max_port > 65535
  201. || $max_port <= 0
  202. || $min_port > $max_port
  203. || count(User::all()) >= $max_port - $min_port + 1
  204. ) {
  205. return 0;
  206. }
  207. $det = (new User())->pluck('port')->toArray();
  208. $port = array_diff(range($min_port, $max_port), $det);
  209. shuffle($port);
  210. return $port[0];
  211. }
  212. /**
  213. * @param $dir
  214. *
  215. * @return array
  216. */
  217. public static function getDir($dir): array
  218. {
  219. $dirArray = [];
  220. $handle = opendir($dir);
  221. if ($handle !== false) {
  222. $i = 0;
  223. while (($file = readdir($handle)) !== false) {
  224. if ($file !== '.' && $file !== '..' && ! strpos($file, '.')) {
  225. $dirArray[$i] = $file;
  226. $i++;
  227. }
  228. }
  229. closedir($handle);
  230. }
  231. return $dirArray;
  232. }
  233. /**
  234. * @param $type
  235. * @param $str
  236. */
  237. public static function isParamValidate($type, $str): bool
  238. {
  239. $list = self::getSsMethod($type);
  240. if (in_array($str, $list)) {
  241. return true;
  242. }
  243. return false;
  244. }
  245. public static function getSsMethod($type): array
  246. {
  247. return match ($type) {
  248. 'ss_obfs' => [
  249. 'simple_obfs_http',
  250. 'simple_obfs_http_compatible',
  251. 'simple_obfs_tls',
  252. 'simple_obfs_tls_compatible',
  253. ],
  254. default => [
  255. 'aes-128-gcm',
  256. 'aes-192-gcm',
  257. 'aes-256-gcm',
  258. 'chacha20-ietf-poly1305',
  259. 'xchacha20-ietf-poly1305',
  260. ],
  261. };
  262. }
  263. /**
  264. * @param $email
  265. *
  266. * @return array
  267. */
  268. public static function isEmailLegal($email): array
  269. {
  270. $res = [];
  271. $res['ret'] = 0;
  272. if (! self::isEmail($email)) {
  273. $res['msg'] = '邮箱不规范';
  274. return $res;
  275. }
  276. $mail_suffix = explode('@', $email)[1];
  277. $mail_filter_list = $_ENV['mail_filter_list'];
  278. switch ($_ENV['mail_filter']) {
  279. case 1:
  280. // 白名单
  281. if (in_array($mail_suffix, $mail_filter_list)) {
  282. $res['ret'] = 1;
  283. } else {
  284. $res['msg'] = '邮箱域名 ' . $mail_suffix . ' 无效,请更换邮件地址';
  285. }
  286. return $res;
  287. case 2:
  288. // 黑名单
  289. if (! in_array($mail_suffix, $mail_filter_list)) {
  290. $res['ret'] = 1;
  291. } else {
  292. $res['msg'] = '邮箱域名 ' . $mail_suffix . ' 无效,请更换邮件地址';
  293. }
  294. return $res;
  295. default:
  296. $res['ret'] = 1;
  297. return $res;
  298. }
  299. }
  300. /**
  301. * @param $input
  302. */
  303. public static function isEmail($input): bool
  304. {
  305. if (! filter_var($input, FILTER_VALIDATE_EMAIL)) {
  306. return false;
  307. }
  308. return true;
  309. }
  310. /**
  311. * @param $input
  312. */
  313. public static function isIPv4($input): bool
  314. {
  315. if (! filter_var($input, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  316. return false;
  317. }
  318. return true;
  319. }
  320. /**
  321. * @param $input
  322. */
  323. public static function isIPv6($input): bool
  324. {
  325. if (! filter_var($input, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
  326. return false;
  327. }
  328. return true;
  329. }
  330. /**
  331. * @param $input
  332. */
  333. public static function isInt($input): bool
  334. {
  335. if (! filter_var($input, FILTER_VALIDATE_INT)) {
  336. return false;
  337. }
  338. return true;
  339. }
  340. /**
  341. * 判断是否 JSON
  342. * TODO: Remove this function when PHP 8.3 is minimum requirement and replace it with native function
  343. *
  344. * @param string $string
  345. */
  346. public static function isJson(string $string): bool
  347. {
  348. if (! json_decode($string)) {
  349. return false;
  350. }
  351. return true;
  352. }
  353. }