Ajax.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. $callback = $this->request->get('callback');
  132. $controllername = input("controllername");
  133. $this->loadlang($controllername);
  134. //强制输出JSON Object
  135. $result = 'define(' . json_encode(Lang::get(), JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE) . ');';
  136. return $result;
  137. }
  138. /**
  139. * 读取角色权限树
  140. */
  141. public function roletree()
  142. {
  143. $this->loadlang('auth/group');
  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. $ruleList = collection(model('AuthRule')->order('weigh', 'desc')->select())->toArray();
  157. //读取父类角色所有节点列表
  158. $parentRuleList = [];
  159. if (in_array('*', explode(',', $parentgroupmodel->rules)))
  160. {
  161. $parentRuleList = $ruleList;
  162. }
  163. else
  164. {
  165. $parent_rule_ids = explode(',', $parentgroupmodel->rules);
  166. foreach ($ruleList as $k => $v)
  167. {
  168. if (in_array($v['id'], $parent_rule_ids))
  169. {
  170. $parentRuleList[] = $v;
  171. }
  172. }
  173. }
  174. //当前所有正常规则列表
  175. Tree::instance()->init($ruleList);
  176. //读取当前角色下规则ID集合
  177. $admin_rule_ids = $this->auth->getRuleIds();
  178. //是否是超级管理员
  179. $superadmin = $this->auth->isSuperAdmin();
  180. //当前拥有的规则ID集合
  181. $current_rule_ids = $id ? explode(',', $currentgroupmodel->rules) : [];
  182. if (!$id || !in_array($pid, Tree::instance()->getChildrenIds($id, TRUE)))
  183. {
  184. $ruleList = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0), 'name');
  185. $hasChildrens = [];
  186. foreach ($ruleList as $k => $v)
  187. {
  188. if ($v['haschild'])
  189. $hasChildrens[] = $v['id'];
  190. }
  191. $nodelist = [];
  192. foreach ($parentRuleList as $k => $v)
  193. {
  194. if (!$superadmin && !in_array($v['id'], $admin_rule_ids))
  195. continue;
  196. $state = array('selected' => in_array($v['id'], $current_rule_ids) && !in_array($v['id'], $hasChildrens));
  197. $nodelist[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => $v['title'], 'type' => 'menu', 'state' => $state);
  198. }
  199. $this->code = 1;
  200. $this->data = $nodelist;
  201. }
  202. else
  203. {
  204. $this->code = -1;
  205. $this->data = __('Can not change the parent to child');
  206. }
  207. }
  208. else
  209. {
  210. $this->code = -1;
  211. $this->data = __('Group not found');
  212. }
  213. }
  214. /**
  215. * 上传文件
  216. */
  217. public function upload()
  218. {
  219. $this->code = -1;
  220. $file = $this->request->file('file');
  221. if (empty($file))
  222. {
  223. $this->msg = "未上传文件或超出服务器上传限制";
  224. return;
  225. }
  226. //判断是否已经存在附件
  227. $sha1 = $file->hash();
  228. $uploaded = model("attachment")->where('sha1', $sha1)->find();
  229. if ($uploaded)
  230. {
  231. $this->code = 1;
  232. $this->data = [
  233. 'url' => $uploaded['url']
  234. ];
  235. return;
  236. }
  237. $upload = Config::get('upload');
  238. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  239. $type = strtolower($matches[2]);
  240. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  241. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  242. $fileInfo = $file->getInfo();
  243. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  244. $suffix = $suffix ? $suffix : 'file';
  245. $replaceArr = [
  246. '{year}' => date("Y"),
  247. '{mon}' => date("m"),
  248. '{day}' => date("d"),
  249. '{hour}' => date("H"),
  250. '{min}' => date("i"),
  251. '{sec}' => date("s"),
  252. '{random}' => Random::alnum(16),
  253. '{random32}' => Random::alnum(32),
  254. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  255. '{suffix}' => $suffix,
  256. '{.suffix}' => $suffix ? '.' . $suffix : '',
  257. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  258. ];
  259. $savekey = $upload['savekey'];
  260. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  261. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  262. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  263. //
  264. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  265. if ($splInfo)
  266. {
  267. $imagewidth = $imageheight = 0;
  268. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  269. {
  270. $imgInfo = getimagesize($splInfo->getPathname());
  271. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  272. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  273. }
  274. $params = array(
  275. 'filesize' => $fileInfo['size'],
  276. 'imagewidth' => $imagewidth,
  277. 'imageheight' => $imageheight,
  278. 'imagetype' => $suffix,
  279. 'imageframes' => 0,
  280. 'mimetype' => $fileInfo['type'],
  281. 'url' => $uploadDir . $splInfo->getSaveName(),
  282. 'uploadtime' => time(),
  283. 'storage' => 'local',
  284. 'sha1' => $sha1,
  285. );
  286. model("attachment")->create(array_filter($params));
  287. $this->code = 1;
  288. $this->data = [
  289. 'url' => $uploadDir . $splInfo->getSaveName()
  290. ];
  291. }
  292. else
  293. {
  294. // 上传失败获取错误信息
  295. $this->data = $file->getError();
  296. }
  297. }
  298. /**
  299. * 通用排序
  300. */
  301. public function weigh()
  302. {
  303. //排序的数组
  304. $ids = $this->request->post("ids");
  305. //拖动的记录ID
  306. $changeid = $this->request->post("changeid");
  307. //操作字段
  308. $field = $this->request->post("field");
  309. //操作的数据表
  310. $table = $this->request->post("table");
  311. //排序的方式
  312. $orderway = $this->request->post("orderway", 'strtolower');
  313. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  314. $sour = $weighdata = [];
  315. $ids = explode(',', $ids);
  316. $prikey = 'id';
  317. $pid = $this->request->post("pid");
  318. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  319. if ($pid !== '')
  320. {
  321. $hasids = [];
  322. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  323. foreach ($list as $k => $v)
  324. {
  325. $hasids[] = $v['id'];
  326. }
  327. $ids = array_values(array_intersect($ids, $hasids));
  328. }
  329. //直接修复排序
  330. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  331. if ($one)
  332. {
  333. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  334. foreach ($list as $k => $v)
  335. {
  336. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  337. }
  338. $this->code = 1;
  339. }
  340. else
  341. {
  342. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  343. foreach ($list as $k => $v)
  344. {
  345. $sour[] = $v[$prikey];
  346. $weighdata[$v[$prikey]] = $v[$field];
  347. }
  348. $position = array_search($changeid, $ids);
  349. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  350. $sour_id = $changeid;
  351. $desc_value = $weighdata[$desc_id];
  352. $sour_value = $weighdata[$sour_id];
  353. //echo "移动的ID:{$sour_id}\n";
  354. //echo "替换的ID:{$desc_id}\n";
  355. $weighids = array();
  356. $temp = array_values(array_diff_assoc($ids, $sour));
  357. foreach ($temp as $m => $n)
  358. {
  359. if ($n == $sour_id)
  360. {
  361. $offset = $desc_id;
  362. }
  363. else
  364. {
  365. if ($sour_id == $temp[0])
  366. {
  367. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  368. }
  369. else
  370. {
  371. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  372. }
  373. }
  374. $weighids[$n] = $weighdata[$offset];
  375. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  376. }
  377. $this->code = 1;
  378. }
  379. }
  380. /**
  381. * 清空系统缓存
  382. */
  383. public function wipecache()
  384. {
  385. $wipe_cache_type = ['TEMP_PATH', 'LOG_PATH', 'CACHE_PATH'];
  386. foreach ($wipe_cache_type as $item)
  387. {
  388. $dir = constant($item);
  389. if (!is_dir($dir))
  390. continue;
  391. $files = new RecursiveIteratorIterator(
  392. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
  393. );
  394. foreach ($files as $fileinfo)
  395. {
  396. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  397. $todo($fileinfo->getRealPath());
  398. }
  399. //rmdir($dir);
  400. }
  401. Cache::clear();
  402. $this->code = 1;
  403. }
  404. /**
  405. * 读取分类数据
  406. */
  407. public function category()
  408. {
  409. $type = $this->request->get('type');
  410. $pid = $this->request->get('pid');
  411. $where = ['status' => 'normal'];
  412. if ($type)
  413. {
  414. $where['type'] = $type;
  415. }
  416. if ($pid)
  417. {
  418. $where['pid'] = $pid;
  419. }
  420. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  421. $this->code = 1;
  422. $this->data = $categorylist;
  423. return;
  424. }
  425. /**
  426. * 读取省市区数据
  427. */
  428. public function area()
  429. {
  430. $province = $this->request->get('province');
  431. $city = $this->request->get('city');
  432. $where = ['pid' => 0, 'level' => 1];
  433. if ($province)
  434. {
  435. $where['pid'] = $province;
  436. $where['level'] = 2;
  437. }
  438. if ($city)
  439. {
  440. $where['pid'] = $city;
  441. $where['level'] = 3;
  442. }
  443. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  444. $this->code = 1;
  445. $this->data = $provincelist;
  446. return;
  447. }
  448. }