diff --git a/application/api/controller/Aiarticle.php b/application/api/controller/Aiarticle.php index ca00917..5a9c856 100644 --- a/application/api/controller/Aiarticle.php +++ b/application/api/controller/Aiarticle.php @@ -30,7 +30,7 @@ class Aiarticle extends Base protected $sResponesData; protected $sError; protected $timeout = 60; - protected $aAiFileds = ['article_id','title_english','title_chinese','journal_id','cite','covered','digest','research_result','content','highlights','discussion','prospect','journal_content','research_background','journal_topic']; + protected $aAiFileds = ['article_id','title_english','title_chinese','journal_id','covered','digest','research_result','content','highlights','discussion','prospect','research_background',]; protected $sJournalUrl = 'http://journalapi.tmrjournals.com/public/index.php';//'http://zmzm.journal.dev.com'; // protected $sJournalUsx = 'https://www.tmrjournals.com'; @@ -83,8 +83,6 @@ class Aiarticle extends Base {#title_chinese#} 10 请将稿件内容翻译成中文 {#content#} - 11 请将稿件所属期刊简介翻译 - {#journal_content#} **稿件关键信息** - 稿件简介:{#abstract#} @@ -97,7 +95,6 @@ class Aiarticle extends Base { "title_chinese": "", "content": "", - "journal_content": "", "covered": "【总字数<=100】", "digest": "【总字数<=500】", "research_background": "", @@ -107,6 +104,11 @@ class Aiarticle extends Base "discussion": "" }' ]; + + //文章图片icon地址 + protected $sArticleIcon = '/public/articleicon/'; + //期刊图片icon地址 + protected $sJournalIcon = '/public/journalicon/'; //"highlights": { // "theory_innovation": "【中西医理论结合点】", // "methodology": "【关键技术+量化指标】", @@ -290,20 +292,16 @@ class Aiarticle extends Base $aContent['article_id'] = $iArticleId; $aContent['title_english'] = $aArticle['title']; $aContent['journal_id'] = $aArticle['journal_id']; - //文章引用 - $aContent['cite'] = $this->_cite($aArticle,$aJournal,$aJournalStage); - if(!empty($aJournal['journal_topic'])){ - $aContent['journal_topic'] = $aJournal['journal_topic']; - } + //获取AI生成表里的数据判断是新增或更新 - $aAiContent = json_decode($this->getAiArticle($iArticleId),true); + $aAiContent = json_decode($this->getAiArticle($iArticleId,1),true); $aAiContent = empty($aAiContent['data']) ? [] : $aAiContent['data']; $aAiArticle = empty($aAiContent['ai_article']) ? [] : $aAiContent['ai_article']; $aAiAuthor = empty($aAiContent['ai_article_autho']) ? [] : $aAiContent['ai_article_autho']; if(empty($aAiArticle)){//新增 //执行数据入库 - $aResult = $this->addAiArticle($aContent,$aAuthor); + $aResult = $this->addAiArticle($aContent); } if(!empty($aAiArticle)){//更新 if(empty($aAiArticle['ai_article_id'])){ @@ -353,7 +351,7 @@ class Aiarticle extends Base $iArticleId = $aArticleId[0]; $aEmail = array_unique(array_column($aAuthor, 'email')); $aWhere = ['email' => ['in',$aEmail]]; - $aUser = Db::name('user')->field('user_id,realname,email,localname')->where($aWhere)->select(); + $aUser = Db::name('user')->field('user_id,realname,email,localname,icon')->where($aWhere)->select(); if(empty($aUser)){ return []; } @@ -372,8 +370,8 @@ class Aiarticle extends Base //姓名 $sName = empty($aAuthor[$value['email']]['author_name']) ? '' : $aAuthor[$value['email']]['author_name']; - $sName = empty($sName) ? $value['realname'] : $sName; $sName = empty($sName) ? $value['localname'] : $sName; + $sName = empty($sName) ? $value['realname'] : $sName; //单位 $sCompany = empty($aAuthor[$value['email']]['company']) ? '' : $aAuthor[$value['email']]['company']; @@ -385,20 +383,7 @@ class Aiarticle extends Base //简介 $sIntroduction = empty($aUserInfo[$value['user_id']]['introduction']) ? '' : $aUserInfo[$value['user_id']]['introduction']; - //请求AI翻译 - // $aSearch['{#author_name#}'] = $sName; - // $aSearch['{#company#}'] = $sCompany; - // $aSearch['{#technical#}'] = $sTechnical; - // $aSearch['{#introduction#}'] = $sIntroduction; - // $aResult = $this->_createContentForOpenAI($aSearch,1); - // $aResult = json_decode($aResult,true); - // if($aResult['status'] == 1){ - // $aContent = empty($aResult['data']) ? [] : $aResult['data']; - // $sCompany = empty($aContent['company']) ? $sCompany : $aContent['company']; - // $sTechnical = empty($aContent['technical']) ? $sTechnical : $aContent['technical']; - // $sIntroduction = empty($aContent['introduction']) ? $sIntroduction : $aContent['introduction']; - // } - $aInfo[] = ['email' => $value['email'],'author_name' => $sName,'technical' => $sTechnical,'introduction' => $sIntroduction,'company' => $sCompany,'article_id' => $iArticleId,'create_time' => time()]; + $aInfo[] = ['user_id' => $value['user_id'],'email' => $value['email'],'author_name' => $sName,'technical' => $sTechnical,'introduction' => $sIntroduction,'company' => $sCompany,'article_id' => $iArticleId,'create_time' => time(),'icon' => $value['icon']]; } return $aInfo; @@ -442,27 +427,39 @@ class Aiarticle extends Base * 获取Ai生成文章信息 * @param article_id 文章ID */ - public function getAiArticle($iArticleId = 0){ + public function getAiArticle($iArticleId = 0,$iSelectAuthor = 2){ $aParam = $this->request->post(); $iArticleId = empty($iArticleId) ? $aParam['article_id'] : $iArticleId; //查询AI生成的文章内容 - $aParam['article_id'] = $iArticleId; - $aParam['is_delete'] = 2; - $aAiArticle = Db::name('ai_article')->where($aParam)->find(); + $aWhere['article_id'] = $iArticleId; + $aWhere['is_delete'] = 2; + $aAiArticle = Db::name('ai_article')->where($aWhere)->find(); if(empty($aAiArticle)){ return json_encode(['status' => 1,'msg' => 'data is null','data' => ['ai_article' => []]]); } + //查询文章通讯作者 - if($aAuthorInfo = Db::name('ai_article_author')->where(['article_id' => $iArticleId])->select()){ - //查询头像 - $aEmail = array_column($aAuthorInfo, 'email'); - $aUser = Db::name('user')->where(['email' => ['in',$aEmail]])->column('email,icon'); - foreach ($aAuthorInfo as $key => $value) { - $aAuthorInfo[$key]['icon'] = empty($aUser[$value['email']]) ? '/static/img/userImg.f3d9bc3b.jpg' : '/public/usericon/'.$aUser[$value['email']]; + $aAiAuthor = []; + if($iSelectAuthor == 2){ + $aResult = json_decode($this->getArticle($iArticleId),true); + if($aResult['status'] == 1){ + //获取数据 + $aArticleContent = empty($aResult['data']) ? [] : $aResult['data']; + //通讯作者 + $aAuthor = empty($aArticleContent['author']) ? [] : $aArticleContent['author']; + if(!empty($aAuthor)){ + $aAiAuthor = $this->_dealAuthor($aAuthor); + if(!empty($aAiAuthor)){ + foreach ($aAiAuthor as $key => $value) { + $aAiAuthor[$key]['icon_path'] = empty($value['icon']) ? '/static/img/userImg.f3d9bc3b.jpg' : '/public/usericon/'.$value['icon']; + } + } + } + } } - return json_encode(['status' => 1,'msg' => 'success','data' => ['ai_article' => $aAiArticle,'ai_article_author' => $aAuthorInfo]]); + return json_encode(['status' => 1,'msg' => 'success','data' => ['ai_article' => $aAiArticle,'ai_article_author' => $aAiAuthor]]); } /** * 基础HTML过滤 @@ -518,35 +515,10 @@ class Aiarticle extends Base //作者判断空值 $aInsertParam['author'] = empty($aInsertParam['author']) ? 'TMR编辑部' : $aInsertParam['author']; - Db::startTrans(); if(!$iId = Db::name('ai_article')->insertGetId($aInsertParam)){ return ['status' => 3,'msg' => 'Adding AI article failed']; } $aResult['data'] = array_merge($aInsertParam,['ai_article_id' => $iId]); - if(!empty($aAuthor)){ - $aInfo = $this->_dealAuthor($aAuthor); - - if(!empty($aInfo)){ - - foreach ($aInfo as $key => $value) { - //请求AI翻译 - $aSearch['{#author_name#}'] = $value['author_name']; - $aSearch['{#company#}'] = $value['company']; - $aSearch['{#technical#}'] = $value['technical']; - $aSearch['{#introduction#}'] = $value['introduction']; - $aResultInfo = $this->_createContentForOpenAI($aSearch,1); - $aResultInfo = json_decode($aResultInfo,true); - if($aResultInfo['status'] == 1){ - $aContent = empty($aResultInfo['data']) ? [] : $aResultInfo['data']; - $aInfo[$key]['company'] = empty($aContent['company']) ? $value['company'] : $aContent['company']; - $aInfo[$key]['technical'] = empty($aContent['technical']) ? $value['technical'] : $aContent['technical']; - $aInfo[$key]['introduction'] = empty($aContent['introduction']) ? $value['introduction'] : $aContent['introduction']; - } - } - Db::name('ai_article_author')->insertAll($aInfo); - } - } - Db::commit(); return json_encode($aResult); } @@ -587,28 +559,18 @@ class Aiarticle extends Base //必填参数验证 $aFields = $this->aAiFileds; - $bStatus = true; $sFiled = ''; $aUpdateParam = []; foreach($aFields as $val){ if(!isset($aParam[$val])){ continue; } - if(empty($aParam[$val])){ - $bStatus = false; - $sFiled = $val; - break; - } $aUpdateParam[$val] = addslashes(strip_tags($aParam[$val])); } - if($bStatus == false){ - return json_encode(['status' => 2,'msg' => $sFiled.'cannot be empty']); - } if(empty($aUpdateParam)){ return json_encode(['status' => 1,'msg' => 'No data currently being processed']); } - Db::startTrans(); //执行入库 $aUpdateParam['update_time'] = time(); $result = Db::name('ai_article')->where('ai_article_id',$iAiArticleId)->limit(1)->update($aUpdateParam); @@ -616,23 +578,6 @@ class Aiarticle extends Base $aResult = json_encode(['status' => 3,'msg' => 'UPDATEING AI article failed']); } $aResult['data'] = $aUpdateParam; - - //更新作者信息 - $aAuthorList = empty($aParam['author_list']) ? []: $aParam['author_list']; - $aAuthorList = is_array($aParam['author_list']) ? $aAuthorList: json_decode($aAuthorList,true); - if(!empty($aAuthorList)){ - foreach ($aAuthorList as $key => $value) { - if(empty($value['email'])){ - continue; - } - $aWhere = ['article_id' => $iArticleId,'email' => $value['email']]; - unset($value['article_id']); - unset($value['email']); - $value['update_time'] = time(); - Db::name('ai_article_author')->where($aWhere)->limit(1)->update($value); - } - } - Db::commit(); return json_encode($aResult); } @@ -661,11 +606,9 @@ class Aiarticle extends Base } //获取AI生成文章内容 - $aAiContent = json_decode($this->getAiArticle($iArticleId),true); + $aAiContent = json_decode($this->getAiArticle($iArticleId,1),true); $aAiContent = empty($aAiContent['data']) ? [] : $aAiContent['data']; $aAiArticle = empty($aAiContent['ai_article']) ? [] : $aAiContent['ai_article']; - //AI通讯作者 - $aAiAuthor = empty($aAiContent['ai_article_author']) ? [] : $aAiContent['ai_article_author']; //判断是否生成AI内容 if(empty($aAiArticle)){ return json_encode(['status' => 3, 'msg' => 'The article content of WeChat official account has not been generated']); @@ -687,10 +630,17 @@ class Aiarticle extends Base //期刊数据 $aJournal = empty($aArticleContent['journal']) ? [] : $aArticleContent['journal']; + //子期刊数据 + $aJournalStage = empty($aArticleContent['journal_stage']) ? [] : $aArticleContent['journal_stage']; + + //通讯作者 + $aAuthor = empty($aArticleContent['author']) ? [] : $aArticleContent['author']; + //文章图片 - $sArticleIcon = trim($this->sJournalUsx,'/').'/public/articleicon/'.$aArticle['article_icon']; + $sArticleIcon = trim($this->sJournalUsx,'/').$this->sArticleIcon.$aArticle['article_icon']; //期刊图片 - $sJournalIcon = trim($this->sJournalUsx,'/').'/public/journalicon/'.$aJournal['journal_icon']; + $sJournalIcon = trim($this->sJournalUsx,'/').$this->sJournalIcon.$aJournal['journal_icon']; + //获取期刊图片二维码 $aJournalQrCode = $this->createJournalQrCode($aJournal); $sJournalCode = empty($aJournalQrCode['qrcode_url']) ? '' : $this->sSubmissionUrl.'public/qrcode/'.$aJournalQrCode['qrcode_url']; @@ -701,6 +651,9 @@ class Aiarticle extends Base $sArticleCode = empty($aArticleQrCode['qrcode_url']) ? '' : $this->sSubmissionUrl.'public/qrcode/'.$aArticleQrCode['qrcode_url']; $aAiArticle['article_qrcode'] = $sArticleCode; + //文章cite + $aAiArticle['cite'] = $this->_cite($aArticle,$aJournal,$aJournalStage); + // //上传素材到微信 if($iIsSync == 1){ @@ -729,13 +682,14 @@ class Aiarticle extends Base $aAiArticle['article_qrcode'] = empty($aArticleQrCodeData['media_url']) ? $sArticleIcon : $aArticleQrCodeData['media_url']; //作者图片上传 - if(!empty($aAiAuthor)){ - foreach ($aAiAuthor as $key => $value) { - if(empty($value['icon'])){ + if(!empty($aAuthor)){ + $aAuthor = $this->_dealAuthor($aAuthor); + foreach ($aAuthor as $key => $value) { + if(empty($value['icon'])){ continue; - } + } //文章二维码图片上传 - $aUpload = ['email' => $value['email'],'icon' => $value['icon']]; + $aUpload = ['email' => $value['email'],'icon' => $value['icon'],'user_id' => $value['user_id']]; $aAuthorResult = json_decode($this->_updateArticleAuthor($aUpload),true); $aAuthorData = empty($aAuthorResult['data']) ? [] : $aAuthorResult['data']; $aAiAuthor[$key]['icon'] = empty($aAuthorData['media_url']) ? $value['icon'] : $aAuthorData['media_url']; @@ -756,8 +710,12 @@ class Aiarticle extends Base $journal_usx .= $aJournal['journal_usx']??''.'/'; } $aAiArticle['journal_usx_url'] = trim($journal_usx); + + //处理期刊内容 + if(empty($aJournal['journal_content'])){ + $aJournal['journal_content'] = empty($aJournal['journal_content']) ? $aJournal['journal_content_english'] : $aJournal['journal_content']; + } $aAiArticle += $aJournal; - //获取模版信息 $sTemplatePath = ROOT_PATH."public/wechatTemplate/".$iTemplateId.'.html'; @@ -777,14 +735,11 @@ class Aiarticle extends Base $aSearch['{###'.$key.'###}'] = htmlspecialchars(strip_tags($value)); } //处理通讯作者信息数据 - $aAuthorInfo = json_decode($this->dealTemplateAuthor($aAiAuthor,$iTemplateId),true); + $aAuthorInfo = json_decode($this->dealTemplateAuthor($aAuthor,$iTemplateId),true); + $aSearch['{###author_info###}'] = empty($aAuthorInfo['data']['author_info']) ? ' ' : implode("\n", $aAuthorInfo['data']['author_info']); $aSearch['{###author###}'] = empty($aAuthorInfo['data']['author']) ? ' ' : $aAuthorInfo['data']['author']; - // //处理公众号推荐 - // $aRecommend = json_decode($this->dealTemplateWechatRecommend($aArticle['journal_id'],$iTemplateId),true); - // $aSearch['{###wechat_recommend###}'] = empty($aRecommend['data']) ? ' ' : implode("\n", $aRecommend['data']); - //处理往期推荐数据 $aPreviousRecommend = json_decode($this->dealTemplatePreviousRecommend($aArticle,$iTemplateId),true); if(empty($aPreviousRecommend['data'])){ @@ -799,7 +754,8 @@ class Aiarticle extends Base //处理期刊主题数据 - $aTopic = json_decode($this->dealTemplateTopic($aAiArticle['journal_topic'],$iTemplateId),true); + $sJournalTopic = empty($aJournal['journal_topic']) ? '' : $aJournal['journal_topic']; + $aTopic = json_decode($this->dealTemplateTopic($sJournalTopic,$iTemplateId),true); if(empty($aTopic['data'])){ $aSearch['{###topic_name_summary###}'] = ''; }else{ @@ -817,7 +773,8 @@ class Aiarticle extends Base } $aSearch['{###jabbr###}'] = trim(trim($aSearch['{###jabbr###}'],'.'),'。'); - + $aSearch['{###free_year###}'] = date('Y'); + $aSearch['{###covered###}'] = '内容涵盖'.str_replace('研究涵盖', '', $aSearch['{###covered###}']); $sTemplate = str_replace(array_keys($aSearch), array_values($aSearch), $sTemplate); file_put_contents(ROOT_PATH.'public/template_info.html', $sTemplate); return json_encode(['status' => 1, 'msg' => '模版生成成功','data' => ['template' => $sTemplate]]); @@ -834,6 +791,9 @@ class Aiarticle extends Base return json_encode(['status' => 2,'msg' => 'Corresponding author or template does not exist']); } + //处理作者 + $aAuthor = $this->_dealAuthor($aAuthor); + //获取通讯作者模版 $sAuthorTemplatePath = ROOT_PATH."public/wechatTemplate/".$iTemplateId.'_author.html'; if (!file_exists($sAuthorTemplatePath)) { @@ -850,60 +810,41 @@ class Aiarticle extends Base $sAuthorInfo = ''; $aLogo = $this->aLogo; foreach ($aAuthor as $key => $value) { + + //请求AI翻译 + $aSearch['{#company#}'] = empty($value['company']) ? '' : $value['company']; + $aSearch['{#technical#}'] = empty($value['technical']) ? '' : $value['technical']; + $aSearch['{#introduction#}'] = empty($value['introduction']) ? '' : $value['introduction']; + $aResult = $this->_createContentForOpenAI($aSearch,1); + $aResult = json_decode($aResult,true); + if($aResult['status'] == 1){ + $aContent = empty($aResult['data']) ? [] : $aResult['data']; + $value['company'] = empty($aContent['company']) ? $value['company'] : $aContent['company']; + $value['technical'] = empty($aContent['technical']) ? $value['technical'] : $aContent['technical']; + $value['introduction'] = empty($aContent['introduction']) ? $value['introduction'] : $aContent['introduction']; + } $aAuthorSerach = []; + if(!empty($value['company'])){ + $value['company'] =str_replace(',', ',', $value['company']); + $aCompany = explode(',', $value['company']); + } + $value['company'] = empty($aCompany[0]) ? $value['company'] : trim($aCompany[0],','); foreach ($value as $k => $val) { if($k == 'icon'){ - if($val == $aLogo['url']){ - $aAuthorSerach['{###'.$k.'###}'] = $val; - }else{ - $aAuthorSerach['{###'.$k.'###}'] = trim($this->sSubmissionUrl,'/').$val; - } - $aAuthorSerach['{###'.$k.'###}'] = trim($aAuthorSerach['{###'.$k.'###}'],'/'); + $aAuthorSerach['{###icon_path###}'] = empty($val) ? $aLogo['url'] : trim($this->sSubmissionUrl,'/').'/public/usericon/'.$val; + $aAuthorSerach['{###icon_path###}'] = trim($aAuthorSerach['{###icon_path###}'],'/'); }else{ $aAuthorSerach['{###'.$k.'###}'] = trim($val,'/'); } } $aAuthorSerachInfo[] = str_replace(array_keys($aAuthorSerach), array_values($aAuthorSerach), $sAuthorTemplate); - $sAuthorInfo = $value['company'].' '.$value['author_name'].';'; + $sTechnical = empty($value['technical']) ? '老师' : $value['technical']; + $sAuthorInfo .= $value['company'].$value['author_name'].$sTechnical.','; } + $sAuthorInfo = trim($sAuthorInfo,','); return json_encode(['status' => 1,'msg' => 'success','data' => ['author_info' => $aAuthorSerachInfo,'author' => trim($sAuthorInfo,';')]]); } - // /** - // * 处理公众号推荐 - // * @param article_id 文章ID - // */ - // private function dealTemplateWechatRecommend($iJournalId = 0,$iTemplateId = 0){ - - // if(empty($iTemplateId)){ - // return json_encode(['status' => 2,'msg' => 'template does not exist']); - // } - // //获取通讯作者 - // $sTemplatePath = ROOT_PATH."public/wechatTemplate/".$iTemplateId.'_wechat_recommend.html'; - // if (!file_exists($sTemplatePath)) { - // return json_encode(['status' => 4, 'msg' => 'Corresponding author template does not exist','data' => '']); - // } - // if (!is_readable($sTemplatePath)) { - // return json_encode(['status' => 5, 'msg' => 'The corresponding author template is unreadable','data' => '']); - // } - // $sTemplate = file_get_contents($sTemplatePath); - - // //查询公众号推荐 - // $aRecommend = Db::name('ai_article')->field('article_id,title_chinese,covered,digest')->where('journal_id',$iJournalId)->select(); - - // $aSearchInfo = []; - // if(!empty($aRecommend)){ - // foreach ($aRecommend as $key => $value) { - // $aSerach = []; - // foreach ($value as $k => $val) { - // $aSerach['{###'.$k.'###}'] = trim(trim(trim($val),'【'),'】'); - // } - // $aSearchInfo[] = str_replace(array_keys($aSerach), array_values($aSerach), $sTemplate); - // } - // } - // return json_encode(['status' => 1,'msg' => 'success','data' => $aSearchInfo]); - // } - /** * 处理模版主题 * @param article_id 文章ID @@ -987,7 +928,7 @@ class Aiarticle extends Base continue; } $aSerach['{###wechat_url###}'] = $value['wechat_url']; - $sIcon = empty($aProductionArticle[$value['article_id']]) ? '' : trim($this->sJournalUsx,'/').'/public/articleicon/'.$aProductionArticle[$value['article_id']]; + $sIcon = empty($aProductionArticle[$value['article_id']]) ? '' : trim($this->sJournalUsx,'/').$this->sArticleIcon.$aProductionArticle[$value['article_id']]; $aSerach['{###wechat_media_url###}'] = empty($value['wechat_media_url']) ? $sIcon : $value['wechat_media_url']; $aSearchInfo[] = str_replace(array_keys($aSerach), array_values($aSerach), $sTemplate); } @@ -1025,7 +966,7 @@ class Aiarticle extends Base if(empty($sLogo)){ $sImg = QrCodeImage::generate($sUrl,500,$sQrCodeUrl); }else{ - $sLogo = trim($this->sJournalUsx,'/').'/public/journalicon/'.$sLogo; + $sLogo = trim($this->sJournalUsx,'/').$this->sJournalIcon.$sLogo; $aImageInfo = json_decode($this->getImage($sLogo,$iJournalId,'journal'),true); if(empty($aImageInfo['data'])){ $sImg = QrCodeImage::generate($sUrl,500,$sQrCodeUrl); @@ -1069,7 +1010,7 @@ class Aiarticle extends Base if(empty($sLogo)){ $sImg = QrCodeImage::generate($sUrl,500,$sQrCodeUrl); }else{ - $sLogo = trim($this->sJournalUsx,'/').'/public/articleicon/'.$sLogo; + $sLogo = trim($this->sJournalUsx,'/').$this->sArticleIcon.$sLogo; $aImageInfo = json_decode($this->getImage($sLogo,$iArticleId,'article'),true); if(empty($aImageInfo['data'])){ $sImg = QrCodeImage::generate($sUrl,500,$sQrCodeUrl); @@ -1181,6 +1122,7 @@ class Aiarticle extends Base //获取模版生成内容 $aResult = json_decode($this->getTemplateContent($iArticleId,$iTemplateId,1),true); + $iStatus = empty($aResult['status']) ? 0 : $aResult['status'];//状态 $sMsg = empty($aResult['msg']) ? 'The content is empty' : $aResult['msg']; if($iStatus != 1){ @@ -1195,123 +1137,10 @@ class Aiarticle extends Base $aParam['template_content'] = $aData['template']; $aParam['template_id'] = $iTemplateId; $aResult = $this->addDraft($aParam); + echo '
';var_dump($aResult);exit;
return $aResult;
}
- /**
- * CURL 发送请求获取Token
- * @param $appid AppID(小程序ID)
- * @param $secret AppSecret(小程序密钥)
- */
-
- private function getAccessToken() {
- //Token缓存值
- $sToken = Cache::get($this->sWechatAccessToken);
- //判断缓存是否存在
- if (!$sToken) { //不存在
- //组装接口地址
- $sUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
- . $this->sAppID . "&secret=" . $this->sAppSecret;
-
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $sUrl);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
- $result = curl_exec($curl);
- //请求失败
- if (curl_errno($curl)){
- $this->sError = curl_errno($curl);
- curl_close($curl);
- return FALSE;
- }
- $result = json_decode($result, true);
- if (!empty($result['access_token'])) {
- $sToken = $result['access_token'];
- Cache::set($this->sWechatAccessToken, $sToken, 7000); // 有效期7200秒
- }
- curl_close($curl);
- }
- return $sToken;
- }
-
- /**
- * CURL 发送请求上传永久素材
- * @param $sToken Token
- * @param $sPath 图片地址
- */
- public function uploadMaterial($sPath = '') {
-
- $aParam = $this->request->post();
-
- $sPath = empty($sPath) ? $aParam['path'] : $sPath;
- // $sPath = ROOT_PATH.'static/img/'.$sPath;
- // return json_encode(['status' => 1,'data' => ['media_id' => '1111111','url' => '22222']]);
- //返回结果数组
- $aResult = ['status' => 1,'msg' => '上传素材成功','data' => []];
-
- $sPath = empty($sPath) ? $aParam['image_path']?? '' : $sPath;//文件地址
- $sType = empty($aParam['type']) ? 'image' : $aParam['type'];//文件类型
-
- // 验证文件有效性
- if (!file_exists($sPath)) {
- return json_encode(['status' => 2,'msg' => '素材不存在'.$sPath]);
- }
- if (!is_readable($sPath)) {
- return json_encode(['status' => 3,'msg' => '素材不可读']);
- }
- if (filesize($sPath) > 10 * 1024 * 1024) {
- return json_encode(['status' => 4,'msg' => '素材不能超过10MB']);
- }
-
- //获取Token
- $sToken = $this->getAccessToken();
- if (empty($sToken)) {
- return json_encode(['status' => 5, 'msg' => '获取access_token失败']);
- }
-
- //CURL 请求接口
- //文件参数
- $data = [
- 'media' => new \CURLFile(
- realpath($sPath),
- mime_content_type($sPath), // 自动检测MIME类型
- basename($sPath) // 上传后的文件名
- ), // 关键:使用CURLFile对象
- ];
- $sUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$sToken}&type={$sType}";
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $sUrl);
- curl_setopt($curl, CURLOPT_POST, true); //设置为POST方式
- curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE) ; // 获取数据返回
- curl_setopt($curl, CURLOPT_PROXY,$this->proxy);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,true);
- curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
- //执行
- $response = curl_exec($curl);
-
- //请求失败
- if (curl_errno($curl)){
- curl_close($curl);
- return json_encode(['status' => 6,'msg' => "网络请求失败: " . curl_errno($curl)]);
- }
- curl_close($curl);//关闭请求
-
- //获取返回结果
- $response = json_decode($response, true);
- if (!empty($response['errcode']) && $response['errcode'] != 0) {
- return json_encode(['status' => 7,'msg' => "微信接口错误: [{$response['errcode']}] {$response['errmsg']}"]);
- }
-
- //插入数据库
- if(empty($response['media_id'])){
- return json_encode(['status' => 8,'msg' => "未获取到上传素材"]);
- }
- return json_encode(['status' => 1,'msg' => 'success','data' => $response]);
- }
-
/**
* 添加文章素材
* @param article_id 文章ID
@@ -1376,8 +1205,6 @@ class Aiarticle extends Base
}
/**
* 添加期刊素材
- * @param $sToken Token
- * @param $sPath 图片地址
*/
private function _addJournalMaterial($aParam = []){
@@ -1539,16 +1366,13 @@ class Aiarticle extends Base
}
//查询是否添加素材
$aWhere = ['email' => $sEmail];
- $aMaterial = Db::name('ai_article_author')->field('media_id,media_url')->where($aWhere)->find();
- if(empty($aMaterial)){
- return json_encode(['status' => 3,'msg' => 'data is null']);
- }
+ $aMaterial = Db::name('ai_author_material')->field('media_id,media_url')->where($aWhere)->find();
if(!empty($aMaterial['media_url'])){
return json_encode(['status' => 1,'msg' => 'success','data' => $aMaterial]);
}
//处理图片地址
- $sImagePath = ROOT_PATH.trim($sIcon,'/');
+ $sImagePath = ROOT_PATH.'/public/usericon/'.trim($sIcon,'/');
if(trim($sIcon) != '/static/img/userImg.f3d9bc3b.jpg'){//非默认头像
//调用微信新增素材接口上传
@@ -1566,16 +1390,167 @@ class Aiarticle extends Base
if(trim($sIcon) == '/static/img/userImg.f3d9bc3b.jpg'){//默认头像
$aData = $this->aLogo;
}
- //更新
+ //更新
$sMediaId = empty($aData['media_id']) ? [] : $aData['media_id'];
$sMediaUrl = empty($aData['url']) ? [] : $aData['url'];
$iTime = empty($aUploadResult['created_at']) ? time() : $aUploadResult['created_at'];
- $aUpdate = ['media_id' => $sMediaId,'media_url' => $sMediaUrl,'update_time' => $iTime];
- $response = Db::name('ai_article_author')->where('email',$sEmail)->limit(1)->update($aUpdate);
+ $aInsert = ['media_id' => $sMediaId,'media_url' => $sMediaUrl,'create_time' => $iTime,'email' => $sEmail,'user_id' => $aParam['user_id']];
+ $response = Db::name('ai_author_material')->insert($aInsert);
if($response === false){
return json_encode(['status' => 3,'msg' => 'fail']);
}
- return json_encode(['status' => 1,'msg' => 'success','data' => $aUpdate]);
+ return json_encode(['status' => 1,'msg' => 'success','data' => $aInsert]);
+ }
+
+ /**
+ * CURL 发送请求获取Token
+ * @param $appid AppID(小程序ID)
+ * @param $secret AppSecret(小程序密钥)
+ */
+
+ private function getAccessToken() {
+ //Token缓存值
+ $sToken = Cache::get($this->sWechatAccessToken);
+ //判断缓存是否存在
+ if (!$sToken) { //不存在
+ //组装接口地址
+ $sUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
+ . $this->sAppID . "&secret=" . $this->sAppSecret;
+
+ $curl = curl_init();
+ curl_setopt($curl, CURLOPT_URL, $sUrl);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
+ curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
+ $result = curl_exec($curl);
+ //请求失败
+ if (curl_errno($curl)){
+ $this->sError = curl_errno($curl);
+ curl_close($curl);
+ return FALSE;
+ }
+var_dump($this->sError,$result);
+ $result = json_decode($result, true);
+
+ if (!empty($result['access_token'])) {
+ $sToken = $result['access_token'];
+ Cache::set($this->sWechatAccessToken, $sToken, 7000); // 有效期7200秒
+ }
+ curl_close($curl);
+ }
+ return $sToken;
+ }
+
+ /**
+ * CURL 发送请求上传永久素材
+ * @param $sToken Token
+ * @param $sPath 图片地址
+ */
+ public function uploadMaterial($sPath = '') {
+
+ $aParam = $this->request->post();
+
+ $sPath = empty($sPath) ? $aParam['path'] : $sPath;
+ // $sPath = ROOT_PATH.'static/img/'.$sPath;
+ // return json_encode(['status' => 1,'data' => ['media_id' => '1111111','url' => '22222']]);
+ //返回结果数组
+ $aResult = ['status' => 1,'msg' => '上传素材成功','data' => []];
+
+ $sPath = empty($sPath) ? $aParam['image_path']?? '' : $sPath;//文件地址
+ $sType = empty($aParam['type']) ? 'image' : $aParam['type'];//文件类型
+
+ // 验证文件有效性
+ if (!file_exists($sPath)) {
+ return json_encode(['status' => 2,'msg' => '素材不存在'.$sPath]);
+ }
+ if (!is_readable($sPath)) {
+ return json_encode(['status' => 3,'msg' => '素材不可读']);
+ }
+ if (filesize($sPath) > 10 * 1024 * 1024) {
+ return json_encode(['status' => 4,'msg' => '素材不能超过10MB']);
+ }
+
+ //获取Token
+ $sToken = $this->getAccessToken();
+ if (empty($sToken)) {
+ return json_encode(['status' => 5, 'msg' => '获取access_token失败']);
+ }
+
+ //CURL 请求接口
+ //文件参数
+ $data = [
+ 'media' => new \CURLFile(
+ realpath($sPath),
+ mime_content_type($sPath), // 自动检测MIME类型
+ basename($sPath) // 上传后的文件名
+ ), // 关键:使用CURLFile对象
+ ];
+ $sUrl = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$sToken}&type={$sType}";
+ $curl = curl_init();
+ curl_setopt($curl, CURLOPT_URL, $sUrl);
+ curl_setopt($curl, CURLOPT_POST, true); //设置为POST方式
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE) ; // 获取数据返回
+ curl_setopt($curl, CURLOPT_PROXY,$this->proxy);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,true);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,false);
+ //执行
+ $response = curl_exec($curl);
+
+ //请求失败
+ if (curl_errno($curl)){
+ curl_close($curl);
+ return json_encode(['status' => 6,'msg' => "网络请求失败: " . curl_errno($curl)]);
+ }
+ curl_close($curl);//关闭请求
+
+ //获取返回结果
+ $response = json_decode($response, true);
+ if (!empty($response['errcode']) && $response['errcode'] != 0) {
+ return json_encode(['status' => 7,'msg' => "微信接口错误: [{$response['errcode']}] {$response['errmsg']}"]);
+ }
+
+ //插入数据库
+ if(empty($response['media_id'])){
+ return json_encode(['status' => 8,'msg' => "未获取到上传素材"]);
+ }
+ return json_encode(['status' => 1,'msg' => 'success','data' => $response]);
+ }
+
+ /**
+ * CURL 发送请求到 微信公众号
+ * @param $messages 内容
+ * @param $model 模型类型
+ */
+ private function curlWechatApi($sUrl = '',$sJsonData = ''){
+
+ //发送CURL请求
+ $curl = curl_init();
+ curl_setopt($curl, CURLOPT_URL, $sUrl);
+ curl_setopt($curl, CURLOPT_POST, true);
+ curl_setopt($curl, CURLOPT_POSTFIELDS, $sJsonData);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
+ curl_setopt($curl, CURLOPT_HTTPHEADER, [
+ 'Content-Type: application/json',
+ 'Content-Length: ' . strlen($sJsonData)
+ ]);
+ curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // 关闭SSL验证(生产环境建议开启)
+ $response = curl_exec($curl);
+ //请求失败
+ if (curl_errno($curl)){
+ curl_close($curl);
+ return ['status' => 2,'msg' => "网络请求失败: " . curl_errno($curl)];
+ }
+ curl_close($curl);//关闭请求
+
+ // 数据处理
+ $response = json_decode($response, true);
+ if (!empty($response['errcode'])) {
+ return ['status' => 3, 'msg' => '接口请求异常'.$response['errmsg'] ?? $response['errcode']];
+ }
+
+ return ['status' => 1,'msg' => '接口请求成功','data' => $response];
}
/**
@@ -1595,7 +1570,7 @@ class Aiarticle extends Base
//生成模版内容
$sContent = empty($aParam['template_content']) ? '' : $aParam['template_content'];
- if(empty($iArticleId) || empty($sContent)){
+ if(empty($iArticleId) || empty($iTemplateId) || empty($sContent)){
return json_encode(['status' => 2,'msg' => 'article_id OR template_content is empty']);
}
@@ -1633,7 +1608,7 @@ class Aiarticle extends Base
], JSON_UNESCAPED_UNICODE);
$aCurlResult = $this->curlWechatApi($sUrl,$sJsonData);
if($aCurlResult['status'] != 1){
- return $aCurlResult;
+ return json_encode($aCurlResult);
}
$response = empty($aCurlResult['data']) ? [] : $aCurlResult['data'];
//判断是否推送成功
@@ -1665,7 +1640,7 @@ class Aiarticle extends Base
/**
* CURL 获取草稿箱的文章
* @param $sToken Token
- * @param article_id int 文章ID
+ * @param media_id string 微信公众号media_id
*/
public function getDraft($sMediaId = ''){
//返回结果数组
@@ -1679,7 +1654,7 @@ class Aiarticle extends Base
}
//查询关联文章信息
- $aArticle = Db::name('ai_article')->field('media_id')->where(['media_id'=>$sMediaId])->find();
+ $aArticle = Db::name('ai_wechat_article')->field('media_id')->where(['media_id'=>$sMediaId])->find();
if(empty($aArticle)){
return json_encode(['status' => 3,'msg' => 'The article does not exist']);
}
@@ -1687,7 +1662,7 @@ class Aiarticle extends Base
//获取Token
$sToken = $this->getAccessToken();
if (empty($sToken)) {
- return json_encode(['status' => 4, 'msg' => '获取access_token失败']);
+ return json_encode(['status' => 4, 'msg' => 'Failed to obtain access_token']);
}
//CURL请求
@@ -1708,37 +1683,201 @@ class Aiarticle extends Base
}
/**
- * CURL 发送请求到 微信公众号
- * @param $messages 内容
- * @param $model 模型类型
+ * CURL 发布草稿箱的文章
+ * @param $sToken Token
+ * @param article_id int 文章ID
*/
- private function curlWechatApi($sUrl = '',$sJsonData = ''){
+ public function publishDraft($sMediaId = ''){
+ //返回结果数组
+ $aResult = ['status' => 1,'msg' => 'Draft box article successfully published','data' => []];
- //发送CURL请求
- $curl = curl_init();
- curl_setopt($curl, CURLOPT_URL, $sUrl);
- curl_setopt($curl, CURLOPT_POST, true);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $sJsonData);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_HTTPHEADER, [
- 'Content-Type: application/json',
- 'Content-Length: ' . strlen($sJsonData)
- ]);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); // 关闭SSL验证(生产环境建议开启)
- $response = curl_exec($curl);
- //请求失败
- if (curl_errno($curl)){
- curl_close($curl);
- return ['status' => 2,'msg' => "网络请求失败: " . curl_errno($curl)];
+ //获取参数
+ $aParam = $this->request->post();
+
+ $sMediaId = empty($sMediaId) ? $aParam['media_id'] : $sMediaId;
+
+ if(empty($sMediaId)){//为空
+ //必填参数验证
+ //文章ID
+ $iArticleId = empty($aParam['article_id']) ? '' : $aParam['article_id'];
+ //模版ID
+ $iTemplateId = empty($aParam['template_id']) ? '' : $aParam['template_id'];
+ if(empty($iArticleId) || empty($iTemplateId)){
+ return json_encode(['status' => 2,'msg' => 'Please select the article or article template to publish']);
+ }
+
+ //获取文章信息
+ $aAiContent = json_decode($this->getAiArticle($iArticleId,1),true);
+ $aAiContent = empty($aAiContent['data']) ? [] : $aAiContent['data'];
+ $aAiArticle = empty($aAiContent['ai_article']) ? [] : $aAiContent['ai_article'];
+ //判断是否生成AI内容
+ if(empty($aAiArticle)){
+ return json_encode(['status' => 3, 'msg' => 'The article content of WeChat official account has not been generated']);
+ }
+
+ //查询该模版是否推送到微信公众号
+ $aWhere['article_id'] = $iArticleId;
+ $aWhere['template_id'] = $iTemplateId;
}
- curl_close($curl);//关闭请求
+ if(!empty($sMediaId)){
+ $aWhere['media_id'] = $sMediaId;
+ }
+
+ $aWechatArticle = Db::name('ai_wechat_article')->field('id,is_publish,media_id,publish_status')->where($aWhere)->find();
+ if(empty($aWechatArticle)){
+ return json_encode(['status' => 4, 'msg' => 'The article was not found in the draft box of WeChat official account']);
+ }
+ $iId = empty($aWechatArticle['id']) ? 0 : $aWechatArticle['id'];
- // 数据处理
- $response = json_decode($response, true);
- if (!empty($response['errcode'])) {
- return ['status' => 3, 'msg' => '接口请求异常'.$response['errmsg'] ?? $response['errcode']];
+ //判断是否发布
+ if($aWechatArticle['publish_status'] != '-1'){
+ return json_encode(['status' => 5, 'msg' => 'The article has been published, please confirm']);
+ }
+ //判断微信公众号media_id 是否为空
+ $sMediaId = empty($aWechatArticle['media_id']) ? '' : $aWechatArticle['media_id'];
+ if(empty($sMediaId)){
+ return json_encode(['status' => 5,'msg' => 'The article has not been pushed to the draft box of WeChat official account, please confirm'],true);
}
- return ['status' => 1,'msg' => '接口请求成功','data' => $response];
+ //获取Token
+ $sToken = $this->getAccessToken();
+ if (empty($sToken)) {
+ return json_encode(['status' => 6, 'msg' => '获取access_token失败']);
+ }
+
+ //验证公众号是否存在该文章
+ $aInfo = json_decode($this->getDraft($sMediaId),true);
+ if($aInfo['status'] != 1){
+ return json_encode($aInfo);
+ }
+
+ // //CURL请求
+ // $sUrl = "https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={$sToken}";
+ // //参数组装
+ // $sJsonData = json_encode([
+ // 'media_id' => $sMediaId
+ // ], JSON_UNESCAPED_UNICODE);
+ // //发送CURL请求
+ // $aCurlResult = $this->curlWechatApi($sUrl,$sJsonData);
+ // if($aCurlResult['status'] != 1){
+ // return $aCurlResult;
+ // }
+ // $response = empty($aCurlResult['data']) ? [] : $aCurlResult['data'];
+
+ // //判断是否推送成功
+ // if(empty($response['publish_id'])){
+ // return json_encode(['status' => 9,'msg' => "未获取到发布草稿的publish_id"]);
+ // }
+$response['publish_id'] = '100000001';
+ //更新文章表publish_id
+ $aUpdate = ['update_time' => time(),'is_publish' => 1,'publish_id' => $response['publish_id'],'publish_status' => 1];
+ $result = Db::name('ai_wechat_article')->where('id',$iId)->limit(1)->update($aUpdate);
+ if($result === false){
+ return json_encode(['status' => 9,'msg' => "Failed to update the status of the published article"]);
+ }
+ return json_encode($aResult);
+ }
+
+ /**
+ * CURL 查询文章的发布状态
+ * @param $sToken Token
+ * @param article_id array 文章ID
+ */
+ public function freePublish(){
+ //返回结果数组
+ $aResult = ['status' => 1,'msg' => 'Successfully synchronized the publishing status of the article','data' => []];
+
+ //获取参数
+ $aParam = $this->request->post();
+ $aWhere = ['is_publish' => 1,'publish_id' => ['<>',''],'publish_status' => 1,'is_delete' => 2];
+ if(!empty($aParam['article_id'])){
+ $aWhere['id'] = $aParam['article_id'];
+ }
+ //查询文章发布ID
+ $aArticlePublishId = Db::name('ai_wechat_article')->where($aWhere)->column('publish_id');
+ if(empty($aArticlePublishId)){
+ return json_encode(['status' => 2,'msg' => 'No articles requiring synchronization status were found'],true);
+ }
+
+ //循环查询
+ $aInsert = $aUpdate = [];
+ foreach ($aArticlePublishId as $key => $value) {
+ if(empty($value)){
+ continue;
+ }
+ $aResult = json_decode($this->_freePublish(100000001),true);
+ if($aResult['status'] != 1){
+ continue;
+ }
+ $aData = empty($aResult['data']) ? [] : $aResult['data'];
+
+ if(empty($aData)){
+ continue;
+ }
+ $aInsert[] = $aData;
+ $aUpdate[$aData['publish_status']][] = $value;
+ }
+ //插入日志表
+ if(!empty($aInsert)){
+ $result = Db::name('wechat_article_publish_log')->insertAll($aInsert);
+ }
+ //更新文章表的发布状态
+ if(!empty($aUpdate)){
+ Db::startTrans();
+ foreach ($aUpdate as $key => $value) {
+ if(empty($value)){
+ continue;
+ }
+ $result = Db::name('ai_wechat_article')->whereIn('publish_id',$value)->limit(count($value))->update(['publish_status' => $key,'update_time' => time()]);
+ }
+ Db::commit();
+ }
+ return json_encode($aResult);
+ }
+ private function _freePublish($sPublishId = '100000001'){
+
+ //获取参数
+ // $aParam = $this->request->post();
+ // $sPublishId = empty($sPublishId) ? $aParam['publish_id']?? '' : $sPublishId;//文件地址
+
+ // if(empty($sPublishId)){
+ // return json_encode(['status' => 2, 'msg' => '请选择要查询的文章发布ID']);
+ // }
+ // //获取Token
+ // $sToken = $this->getAccessToken();
+ // if (empty($sToken)) {
+ // return json_encode(['status' => 3, 'msg' => '获取access_token失败']);
+ // }
+
+ // //CURL请求
+ // $sUrl = "https://api.weixin.qq.com/cgi-bin/freepublish/get?access_token={$sToken}";
+ // //参数组装
+ // $sJsonData = json_encode([
+ // 'publish_id' => $sPublishId
+ // ], JSON_UNESCAPED_UNICODE);
+ // //发送CURL请求
+ // $aCurlResult = $this->curlWechatApi($sUrl,$sJsonData);
+ // if($aCurlResult['status'] != 1){
+ // return $aCurlResult;
+ // }
+ // $response = empty($aCurlResult['data']) ? [] : $aCurlResult['data'];
+ $response = ['publish_id' => '1000001','publish_status' => 2,'article_id'=> '','article_detail','fail_idx' => [1,2]];
+ //log日志需要参数
+ $aField = ['publish_id','publish_status' ,'article_id' ,'article_detail' ,'fail_idx' ,'create_time'];
+
+ $aInsert = [];
+ foreach ($aField as $value) {
+ if($value == 'create_time'){
+ $aInsert[$value] = time();
+ continue;
+ }
+ $aInsert[$value] = empty($response[$value]) ? ' ' : $response[$value];
+ if(is_array($aInsert[$value])){
+ $aInsert[$value] = json_encode($aInsert[$value]);
+ }
+ }
+ $aResult['status'] = 1;
+ $aResult['data'] = $aInsert;
+ return json_encode($aResult);
}
}