Backend.php 14 KB

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