Video.php 16 KB

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