You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

312 lines
11 KiB

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