123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474 |
- <?php
- namespace app\admin\controller\wechat;
- use app\common\constants\Message;
- use app\common\controller\Backend;
- use app\common\library\Redis;
- use app\main\constants\WechatSubscribeConstants;
- use app\main\service\AdminService;
- use app\main\service\UrlService;
- use think\Exception;
- /**
- * 被关注回复配置管理
- *
- * @icon fa fa-circle-o
- */
- class Subscribe extends Backend
- {
- protected $gzhName = null;
- public $noNeedRight = ['getkandian','getlist','del'];
- /**
- * WechatSubscribeConfig模型对象
- */
- protected $model = null;
- public function _initialize()
- {
- parent::_initialize();
- //公众号名称
- $wxJson = model("AdminConfig")
- ->where('admin_id', $this->auth->id)
- ->value('json');
- if (!empty($wxJson)) {
- $wxInfo = json_decode($wxJson, true);
- $this->gzhName = $wxInfo['authorizer_info']['nick_name'];
- }
- $this->model = model('WechatSubscribeConfig');
- }
- /**
- * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
- * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
- * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
- */
- /**
- * 被关注回复设置
- *
- * @return string|\think\response\Json
- * @throws \think\Exception
- */
- public function index()
- {
- $this->request->filter(['strip_tags']);
- if($this->request->isPost()){
- $data = [
- 'status'=>1,
- 'type'=>1
- ];
- $switch = model('WechatSubscribeSwitch')->where('admin_id','eq',$this->auth->id)->find();
- if(!empty($switch)){
- $data['status'] = $switch['status'];
- $data['type'] = $switch['type'];
- }
- return json($data);
- }
- return $this->view->fetch();
- }
- /**
- * 设置开启/关闭状态
- *
- * @return string|\think\response\Json
- */
- public function operate()
- {
- $enabled = $this->request->param('enabled');
- $type = $this->request->param('type');
- $updateData = [];
- if ($enabled == 1) {
- //开启
- $updateData['status'] = 1;
- } elseif ($enabled == 2) {
- //关闭
- $updateData['status'] = 2;
- } else {
- //异常状态
- $this->error('参数错误');
- }
- $updateData['type'] = $type;
- $updateData['updatetime'] = time();
- $config = model('WechatSubscribeSwitch')->where('admin_id', 'eq', $this->auth->id)->find();
- if ($config) {//编辑
- $result = $config->save($updateData);
- } else {
- // switch
- $switch['admin_id'] = $this->auth->id;
- $switch['status'] = $updateData['status'];
- $switch['type'] = $updateData['type'];
- $switch['createtime'] = time();
- $switch['updatetime'] = time();
- model('WechatSubscribeSwitch')->save($switch);
- }
- Redis::instance()->del('OSSC:' . $this->auth->id);
- Redis::instance()->del('OSCC:' . $this->auth->id);
- Redis::instance()->del('OSCCT:' . $this->auth->id);
- if ($result !== false) {
- $this->success();
- } else {
- $this->error($this->model->getError());
- }
- }
- /**
- * 保存设置
- * @return string|\think\response\Json *
- */
- public function save()
- {
- if ($this->request->isPost()) {
- //签到方式 $sign_type 1=> 回复签到; 2 => 自动签到
- $data = json_decode($this->request->post('data'), true);
- $timeChecker = $this->timeChecker(strtotime($data['starttime']),strtotime($data['endtime']),$data['id']);
- if($timeChecker['code'] == 0){
- $this->error($timeChecker['msg']);
- }
- $sign_type = $data["sign_type"]??'';
- //签到文案
- $sign_txt = $data["sign_txt"]??'';
- $newsContent = $data["news_content"]??'[]';
- $textContent = $data["text_content"]??'[]';
- $subType = $data["sub_type"]??'';
- //文本每一二条之间的提示语
- $text_split = $data["text_split"]??'';
- $text_tip = $data["text_tip"]??'';
- $text_tip = str_replace('<br>',"\r\n", $text_tip);
- $text_tip_word = json_encode([
- 'text_split' => $text_split,
- 'text_tip' => $text_tip,
- ],JSON_UNESCAPED_UNICODE);
- $tmp = $subType;
- $content = '';
- if ($subType == 'news') {
- $content = json_encode($newsContent, JSON_UNESCAPED_UNICODE);
- } elseif ($subType == 'text') {
- $content = json_encode($textContent, JSON_UNESCAPED_UNICODE);
- }
- //替换域名
- if ($content) {
- $content = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $content)->data;
- }
- try {
- $isNew = false;
- $config = $this->model
- ->where('id', 'eq', $data['id'])
- ->find();
- if (empty($data['id']) || !isset($data['id'])) {
- //新增设置
- $configData['admin_id'] = $this->auth->id;
- if($subType == 'news'){
- $configData['type'] = 'news';
- $configData['news_content'] = $content;
- $configData['text_content'] = '';
- }else{
- $configData['type'] = 'text';
- $configData['text_content'] = $content;
- $configData['news_content'] = '';
- }
- $configData['event_keys'] = json_encode([
- 'text' => '',
- 'news' => ''
- ], JSON_UNESCAPED_UNICODE);
- $configData['sign_type'] = $sign_type;
- $configData['sign_txt'] = $sign_txt;
- $configData['title'] = $data['title'];
- $configData['starttime'] = strtotime($data['starttime']);
- $configData['endtime'] = strtotime($data['endtime']);
- $configData['status'] = $data['show_type'];
- $result = $this->model->allowField(true)->save($configData);
- if ($result == false) {
- throw new Exception($this->model->getError());
- }
- $isNew = true;
- $updateConfigData = [
- 'event_keys' => [
- 'text' => '',
- 'news' => '',
- ],
- 'text_content' => '',
- 'news_content' => '',
- 'text_tip_word' => $text_tip_word,
- ];
- }
- else {
- $updateConfigData = [
- 'event_keys' => json_decode($config->event_keys, true),
- 'type' => $subType,
- 'text_tip_word' => $text_tip_word,
- 'sign_type' => $sign_type,
- 'sign_txt' => $sign_type == WechatSubscribeConstants::SUBCRIBE_SIGN_TYPE_TWO ? $sign_txt : ''
- ];
- }
- $updateConfigData['title'] = $data['title'];
- $updateConfigData['starttime'] = strtotime($data['starttime']);
- $updateConfigData['endtime'] = strtotime($data['endtime']);
- $updateConfigData['status'] = $data['show_type'];
- if($subType == 'news'){
- $updateConfigData['type'] = 'news';
- $updateConfigData['news_content'] = $content;
- $updateConfigData['text_content'] = '';
- }else{
- $updateConfigData['type'] = 'text';
- $updateConfigData['text_content'] = $content;
- $updateConfigData['news_content'] = '';
- }
- $replyEventkey = '';
- //走更新路线
- if (!$isNew && !empty($config->event_keys)) {
- $eventKeys = json_decode($config->event_keys, true);
- if (isset($eventKeys[$tmp])) {
- $replyEventkey = $eventKeys[$tmp];
- $resourceModel = model("WechatResponse")
- ->where('eventkey', 'eq', $replyEventkey)
- ->find();
- if (empty($resourceModel)) {
- $isNew = true;
- }
- } else {
- $isNew = true;
- }
- }
- if ($isNew) {
- //新建资源
- $resourceData = [
- 'admin_id' => $this->auth->id,
- 'title' => '',
- 'eventkey' => $this->auth->id . '_' . uniqid(),
- 'type' => $tmp,
- 'content' => '',
- 'status' => 'normal',
- 'is_subscribe' => '1'
- ];
- //先创建
- $resourceResult = model("WechatResponse")
- ->allowField(true)
- ->save($resourceData);
- if ($resourceResult !== false) {
- $replyEventkey = $resourceData['eventkey'];
- } else {
- throw new Exception('创建回复资源失败');
- }
- }
- switch ($tmp) {
- case WechatSubscribeConstants::SUBCRIBE_TYPE_TEXT:
- //组织内容
- if($sign_type == WechatSubscribeConstants::SUBCRIBE_SIGN_TYPE_TWO ){
- $temp = WechatSubscribeConstants::SUBCRIBE_TEXT_SIGN_TEMPLATE;
- }else{
- $temp = WechatSubscribeConstants::SUBCRIBE_TEXT_TEMPLATE;
- }
- $bookTemp = WechatSubscribeConstants::SUBCRIBE_TEXT_BOOK_TEMPLATE;
- $bookSets = json_decode($content, true);
- $contentStr = [];
- $resourceContent = '';
- if (is_array($bookSets)) {
- foreach ($bookSets as $index=>$bookSet) {
- if ($index == 1 && $text_split) {
- $contentStr[] = $text_split;
- }
- $url = $bookSet['url'];
- $title = $bookSet['title'];
- $contentStr[] = str_replace(['{URL}', '{TITLE}'], [$url, $title], $bookTemp);
- }
- $resourceContent = str_replace(['{TEXT_TIP}', '$gzh_name', '{CONTENT}'], [$text_tip, $this->gzhName, implode("\r\n\r\n", $contentStr)], $temp);
- }
- if($sign_type == WechatSubscribeConstants::SUBCRIBE_SIGN_TYPE_TWO){
- $sign_str = "<a href='weixin://bizmsgmenu?msgmenucontent=" . Message::MESSAGE_KEYWORD . "&msgmenuid={{" . time() . "}}\"'>{$sign_txt}</a>";
- $resourceContent = str_replace('{SIGNTXT}', $sign_str, $resourceContent);
- }
- $newResourceData = [
- 'type' => 'text',
- 'title' => '文字类型回复',
- 'content' => $resourceContent,
- ];
- $updateConfigData['event_keys']['text'] = $replyEventkey;
- $updateConfigData['text_content'] = $content;
- break;
- case WechatSubscribeConstants::SUBCRIBE_TYPE_NEWS:
- $newResourceData = [
- 'type' => 'news',
- 'title' => '图文类型回复',
- 'content' => $content,
- ];
- $updateConfigData['event_keys']['news'] = $replyEventkey;
- $updateConfigData['news_content'] = $content;
- break;
- }
- //更新资源
- $resourceResult = model("WechatResponse")
- ->allowField(true)
- ->save($newResourceData, ['eventkey'=>$replyEventkey]);
- if ($resourceResult == false) {
- throw new Exception('创建回复资源失败');
- }
- //创建成功后替换关键字回复的event_key
- $maps = [
- 'admin_id' => ['eq', $this->auth->id],
- 'text' => ['eq', 'subscribe']
- ];
- $replyModel = model("WechatAutoreply")->where($maps)->find();
- if (empty($replyModel)) {
- //新增
- $replyModel = model("WechatAutoreply")->allowField(true)
- ->save(
- [
- 'admin_id' => $this->auth->id,
- 'title' => 'subscribe',
- 'text' => 'subscribe',
- 'eventkey' => $replyEventkey,
- 'status' => 'normal'
- ]
- );
- if ($replyModel === false) {
- throw new Exception('创建关键字回复失败');
- }
- } else {
- //更新
- $replyModel->save(['eventkey' => $replyEventkey]);
- }
- $updateConfigData['event_keys'] = json_encode($updateConfigData['event_keys'], JSON_UNESCAPED_UNICODE);
- //更新设置
- $result = $this->model->allowField(true)->save($updateConfigData, ['id' => $data['id']]);
- if ($result !== false) {
- Redis::instance()->del('OSCC:' . $this->auth->id);
- Redis::instance()->del('OSCC:' . $this->auth->id);
- Redis::instance()->del('OSCCT:' . $this->auth->id);
- $this->success();
- } else {
- $this->error($this->model->getError());
- }
- } catch (\think\exception\PDOException $e) {
- $this->error($e->getMessage());
- } catch (Exception $e) {
- $this->error($e->getMessage());
- }
- } else {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- }
- /**
- * 列表
- */
- public function getlist()
- {
- //设置过滤方法
- $this->request->filter(['strip_tags']);
- if ($this->request->isPost())
- {
- $pageSize = $this->request->post("pageSize", 20);
- $pageNo = $this->request->post("pageNo", 1);
- $where['admin_id'] = ['eq',$this->auth->id];
- $total = $this->model->where($where)->order('id','desc')->count();
- $list = $this->model->where($where)->order('id','desc')->paginate($pageSize,false,['page'=>$pageNo]);
- $rows = [];
- if(!empty($list)){
- foreach($list as $key=>$li){
- $rows[$key]['id'] = $li['id'];
- $rows[$key]['title'] = $li['title'];
- $rows[$key]['type'] = $li['type'];
- $rows[$key]['sign_type'] = $li['sign_type'];
- $rows[$key]['sign_txt'] = $li['sign_txt'];
- $rows[$key]['text_tip_word'] = $li['text_tip_word'];
- $rows[$key]['type_text'] = $li['type'] == 'news' ? '图文形式' : '文字形式';
- $rows[$key]['text_content'] = $li['text_content'];
- $rows[$key]['news_content'] = $li['news_content'];
- $rows[$key]['status'] = $li['status'] == 'normal' ? 1 : 2;
- $rows[$key]['status_text'] = $li['status'] == 'normal' ? '生效' : '失效';
- if(empty($li['title'])){
- $rows[$key]['title'] = '老数据';
- }
- $rows[$key]['updatetime'] = date('Y-m-d H:i:s',$li['updatetime']);
- $rows[$key]['starttime'] = empty($li['starttime']) ? '-' : date('Y-m-d H:i:s',$li['starttime']);
- $rows[$key]['endtime'] = empty($li['endtime']) ? '-' : date('Y-m-d H:i:s',$li['endtime']);
- $rows[$key]['kandian'] = \think\Config::get('site.kandian_sign');
- }
- }
- $result = array("total" => $total, "rows" => $rows);
- return json($result);
- }
- return $this->view->fetch();
- }
- private function timeChecker($starttime,$endtime,$id){
- $result = ['code'=>1,'msg'=>''];
- if(empty($starttime) && empty($endtime)){
- $result = ['code'=>0,'msg'=>'起止时间不能为空'];
- }
- if(!empty($starttime) && $starttime >= $endtime){
- $result = ['code'=>0,'msg'=>'结束时间要晚于开始时间'];
- }
- if((!empty($starttime) && empty($endtime)) || (empty($starttime) && !empty($endtime))){
- $result = ['code'=>0,'msg'=>'起止时间不能为空'];
- }
- $maps = [
- 'admin_id' => $this->auth->id,
- 'status' => 'normal'
- ];
- if($id){
- $maps['id'] = ['neq',$id];
- }
- $rows = $this->model->where($maps)->field('id,starttime,endtime')->select();
- if(!empty($rows)){
- foreach($rows as $row){
- if($starttime >= $row['starttime'] && $row['endtime'] >= $starttime){
- $result = ['code'=>0,'msg'=>'设置的起止时间有重复'];
- break;
- }
- if($endtime >= $row['starttime'] && $row['endtime'] >= $endtime){
- $result = ['code'=>0,'msg'=>'设置的起止时间有重复'];
- break;
- }
- if($endtime == $row['starttime'] && $row['endtime'] == $endtime){
- $result = ['code'=>0,'msg'=>'设置的起止时间有重复'];
- break;
- }
- }
- }
- return $result;
- }
- public function getkandian(){
- $kandian = config('site.kandian_sign');
- return ['kandian'=>$kandian];
- }
- }
|