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