<?php
class autoAction extends FirstendAction
{
    public function _initialize()
    {
        parent::_initialize();	
		$this->_api = new api_getinfo();
		$where['fabu'] = 0;		
		$clist = D('article')->field('cate_id')->where($where)->group('cate_id')->select();
		foreach ($clist as $key => $val) {
			$cat[] = $val['cate_id'];
		}
		$map['id'] = array('in',$cat);		
		$catelist = D('article_cate')->where($map)->order('ordid asc')->select();
		foreach ($catelist as $key => $val) {
			$catelist[$key] = $val;
		}
		$cate = $catelist[array_rand($catelist)];
		$this->autoid = $cate['id'];
    }
	    	
    public function getinfo_one($p){
		$map['cate_id'] = $this->autoid;
		$map['fabu'] = 0;	
		if($p==1){			
		$map['doc_id'] = array('gt','0');
		}		
		if($p==2){				
		$map['doc_id'] = array('gt','0');
		$map['doc_id_2'] = array('gt','0');
		}
		$info = D('article')->order('add_time asc')->where($map)->find();			
		return $info;
	}
	public function getitem_two($p){		
		if($p==1){
		$map['cate_id'] = $this->autoid;	
		$map['fabu'] = 0;		
		$map['doc_id'] = array('EXP','IS NULL');	
		}		
		if($p==2){		
		$map = array(
		'cate_id'=>$this->autoid,
		'fabu' => 0,
		'_complex' => array(
        'doc_id' => array('EXP', 'IS NULL'),
        'doc_id_2' => array('EXP', 'IS NULL'),
        '_logic' => 'OR'
        )
        );
		}
		$info = D('article')->order('id asc')->where($map)->find();			
		return $info;
	}
	public function index(){
		$key = I('key');
		if($key != C('ftx_auto_key') || !$key){
		$this->jsonReturn('请设置KEY');		
		}
		if(C('ftx_ai_mod')){
		$this->addinfo_two();	
		$this->adddocid_two();
		}else{
		$this->addinfo_one();	
		$this->adddocid_one();		
		}					
	}
	
	public function addinfo_one(){
		$tui = 0;
		if(C('ftx_ai_tui')){
		$num = rand(1,10);	
		if($num==8){
		$tui = 1;	
		}
		}		
		$fabu = $this->getinfo_one(1);	
		if($fabu['doc_id']){
		$doa = $this->getaitext($fabu['doc_id']);
		if($doa['msg']=='ok'){
		$html = $this->putimg($doa['info'],$fabu['title'],$fabu['cate_id']);	
		}else{		
		if($doa['msg'] =='RUNNING'){
		$end = time() - $fabu['add_time'];	
		$this->delout($fabu['add_time'],$fabu['id']);	
		echo '文章ID['.$fabu['id'].']docid['.$fabu['doc_id'].']获取内容失败，原因：内容正在生成中，2分钟以后再次获取<br>';	
		}else{
		$this->delout($fabu['add_time'],$fabu['id']);		
		echo '文章ID['.$fabu['id'].']docid['.$fabu['doc_id'].']获取内容失败，'.$doa['msg'].'<br>';	
		}			
		}	
		}else{
		D('article')->where(array('fabu'=>3))->save(array('fabu'=>0));
		}			
		if($html){
		$items['info'] = $html;    		
		preg_match("<img.*src=[\"](.*?)[\"].*?>", $html, $match);
		$data['mpic'] = $match[1];
		$data['intro'] = utf_substr($items['info'],150);
		$data['add_time'] = time();
		$data['fabu'] = 1;
		$data['author']  = C('ftx_ai_author');	
		$data['status']  = C('ftx_ai_status');
		$data['tui'] = $tui;
		$do = D('article')->where(array('id'=>$fabu['id']))->save($data);
		D('article_'.$fabu['cate_id'])->where(array('vid'=>$fabu['id']))->save($items);
		echo 'ID['.$fabu['id'].']内容发布成功!<br>';	
		}
	}
	public function addinfo_two(){
		$tui = 0;
		if(C('ftx_ai_tui')){
		$num = rand(1,10);	
		if($num==8){
		$tui = 1;	
		}
		}
		$fabu = $this->getinfo_one(2);
		if($fabu['doc_id'] && $fabu['doc_id_2']){
		$doa = $this->getaitext($fabu['doc_id']);
		if($doa['msg']=='ok'){
		$htmla = $this->putimg($doa['info'],$fabu['title'],$fabu['cate_id']);	
		echo '第一篇docid['.$fabu['doc_id'].']获取内容成功！<br>';
		}else{
		if($doa['msg'] =='RUNNING'){
		$this->delout($fabu['add_time'],$fabu['id']);
		echo '第一篇文章ID['.$fabu['id'].']docid['.$fabu['doc_id'].']获取内容失败，原因：内容正在生成中，2分钟以后再次获取<br>';	
		}else{
		$this->delout($fabu['add_time'],$fabu['id']);			
		echo '第一篇文章ID['.$fabu['id'].']docid['.$fabu['doc_id'].']获取内容失败，'.$doa['msg'].'<br>';	
		}				
		}				
		$dob = $this->getaitext($fabu['doc_id_2']);
		if($dob['msg']=='ok'){		
		$htmlb = $dob['info'];		
		echo '第二篇docid2['.$fabu['doc_id_2'].']获取内容成功！<br>';
		}else{
		if($dob['msg'] =='RUNNING'){
		$this->delout($fabu['add_time'],$fabu['id']);	
		echo '第二篇文章ID['.$fabu['id'].']docid['.$fabu['doc_id_2'].']获取内容失败，原因：内容正在生成中，2分钟以后再次获取<br>';	
		}else{
		$this->delout($fabu['add_time'],$fabu['id']);		
		echo '第二篇文章ID['.$fabu['id'].']docid['.$fabu['doc_id_2'].']获取内容失败，'.$dob['msg'].'<br>';	
		}						
		}
		if($htmla && $htmlb){
		$html = ''.$htmla.'<p>除此之外，还有：</p>'.$htmlb;		
		}
		if($html){
		$items['info'] = $html;    		
		preg_match("<img.*src=[\"](.*?)[\"].*?>", $html, $match);
		$data['mpic'] = $match[1];
		$data['intro'] = utf_substr($items['info'],150);
		$data['add_time'] = time();
		$data['fabu'] = 1;
		$data['author']  = C('ftx_ai_author');	
		$data['status']  = C('ftx_ai_status');
		$data['tui'] = $tui;
		$do = D('article')->where(array('id'=>$fabu['id']))->save($data);
		D('article_'.$fabu['cate_id'])->where(array('vid'=>$fabu['id']))->save($items);
		echo '文章ID['.$fabu['id'].']发布成功!<br>';	
		}
		}else{
		D('article')->where(array('fabu'=>3))->save(array('fabu'=>0));	
		}		
		
	}
	public function adddocid_one(){
		$item = $this->getitem_two(1);
		if($item && !$item['doc_id']){
		$doc = $this->getdocid($item);
		$docid = $doc['data']['doc_id'];			
		if($docid){
		$data1['doc_id'] = $docid;	
		$data1['add_time'] = time();	
		D('article')->where(array('id'=>$item['id']))->save($data1);	
		echo '生成docid['.$docid.']成功!<br>';
		}else{
		echo '生成docid失败，错误码：'.$doc['code'].','.$doc['message'].'<br>';	
		}				
		}else{
		echo '全部标题生成docid完成!<br>';	
		}		
		
	}
	public function adddocid_two(){
		$item = $this->getitem_two(2);
		if($item && !$item['doc_id']){
		$doc = $this->getdocid($item);
		$docid = $doc['data']['doc_id'];			
		if($docid){
		$data1['doc_id'] = $docid;	
		$data1['add_time'] = time();	
		D('article')->where(array('id'=>$item['id']))->save($data1);	
		echo '生成docid['.$docid.']成功!<br>';
		}else{
		echo '生成docid失败，错误码：'.$doc['code'].','.$doc['message'].'<br>';	
		}				
		}else{
		echo '全部标题生成docid完成!<br>';	
		}				
		if($item && !$item['doc_id_2']){
		$doc2 = $this->getdocid($item);
		$docid2 = $doc2['data']['doc_id'];			
		if($docid2){
		$data2['doc_id_2'] = $docid2;	
		$data2['add_time'] = time();	
		D('article')->where(array('id'=>$item['id']))->save($data2);	
		echo '生成docid2['.$docid2.']成功!<br>';
		}else{
		echo '生成docid2失败，错误码：'.$doc2['code'].','.$doc2['message'].'<br>';	
		}	
		}else{
		echo '全部标题生成docid2完成!<br>';		
		}
		
	}
	public function delout($time,$id){
		$time = $time+1800;
		if($time<time()){
		D('article')->where(array('id'=>$id))->save(array('fabu'=>3));	
		}
	}
	//插入配图
	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);	
		   }
		   if(is_file($path.$newname.'.'.C('ftx_img_type'))){
			$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 getdocid($info){
		$doc = $this->_api->getdocid($info['title'],C('ftx_ai_long')); 
		if($doc['code']==422){	
		D('article')->where(array('id'=>$info['id']))->delete();
		}
		if($doc['code']==200){		
		$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));
        }					
		}
		return $doc;
	}
	//获取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'].','.$item['data']['doc_status'];
			if($item['data']['doc_status']=='RUNNING'){
			$data['msg'] = 'RUNNING';	
			}			
			$data['info']= '';
		}
		return $data;
	}
	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 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;
    }
}
?>