Backend.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. $this->relationSearch = true;
  40. //设置过滤方法
  41. $this->request->filter(['strip_tags']);
  42. if ($this->request->isAjax()) {
  43. //如果发送的来源是Selectpage,则转发到Selectpage
  44. if ($this->request->request('keyField')) {
  45. return $this->selectpage();
  46. }
  47. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  48. $total = $this->model
  49. ->where($where)
  50. ->order($sort, $order)
  51. ->count();
  52. $list = $this->model
  53. ->where($where)
  54. ->order($sort, $order)
  55. ->limit($offset, $limit)
  56. ->select();
  57. $list = collection($list)->toArray();
  58. $result = array("total" => $total, "rows" => $list);
  59. return json($result);
  60. }
  61. return $this->view->fetch();
  62. }
  63. /**
  64. * 回收站
  65. */
  66. public function recyclebin()
  67. {
  68. //设置过滤方法
  69. $this->request->filter(['strip_tags']);
  70. if ($this->request->isAjax()) {
  71. list($where, $sort, $order, $offset, $limit) = $this->buildparams();
  72. $total = $this->model
  73. ->onlyTrashed()
  74. ->where($where)
  75. ->order($sort, $order)
  76. ->count();
  77. $list = $this->model
  78. ->onlyTrashed()
  79. ->where($where)
  80. ->order($sort, $order)
  81. ->limit($offset, $limit)
  82. ->select();
  83. $result = array("total" => $total, "rows" => $list);
  84. return json($result);
  85. }
  86. return $this->view->fetch();
  87. }
  88. /**
  89. * 添加
  90. */
  91. public function add()
  92. {
  93. if ($this->request->isPost()) {
  94. $params = $this->request->post("row/a");
  95. if ($params) {
  96. $params = $this->preExcludeFields($params);
  97. if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
  98. $params[$this->dataLimitField] = $this->auth->id;
  99. }
  100. $result = false;
  101. Db::startTrans();
  102. try {
  103. //是否采用模型验证
  104. if ($this->modelValidate) {
  105. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  106. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
  107. $this->model->validateFailException(true)->validate($validate);
  108. }
  109. $result = $this->model->allowField(true)->save($params);
  110. Db::commit();
  111. } catch (ValidateException $e) {
  112. Db::rollback();
  113. $this->error($e->getMessage());
  114. } catch (PDOException $e) {
  115. Db::rollback();
  116. $this->error($e->getMessage());
  117. } catch (Exception $e) {
  118. Db::rollback();
  119. $this->error($e->getMessage());
  120. }
  121. if ($result !== false) {
  122. $this->success();
  123. } else {
  124. $this->error(__('No rows were inserted'));
  125. }
  126. }
  127. $this->error(__('Parameter %s can not be empty', ''));
  128. }
  129. return $this->view->fetch();
  130. }
  131. /**
  132. * 编辑
  133. */
  134. public function edit($ids = null)
  135. {
  136. $row = $this->model->get($ids);
  137. if (!$row) {
  138. $this->error(__('No Results were found'));
  139. }
  140. $adminIds = $this->getDataLimitAdminIds();
  141. if (is_array($adminIds)) {
  142. if (!in_array($row[$this->dataLimitField], $adminIds)) {
  143. $this->error(__('You have no permission'));
  144. }
  145. }
  146. if ($this->request->isPost()) {
  147. $params = $this->request->post("row/a");
  148. if ($params) {
  149. $params = $this->preExcludeFields($params);
  150. $result = false;
  151. Db::startTrans();
  152. try {
  153. //是否采用模型验证
  154. if ($this->modelValidate) {
  155. $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
  156. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
  157. $row->validateFailException(true)->validate($validate);
  158. }
  159. $result = $row->allowField(true)->save($params);
  160. Db::commit();
  161. } catch (ValidateException $e) {
  162. Db::rollback();
  163. $this->error($e->getMessage());
  164. } catch (PDOException $e) {
  165. Db::rollback();
  166. $this->error($e->getMessage());
  167. } catch (Exception $e) {
  168. Db::rollback();
  169. $this->error($e->getMessage());
  170. }
  171. if ($result !== false) {
  172. $this->success();
  173. } else {
  174. $this->error(__('No rows were updated'));
  175. }
  176. }
  177. $this->error(__('Parameter %s can not be empty', ''));
  178. }
  179. $this->view->assign("row", $row);
  180. return $this->view->fetch();
  181. }
  182. /**
  183. * 删除
  184. */
  185. public function del($ids = "")
  186. {
  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. if ($ids) {
  291. if ($this->request->has('params')) {
  292. parse_str($this->request->post("params"), $values);
  293. $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
  294. if ($values) {
  295. $adminIds = $this->getDataLimitAdminIds();
  296. if (is_array($adminIds)) {
  297. $this->model->where($this->dataLimitField, 'in', $adminIds);
  298. }
  299. $count = 0;
  300. Db::startTrans();
  301. try {
  302. $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
  303. foreach ($list as $index => $item) {
  304. $count += $item->allowField(true)->isUpdate(true)->save($values);
  305. }
  306. Db::commit();
  307. } catch (PDOException $e) {
  308. Db::rollback();
  309. $this->error($e->getMessage());
  310. } catch (Exception $e) {
  311. Db::rollback();
  312. $this->error($e->getMessage());
  313. }
  314. if ($count) {
  315. $this->success();
  316. } else {
  317. $this->error(__('No rows were updated'));
  318. }
  319. } else {
  320. $this->error(__('You have no permission'));
  321. }
  322. }
  323. }
  324. $this->error(__('Parameter %s can not be empty', 'ids'));
  325. }
  326. /**
  327. * 导入
  328. */
  329. protected function import()
  330. {
  331. $file = $this->request->request('file');
  332. if (!$file) {
  333. $this->error(__('Parameter %s can not be empty', 'file'));
  334. }
  335. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  336. if (!is_file($filePath)) {
  337. $this->error(__('No results were found'));
  338. }
  339. //实例化reader
  340. $ext = pathinfo($filePath, PATHINFO_EXTENSION);
  341. if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
  342. $this->error(__('Unknown data format'));
  343. }
  344. if ($ext === 'csv') {
  345. $file = fopen($filePath, 'r');
  346. $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
  347. $fp = fopen($filePath, "w");
  348. $n = 0;
  349. while ($line = fgets($file)) {
  350. $line = rtrim($line, "\n\r\0");
  351. $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
  352. if ($encoding != 'utf-8') {
  353. $line = mb_convert_encoding($line, 'utf-8', $encoding);
  354. }
  355. if ($n == 0 || preg_match('/^".*"$/', $line)) {
  356. fwrite($fp, $line . "\n");
  357. } else {
  358. fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
  359. }
  360. $n++;
  361. }
  362. fclose($file) || fclose($fp);
  363. $reader = new Csv();
  364. } elseif ($ext === 'xls') {
  365. $reader = new Xls();
  366. } else {
  367. $reader = new Xlsx();
  368. }
  369. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  370. $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  371. $table = $this->model->getQuery()->getTable();
  372. $database = \think\Config::get('database.database');
  373. $fieldArr = [];
  374. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  375. foreach ($list as $k => $v) {
  376. if ($importHeadType == 'comment') {
  377. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  378. } else {
  379. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  380. }
  381. }
  382. //加载文件
  383. $insert = [];
  384. try {
  385. if (!$PHPExcel = $reader->load($filePath)) {
  386. $this->error(__('Unknown data format'));
  387. }
  388. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  389. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  390. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  391. $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
  392. $fields = [];
  393. for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
  394. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  395. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  396. $fields[] = $val;
  397. }
  398. }
  399. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
  400. $values = [];
  401. for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
  402. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  403. $values[] = is_null($val) ? '' : $val;
  404. }
  405. $row = [];
  406. $temp = array_combine($fields, $values);
  407. foreach ($temp as $k => $v) {
  408. if (isset($fieldArr[$k]) && $k !== '') {
  409. $row[$fieldArr[$k]] = $v;
  410. }
  411. }
  412. if ($row) {
  413. $insert[] = $row;
  414. }
  415. }
  416. } catch (Exception $exception) {
  417. $this->error($exception->getMessage());
  418. }
  419. if (!$insert) {
  420. $this->error(__('No rows were updated'));
  421. }
  422. try {
  423. //是否包含admin_id字段
  424. $has_admin_id = false;
  425. foreach ($fieldArr as $name => $key) {
  426. if ($key == 'admin_id') {
  427. $has_admin_id = true;
  428. break;
  429. }
  430. }
  431. if ($has_admin_id) {
  432. $auth = Auth::instance();
  433. foreach ($insert as &$val) {
  434. if (!isset($val['admin_id']) || empty($val['admin_id'])) {
  435. $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
  436. }
  437. }
  438. }
  439. $this->model->saveAll($insert);
  440. } catch (PDOException $exception) {
  441. $msg = $exception->getMessage();
  442. if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
  443. $msg = "导入失败,包含【{$matches[1]}】的记录已存在";
  444. };
  445. $this->error($msg);
  446. } catch (Exception $e) {
  447. $this->error($e->getMessage());
  448. }
  449. $this->success();
  450. }
  451. }