Api.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. <?php
  2. namespace app\controller;
  3. use app\BaseController;
  4. use app\model\FileModel;
  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\facade\View;
  13. use think\helper\Str;
  14. class Api extends BaseController
  15. {
  16. public function site(): \think\response\Json
  17. {
  18. return $this->success("ok", [
  19. 'email' => $this->systemSetting('email', ''),
  20. 'qqGroup' => $this->systemSetting("qqGroup", ''),
  21. 'beianMps' => $this->systemSetting("beianMps", ''),
  22. 'copyright' => $this->systemSetting("copyright", ''),
  23. "recordNumber" => $this->systemSetting("recordNumber", ''),
  24. "mobileRecordNumber" => $this->systemSetting('mobileRecordNumber', '0'),
  25. "auth" => $this->auth,
  26. "logo" => $this->systemSetting('logo', ''),
  27. "qq_login" => $this->systemSetting('qq_login', '0'),
  28. "loginCloseRecordNumber" => $this->systemSetting('loginCloseRecordNumber', '0'),
  29. "is_push_link_store" => $this->auth ? $this->systemSetting('is_push_link_store', '0') : '0',
  30. "is_push_link_store_tips" => $this->systemSetting('is_push_link_store_tips', '0'),
  31. "is_push_link_status" => $this->systemSetting("is_push_link_status", '0'),
  32. 'google_ext_link' => $this->systemSetting("google_ext_link", ''),
  33. 'edge_ext_link' => $this->systemSetting("edge_ext_link", ''),
  34. 'local_ext_link' => $this->systemSetting("local_ext_link", ''),
  35. "customAbout" => $this->systemSetting("customAbout", '')
  36. ]);
  37. }
  38. public function background(): \think\response\File
  39. {
  40. return download('static/background.jpeg', 'background.jpeg')->mimeType(\PluginStaticSystem::mimeType('static/background.jpeg'))->force(false)->expire(60 * 60 * 24 * 3);
  41. }
  42. //获取默认壁纸
  43. function DefBg(): \think\response\Json
  44. {
  45. $config = $this->systemSetting('defaultTab', 'static/defaultTab.json', true);
  46. if ($config) {
  47. $fp = public_path() . $config;
  48. if (file_exists($fp)) {
  49. $file = file_get_contents($fp);
  50. $json = json_decode($file, true);
  51. if (isset($json['config']['theme']['backgroundImage'])) {
  52. $bg = $json['config']['theme']['backgroundImage'];
  53. $bgMime = $json['config']['theme']['backgroundMime'] ?? 0;
  54. return $this->success("ok", ['background' => $bg, "mime" => $bgMime]);
  55. }
  56. }
  57. }
  58. return $this->success("ok", ['background' => "static/background.jpeg", "mime" => 0]);
  59. }
  60. function globalNotify(): \think\response\Json
  61. {
  62. $info = SettingModel::Config("globalNotify", false);
  63. if ($info) {
  64. return $this->success('ok', $info);
  65. }
  66. return $this->error('empty');
  67. }
  68. //获取邮件验证码
  69. function getMailCode(): \think\response\Json
  70. {
  71. $mail = $this->request->post("mail", false);
  72. $code = rand(100000, 999999);
  73. if ($mail) {
  74. if (Cache::get('code' . $mail)) {
  75. return $this->success("请勿频繁获取验证码");
  76. }
  77. $k = SettingModel::Config('smtp_code_template', false);
  78. if ($k === false || mb_strlen(trim($k)) == 0) {
  79. $k = '
  80. <div style="border:1px #DEDEDE solid;border-top:3px #009944 solid;padding:25px;background-color:#FFF;">
  81. <div style="font-size:17px;font-weight:bold;">邮箱验证码</div>
  82. <div style="font-size:14px;line-height:36px;padding-top:15px;padding-bottom:15px;">
  83. 尊敬的用户,您好!<br>
  84. 您的验证码是:<b style="color: #1e9fff">{$code}</b>。5分钟内有效,请尽快验证。
  85. </div>
  86. <div style="line-height:15px;">
  87. 此致
  88. </div>
  89. </div>
  90. ';
  91. }
  92. $html = View::display($k, ['time' => date('Y-m-d H:i:s'), 'code' => $code]);
  93. try {
  94. $status = \Mail::send($mail, $html);
  95. if ($status) {
  96. Cache::set('code' . $mail, $code, 300);
  97. return $this->success('发送成功');
  98. }
  99. } catch (\Exception $e) {
  100. return $this->error($e->getMessage());
  101. }
  102. }
  103. return $this->error('发送失败');
  104. }
  105. private function addHttpProtocolRemovePath($url): string
  106. {
  107. // 解析URL
  108. $parsedUrl = parse_url($url);
  109. // 检查是否已经有协议,如果没有则添加http://
  110. if (!isset($parsedUrl['scheme'])) {
  111. // 检查是否以 // 开头,如果是,则转换为相对协议
  112. if (isset($parsedUrl['host']) && strpos($url, '//') === 0) {
  113. $url = 'http:' . $url;
  114. } else {
  115. $url = 'http://' . $url;
  116. }
  117. } else {
  118. // 如果有协议但没有路径,保留原样
  119. $url = $parsedUrl['scheme'] . '://';
  120. // 如果有主机,则添加主机部分
  121. if (isset($parsedUrl['host'])) {
  122. $url .= $parsedUrl['host'];
  123. // 如果有端口号,则添加端口号
  124. if (isset($parsedUrl['port'])) {
  125. $url .= ':' . $parsedUrl['port'];
  126. }
  127. }
  128. }
  129. return $url;
  130. }
  131. private function addHttpProtocol($url)
  132. {
  133. // 检查是否已经有协议,如果没有则添加http://
  134. if (!parse_url($url, PHP_URL_SCHEME)) {
  135. // 检查是否以 // 开头,如果是,则转换为相对协议
  136. if (strpos($url, '//') === 0) {
  137. $url = 'https:' . $url;
  138. } else {
  139. $url = 'http://' . $url;
  140. }
  141. }
  142. return $url;
  143. }
  144. private function hasOnlyPath($url): bool
  145. {
  146. $parsedUrl = parse_url($url);
  147. // 检查是否存在路径但不存在域名和协议
  148. if (isset($parsedUrl['path']) && !isset($parsedUrl['host']) && !isset($parsedUrl['scheme'])) {
  149. return true;
  150. }
  151. return false;
  152. }
  153. function getIcon(): \think\response\Json
  154. {
  155. $avatar = $this->request->post('avatar');
  156. if ($avatar) {
  157. $remote_avatar = $this->systemSetting("remote_avatar", "https://avatar.mtab.cc/6.x/bottts/png?seed=", true);
  158. $str = $this->downloadFile($remote_avatar . $avatar, md5($avatar) . '.png');
  159. return $this->success(['src' => $str]);
  160. }
  161. $url = $this->request->post('url', false);
  162. $icon = "";
  163. $cdn = $this->systemSetting('assets_host', '');
  164. if ($url) {
  165. $realUrl = $this->addHttpProtocolRemovePath($url);
  166. $client = \Axios::http();
  167. try {
  168. $response = $client->get($realUrl, [
  169. 'headers' => [
  170. "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"
  171. ]
  172. ]);
  173. $status = $response->getStatusCode();
  174. } catch (\Exception $e) {
  175. return $this->error('无法连接远程目标服务器');
  176. }
  177. if ($status == 200) {
  178. $body = $response->getBody()->getContents();
  179. $dom = new Dom();
  180. $dom->loadStr($body);
  181. $title = $dom->find('title');
  182. if (count($title) > 0) {
  183. $title = $title->innerText;
  184. }
  185. try {
  186. $list = $dom->find('[rel="icon"]');
  187. if (count($list) == 0) {
  188. $list = $dom->find('[rel="shortcut icon"]');
  189. }
  190. if (count($list) == 0) {
  191. $list = $dom->find('[rel="Shortcut Icon"]');
  192. }
  193. if (count($list) > 0) {
  194. $href = $list->href;
  195. if ($this->hasOnlyPath($href)) {
  196. if ($href[0] != '/') {
  197. $href = "/" . $href;
  198. }
  199. $href = $realUrl . $href;
  200. }
  201. $href = $this->addHttpProtocol($href);
  202. $icon = $href;
  203. $response = \Axios::http()->get($icon, [
  204. 'headers' => [
  205. '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'
  206. ]
  207. ]);
  208. $contentType = $response->getHeader('content-type');
  209. $contentType = $contentType[0];
  210. if (preg_match('/(png|jpg|jpeg|x-icon|svg\+xml)$/', $contentType, $matches)) {
  211. $contentType = array(
  212. 'png' => 'png',
  213. 'jpg' => 'jpg',
  214. 'jpeg' => 'jpeg',
  215. 'x-icon' => 'ico',
  216. 'svg+xml' => 'svg',
  217. );
  218. $fileFormat = $matches[1];
  219. $icon = $this->downloadFile($icon, md5($realUrl) . '.' . $contentType[$fileFormat]);
  220. if ($icon) {
  221. $icon = $cdn . $icon;
  222. }
  223. } else {
  224. $icon = '';
  225. }
  226. }
  227. } catch (\ErrorException $e) {
  228. }
  229. }
  230. if (strlen($icon) == 0) {
  231. try {
  232. $client = \Axios::http();
  233. $response = $client->get($realUrl . '/favicon.ico');
  234. $status = $response->getStatusCode();
  235. if ($status == 200) {
  236. $icon = $realUrl . '/favicon.ico';
  237. $icon = $this->downloadFile($icon, md5($realUrl) . '.ico');
  238. if ($icon) {
  239. $icon = $cdn . $icon;
  240. }
  241. }
  242. } catch (\Exception $e) {
  243. }
  244. }
  245. if (strlen($icon) > 0) {
  246. return $this->success(['src' => $icon, 'name' => $title]);
  247. }
  248. }
  249. return $this->error('没有抓取到图标');
  250. }
  251. private function downloadFile($url, $name)
  252. {
  253. $user = $this->getUser();
  254. $client = \Axios::http();
  255. $path = '/images/' . date('Y/m/d/');
  256. $remotePath = public_path() . $path;
  257. $downloadPath = $remotePath . $name;
  258. if (!is_dir($remotePath)) {
  259. mkdir($remotePath, 0755, true);
  260. }
  261. try {
  262. $response = $client->request('GET', $url, [
  263. 'sink' => $downloadPath,
  264. 'headers' => [
  265. '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'
  266. ]
  267. ]);
  268. FileModel::addFile($path . $name, $user['user_id'] ?? null);
  269. return $path . $name;
  270. } catch (RequestException $e) {
  271. }
  272. return false;
  273. }
  274. function renderIco(): \think\Response
  275. {
  276. $send = $this->request->get('seed');
  277. $client = new Client();
  278. $remote_avatar = $this->systemSetting('remote_avatar', 'https://avatar.mtab.cc/6.x/bottts/png?seed=', true);
  279. $response = $client->get($remote_avatar . urlencode($send), [
  280. 'stream' => true,
  281. 'timeout' => 10,
  282. ]);
  283. return response($response->getBody(), 200, ['Content-Type' => 'image/png']);
  284. }
  285. function upload(): \think\response\Json
  286. {
  287. $user = $this->getUser();
  288. if (!$user) {
  289. if ($this->systemSetting('touristUpload') !== '1') {
  290. //如果没有开启游客上传
  291. return $this->error('管理员已关闭游客上传!请登录后使用');
  292. }
  293. }
  294. $type = $this->request->header("Up-Type", '');
  295. $file = $this->request->file('file');
  296. if (empty($file)) {
  297. return $this->error('not File');
  298. }
  299. $maxSize = (double)$this->systemSetting('upload_size', '2');
  300. if ($file->getSize() > 1024 * 1024 * $maxSize) {
  301. $limit = $maxSize < 1 ? ($maxSize * 1000) . 'KB' : ($maxSize) . 'MB';
  302. return $this->error("文件最大$limit,请压缩后再试");
  303. }
  304. if (in_array(strtolower($file->getOriginalExtension()), ['png', 'jpg', 'jpeg', 'webp', 'ico', 'svg'])) {
  305. // 验证文件并保存
  306. try {
  307. // 构建保存路径
  308. $savePath = '/images/' . date('Y/m/d');
  309. $hash = Str::random(32);
  310. $fileName = $hash . '.' . $file->getOriginalExtension();
  311. $filePath = Filesystem::disk('images')->putFileAs($savePath, $file, $fileName);
  312. $minPath = '';
  313. if ($type == 'icon' || $type == 'avatar') {
  314. $fp = joinPath(public_path(), $filePath);
  315. $image = new \ImageBack($fp);
  316. $image->resize(120, 0)->save($fp);
  317. } else if ($type == 'AdminBackground') {
  318. $minPath = joinPath($savePath, "/min_$fileName");
  319. $fp = joinPath(public_path(), $filePath);
  320. $image = new \ImageBack($fp);
  321. $image->resize(400, 0)->save(joinPath(public_path(), $minPath));
  322. FileModel::addFile($minPath, $user['user_id'] ?? null);
  323. }
  324. $cdn = $this->systemSetting('assets_host', '/', true);
  325. FileModel::addFile($filePath, $user['user_id'] ?? null);
  326. return $this->success(['url' => $cdn . $filePath, "minUrl" => joinPath($cdn, $minPath)]);
  327. } catch (\think\exception\ValidateException $e) {
  328. return $this->error($e->getMessage());
  329. // 验证失败,给出错误提示
  330. // ...
  331. }
  332. }
  333. return $this->error('上传失败');
  334. }
  335. function AdminUpload(): \think\response\Json
  336. {
  337. $user = $this->getAdmin();
  338. $file = $this->request->file('file');
  339. if (empty($file)) {
  340. return $this->error('not File');
  341. }
  342. if ($file->getSize() > 1024 * 1024 * 5) {
  343. return $this->error('max fileSize is 5M');
  344. }
  345. // 验证文件并保存
  346. try {
  347. // 构建保存路径
  348. $savePath = '/images/' . date('Y/m/d');
  349. $hash = Str::random(32);
  350. $fileName = $hash . '.' . $file->getOriginalExtension();
  351. $filePath = Filesystem::disk('images')->putFileAs($savePath, $file, $fileName);
  352. $cdn = $this->systemSetting('assets_host', '/', true);
  353. FileModel::addFile($filePath, $user['user_id'] ?? null);
  354. return $this->success(['url' => $cdn . $filePath]);
  355. } catch (\think\exception\ValidateException $e) {
  356. // 验证失败,给出错误提示
  357. // ...
  358. }
  359. return $this->error('上传失败');
  360. }
  361. function refresh(): \think\response\Json
  362. {
  363. $user = $this->getUser();
  364. if ($user) {
  365. $data = [];
  366. $data['link_update_time'] = LinkModel::where("user_id", $user['user_id'])->value("update_time");
  367. return $this->success("ok", $data);
  368. }
  369. return $this->error("not login");
  370. }
  371. }