Ajax.php 13 KB

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