Backend.php 17 KB

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