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\Log;
  13. use think\facade\View;
  14. use think\helper\Str;
  15. class Api extends BaseController
  16. {
  17. public function site(): \think\response\Json
  18. {
  19. return $this->success("ok", [
  20. 'email' => $this->systemSetting('email', ''),
  21. 'qqGroup' => $this->systemSetting("qqGroup", ''),
  22. 'beianMps' => $this->systemSetting("beianMps", ''),
  23. 'copyright' => $this->systemSetting("copyright", ''),
  24. "recordNumber" => $this->systemSetting("recordNumber", ''),
  25. "mobileRecordNumber" => $this->systemSetting('mobileRecordNumber', '0'),
  26. "auth" => $this->auth,
  27. "logo" => $this->systemSetting('logo', ''),
  28. "qq_login" => $this->systemSetting('qq_login', '0'),
  29. "loginCloseRecordNumber" => $this->systemSetting('loginCloseRecordNumber', '0'),
  30. "is_push_link_store" => $this->auth ? $this->systemSetting('is_push_link_store', '0') : '0',
  31. "is_push_link_store_tips" => $this->systemSetting('is_push_link_store_tips', '0'),
  32. "is_push_link_status" => $this->systemSetting("is_push_link_status", '0'),
  33. 'google_ext_link' => $this->systemSetting("google_ext_link", ''),
  34. 'edge_ext_link' => $this->systemSetting("edge_ext_link", ''),
  35. 'local_ext_link' => $this->systemSetting("local_ext_link", ''),
  36. "customAbout" => $this->systemSetting("customAbout", ''),
  37. "user_register" => $this->systemSetting("user_register", '0', true)
  38. ]);
  39. }
  40. public function background(): \think\response\File
  41. {
  42. return download('static/background.jpeg', 'background.jpeg')->mimeType(\PluginStaticSystem::mimeType('static/background.jpeg'))->force(false)->expire(60 * 60 * 24 * 3);
  43. }
  44. //获取默认壁纸
  45. function DefBg(): \think\response\Json
  46. {
  47. $config = $this->systemSetting('defaultTab', 'static/defaultTab.json', true);
  48. if ($config) {
  49. $fp = public_path() . $config;
  50. if (file_exists($fp)) {
  51. $file = file_get_contents($fp);
  52. $json = json_decode($file, true);
  53. if (isset($json['config']['theme']['backgroundImage'])) {
  54. $bg = $json['config']['theme']['backgroundImage'];
  55. $bgMime = $json['config']['theme']['backgroundMime'] ?? 0;
  56. return $this->success("ok", ['background' => $bg, "mime" => $bgMime]);
  57. }
  58. }
  59. }
  60. return $this->success("ok", ['background' => "static/background.jpeg", "mime" => 0]);
  61. }
  62. function globalNotify(): \think\response\Json
  63. {
  64. $info = SettingModel::Config("globalNotify", false);
  65. if ($info) {
  66. return $this->success('ok', $info);
  67. }
  68. return $this->error('empty');
  69. }
  70. //获取邮件验证码
  71. function getMailCode(): \think\response\Json
  72. {
  73. $mail = $this->request->post("mail", false);
  74. $code = rand(100000, 999999);
  75. if ($mail) {
  76. if (Cache::get('code' . $mail)) {
  77. return $this->success("请勿频繁获取验证码");
  78. }
  79. $k = SettingModel::Config('smtp_code_template', false);
  80. if ($k === false || mb_strlen(trim($k)) == 0) {
  81. $k = '
  82. <div style="border:1px #DEDEDE solid;border-top:3px #009944 solid;padding:25px;background-color:#FFF;">
  83. <div style="font-size:17px;font-weight:bold;">邮箱验证码</div>
  84. <div style="font-size:14px;line-height:36px;padding-top:15px;padding-bottom:15px;">
  85. 尊敬的用户,您好!<br>
  86. 您的验证码是:<b style="color: #1e9fff">{$code}</b>。5分钟内有效,请尽快验证。
  87. </div>
  88. <div style="line-height:15px;">
  89. 此致
  90. </div>
  91. </div>
  92. ';
  93. }
  94. $html = View::display($k, ['time' => date('Y-m-d H:i:s'), 'code' => $code]);
  95. try {
  96. $status = \Mail::send($mail, $html);
  97. if ($status) {
  98. Cache::set('code' . $mail, $code, 300);
  99. return $this->success('发送成功');
  100. }
  101. } catch (\Exception $e) {
  102. return $this->error($e->getMessage());
  103. }
  104. }
  105. return $this->error('发送失败');
  106. }
  107. private function addHttpProtocolRemovePath($url): string
  108. {
  109. // 解析URL
  110. $parsedUrl = parse_url($url);
  111. // 检查是否已经有协议,如果没有则添加http://
  112. if (!isset($parsedUrl['scheme'])) {
  113. // 检查是否以 // 开头,如果是,则转换为相对协议
  114. if (isset($parsedUrl['host']) && strpos($url, '//') === 0) {
  115. $url = 'http:' . $url;
  116. } else {
  117. $url = 'http://' . $url;
  118. }
  119. } else {
  120. // 如果有协议但没有路径,保留原样
  121. $url = $parsedUrl['scheme'] . '://';
  122. // 如果有主机,则添加主机部分
  123. if (isset($parsedUrl['host'])) {
  124. $url .= $parsedUrl['host'];
  125. // 如果有端口号,则添加端口号
  126. if (isset($parsedUrl['port'])) {
  127. $url .= ':' . $parsedUrl['port'];
  128. }
  129. }
  130. }
  131. return $url;
  132. }
  133. private function addHttpProtocol($url)
  134. {
  135. // 检查是否已经有协议,如果没有则添加http://
  136. if (!parse_url($url, PHP_URL_SCHEME)) {
  137. // 检查是否以 // 开头,如果是,则转换为相对协议
  138. if (strpos($url, '//') === 0) {
  139. $url = 'https:' . $url;
  140. } else {
  141. $url = 'http://' . $url;
  142. }
  143. }
  144. return $url;
  145. }
  146. private function hasOnlyPath($url): bool
  147. {
  148. if(!$url){
  149. return false;
  150. }
  151. $parsedUrl = parse_url($url);
  152. // 检查是否存在路径但不存在域名和协议
  153. if (isset($parsedUrl['path']) && !isset($parsedUrl['host']) && !isset($parsedUrl['scheme'])) {
  154. return true;
  155. }
  156. return false;
  157. }
  158. function getIcon(): \think\response\Json
  159. {
  160. $avatar = $this->request->post('avatar');
  161. if ($avatar) {
  162. $remote_avatar = $this->systemSetting("remote_avatar", "https://avatar.mtab.cc/6.x/icons/png?seed=", true);
  163. $str = $this->downloadFile($remote_avatar . $avatar, md5($avatar) . '.png');
  164. return $this->success(['src' => $str]);
  165. }
  166. $url = $this->request->post('url', false);
  167. $icon = "";
  168. $cdn = $this->systemSetting('assets_host', '');
  169. $title = "";
  170. if ($url) {
  171. $realUrl = $this->addHttpProtocolRemovePath($url);
  172. $client = \Axios::http();
  173. try {
  174. $response = $client->get($realUrl, [
  175. 'headers' => [
  176. "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"
  177. ]
  178. ]);
  179. $status = $response->getStatusCode();
  180. } catch (\Exception $e) {
  181. return $this->error('无法连接远程目标服务器');
  182. }
  183. if ($status == 200) {
  184. $body = $response->getBody()->getContents();
  185. $dom = new Dom();
  186. $dom->loadStr($body);
  187. $titles = $dom->find('title');
  188. if (count($titles) > 0) {
  189. $title = $titles->innerText;
  190. }
  191. try {
  192. $list = $dom->find('[rel="icon"]');
  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/icons/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' => $response->getHeader("content-type")[0]]);
  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(144, 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. }