Ajax.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. $field = substr($field, 0, -3);
  36. switch ($field)
  37. {
  38. case 'category':
  39. $field = 'category';
  40. $searchfield = 'name';
  41. break;
  42. case 'user':
  43. $searchfield = 'nickname';
  44. break;
  45. }
  46. $searchlist = Db::name($field)
  47. ->whereOr($searchfield, 'like', "%{$search}%")
  48. ->whereOr('id', 'like', "%{$search}%")
  49. ->limit(10)
  50. ->field("id,{$searchfield} AS name")
  51. ->select();
  52. foreach ($searchlist as $k => &$v)
  53. {
  54. $v['name'] = $v['name'] . "[id:{$v['id']}]";
  55. }
  56. unset($v);
  57. $this->code = 1;
  58. $this->data = ['searchlist' => $searchlist];
  59. }
  60. /**
  61. * 加载语言包
  62. */
  63. public function lang()
  64. {
  65. header('Content-Type: application/javascript');
  66. $modulename = $this->request->module();
  67. $callback = $this->request->get('callback');
  68. $controllername = input("controllername");
  69. Lang::load(APP_PATH . $modulename . '/lang/' . Lang::detect() . '/' . str_replace('.', '/', $controllername) . '.php');
  70. //强制输出JSON Object
  71. $result = 'define(' . json_encode(Lang::get(), JSON_FORCE_OBJECT | JSON_UNESCAPED_UNICODE) . ');';
  72. return $result;
  73. }
  74. /**
  75. * 读取角色权限树
  76. */
  77. public function roletree()
  78. {
  79. $model = model('AuthGroup');
  80. $id = $this->request->post("id");
  81. $pid = $this->request->post("pid");
  82. $parentgroupmodel = $model->get($pid);
  83. $currentgroupmodel = NULL;
  84. if ($id)
  85. {
  86. $currentgroupmodel = $model->get($id);
  87. }
  88. if (($pid || $parentgroupmodel) && (!$id || $currentgroupmodel))
  89. {
  90. $id = $id ? $id : NULL;
  91. //读取父类角色所有节点列表
  92. $parentrulelist = model('AuthRule')->all(in_array('*', explode(',', $parentgroupmodel->rules)) ? NULL : $parentgroupmodel->rules);
  93. //读取当前角色下规则ID集合
  94. $admin_rule_ids = $this->auth->getRuleIds();
  95. $superadmin = $this->auth->isSuperAdmin();
  96. $current_rule_ids = $id ? explode(',', $currentgroupmodel->rules) : [];
  97. if (!$id || !in_array($pid, Tree::instance()->init($model->all(['status' => 'normal']))->getChildrenIds($id, TRUE)))
  98. {
  99. //构造jstree所需的数据
  100. $nodelist = [];
  101. foreach ($parentrulelist as $k => $v)
  102. {
  103. if (!$superadmin && !in_array($v['id'], $admin_rule_ids))
  104. continue;
  105. $state = array('selected' => !$v['ismenu'] && in_array($v['id'], $current_rule_ids));
  106. $nodelist[] = array('id' => $v['id'], 'parent' => $v['pid'] ? $v['pid'] : '#', 'text' => $v['title'], 'type' => 'menu', 'state' => $state);
  107. }
  108. $this->code = 1;
  109. $this->data = $nodelist;
  110. }
  111. else
  112. {
  113. $this->code = -1;
  114. $this->data = __('Can not change the parent to child');
  115. }
  116. }
  117. else
  118. {
  119. $this->code = -1;
  120. $this->data = __('Group not found');
  121. }
  122. }
  123. /**
  124. * 上传文件
  125. */
  126. public function upload()
  127. {
  128. $this->code = -1;
  129. $file = $this->request->file('file');
  130. //判断是否已经存在附件
  131. $sha1 = $file->hash();
  132. $uploaded = model("attachment")->where('sha1', $sha1)->find();
  133. if ($uploaded)
  134. {
  135. $this->code = 1;
  136. $this->data = [
  137. 'url' => $uploaded['url']
  138. ];
  139. return;
  140. }
  141. $upload = Config::get('upload');
  142. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  143. $type = strtolower($matches[2]);
  144. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  145. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  146. $fileInfo = $file->getInfo();
  147. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  148. $suffix = $suffix ? $suffix : 'file';
  149. $replaceArr = [
  150. '{year}' => date("Y"),
  151. '{mon}' => date("m"),
  152. '{day}' => date("d"),
  153. '{hour}' => date("H"),
  154. '{min}' => date("i"),
  155. '{sec}' => date("s"),
  156. '{random}' => Random::alnum(16),
  157. '{random32}' => Random::alnum(32),
  158. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  159. '{suffix}' => $suffix,
  160. '{.suffix}' => $suffix ? '.' . $suffix : '',
  161. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  162. ];
  163. $savekey = $upload['savekey'];
  164. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  165. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  166. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  167. //
  168. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  169. if ($splInfo)
  170. {
  171. $imagewidth = $imageheight = 0;
  172. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  173. {
  174. $imgInfo = getimagesize($splInfo->getPathname());
  175. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  176. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  177. }
  178. $params = array(
  179. 'filesize' => $fileInfo['size'],
  180. 'imagewidth' => $imagewidth,
  181. 'imageheight' => $imageheight,
  182. 'imagetype' => $suffix,
  183. 'imageframes' => 0,
  184. 'mimetype' => $fileInfo['type'],
  185. 'url' => $uploadDir . $splInfo->getSaveName(),
  186. 'uploadtime' => time(),
  187. 'storage' => 'local',
  188. 'sha1' => $sha1,
  189. );
  190. model("attachment")->create(array_filter($params));
  191. $this->code = 1;
  192. $this->data = [
  193. 'url' => $uploadDir . $splInfo->getSaveName()
  194. ];
  195. }
  196. else
  197. {
  198. // 上传失败获取错误信息
  199. $this->data = $file->getError();
  200. }
  201. }
  202. /**
  203. * 通用排序
  204. */
  205. public function weigh()
  206. {
  207. //排序的数组
  208. $ids = $this->request->post("ids");
  209. //拖动的记录ID
  210. $changeid = $this->request->post("changeid");
  211. //操作字段
  212. $field = $this->request->post("field");
  213. //操作的数据表
  214. $table = $this->request->post("table");
  215. //排序的方式
  216. $orderway = $this->request->post("orderway", 'strtolower');
  217. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  218. $sour = $weighdata = [];
  219. $ids = explode(',', $ids);
  220. $prikey = 'id';
  221. $pid = $this->request->post("pid");
  222. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  223. if ($pid !== '')
  224. {
  225. $hasids = [];
  226. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  227. foreach ($list as $k => $v)
  228. {
  229. $hasids[] = $v['id'];
  230. }
  231. $ids = array_values(array_intersect($ids, $hasids));
  232. }
  233. //直接修复排序
  234. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  235. if ($one)
  236. {
  237. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  238. foreach ($list as $k => $v)
  239. {
  240. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  241. }
  242. $this->code = 1;
  243. }
  244. else
  245. {
  246. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  247. foreach ($list as $k => $v)
  248. {
  249. $sour[] = $v[$prikey];
  250. $weighdata[$v[$prikey]] = $v[$field];
  251. }
  252. $position = array_search($changeid, $ids);
  253. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  254. $sour_id = $changeid;
  255. $desc_value = $weighdata[$desc_id];
  256. $sour_value = $weighdata[$sour_id];
  257. //echo "移动的ID:{$sour_id}\n";
  258. //echo "替换的ID:{$desc_id}\n";
  259. $weighids = array();
  260. $temp = array_values(array_diff_assoc($ids, $sour));
  261. foreach ($temp as $m => $n)
  262. {
  263. if ($n == $sour_id)
  264. {
  265. $offset = $desc_id;
  266. }
  267. else
  268. {
  269. if ($sour_id == $temp[0])
  270. {
  271. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  272. }
  273. else
  274. {
  275. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  276. }
  277. }
  278. $weighids[$n] = $weighdata[$offset];
  279. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  280. }
  281. $this->code = 1;
  282. }
  283. }
  284. /**
  285. * 清空系统缓存
  286. */
  287. public function wipecache()
  288. {
  289. $wipe_cache_type = ['TEMP_PATH', 'LOG_PATH', 'CACHE_PATH'];
  290. foreach ($wipe_cache_type as $item)
  291. {
  292. $dir = constant($item);
  293. if (!is_dir($dir))
  294. continue;
  295. $files = new RecursiveIteratorIterator(
  296. new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST
  297. );
  298. foreach ($files as $fileinfo)
  299. {
  300. $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  301. $todo($fileinfo->getRealPath());
  302. }
  303. //rmdir($dir);
  304. }
  305. Cache::clear();
  306. $this->code = 1;
  307. }
  308. /**
  309. * 读取分类数据
  310. */
  311. public function category()
  312. {
  313. $type = $this->request->get('type');
  314. $pid = $this->request->get('pid');
  315. $where = ['status' => 'normal'];
  316. if ($type)
  317. {
  318. $where['type'] = $type;
  319. }
  320. if ($pid)
  321. {
  322. $where['pid'] = $pid;
  323. }
  324. $categorylist = Db::name('category')->where($where)->field('id as value,name')->order('weigh desc,id desc')->select();
  325. $this->code = 1;
  326. $this->data = $categorylist;
  327. return;
  328. }
  329. /**
  330. * 读取省市区数据
  331. */
  332. public function area()
  333. {
  334. $province = $this->request->get('province');
  335. $city = $this->request->get('city');
  336. $where = ['pid' => 0, 'level' => 1];
  337. if ($province)
  338. {
  339. $where['pid'] = $province;
  340. $where['level'] = 2;
  341. }
  342. if ($city)
  343. {
  344. $where['pid'] = $city;
  345. $where['level'] = 3;
  346. }
  347. $provincelist = Db::name('area')->where($where)->field('id as value,name')->select();
  348. $this->code = 1;
  349. $this->data = $provincelist;
  350. return;
  351. }
  352. }