123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456 |
- <?php
- namespace app\admin\controller\ad;
- use app\admin\service\LogService;
- use app\common\controller\Backend;
- use app\common\library\Redis;
- use app\common\model\AdMaterial;
- use app\main\constants\AdConstants;
- use think\Controller;
- use think\Request;
- /**
- * 广告系统素材库
- *
- * @icon fa fa-circle-o
- */
- class Material extends Backend
- {
- /**
- * AdMaterial模型对象
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- /**
- * @var AdMaterial
- */
- $this->model = model('AdMaterial');
- $this->assign('materialPositons', $this->model->getMaterialPositions()); //素材展示位置
- }
- /**
- * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
- * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
- * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
- */
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- /*
- * 已经弃用,如果为了兼容老版可取消注释
- foreach ($params as $k => &$v)
- {
- $v = is_array($v) ? implode(',', $v) : $v;
- }
- */
- if ($this->dataLimit)
- {
- $params[$this->dataLimitField] = $this->auth->id;
- }
- try
- {
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
- $this->model->validate($validate);
- }
- $params['material_position'] = implode(',', $params['material_position']);
- $this->_formatParams($params);
- $this->_validateParams($params);
- // 分身
- try{
- $shapeParams = $this->_shapeShift($params);
- foreach ($shapeParams as $k => $shape){
- $this->model->allowField(true)->insert($shape);
- }
- $result = true;
- }catch (\Exception $exception){
- LogService::error($exception->getMessage());
- }
- if ($result !== false)
- {
- $this->success();
- }
- else
- {
- $this->error($this->model->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- return $this->view->fetch();
- }
- /**
- * 编辑
- */
- public function edit($ids = NULL)
- {
- $row = $this->model->get($ids);
- if (!$row)
- $this->error(__('No Results were found'));
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- if (!in_array($row[$this->dataLimitField], $adminIds))
- {
- $this->error(__('You have no permission'));
- }
- }
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- /*
- * 已经弃用,如果为了兼容老版可取消注释
- foreach ($params as $k => &$v)
- {
- $v = is_array($v) ? implode(',', $v) : $v;
- }
- */
- try
- {
- //是否采用模型验证
- if ($this->modelValidate)
- {
- $name = basename(str_replace('\\', '/', get_class($this->model)));
- $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
- $row->validate($validate);
- }
- $params['material_position'] = implode(',', $params['material_position']);
- $this->_formatParams($params);
- $this->_validateParams($params);
- $result = $row->allowField(true)->save($params);
- if ($result !== false)
- {
- $this->success();
- }
- else
- {
- $this->error($row->getError());
- }
- }
- catch (\think\exception\PDOException $e)
- {
- $this->error($e->getMessage());
- }
- }
- $this->error(__('Parameter %s can not be empty', ''));
- }
- $this->view->assign("row", $row);
- $this->view->assign('material_position', explode(',', $row->material_position));
- return $this->view->fetch();
- }
- /**
- * @param $params
- * 格式化表单提交数据
- */
- private function _formatParams(&$params)
- {
- if($params['type'] == 3){
- $params['img_url'] ='';
- $params['link_url'] ='';
- $params['js_code'] ='';
- $params['ad_baidu'] = '';
- $params['material_position'] = '';
- }elseif ($params['type'] == 2){
- $params['img_url'] ='';
- $params['link_url'] ='';
- $params['js_code'] ='';
- $params['link_game'] = '';
- $this->_filterPosition($params);
- }elseif ($params['type'] == 1){
- $params['img_url'] ='';
- $params['link_url'] ='';
- $params['ad_baidu'] = '';
- $params['link_game'] = '';
- $this->_filterPosition($params);
- }else{
- $params['js_code'] ='';
- $params['ad_baidu'] = '';
- $params['link_game'] = '';
- }
- }
- // 如果素材是 JS链接 或者是百度联盟广告,过滤掉位置
- private function _filterPosition(&$params)
- {
- $position_arr = explode(',', $params['material_position']);
- $position_arr = array_diff($position_arr, [AdConstants::AD_P_INDEX_FLOAT_FRAME, AdConstants::AD_P_DETAIL_FLOAT_FRAME]);
- $params['material_position'] = implode(',', $position_arr);
- }
- /**
- * 校验数据是否正确
- * @param $params
- */
- private function _validateParams(&$params)
- {
- if ($params['type'] == 3) {
- if (empty(trim($params['link_game']))) {
- $this->error('请填写福利广告地址');
- }
- } elseif ($params['type'] == 2) {
- if (empty(trim($params['ad_baidu']))) {
- $this->error('请填写百度联盟广告ID');
- }
- } elseif ($params['type'] == 1) {
- if (empty(trim($params['js_code']))) {
- $this->error('JS代码块为必填项');
- }
- } else {
- if (empty($params['img_url'])) {
- $this->error('请选择图片');
- }
- if (empty($params['link_url'])) {
- $this->error('请填写链接地址');
- }
- }
- // (除福利广告)广告位必须选择
- if ($params['type'] != 3) {
- if (empty($params['material_position'])) {
- $this->error('请选择展示位置');
- }
- }
- }
- /**
- * 分身术
- * @param $params
- * @return array
- */
- private function _shapeShift($params)
- {
- $targetParams = [];
- $params['show_starttime'] = $this->model->setShowStarttimeAttr($params['show_starttime']);
- $params['show_endtime'] = $this->model->setShowStarttimeAttr($params['show_endtime']);
- $params['createtime'] = time();
- $params['updatetime'] = time();
- if ($params['type'] == 0) {
- $img_urls = explode(',', $params['img_url']);
- foreach ($img_urls as $img_url) {
- $item = $params;
- $item['img_url'] = $img_url;
- array_push($targetParams, $item);
- }
- } elseif ($params['type'] == 3) {
- // 福利广告
- $link_games = explode("\r\n", $params['link_game']);
- $link_games = array_filter($link_games);
- foreach ($link_games as $link_game) {
- $item = $params;
- $item['link_game'] = $link_game;
- array_push($targetParams, $item);
- }
- }else{
- array_push($targetParams, $params);
- }
- return $targetParams;
- }
- /**
- * 删除
- */
- public function del($ids = "")
- {
- if ($ids)
- {
- $pk = $this->model->getPk();
- $adminIds = $this->getDataLimitAdminIds();
- if (is_array($adminIds))
- {
- $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
- }
- $list = $this->model->where($pk, 'in', $ids)->select();
- $count = 0;
- foreach ($list as $k => $v)
- {
- $count += $v->delete();
- }
- if ($count)
- {
- $this->success();
- }
- else
- {
- $this->error(__('No rows were deleted'));
- }
- }
- $this->error(__('Parameter %s can not be empty', 'ids'));
- }
- /**
- * 批量生效 | 批量失效
- */
- public function batchValidate()
- {
- $params = $this->request->param();
- $ids = $params['ids'];
- $state = $params['state'];
- if (is_array($ids)) {
- foreach ($ids as $id) {
- $result = $this->model->update(['state' => $state], ['id' => $id]);
- }
- } else {
- $result = $this->model->update(['state' => $state], ['id' => $ids]);
- }
- if($result){
- $this->success('设置成功');
- }else{
- $this->error('设置失败');
- }
- }
- /**
- * 导入
- */
- public function import()
- {
- $file = $this->request->request('file');
- if (!$file)
- {
- $this->error(__('Parameter %s can not be empty', 'file'));
- }
- $filePath = ROOT_PATH . DS . 'public' . DS . $file;
- if (!is_file($filePath))
- {
- $this->error(__('No results were found'));
- }
- $PHPReader = new \PHPExcel_Reader_Excel2007();
- if (!$PHPReader->canRead($filePath))
- {
- $PHPReader = new \PHPExcel_Reader_Excel5();
- if (!$PHPReader->canRead($filePath))
- {
- $PHPReader = new \PHPExcel_Reader_CSV();
- if (!$PHPReader->canRead($filePath))
- {
- $this->error(__('Unknown data format'));
- }
- }
- }
- //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
- /*$importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';
- $table = $this->model->getQuery()->getTable();
- $database = \think\Config::get('database.database');
- $fieldArr = [];
- $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
- foreach ($list as $k => $v)
- {
- if ($importHeadType == 'comment')
- {
- $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
- }
- else
- {
- $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
- }
- }*/
- $fieldArr = [
- 'id'=>'id',
- '图片URL'=>'img_url',
- '链接URL'=>'link_url',
- '展示页面位置'=>'material_position',
- '展示开始时间'=>'show_starttime',
- '展示结束时间'=>'show_endtime',
- '权重'=>'weight',
- '状态'=>'state',
- '创建时间'=>'createtime',
- '更新时间'=>'updatetime'
- ];
- $PHPExcel = $PHPReader->load($filePath); //加载文件
- $currentSheet = $PHPExcel->getSheet(0); //读取文件中的第一个工作表
- $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
- $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
- $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);
- for ($currentRow = 1; $currentRow <= 1; $currentRow++)
- {
- for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
- {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $fields[] = $val;
- }
- }
- $insert = [];
- for ($currentRow = 2; $currentRow <= $allRow; $currentRow++)
- {
- $values = [];
- for ($currentColumn = 0; $currentColumn < $maxColumnNumber; $currentColumn++)
- {
- $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
- $values[] = is_null($val) ? '' : $val;
- }
- $row = [];
- $temp = array_combine($fields, $values);
- foreach ($temp as $k => $v)
- {
- if (isset($fieldArr[$k]) && $k !== '')
- {
- $row[$fieldArr[$k]] = $v;
- }
- }
- if ($row)
- {
- $insert[] = $row;
- }
- }
- if (!$insert)
- {
- $this->error(__('No rows were updated'));
- }
- try
- {
- $this->model->saveAll($insert);
- }
- catch (\think\exception\PDOException $exception)
- {
- $this->error($exception->getMessage());
- }
- $this->success();
- }
- }
|