Ajax.php 12 KB

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