Api.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. <?php
  2. namespace app\controller;
  3. use app\BaseController;
  4. use app\model\ConfigModel;
  5. use app\model\LinkModel;
  6. use app\model\SettingModel;
  7. use GuzzleHttp\Client;
  8. use GuzzleHttp\Exception\RequestException;
  9. use PHPHtmlParser\Dom;
  10. use think\facade\Cache;
  11. use think\facade\Filesystem;
  12. use think\helper\Str;
  13. class Api extends BaseController
  14. {
  15. public function site(): \think\response\Json
  16. {
  17. $auth = false;
  18. if ($this->Setting('authCode', env('authCode', false), true)) {
  19. $auth = true;
  20. }
  21. return $this->success("ok", [
  22. 'email' => $this->Setting('email', ''),
  23. "recordNumber" => $this->Setting("recordNumber", ''),
  24. "auth" => $auth
  25. ]);
  26. }
  27. public function background()
  28. {
  29. $bg = $this->Setting('backgroundImage');
  30. if ($bg) {
  31. return redirect($bg, 302);
  32. }
  33. return download("static/background.jpeg",);
  34. }
  35. //获取邮件验证码
  36. function getMailCode(): \think\response\Json
  37. {
  38. $mail = $this->request->post("mail", false);
  39. $code = rand(100000, 999999);
  40. if ($mail) {
  41. if (Cache::get('code' . $mail)) {
  42. return $this->success("请勿频繁获取验证码");
  43. }
  44. $status = \Mail::send($mail, "<h2>您的验证码是: <b style='color:#1d5cdc'>$code</b></h2>");
  45. if ($status) {
  46. Cache::set('code' . $mail, $code, 60);
  47. return $this->success("发送成功");
  48. }
  49. }
  50. return $this->error('发送失败');
  51. }
  52. private function addHttpProtocolRemovePath($url): string
  53. {
  54. // 解析URL
  55. $parsedUrl = parse_url($url);
  56. // 检查是否已经有协议,如果没有则添加http://
  57. if (!isset($parsedUrl['scheme'])) {
  58. // 检查是否以 // 开头,如果是,则转换为相对协议
  59. if (isset($parsedUrl['host']) && strpos($url, '//') === 0) {
  60. $url = 'http:' . $url;
  61. } else {
  62. $url = 'http://' . $url;
  63. }
  64. } else {
  65. // 如果有协议但没有路径,保留原样
  66. $url = $parsedUrl['scheme'] . '://';
  67. // 如果有主机,则添加主机部分
  68. if (isset($parsedUrl['host'])) {
  69. $url .= $parsedUrl['host'];
  70. // 如果有端口号,则添加端口号
  71. if (isset($parsedUrl['port'])) {
  72. $url .= ':' . $parsedUrl['port'];
  73. }
  74. }
  75. }
  76. return $url;
  77. }
  78. private function addHttpProtocol($url)
  79. {
  80. // 检查是否已经有协议,如果没有则添加http://
  81. if (!parse_url($url, PHP_URL_SCHEME)) {
  82. // 检查是否以 // 开头,如果是,则转换为相对协议
  83. if (strpos($url, '//') === 0) {
  84. $url = 'https:' . $url;
  85. } else {
  86. $url = 'http://' . $url;
  87. }
  88. }
  89. return $url;
  90. }
  91. private function hasOnlyPath($url): bool
  92. {
  93. $parsedUrl = parse_url($url);
  94. // 检查是否存在路径但不存在域名和协议
  95. if (isset($parsedUrl['path']) && !isset($parsedUrl['host']) && !isset($parsedUrl['scheme'])) {
  96. return true;
  97. }
  98. return false;
  99. }
  100. function getIcon(): \think\response\Json
  101. {
  102. $avatar = $this->request->post('avatar');
  103. if ($avatar) {
  104. $remote_avatar = $this->Setting("remote_avatar", "https://avatar.mtab.cc/6.x/bottts/png?seed=", true);
  105. $str = $this->downloadFile($remote_avatar . $avatar, md5($avatar) . '.png');
  106. return $this->success(['src' => $str]);
  107. }
  108. $url = $this->request->post('url', false);
  109. $icon = "";
  110. $cdn = $this->Setting('assets_host', '');
  111. if ($url) {
  112. $realUrl = $this->addHttpProtocolRemovePath($url);
  113. $client = \Axios::http();
  114. try {
  115. $response = $client->get($realUrl, [
  116. 'headers' => [
  117. "User-Agent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
  118. ]
  119. ]);
  120. $status = $response->getStatusCode();
  121. } catch (\Exception $e) {
  122. return $this->error('无法连接远程目标服务器');
  123. }
  124. if ($status == 200) {
  125. $body = $response->getBody()->getContents();
  126. $dom = new Dom();
  127. $dom->loadStr($body);
  128. $title = $dom->find('title');
  129. if (count($title) > 0) {
  130. $title = $title->innerText;
  131. }
  132. try {
  133. $list = $dom->find('[rel="icon"]');
  134. if (count($list) == 0) {
  135. $list = $dom->find('[rel="shortcut icon"]');
  136. }
  137. if (count($list) == 0) {
  138. $list = $dom->find('[rel="Shortcut Icon"]');
  139. }
  140. if (count($list) > 0) {
  141. $href = $list->href;
  142. if ($this->hasOnlyPath($href)) {
  143. if ($href[0]!='/') {
  144. $href = "/" . $href;
  145. }
  146. $href = $realUrl . $href;
  147. }
  148. $href = $this->addHttpProtocol($href);
  149. $icon = $href;
  150. $response = \Axios::http()->get($icon, [
  151. 'headers' => [
  152. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  153. ]
  154. ]);
  155. $contentType = $response->getHeader('content-type');
  156. $contentType = $contentType[0];
  157. if (preg_match('/(png|jpg|jpeg|x-icon|svg\+xml)$/', $contentType, $matches)) {
  158. $contentType = array(
  159. 'png' => 'png',
  160. 'jpg' => 'jpg',
  161. 'jpeg' => 'jpeg',
  162. 'x-icon' => 'ico',
  163. 'svg+xml' => 'svg',
  164. );
  165. $fileFormat = $matches[1];
  166. $icon = $this->downloadFile($icon, md5($realUrl) . '.' . $contentType[$fileFormat]);
  167. if ($icon) {
  168. $icon = $cdn . $icon;
  169. }
  170. } else {
  171. $icon = '';
  172. }
  173. }
  174. } catch (\ErrorException $e) {
  175. }
  176. }
  177. if (strlen($icon) == 0) {
  178. try {
  179. $client = \Axios::http();
  180. $response = $client->get($realUrl . '/favicon.ico');
  181. $status = $response->getStatusCode();
  182. if ($status == 200) {
  183. $icon = $realUrl . '/favicon.ico';
  184. $icon = $this->downloadFile($icon, md5($realUrl) . '.ico');
  185. if ($icon) {
  186. $icon = $cdn . $icon;
  187. }
  188. }
  189. } catch (\Exception $e) {
  190. }
  191. }
  192. if (strlen($icon) > 0) {
  193. return $this->success(['src' => $icon, 'name' => $title]);
  194. }
  195. }
  196. return $this->error('没有抓取到图标');
  197. }
  198. private function downloadFile($url, $name)
  199. {
  200. $client = \Axios::http();
  201. $path = '/images/' . date('Y/m/d/');
  202. $remotePath = public_path() . $path;
  203. $downloadPath = $remotePath . $name;
  204. if (!is_dir($remotePath)) {
  205. mkdir($remotePath, 0755, true);
  206. }
  207. try {
  208. $response = $client->request('GET', $url, [
  209. 'sink' => $downloadPath,
  210. 'headers' => [
  211. 'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
  212. ]
  213. ]);
  214. return $path . $name;
  215. } catch (RequestException $e) {
  216. }
  217. return false;
  218. }
  219. function renderIco(): \think\Response
  220. {
  221. $send = $this->request->get('seed');
  222. $client = new Client();
  223. $remote_avatar = $this->Setting('remote_avatar', 'https://avatar.mtab.cc/6.x/bottts/png?seed=', true);
  224. $response = $client->get($remote_avatar . urlencode($send), [
  225. 'stream' => true,
  226. 'timeout' => 10,
  227. ]);
  228. return response($response->getBody(), 200, ['Content-Type' => 'image/png']);
  229. }
  230. function upload(): \think\response\Json
  231. {
  232. $file = $this->request->file('file');
  233. if (empty($file)) {
  234. return $this->error('not File');
  235. }
  236. if ($file->getSize() > 1024 * 1024 * 5) {
  237. return $this->error('文件最大5MB');
  238. }
  239. if (in_array(strtolower($file->getOriginalExtension()), ['png', 'jpg', 'jpeg', 'webp', 'ico', 'svg'])) {
  240. // 验证文件并保存
  241. try {
  242. // 构建保存路径
  243. $savePath = '/images/' . date('Y/m/d');
  244. $hash = Str::random(32);
  245. $fileName = $hash . '.' . $file->getOriginalExtension();
  246. $filePath = Filesystem::disk('images')->putFileAs($savePath, $file, $fileName);
  247. $cdn = $this->Setting('assets_host', '/', true);
  248. return $this->success(['url' => $cdn . $filePath]);
  249. } catch (\think\exception\ValidateException $e) {
  250. // 验证失败,给出错误提示
  251. // ...
  252. }
  253. }
  254. return $this->error('上传失败');
  255. }
  256. function AdminUpload(): \think\response\Json
  257. {
  258. $this->getAdmin();
  259. $file = $this->request->file('file');
  260. if (empty($file)) {
  261. return $this->error('not File');
  262. }
  263. if ($file->getSize() > 1024 * 1024 * 5) {
  264. return $this->error('max fileSize is 5M');
  265. }
  266. // 验证文件并保存
  267. try {
  268. // 构建保存路径
  269. $savePath = '/images/' . date('Y/m/d');
  270. $hash = Str::random(32);
  271. $fileName = $hash . '.' . $file->getOriginalExtension();
  272. $filePath = Filesystem::disk('images')->putFileAs($savePath, $file, $fileName);
  273. $cdn = $this->Setting('assets_host', '/', true);
  274. return $this->success(['url' => $cdn . $filePath]);
  275. } catch (\think\exception\ValidateException $e) {
  276. // 验证失败,给出错误提示
  277. // ...
  278. }
  279. return $this->error('上传失败');
  280. }
  281. function refresh(): \think\response\Json
  282. {
  283. $user = $this->getUser();
  284. if ($user) {
  285. $data = [];
  286. $data['link_update_time'] = LinkModel::where("user_id", $user['user_id'])->value("update_time");
  287. return $this->success("ok", $data);
  288. }
  289. return $this->error("not login");
  290. }
  291. }