Backend.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace app\admin\library\traits;
  3. trait Backend
  4. {
  5. /**
  6. * 排除前台提交过来的字段
  7. * @param $params
  8. * @return array
  9. */
  10. private function preExcludeFields($params)
  11. {
  12. if (is_array($this->excludeFields)) {
  13. foreach ($this->excludeFields as $field) {
  14. if (key_exists($field,$params))
  15. {
  16. unset($params[$field]);
  17. }
  18. }
  19. } else {
  20. if (key_exists($this->excludeFields,$params))
  21. {
  22. unset($params[$this->excludeFields]);
  23. }
  24. }
  25. return $params;
  26. }
  27. /**
  28. * 查看
  29. */
  30. public function index()
  31. {
  32. //设置过滤方法
  33. $this->request->filter(['strip_tags']);
  34. if ($this->request->isAjax()) {
  35. //如果发送的来源是Selectpage,则转发到Selectpage
  36. if ($this->request->request('keyField')) {
  37. return $this->selectpage();
  38. }
  39. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  40. $total = $this->model
  41. ->where($where)
  42. ->order($sort, $order)
  43. ->count();
  44. $list = $this->model
  45. ->where($where)
  46. ->order($sort, $order)
  47. ->limit($offset, $limit)
  48. ->select();
  49. $list = collection($list)->toArray();
  50. $result = array("total" => $total, "rows" => $list);
  51. return json($result);
  52. }
  53. return $this->view->fetch();
  54. }
  55. /**
  56. * 回收站
  57. */
  58. public function recyclebin()
  59. {
  60. //设置过滤方法
  61. $this->request->filter(['strip_tags']);
  62. if ($this->request->isAjax()) {
  63. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  64. $total = $this->model
  65. ->onlyTrashed()
  66. ->where($where)
  67. ->order($sort, $order)
  68. ->count();
  69. $list = $this->model
  70. ->onlyTrashed()
  71. ->where($where)
  72. ->order($sort, $order)
  73. ->limit($offset, $limit)
  74. ->select();
  75. $result = array("total" => $total, "rows" => $list);
  76. return json($result);
  77. }
  78. return $this->view->fetch();
  79. }
  80. /**
  81. * 添加
  82. */
  83. public function add()
  84. {
  85. if ($this->request->isPost()) {
  86. $params = $this->request->post("row/a");
  87. if ($params) {
  88. $params = $this->preExcludeFields($params);
  89. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  90. $params[$this->dataLimitField] = $this->auth->id;
  91. }
  92. try {
  93. //是否采用模型验证
  94. if ($this->modelValidate) {
  95. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  96. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  97. $this->model->validate($validate);
  98. }
  99. $result = $this->model->allowField(true)->save($params);
  100. if ($result !== false) {
  101. $this->success();
  102. } else {
  103. $this->error($this->model->getError());
  104. }
  105. } catch (\think\exception\PDOException $e) {
  106. $this->error($e->getMessage());
  107. } catch (\think\Exception $e) {
  108. $this->error($e->getMessage());
  109. }
  110. }
  111. $this->error(__('Parameter %s can not be empty', ''));
  112. }
  113. return $this->view->fetch();
  114. }
  115. /**
  116. * 编辑
  117. */
  118. public function edit($ids = NULL)
  119. {
  120. $row = $this->model->get($ids);
  121. if (!$row)
  122. $this->error(__('No Results were found'));
  123. $adminIds = $this->getDataLimitAdminIds();
  124. if (is_array($adminIds)) {
  125. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  126. $this->error(__('You have no permission'));
  127. }
  128. }
  129. if ($this->request->isPost()) {
  130. $params = $this->request->post("row/a");
  131. if ($params) {
  132. $params = $this->preExcludeFields($params);
  133. try {
  134. //是否采用模型验证
  135. if ($this->modelValidate) {
  136. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  137. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  138. $row->validate($validate);
  139. }
  140. $result = $row->allowField(true)->save($params);
  141. if ($result !== false) {
  142. $this->success();
  143. } else {
  144. $this->error($row->getError());
  145. }
  146. } catch (\think\exception\PDOException $e) {
  147. $this->error($e->getMessage());
  148. } catch (\think\Exception $e) {
  149. $this->error($e->getMessage());
  150. }
  151. }
  152. $this->error(__('Parameter %s can not be empty', ''));
  153. }
  154. $this->view->assign("row", $row);
  155. return $this->view->fetch();
  156. }
  157. /**
  158. * 删除
  159. */
  160. public function del($ids = "")
  161. {
  162. if ($ids) {
  163. $pk = $this->model->getPk();
  164. $adminIds = $this->getDataLimitAdminIds();
  165. if (is_array($adminIds)) {
  166. $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
  167. }
  168. $list = $this->model->where($pk, 'in', $ids)->select();
  169. $count = 0;
  170. foreach ($list as $k => $v) {
  171. $count += $v->delete();
  172. }
  173. if ($count) {
  174. $this->success();
  175. } else {
  176. $this->error(__('No rows were deleted'));
  177. }
  178. }
  179. $this->error(__('Parameter %s can not be empty', 'ids'));
  180. }
  181. /**
  182. * 真实删除
  183. */
  184. public function destroy($ids = "")
  185. {
  186. $pk = $this->model->getPk();
  187. $adminIds = $this->getDataLimitAdminIds();
  188. if (is_array($adminIds)) {
  189. $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
  190. }
  191. if ($ids) {
  192. $this->model->where($pk, 'in', $ids);
  193. }
  194. $count = 0;
  195. $list = $this->model->onlyTrashed()->select();
  196. foreach ($list as $k => $v) {
  197. $count += $v->delete(true);
  198. }
  199. if ($count) {
  200. $this->success();
  201. } else {
  202. $this->error(__('No rows were deleted'));
  203. }
  204. $this->error(__('Parameter %s can not be empty', 'ids'));
  205. }
  206. /**
  207. * 还原
  208. */
  209. public function restore($ids = "")
  210. {
  211. $pk = $this->model->getPk();
  212. $adminIds = $this->getDataLimitAdminIds();
  213. if (is_array($adminIds)) {
  214. $this->model->where($this->dataLimitField, 'in', $adminIds);
  215. }
  216. if ($ids) {
  217. $this->model->where($pk, 'in', $ids);
  218. }
  219. $count = 0;
  220. $list = $this->model->onlyTrashed()->select();
  221. foreach ($list as $index => $item) {
  222. $count += $item->restore();
  223. }
  224. if ($count) {
  225. $this->success();
  226. }
  227. $this->error(__('No rows were updated'));
  228. }
  229. /**
  230. * 批量更新
  231. */
  232. public function multi($ids = "")
  233. {
  234. $ids = $ids ? $ids : $this->request->param("ids");
  235. if ($ids) {
  236. if ($this->request->has('params')) {
  237. parse_str($this->request->post("params"), $values);
  238. if (!$this->auth->isSuperAdmin()) {
  239. $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
  240. }
  241. if ($values) {
  242. $adminIds = $this->getDataLimitAdminIds();
  243. if (is_array($adminIds)) {
  244. $this->model->where($this->dataLimitField, 'in', $adminIds);
  245. }
  246. $count = 0;
  247. $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  248. foreach ($list as $index => $item) {
  249. $count += $item->allowField(true)->isUpdate(true)->save($values);
  250. }
  251. if ($count) {
  252. $this->success();
  253. } else {
  254. $this->error(__('No rows were updated'));
  255. }
  256. } else {
  257. $this->error(__('You have no permission'));
  258. }
  259. }
  260. }
  261. $this->error(__('Parameter %s can not be empty', 'ids'));
  262. }
  263. /**
  264. * 导入
  265. */
  266. protected function import()
  267. {
  268. $file = $this->request->request('file');
  269. if (!$file) {
  270. $this->error(__('Parameter %s can not be empty', 'file'));
  271. }
  272. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  273. if (!is_file($filePath)) {
  274. $this->error(__('No results were found'));
  275. }
  276. $PHPReader = new \PHPExcel_Reader_Excel2007();
  277. if (!$PHPReader->canRead($filePath)) {
  278. $PHPReader = new \PHPExcel_Reader_Excel5();
  279. if (!$PHPReader->canRead($filePath)) {
  280. $PHPReader = new \PHPExcel_Reader_CSV();
  281. if (!$PHPReader->canRead($filePath)) {
  282. $this->error(__('Unknown data format'));
  283. }
  284. }
  285. }
  286. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  287. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  288. $table = $this->model->getQuery()->getTable();
  289. $database = \think\Config::get('database.database');
  290. $fieldArr = [];
  291. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  292. foreach ($list as $k => $v) {
  293. if ($importHeadType == 'comment') {
  294. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  295. } else {
  296. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  297. }
  298. }
  299. $PHPExcel = $PHPReader->load($filePath); //加载文件
  300. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  301. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  302. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  303. $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
  304. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  305. for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
  306. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  307. $fields[] = $val;
  308. }
  309. }
  310. $insert = [];
  311. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  312. $values = [];
  313. for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++) {
  314. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  315. $values[] = is_null($val) ? '' : $val;
  316. }
  317. $row = [];
  318. $temp = array_combine($fields, $values);
  319. foreach ($temp as $k => $v) {
  320. if (isset($fieldArr[$k]) && $k !== '') {
  321. $row[$fieldArr[$k]] = $v;
  322. }
  323. }
  324. if ($row) {
  325. $insert[] = $row;
  326. }
  327. }
  328. if (!$insert) {
  329. $this->error(__('No rows were updated'));
  330. }
  331. try {
  332. $this->model->saveAll($insert);
  333. } catch (\think\exception\PDOException $exception) {
  334. $this->error($exception->getMessage());
  335. } catch (\Exception $e) {
  336. $this->error($e->getMessage());
  337. }
  338. $this->success();
  339. }
  340. }