Ajax.php 12 KB

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