Ajax.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. $this->code = 200;
  180. $this->data = $uploaded['url'];
  181. return;
  182. }
  183. $upload = Config::get('upload');
  184. preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
  185. $type = strtolower($matches[2]);
  186. $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
  187. $size = (int) $upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
  188. $fileInfo = $file->getInfo();
  189. $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
  190. $suffix = $suffix ? $suffix : 'file';
  191. $replaceArr = [
  192. '{year}' => date("Y"),
  193. '{mon}' => date("m"),
  194. '{day}' => date("d"),
  195. '{hour}' => date("H"),
  196. '{min}' => date("i"),
  197. '{sec}' => date("s"),
  198. '{random}' => Random::alnum(16),
  199. '{random32}' => Random::alnum(32),
  200. '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
  201. '{suffix}' => $suffix,
  202. '{.suffix}' => $suffix ? '.' . $suffix : '',
  203. '{filemd5}' => md5_file($fileInfo['tmp_name']),
  204. ];
  205. $savekey = $upload['savekey'];
  206. $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);
  207. $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
  208. $fileName = substr($savekey, strripos($savekey, '/') + 1);
  209. //
  210. $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
  211. if ($splInfo)
  212. {
  213. $imagewidth = $imageheight = 0;
  214. if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf']))
  215. {
  216. $imgInfo = getimagesize($splInfo->getPathname());
  217. $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
  218. $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
  219. }
  220. $params = array(
  221. 'filesize' => $fileInfo['size'],
  222. 'imagewidth' => $imagewidth,
  223. 'imageheight' => $imageheight,
  224. 'imagetype' => $suffix,
  225. 'imageframes' => 0,
  226. 'mimetype' => $fileInfo['type'],
  227. 'url' => $uploadDir . $splInfo->getSaveName(),
  228. 'uploadtime' => time(),
  229. 'sha1' => $sha1,
  230. );
  231. model("attachment")->create(array_filter($params));
  232. $this->code = 200;
  233. $this->data = $uploadDir . $splInfo->getSaveName();
  234. }
  235. else
  236. {
  237. // 上传失败获取错误信息
  238. $this->data = $file->getError();
  239. }
  240. }
  241. /**
  242. * 通用排序
  243. */
  244. public function weigh()
  245. {
  246. //排序的数组
  247. $ids = $this->request->post("ids");
  248. //拖动的记录ID
  249. $changeid = $this->request->post("changeid");
  250. //操作字段
  251. $field = $this->request->post("field");
  252. //操作的数据表
  253. $table = $this->request->post("table");
  254. //排序的方式
  255. $orderway = $this->request->post("orderway", 'strtolower');
  256. $orderway = $orderway == 'asc' ? 'ASC' : 'DESC';
  257. $sour = $weighdata = [];
  258. $ids = explode(',', $ids);
  259. $prikey = 'id';
  260. $pid = $this->request->post("pid");
  261. // 如果设定了pid的值,此时只匹配满足条件的ID,其它忽略
  262. if ($pid !== '')
  263. {
  264. $hasids = [];
  265. $list = Db::name($table)->where($prikey, 'in', $ids)->where('pid', 'in', $pid)->field('id,pid')->select();
  266. foreach ($list as $k => $v)
  267. {
  268. $hasids[] = $v['id'];
  269. }
  270. $ids = array_values(array_intersect($ids, $hasids));
  271. }
  272. //直接修复排序
  273. $one = Db::name($table)->field("{$field},COUNT(*) AS nums")->group($field)->having('nums > 1')->find();
  274. if ($one)
  275. {
  276. $list = Db::name($table)->field("$prikey,$field")->order($field, $orderway)->select();
  277. foreach ($list as $k => $v)
  278. {
  279. Db::name($table)->where($prikey, $v[$prikey])->update([$field => $k + 1]);
  280. }
  281. $this->code = 1;
  282. }
  283. else
  284. {
  285. $list = Db::name($table)->field("$prikey,$field")->where($prikey, 'in', $ids)->order($field, $orderway)->select();
  286. foreach ($list as $k => $v)
  287. {
  288. $sour[] = $v[$prikey];
  289. $weighdata[$v[$prikey]] = $v[$field];
  290. }
  291. $position = array_search($changeid, $ids);
  292. $desc_id = $sour[$position]; //移动到目标的ID值,取出所处改变前位置的值
  293. $sour_id = $changeid;
  294. $desc_value = $weighdata[$desc_id];
  295. $sour_value = $weighdata[$sour_id];
  296. //echo "移动的ID:{$sour_id}\n";
  297. //echo "替换的ID:{$desc_id}\n";
  298. $weighids = array();
  299. $temp = array_values(array_diff_assoc($ids, $sour));
  300. foreach ($temp as $m => $n)
  301. {
  302. if ($n == $sour_id)
  303. {
  304. $offset = $desc_id;
  305. }
  306. else
  307. {
  308. if ($sour_id == $temp[0])
  309. {
  310. $offset = isset($temp[$m + 1]) ? $temp[$m + 1] : $sour_id;
  311. }
  312. else
  313. {
  314. $offset = isset($temp[$m - 1]) ? $temp[$m - 1] : $sour_id;
  315. }
  316. }
  317. $weighids[$n] = $weighdata[$offset];
  318. Db::name($table)->where($prikey, $n)->update([$field => $weighdata[$offset]]);
  319. }
  320. $this->code = 1;
  321. }
  322. }
  323. /**
  324. * 清空系统缓存
  325. */
  326. public function wipeCache()
  327. {
  328. $wipe_cache_type = ['TEMP_PATH', 'LOG_PATH', 'CACHE_PATH'];
  329. foreach ($wipe_cache_type as $item) {
  330. if ($item == 'LOG_PATH') {
  331. $dirs = (array) glob(constant($item) . '*');
  332. foreach ($dirs as $dir) {
  333. array_map('unlink', (array) glob($dir . DIRECTORY_SEPARATOR . '*.*'));
  334. }
  335. array_map('rmdir', $dirs);
  336. } else {
  337. array_map('unlink', (array) glob(constant($item) . DIRECTORY_SEPARATOR . '*.*'));
  338. }
  339. }
  340. Cache::clear();
  341. $this->success('清空系统缓存成功!');
  342. }
  343. }