Ajax.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use fast\Random;
  5. use think\addons\Service;
  6. use think\Cache;
  7. use think\Config;
  8. use think\Db;
  9. use think\Lang;
  10. use think\Validate;
  11. /**
  12. * Ajax异步请求接口
  13. * @internal
  14. */
  15. class Ajax extends Backend
  16. {
  17. protected $noNeedLogin = ['lang'];
  18. protected $noNeedRight = ['*'];
  19. protected $layout = '';
  20. public function _initialize()
  21. {
  22. parent::_initialize();
  23. //设置过滤方法
  24. $this->request->filter(['strip_tags', 'htmlspecialchars']);
  25. }
  26. /**
  27. * 加载语言包
  28. */
  29. public function lang()
  30. {
  31. header('Content-Type: application/javascript');
  32. $controllername = input("controllername");
  33. //默认只加载了控制器对应的语言名,你还根据控制器名来加载额外的语言包
  34. $this->loadlang($controllername);
  35. return jsonp(Lang::get(), 200, [], ['json_encode_param' => JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE]);
  36. }
  37. /**
  38. * 上传文件
  39. */
  40. public function upload()
  41. {
  42. Config::set('default_return_type', 'json');
  43. $file = $this->request->file('file');
  44. if (empty($file)) {
  45. $this->error(__('No file upload or server upload limit exceeded'));
  46. }
  47. //判断是否已经存在附件
  48. $sha1 = $file->hash();
  49. $extparam = $this->request->post();
  50. $upload = Config::get('upload');
  51. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  52. $type = strtolower($matches[2]);
  53. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  54. $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  55. $fileInfo = $file->getInfo();
  56. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  57. $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
  58. $mimetypeArr = explode(',', strtolower($upload['mimetype']));
  59. $typeArr = explode('/', $fileInfo['type']);
  60. //禁止上传PHP和HTML文件
  61. if (in_array($fileInfo['type'], ['text/x-php', 'text/html']) || in_array($suffix, ['php', 'html', 'htm'])) {
  62. $this->error(__('Uploaded file format is limited'));
  63. }
  64. //验证文件后缀
  65. if ($upload['mimetype'] !== '*' &&
  66. (
  67. !in_array($suffix, $mimetypeArr)
  68. || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
  69. )
  70. ) {
  71. $this->error(__('Uploaded file format is limited'));
  72. }
  73. //验证是否为图片文件
  74. $imagewidth = $imageheight = 0;
  75. if (in_array($fileInfo['type'], ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
  76. $imgInfo = getimagesize($fileInfo['tmp_name']);
  77. if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
  78. $this->error(__('Uploaded file is not a valid image'));
  79. }
  80. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  81. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  82. }
  83. $replaceArr = [
  84. '{year}' => date("Y"),
  85. '{mon}' => date("m"),
  86. '{day}' => date("d"),
  87. '{hour}' => date("H"),
  88. '{min}' => date("i"),
  89. '{sec}' => date("s"),
  90. '{random}' => Random::alnum(16),
  91. '{random32}' => Random::alnum(32),
  92. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  93. '{suffix}' => $suffix,
  94. '{.suffix}' => $suffix ? '.' . $suffix : '',
  95. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  96. ];
  97. $savekey = $upload['savekey'];
  98. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  99. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  100. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  101. //
  102. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  103. if ($splInfo) {
  104. $params = array(
  105. 'admin_id' => (int)$this->auth->id,
  106. 'user_id' => 0,
  107. 'filesize' => $fileInfo['size'],
  108. 'imagewidth' => $imagewidth,
  109. 'imageheight' => $imageheight,
  110. 'imagetype' => $suffix,
  111. 'imageframes' => 0,
  112. 'mimetype' => $fileInfo['type'],
  113. 'url' => $uploadDir . $splInfo->getSaveName(),
  114. 'uploadtime' => time(),
  115. 'storage' => 'local',
  116. 'sha1' => $sha1,
  117. 'extparam' => json_encode($extparam),
  118. );
  119. $attachment = model("attachment");
  120. $attachment->data(array_filter($params));
  121. $attachment->save();
  122. \think\Hook::listen("upload_after", $attachment);
  123. $this->success(__('Upload successful'), null, [
  124. 'url' => $uploadDir . $splInfo->getSaveName()
  125. ]);
  126. } else {
  127. // 上传失败获取错误信息
  128. $this->error($file->getError());
  129. }
  130. }
  131. /**
  132. * 通用排序
  133. */
  134. public function weigh()
  135. {
  136. //排序的数组
  137. $ids = $this->request->post("ids");
  138. //拖动的记录ID
  139. $changeid = $this->request->post("changeid");
  140. //操作字段
  141. $field = $this->request->post("field");
  142. //操作的数据表
  143. $table = $this->request->post("table");
  144. if (!Validate::is($table, "alphaDash")) {
  145. $this->error();
  146. }
  147. //主键
  148. $pk = $this->request->post("pk");
  149. //排序的方式
  150. $orderway = strtolower($this->request->post("orderway", ""));
  151. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  152. $sour = $weighdata = [];
  153. $ids = explode(',', $ids);
  154. $prikey = $pk ? $pk : (Db::name($table)->getPk() ?: 'id');
  155. $pid = $this->request->post("pid");
  156. //限制更新的字段
  157. $field = in_array($field, ['weigh']) ? $field : 'weigh';
  158. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  159. if ($pid !== '') {
  160. $hasids = [];
  161. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field("{$prikey},pid")->select();
  162. foreach ($list as $k => $v) {
  163. $hasids[] = $v[$prikey];
  164. }
  165. $ids = array_values(array_intersect($ids, $hasids));
  166. }
  167. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  168. foreach ($list as $k => $v) {
  169. $sour[] = $v[$prikey];
  170. $weighdata[$v[$prikey]] = $v[$field];
  171. }
  172. $position = array_search($changeid, $ids);
  173. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  174. $sour_id = $changeid;
  175. $weighids = array();
  176. $temp = array_values(array_diff_assoc($ids, $sour));
  177. foreach ($temp as $m => $n) {
  178. if ($n == $sour_id) {
  179. $offset = $desc_id;
  180. } else {
  181. if ($sour_id == $temp[0]) {
  182. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  183. } else {
  184. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  185. }
  186. }
  187. $weighids[$n] = $weighdata[$offset];
  188. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  189. }
  190. $this->success();
  191. }
  192. /**
  193. * 清空系统缓存
  194. */
  195. public function wipecache()
  196. {
  197. $type = $this->request->request("type");
  198. switch ($type) {
  199. case 'all':
  200. case 'content':
  201. rmdirs(CACHE_PATH, false);
  202. Cache::clear();
  203. if ($type == 'content') {
  204. break;
  205. }
  206. case 'template':
  207. rmdirs(TEMP_PATH, false);
  208. if ($type == 'template') {
  209. break;
  210. }
  211. case 'addons':
  212. Service::refresh();
  213. if ($type == 'addons') {
  214. break;
  215. }
  216. }
  217. \think\Hook::listen("wipecache_after");
  218. $this->success();
  219. }
  220. /**
  221. * 读取分类数据,联动列表
  222. */
  223. public function category()
  224. {
  225. $type = $this->request->get('type');
  226. $pid = $this->request->get('pid');
  227. $where = ['status' => 'normal'];
  228. $categorylist = null;
  229. if ($pid !== '') {
  230. if ($type) {
  231. $where['type'] = $type;
  232. }
  233. if ($pid) {
  234. $where['pid'] = $pid;
  235. }
  236. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  237. }
  238. $this->success('', null, $categorylist);
  239. }
  240. /**
  241. * 读取省市区数据,联动列表
  242. */
  243. public function area()
  244. {
  245. $params = $this->request->get("row/a");
  246. if (!empty($params)) {
  247. $province = isset($params['province']) ? $params['province'] : '';
  248. $city = isset($params['city']) ? $params['city'] : null;
  249. } else {
  250. $province = $this->request->get('province');
  251. $city = $this->request->get('city');
  252. }
  253. $where = ['pid' => 0, 'level' => 1];
  254. $provincelist = null;
  255. if ($province !== '') {
  256. if ($province) {
  257. $where['pid'] = $province;
  258. $where['level'] = 2;
  259. }
  260. if ($city !== '') {
  261. if ($city) {
  262. $where['pid'] = $city;
  263. $where['level'] = 3;
  264. }
  265. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  266. }
  267. }
  268. $this->success('', null, $provincelist);
  269. }
  270. }