Ajax.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. <?php
  2. namespace app\admin\controller;
  3. use app\common\controller\Backend;
  4. use fast\Random;
  5. use fast\Tree;
  6. use RecursiveDirectoryIterator;
  7. use RecursiveIteratorIterator;
  8. use think\Cache;
  9. use think\Config;
  10. use think\Db;
  11. use think\Lang;
  12. /**
  13. * Ajax异步请求接口
  14. * @internal
  15. */
  16. class Ajax extends Backend
  17. {
  18. protected $noNeedLogin = ['lang'];
  19. protected $noNeedRight = ['*'];
  20. protected $layout = '';
  21. /**
  22. * 自动完成
  23. */
  24. public function typeahead()
  25. {
  26. $search = $this->request->get("search");
  27. $field = $this->request->get("field");
  28. $field = str_replace(['row[', ']'], '', $field);
  29. if (substr($field, -3) !== '_id' && substr($field, -4) !== '_ids')
  30. {
  31. $this->code = -1;
  32. return;
  33. }
  34. $searchfield = 'name';
  35. $fieldArr = explode('_', $field);
  36. $field = $fieldArr[0];
  37. switch ($field)
  38. {
  39. case 'category':
  40. $field = 'category';
  41. $searchfield = 'name';
  42. break;
  43. case 'user':
  44. $searchfield = 'nickname';
  45. break;
  46. }
  47. $searchlist = Db::name($field)
  48. ->whereOr($searchfield, 'like', "%{$search}%")
  49. ->whereOr('id', 'like', "%{$search}%")
  50. ->limit(10)
  51. ->field("id,{$searchfield} AS name")
  52. ->select();
  53. $this->code = 1;
  54. $this->data = ['searchlist' => $searchlist];
  55. }
  56. /**
  57. * SelectPage通用下拉列表搜索
  58. */
  59. public function selectpage()
  60. {
  61. //搜索关键词,客户端输入以空格分开,这里接收为数组
  62. $word = $this->request->request("q_word/a");
  63. //当前页
  64. $page = $this->request->request("pageNumber");
  65. //分页大小
  66. $pagesize = $this->request->request("pageSize");
  67. //搜索条件
  68. $andor = $this->request->request("and_or");
  69. //排序方式
  70. $orderby = $this->request->request("order_by/a");
  71. //表名
  72. $table = $this->request->request("db_table");
  73. //显示的字段
  74. $field = $this->request->request("field");
  75. //主键
  76. $primarykey = $this->request->request("pkey_name");
  77. //主键值
  78. $primaryvalue = $this->request->request("pkey_value");
  79. //搜索字段
  80. $searchfield = $this->request->request("search_field/a");
  81. //自定义搜索条件
  82. $custom = $this->request->request("custom/a");
  83. $order = [];
  84. foreach ($orderby as $k => $v)
  85. {
  86. $order[$v[0]] = $v[1];
  87. }
  88. $field = $field ? $field : 'name';
  89. //如果不使用ajax/selectpage这个页面提供结果,则是自己的控制器单独写搜索条件,$where按自己的需求写即可
  90. //这里只是能用考虑,所以搜索条件写得比较复杂
  91. //如果有primaryvalue,说明当前是初始化传值
  92. if ($primaryvalue)
  93. {
  94. $where = [$primarykey => ['in', $primaryvalue]];
  95. }
  96. else
  97. {
  98. $where = function($query) use($word, $andor, $field, $searchfield, $custom) {
  99. $where = $andor == "OR" ? "whereOr" : "where";
  100. foreach ($word as $k => $v)
  101. {
  102. foreach ($searchfield as $m => $n)
  103. {
  104. $query->{$where}($n, "like", "%{$v}%");
  105. }
  106. }
  107. if ($custom && is_array($custom))
  108. {
  109. foreach ($custom as $k => $v)
  110. {
  111. $query->where($k, '=', $v);
  112. }
  113. }
  114. };
  115. }
  116. $list = [];
  117. $total = Db::name($table)->where($where)->count();
  118. if ($total > 0)
  119. {
  120. $list = Db::name($table)->where($where)->order($order)->page($page, $pagesize)->field("{$primarykey},{$field}")->select();
  121. }
  122. //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
  123. return json(['list' => $list, 'total' => $total]);
  124. }
  125. /**
  126. * 加载语言包
  127. */
  128. public function lang()
  129. {
  130. header('Content-Type: application/javascript');
  131. $modulename = $this->request->module();
  132. $callback = $this->request->get('callback');
  133. $controllername = input("controllername");
  134. Lang::load(APP_PATH . $modulename . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $controllername) . '.php');
  135. //强制输出JSON Object
  136. $result = 'define(' . json_encode(Lang::get(), JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE) . ');';
  137. return $result;
  138. }
  139. /**
  140. * 读取角色权限树
  141. */
  142. public function roletree()
  143. {
  144. $model = model('AuthGroup');
  145. $id = $this->request->post("id");
  146. $pid = $this->request->post("pid");
  147. $parentgroupmodel = $model->get($pid);
  148. $currentgroupmodel = NULL;
  149. if ($id)
  150. {
  151. $currentgroupmodel = $model->get($id);
  152. }
  153. if (($pid || $parentgroupmodel) && (!$id || $currentgroupmodel))
  154. {
  155. $id = $id ? $id : NULL;
  156. //读取父类角色所有节点列表
  157. $parentrulelist = model('AuthRule')->all(in_array('*', explode(',', $parentgroupmodel->rules)) ? NULL : $parentgroupmodel->rules);
  158. //读取当前角色下规则ID集合
  159. $admin_rule_ids = $this->auth->getRuleIds();
  160. $superadmin = $this->auth->isSuperAdmin();
  161. $current_rule_ids = $id ? explode(',', $currentgroupmodel->rules) : [];
  162. if (!$id || !in_array($pid, Tree::instance()->init($model->all(['status' => 'normal']))->getChildrenIds($id, TRUE)))
  163. {
  164. //构造jstree所需的数据
  165. $nodelist = [];
  166. foreach ($parentrulelist as $k => $v)
  167. {
  168. if (!$superadmin && !in_array($v['id'], $admin_rule_ids))
  169. continue;
  170. $state = array('selected' => !$v['ismenu'] && in_array($v['id'], $current_rule_ids));
  171. $nodelist[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => $v['title'], 'type' => 'menu', 'state' => $state);
  172. }
  173. $this->code = 1;
  174. $this->data = $nodelist;
  175. }
  176. else
  177. {
  178. $this->code = -1;
  179. $this->data = __('Can not change the parent to child');
  180. }
  181. }
  182. else
  183. {
  184. $this->code = -1;
  185. $this->data = __('Group not found');
  186. }
  187. }
  188. /**
  189. * 上传文件
  190. */
  191. public function upload()
  192. {
  193. $this->code = -1;
  194. $file = $this->request->file('file');
  195. //判断是否已经存在附件
  196. $sha1 = $file->hash();
  197. $uploaded = model("attachment")->where('sha1', $sha1)->find();
  198. if ($uploaded)
  199. {
  200. $this->code = 1;
  201. $this->data = [
  202. 'url' => $uploaded['url']
  203. ];
  204. return;
  205. }
  206. $upload = Config::get('upload');
  207. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  208. $type = strtolower($matches[2]);
  209. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  210. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  211. $fileInfo = $file->getInfo();
  212. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  213. $suffix = $suffix ? $suffix : 'file';
  214. $replaceArr = [
  215. '{year}' => date("Y"),
  216. '{mon}' => date("m"),
  217. '{day}' => date("d"),
  218. '{hour}' => date("H"),
  219. '{min}' => date("i"),
  220. '{sec}' => date("s"),
  221. '{random}' => Random::alnum(16),
  222. '{random32}' => Random::alnum(32),
  223. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  224. '{suffix}' => $suffix,
  225. '{.suffix}' => $suffix ? '.' . $suffix : '',
  226. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  227. ];
  228. $savekey = $upload['savekey'];
  229. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  230. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  231. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  232. //
  233. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  234. if ($splInfo)
  235. {
  236. $imagewidth = $imageheight = 0;
  237. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  238. {
  239. $imgInfo = getimagesize($splInfo->getPathname());
  240. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  241. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  242. }
  243. $params = array(
  244. 'filesize' => $fileInfo['size'],
  245. 'imagewidth' => $imagewidth,
  246. 'imageheight' => $imageheight,
  247. 'imagetype' => $suffix,
  248. 'imageframes' => 0,
  249. 'mimetype' => $fileInfo['type'],
  250. 'url' => $uploadDir . $splInfo->getSaveName(),
  251. 'uploadtime' => time(),
  252. 'storage' => 'local',
  253. 'sha1' => $sha1,
  254. );
  255. model("attachment")->create(array_filter($params));
  256. $this->code = 1;
  257. $this->data = [
  258. 'url' => $uploadDir . $splInfo->getSaveName()
  259. ];
  260. }
  261. else
  262. {
  263. // 上传失败获取错误信息
  264. $this->data = $file->getError();
  265. }
  266. }
  267. /**
  268. * 通用排序
  269. */
  270. public function weigh()
  271. {
  272. //排序的数组
  273. $ids = $this->request->post("ids");
  274. //拖动的记录ID
  275. $changeid = $this->request->post("changeid");
  276. //操作字段
  277. $field = $this->request->post("field");
  278. //操作的数据表
  279. $table = $this->request->post("table");
  280. //排序的方式
  281. $orderway = $this->request->post("orderway", 'strtolower');
  282. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  283. $sour = $weighdata = [];
  284. $ids = explode(',', $ids);
  285. $prikey = 'id';
  286. $pid = $this->request->post("pid");
  287. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  288. if ($pid !== '')
  289. {
  290. $hasids = [];
  291. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  292. foreach ($list as $k => $v)
  293. {
  294. $hasids[] = $v['id'];
  295. }
  296. $ids = array_values(array_intersect($ids, $hasids));
  297. }
  298. //直接修复排序
  299. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  300. if ($one)
  301. {
  302. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  303. foreach ($list as $k => $v)
  304. {
  305. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  306. }
  307. $this->code = 1;
  308. }
  309. else
  310. {
  311. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  312. foreach ($list as $k => $v)
  313. {
  314. $sour[] = $v[$prikey];
  315. $weighdata[$v[$prikey]] = $v[$field];
  316. }
  317. $position = array_search($changeid, $ids);
  318. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  319. $sour_id = $changeid;
  320. $desc_value = $weighdata[$desc_id];
  321. $sour_value = $weighdata[$sour_id];
  322. //echo "移动的ID:{$sour_id}\n";
  323. //echo "替换的ID:{$desc_id}\n";
  324. $weighids = array();
  325. $temp = array_values(array_diff_assoc($ids, $sour));
  326. foreach ($temp as $m => $n)
  327. {
  328. if ($n == $sour_id)
  329. {
  330. $offset = $desc_id;
  331. }
  332. else
  333. {
  334. if ($sour_id == $temp[0])
  335. {
  336. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  337. }
  338. else
  339. {
  340. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  341. }
  342. }
  343. $weighids[$n] = $weighdata[$offset];
  344. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  345. }
  346. $this->code = 1;
  347. }
  348. }
  349. /**
  350. * 清空系统缓存
  351. */
  352. public function wipecache()
  353. {
  354. $wipe_cache_type = ['TEMP_PATH', 'LOG_PATH', 'CACHE_PATH'];
  355. foreach ($wipe_cache_type as $item)
  356. {
  357. $dir = constant($item);
  358. if (!is_dir($dir))
  359. continue;
  360. $files = new RecursiveIteratorIterator(
  361. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
  362. );
  363. foreach ($files as $fileinfo)
  364. {
  365. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  366. $todo($fileinfo->getRealPath());
  367. }
  368. //rmdir($dir);
  369. }
  370. Cache::clear();
  371. $this->code = 1;
  372. }
  373. /**
  374. * 读取分类数据
  375. */
  376. public function category()
  377. {
  378. $type = $this->request->get('type');
  379. $pid = $this->request->get('pid');
  380. $where = ['status' => 'normal'];
  381. if ($type)
  382. {
  383. $where['type'] = $type;
  384. }
  385. if ($pid)
  386. {
  387. $where['pid'] = $pid;
  388. }
  389. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  390. $this->code = 1;
  391. $this->data = $categorylist;
  392. return;
  393. }
  394. /**
  395. * 读取省市区数据
  396. */
  397. public function area()
  398. {
  399. $province = $this->request->get('province');
  400. $city = $this->request->get('city');
  401. $where = ['pid' => 0, 'level' => 1];
  402. if ($province)
  403. {
  404. $where['pid'] = $province;
  405. $where['level'] = 2;
  406. }
  407. if ($city)
  408. {
  409. $where['pid'] = $city;
  410. $where['level'] = 3;
  411. }
  412. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  413. $this->code = 1;
  414. $this->data = $provincelist;
  415. return;
  416. }
  417. }