model = model('Referral'); $this->dayCollectModel = model('ReferralDayCollect'); $this->view->assign("wxTypeList", $this->model->getWxTypeList()); $this->view->assign("typeList", $this->model->getTypeList()); $groupId = $this->auth->getGroupIds()[0]; if($groupId == 4){ $this->bookAgentId = $this->auth->id; if($this->auth->channel_id){ $this->bookChannelId = $this->auth->channel_id; }else{ $aeInfo = model('AdminExtend')->getInfo($this->auth->id); $this->bookChannelId = $aeInfo['create_by']; } }elseif($groupId == 3){ $this->bookAgentId = 0; $this->bookChannelId = $this->auth->id; }else{ $this->bookAgentId = 0; $this->bookChannelId = 0; } $this->view->assign("sexList", $this->model->getGuideSexList()); } public function collection() { $ids = $this->request->param('ids'); if($ids){ $update = model("Referral") ->wherein('id', $ids) ->exp('is_collect', 'abs(is_collect -1)') ->update(); if($update !== false){ $this->success("操作成功"); }else{ $this->error("操作失败"); } }else{ $this->error("没有找到这条推广链接"); } } /** * 查看 */ public function daily() { $params_arr = []; if ($this->auth->agent_id) { //配号代理商 $params_arr['channel_id'] = $this->auth->agent_id; $params_arr['agent_id'] = $this->auth->id; } elseif ($this->group == 4) { //代理商 $params_arr['agent_id'] = $this->auth->id; $params_arr['channel_id'] = $this->auth->channel_id; } elseif ($this->group == 3) { //渠道商 $params_arr['channel_id'] = $this->auth->channel_id; } $adminConfig = AdminService::instance()->getAdminConfigModel()->getAdminInfoAll($params_arr['channel_id']); $configChannelIds = Config::get('site.smallpay_channel_id') ?? ''; if ($configChannelIds == '*') { $open = true; } else { $list = explode(',', $configChannelIds); $open = in_array($this->auth->id, $list); } if ($open) { $adminConfig['small_goods_id'] = Config::get('site.smallpay_goods_id'); } $this->assign('adminconfig', $adminConfig); $this->assign('param', $params_arr); return $this->view->fetch(); } /** * 每日数据 * * @param string $ids * @return string|\think\response\Json * @throws Exception */ public function daydata($ids ='') { if (empty($ids)) { $this->error('缺少参数'); } //设置过滤方法 $this->request->filter(['strip_tags']); if ($this->request->isAjax()) { //如果发送的来源是Selectpage,则转发到Selectpage /*if ($this->request->request('pkey_name')) { return $this->selectpage(); }*/ //list($where, $sort, $order, $offset, $limit) = $this->buildparams(); if (VisitLimitService::instance()->checkMigratedV2()) { $list = \app\main\service\ReferralService::instance()->getMigrateReferralDayCollect($ids)->data; $total = count($list); } else { $map = [ //'createdate' => ['<', date("Ymd")], 'createdate' => ['between', [date("Ymd", strtotime("-31 days")), date("Ymd", strtotime("-1 days"))]], 'referral_id' => $ids, ]; $total = $this->dayCollectModel ->where($map) ->count(); $list = $this->dayCollectModel ->where($map) ->order('createdate', 'desc') ->select(); } if (!empty($list)) { $cost = model("Referral")->where('id', 'eq', $ids)->value('cost'); foreach ($list as &$row) { $row['recharge_money'] = StringHelper::moneyFormat($row['recharge_money']); $row['all_recharge_money'] = StringHelper::moneyFormat($row['all_recharge_money']); $row['cost'] = $cost; } } $result = array("total" => $total, "rows" => $list); return json($result); } $this->assignconfig('referral_id', $ids); return $this->view->fetch(); } private function getChannelOphost($channel_id){ $adminConfig = model('adminConfig')->getAdminInfoAll($channel_id); $url_referral = Config::get('site.scheme').'://'.$adminConfig['appid'].'.'.$adminConfig['ophost_host']; return $url_referral; } private function index_ajax($ophost_url,$admin_id = null,$push = null,$collect = null,$disable = null){ //如果发送的来源是Selectpage,则转发到Selectpage if ($this->request->request('pkey_name')) { return $this->selectpage(); } [$where, $sort, $order, $offset, $limit] = $this->buildparams(); $limit = 10; $condition = []; if($admin_id){ $condition['admin_id'] = $admin_id; }else{ $condition['admin_id'] = $this->auth->id; } if($push !== null){ $condition['push'] = $push ?? '0'; } if($collect !== null){ $condition['is_collect'] = 1; } if($disable !== null){ $condition['referral.state'] = '0'; } else { $condition['referral.state'] = '1'; } if (strstr($push, ',')){ $condition['push'] = ['in', explode(',', $push)]; } $filter = \json_decode($this->request->param('filter'), true); if(isset($filter['book_id']) || isset($filter['book.name'])){ $total = $this->model ->with('book') ->where($where) ->where($condition) ->count(); $list = $this->model ->with('book') ->where($where) ->where($condition) ->order($sort, $order) ->limit($offset, $limit) ->select(); } else { $total = $this->model ->where($where) ->where($condition) ->count(); $list = $this->model ->where($where) ->where($condition) ->order($sort, $order) ->limit($offset, $limit) ->select(); $book_list = BookService::instance()->getBookModel()->getBooksInfo(array_column($list, 'book_id')); foreach ($list as $index=>$ref) { if (array_key_exists($ref['book_id'], $book_list)) { $list[$index]['book'] = $book_list[$ref['book_id']]; } } } $migrateCollectList = []; $migrate = VisitLimitService::instance()->checkMigratedV2(); if ($migrate) { $referralIds = array_column($list, 'id'); $migrateCollectList = \app\main\service\ReferralService::instance()->getReferralCollectFromApi($referralIds)->data; } foreach ($list as $k=>$v){ //获取当前书籍的默认关注章节 if(empty($v['guide_chapter_idx']) && !empty($v['book_id'])){ $default_chapter_idx = 0; if($this->group == 4 || $this->group == 3){ $default_chapter_idx = model('Guide')->getGuideChapter($this->auth->id,$v['book_id'],0,$this->auth->channel_id); }else if($this->group == 2){ $group = model('AuthGroupAccess')->getGroupId($condition['admin_id']); if($group == 3){ $default_chapter_idx = model('Guide')->getGuideChapter($condition['admin_id'],$v['book_id'],0,$condition['admin_id']); }else if($group == 4){ if($adminExtend = model('AdminExtend')->getInfo($condition['admin_id'])){ $default_chapter_idx = model('Guide')->getGuideChapter($condition['admin_id'],$v['book_id'],0,$adminExtend['create_by']); } } } $list[$k]['guide_chapter_idx'] = $default_chapter_idx; } $list[$k]['url_referral'] = $ophost_url.'/t/'.$v['id']; $list[$k]['skin_url'] = ReferralService::instance()->getSkinUrl($v['id'], $v['source_url']); if ($migrate) { if (array_key_exists($v['id'], $migrateCollectList)) { foreach ($migrateCollectList[$v['id']] as $key=>$value) { $list[$k][$key] = $value; } } } else { $dayMTkey = "M-T:".$v['id'].":".date("d"); //今日充值金额key $list[$k]['dayuv'] = (int)Redis::instance()->get(CacheConstants::getReadOfReferralIdKey($v['id'])); $list[$k]['dayut'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfReferralIdKey($v['id'])); //今日关注人数 $list[$k]['daymt'] = (int)Redis::instance()->get($dayMTkey)? round(Redis::instance()->get($dayMTkey) / 100, 2) :0; //今日充值金额 $list[$k]['dayjt'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfPureReferralIdKey($v['id'])); //今日净关注人数 $list[$k]['dayqt'] = (int)Redis::instance()->get(CacheConstants::getUnsubscribeOfReferralIdKey($v['id'])); //今日取消关注人数 $list[$k]['net_follow_num'] = (int)$list[$k]['net_follow_num']; if ($list[$k]['uv'] < $list[$k]['dayuv']) { $list[$k]['uv'] = $list[$k]['dayuv']; } if ($list[$k]['follow'] < $list[$k]['dayut']) { $list[$k]['follow'] = $list[$k]['dayut']; } if ($list[$k]['net_follow_num'] < $list[$k]['dayjt']) { $list[$k]['net_follow_num'] = $list[$k]['dayjt']; } $dayMTNkey = "M-T-N:".$v['id'].":".date("d"); //今日充值笔数key $list[$k]['order_nums'] = (int)$list[$k]['orders_num']; $list[$k]['day_order_nums'] = (int)Redis::instance()->get($dayMTNkey); } if(!empty($v['book_id'])){ $isLimited = model('BookLimit')->backendHasLimit($this->bookAgentId,$this->bookChannelId,$v['book_id']); if($isLimited){ $list[$k]['limited'] = 1; }else{ $list[$k]['limited'] = 0; } }else{ $list[$k]['limited'] = 0; } $list[$k]['short_url'] = replaceShortDomain($list[$k]['url_referral'], $v['short_id']); } $result = array("total" => $total, "rows" => $list); return json($result); } public function admin_index() { [$where, $sort, $order, $offset, $limit] = $this->buildparams(); $push = $this->request->param('push') ?? '0'; $this->assign('push', $push); $this->assignconfig('push', $push); if ($this->request->isAjax()) { $list = \app\main\service\ReferralService::instance()->getAdminReferralList($this->auth->id, $push, $where, $sort, $order, $offset, $limit)->data; return $list; } return $this->view->fetch(); } /** * 查看 */ public function index() { $base_url_params = []; $channel_url_path = null; // 是否开启微信分享开关 $open_wechat_share = Config::get('site.open_wechat_share') ?? 0; //禁用 $disable = $this->request->param('disable') ?? null; if($disable){ $base_url_params['disable'] = 1; } //收藏 $collection = $this->request->param('collection') ?? null; if($collection){ $base_url_params['collection'] = 1; } //内推外派 $push = null; if(!$disable && !$collection){ $push = $this->request->param('push') ?? '0'; } $base_url_params['push'] = $push; //被查看的渠道ID $lock_id = $_GET['ids'] ?? 0; //查看渠道 if($lock_id){ $base_url_params['ids'] = $_GET['ids']; $this->assign('type',1); $this->assignconfig('rtype',1); if ($this->group == 2) { $channel_url_path = $this->getChannelOphost($_GET['ids']); } } //渠道本身 if(!$lock_id){ if ($collection == 1 || $disable == 1) { $this->assign('type', 1); } else { $this->assign('type', 0); } $this->assignconfig('rtype',0); $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; if($this->group == 4 || $this->group == 3){ $channel_url_path = $this->getChannelOphost($channel_id); } if($this->auth->agent_id || $this->group == 3){ if(!model('AdminConfig')->checkWechatConfig($this->auth->id)){ $this->error('请先授权微信服务号给本系统,正在跳转授权设置页面~', url('admin/config')); } } } $this->assign('push', $push); $this->assign('collection',$collection); $this->assign('disable',$disable); $this->assignconfig('push',$push); $this->assignconfig('collection',$collection); $this->assignconfig('url_referral', $channel_url_path); $this->assignconfig('open_wechat_share', $open_wechat_share); $this->assignconfig('authGroupId', $this->group); $this->assignconfig('referralUrl',Url::build('admin/referral.referral/index',$base_url_params)); $adminExtendInfo = model('AdminExtend')->getInfo($this->auth->id); $this->assignconfig('authDistribute', $adminExtendInfo['distribute']); if($this->request->isAjax()){ return $this->index_ajax($channel_url_path,$lock_id,$push,$collection,$disable); } return $this->view->fetch(); } public function lookAgentReferral(){ $base_url_params = []; //禁用 $disable = $this->request->param('disable') ?? null; if($disable){ $base_url_params['disable'] = 1; } //收藏 $collection = $this->request->param('collection') ?? null; if($collection){ $base_url_params['collection'] = 1; } //内推外派 $push = null; if(!$disable && !$collection){ $push = $this->request->param('push') ?? '0'; $base_url_params['push'] = $push; } $dls = model("AdminExtend")->join('admin',' `admin_extend`.`admin_id` = `admin`.`id`')->where(['create_by'=> $this->auth->id])->select(); if ($this->request->isAjax()) { //如果发送的来源是Selectpage,则转发到Selectpage if ($this->request->request('pkey_name')) { return $this->selectpage(); } [$where, $sort, $order, $offset, $limit] = $this->buildparams(); //$map['admin_id'] = array('in', $this->auth->id); if($dls){ $map['admin_id'] = array('in',implode(',',array_column($dls, 'admin_id'))); } else { $result = array("total" => 0, "rows" => []); return json($result); } $common = []; if($push !== null){ $common['referral.push'] = $push ?? '0'; } if($collection !== null){ $common['referral.is_collect'] = 1; } if($disable !== null){ $common['referral.state'] = '0'; } else { $common['referral.state'] = '1'; } $total = $this->model ->with('book') ->where($where) ->where($map) ->where($common) ->order($sort, $order) ->count(); //dump($this->model->getLastSql());die; $list = $this->model ->with('book') ->where($where) ->where($map) ->where($common) ->order($sort, $order) ->limit($offset, $limit) ->select(); $adminExtend = model('AdminExtend')->where($map)->select(); $migrateCollectList = []; $migrate = VisitLimitService::instance()->checkMigratedV2(); if ($migrate) { $referralIds = array_column($list, 'id'); $migrateCollectList = \app\main\service\ReferralService::instance()->getReferralCollectFromApi($referralIds)->data; } foreach($list as $k => $v){ $url_referral = ''; foreach($adminExtend as $val){ if($v['admin_id'] == $val['admin_id']){ if($val['distribute']){ $info = model('AdminConfig')->getAdminInfoAll($val['admin_id']); if(isset($info['entry_host']) && !empty($info['entry_host'])){ $url_referral = Config::get('site.scheme').'://'.$info['entry_host']; }else{ if(isset($info['ophost_host']) && isset($info['appid'])){ $url_referral = Config::get('site.scheme').'://'.$info['appid'].'.'.$info['ophost_host']; } } }else{ $info = model('AdminConfig')->getAdminInfoAll($this->auth->id); if(isset($info['entry_host']) && !empty($info['entry_host'])){ $url_referral = Config::get('site.scheme').'://'.$info['entry_host']; }else{ if(isset($info['ophost_host']) && isset($info['appid'])){ $url_referral = Config::get('site.scheme').'://'.$info['appid'].'.'.$info['ophost_host']; } } } } } $list[$k]['url_referral'] = $url_referral.'/t/'.$v['id']; $list[$k]['short_url'] = replaceShortDomain($list[$k]['url_referral'], $v['short_id']); $list[$k]['url_referral'] = $url_referral.'/t/'.$v['id']; if ($migrate) { if (array_key_exists($v['id'], $migrateCollectList)) { $list[$k] = array_merge($list[$k]->getData(), $migrateCollectList[$v['id']]); } } else { $dayMTkey = "M-T:".$v['id'].":".date("d"); //今日充值金额key $list[$k]['dayuv'] = (int)Redis::instance()->get(CacheConstants::getReadOfReferralIdKey($v['id'])); $list[$k]['dayut'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfReferralIdKey($v['id'])); //今日关注人数 $list[$k]['daymt'] = (int)Redis::instance()->get($dayMTkey)? round(Redis::instance()->get($dayMTkey) / 100, 2) :0; //今日充值金额 $list[$k]['dayjt'] = (int)Redis::instance()->get(CacheConstants::getSubscribeOfPureReferralIdKey($v['id'])); //今日净关注人数 $list[$k]['dayqt'] = (int)Redis::instance()->get(CacheConstants::getUnsubscribeOfReferralIdKey($v['id'])); //今日取消关注人数 $list[$k]['net_follow_num'] = (int)$list[$k]['net_follow_num']; if ($list[$k]['uv'] < $list[$k]['dayuv']) { $list[$k]['uv'] = $list[$k]['dayuv']; } if ($list[$k]['follow'] < $list[$k]['dayut']) { $list[$k]['follow'] = $list[$k]['dayut']; } if ($list[$k]['net_follow_num'] < $list[$k]['dayjt']) { $list[$k]['net_follow_num'] = $list[$k]['dayjt']; } $dayMTNkey = "M-T-N:".$v['id'].":".date("d"); //今日充值笔数key $list[$k]['order_nums'] = (int)$list[$k]['orders_num']; $list[$k]['day_order_nums'] = (int)Redis::instance()->get($dayMTNkey); } } $result = array("total" => $total, "rows" => $list); return json($result); } $this->assign('push', $push); $this->assign('collection',$collection); $this->assign('disable',$disable); $this->assignconfig('push',$push); $this->assignconfig('collection',$collection); $this->assignconfig('adminExtend',$dls); $this->assignconfig('look_url',Url::build('admin/referral.referral/lookAgentReferral',$base_url_params)); return $this->view->fetch(); } /** * 添加 */ public function add() { $isLimited = false; if ($this->request->isPost()) { $params = $this->request->post("row/a"); if ($params) { $params['admin_id'] = $this->auth->id; $params['createtime'] = time(); 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); } if(isset($params['book_id'])){ if(empty($params['book_id'])){ $this->error('获取书籍信息失败'); } $bookInfo = model('book')->get($params['book_id']); if ($bookInfo['state'] == 0 || $bookInfo['cansee'] == 0) { $this->error('抱歉,本书已下架,无法生成推广链接~'); } } //获取当前书籍的默认关注章节 $default_chapter_idx = $params['guide_chapter_idx'] ?? 0; if(isset($params['guide_chapter_idx']) && empty($params['guide_chapter_idx']) && isset($params['book_id']) && !empty($params['book_id'])){ if($this->group == 4){ $default_chapter_idx = model('Guide')->getGuideChapter($this->auth->id,$params['book_id'],0,$this->auth->channel_id); }else{ if (in_array($this->group, [7, 8])) { //vip和vip运营者 //弹出警告 必填项 $this->error('导粉章节数必填'); //$default_chapter_idx = model('Guide')->getGuideChapter(0,$params['book_id'],0,0); } else { $default_chapter_idx = model('Guide')->getGuideChapter($this->auth->id,$params['book_id'],0,$this->auth->channel_id); } } } //导粉章节小于收费章节 if(isset($params['book_id'])){ if($default_chapter_idx > $this->bookPayChapterIdex($params['book_id'])){ $this->error('导粉章节数必须小于收费章节数'); } } //落地页推广 if($params['type'] == 3){ if(!$params['guide_idx']){ $this->error('落地页章节数必填'); } if($params['guide_idx'] > $default_chapter_idx){ $this->error('落地页章节数必须小于导粉章节数'); } if($params['guide_idx'] > $this->bookReferralNumber($params['book_id'])){ $this->error('落地页章节数必须小于推广文案数量'); } } if(!$this->request->has('push') && !isset($params['push'])){ $params['push'] = 0; } if($this->request->has('push')){ $params['push'] = $this->request->param('push'); } $params['share_image'] = ResourceService::instance()->getRandomImage()->data; $params['share_title'] = ResourceService::instance()->getRandomTitle()->data; $insertId = $this->model->allowField(true)->insertGetId($params); if($insertId === false){ $this->error($this->model->getError()); } $params['closeTip'] = 0; //vip和vip运营创建分流链接 if (in_array($this->group, [7, 8])) { //生成VIP推广链接信息 $vipReferralParams = [ 'admin_id' => $this->auth->id, 'createtime' => time(), 'referral_id' => $insertId, 'push' => $params['push'], //'short_url' => Config::get('site.short_url_host').'/v/'.$id, ]; $vipReferralId = model('ReferralLibrary')->allowField(true)->insertGetId($vipReferralParams); $params['closeTip'] = 1; $this->success('', null, $params); } // $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; $params['url_referral'] = $this->getChannelOphost($channel_id) . '/t/' . $insertId; $source_url = ''; $params['id'] = $insertId; //首页 if ($params['type'] == 2) { $source_url .= '?referral_id='.$insertId; } else { $source_url .= '/index/book/chapter?book_id=' . $params['book_id'] . '&sid=' . $params['chapter_id'] . '&referral_id=' . $insertId; } if ($this->group == 4) { $source_url .= '&agent_id='.$this->auth->id; } $params['source_url'] =getCurrentDomain($channel_id,$source_url); $params['jmp_url'] = getCurrentDomain($channel_id,'/t/'.$insertId); //绑定域名短链ID及重置生成短链接的源地址,代理商使用渠道的短链域名池 $short = model('ShortRelation')->getRandShort($channel_id); if($short){ $params['short_id'] = $short->id; $short_source_url = replaceShortDomain($params['jmp_url'], $short->id); $params['jmp_url'] = $short_source_url; }else{ $short_source_url = $params['source_url']; } $shoturl = new ShortUrl(); //生成腾讯短链 $params['short_url_qq'] = $shoturl->tencent($channel_id, $short_source_url); //生成sina短链 $params['short_url_weibo'] = $shoturl->sina($short_source_url); $this->model->save($params, ['id' => $insertId]); //删除Redis缓存 $redis = Redis::instance(); $redis->del('RI:N:'.$insertId); } catch (Exception $e) { $this->error($e->getMessage()); } $this->success('', null, $params); } $this->error(__('Parameter %s can not be empty', '')); } if (!$this->request->has('type') || $this->request->get('type') != 2) { if (!$this->request->has('book_id') || !$this->request->has('chapter_id')) { $this->error('参数错误!'); } $book_id = $this->request->get('book_id'); $chapter_id = $this->request->get('chapter_id'); $book = model('Book')::get($book_id); $this->assign('book', $book); $data = model('Book')::getChapterInfo($book_id, $chapter_id); if ($data['code']) { $this->error($data['msg']); } $isLimited = model('BookLimit')->backendHasLimit($this->bookAgentId,$this->bookChannelId,$book_id); $this->assign('chapter', $data['data']); } $this->assign('limited',$isLimited); if($this->request->get('type') == 3) { //表单默认值 $guide_title = model('ManageTitle')->getRandTitle(['1','2']); $guide_image = model('ManageCover')->getRandImage(['1','2']); $def = ['guide_title' => $guide_title, 'guide_image' => $guide_image]; $this->assign('def', $def); } $channel_id = $this->auth->agent_id ?? $this->auth->channel_id; $adminConfig = model('AdminConfig')->getAdminInfoAll($channel_id); $this->assign('ref_out_push',intval($adminConfig['ref_out_push'] ?? 0)); $this->assign('type',intval($this->request->get('type'))); $this->assign('chapter_idx',intval($this->request->param('chapter_idx')) ?? 0); return $this->view->fetch(); } /** * 书收费章节 * @param $book_id * @return bool */ private function bookPayChapterIdex($book_id){ //获取书籍信息 $book = model('Book')->BookInfo($book_id); //全局免费章节数 $free_chapter_idx = config('site.book_free_chapter_num'); //如果本书籍设置了免费章节数,以本书籍的免费章节数为准 if(isset($book['free_chapter_num']) && intval($book['free_chapter_num'])>0){ $free_chapter_idx = $book['free_chapter_num']; } return $free_chapter_idx; } /** * 书推广文案数量 * @param $book_id * @return bool */ private function bookReferralNumber($book_id){ //获取书籍信息 $book = model('Book')->BookInfo($book_id); return $book['referral_num'] ?? 10; } /** * 二维码模板 * @param $url * @param $source_url * @param null $tpl_id * @return mixed * @throws Exception */ public function show_tpl($url,$source_url = null,$tpl_id = null){ if(!intval($tpl_id)){ $current_url = DiyQRCode::createQRCodeByUrl($url,220); $source_url = $current_url; $qrcode_list = DiyQRCode::getTplPath($source_url); }else{ $source_url = DiyQRCode::createQRCodeByUrl($url,220); $current_url = DiyQRCode::createTplQRCode($source_url,$tpl_id); $qrcode_list = DiyQRCode::getTplPath($source_url); } $this->assign('source_url',$source_url); $this->assign('current_url',$current_url); $this->assign('url',$url); $this->assign('tpl_id',intval($tpl_id)); $this->assign('qrcode_list',$qrcode_list); return $this->view->fetch(); } /** * 图文推广链接 * @param null|int $book_id * @param null|int $chapter_idx * @param null|int $referral_id * @return string */ public function essay($book_id = null, $chapter_idx = null, $referral_id = null) { if ($referral_id) { $row = $this->model->get($referral_id); $book_id = $row['book_id']; } else { $row = [ 'book_id' => $book_id, 'chapter_idx' => intval($chapter_idx), ]; } //书籍信息 $book = model('book')::get($book_id); $isLimited = model('BookLimit')->backendHasLimit($this->bookAgentId,$this->bookChannelId,$book_id); $this->assign('limited',$isLimited); $this->assign('book', $book); $this->assign('row', $row); $this->view->engine->layout(false); return $this->view->fetch(); } /** * 编辑 */ public function edit($ids = null) { $row = $this->model->get($ids); if (!$row) { $this->error(__('No Results were found')); } $editFrom = $this->request->get('from', ''); $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"); $params['share_image'] = ResourceService::instance()->getRandomImage()->data; $params['share_title'] = ResourceService::instance()->getRandomTitle()->data; if ($params) { 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); } //获取当前书籍的默认关注章节 $default_chapter_idx = $params['guide_chapter_idx'] ?? 0; if(isset($params['guide_chapter_idx']) && empty($params['guide_chapter_idx']) && !empty($row['book_id'])){ if($this->group == 4){ $default_chapter_idx = model('Guide')->getGuideChapter($this->auth->id,$row['book_id'],0,$this->auth->channel_id); }else{ if (in_array($this->group, [7, 8])) { //vip和vip运营者 $default_chapter_idx = model('Guide')->getGuideChapter(0,$row['book_id'],0,0); } else { $default_chapter_idx = model('Guide')->getGuideChapter($this->auth->id,$row['book_id'],0,$this->auth->channel_id); } } } if ($row['type'] != 2) { // 修改推广链接 $source_url = '/index/book/chapter?book_id=' . $row['book_id'] . '&sid=' . $params['chapter_id'] . '&referral_id=' . $row['id']; if ($this->group == 4) { $source_url .= '&agent_id=' . $this->auth->id; } $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; $params['source_url'] = getCurrentDomain($channel_id, $source_url); } //导粉章节小于收费章节 if(!empty($row['book_id'])){ if($default_chapter_idx > $this->bookPayChapterIdex($row['book_id'])){ $this->error('导粉章节数必须小于收费章节数'); } } //落地页推广 if($row['type'] == 3 && isset($params['guide_idx'])){ if(!$params['guide_idx']){ $this->error('落地页章节数必填'); } if($params['guide_idx'] > $this->bookReferralNumber($row['book_id'])){ $this->error('落地页章节数必须小于推广文案数量'); } if($params['guide_idx'] > $default_chapter_idx){ $this->error('落地页章节数必须小于导粉章节数'); } } $result = $row->allowField(true)->save($params); if ($result !== false) { $redis = Redis::instance(); $key = 'RI:N:' . $row['id']; $redis->del($key); //@todo vip 批量修改 if ($params['edit_from'] == 'vipreferral') { $library = model("ReferralLibrary")->where('referral_id', 'eq', $ids)->find(); $children = model("ReferralSlave")->where('library_id', 'eq', $library->id)->field('referral_id')->select(); if (isset($params['cost'])) { unset($params['cost']); } if (!empty($children)) { $referralIds = array_map(function ($v) { return $v->referral_id;}, $children); model('referral')->allowField(true)->save($params, ['id' => ['in', $referralIds]]); foreach ($referralIds as $referralId) { $redis = Redis::instance(); $key = 'RI:N:' . $referralId; $redis->del($key); } } } $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("edit_from", $editFrom); if ($row['type'] == 1 || $row['type'] == 3) { $book = model('Book')::get($row['book_id']); $this->assign('book', $book); } if (!empty($row['book_id'])) { $freeChapterIds = $this->bookPayChapterIdex($row['book_id']); if ($freeChapterIds > 0) { $chapters = model("Book")::getChapterList($row['book_id'], 1, $freeChapterIds); if ($chapters['code'] == 100){ throw new HttpException(400, '异常错误,请重试'); } } } $this->assign('chapters', $chapters['data']['data'] ?? []); return $this->view->fetch(); } /** * 选择(多选) * @return string|\think\response\Json */ public function select() { $base_url_params = []; $channel_url_path = null; // 是否开启微信分享开关 $open_wechat_share = Config::get('site.open_wechat_share') ?? 0; //内推外派 $push = $this->request->param('push') ?? 0; $base_url_params['push'] = $push; //被查看的渠道ID $lock_id = $_GET['ids'] ?? 0; //查看渠道 if($lock_id){ $base_url_params['ids'] = $_GET['ids']; $this->assign('type',1); $this->assignconfig('rtype',1); if ($this->group == 2) { $channel_url_path = $this->getChannelOphost($_GET['ids']); } } //渠道本身 if(!$lock_id){ $this->assign('type',0); $this->assignconfig('rtype',0); $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; if($this->group == 4 || $this->group == 3){ $channel_url_path = $this->getChannelOphost($channel_id); } if($this->auth->agent_id || $this->group == 3){ if(!model('AdminConfig')->checkWechatConfig($this->auth->id)){ $this->error('请先授权微信服务号给本系统,正在跳转授权设置页面~', url('admin/config')); } } } $this->assign('push', $push); $this->assignconfig('push',$push); $this->assignconfig('url_referral', $channel_url_path); $this->assignconfig('open_wechat_share', $open_wechat_share); $this->assignconfig('authGroupId', $this->group); $this->assignconfig('referralUrl',Url::build('admin/referral.referral/index',$base_url_params)); $adminExtendInfo = model('AdminExtend')->getInfo($this->auth->id); $this->assignconfig('authDistribute', $adminExtendInfo['distribute']); if ($this->request->isAjax()) { if($this->request->has('push')){ return $this->index_ajax($channel_url_path,$lock_id,$push); }else{ return $this->index_ajax($channel_url_path,$lock_id,null); } } return $this->view->fetch(); } /** * 删除 */ 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; $redis = Redis::instance(); foreach ($list as $k => $v) { $id = $v->id; $count += $v->delete(); // $redis->hdel('T:',$id); //清除redis缓存 $redis->del('RI:N:' . $id); //清除redis缓存 } if ($count) { $this->success(); } else { $this->error(__('No rows were deleted')); } } $this->error(__('Parameter %s can not be empty', 'ids')); } /** * 生成图片章节 */ public function image() { $bookId = $this->request->get('book_id'); $head = $this->request->get('head'); if (!$bookId || !$head) { $this->error('缺少参数!'); } $imgPath = ROOT_PATH . 'public/uploads/chapter/' . $bookId . '/'; //图片保存路径 $imgIndexPath = ROOT_PATH . 'public/uploads/chapter_index/' . $bookId . '/'; //图片索引文件路径 $cdnPath = Config::get('upload.cdnurl') . '/uploads/chapter/' . $bookId . '/'; //cdn路径 if (!is_dir(ROOT_PATH . 'public/uploads/chapter_index/' . $bookId)) { mkdir(ROOT_PATH . 'public/uploads/chapter_index/' . $bookId, 0777, true); } if (!file_exists($imgPath)) { //创建文件夹 mkdir($imgPath, 0700,true); clearstatcache(); } $data = model('Book')::getHeadChapters($bookId, $head); if ($data['code']) { $this->error($data['msg']); } $font = [ // 'path' => ROOT_PATH . 'public/assets/fonts/SourceHanSans-Light.otf', //思源黑体 'path' => ROOT_PATH . 'public/assets/fonts/PingFang-Regular.ttf', //苹方 'size' => 32 ]; $box = imageftbbox($font['size'], 0, $font['path'], '字'); //测算单个汉字宽高 $font['width'] = max($box[2], $box[4]) - min($box[0], $box[6]); $font['height'] = max($box[3], $box[5]) - min($box[1], $box[7]); $lineSpacing = 24; //行间距 $cosSpacing = 10; //列间距 $paragraphSpacing = 40; //段间距 $maxLen = 240; //最大文字,超过就新开一页 $maxPage = 634; //页面最大宽度 foreach ($data['data'] as &$chapter) { $page = 1; //当前第几页 $strLen = 0; //当前汉字数 $pageLine = 0; //当前页面第几行 $paragraphNum = 0; //当前页面共几段 $arr = []; foreach ($chapter['content'] as $key=>$line) { if ($key == 0 || !$line) { continue; } $lineLen = mb_strlen($line); if (($strLen + $lineLen + 2) > $maxLen && $strLen > 0) { //换页 $strLen = $lineLen; $page++; $pageLine = 0; $paragraphNum = 0; } else { $strLen = $strLen + $lineLen; } $pageLine++; $lineWidth = ($font['width'] + $cosSpacing) * 2; //开头空2个汉字位置 for ($i = 0; $i < mb_strlen($line); $i++) { $text = mb_substr($line, $i, 1, 'UTF-8'); $nextCN = true; //下一个字符 中文true 符号false if((($lineWidth + $font['width'] * 2) > $maxPage) && $i < (mb_strlen($line) - 1)){ //具有下一个字符 $nextText = mb_substr($line, $i + 1, 1, 'UTF-8'); //下一个字符 if (!preg_match("/^[\x{4e00}-\x{9fa5}]+$/u", $nextText)) { //下一个字符不是是中文 $nextCN = false; } } if (!$nextCN || (($lineWidth + $font['width']) > $maxPage)) { //下一个不是中文或者宽度超出换行 $lineWidth = 0; $pageLine++; } $arr[$page]['page'][$pageLine][] = [ 'x' => $lineWidth, 'y' => $cosSpacing + $pageLine * $font['height'] + ($pageLine-1) * $lineSpacing + $paragraphNum * $paragraphSpacing, 'text' => $text ]; $lineWidth = $lineWidth + $font['width'] + $cosSpacing; } $paragraphNum++; $arr[$page]['paragraphNum'] = $paragraphNum; } $version = md5(implode('', $chapter['content'])); $index_file = $imgIndexPath . $chapter['id'] . '-' . $version . '.txt'; if (file_exists($index_file)) { $chapter['content'] = json_decode(file_get_contents($index_file), true); } else { $imgArr = []; foreach ($arr as $key => $page) { $lineNum = count($page['page']); $height = $lineNum * $font['height'] + ($lineNum - 1) * $lineSpacing + $page['paragraphNum'] * $paragraphSpacing + $cosSpacing * 2; $image = imagecreatetruecolor($maxPage, $height); $black = imagecolorallocate($image, 0, 0, 0); $white = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, $maxPage, $height, $white); foreach ($page['page'] as $line) { foreach ($line as $str) { imagefttext($image, $font['size'], 0, $str['x'], $str['y'], $black, $font['path'], $str['text']); } } $file_name = $chapter['id'] . '-' . $key . substr($version, 0, 5) . '.jpg'; imagejpeg($image, $imgPath . $file_name); imagedestroy($image); $img_info = getimagesize($imgPath . $file_name); $imgArr[] = ['imgurl' => $cdnPath.$file_name, 'width' => $img_info[0] ?? 0, 'height' => $img_info[1] ?? 0]; } if ($imgArr) { file_put_contents($index_file, json_encode($imgArr)); $chapter['content'] = $imgArr; } } // break; } exit(json_encode($data['data'])); // $this->success('图片生成成功!', null, $imgArr); } public function essayimage($book_id = null, $chapter_idx = null, $referral_id = null) { if ($referral_id) { $row = $this->model->get($referral_id); $book_id = $row['book_id']; } else { $row = [ 'book_id' => $book_id, 'chapter_idx' => $chapter_idx, ]; } //书籍信息 $isLimited = model('BookLimit')->backendHasLimit($this->bookAgentId,$this->bookChannelId,$book_id); $this->assign('limited',$isLimited); $book = model('book')->BookInfo($book_id); $this->assign('book', $book); $this->assign('row', $row); $this->view->engine->layout(false); return $this->view->fetch(); } /** * 背景图模式 * @param null $book_id * @param null $chapter_idx * @param null $referral_id * @return string * @throws Exception */ public function background($book_id = null, $chapter_idx = null, $referral_id = null){ if ($referral_id) { $row = $this->model->get($referral_id); $book_id = $row['book_id']; } else { $row = [ 'book_id' => $book_id, 'chapter_idx' => $chapter_idx, ]; } //书籍信息 $book = model('book')->BookInfo($book_id); $this->assign('book', $book); $this->assign('row', $row); $this->view->engine->layout(false); return $this->view->fetch(); } /** * 生成推广文案底部二维码 * * @param int $referral_id 推广链接id * @param int $idx 推广图片序号 */ public function qrcode() { $referral_id = $this->request->get('referral_id'); if (!$referral_id) { $this->error('参数错误!'); } $idx = $this->request->get('idx', 1); /** * 图片序号的生成格式 */ $imgSize = [ 1 => [ 'size' => 164, //二维码宽度 'x' => 376, //水印x 'y' => 35 //水印y ], 2 => [ 'size' => 168, //二维码宽度 'x' => 374, //水印x 'y' => 33 //水印y ], 3 => [ 'size' => 156, //二维码宽度 'x' => 372, //水印x 'y' => 46 //水印y ], 4 => [ 'size' => 200, //二维码宽度 'x' => 356, //水印x 'y' => 15 //水印y ], 5 => [ 'size' => 200, //二维码宽度 'x' => 356, //水印x 'y' => 15 //水印y ], 6 => [ 'size' => 200, //二维码宽度 'x' => 356, //水印x 'y' => 15 //水印y ] ]; /** * 跳转短链生成格式 */ $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; $jmp_url = getCurrentDomain($channel_id,'/t/' . $referral_id); /** * 生成二维码 */ $qrCode = new QrCode($jmp_url); $qrCode->setSize($imgSize[$idx]['size']); //二维码尺寸 $qrCode->setWriterByName('png'); $qrCode->setEncoding('UTF-8'); $qrCode->setMargin(10); $tmpPath = sys_get_temp_dir(); if (substr($tmpPath, -1, 1) == '/') { $tmpPath = $tmpPath . uniqid() . '.png'; } else { $tmpPath = $tmpPath . '/' . uniqid() . '.png'; } $qrCode->writeFile($tmpPath); /** * 二维码合并 */ $image_1 = imagecreatefrompng(ROOT_PATH . "public/assets/img/essay/qrcode_{$idx}.png"); //底图 $image_2 = imagecreatefrompng($tmpPath); //二维码图片 $images_qrcode = imagecreatetruecolor($imgSize[$idx]['size'], $imgSize[$idx]['size']); //建立一个图片 $images_qrcode_info = getimagesize($tmpPath); imagecopyresampled($images_qrcode, $image_2, 0, 0, 0, 0, $imgSize[$idx]['size'],$imgSize[$idx]['size'], $images_qrcode_info[0],$images_qrcode_info[1]); imagecopymerge($image_1, $images_qrcode, $imgSize[$idx]['x'], $imgSize[$idx]['y'], 0, 0, $imgSize[$idx]['size'], $imgSize[$idx]['size'], 100); $imgPath = ROOT_PATH . 'public/uploads/qrcode/'; //图片保存路径 if (!file_exists($imgPath)) { //创建文件夹 mkdir($imgPath, 0700, true); clearstatcache(); } $imgPath = $imgPath . $referral_id . '_' . $idx . '.png'; $imgUrl = cdnurl("/uploads/qrcode/" . $referral_id . '_' . $idx . '.png'); $res = imagepng($image_1, $imgPath); unlink($tmpPath); imagedestroy($image_1); imagedestroy($image_2); if ($res) { $data = [ 'url' => $imgUrl ]; $this->success('', null, $data); } $this->error('二维码生成失败!', null); } /** * 禁用或解禁 根据当前状态进行切换 * @param null $ids */ public function disable($ids = null){ if ($ids) { $isVip = $this->request->param('isVip') ?? 0; $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; $redis = Redis::instance(); foreach ($list as $k => $v) { $state = '0'; if($v['state'] == '0') { $state = '1'; } $count += $v->where('id', $v['id'])->update(['state'=> $state]); $redis->del('RI:N:'.$v['id']); if ($isVip) { //VIP分流链接 $library = model("ReferralLibrary")->where('referral_id', 'eq', $v['id'])->find(); $vipKey = 'RIV:'.$library['id']; $redis->del($vipKey); } } if ($count) { $this->success(); } else { $this->error(__('No rows were updated')); } } $this->error(__('Parameter %s can not be empty', 'ids')); } /** * @param $id */ public function merge_image($id) { if ($this->request->isPost()) { $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; $mergeImage = ImageService::instance()->getReferralImage($id, $channel_id); if ($mergeImage->code != ErrorCodeConstants::SUCCESS) { $this->error($mergeImage->msg); } else { $this->success("", null, ["path" => $mergeImage->data]); } } } /** * 获取分享的信息 * @param $id * @param string $type * @return \think\response\Json */ public function ajaxGetShare($id, $type='s_chat') { $data = $this->model->where('id', '=', $id)->find() ->toarray(); $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id; $shareLink = $data['short_url_qq'] ? $data['short_url_qq'] : getCurrentDomain($channel_id,$data['source_url']); //$shareLink = ReferralService::instance()->get189Url($id, $shareLink)->data; $shareLink = ReferralService::instance()->get189Urlv3($id, $shareLink)->data; if($data['share_image']){ $shareIcon = $data['share_image']; }else{ $shareIcon = ResourceService::instance()->getRandomCover()->data; } if($data['share_title']){ $shareTitle = $data['share_title']; }else{ $shareTitle = ResourceService::instance()->getRandomTitle()->data; } $shareDesc = ResourceService::instance()->getRandomDesc()->data; if(!$shareDesc){ $shareDesc = $shareTitle; } $this->assign('type', $type); $this->assign('data', $data); $this->assign('shareLink', $shareLink); $this->assign('shareIcon', $shareIcon); $this->assign('shareTitle', $shareTitle); $this->assign('shareDesc', $shareDesc); if($type == 's_friends'){ $shareType = 8; }else{ $shareType = 1; } $result = [ 'shareLink' => $shareLink, 'shareIcon' => $shareIcon, 'shareTitle' => $shareTitle, 'shareType' => $shareType, 'shareDesc' => $shareDesc ]; return json($result); } public function ajaxGetRandomTitle() { $shareTitle = ResourceService::instance()->getRandomTitle()->data; return json([ 'data' => $shareTitle ]); } }