Ajax.php 13 KB

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