Ajax.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use fast\Random;
  5. use think\Cache;
  6. use think\Config;
  7. use think\Db;
  8. use think\Lang;
  9. /**
  10. * Ajax异步请求接口
  11. * @internal
  12. */
  13. class Ajax extends Backend
  14. {
  15. protected $noNeedLogin = ['lang'];
  16. protected $noNeedRight = ['*'];
  17. protected $layout = '';
  18. public function _initialize()
  19. {
  20. parent::_initialize();
  21. //设置过滤方法
  22. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  23. }
  24. /**
  25. * 加载语言包
  26. */
  27. public function lang()
  28. {
  29. header('Content-Type: application/javascript');
  30. $controllername = input("controllername");
  31. //默认只加载了控制器对应的语言名,你还根据控制器名来加载额外的语言包
  32. $this->loadlang($controllername);
  33. return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
  34. }
  35. /**
  36. * 上传文件
  37. */
  38. public function upload()
  39. {
  40. Config::set('default_return_type', 'json');
  41. $file = $this->request->file('file');
  42. if (empty($file))
  43. {
  44. $this->error(__('No file upload or server upload limit exceeded'));
  45. }
  46. //判断是否已经存在附件
  47. $sha1 = $file->hash();
  48. $upload = Config::get('upload');
  49. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  50. $type = strtolower($matches[2]);
  51. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  52. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  53. $fileInfo = $file->getInfo();
  54. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  55. $suffix = $suffix ? $suffix : 'file';
  56. $mimetypeArr = explode(',', $upload['mimetype']);
  57. $typeArr = explode('/', $fileInfo['type']);
  58. //验证文件后缀
  59. if ($upload['mimetype'] !== '*' && !in_array($suffix, $mimetypeArr) && !in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr))
  60. {
  61. $this->error(__('Uploaded file format is limited'));
  62. }
  63. $replaceArr = [
  64. '{year}' => date("Y"),
  65. '{mon}' => date("m"),
  66. '{day}' => date("d"),
  67. '{hour}' => date("H"),
  68. '{min}' => date("i"),
  69. '{sec}' => date("s"),
  70. '{random}' => Random::alnum(16),
  71. '{random32}' => Random::alnum(32),
  72. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  73. '{suffix}' => $suffix,
  74. '{.suffix}' => $suffix ? '.' . $suffix : '',
  75. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  76. ];
  77. $savekey = $upload['savekey'];
  78. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  79. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  80. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  81. //
  82. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  83. if ($splInfo)
  84. {
  85. $imagewidth = $imageheight = 0;
  86. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  87. {
  88. $imgInfo = getimagesize($splInfo->getPathname());
  89. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  90. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  91. $url = $upload['cdnurl'] . $uploadDir . $splInfo->getSaveName();
  92. }else{
  93. $url = $uploadDir . $splInfo->getSaveName();
  94. }
  95. $params = array(
  96. 'filesize' => $fileInfo['size'],
  97. 'imagewidth' => $imagewidth,
  98. 'imageheight' => $imageheight,
  99. 'imagetype' => $suffix,
  100. 'imageframes' => 0,
  101. 'mimetype' => $fileInfo['type'],
  102. 'url' => $url,
  103. 'uploadtime' => time(),
  104. 'storage' => 'local',
  105. 'sha1' => $sha1,
  106. );
  107. $attachment = model("attachment");
  108. $attachment->data(array_filter($params));
  109. $attachment->save();
  110. \think\Hook::listen("upload_after", $attachment);
  111. $this->success(__('Upload successful'), null, [
  112. 'url' => $url
  113. ]);
  114. }
  115. else
  116. {
  117. // 上传失败获取错误信息
  118. $this->error($file->getError());
  119. }
  120. }
  121. /**
  122. * 上传文件
  123. */
  124. public function miniUpload()
  125. {
  126. Config::set('default_return_type', 'json');
  127. $file = $this->request->file('file');
  128. if (empty($file))
  129. {
  130. $this->error(__('No file upload or server upload limit exceeded'));
  131. }
  132. //判断是否已经存在附件
  133. $sha1 = $file->hash();
  134. $upload = Config::get('upload');
  135. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  136. $type = strtolower($matches[2]);
  137. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  138. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  139. $fileInfo = $file->getInfo();
  140. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  141. $suffix = $suffix ? $suffix : 'file';
  142. $mimetypeArr = explode(',', $upload['mimetype']);
  143. $typeArr = explode('/', $fileInfo['type']);
  144. //验证文件后缀
  145. if ($upload['mimetype'] !== '*' && !in_array($suffix, $mimetypeArr) && !in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr))
  146. {
  147. $this->error(__('Uploaded file format is limited'));
  148. }
  149. $replaceArr = [
  150. '{year}' => date("Y"),
  151. '{mon}' => date("m"),
  152. '{day}' => date("d"),
  153. '{hour}' => date("H"),
  154. '{min}' => date("i"),
  155. '{sec}' => date("s"),
  156. '{random}' => Random::alnum(16),
  157. '{random32}' => Random::alnum(32),
  158. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  159. '{suffix}' => $suffix,
  160. '{.suffix}' => $suffix ? '.' . $suffix : '',
  161. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  162. ];
  163. $savekey = $upload['savekey'];
  164. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  165. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  166. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  167. //
  168. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  169. if ($splInfo)
  170. {
  171. $imagewidth = $imageheight = 0;
  172. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  173. {
  174. $imgInfo = getimagesize($splInfo->getPathname());
  175. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  176. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  177. $url = $upload['cdnurl'] . $uploadDir . $splInfo->getSaveName();
  178. }else{
  179. $url = $uploadDir . $splInfo->getSaveName();
  180. }
  181. if ($imagewidth != 1080 || $imageheight !=864){
  182. $this->error('上传图片的尺寸必须是 1080*864');
  183. }
  184. $params = array(
  185. 'filesize' => $fileInfo['size'],
  186. 'imagewidth' => $imagewidth,
  187. 'imageheight' => $imageheight,
  188. 'imagetype' => $suffix,
  189. 'imageframes' => 0,
  190. 'mimetype' => $fileInfo['type'],
  191. 'url' => $url,
  192. 'uploadtime' => time(),
  193. 'storage' => 'local',
  194. 'sha1' => $sha1,
  195. );
  196. $attachment = model("attachment");
  197. $attachment->data(array_filter($params));
  198. $attachment->save();
  199. \think\Hook::listen("upload_after", $attachment);
  200. $this->success(__('Upload successful'), null, [
  201. 'url' => $url
  202. ]);
  203. }
  204. else
  205. {
  206. // 上传失败获取错误信息
  207. $this->error($file->getError());
  208. }
  209. }
  210. /**
  211. * 通用排序
  212. */
  213. public function weigh()
  214. {
  215. //排序的数组
  216. $ids = $this->request->post("ids");
  217. //拖动的记录ID
  218. $changeid = $this->request->post("changeid");
  219. //操作字段
  220. $field = $this->request->post("field");
  221. //操作的数据表
  222. $table = $this->request->post("table");
  223. //排序的方式
  224. $orderway = $this->request->post("orderway", 'strtolower');
  225. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  226. $sour = $weighdata = [];
  227. $ids = explode(',', $ids);
  228. $prikey = 'id';
  229. $pid = $this->request->post("pid");
  230. //限制更新的字段
  231. $field = in_array($field, ['weigh']) ? $field : 'weigh';
  232. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  233. if ($pid !== '')
  234. {
  235. $hasids = [];
  236. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  237. foreach ($list as $k => $v)
  238. {
  239. $hasids[] = $v['id'];
  240. }
  241. $ids = array_values(array_intersect($ids, $hasids));
  242. }
  243. //直接修复排序
  244. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  245. if ($one)
  246. {
  247. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  248. foreach ($list as $k => $v)
  249. {
  250. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  251. }
  252. $this->success();
  253. }
  254. else
  255. {
  256. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  257. foreach ($list as $k => $v)
  258. {
  259. $sour[] = $v[$prikey];
  260. $weighdata[$v[$prikey]] = $v[$field];
  261. }
  262. $position = array_search($changeid, $ids);
  263. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  264. $sour_id = $changeid;
  265. $desc_value = $weighdata[$desc_id];
  266. $sour_value = $weighdata[$sour_id];
  267. //echo "移动的ID:{$sour_id}\n";
  268. //echo "替换的ID:{$desc_id}\n";
  269. $weighids = array();
  270. $temp = array_values(array_diff_assoc($ids, $sour));
  271. foreach ($temp as $m => $n)
  272. {
  273. if ($n == $sour_id)
  274. {
  275. $offset = $desc_id;
  276. }
  277. else
  278. {
  279. if ($sour_id == $temp[0])
  280. {
  281. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  282. }
  283. else
  284. {
  285. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  286. }
  287. }
  288. $weighids[$n] = $weighdata[$offset];
  289. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  290. }
  291. $this->success();
  292. }
  293. }
  294. /**
  295. * 清空系统缓存
  296. */
  297. public function wipecache()
  298. {
  299. // $wipe_cache_type = ['TEMP_PATH', 'LOG_PATH', 'CACHE_PATH'];
  300. $wipe_cache_type = ['TEMP_PATH', 'CACHE_PATH'];
  301. foreach ($wipe_cache_type as $item)
  302. {
  303. $dir = constant($item);
  304. if (!is_dir($dir))
  305. continue;
  306. rmdirs($dir);
  307. }
  308. Cache::clear();
  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 !== '')
  322. {
  323. if ($type)
  324. {
  325. $where['type'] = $type;
  326. }
  327. if ($pid)
  328. {
  329. $where['pid'] = $pid;
  330. }
  331. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  332. }
  333. $this->success('', null, $categorylist);
  334. }
  335. /**
  336. * 读取省市区数据,联动列表
  337. */
  338. public function area()
  339. {
  340. $province = $this->request->get('province');
  341. $city = $this->request->get('city');
  342. $where = ['pid' => 0, 'level' => 1];
  343. $provincelist = null;
  344. if ($province !== '')
  345. {
  346. if ($province)
  347. {
  348. $where['pid'] = $province;
  349. $where['level'] = 2;
  350. }
  351. if ($city !== '')
  352. {
  353. if ($city)
  354. {
  355. $where['pid'] = $city;
  356. $where['level'] = 3;
  357. }
  358. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  359. }
  360. }
  361. $this->success('', null, $provincelist);
  362. }
  363. /**
  364. * 上传微信txt文件(微信txt权限验证文件,上传到public下,且禁止重命名)
  365. */
  366. public function uploadTxt()
  367. {
  368. Config::set('upload.savekey','/{filename}{.suffix}');
  369. $this->upload();
  370. }
  371. /**
  372. * 上传文件,不带 cdn 域名的
  373. */
  374. public function uploadNoCdn()
  375. {
  376. Config::set('upload.cdnurl', '');
  377. $this->upload();
  378. }
  379. }