Ajax.php 12 KB

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