Ajax.php 9.5 KB

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