123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514 |
- <?php
- namespace app\admin\controller\wechat;
- use app\common\controller\Backend;
- use app\common\library\Redis;
- use app\common\model\AutoreplyCollect;
- use app\common\model\WechatAutoreply;
- use app\main\constants\CacheConstants;
- use app\main\constants\ErrorCodeConstants;
- use app\main\constants\WechatSubscribeConstants;
- use app\main\service\AutoreplyService;
- use app\main\service\BookService;
- use app\main\service\UrlService;
- use app\main\service\VisitLimitService;
- use think\Collection;
- use think\Exception;
- /**
- * 微信自动回复管理
- *
- * @icon fa fa-circle-o
- */
- class Autoreply extends Backend
- {
- /**
- * @var WechatAutoreply
- */
- protected $model = null;
- protected $noNeedRight = ['check_text_unique','save', 'signreply'];
- protected $dataLimit = 'personal';
- public function _initialize()
- {
- parent::_initialize();
- $this->model = model('WechatAutoreply');
- }
- /**
- * 查看
- */
- public function index()
- {
- //设置过滤方法
- $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();
- $total = $this->model
- ->whereNotIn('title', ['签到', 'subscribe'])
- ->where($where)
- ->order($sort, $order)
- ->count();
- $list = $this->model
- ->whereNotIn('title', ['签到', 'subscribe'])
- ->where($where)
- ->order($sort, $order)
- ->limit($offset, $limit)
- ->select();
- if ($list) {
- $collect = new AutoreplyCollect();
- $ids = array_column($list, 'id');
- if (VisitLimitService::instance()->checkMigratedV2()) {
- $collect_list = AutoreplyService::instance()->getMigrateData($ids)->data;
- } else {
- $collect_list = $collect->whereIn('id', $ids)->column('id,uv,subscribe,money');
- }
- // if (row.type == 'text') {
- // list = JSON.parse(row.text_content);
- // } else if (row.type == 'news') {
- // list = JSON.parse(row.news_content);
- // } else {
- // return '-';
- // }
- $list = Collection::make($list)->toArray();
- foreach ($list as $index => $item) {
- if ($item['type'] == 'text') {
- $resource_list = json_decode($item['text_content'], true);
- } else {
- $resource_list = json_decode($item['news_content'], true);
- }
- $book_names = [];
- if ($resource_list) {
- foreach ($resource_list as $resource) {
- $resource['image_type'] = $resource['image_type'] ?? 1;
- if ($resource['image_type'] == 1 && array_key_exists('book_id', $resource)) {
- $chapter = model('Book')::getChapterInfo($resource['book_id'], $resource['chapter_id']);
- $book = model('Book')->BookInfo($resource['book_id']);
- if ($book && !$chapter['code']) {
- $book_names[] = $book['name'].' '.$chapter['data']['name'];
- }
- }
- }
- }
- if (array_key_exists($item['id'], $collect_list)) {
- $list[$index] = array_merge($item, $collect_list[$item['id']]);
- }
- if (array_key_exists('books', $item) && $item['books']) {
- $list[$index]['books'] = json_decode($item['books'], true);
- }
- $list[$index]['book_names'] = $book_names;
- }
- }
- $result = array("total" => $total, "rows" => $list);
- return json($result);
- }
- if($this->auth->agent_id || $this->group == 3){
- if(!model('AdminConfig')->checkWechatConfig($this->auth->id)){
- $this->error('请先授权微信服务号给本系统,正在跳转授权设置页面~', url('admin/config'));
- }
- }
- return $this->view->fetch();
- }
- /**
- * 添加
- */
- public function add()
- {
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- $params['title'] = $params['text'];
- $keywords = explode(',', $params['title']);
- if (in_array('subscribe', $keywords)) {
- $this->error('请在新版被关注回复中设置关注回复内容');
- }
- /*
- * 已经弃用,如果为了兼容老版可取消注释
- 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);
- }
- $result = $this->model->allowField(true)->save($params);
- 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(['id' => $ids, 'admin_id' => $this->auth->id]);
- if (!$row)
- $this->error(__('No Results were found'));
- if ($row['title'] == 'subscribe')
- $this->error(__('请在新版被关注回复中设置关注回复内容'));
- if ($this->request->isPost())
- {
- $params = $this->request->post("row/a");
- if ($params)
- {
- $params['title'] = $params['text'];
- $row->save($params);
- $this->success();
- }
- $this->error();
- }
- $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id;
- $news = UrlService::instance()->replaceReferralHost($channel_id, $row['news_content'], false)->data;
- $text = UrlService::instance()->replaceReferralHost($channel_id, $row['text_content'], false)->data;
- if ($news) {
- $row['news_content'] = json_decode($news, true);
- }else{
- $row['news_content'] = [];
- }
- if ($text) {
- $row['text_content'] = json_decode($text, true);
- }else{
- $row['text_content'] = [];
- }
- if ($row['text_tip_word']) {
- $row['text_tip_word'] = json_decode($row['text_tip_word'], true);
- }else{
- $row['text_tip_word'] = [
- 'text_split' => '更多精彩内容,点击下方蓝字阅读',
- 'text_tip' => '$user_nickname,欢迎关注「$gzh_name」,点击下方继续阅读',
- ];
- }
- $this->assignconfig("row", $row);
- $this->assignconfig('kandian', \think\Config::get('site.kandian_sign'));
- return $this->view->fetch();
- }
- /**
- * 判断文本是否唯一
- * @internal
- */
- public function check_text_unique()
- {
- $row = $this->request->post("row/a");
- $except = $this->request->post("except");
- $text = isset($row['text']) ? $row['text'] : '';
- if ($this->model->where('text', $text)->where('admin_id', $this->auth->id)->where(function($query) use($except) {
- if ($except)
- {
- $query->where('text', '<>', $except);
- }
- })->count() == 0)
- {
- return $this->success();
- }
- else
- {
- return $this->error(__('Text already exists'));
- }
- }
- public function save()
- {
- $resourceTypeList = ['2' => 'text', '3' => 'news'];
- if ($this->request->isPost()) {
- $params = json_decode($this->request->post('data'), true);
- $newsContent = $params["news_content"];
- $textContent = $params["text_content"];
- $resource_type = $params["resource_type"];
- //文本每一二条之间的提示语
- $text_split = $params["text_split"];
- $text_tip = $params["text_tip"];
- $text_tip = str_replace('<br>',"\r\n", $text_tip);
- $keywords = $params["keywords"];
- $keyword_list = explode(',',$keywords);
- if (in_array('subscribe', $keyword_list)) {
- $this->error('请在新版被关注回复中设置关注回复内容');
- }
- $text_tip_word = json_encode([
- 'text_split' => $text_split,
- 'text_tip' => $text_tip,
- ], JSON_UNESCAPED_UNICODE);
- if (!isset($resourceTypeList[$resource_type])) {
- throw new Exception('模式错误');
- }
- $type = $resourceTypeList[$resource_type];
- $channel_id = $this->auth->agent_id ? $this->auth->agent_id : $this->auth->channel_id;
- if ($textContent) {
- foreach ($textContent as $index => $item) {
- if (empty($item['url']) && isset($item['chapter_id'])) {
- $textContent[$index]['url'] = getCurrentDomain($channel_id, '/index/book/chapter?book_id=' . $item['book_id'] . '&chapter_id=' . $item['chapter_id']);
- }
- }
- $textContent = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), json_encode($textContent, JSON_UNESCAPED_UNICODE))->data;
- }
- if ($newsContent) {
- foreach ($newsContent as $index => $item) {
- if (empty($item['url']) && isset($item['chapter_id'])) {
- $newsContent[$index]['url'] = getCurrentDomain($channel_id, '/index/book/chapter?book_id=' . $item['book_id'] . '&chapter_id=' . $item['chapter_id']);
- }
- }
- $newsContent = UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), json_encode($newsContent, JSON_UNESCAPED_UNICODE))->data;
- }
- //替换域名
- $time = time();
- try {
- //编辑
- if ($params['id']??'') {
- $reply = $this->model
- ->where('id', $params['id'])
- ->find();
- if (!$reply) {
- throw new Exception('数据不存在');
- }
- }else{
- $reply = $this->model
- ->where('title', $keywords)
- ->where('admin_id', $this->auth->id)
- ->find();
- }
- if (!$reply) {
- //新增设置
- $data['admin_id'] = $this->auth->id;
- $data['type'] = $type;
- $data['status'] = 'normal';
- $data['title'] = $data['text'] = $keywords;
- $data['text_content'] = $textContent;
- $data['news_content'] = $newsContent;
- $data['text_tip_word'] = $text_tip_word;
- $data['createtime'] = $data['updatetime'] = $time;
- $data['event_keys'] = json_encode([
- 'text' => $this->auth->id . '_' . uniqid(),
- 'news' => $this->auth->id . '_' . uniqid(),
- ], JSON_UNESCAPED_UNICODE);
- $result = $this->model->insert($data);
- if ($result == false) {
- throw new Exception($this->model->getError());
- }
- } else {
- $update = [
- 'type' => $type,
- 'text_tip_word' => $text_tip_word,
- 'text_content' => $textContent,
- 'news_content' => $newsContent,
- 'createtime' => $time,
- 'updatetime' => $time,
- ];
- if (!$reply['event_keys']) {
- $update['event_keys'] = json_encode([
- 'text' => $this->auth->id . '_' . uniqid(),
- 'news' => $this->auth->id . '_' . uniqid(),
- ], JSON_UNESCAPED_UNICODE);
- }
- $update['title'] = $update['text'] = $keywords;
- $data = array_merge($reply->toArray(), $update);
- $this->model->update($update, ['id' => $reply['id']]);
- }
- $event_keys = json_decode($data['event_keys'], true);
- foreach ($event_keys as $type => $event_key) {
- $update = [];
- switch ($type) {
- case WechatSubscribeConstants::SUBCRIBE_TYPE_TEXT:
- if ($textContent) {
- //组织内容
- $resourceContent = $this->getTextContent($textContent, $text_split, $text_tip);
- $update = [
- 'type' => 'text',
- 'title' => '文字类型回复',
- 'content' => $resourceContent,
- 'updatetime' => $time,
- 'status' => 'normal',
- ];
- }
- break;
- default:
- if ($newsContent) {
- $update = [
- 'type' => 'news',
- 'title' => '图文类型回复',
- 'content' => $newsContent,
- 'updatetime' => $time,
- ];
- }
- break;
- }
- $where = [
- 'admin_id' => $this->auth->id,
- 'eventkey' => $event_key,
- ];
- if ($update) {
- $update['status'] = 'normal';
- if (!model("WechatResponse")->where($where)->find()) {
- $insert = array_merge($where, $update, ['createtime' => $time]);
- model("WechatResponse")->insert($insert);
- } else {
- model("WechatResponse")->update($update, $where);
- }
- }
- }
- } catch (\think\exception\PDOException $e) {
- $this->error($e->getMessage());
- } catch (Exception $e) {
- $this->error($e->getMessage().$e->getLine());
- }
- } else {
- $this->error(__('Parameter %s can not be empty', ''));
- }
- }
- public function getTextContent($content, $text_split, $text_tip)
- {
- $temp = WechatSubscribeConstants::AUTOREPLY_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);
- }
- $wxJson = model("AdminConfig")
- ->where('admin_id', $this->auth->id)
- ->value('json');
- $gzhName = '';
- if (!empty($wxJson)) {
- $wxInfo = json_decode($wxJson, true);
- $gzhName = $wxInfo['authorizer_info']['nick_name'];
- }
- $resourceContent = str_replace(['{TEXT_TIP}', '$gzh_name', '{CONTENT}'], [$text_tip, $gzhName, implode("\r\n\r\n", $contentStr)], $temp);
- }
- return $resourceContent;
- }
- public function signreply()
- {
- $where = [
- 'admin_id' => $this->auth->id,
- 'title' => '签到',
- 'status' => 'normal',
- ];
- $find = model('wechat_autoreply')->where($where)->find();
- if ($this->request->isPost()) {
- $channelId = $this->getCurrentAccountChannelId();
- $data = json_decode($this->request->post('data'), true);
- $type = $data['type']??1;
- $text_split = $data['text_split']??'';
- $text = $data['text']??'{}';
- $textContent = UrlService::instance()->replaceReferralHost($channelId, json_encode($text, JSON_UNESCAPED_UNICODE))->data;
- if ($find) {
- if ($type == 2) {
- $update = [
- 'type' => 'text',
- 'text_content' => $textContent,
- 'text_tip_word' => $text_split
- ];
- } else {
- $update = [
- 'type' => 'news',
- 'news_content' => '[]',
- ];
- }
- model('wechat_autoreply')->update($update, $where);
- $cacheKey = CacheConstants::getSignReplyCache($this->auth->id);
- Redis::instance()->del($cacheKey.'OS:1');
- Redis::instance()->del($cacheKey.'OS:2');
- Redis::instance()->del($cacheKey.'OS:0');
- } else {
- $insert = $where;
- if ($type == 2) {
- $insert['type'] = 'text';
- } else {
- $insert['type'] = 'news';
- }
- //新增设置
- $insert['status'] = 'normal';
- $insert['title'] = $insert['text'] = '签到';
- $insert['text_content'] = $textContent;
- $insert['news_content'] = '[]';
- $insert['text_tip_word'] = $text_split;
- $insert['createtime'] = $insert['updatetime'] = time();
- $insert['event_keys'] = json_encode([
- 'text' => $this->auth->id . '_' . uniqid(),
- 'news' => $this->auth->id . '_' . uniqid(),
- ], JSON_UNESCAPED_UNICODE);
- model('wechat_autoreply')->insert($insert);
- }
- $cacheKey = CacheConstants::getSignReplyCache($channelId);
- Redis::instance()->del($cacheKey);
- $this->success();
- }
- if ($find && $find['text_content'] != '') {
- $data = [
- 'text' => UrlService::instance()->replaceReferralHost($this->getCurrentAccountChannelId(), $find['text_content'], false)->data,
- 'type' => $find['type'] == 'news' ? 1 : 2,
- 'text_split' => $find['text_tip_word'],
- ];
- } else {
- $data = [
- 'text' => '[]',
- 'type' => 1,
- 'text_split' => '',
- ];
- }
- $this->assignconfig($data);
- return $this->view->fetch();
- }
- }
|