<?php
class caijiAction extends FirstendAction {
	public function _initialize() {
		parent::_initialize();
	}
	public function index() {
		$key = I('key');
		if($key != C('ftx_auto_key') || !$key){
		$this->jsonReturn(0,'请设置KEY');		
		}
		$txt_path = C('ftx_attach_path') . 'autotxt/';
		$files = $this->getFolders($txt_path);
		foreach ($files as $folder) {
			$filepath = $txt_path.$folder;
		    if($this->hasFiles($filepath)){
				$cat[] = $folder;
			}
		}
		$cate_id = $cat[array_rand($cat)];
		if(!$cate_id) {
			$this->ajaxReturn(0, '所有文档导入完成');
		}
		$author  = C('ftx_ai_author');
		$status  = C('ftx_ai_status');
		$upload_path = $txt_path.$cate_id.'/';
		$filename = scandir($upload_path);
		for ($i=0;$i<count($filename);$i++) {
			if($filename[$i]=='.'||$filename[$i]=='..') {
				unset($filename[$i]);
			}
		}
		foreach($filename as $key=>$val) {
			$filelist[] = $val;
		}
		$totalnum = count($filelist);
		if($totalnum) {
			$xfile = $filelist[0];
			$title = mb_convert_encoding($xfile,'UTF-8','GBK');
			$title = str_replace(".txt","", $title);
			$where['title'] = $title;
			$file = $upload_path.$xfile;
			if(D('article')->where($where)->find()) {
				unlink($file);
				$this->ajaxReturn(99, '文档标题重复已删除');
			}
			$arr =  $this->read($file);
			for ($s=0;$s<count($arr);$s++) {
				if(trim($arr[$s])) {
					$infos .= '<p>'.$arr[$s].'</p>';
				}
			}
			$infod = $infos;
			if($cate_id) {
				$cinfo = D('article_cate')->where(array('id'=>$cate_id))->find();
				if($cinfo['ename']) {
					$cpath = $cinfo['ename'];
				} else {
					$cpath = 'pic';
				}
				$path = "data/upload/article/".$cpath."/";
				$newname = md5($title);
				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');
						$position = strpos($infos, "<p>", strpos($infos, "<p>") + 1);
						$imageHTML = '<p><center><img src="'.$newimg.'" alt="'.$title.'"></center></p>';
						$infod = substr_replace($infos, $imageHTML, $position, 0);
					}
				}
			}
			preg_match("<img.*src=[\"](.*?)[\"].*?>", $infod, $match);
			$item['mpic'] = $match[1];
			$item['intro'] = utf_substr($infod,150);
			$item['mid'] = substr(md5(md5($title)),8,16);
			$item['cate_id'] = $cate_id;
			$item['title'] = $title;
			$item['author'] = $author;
			$item['add_time'] = time();
			$item['status'] = $status;
			$item['fabu'] = 1;
			if($item['cate_id'] && $item['title'] && $infod) {
				$res = D('article')->add($item);
				if($res) {
					$items['vid'] = $res;
					$items['info'] = $infod;
					D('article_'.$cate_id)->add($items);
					unlink($file);
					$this->ajaxReturn(100, 'OK');
				} else {
					$this->ajaxReturn(101, 'error');
				}
			} else {
				$this->ajaxReturn(102, 'error');
			}
		} else {
			$this->ajaxReturn(103, 'over');
		}
	}
	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;
	}
	public function read($file_txt) {
		$data=array();
		$i=0;
		$content=fopen($file_txt,'r');
		if(!$content) {
			echo '读取文件失败！';
			exit;
		}
		while(!feof($content)) {
			$str=fgets($content);
			//读取的数据存在乱码需要设置编码
			$encoding = mb_detect_encoding($str,array('GB2312','GBK','UTF-16','UCS-2','UTF-8','BIG5','ASCII'));
			if($encoding!=false) {
				if ($encoding != "EUC-CN") {
					if($encoding != "CP936") {
						$data[$i] = iconv($encoding, "UTF-8", $str);
					} else {
						$data[$i] = $str;
					}
				} else {
					$data[$i] = iconv($encoding, "UTF-8", $str);
				}
			} else {
				$data[$i] = mb_convert_encoding($str,'UTF-8','Unicode');
			}
			$i++;
			unset($str);
		}
		return $data;
	}
	public function getFolders($directory) {
		$folders = array();
		// 用于存储文件夹的数组
		// 使用scandir()函数获取目录下的所有文件和文件夹
		$files = scandir($directory);
		// 遍历目录下的文件和文件夹
		foreach ($files as $file) {
			// 排除当前目录（.）和上级目录（..）
			if ($file != '.' && $file != '..') {
				// 使用is_dir()函数判断是否为文件夹
				if (is_dir($directory . '/' . $file)) {
					// 将文件夹添加到数组中
					$folders[] = $file;
				}
			}
		}
		return $folders;
	}
	public function hasFiles($directory) {
		// 使用scandir()函数获取目录下的所有文件和文件夹
		$files = scandir($directory);
		// 遍历目录下的文件和文件夹
		foreach ($files as $file) {
			// 排除当前目录（.）和上级目录（..）
			if ($file != '.' && $file != '..') {
				// 使用is_file()函数判断是否为文件
				if (is_file($directory . '/' . $file)) {
					// 存在文件，返回true
					return true;
				}
			}
		}
		// 不存在文件，返回false
		return false;
	}
}