Backend.php 17 KB

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