Backend.php 16 KB

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