<?php
class articleAction extends BackendAction
{
    public function _initialize()
    {
        parent::_initialize();
        $this->_mod = D('article');    
		$this->_cate_mod = D('article_cate');
		$catelist = D('article_cate')->select();
		$this->assign('catelist', $catelist);
		$this->_api = new api_getinfo();
    }
    public function _before_index()
    {
        $res = $this->_cate_mod->field('id,name,ename')->select();
        $cate_list = array();
        foreach ($res as $val) {
            $cate_list[$val['id']] = $val['name'];			
        }		
        $this->assign('cate_list', $cate_list);		
        $p = $this->_get('p', 'intval', 1);
        $this->assign('p', $p);
        $this->sort = 'id';
        $this->order = 'DESC';		
    }
	public function del() {
		$id = I('id');					
 		$list = explode(',',$id);
		foreach($list as $key=>$val){
		  $spi = explode('_',$val);	
		  $sqlmod = 'article_'.$spi[1];
		  $this->_mod->where(array('id'=>$spi[0]))->delete();
		  D($sqlmod)->where(array('vid'=>$spi[0]))->delete();
		  $this->_mod->xiufusql($sqlmod);
		  $this->_mod->xiufusql('article');
		}							
        $this->ajaxReturn(1);
    }
	public function move() {
        if (IS_POST) {
            $cate_id = $this->_post('pid', 'intval');	
			$newmod = 'article_'.$cate_id;
            $ids = $this->_post('ids');			            	
			$list = explode(',',$ids);
		foreach($list as $key=>$val){
		  $dd = explode('_',$val);	
		  $oldcid = $dd[1];
		  $id  = $dd[0];
		  $sqlmod = 'article_'.$oldcid;		  
		  $this->_mod->where(array('id'=>$id))->save(array('cate_id'=>$cate_id));
		  $item = D($sqlmod)->where(array('vid'=>$id))->find();		  
		  D($newmod)->add($item);
		  D($sqlmod)->where(array('vid'=>$id))->delete();
		  $this->_mod->xiufusql($sqlmod);
		}
          $this->ajaxReturn(1, L('operation_success'), '', 'move');
        } else {
            $ids = trim(I('id'), ',');
            $this->assign('ids', $ids);
            $resp = $this->fetch();
            $this->ajaxReturn(1, '', $resp);
        }
    }
	public function auto() {
		
		$this->display();
	}
	public function caiji() {
		
		$this->display();
	}
	public function moreadd() {
		$map['fabu'] = 0;		
		$map['doc_id'] = array('exp','is null');
		$noid = D('article')->where($map)->count();
		$this->assign('noid', $noid);
		
		$smap['fabu'] = 0;		
		$smap['doc_id'] = array('exp','is not null');
		$count = D('article')->where($smap)->count();
		$this->assign('count', $count);
		$this->display();
	}
	public function geta(){
		$map['fabu'] = 0;		
		$map['doc_id'] = array('exp','is null');
		$noid = D('article')->where($map)->count();		
		$this->ajaxReturn(1,'',$noid);
	}
	public function getb(){
		$map['fabu'] = 0;		
		$map['doc_id'] = array('exp','is not null');
		$count = D('article')->where($map)->count();		
		$this->ajaxReturn(1,'',$count);
	}
	public function keyWordCheck($content){
        $str = trim($content);
        $nokw = C('ftx_nokw');
        $nokw = trim($nokw);
        $arr = explode(",", $nokw);
        for($i=0,$k=count($arr);$i<$k;$i++){    
            if($arr[$i]==''){
              continue;    
            }
            if(@strpos($str,$arr[$i])!==false){        
              return $arr[$i];
            }    
        }   
        return false;
    }
	public function batadd(){
		if (IS_POST) {
			$cate_id = I('cid');
			$titles = I('titles');
			if(!$cate_id){
			$this->ajaxReturn(0, '请选择分类');	
			}
			if(!$titles){
			$this->ajaxReturn(0, '请输入标题,一行一条');	
			}
			$titles = str_replace("\r\n", "<br>", $titles);
			$titles = str_replace("\r", "<br>", $titles);
			$titles = str_replace("\n", "<br>", $titles);
			$arr = explode("<br>", $titles);
			//$arr = explode(PHP_EOL,$titles);
			//$arr = preg_split("/\R/", $titles);			
			$totalnum = count($arr);
			$coll=0;
			if($totalnum){
		        for($i=0;$i<$totalnum;$i++){					
				    $name = $arr[$i];				
				    $name = trim($name);				
				    $itemarray['title']  = $name;						
				    $itemarray['cate_id']= $cate_id;
				    $itemarray['mid']    = substr(md5(md5($name)),8,16);
					$itemarray['fabu']   = 0;	
					$itemarray['status']   = 0;
				    if($name && !$this->keyWordCheck($name)){
			           $item_list[]=$itemarray;
				    }
		        }
			    foreach ($item_list as $key => $val) {
				    $res = $this->_ajax_tb_publish_insert($val);
					if($res>0){
				    $coll++;
			        }
		        }
		    }
			$this->ajaxReturn(1, '本次发布成功'.$coll.'篇标题');	
		}	
	}
	private function _ajax_tb_publish_insert($item) { 
	      $data['title'] = $item['title'];
		  $data['cate_id'] = $item['cate_id'];
		  $data['mid'] = $item['mid'];
		  $data['fabu'] = $item['fabu'];
		  $data['status'] = $item['status'];
		  $result = D('article')->ajax_publish($data);
		  if($result){
		  $cid = $item['cate_id'];	
		  $in['vid'] = $result;
		  D('article_'.$cid)->add($in);	  
		  }
        return $result;
    }
	public function batinfo(){
		$p = I('p', 1, 'intval');
		$count = I('count');
		if($p==1){
			$nocoll = 0;
			$okcoll = 0;			
		}else{
			if(F('nocoll')){
			$nocoll = F('nocoll');
			}else{
			$nocoll = 0;
			}
			if(F('okcoll')){
			$okcoll = F('okcoll');
			}else{
			$okcoll = 0;
			}
			
		}
		if (!C('ftx_ai_sercet')) {
            $this->ajaxReturn(0, '请设置API密钥！');
        }
		$tui = 0;
		if(C('ftx_ai_tui')){
		$num = rand(1,10);	
		if($num==8){
		$tui = 1;	
		}
		}
		$map['fabu'] = 0;		
		$map['doc_id'] = array('exp','is null');
		$info = D('article')->order('id asc')->where($map)->find();
		if(!$info || $p>$count){		
		F('nocoll',NULL);	
		F('okcoll',NULL);				
		$this->ajaxReturn(0, '已经完成！请返回，谢谢');	
		}
		$doc = $this->_api->getdocid($info['title'],C('ftx_ai_long')); 	
		if($doc['code']==200){
		$data['doc_id'] = $doc['data']['doc_id'];	
		D('article')->where(array('id'=>$info['id']))->save($data);
		$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));
        }
		$okcoll++;
		}else{
		$nocoll++;		
		}				 				
		F('okcoll',$okcoll);		
		F('nocoll',$nocoll);		
		$this->assign('p', $p); 		
		$this->assign('okcoll', $okcoll); 		
		$this->assign('nocoll', $nocoll); 				
		$fetch = $this->fetch('batinfo');
		$this->ajaxReturn(1, '批量发起创作请求', $fetch);	
	}
	
	public function batinfofromid(){
		$p = I('p', 1, 'intval');
		$count = I('count');
		if($p==1){
			$no = 0;
			$ok = 0;			
		}else{
			if(F('no')){
			$no = F('no');
			}else{
			$no = 0;
			}
			if(F('ok')){
			$ok = F('ok');
			}else{
			$ok = 0;
			}			
		}
		if (!C('ftx_ai_sercet')) {
            $this->ajaxReturn(0, '请设置API密钥！');
        }
		$tui = 0;
		if(C('ftx_ai_tui')){
		$num = rand(1,10);	
		if($num==8){
		$tui = 1;	
		}
		}
		$map['fabu'] = 0;		
		$map['doc_id'] = array('exp','is not null');
		$info = D('article')->order('id asc')->where($map)->find();
		if(!$info || $p>$count){		
		F('no',NULL);	
		F('ok',NULL);			
		$this->ajaxReturn(0, '已经发布完成！请返回，谢谢');	
		}
		$cinfo = D('article_cate')->where(array('id'=>$info['cate_id']))->find();	        
        if($cinfo['ename']){	
        $cpath = $cinfo['ename'];
        }else{
        $cpath = 'pic';	
        }	
        $path = "data/upload/article/".$cpath."/";	
        $newname = md5($info['title']);	
		if($info['doc_id']){		
        $item = $this->_api->getinfofromid($info['doc_id']); 	
		if($item['code']==200 && $item['data']['doc_status']=='FINISHED'){
		$infos = $item['data']['content'];     
		$infoarr = explode(PHP_EOL,$infos);
		for($s=1;$s<count($infoarr);$s++){
			if(trim($infoarr[$s])){
			$datainfo .= '<p>'.$infoarr[$s].'</p>';	
			}
		}
		$items['info'] = $datainfo;	
		if($cinfo['peitu'] && C('ftx_img_put')==2){        
		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,$info['title']);	
		}
        if(is_file($path.$newname.'.'.C('ftx_img_type'))){  		
		$position = strpos($datainfo, "<p>", strpos($datainfo, "<p>") + 1); 
        $imageHTML = '<p><center><img src="'.$newimg.'" alt="'.$info['title'].'"></center></p>';
		$items['info'] = substr_replace($datainfo, $imageHTML, $position, 0);
        }		
        }
		
		preg_match("<img.*src=[\"](.*?)[\"].*?>", $items['info'], $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'=>$info['id']))->save($data);
		if($do){
		$cid = $info['cate_id'];	
		D('article_'.$cid)->where(array('vid'=>$info['id']))->save($items);	
		$ok++;	
		}else{
		$no++;	
		}
		}else{
		$no++;		
		}
		}		 				
		F('ok',$ok);		
		F('no',$no);		
		$this->assign('p', $p); 		
		$this->assign('ok', $ok); 		
		$this->assign('no', $no); 				
		$fetch = $this->fetch('batinfofromid');
		$this->ajaxReturn(1, '内容批量发布中', $fetch);	
	}
    public function add() {

            if (IS_POST) {
				$items['info'] = html_entity_decode(I('info'));				
                if (FALSE === ( $data = $this->_mod->create() )) {
                    $this->error($this->_mod->getError());
                }
                if (!trim($data['cate_id'])) {
                    $this->error("请选择分类");
                }
				if (!trim($data['title'])) {
                    $this->error("标题不能为空");
                }
				if($this->_mod->where(array('title'=>$data['title']))->count())
                {
                    $this->error('标题已存在');
                }				
								
                $cinfo = D('article_cate')->where(array('id'=>$data['cate_id']))->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($data['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,$data['title']);
				}
				if(is_file($path.$newname.'.'.C('ftx_img_type'))){                                		
                $position = strpos($items['info'], "<p>", strpos($items['info'], "<p>") + 1); 
                $imageHTML = '<p><center><img src="'.$newimg.'" alt="'.$data['title'].'"></center></p>';
                $items['info'] = substr_replace($items['info'], $imageHTML, $position, 0);			
                }		
                }
				if(!$data['mpic']){
				preg_match("<img.*src=[\"](.*?)[\"].*?>", $items['info'], $match);
				$data['mpic'] = $match[1];
				}
				if(!$data['intro']){
				$data['intro'] = utf_substr($items['info'],150);
				}
		        $data['fabu'] = 1;                                  
                $data['add_time']= time();      
				$data['mid']= substr(md5(md5($data['title'])),8,16);
                $item_id=$this->_mod->add($data);
                if (!$item_id) {
                $this->error(l("operation_failure"));
                }else{
				$cid = $data['cate_id'];
				$items['vid'] = $item_id;				
				D('article_'.$cid)->add($items);
                $this->success(l("operation_success"));	
				}
				
				
            }else {				
                $this->display();
            }
     }
	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 edit() {
            if (IS_POST) {        
			    $items['info'] = I('info');		
				$ainfo['info'] = html_entity_decode($items['info']);
				$oldcid = I('oldcid');
                if (false === $data = $this->_mod->create()) {
                    $this->error($this->_mod->getError());
                }
                if( !$data['cate_id']||!trim($data['cate_id']) ){
                    $this->error('请选择分类');
                }
                $item_id = $data['id'];
                $data['add_time'] = strtotime($data['add_time']); 
				$data['mid']= substr(md5(md5($data['title'])),8,16);
				if(!$data['mpic']){
				preg_match("<img.*src=[\"](.*?)[\"].*?>", $ainfo['info'], $match);
				$data['mpic'] = $match[1];
				}
				if(!$data['intro']){
				$data['intro'] = utf_substr($ainfo['info'],150);
				}
                $this->_mod->where(array('id'=>$item_id))->save($data);
				$cid = $data['cate_id'];		
				$newsqlmod = D('article_'.$cid);
				$oldsqlmod = D('article_'.$oldcid);
				$ainfo['vid'] = $item_id;				
				if($oldcid != $data['cate_id']){
				$newsqlmod->add($ainfo);			            
				$oldsqlmod->where(array('vid' => $item_id))->delete();	
				}else{
				$in['info'] = $ainfo['info'];	
				$newsqlmod->where(array('vid' => $item_id))->save($in);	
				} 
                $this->success(L('operation_success'));
            } else {
                $id = I('id');
                $item = $this->_mod->where(array('id'=>$id))->find();	
				$item['add_time'] = date('Y-m-d H:i:s',$item['add_time']);				
				$cid = $item['cate_id'];		
				$sqlmod = D('article_'.$cid);
				$article = $sqlmod->where(array('vid' => $id))->find();	
				$this->assign('id', $id);			
				$item['info'] = $article['info'];
                $this->assign('info', $item);                
                $this->display();
            }
        }
    protected function _search()
    {
        $map = array();
        ($time_start = $this->_request('time_start', 'trim')) && $map['add_time'][] = array('egt', strtotime($time_start));
        ($time_end = $this->_request('time_end', 'trim')) && $map['add_time'][] = array('elt', strtotime($time_end) + (24 * 60 * 60 - 1));   
        ($keyword = $this->_request('keyword', 'trim')) && $map['title'] = array('like', '%'.$keyword.'%');   	
		($cate_id = $this->_request('cate_id', 'intval')) && $map['cate_id'] = $cate_id;
		$status = $this->_request('status', 'trim');
		if ($status != '') {
			$map['status'] = $status;
		}
        $fabu = $this->_request('fabu', 'trim');
		if ($fabu != '') {
			$map['fabu'] = $fabu;
		}        
		$this->assign('search', 
		   array(
		   'time_start' => $time_start,
		   'time_end' => $time_end,
		   'cate_id' => $cate_id,		   
		   'status' => $status,		   
		   'fabu' => $fabu,		
		   'keyword' => $keyword,		   
		   )
		   );
        return $map;
    }
    
    public function make_dir($path)
    {
        if (!file_exists($path)) {
            $mk = @mkdir($path, 0777, true);
            @chmod($path, 0777, true);
        }
        return true;
    }
    
    public function ajax_upload_img() {
        $type = $this->_get('type', 'trim', 'img');		
        if (!empty($_FILES[$type]['name'])) {
            $dir = date('Ymd', time()) . '/';			
            $result = $this->_upload($_FILES[$type], 'article/adminadd/'.$dir );
            if ($result['error']) {
                $this->ajaxReturn(0, $result['info']);
            } else {
                $savename = '/'.C('ftx_attach_path').'article/adminadd/'.$dir . $result['info'][0]['savename'];
                $this->ajaxReturn( 1, L( "operation_success" ), $savename);
            }
        } else {
            $this->ajaxReturn(0, L('illegal_parameters'));
        }
    }
	public function ajaxwrite()
    {
		if (!C('ftx_ai_sercet')) {
            $this->ajaxReturn(0, '请设置API密钥！');
        }
        if (!isset($_REQUEST['title'])) {
            $this->ajaxReturn(0, '请输入标题！');
        }
		if($this->_mod->where(array('title' => $_REQUEST['title']))->count()){
			$this->ajaxReturn(0, '标题已存在！');
		}
		$docid = I('docid');
		if($docid){
		$item = $this->_api->getinfofromid($docid); 
		if($item['code']==200 && $item['data']['doc_status']=='FINISHED'){		
		$infos = $item['data']['content'];     
		$infoarr = explode(PHP_EOL,$infos);
		for($s=1;$s<count($infoarr);$s++){
			if(trim($infoarr[$s])){
			$datainfo .= '<p>'.$infoarr[$s].'</p>';	
			}
		}
		$this->ajaxReturn(1, '' , $datainfo);
		}else{				
		$this->ajaxReturn(0, '生成内容失败，错误码：'.$item['code'].','.$item['message'].','.$item['data']['doc_status']);		
		}	
		}else{
		$doc = $this->_api->getdocid($_REQUEST['title'],C('ftx_ai_long'));    
		if($doc['code']==200){
		$docid = $doc['data']['doc_id'];	
		$this->assign('docid', $docid); 	
		$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));
        }
		$resp = $this->fetch('collect');
		$this->ajaxReturn(1, $docid, $resp);
		}else{
		$this->ajaxReturn(0, '生成ID失败，错误码：'.$doc['code'].','.$doc['message']);		
		}	
		}        
        
    }
    
    
    
}
?>
	 
