Material.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. <?php
  2. namespace app\admin\controller\ad;
  3. use app\admin\service\LogService;
  4. use app\common\controller\Backend;
  5. use app\common\library\Redis;
  6. use app\common\model\AdMaterial;
  7. use app\main\constants\AdConstants;
  8. use think\Controller;
  9. use think\Request;
  10. /**
  11. * 广告系统素材库
  12. *
  13. * @icon fa fa-circle-o
  14. */
  15. class Material extends Backend
  16. {
  17. /**
  18. * AdMaterial模型对象
  19. */
  20. protected $model = null;
  21. public function _initialize()
  22. {
  23. parent::_initialize();
  24. /**
  25. * @var AdMaterial
  26. */
  27. $this->model = model('AdMaterial');
  28. $this->assign('materialPositons', $this->model->getMaterialPositions()); //素材展示位置
  29. }
  30. /**
  31. * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
  32. * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
  33. * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
  34. */
  35. /**
  36. * 添加
  37. */
  38. public function add()
  39. {
  40. if ($this->request->isPost())
  41. {
  42. $params = $this->request->post("row/a");
  43. if ($params)
  44. {
  45. /*
  46. * 已经弃用,如果为了兼容老版可取消注释
  47. foreach ($params as $k => &$v)
  48. {
  49. $v = is_array($v) ? implode(',', $v) : $v;
  50. }
  51. */
  52. if ($this->dataLimit)
  53. {
  54. $params[$this->dataLimitField] = $this->auth->id;
  55. }
  56. try
  57. {
  58. //是否采用模型验证
  59. if ($this->modelValidate)
  60. {
  61. $name = basename(str_replace('\\', '/', get_class($this->model)));
  62. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
  63. $this->model->validate($validate);
  64. }
  65. $params['material_position'] = implode(',', $params['material_position']);
  66. $this->_formatParams($params);
  67. $this->_validateParams($params);
  68. // 分身
  69. try{
  70. $shapeParams = $this->_shapeShift($params);
  71. foreach ($shapeParams as $k => $shape){
  72. $this->model->allowField(true)->insert($shape);
  73. }
  74. $result = true;
  75. }catch (\Exception $exception){
  76. LogService::error($exception->getMessage());
  77. }
  78. if ($result !== false)
  79. {
  80. $this->success();
  81. }
  82. else
  83. {
  84. $this->error($this->model->getError());
  85. }
  86. }
  87. catch (\think\exception\PDOException $e)
  88. {
  89. $this->error($e->getMessage());
  90. }
  91. }
  92. $this->error(__('Parameter %s can not be empty', ''));
  93. }
  94. return $this->view->fetch();
  95. }
  96. /**
  97. * 编辑
  98. */
  99. public function edit($ids = NULL)
  100. {
  101. $row = $this->model->get($ids);
  102. if (!$row)
  103. $this->error(__('No Results were found'));
  104. $adminIds = $this->getDataLimitAdminIds();
  105. if (is_array($adminIds))
  106. {
  107. if (!in_array($row[$this->dataLimitField], $adminIds))
  108. {
  109. $this->error(__('You have no permission'));
  110. }
  111. }
  112. if ($this->request->isPost())
  113. {
  114. $params = $this->request->post("row/a");
  115. if ($params)
  116. {
  117. /*
  118. * 已经弃用,如果为了兼容老版可取消注释
  119. foreach ($params as $k => &$v)
  120. {
  121. $v = is_array($v) ? implode(',', $v) : $v;
  122. }
  123. */
  124. try
  125. {
  126. //是否采用模型验证
  127. if ($this->modelValidate)
  128. {
  129. $name = basename(str_replace('\\', '/', get_class($this->model)));
  130. $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
  131. $row->validate($validate);
  132. }
  133. $params['material_position'] = implode(',', $params['material_position']);
  134. $this->_formatParams($params);
  135. $this->_validateParams($params);
  136. $result = $row->allowField(true)->save($params);
  137. if ($result !== false)
  138. {
  139. $this->success();
  140. }
  141. else
  142. {
  143. $this->error($row->getError());
  144. }
  145. }
  146. catch (\think\exception\PDOException $e)
  147. {
  148. $this->error($e->getMessage());
  149. }
  150. }
  151. $this->error(__('Parameter %s can not be empty', ''));
  152. }
  153. $this->view->assign("row", $row);
  154. $this->view->assign('material_position', explode(',', $row->material_position));
  155. return $this->view->fetch();
  156. }
  157. /**
  158. * @param $params
  159. * 格式化表单提交数据
  160. */
  161. private function _formatParams(&$params)
  162. {
  163. if($params['type'] == 3){
  164. $params['img_url'] ='';
  165. $params['link_url'] ='';
  166. $params['js_code'] ='';
  167. $params['ad_baidu'] = '';
  168. $params['material_position'] = '';
  169. }elseif ($params['type'] == 2){
  170. $params['img_url'] ='';
  171. $params['link_url'] ='';
  172. $params['js_code'] ='';
  173. $params['link_game'] = '';
  174. $this->_filterPosition($params);
  175. }elseif ($params['type'] == 1){
  176. $params['img_url'] ='';
  177. $params['link_url'] ='';
  178. $params['ad_baidu'] = '';
  179. $params['link_game'] = '';
  180. $this->_filterPosition($params);
  181. }else{
  182. $params['js_code'] ='';
  183. $params['ad_baidu'] = '';
  184. $params['link_game'] = '';
  185. }
  186. }
  187. // 如果素材是 JS链接 或者是百度联盟广告,过滤掉位置
  188. private function _filterPosition(&$params)
  189. {
  190. $position_arr = explode(',', $params['material_position']);
  191. $position_arr = array_diff($position_arr, [AdConstants::AD_P_INDEX_FLOAT_FRAME, AdConstants::AD_P_DETAIL_FLOAT_FRAME]);
  192. $params['material_position'] = implode(',', $position_arr);
  193. }
  194. /**
  195. * 校验数据是否正确
  196. * @param $params
  197. */
  198. private function _validateParams(&$params)
  199. {
  200. if ($params['type'] == 3) {
  201. if (empty(trim($params['link_game']))) {
  202. $this->error('请填写福利广告地址');
  203. }
  204. } elseif ($params['type'] == 2) {
  205. if (empty(trim($params['ad_baidu']))) {
  206. $this->error('请填写百度联盟广告ID');
  207. }
  208. } elseif ($params['type'] == 1) {
  209. if (empty(trim($params['js_code']))) {
  210. $this->error('JS代码块为必填项');
  211. }
  212. } else {
  213. if (empty($params['img_url'])) {
  214. $this->error('请选择图片');
  215. }
  216. if (empty($params['link_url'])) {
  217. $this->error('请填写链接地址');
  218. }
  219. }
  220. // (除福利广告)广告位必须选择
  221. if ($params['type'] != 3) {
  222. if (empty($params['material_position'])) {
  223. $this->error('请选择展示位置');
  224. }
  225. }
  226. }
  227. /**
  228. * 分身术
  229. * @param $params
  230. * @return array
  231. */
  232. private function _shapeShift($params)
  233. {
  234. $targetParams = [];
  235. $params['show_starttime'] = $this->model->setShowStarttimeAttr($params['show_starttime']);
  236. $params['show_endtime'] = $this->model->setShowStarttimeAttr($params['show_endtime']);
  237. $params['createtime'] = time();
  238. $params['updatetime'] = time();
  239. if ($params['type'] == 0) {
  240. $img_urls = explode(',', $params['img_url']);
  241. foreach ($img_urls as $img_url) {
  242. $item = $params;
  243. $item['img_url'] = $img_url;
  244. array_push($targetParams, $item);
  245. }
  246. } elseif ($params['type'] == 3) {
  247. // 福利广告
  248. $link_games = explode("\r\n", $params['link_game']);
  249. $link_games = array_filter($link_games);
  250. foreach ($link_games as $link_game) {
  251. $item = $params;
  252. $item['link_game'] = $link_game;
  253. array_push($targetParams, $item);
  254. }
  255. }else{
  256. array_push($targetParams, $params);
  257. }
  258. return $targetParams;
  259. }
  260. /**
  261. * 删除
  262. */
  263. public function del($ids = "")
  264. {
  265. if ($ids)
  266. {
  267. $pk = $this->model->getPk();
  268. $adminIds = $this->getDataLimitAdminIds();
  269. if (is_array($adminIds))
  270. {
  271. $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
  272. }
  273. $list = $this->model->where($pk, 'in', $ids)->select();
  274. $count = 0;
  275. foreach ($list as $k => $v)
  276. {
  277. $count += $v->delete();
  278. }
  279. if ($count)
  280. {
  281. $this->success();
  282. }
  283. else
  284. {
  285. $this->error(__('No rows were deleted'));
  286. }
  287. }
  288. $this->error(__('Parameter %s can not be empty', 'ids'));
  289. }
  290. /**
  291. * 批量生效 | 批量失效
  292. */
  293. public function batchValidate()
  294. {
  295. $params = $this->request->param();
  296. $ids = $params['ids'];
  297. $state = $params['state'];
  298. if (is_array($ids)) {
  299. foreach ($ids as $id) {
  300. $result = $this->model->update(['state' => $state], ['id' => $id]);
  301. }
  302. } else {
  303. $result = $this->model->update(['state' => $state], ['id' => $ids]);
  304. }
  305. if($result){
  306. $this->success('设置成功');
  307. }else{
  308. $this->error('设置失败');
  309. }
  310. }
  311. /**
  312. * 导入
  313. */
  314. public function import()
  315. {
  316. $file = $this->request->request('file');
  317. if (!$file)
  318. {
  319. $this->error(__('Parameter %s can not be empty', 'file'));
  320. }
  321. $filePath = ROOT_PATH . DS . 'public' . DS . $file;
  322. if (!is_file($filePath))
  323. {
  324. $this->error(__('No results were found'));
  325. }
  326. $PHPReader = new \PHPExcel_Reader_Excel2007();
  327. if (!$PHPReader->canRead($filePath))
  328. {
  329. $PHPReader = new \PHPExcel_Reader_Excel5();
  330. if (!$PHPReader->canRead($filePath))
  331. {
  332. $PHPReader = new \PHPExcel_Reader_CSV();
  333. if (!$PHPReader->canRead($filePath))
  334. {
  335. $this->error(__('Unknown data format'));
  336. }
  337. }
  338. }
  339. //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
  340. /*$importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
  341. $table = $this->model->getQuery()->getTable();
  342. $database = \think\Config::get('database.database');
  343. $fieldArr = [];
  344. $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
  345. foreach ($list as $k => $v)
  346. {
  347. if ($importHeadType == 'comment')
  348. {
  349. $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
  350. }
  351. else
  352. {
  353. $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
  354. }
  355. }*/
  356. $fieldArr = [
  357. 'id'=>'id',
  358. '图片URL'=>'img_url',
  359. '链接URL'=>'link_url',
  360. '展示页面位置'=>'material_position',
  361. '展示开始时间'=>'show_starttime',
  362. '展示结束时间'=>'show_endtime',
  363. '权重'=>'weight',
  364. '状态'=>'state',
  365. '创建时间'=>'createtime',
  366. '更新时间'=>'updatetime'
  367. ];
  368. $PHPExcel = $PHPReader->load($filePath); //加载文件
  369. $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
  370. $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
  371. $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
  372. $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
  373. for ($currentRow = 1; $currentRow <= 1; $currentRow++)
  374. {
  375. for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
  376. {
  377. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  378. $fields[] = $val;
  379. }
  380. }
  381. $insert = [];
  382. for ($currentRow = 2; $currentRow <= $allRow; $currentRow++)
  383. {
  384. $values = [];
  385. for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
  386. {
  387. $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
  388. $values[] = is_null($val) ? '' : $val;
  389. }
  390. $row = [];
  391. $temp = array_combine($fields, $values);
  392. foreach ($temp as $k => $v)
  393. {
  394. if (isset($fieldArr[$k]) && $k !== '')
  395. {
  396. $row[$fieldArr[$k]] = $v;
  397. }
  398. }
  399. if ($row)
  400. {
  401. $insert[] = $row;
  402. }
  403. }
  404. if (!$insert)
  405. {
  406. $this->error(__('No rows were updated'));
  407. }
  408. try
  409. {
  410. $this->model->saveAll($insert);
  411. }
  412. catch (\think\exception\PDOException $exception)
  413. {
  414. $this->error($exception->getMessage());
  415. }
  416. $this->success();
  417. }
  418. }