Ajax.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. $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. $this->error(__('Uploaded file format is limited'));
  61. }
  62. $replaceArr = [
  63. '{year}' => date("Y"),
  64. '{mon}' => date("m"),
  65. '{day}' => date("d"),
  66. '{hour}' => date("H"),
  67. '{min}' => date("i"),
  68. '{sec}' => date("s"),
  69. '{random}' => Random::alnum(16),
  70. '{random32}' => Random::alnum(32),
  71. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  72. '{suffix}' => $suffix,
  73. '{.suffix}' => $suffix ? '.' . $suffix : '',
  74. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  75. ];
  76. $savekey = $upload['savekey'];
  77. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  78. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  79. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  80. //
  81. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  82. if ($splInfo) {
  83. $imagewidth = $imageheight = 0;
  84. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
  85. $imgInfo = getimagesize($splInfo->getPathname());
  86. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  87. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  88. }
  89. $params = array(
  90. 'filesize' => $fileInfo['size'],
  91. 'imagewidth' => $imagewidth,
  92. 'imageheight' => $imageheight,
  93. 'imagetype' => $suffix,
  94. 'imageframes' => 0,
  95. 'mimetype' => $fileInfo['type'],
  96. 'url' => $uploadDir . $splInfo->getSaveName(),
  97. 'uploadtime' => time(),
  98. 'storage' => 'local',
  99. 'sha1' => $sha1,
  100. );
  101. $attachment = model("attachment");
  102. $attachment->data(array_filter($params));
  103. $attachment->save();
  104. \think\Hook::listen("upload_after", $attachment);
  105. $this->success(__('Upload successful'), null, [
  106. 'url' => $uploadDir . $splInfo->getSaveName()
  107. ]);
  108. } else {
  109. // 上传失败获取错误信息
  110. $this->error($file->getError());
  111. }
  112. }
  113. /**
  114. * 通用排序
  115. */
  116. public function weigh()
  117. {
  118. //排序的数组
  119. $ids = $this->request->post("ids");
  120. //拖动的记录ID
  121. $changeid = $this->request->post("changeid");
  122. //操作字段
  123. $field = $this->request->post("field");
  124. //操作的数据表
  125. $table = $this->request->post("table");
  126. //排序的方式
  127. $orderway = $this->request->post("orderway", 'strtolower');
  128. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  129. $sour = $weighdata = [];
  130. $ids = explode(',', $ids);
  131. $prikey = 'id';
  132. $pid = $this->request->post("pid");
  133. //限制更新的字段
  134. $field = in_array($field, ['weigh']) ? $field : 'weigh';
  135. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  136. if ($pid !== '') {
  137. $hasids = [];
  138. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  139. foreach ($list as $k => $v) {
  140. $hasids[] = $v['id'];
  141. }
  142. $ids = array_values(array_intersect($ids, $hasids));
  143. }
  144. //直接修复排序
  145. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  146. if ($one) {
  147. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  148. foreach ($list as $k => $v) {
  149. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  150. }
  151. $this->success();
  152. } else {
  153. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  154. foreach ($list as $k => $v) {
  155. $sour[] = $v[$prikey];
  156. $weighdata[$v[$prikey]] = $v[$field];
  157. }
  158. $position = array_search($changeid, $ids);
  159. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  160. $sour_id = $changeid;
  161. $desc_value = $weighdata[$desc_id];
  162. $sour_value = $weighdata[$sour_id];
  163. //echo "移动的ID:{$sour_id}\n";
  164. //echo "替换的ID:{$desc_id}\n";
  165. $weighids = array();
  166. $temp = array_values(array_diff_assoc($ids, $sour));
  167. foreach ($temp as $m => $n) {
  168. if ($n == $sour_id) {
  169. $offset = $desc_id;
  170. } else {
  171. if ($sour_id == $temp[0]) {
  172. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  173. } else {
  174. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  175. }
  176. }
  177. $weighids[$n] = $weighdata[$offset];
  178. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  179. }
  180. $this->success();
  181. }
  182. }
  183. /**
  184. * 清空系统缓存
  185. */
  186. public function wipecache()
  187. {
  188. $type = $this->request->request("type");
  189. switch ($type) {
  190. case 'content' || 'all':
  191. rmdirs(CACHE_PATH, false);
  192. Cache::clear();
  193. if ($type == 'content')
  194. break;
  195. case 'template' || 'all':
  196. rmdirs(TEMP_PATH, false);
  197. if ($type == 'template')
  198. break;
  199. case 'addons' || 'all':
  200. Service::refresh();
  201. if ($type == 'addons')
  202. break;
  203. }
  204. \think\Hook::listen("wipecache_after");
  205. $this->success();
  206. }
  207. /**
  208. * 读取分类数据,联动列表
  209. */
  210. public function category()
  211. {
  212. $type = $this->request->get('type');
  213. $pid = $this->request->get('pid');
  214. $where = ['status' => 'normal'];
  215. $categorylist = null;
  216. if ($pid !== '') {
  217. if ($type) {
  218. $where['type'] = $type;
  219. }
  220. if ($pid) {
  221. $where['pid'] = $pid;
  222. }
  223. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  224. }
  225. $this->success('', null, $categorylist);
  226. }
  227. /**
  228. * 读取省市区数据,联动列表
  229. */
  230. public function area()
  231. {
  232. $province = $this->request->get('province');
  233. $city = $this->request->get('city');
  234. $where = ['pid' => 0, 'level' => 1];
  235. $provincelist = null;
  236. if ($province !== '') {
  237. if ($province) {
  238. $where['pid'] = $province;
  239. $where['level'] = 2;
  240. }
  241. if ($city !== '') {
  242. if ($city) {
  243. $where['pid'] = $city;
  244. $where['level'] = 3;
  245. }
  246. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  247. }
  248. }
  249. $this->success('', null, $provincelist);
  250. }
  251. }