Backend.php 17 KB

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