Backend.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. if (!$this->request->isPost()) {
  187. $this->error(__("Invalid parameters"));
  188. }
  189. $ids = $ids ? $ids : $this->request->post("ids");
  190. if ($ids) {
  191. $pk = $this->model->getPk();
  192. $adminIds = $this->getDataLimitAdminIds();
  193. if (is_array($adminIds)) {
  194. $this->model->where($this->dataLimitField, 'in', $adminIds);
  195. }
  196. $list = $this->model->where($pk, 'in', $ids)->select();
  197. $count = 0;
  198. Db::startTrans();
  199. try {
  200. foreach ($list as $k => $v) {
  201. $count += $v->delete();
  202. }
  203. Db::commit();
  204. } catch (PDOException $e) {
  205. Db::rollback();
  206. $this->error($e->getMessage());
  207. } catch (Exception $e) {
  208. Db::rollback();
  209. $this->error($e->getMessage());
  210. }
  211. if ($count) {
  212. $this->success();
  213. } else {
  214. $this->error(__('No rows were deleted'));
  215. }
  216. }
  217. $this->error(__('Parameter %s can not be empty', 'ids'));
  218. }
  219. /**
  220. * 真实删除
  221. */
  222. public function destroy($ids = "")
  223. {
  224. if (!$this->request->isPost()) {
  225. $this->error(__("Invalid parameters"));
  226. }
  227. $ids = $ids ? $ids : $this->request->post("ids");
  228. $pk = $this->model->getPk();
  229. $adminIds = $this->getDataLimitAdminIds();
  230. if (is_array($adminIds)) {
  231. $this->model->where($this->dataLimitField, 'in', $adminIds);
  232. }
  233. if ($ids) {
  234. $this->model->where($pk, 'in', $ids);
  235. }
  236. $count = 0;
  237. Db::startTrans();
  238. try {
  239. $list = $this->model->onlyTrashed()->select();
  240. foreach ($list as $k => $v) {
  241. $count += $v->delete(true);
  242. }
  243. Db::commit();
  244. } catch (PDOException $e) {
  245. Db::rollback();
  246. $this->error($e->getMessage());
  247. } catch (Exception $e) {
  248. Db::rollback();
  249. $this->error($e->getMessage());
  250. }
  251. if ($count) {
  252. $this->success();
  253. } else {
  254. $this->error(__('No rows were deleted'));
  255. }
  256. $this->error(__('Parameter %s can not be empty', 'ids'));
  257. }
  258. /**
  259. * 还原
  260. */
  261. public function restore($ids = "")
  262. {
  263. if (!$this->request->isPost()) {
  264. $this->error(__("Invalid parameters"));
  265. }
  266. $ids = $ids ? $ids : $this->request->post("ids");
  267. $pk = $this->model->getPk();
  268. $adminIds = $this->getDataLimitAdminIds();
  269. if (is_array($adminIds)) {
  270. $this->model->where($this->dataLimitField, 'in', $adminIds);
  271. }
  272. if ($ids) {
  273. $this->model->where($pk, 'in', $ids);
  274. }
  275. $count = 0;
  276. Db::startTrans();
  277. try {
  278. $list = $this->model->onlyTrashed()->select();
  279. foreach ($list as $index => $item) {
  280. $count += $item->restore();
  281. }
  282. Db::commit();
  283. } catch (PDOException $e) {
  284. Db::rollback();
  285. $this->error($e->getMessage());
  286. } catch (Exception $e) {
  287. Db::rollback();
  288. $this->error($e->getMessage());
  289. }
  290. if ($count) {
  291. $this->success();
  292. }
  293. $this->error(__('No rows were updated'));
  294. }
  295. /**
  296. * 批量更新
  297. */
  298. public function multi($ids = "")
  299. {
  300. if (!$this->request->isPost()) {
  301. $this->error(__("Invalid parameters"));
  302. }
  303. $ids = $ids ? $ids : $this->request->post("ids");
  304. if ($ids) {
  305. if ($this->request->has('params')) {
  306. parse_str($this->request->post("params"), $values);
  307. $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
  308. if ($values) {
  309. $adminIds = $this->getDataLimitAdminIds();
  310. if (is_array($adminIds)) {
  311. $this->model->where($this->dataLimitField, 'in', $adminIds);
  312. }
  313. $count = 0;
  314. Db::startTrans();
  315. try {
  316. $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  317. foreach ($list as $index => $item) {
  318. $count += $item->allowField(true)->isUpdate(true)->save($values);
  319. }
  320. Db::commit();
  321. } catch (PDOException $e) {
  322. Db::rollback();
  323. $this->error($e->getMessage());
  324. } catch (Exception $e) {
  325. Db::rollback();
  326. $this->error($e->getMessage());
  327. }
  328. if ($count) {
  329. $this->success();
  330. } else {
  331. $this->error(__('No rows were updated'));
  332. }
  333. } else {
  334. $this->error(__('You have no permission'));
  335. }
  336. }
  337. }
  338. $this->error(__('Parameter %s can not be empty', 'ids'));
  339. }
  340. /**
  341. * 导入
  342. */
  343. protected function import()
  344. {
  345. $file = $this->request->request('file');
  346. if (!$file) {
  347. $this->error(__('Parameter %s can not be empty', 'file'));
  348. }
  349. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  350. if (!is_file($filePath)) {
  351. $this->error(__('No results were found'));
  352. }
  353. //实例化reader
  354. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  355. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  356. $this->error(__('Unknown data format'));
  357. }
  358. if ($ext === 'csv') {
  359. $file = fopen($filePath, 'r');
  360. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  361. $fp = fopen($filePath, "w");
  362. $n = 0;
  363. while ($line = fgets($file)) {
  364. $line = rtrim($line, "\n\r\0");
  365. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  366. if ($encoding != 'utf-8') {
  367. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  368. }
  369. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  370. fwrite($fp, $line . "\n");
  371. } else {
  372. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  373. }
  374. $n++;
  375. }
  376. fclose($file) || fclose($fp);
  377. $reader = new Csv();
  378. } elseif ($ext === 'xls') {
  379. $reader = new Xls();
  380. } else {
  381. $reader = new Xlsx();
  382. }
  383. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  384. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  385. $table = $this->model->getQuery()->getTable();
  386. $database = \think\Config::get('database.database');
  387. $fieldArr = [];
  388. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  389. foreach ($list as $k => $v) {
  390. if ($importHeadType == 'comment') {
  391. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  392. } else {
  393. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  394. }
  395. }
  396. //加载文件
  397. $insert = [];
  398. try {
  399. if (!$PHPExcel = $reader->load($filePath)) {
  400. $this->error(__('Unknown data format'));
  401. }
  402. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  403. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  404. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  405. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  406. $fields = [];
  407. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  408. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  409. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  410. $fields[] = $val;
  411. }
  412. }
  413. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  414. $values = [];
  415. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  416. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  417. $values[] = is_null($val) ? '' : $val;
  418. }
  419. $row = [];
  420. $temp = array_combine($fields, $values);
  421. foreach ($temp as $k => $v) {
  422. if (isset($fieldArr[$k]) && $k !== '') {
  423. $row[$fieldArr[$k]] = $v;
  424. }
  425. }
  426. if ($row) {
  427. $insert[] = $row;
  428. }
  429. }
  430. } catch (Exception $exception) {
  431. $this->error($exception->getMessage());
  432. }
  433. if (!$insert) {
  434. $this->error(__('No rows were updated'));
  435. }
  436. try {
  437. //是否包含admin_id字段
  438. $has_admin_id = false;
  439. foreach ($fieldArr as $name => $key) {
  440. if ($key == 'admin_id') {
  441. $has_admin_id = true;
  442. break;
  443. }
  444. }
  445. if ($has_admin_id) {
  446. $auth = Auth::instance();
  447. foreach ($insert as &$val) {
  448. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  449. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  450. }
  451. }
  452. }
  453. $this->model->saveAll($insert);
  454. } catch (PDOException $exception) {
  455. $msg = $exception->getMessage();
  456. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  457. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  458. };
  459. $this->error($msg);
  460. } catch (Exception $e) {
  461. $this->error($e->getMessage());
  462. }
  463. $this->success();
  464. }
  465. }