Ajax.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use app\common\exception\UploadException;
  5. use app\common\library\Upload;
  6. use app\common\service\OssService;
  7. use fast\Random;
  8. use think\addons\Service;
  9. use think\Cache;
  10. use think\Config;
  11. use think\Db;
  12. use think\Lang;
  13. use think\Loader;
  14. use think\Log;
  15. use think\Response;
  16. use think\Validate;
  17. /**
  18. * Ajax异步请求接口
  19. * @internal
  20. */
  21. class Ajax extends Backend
  22. {
  23. protected $noNeedLogin = ['lang'];
  24. protected $noNeedRight = ['*'];
  25. protected $layout = '';
  26. public function _initialize()
  27. {
  28. parent::_initialize();
  29. //设置过滤方法
  30. $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
  31. }
  32. /**
  33. * 加载语言包
  34. */
  35. public function lang()
  36. {
  37. $this->request->get(['callback' => 'define']);
  38. $header = ['Content-Type' => 'application/javascript'];
  39. if (!config('app_debug')) {
  40. $offset = 30 * 60 * 60 * 24; // 缓存一个月
  41. $header['Cache-Control'] = 'public';
  42. $header['Pragma'] = 'cache';
  43. $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
  44. }
  45. $controllername = $this->request->get('controllername');
  46. $lang = $this->request->get('lang');
  47. if (!$lang || !in_array($lang, config('allow_lang_list')) || !$controllername || !preg_match("/^[a-z0-9_\.]+$/i", $controllername)) {
  48. return jsonp(['errmsg' => '参数错误'], 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
  49. }
  50. $controllername = input("controllername");
  51. $className = Loader::parseClass($this->request->module(), 'controller', $controllername, false);
  52. //存在对应的类才加载
  53. if (class_exists($className)) {
  54. $this->loadlang($controllername);
  55. }
  56. return jsonp(Lang::get(), 200, $header, ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
  57. }
  58. /**
  59. * 上传文件
  60. */
  61. public function upload()
  62. {
  63. Config::set('default_return_type', 'json');
  64. //必须还原upload配置,否则分片及cdnurl函数计算错误
  65. Config::load(APP_PATH . 'extra/upload.php', 'upload');
  66. $chunkid = $this->request->post("chunkid");
  67. if ($chunkid) {
  68. if (!Config::get('upload.chunking')) {
  69. $this->error(__('Chunk file disabled'));
  70. }
  71. $action = $this->request->post("action");
  72. $chunkindex = $this->request->post("chunkindex/d");
  73. $chunkcount = $this->request->post("chunkcount/d");
  74. $filename = $this->request->post("filename");
  75. $method = $this->request->method(true);
  76. if ($action == 'merge') {
  77. $attachment = null;
  78. //合并分片文件
  79. try {
  80. $upload = new Upload();
  81. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  82. } catch (UploadException $e) {
  83. $this->error($e->getMessage());
  84. }
  85. $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  86. } elseif ($method == 'clean') {
  87. //删除冗余的分片文件
  88. try {
  89. $upload = new Upload();
  90. $upload->clean($chunkid);
  91. } catch (UploadException $e) {
  92. $this->error($e->getMessage());
  93. }
  94. $this->success();
  95. } else {
  96. //上传分片文件
  97. //默认普通上传文件
  98. $file = $this->request->file('file');
  99. try {
  100. $upload = new Upload($file);
  101. $upload->chunk($chunkid, $chunkindex, $chunkcount);
  102. } catch (UploadException $e) {
  103. $this->error($e->getMessage());
  104. }
  105. $this->success();
  106. }
  107. } else {
  108. $attachment = null;
  109. //默认普通上传文件
  110. $file = $this->request->file('file');
  111. try {
  112. $upload = new Upload($file);
  113. $attachment = $upload->upload();
  114. } catch (UploadException $e) {
  115. $this->error($e->getMessage());
  116. }
  117. $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  118. }
  119. }
  120. /**
  121. * 上传文件Oss
  122. */
  123. public function uploads()
  124. {
  125. Config::set('default_return_type', 'json');
  126. //必须还原upload配置,否则分片及cdnurl函数计算错误
  127. Config::load(APP_PATH . 'extra/upload.php', 'upload');
  128. $ossService = OssService::instance();
  129. $chunkid = $this->request->post("chunkid");
  130. if ($chunkid) {
  131. if (!Config::get('upload.chunking')) {
  132. $this->error(__('Chunk file disabled'));
  133. }
  134. $action = $this->request->post("action");
  135. $chunkindex = $this->request->post("chunkindex/d");
  136. $chunkcount = $this->request->post("chunkcount/d");
  137. $filename = $this->request->post("filename");
  138. $method = $this->request->method(true);
  139. if ($action == 'merge') {
  140. $attachment = null;
  141. //合并分片文件
  142. try {
  143. $upload = new Upload();
  144. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  145. } catch (UploadException $e) {
  146. $this->error($e->getMessage());
  147. }
  148. // 上传到OSS
  149. $objectUrl = 'uploads/' . date('Ymd/') . Random::alnum(16) . '/' . $attachment->filename;
  150. $this->uploadToOss($attachment, $ossService, $objectUrl);
  151. $this->success(__('Uploaded successful'), '', ['url' => cdnurl('/' . $objectUrl), 'fullurl' => cdnurl('/' . $objectUrl)]);
  152. } elseif ($method == 'clean') {
  153. //删除冗余的分片文件
  154. try {
  155. $upload = new Upload();
  156. $upload->clean($chunkid);
  157. } catch (UploadException $e) {
  158. $this->error($e->getMessage());
  159. }
  160. $this->success();
  161. } else {
  162. //上传分片文件
  163. //默认普通上传文件
  164. $file = $this->request->file('file');
  165. try {
  166. $upload = new Upload($file);
  167. $upload->chunk($chunkid, $chunkindex, $chunkcount);
  168. } catch (UploadException $e) {
  169. $this->error($e->getMessage());
  170. }
  171. $this->success();
  172. }
  173. } else {
  174. $attachment = null;
  175. //默认普通上传文件
  176. $file = $this->request->file('file');
  177. try {
  178. $upload = new Upload($file);
  179. $attachment = $upload->upload();
  180. } catch (UploadException $e) {
  181. $this->error($e->getMessage());
  182. }
  183. // 上传到OSS
  184. $objectUrl = 'uploads/' . date('Ymd/') . Random::alnum(16) . '/' . $attachment->filename;
  185. $this->uploadToOss($attachment, $ossService, $objectUrl);
  186. $this->success(__('Uploaded successful'), '', ['url' => cdnurl('/' . $objectUrl), 'fullurl' => cdnurl('/' . $objectUrl)]);
  187. }
  188. }
  189. /**
  190. * 通用排序
  191. */
  192. public function weigh()
  193. {
  194. //排序的数组
  195. $ids = $this->request->post("ids");
  196. //拖动的记录ID
  197. $changeid = $this->request->post("changeid");
  198. //操作字段
  199. $field = $this->request->post("field");
  200. //操作的数据表
  201. $table = $this->request->post("table");
  202. if (!Validate::is($table, "alphaDash")) {
  203. $this->error();
  204. }
  205. //主键
  206. $pk = $this->request->post("pk");
  207. //排序的方式
  208. $orderway = strtolower($this->request->post("orderway", ""));
  209. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  210. $sour = $weighdata = [];
  211. $ids = explode(',', $ids);
  212. $prikey = $pk && preg_match("/^[a-z0-9\-_]+$/i", $pk) ? $pk : (Db::name($table)->getPk() ?: 'id');
  213. $pid = $this->request->post("pid", "");
  214. //限制更新的字段
  215. $field = in_array($field, ['weigh']) ? $field : 'weigh';
  216. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  217. if ($pid !== '') {
  218. $hasids = [];
  219. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
  220. foreach ($list as $k => $v) {
  221. $hasids[] = $v[$prikey];
  222. }
  223. $ids = array_values(array_intersect($ids, $hasids));
  224. }
  225. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  226. foreach ($list as $k => $v) {
  227. $sour[] = $v[$prikey];
  228. $weighdata[$v[$prikey]] = $v[$field];
  229. }
  230. $position = array_search($changeid, $ids);
  231. $desc_id = isset($sour[$position]) ? $sour[$position] : end($sour); //移动到目标的ID值,取出所处改变前位置的值
  232. $sour_id = $changeid;
  233. $weighids = array();
  234. $temp = array_values(array_diff_assoc($ids, $sour));
  235. foreach ($temp as $m => $n) {
  236. if ($n == $sour_id) {
  237. $offset = $desc_id;
  238. } else {
  239. if ($sour_id == $temp[0]) {
  240. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  241. } else {
  242. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  243. }
  244. }
  245. if (!isset($weighdata[$offset])) {
  246. continue;
  247. }
  248. $weighids[$n] = $weighdata[$offset];
  249. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  250. }
  251. $this->success();
  252. }
  253. /**
  254. * 清空系统缓存
  255. */
  256. public function wipecache()
  257. {
  258. try {
  259. $type = $this->request->request("type");
  260. switch ($type) {
  261. case 'all':
  262. // no break
  263. case 'content':
  264. //内容缓存
  265. rmdirs(CACHE_PATH, false);
  266. Cache::clear();
  267. if ($type == 'content') {
  268. break;
  269. }
  270. case 'template':
  271. // 模板缓存
  272. rmdirs(TEMP_PATH, false);
  273. if ($type == 'template') {
  274. break;
  275. }
  276. case 'addons':
  277. // 插件缓存
  278. Service::refresh();
  279. if ($type == 'addons') {
  280. break;
  281. }
  282. case 'browser':
  283. // 浏览器缓存
  284. // 只有生产环境下才修改
  285. if (!config('app_debug')) {
  286. $version = config('site.version');
  287. $newversion = preg_replace_callback("/(.*)\.([0-9]+)\$/", function ($match) {
  288. return $match[1] . '.' . ($match[2] + 1);
  289. }, $version);
  290. if ($newversion && $newversion != $version) {
  291. Db::startTrans();
  292. try {
  293. \app\common\model\Config::where('name', 'version')->update(['value' => $newversion]);
  294. \app\common\model\Config::refreshFile();
  295. Db::commit();
  296. } catch (\Exception $e) {
  297. Db::rollback();
  298. exception($e->getMessage());
  299. }
  300. }
  301. }
  302. if ($type == 'browser') {
  303. break;
  304. }
  305. }
  306. } catch (\Exception $e) {
  307. $this->error($e->getMessage());
  308. }
  309. \think\Hook::listen("wipecache_after");
  310. $this->success();
  311. }
  312. /**
  313. * 读取分类数据,联动列表
  314. */
  315. public function category()
  316. {
  317. $type = $this->request->get('type', '');
  318. $pid = $this->request->get('pid', '');
  319. $where = ['status' => 'normal'];
  320. $categorylist = null;
  321. if ($pid || $pid === '0') {
  322. $where['pid'] = $pid;
  323. }
  324. if ($type) {
  325. $where['type'] = $type;
  326. }
  327. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  328. $this->success('', '', $categorylist);
  329. }
  330. /**
  331. * 读取省市区数据,联动列表
  332. */
  333. public function area()
  334. {
  335. $params = $this->request->get("row/a");
  336. if (!empty($params)) {
  337. $province = isset($params['province']) ? $params['province'] : null;
  338. $city = isset($params['city']) ? $params['city'] : null;
  339. } else {
  340. $province = $this->request->get('province');
  341. $city = $this->request->get('city');
  342. }
  343. $where = ['pid' => 0, 'level' => 1];
  344. $provincelist = null;
  345. if ($province !== null) {
  346. $where['pid'] = $province;
  347. $where['level'] = 2;
  348. if ($city !== null) {
  349. $where['pid'] = $city;
  350. $where['level'] = 3;
  351. }
  352. }
  353. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  354. $this->success('', '', $provincelist);
  355. }
  356. /**
  357. * 生成后缀图标
  358. */
  359. public function icon()
  360. {
  361. $suffix = $this->request->request("suffix");
  362. $suffix = $suffix ? $suffix : "FILE";
  363. $data = build_suffix_image($suffix);
  364. $header = ['Content-Type' => 'image/svg+xml'];
  365. $offset = 30 * 60 * 60 * 24; // 缓存一个月
  366. $header['Cache-Control'] = 'public';
  367. $header['Pragma'] = 'cache';
  368. $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
  369. $response = Response::create($data, '', 200, $header);
  370. return $response;
  371. }
  372. /**
  373. * @param $attachment
  374. * @param OssService $ossService
  375. * @return string
  376. * @throws
  377. */
  378. protected function uploadToOss($attachment, OssService $ossService, $objectUrl): string
  379. {
  380. $filePath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url);
  381. $url = $ossService->uploadFile($filePath, $objectUrl);
  382. @unlink($filePath);
  383. return $url;
  384. }
  385. }