Backend.php 17 KB

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