Ajax.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 OSS\OssClient;
  15. /**
  16. * Ajax异步请求接口
  17. * @internal
  18. */
  19. class Ajax extends Backend
  20. {
  21. protected $noNeedLogin = ['lang'];
  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. Config::set('default_return_type', 'json');
  54. //必须设定cdnurl为空,否则cdnurl函数计算错误
  55. Config::set('upload.cdnurl', '');
  56. $chunkid = $this->request->post("chunkid");
  57. if ($chunkid) {
  58. if (!Config::get('upload.chunking')) {
  59. $this->error(__('Chunk file disabled'));
  60. }
  61. $action = $this->request->post("action");
  62. $chunkindex = $this->request->post("chunkindex/d");
  63. $chunkcount = $this->request->post("chunkcount/d");
  64. $filename = $this->request->post("filename");
  65. $method = $this->request->method(true);
  66. if ($action == 'merge') {
  67. $attachment = null;
  68. //合并分片文件
  69. try {
  70. $upload = new Upload();
  71. $attachment = $upload->merge($chunkid, $chunkcount, $filename);
  72. } catch (UploadException $e) {
  73. $this->error($e->getMessage());
  74. }
  75. $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  76. } elseif ($method == 'clean') {
  77. //删除冗余的分片文件
  78. try {
  79. $upload = new Upload();
  80. $upload->clean($chunkid);
  81. } catch (UploadException $e) {
  82. $this->error($e->getMessage());
  83. }
  84. $this->success();
  85. } else {
  86. //上传分片文件
  87. //默认普通上传文件
  88. $file = $this->request->file('file');
  89. try {
  90. $upload = new Upload($file);
  91. $upload->chunk($chunkid, $chunkindex, $chunkcount);
  92. } catch (UploadException $e) {
  93. $this->error($e->getMessage());
  94. }
  95. $this->success();
  96. }
  97. } else {
  98. $attachment = null;
  99. //默认普通上传文件
  100. $file = $this->request->file('file');
  101. $type = $this->request->param('category');
  102. if ($type == 'oss') {
  103. $filename = $file->getInfo();
  104. $config = [
  105. 'KeyId' => \think\Env::get('oss.key_id'),
  106. 'KeySecret' => \think\Env::get('oss.key_secret'),
  107. 'Endpoint' => \think\Env::get('oss.endpoint'),
  108. 'Bucket' => \think\Env::get('oss.bucket'),
  109. 'Directory' => \think\Env::get('oss.directory'),
  110. ];
  111. //获取oss实例
  112. $ossClient = new OssClient($config['KeyId'],$config['KeySecret'],$config['Endpoint']);
  113. $bucket = $config['Bucket']; //创建的项目
  114. $object = $config['Directory'] . '/' . $filename['name'] . uniqid(Random::alnum(12)); //文件名
  115. $res = $ossClient->uploadFile($bucket,$object,$file->getRealPath());
  116. $url = str_replace("http://", "https://", $res['info']['url']);
  117. $this->success(__('Uploaded successful'), '', ['url' => $url, 'fullurl' => $url]);
  118. }elseif($type == 'export'){
  119. try {
  120. $upload = new Upload($file);
  121. $attachment = $upload->upload();
  122. } catch (UploadException $e) {
  123. $this->error($e->getMessage());
  124. }
  125. $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
  126. }else{
  127. try {
  128. $upload = new Upload($file);
  129. $attachment = $upload->upload();
  130. } catch (UploadException $e) {
  131. $this->error($e->getMessage());
  132. }
  133. $this->success(__('Uploaded successful'), '', ['url' => cdnurl($attachment->url, true), 'fullurl' => cdnurl($attachment->url, true)]);
  134. }
  135. }
  136. }
  137. /**
  138. * 通用排序
  139. */
  140. public function weigh()
  141. {
  142. //排序的数组
  143. $ids = $this->request->post("ids");
  144. //拖动的记录ID
  145. $changeid = $this->request->post("changeid");
  146. //操作字段
  147. $field = $this->request->post("field");
  148. //操作的数据表
  149. $table = $this->request->post("table");
  150. if (!Validate::is($table, "alphaDash")) {
  151. $this->error();
  152. }
  153. //主键
  154. $pk = $this->request->post("pk");
  155. //排序的方式
  156. $orderway = strtolower($this->request->post("orderway", ""));
  157. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  158. $sour = $weighdata = [];
  159. $ids = explode(',', $ids);
  160. $prikey = $pk && preg_match("/^[a-z0-9\-_]+$/i", $pk) ? $pk : (Db::name($table)->getPk() ?: 'id');
  161. $pid = $this->request->post("pid", "");
  162. //限制更新的字段
  163. $field = in_array($field, ['weigh']) ? $field : 'weigh';
  164. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  165. if ($pid !== '') {
  166. $hasids = [];
  167. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
  168. foreach ($list as $k => $v) {
  169. $hasids[] = $v[$prikey];
  170. }
  171. $ids = array_values(array_intersect($ids, $hasids));
  172. }
  173. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  174. foreach ($list as $k => $v) {
  175. $sour[] = $v[$prikey];
  176. $weighdata[$v[$prikey]] = $v[$field];
  177. }
  178. $position = array_search($changeid, $ids);
  179. $desc_id = isset($sour[$position]) ? $sour[$position] : end($sour); //移动到目标的ID值,取出所处改变前位置的值
  180. $sour_id = $changeid;
  181. $weighids = array();
  182. $temp = array_values(array_diff_assoc($ids, $sour));
  183. foreach ($temp as $m => $n) {
  184. if ($n == $sour_id) {
  185. $offset = $desc_id;
  186. } else {
  187. if ($sour_id == $temp[0]) {
  188. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  189. } else {
  190. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  191. }
  192. }
  193. if (!isset($weighdata[$offset])) {
  194. continue;
  195. }
  196. $weighids[$n] = $weighdata[$offset];
  197. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  198. }
  199. $this->success();
  200. }
  201. /**
  202. * 清空系统缓存
  203. */
  204. public function wipecache()
  205. {
  206. try {
  207. $type = $this->request->request("type");
  208. switch ($type) {
  209. case 'all':
  210. // no break
  211. case 'content':
  212. //内容缓存
  213. rmdirs(CACHE_PATH, false);
  214. Cache::clear();
  215. if ($type == 'content') {
  216. break;
  217. }
  218. case 'template':
  219. // 模板缓存
  220. rmdirs(TEMP_PATH, false);
  221. if ($type == 'template') {
  222. break;
  223. }
  224. case 'addons':
  225. // 插件缓存
  226. Service::refresh();
  227. if ($type == 'addons') {
  228. break;
  229. }
  230. case 'browser':
  231. // 浏览器缓存
  232. // 只有生产环境下才修改
  233. if (!config('app_debug')) {
  234. $version = config('site.version');
  235. $newversion = preg_replace_callback("/(.*)\.([0-9]+)\$/", function ($match) {
  236. return $match[1] . '.' . ($match[2] + 1);
  237. }, $version);
  238. if ($newversion && $newversion != $version) {
  239. Db::startTrans();
  240. try {
  241. \app\common\model\Config::where('name', 'version')->update(['value' => $newversion]);
  242. \app\common\model\Config::refreshFile();
  243. Db::commit();
  244. } catch (\Exception $e) {
  245. Db::rollback();
  246. exception($e->getMessage());
  247. }
  248. }
  249. }
  250. if ($type == 'browser') {
  251. break;
  252. }
  253. }
  254. } catch (\Exception $e) {
  255. $this->error($e->getMessage());
  256. }
  257. \think\Hook::listen("wipecache_after");
  258. $this->success();
  259. }
  260. /**
  261. * 读取分类数据,联动列表
  262. */
  263. public function category()
  264. {
  265. $type = $this->request->get('type', '');
  266. $pid = $this->request->get('pid', '');
  267. $where = ['status' => 'normal'];
  268. $categorylist = null;
  269. if ($pid || $pid === '0') {
  270. $where['pid'] = $pid;
  271. }
  272. if ($type) {
  273. $where['type'] = $type;
  274. }
  275. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  276. $this->success('', '', $categorylist);
  277. }
  278. /**
  279. * 读取省市区数据,联动列表
  280. */
  281. public function area()
  282. {
  283. $params = $this->request->get("row/a");
  284. if (!empty($params)) {
  285. $province = isset($params['province']) ? $params['province'] : null;
  286. $city = isset($params['city']) ? $params['city'] : null;
  287. } else {
  288. $province = $this->request->get('province');
  289. $city = $this->request->get('city');
  290. }
  291. $where = ['parent_id' => 0, 'level' => 1];
  292. $provincelist = null;
  293. if ($province !== null) {
  294. $where['parent_id'] = $province;
  295. $where['level'] = 2;
  296. if ($city !== null) {
  297. $where['parent_id'] = $city;
  298. $where['level'] = 3;
  299. }
  300. }
  301. //dump($where);die;
  302. $provincelist = Db::name('region')->where($where)->field('id as value,name')->select();
  303. $this->success('', '', $provincelist);
  304. }
  305. /**
  306. * 生成后缀图标
  307. */
  308. public function icon()
  309. {
  310. $suffix = $this->request->request("suffix");
  311. $suffix = $suffix ? $suffix : "FILE";
  312. $data = build_suffix_image($suffix);
  313. $header = ['Content-Type' => 'image/svg+xml'];
  314. $offset = 30 * 60 * 60 * 24; // 缓存一个月
  315. $header['Cache-Control'] = 'public';
  316. $header['Pragma'] = 'cache';
  317. $header['Expires'] = gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
  318. $response = Response::create($data, '', 200, $header);
  319. return $response;
  320. }
  321. }