Backend.php 16 KB

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