Backend.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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. use think\Exception;
  9. trait Backend
  10. {
  11. /**
  12. * 排除前台提交过来的字段
  13. * @param $params
  14. * @return array
  15. */
  16. protected function preExcludeFields($params)
  17. {
  18. if (is_array($this->excludeFields)) {
  19. foreach ($this->excludeFields as $field) {
  20. if (key_exists($field, $params)) {
  21. unset($params[$field]);
  22. }
  23. }
  24. } else {
  25. if (key_exists($this->excludeFields, $params)) {
  26. unset($params[$this->excludeFields]);
  27. }
  28. }
  29. return $params;
  30. }
  31. /**
  32. * 查看
  33. */
  34. public function index()
  35. {
  36. //设置过滤方法
  37. $this->request->filter(['strip_tags']);
  38. if ($this->request->isAjax()) {
  39. //如果发送的来源是Selectpage,则转发到Selectpage
  40. if ($this->request->request('keyField')) {
  41. return $this->selectpage();
  42. }
  43. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  44. $total = $this->model
  45. ->where($where)
  46. ->order($sort, $order)
  47. ->count();
  48. $list = $this->model
  49. ->where($where)
  50. ->order($sort, $order)
  51. ->limit($offset, $limit)
  52. ->select();
  53. $list = collection($list)->toArray();
  54. $result = array("total" => $total, "rows" => $list);
  55. return json($result);
  56. }
  57. return $this->view->fetch();
  58. }
  59. /**
  60. * 回收站
  61. */
  62. public function recyclebin()
  63. {
  64. //设置过滤方法
  65. $this->request->filter(['strip_tags']);
  66. if ($this->request->isAjax()) {
  67. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  68. $total = $this->model
  69. ->onlyTrashed()
  70. ->where($where)
  71. ->order($sort, $order)
  72. ->count();
  73. $list = $this->model
  74. ->onlyTrashed()
  75. ->where($where)
  76. ->order($sort, $order)
  77. ->limit($offset, $limit)
  78. ->select();
  79. $result = array("total" => $total, "rows" => $list);
  80. return json($result);
  81. }
  82. return $this->view->fetch();
  83. }
  84. /**
  85. * 添加
  86. */
  87. public function add()
  88. {
  89. if ($this->request->isPost()) {
  90. $params = $this->request->post("row/a");
  91. if ($params) {
  92. $params = $this->preExcludeFields($params);
  93. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  94. $params[$this->dataLimitField] = $this->auth->id;
  95. }
  96. try {
  97. //是否采用模型验证
  98. if ($this->modelValidate) {
  99. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  100. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  101. $this->model->validate($validate);
  102. }
  103. $result = $this->model->allowField(true)->save($params);
  104. if ($result !== false) {
  105. $this->success();
  106. } else {
  107. $this->error($this->model->getError());
  108. }
  109. } catch (\think\exception\PDOException $e) {
  110. $this->error($e->getMessage());
  111. } catch (\think\Exception $e) {
  112. $this->error($e->getMessage());
  113. }
  114. }
  115. $this->error(__('Parameter %s can not be empty', ''));
  116. }
  117. return $this->view->fetch();
  118. }
  119. /**
  120. * 编辑
  121. */
  122. public function edit($ids = null)
  123. {
  124. $row = $this->model->get($ids);
  125. if (!$row) {
  126. $this->error(__('No Results were found'));
  127. }
  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. }