<?php 
class Mydocument_Controller extends Front_Controller {
	function __construct(){
		parent::__construct();
		$this->lmtpl->user	=	$_SESSION['user'];
		$this->myd			=	new Mydocument_Model();
		$this->category		=	new Model_Category_Model();
		$this->channel		=	new Model_Channel_Model();
		$this->content		=	new Model_Content_Model();
	}
	function index($page=1){
		//计算分页
		$count				=	$this->myd->conlist(false,false,0,0)->count();
		$pagecfg['total_items']			=	$count;
		$GLOBALS['sum']					=	$count;
		$GLOBALS['page']				=	$page;
		$GLOBALS['pagesize']			=	30;
		$GLOBALS['dir']					=	BASEURI."mydocument/index";
		$GLOBALS['uri_segment']			=	"";
		$GLOBALS['is_html']				=	false;
		$this->pagination				=	new Pagination($pagecfg);
		$this->lmtpl->conlist		=	$this->myd->conlist(false,false,$page)->result_array();
		$this->lmtpl->title			=	"我的文档";
		$this->lmtpl->keywords		=	'';
		$this->lmtpl->description	=	'';
		$this->lmtpl->render(self::tplpath("member_mydocument"));
	}
	function select_channel_category(){
		$this->lmtpl->title			=	"我的文档";
		$this->lmtpl->keywords		=	'';
		$this->lmtpl->description	=	'';
		$this->lmtpl->render(self::tplpath("select_channel_category"));

	}
	function add($channel_id=false){
		if($this->input->post()){
			$content	=	$this->input->post('content');
			$channel_id	=	$content["channel_id"];
			$cat_id		=	$content["cat_id"];
			$channel	=	$this->channel->getchannel($channel_id);
			$content['publish_date']	=	time();
			$content['memberid']		=	$_SESSION['user']->user_id;
			//检查目录
			$dir	=	path::uploadattachment();
			if(!file_exists($dir)){
				file::create_dir_path($dir,true);
			}
			//移动缩略图位置
			if($content['thumb']){
				$newpath	=	$dir."/".date("ymdhis",time()).rand(1,1000).".".pathinfo($content['thumb'],PATHINFO_EXTENSION);
				$oldpath			=	$content['thumb'];
				$content['big_img']	=	$newpath;
				$content['thumb']	=	path::getThumb($newpath);
				@rename($oldpath,$content['big_img']);
				@rename(path::getThumb($oldpath),$content['thumb']);
			}
			//插入文章
			$content_id	=	$this->content->addContent($channel->model_value,$content);
			//插入全局内容表以便搜索
			$content['content_id']	=	$content_id;
			$this->content->searchCache($content);
			//检查并处理附件。
			if($channel->model_annex_table!=""&&is_array($annexs	=	$this->input->post('annex'))){
				for ($i=0;$i<count($annexs['path']);$i++){
					//移动文件
					$newpath	=	$dir."/".date("ymdhis",time()).rand(1,1000).".".pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					$ext		=	pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					@rename($annexs['path'][$i],$newpath);
					@rename(path::getThumb($annexs['path'][$i]),path::getThumb($newpath));
					$annex	=	array(
					'path'			=>	$newpath,
					'name'			=>	basename($newpath),
					'channel_id'	=>	$channel_id,
					'file_type'		=>	$ext,
					'content_id'	=>	$content_id,
					'description'	=>	$annexs['description'][$i],
					'read_money'	=>	$annexs['read_money'][$i],
					'read_pointer'	=>	$annexs['read_pointer'][$i],
					'file_size'		=>	intval(@filesize($newpath)/1024),
					'upload_time'	=>	date("Y-m-d H:i:s",time()),
					'thumbs_path'	=>	(in_array(strtolower($ext),array("jpeg","jpg","png","gif"))?1:0)?path::getThumb($newpath):"",
					'is_image'		=>	in_array(strtolower($ext),array("jpeg","jpg","png","gif"))?1:0,
					'is_thumbs'		=>	file_exists(path::getThumb($newpath))?1:0,
					);

					$this->content->addAnnex($channel->model_value,$annex);

				}
			}
			$this->Report("新增文档成功","mydocument/index");
		}
		else{
			$channel					=	$this->channel->getchannel($channel_id);
			$this->lmtpl->title			=	"添加文档";
			$this->lmtpl->keywords		=	'';
			$this->lmtpl->description	=	'';
			$this->lmtpl->channel_id		=	$channel_id;
			$this->lmtpl->treeCategory		=	$this->category->dropdownCategory("content[cat_id]",$channel,null," dataType='Require' msg='请选择内容主分类'");
			$this->lmtpl->formaction		=	"mydocument/add";
			$this->lmtpl->annex				=	array();
			$this->lmtpl->render(self::tplpath("mydocument_add"));
		}
	}

	function edit($channel_id=false,$content_id=false){
		if(@$this->input->post()){
			$content	=	$this->input->post('content');
			$content_id	=	$this->input->post('content_id');
			$channel_id	=	$content["channel_id"];
			$channel	=	$this->channel->getchannel($channel_id);
			//检查目录
			$dir		=	path::uploadattachment();
			if(!file_exists($dir)){
				file::create_dir_path($dir,true);
			}
			//移动缩略图位置
			if($content['thumb']){
				$newpath	=	$dir."/".date("ymdhis",time()).rand(1,1000).".".pathinfo($content['thumb'],PATHINFO_EXTENSION);
				$oldpath			=	$content['thumb'];
				$content['big_img']	=	$newpath;
				$content['thumb']	=	path::getThumb($newpath);
				@rename($oldpath,$content['big_img']);
				@rename(path::getThumb($oldpath),$content['thumb']);
			}
			//插入文章
			$this->content->updateContent($channel->model_value,$content,$content_id);
			//更新缓存
			$this->content->updateSearchCache($content,$content_id);
			//检查并处理附件。
			if($channel->model_annex_table!=""){
				//修改附件
				if(is_array($oldannexs	=	@$this->input->post('oldannexs')))
				for($i=0;$i<count($oldannexs['annex_id']);$i++){
					$editannex	=	array(
					'description'	=>	$oldannexs['description'][$i],
					'read_money'	=>	$oldannexs['read_money'][$i],
					'read_pointer'	=>	$oldannexs['read_pointer'][$i],
					'upload_time'	=>	date("Y-m-d H:i:s",time()),
					);
					//处理修改的附件
					if(@$_FILES['newpaths'.$oldannexs['annex_id'][$i]]['tmp_name']!=""){
						$ext		=	pathinfo($_FILES['newpaths'.$oldannexs['annex_id'][$i]]['name'],PATHINFO_EXTENSION);
						$FILES = Validation::factory($_FILES)
						->add_rules('newpaths['.$oldannexs['annex_id'][$i].']', 'upload::valid', 'upload::type['.Kohana::config('upload.limittype').']', 'upload::size[10M]');
						if ($FILES->validate()){
							$newfilename	=	date("ymdhis",time()).rand(1,1000).".".pathinfo($_FILES['newpaths'.$oldannexs['annex_id'][$i]]['name'],PATHINFO_EXTENSION);
							$filename 		= 	upload::save('newpaths'.$oldannexs['annex_id'][$i],$newfilename,$dir);
						}
						else{
							$this->main->message		=	"上传附件格式非法";
							$this->main->message_type	=	"error";
							unset($_POST);
							self::edit($content_id);
							exit();
						}
						@unlink($oldannexs['path'][$i]);
						$editannex['path']		=	$filename;
						$editannex['file_type']	=	$ext;
						$editannex['name']		=	basename($filename);
						$editannex['file_size']	=	intval(@filesize($filename)/1024);
						$editannex['is_image']	=	in_array(strtolower($ext),array("jpeg","jpg","png","gif"))?1:0;

					}
					//修改缩略图
					if(@$_FILES['newthumbs'.$oldannexs['annex_id'][$i]]['tmp_name']!=""){
						//处理修改的附件
						$FILES = Validation::factory($_FILES)->add_rules('newthumbs'.$oldannexs['annex_id'][$i].$oldannexs['annex_id'][$i], 'upload::valid', 'upload::type[jpg,gif,png,jpeg]', 'upload::size['.Kohana::config('upload.filesize').']');
						if ($FILES->validate()){
							$newfilename	=	date("ymdhis",time()).rand(1,1000).".".pathinfo($_FILES['newthumbs'.$oldannexs['annex_id'][$i]]['name'],PATHINFO_EXTENSION);
							$thumbpath = upload::save('newthumbs'.$oldannexs['annex_id'][$i],$newfilename,$dir);
						}
						else{
							$this->main->message		=	"上传缩略图格式非法";
							$this->main->message_type	=	"error";
							unset($_POST);
							self::edit($channel_id,$content_id);
							exit();
						}
						@unlink(path::getThumb($oldannexs['path'][$i]));
						$editannex['thumbs_path']	=	$thumbpath;
						$editannex['is_thumbs']		=	1;
					}
					$this->content->updateAnnex($channel->model_value,$editannex,$oldannexs['annex_id'][$i]);
				}
				//加入新附件
				if(is_array($annexs	=	$this->input->post('annex')))
				for ($i=0;$i<count($annexs['path']);$i++){
					//移动文件
					$newpath	=	$dir."/".date("ymdhis",time()).rand(1,1000).".".pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					$ext		=	pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					@rename($annexs['path'][$i],$newpath);
					@rename(path::getThumb($annexs['path'][$i]),path::getThumb($newpath));
					$annex	=	array(
					'path'			=>	$newpath,
					'name'			=>	basename($newpath),
					'channel_id'	=>	$channel_id,
					'file_type'		=>	$ext,
					'content_id'	=>	$content_id,
					'description'	=>	$annexs['description'][$i],
					'read_money'	=>	$annexs['read_money'][$i],
					'read_pointer'	=>	$annexs['read_pointer'][$i],
					'file_size'		=>	intval(@filesize($newpath)/1024),
					'upload_time'	=>	date("Y-m-d H:i:s",time()),
					'thumbs_path'	=>	(in_array(strtolower($ext),array("jpeg","jpg","png","gif"))?1:0)?path::getThumb($newpath):"",
					'is_image'		=>	in_array(strtolower($ext),array("jpeg","jpg","png","gif"))?1:0,
					'is_thumbs'		=>	file_exists(path::getThumb($newpath))?1:0,
					);

					$this->content->addAnnex($channel->model_value,$annex);

				}
			}
			$this->Report("修改文档成功","mydocument/index");
		}
		else{
			$channel	=	$this->channel->getchannel($channel_id);
//			$this->file						=	new file();
			if(file_exists("upload/tmp")){
				$paths						=	file::scan_dir("upload/tmp");
			}
			else{
				$paths						=	0;
			}
			$this->lmtpl->content			=	$this->content->get_content_id($channel->model_value,$content_id);
			$this->lmtpl->total_annex		=	count($paths);
			$this->lmtpl->treeCategory		=	$this->category->dropdownCategory("content[cat_id]",$channel,$this->lmtpl->content->cat_id," dataType='Require' msg='请选择内容主分类'");
			$this->lmtpl->title				=	"编辑文档";
			$this->lmtpl->keywords			=	"";
			$this->lmtpl->description		=	"";
			$annexs							=	$this->content->getannexs($channel->model_value,$content_id)->result_array();
			$this->lmtpl->annex				=	is_array($annexs)?$annexs:array();
			$this->lmtpl->channel_id		=	$channel_id;
			$this->lmtpl->formaction		=	"mydocument/edit";
			$this->lmtpl->render(self::tplpath('mydocument_add'));
		}
	}

	function delete($channel_id,$content_id,$page=1){
		$channel		=	$this->channel->getchannel($channel_id);
		//删除文章
		$this->myd->delete($channel->model_value,$channel_id,$content_id);
		$this->myd->deleteSearch($channel_id,$content_id);
		$this->index($page);

	}
	//删除附件
	function deleteannex($channel_id,$annex_id){
		$channel			=	$this->channel->getchannel($channel_id);
		$this->content->delete_annex($channel->model_value,$annex_id);
	}
	function thumb($channelid=false,$inputid=false){
		if($this->input->post()){
			extract($_POST);
			$_FILES = Validation::factory($_FILES)
			->add_rules('uploadfile', 'upload::valid', 'upload::type[gif,jpg,png,rar,zip,jpeg,doc,txt]', 'upload::size[10M]');
			if($_FILES->validate()){
				// Temporary file name
				$filename 				= 	upload::save('uploadfile',null,"upload/tmp");
				$thumb					=	path::getThumb($filename);
				if(IS_THUMB){
					list($x,$y)						=	explode("|",THUMB_WAY);
					list($org_width,$org_height)	=	getimagesize($filename);
					if($org_width>$org_height){ $resizeType	=	Image::HEIGHT;}else{	$resizeType	=	Image::WIDTH;	}
					$image	=	new Image($filename);
					$image->resize($width,$height,$resizeType);
					if($x!=1&&$y!=1){
						$image->crop($width,$height,$x,$y);
					}
					$image->save($thumb);
				}
				if(WATERMARK_ENABLE){
					Image::factory($filename)
					->makewater($water=array('type'=>WATERMARK_TYPE,'transparence'=>WATERMARK_TRANSPARENCE,'margin'=>20,'position'=>WATERMARK_POS),$font=array("color"=>"#FFFFFF","text"=>WATERMARK_TEXT,"size"=>24,"font"=>"public/share/font/ariblk.ttf","is_zh"=>true),$water_image=array('src'=>WATERMARK_PATH))
					->save($filename);
				}
				$this->lmtpl->post		=	true;
				$this->lmtpl->inputid	=	$inputid;
				$this->lmtpl->path		=	$filename;
				$this->lmtpl->imagepath	=	$thumb;
				$this->lmtpl->render(self::tplpath('mydocument_thumb'));
			}
		}
		else{
			$this->lmtpl->channel	=	$this->channel->getchannel($channelid);
			$this->lmtpl->inputid	=	$inputid;
			$this->lmtpl->post		=	false;
			$this->lmtpl->render(self::tplpath('mydocument_thumb'));
		}
	}
	function batchupload($url='',$channelid=false){
		if($this->input->post()){
			parse_str(str_replace("&amp;","&",$url),$result);
			extract($result);
			if(@$currentPath!=''){
				$targPath=$currentPath;
			}
			else{
				$targPath='upload/tmp';
			}
			$_FILES = Validation::factory($_FILES)
			->add_rules('uploadfile', 'upload::valid', 'upload::type[gif,jpg,png,rar,zip,jpeg,doc,txt]', 'upload::size[10M]');
			if ($_FILES->validate()){
				// Temporary file name
				$filename = upload::save('uploadfile',null,$targPath);
				//检查是能生成缩略图
				if(in_array(strtolower(pathinfo($filename,PATHINFO_EXTENSION)),array("jpg","jpeg","png","gif"))){
					list($org_width,$org_height)	=	getimagesize($filename);
					if($org_width>$org_height){ $resizeType	=	Image::HEIGHT;}else{	$resizeType	=	Image::WIDTH;	}

					if(IS_THUMB){
						list($x,$y)						=	explode("|",THUMB_WAY);
						list($org_width,$org_height)	=	getimagesize($filename);
						if($org_width>$org_height){ $resizeType	=	Image::HEIGHT;}else{	$resizeType	=	Image::WIDTH;	}
						if($x==1&&$y==1){	$resizeType	=	Image::AUTO;	}
						$image	=	new Image($filename);
						$image->resize($width,$height,$resizeType);
						if($x!=1&&$y!=1){
							$image->crop($width,$height,$x,$y);
						}
						$image->save(path::getThumb($filename));
					}
					if(WATERMARK_ENABLE){
						Image::factory($filename)
						->makewater($water=array('type'=>WATERMARK_TYPE,'transparence'=>WATERMARK_TRANSPARENCE,'margin'=>20,'position'=>WATERMARK_POS),$font=array("color"=>"#FFFFFF","text"=>WATERMARK_TEXT,"size"=>24,"font"=>"public/share/font/ariblk.ttf","is_zh"=>true),$water_image=array('src'=>WATERMARK_PATH))
						->save($filename);
					}

				}
				$result['result']	=	"success";
				$result['temppath']	=	$filename;
				$result['size']		=	"上传成功";
				echo json_encode($result);
			}
			else{
				$result['result']	=	"error";
				$result['error']	=	"文件格式错误";
				echo json_encode($result);
			}
		}
		else{
			$this->lmtpl->title			=	"批量上传附件";
			$this->lmtpl->keywords		=	'';
			$this->lmtpl->description	=	'';
			$this->lmtpl->filesize		=	'1MB';
			$this->lmtpl->limitfiles	=	10;
			$this->lmtpl->currentPath	=	'';
			$this->lmtpl->channel		=	$this->channel->getchannel($channelid);
			$this->lmtpl->render(self::tplpath('member_batchupload'));
		}
	}
}