<?php
set_time_limit(0);
ini_set('memory_limit','-1');
error_reporting(0);
ini_set("display_errors", 0);
class juheAction extends FirstendAction {
	public function _initialize() {
		parent::_initialize();
		$this->_api = new api_getinfo();
	}
	
	public function getk() {
		$cate = D('klist')->field('cate_id')->where(array('status'=>0))->group('cate_id')->select();
		if(count($cate)){
		$cat = $cate[array_rand($cate)]['cate_id'];
		return D('klist')->where(array('cate_id'=>$cat,'status'=>0))->find();
		}
	}
	public function index() {
		$key = I('key');		
		if(!C('ftx_aiauto_key') || !$key) {
			//$this->jsonReturn('聚合发布接口KEY不允许为空，请设置后再执行');
			die('聚合发布接口KEY不允许为空，请设置后再执行');
		}
		if($key != C('ftx_aiauto_key')) {
			//$this->jsonReturn('聚合发布接口KEY错误，请检查是否跟后台设置的一致！');
			die('聚合发布接口KEY错误，请检查是否跟后台设置的一致!');
		}
		if(!D('fabu_num')->where(array('date'=>date("Ymd")))->find()) {
			D('fabu_num')->add(array('date'=>date("Ymd"),'num'=>0));
		}
		$fabu_num = C('ftx_fabu_num');
		$tody_num = D('fabu_num')->where(array('date'=>date("Ymd")))->getField('num');
		if($fabu_num>0 && $tody_num>=$fabu_num) {
			//$this->jsonReturn('今日发布数量已达上限');
			die('今日发布数量已达上限');
		}
		$ido = $this->auto_fabu();
		if($ido) {
			D('fabu_num')->where(array('date'=>date("Ymd")))->setInc('num',1);
			echo '文章【'.$ido.'】发布成功！<br>' ;
			//$this->jsonReturn('发布成功！');
		}
		$tag = $this->getk();
		if(!$tag) {
			//$this->jsonReturn('没有可使用的标题，请导入新的标题后再执行');
			die('没有可使用的标题，请导入新的标题后再执行');
		}
		$titles = $this->get_baidu_title($tag['title']);
		if($titles) {
			foreach($titles as $bdtitle) {
				$bdtitle = trim($bdtitle);
				if($bdtitle!='') {
					$bdata['title'] = $bdtitle;
					$has = D('bdlist')->where($bdata)->find();
					if($has) {
						$hid[] = $has['id'];
						$tid[] = $has['title'];
					} else {
						$hid[] = D('bdlist')->add($bdata);
						$tid[] = $bdata['title'];
					}
				}
			}
			$this->auto_get_docid($hid,$tag['id']);
		} else {
			D('klist')->where(array('id'=>$tag['id']))->save(array('status'=>2));
			//$this->jsonReturn('获取百度知道标题失败！');
			echo '标题id【'.$tag['id'].'】获取百度知道标题失败！<br>';
		}
		
	}
	
	//获取docid 如果已存在并且无AI正文则获取生成正文内容
	public function auto_get_docid($hid,$tagid) {
		$br = PHP_EOL;
		$map['id'] = array('in',$hid);
		$list = D('bdlist')->where($map)->select();
		foreach ($list as $key => $val) {
			if(!$val['docid']) {
				$do = $this->getdocid($val['title']);
				if($do['msg']=='ok') {
					D('bdlist')->where(array('id'=>$val['id']))->save(array('docid'=>$do['docid'],'status'=>1));
					$hids[] = $val['id'];
					$titles[] = $val['title'];
					echo '百度标题['.$val['id'].']获取docid成功！<br>' ;
				} else {
					D('bdlist')->where(array('id'=>$val['id']))->save(array('status'=>2));	
					echo '百度标题['.$val['id'].']'.$do['msg'] .'<br>';
				}
			} else {
				if($val['status'] ==1 && $val['docid']){
				$do = $this->getaitext($val['docid']);	
				if($do['msg']=='ok') {
					D('bdlist')->where(array('id'=>$val['id']))->save(array('aitxt'=>$do['info'],'status'=>3));
					$hids[] = $val['id'];
				    $titles[] = $val['title'];
					echo '标题id【'.$val['id'].'】获取AI内容成功！<br>' ;
				}else{					
					echo '标题id【'.$val['id'].'】'.$do['msg'] . '<br>';
				}
				}else if($val['status'] ==3 && $val['aitxt']){
				    $hids[] = $val['id'];
				    $titles[] = $val['title'];
				    echo '标题id【'.$val['id'].'】获取AI内容成功！<br>' ;
				}
			}
		}
		if(count($hids) && count($titles)) {			
			D('klist')->where(array('id'=>$tagid))->save(array('bdlist'=>json_encode($hids,320),'bdtitle'=>json_encode($titles,320),'status'=>1));
			echo '标题【'.$tagid.'】获取百度知道标题成功！<br>';
		}else{
			D('klist')->where(array('id'=>$tagid))->save(array('status'=>2));	
			echo '标题【'.$tagid.'】获取百度知道标题失败！<br>';
		}
	}
	
	//生成docid 并更新用户AI账户
	public function getdocid($title) {
		$doc = $this->_api->getdocid($title,C('ftx_ai_long'));
		if($doc['code']==200) {
			$docid = $doc['data']['doc_id'];
			$surplus = $doc['data']['surplus'];
			if(D('setting')->where(array('name' => 'ai_surplus'))->count()) {
				D('setting')->where(array('name' => 'ai_surplus'))->save(array('data' => $surplus));
			} else {
				D('setting')->add(array('name' => 'ai_surplus','data' => $surplus));
			}
			$data['msg'] = 'ok';
			$data['docid'] = $docid;
		} else {
			$data['msg'] = '获取docid失败，错误码：'.$doc['code'].','.$doc['message'];
			$data['docid'] = 0;
		}
		return $data;
	}
	
	//获取AI内容
	public function getaitext($docid) {
		$item = $this->_api->getinfofromid($docid);
		if($item['code']==200 && $item['data']['doc_status']=='FINISHED') {
			$data['msg'] = 'ok';			
			$infoarr = $this->wrap_split_string($item['data']['content']);
		    for ($s=0;$s<count($infoarr);$s++) {
			if(trim($infoarr[$s])) {
				$datainfo .= '<p>'.$infoarr[$s].'</p>';
			}
		    }
			$data['info']= $datainfo;
		} else {
			$data['msg'] = '获取内容失败，错误码：'.$item['code'].','.$item['message'];
			$data['info']= '';
		}
		return $data;
	}
	
	//发布内容
	public function auto_fabu() {
		$tui = 0;
		if(C('ftx_ai_tui')) {
			$num = rand(1,10);
			if($num==8) {
				$tui = 1;
			}
		}
		$item = D('klist')->where(array('status'=>1))->order('id asc')->find();			
		if($item){		
		$list = json_decode($item['bdlist'],true);
		$title = json_decode($item['bdtitle'],true);
		$ht = '';
		$html = '';
		$ht .= '<h2>文章目录列表：</h2><ul>';
		for ($i=0;$i<count($list);$i++) {
			$bn = $i+1;
			$ht .= '<li style="margin-bottom:3px;list-style:none">'.$bn.'、<a href="#'.$title[$i].'" title="'.$title[$i].'">'.$title[$i].'</a></li>';			
			$bditem = $this->getbditem($list[$i]);
			$text = $this->gettxt($bditem);
			if($text) {
				$textnum[] = $i;
				echo '标题ID:'.$list[$i].',标题【'.$title[$i].'】获取内容成功<br>';	
				if($i==0){
				$text = $this->putimg($text,$item['title'],$item['cate_id']);
				}
				$html .= '<h2 id="'.$title[$i].'">'.$title[$i].'</h2>'.$text;
			}else{				
				echo '标题ID:'.$list[$i].',标题【'.$title[$i].'】,逗号docid:'.$bditem['docid'].',获取内容失败！<br>';	
			}
		}
		
		if(count($textnum) == count($list)){		
		$ht .= '</ul>';
		if(C('ftx_title_daohang')){
		$items['info'] = $html;	
		}else{
		$items['info'] = $ht.$html;	
		}		
		preg_match("<img.*src=[\"](.*?)[\"].*?>", $items['info'], $match);
		$data['title'] = $item['title'];
		$data['mpic'] = $match[1];
		$data['mid'] = substr(md5(md5($item['title'])),8,16);
		$data['intro'] = utf_substr($items['info'],150);
		$data['add_time'] = time();
		$data['fabu'] = 1;
		$data['cate_id'] = $item['cate_id'];
		$data['author']  = C('ftx_ai_author');
		$data['status']  = C('ftx_ai_status');
		$data['tui'] = $tui;		
		$do = D('article')->where(array('mid'=>$data['mid']))->getField('id');
		if(!$do){
		$do = D('article')->add($data);	
		}		
		if($do) {
			$items['vid'] = $do;
			if(!D('article_'.$item['cate_id'])->where(array('vid'=>$do))->find()){
			$s = D('article_'.$item['cate_id'])->add($items);	
			}else{
			$s = 1;	
			}			
		}
		if($s) {
			D('klist')->where(array('id'=>$item['id']))->save(array('status'=>3,'article_id'=>$do));
			return $item['title'];
		}	
		}else{
		D('klist')->where(array('id'=>$item['id']))->save(array('status'=>4));	
		echo '标题【'.$item['title'].'】,发布失败！<br>';	
		}		
		}else{
		echo '当前没有可发布的标题！<br>' ;	
		}
	}
	//插入配图
	public function putimg($text,$title,$cid){		
		$cinfo = D('article_cate')->where(array('id'=>$cid))->find();
		if($cinfo['peitu'] && C('ftx_img_put')==2){
		if($cinfo['ename']) {
			$cpath = $cinfo['ename'];
		} else {
			$cpath = 'pic';
		}
		$path = "data/upload/article/".$cpath."/";
		$newname = md5($title);		
		
		if(is_file($path.$newname.'.'.C('ftx_img_type'))) {
			$newimg = C('ftx_site_url').$path.$newname.'.'.C('ftx_img_type');	
		   }else{
			$newimg = $this->doimg($cpath,$title);	
		   }
			$position = strpos($text, "<p>", strpos($text, "<p>") + 1); 
			$imageHTML = '<p><center><img src="'.$newimg.'" alt="'.$title.'"></center></p>';
			$text = substr_replace($text, $imageHTML, $position, 0);		
		 
        }
		return $text;
	}
	
	public function getbditem($bid) {
		$item = D('bdlist')->where(array('id'=>$bid))->find();
		return $item;
	}
	//生成聚合内容
	public function gettxt($bditem) {			
		if($bditem['status']==3) {
			$text = $bditem['aitxt'];
		} else {
			if($bditem['docid']) {
				$do = $this->getaitext($bditem['docid']);
				if($do['msg']=='ok') {
					$text = $do['info'];
					D('bdlist')->where(array('id'=>$bditem['id']))->save(array('aitxt'=>$do['info'],'status'=>3));
				}
			}
		}
		if($text){			
		return $text;
		}
	}
	
	//内容分割
	public function wrap_split_string($str){
        $pattern = "/\r\n|\r|\n/";
        $lines = preg_split($pattern, $str);
        foreach ($lines as &$line) {
            $line = trim($line);
        }
        return $lines;
    }
	//采集百度知道标题
	public function get_baidu_title($title) {
		$title_num = C('ftx_title_num');
		$title_num = $title_num>6?6:$title_num;
		$uetitle = urlencode($title);
		$url = 'https://zhidao.baidu.com/search?lm=0&rn=10&pn=0&fr=search&dyTabStr=null&word=' . $uetitle;
		$header = array (
		      0 => 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
		      1 => 'Accept-Language: zh-CN,zh;q=0.9',
		      2 => 'Cache-Control: no-cache',
		      3 => 'Connection: keep-alive',
		      4 => 'Pragma: no-cache',
		      5 => 'Referer: https://zhidao.baidu.com/search?word=' . $uetitle . '&site=-1&sites=0&date=0&pn=0',
		      6 => 'Sec-Fetch-Dest: document',
		      7 => 'Sec-Fetch-Mode: navigate',
		      8 => 'Sec-Fetch-Site: same-origin',
		      9 => 'Sec-Fetch-User: ?1',
		      10 => 'Upgrade-Insecure-Requests: 1',
		      11 => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.44',
		      12 => 'sec-ch-ua: "Microsoft Edge";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
		      13 => 'sec-ch-ua-mobile: ?0',
		      14 => 'sec-ch-ua-platform: "Windows"',
		    );
		$timeout = 10;
		$ch  = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_ENCODING, "gzip");
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		if(substr($url, 0, 8) === 'https://') {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}
		if(!empty($cookie)) {
			$header[] = $cookie;
		}
		if(!empty($header)) {
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		}
		$daili = $this->get_daili();
		if(count($daili)==2) {
			curl_setopt($ch, CURLOPT_PROXY, $daili[0]);
			curl_setopt($ch, CURLOPT_PROXYPORT, $daili[1]);
		}
		curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);
		$html = curl_exec($ch);
		curl_close($ch);
		if(!$html) {
			$daili = $this->get_daili(1);
			//return array('msg'=>'该IP可能已被百度屏蔽，请稍候再试，或者使用代理IP采集1');
			return 0;
		}
		//var_dump($html);
		$dom = new DOMDocument();
		libxml_use_internal_errors(true);
		$dom->loadHTML($html);
		$links = $dom->getElementsByTagName('a');
		$targetContents = [];
		if(count($links)==0) {
			//return array('msg'=>'该IP可能已被百度屏蔽，请稍候再试，或者使用代理IP采集2');
			return 0;
		}
		foreach ($links as $link) {
			if ($link->hasAttribute('class') && $link->getAttribute('class')==='ti') {
				$textContent = $link->nodeValue;
				$textContent = strip_tags($textContent);
				if($textContent!='') {
					$targetContents[] = $textContent;
				}
			}
		}
		if(count($targetContents)==0) {
			//return array('msg'=>'该IP可能已被百度屏蔽，请稍候再试，或者使用代理IP采集3');
			return 0;
		}
		$uniqueContents = array_unique($targetContents);
		$title_num = count($uniqueContents)<$title_num?count($uniqueContents):$title_num;
		$titles = array_slice($uniqueContents,0,$title_num);
		if(count($titles)==0) {
			//return array('msg'=>'未获取到百度知道的标题');
			return 0;
		}
		return $titles;
	}
	
	//获取代理  更新代理
	public function get_daili($gengxin = 0) {
		global $zbp;
		if(C('ftx_daili_on')==0) return array();
		$time = C('ftx_daili_time');
		$daili_invalid = C('ftx_daili_invalid');
		if($daili_invalid==0)$daili_invalid=30;
		$dailis = array();
		$dailis = explode(':',C('ftx_daili'));
		if((time()-$time)>$daili_invalid || $gengxin==1) {
			$daili_api = C('ftx_daili_api');
			if($daili_api!='') {
				$daili_content = file_get_contents($daili_api);
				$daili_content = trim($daili_content);
				$dailis2 = explode(':',trim($daili_content));
				if(count($dailis2)==2) {
					$time = time();
					$daili = is_array($daili_content) ? serialize($daili_content) : $daili_content;
					$daili_time = is_array($time) ? serialize($time) : $time;
					if(D('setting')->where(array('name' =>'daili'))->count()) {
						D('setting')->where(array('name' =>'daili'))->save(array('data' => $daili));
					} else {
						D('setting')->add(array('name' =>'daili','data' => $daili));
					}
					if(D('setting')->where(array('name' =>'daili_time'))->count()) {
						D('setting')->where(array('name' =>'daili_time'))->save(array('data' => $daili_time));
					} else {
						D('setting')->add(array('name' =>'daili_time','data' => $daili_time));
					}
					$dailis = $dailis2;
				}
			}
		}
		return $dailis;
	}
	
	//生成图片
	public function doimg($cpath,$title) {
		$con = "data/upload/peitu/".$cpath."/";
		$imgname = scandir($con);
		for ($y=2;$y<count($imgname);$y++) {
			$conname[] = $imgname[$y];
		}
		if(count($conname)) {
			$num = count($conname)-1;
			$pi = rand(0,$num);
			$img = $conname[$pi];
			$src = C('ftx_site_url').$con.$img;
			$path = "data/upload/article/".$cpath."/";
			$this->make_dir($path);
			$newname = md5($title);			
			Image::image_hp($src,$title,$path,$newname);
			$newimg = C('ftx_site_url').$path.$newname.'.'.C('ftx_img_type');
			return $newimg;
		}
	}
	
	//创建目录
	public function make_dir($path) {
		if (!file_exists($path)) {
			$mk = @mkdir($path, 0777, true);
			@chmod($path, 0777, true);
		}
		return true;
	}
}
?>