Ajax.php 13 KB

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