Backend.php 16 KB

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