Ajax.php 13 KB

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