Backend.php 17 KB

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