<?php
class Model_Content_Controller extends Base_Controller {
	function __construct(){
		parent::__construct();
		$this->channel	=	new Model_Channel_Model();
		$this->category	=	new Model_Category_Model();
		$this->content	=	new Model_Content_Model();
		$this->createForm=	new Model_Createform_Model();
		$this->modelhtml=	new Model_html_Controller();
		$this->column		=	new Model_Column_Model();
		$this->html			=	new Html_Model();
	}
	function index($channel_id=false,$cat_id=0,$page=1,$showline=30,$keywords=false){
		if(@$this->input->post()){
			$search				=	$this->input->post("search");
			$channel_id			=	$search['channel_id'];
			$cat_id				=	$search['cat_id'];
			$keywords			=	$search['keywords'];
		}
		$this->view				=	new View("content/list");
		$channelList			=	$this->channel->getchannellist();
		if(count($channelList)==0){
			die('请先添加站点');
		}
		if($channel_id===false){
			$channel			=	$channelList[0];
			$channel_id			=	$channel->channel_id;
		}
		else{
			$channel			=	$this->channel->getchannel($channel_id);
		}

		if($channel_id){
			/**
			 * 内容列表
			 */
			//分页
			$contents_sum					=	$this->content->get_content_list(array("channel_id"=>$channel_id,"model_value"=>$channel->model_value,"category_id"=>$cat_id,"keywords"=>$keywords,"page"=>false,"showline"=>false))->count();
			$pagecfg['total_items']			=	$contents_sum;
			$pagecfg['current_page']		=	$page;
			$pagecfg['items_per_page']		=	$showline;
			$pagecfg['base_url']			=	BASEURI."model_content/index";
			$pagecfg['uri_segment']			=	$channel_id."/".$cat_id;
			$this->pagination				=	new Pagination($pagecfg);
			$contents_list					=	$this->content->get_content_list(array("channel_id"=>$channel_id,"model_value"=>$channel->model_value,"category_id"=>$cat_id,"keywords"=>$keywords,"page"=>$page,"showline"=>$showline))->result_array();
			$this->view->categoryobj		=	array();
			$this->view->category_id		=	"false";
			$this->view->showline			=	$showline;
		}
		else{
			$htis->view->message_type		=	"error";
			$this->view->message			=	$this->lang->line('error');
		}
		$consobj							=	array();
		foreach ($contents_list as $con){
			$con->url	=	$this->html->url($channel_id,$con->cat_id,$con->content_id);
			$consobj[]	=	$con;
		}
		$this->view->contents			=	$consobj;
		$this->view->model				=	$this->category;
		$this->view->titile				=	"内容列表";
		$this->main->formAction			=	"model_content/index";
		$this->view->channel_id			=	$channel_id;
		$this->view->title				=	Kohana::lang("content_lang.".$channel->channel_name);
		$this->view->treeCategory		=	$this->category->dropdownCategory("search[cat_id]",$channel);
		$this->view->channel_name		=	$channel->channel_name;
		$this->view->dropdowncChannel	=	$this->channel->dropdowncChannel("search[channel_id]",$channel_id,"onChange='button_location(\"".BASEURI."model_content/index/\"+this.value)'");
		$this->display();
	}

	function add($channel_id=false){
		if($this->input->post()){
			$content	=	$this->input->post('content');
			$channel_id	=	$content["channel_id"];
			$cat_id		=	@$content["cat_id"]?$content["cat_id"]:false;
			$channel	=	$this->channel->getchannel($channel_id);
			$content['publish_date']	=	time();
			//检查附件目录
			$dir		=	path::uploadattachment();
			if(file_exists($dir)){
				file::create_dir_path($dir);
			}
			//处理缩略图检查目录
			if($content['thumb']!=''){
				$content['big_img']	=	path::getBigImage($content['thumb']);
			}
			//插入文章
			$content_id	=	$this->content->addContent($channel->model_value,$content);
			//插入全局内容表以便搜索
			$search['content_id']	=	$content_id;
			$fields 		= 	$this->column->list_fields("search_cache");
			
			foreach($fields as $column=>$value){
				if(array_key_exists($column,$content))	$search[$column]	=	$content[$column];
			}
			$this->content->searchCache($search);
			//检查并处理附件。
			
			if($channel->model_annex_table!=""&&is_array($annexs	=	$this->input->post('annex'))){
				for ($i=0;$i<count($annexs['path']);$i++){
					//移动文件
					$ext		=	pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					$newpath	=	$dir."/".date("ymdhis",time()).rand(1,1000).".".pathinfo($annexs['path'][$i],PATHINFO_EXTENSION);
					if(!preg_match("#http:#",$annexs['path'][$i])){
						@rename($annexs['path'][$i],$newpath);
						@rename(path::getThumb($annexs['path'][$i]),path::getThumb($newpath));
					}
					else{
						$newpath=	$annexs['path'][$i];
					}
					$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->main->message		=	Kohana::lang("content_lang.already_save");
			$htis->main->message_type	=	"success";
			//更新HTML文件
			//1，更新首页
			$this->modelhtml->updateIndexHtml();
			//2，更新分类
			$this->modelhtml->updateCategoryHtml($channel_id,$cat_id);
			//3，更新内容
			$this->modelhtml->updateContentHtml($channel_id,$cat_id,$content_id);
			if($this->input->post('is_keep')){
				unset($_POST);
				$this->add($channel_id);
			}
			else{
				unset($_POST);
				$this->index($channel_id);
			}
		}
		else{
			$channel	=	$this->channel->getchannel($channel_id);
			$this->view	=	new View("content/add");
			if(!$form=$this->createForm->create($channel_id,"content")){
				$htis->view->message_type	=	"error";
				$this->view->message		=	Kohana::lang('content_lang.form_error');
			}
			$this->file						=	new file();
			if(file_exists("upload/tmp")){
				$paths						=	$this->file->scan_dir("upload/tmp");
			}
			else{
				$paths						=	0;
			}
			$this->view->total_annex		=	count($paths);
			$this->view->form				=	$form;
			$this->main->formAction			=	"model_content/add";
			$this->main->is_validator		=	true;
			$this->view->attachForm			=	$this->createForm->create($channel_id,"attachment");
			$this->view->treeCategory		=	$this->category->dropdownCategory("content[cat_id]",$channel,null," dataType='Require' msg='请选择内容主分类'");
			$this->view->title				=	"添加内容";
			$this->view->attachLists		=	array();
			$this->view->channel_id			=	$channel_id;
			$this->display();
		}
	}

	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);
			}
			//处理缩略图检查目录
			if($content['thumb']!=''){
				$content['big_img']	=	path::getBigImage($content['thumb']);
			}
			//插入文章
			$this->content->updateContent($channel->model_value,$content,$content_id);
			//更新缓存
			$search['content_id']	=	$content_id;
			$fields 		= 	$this->column->list_fields("search_cache");
			foreach($fields as $column=>$value){
				if(array_key_exists($column,$content))	$search[$column]	=	$content[$column];
			}
			$this->content->updateSearchCache($search,$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);
					if(!preg_match("#http:#i",$annexs['path'][$i])){
						@rename($annexs['path'][$i],$newpath);
						@rename(path::getThumb($annexs['path'][$i]),path::getThumb($newpath));
					}
					else{
						$newpath=	$annexs['path'][$i];
					}
					$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->main->message			=	"操作成功";
			$htis->main->message_type		=	"success";
			unset($_POST);
			//更新HTML文件
			//1，更新首页
			$this->modelhtml->updateIndexHtml();
			//2，更新分类
			$this->modelhtml->updateCategoryHtml($channel_id,@$content['cat_id']);
			//3，更新内容
			$this->modelhtml->updateContentHtml($channel_id,@$content['cat_id'],$content_id);
			$this->index($channel_id);
		}
		else{
			$channel	=	$this->channel->getchannel($channel_id);
			$this->view	=	new View("content/add");
			$content	=	$this->content->get_content_id($channel->model_value,$content_id);
			if(!$form=$this->createForm->create($channel_id,"content",$content)){
				$htis->view->message_type	=	"error";
				$this->view->message		=	Kohana::lang('content_lang.form_error');
			}
			$this->file						=	new file();
			if(file_exists("upload/tmp")){
				$paths						=	$this->file->scan_dir("upload/tmp");
			}
			else{
				$paths						=	0;
			}
			$this->view->content			=	$content;
			$this->view->total_annex		=	count($paths);
			$this->view->form				=	$form;
			$this->main->formAction			=	"model_content/edit";
			$this->main->is_validator		=	true;
			$this->view->treeCategory		=	$this->category->dropdownCategory("content[cat_id]",$channel,$this->view->content->cat_id," dataType='Require' msg='请选择内容主分类'");
			$this->view->title				=	"添加内容";
			$annexs							=	$this->content->getannexs($channel->model_value,$content_id)->result_array();
			$attachForm						=	$this->createForm->create($channel_id,"EditAttachment",$annexs);
			$this->view->attachLists		=	$attachForm['attachLists'];
			$this->view->attachForm			=	$attachForm['formFeild'];
			$this->view->channel_id			=	$channel_id;
			$this->display();
		}
	}

	function delete($channel_id=false,$content_id=false,$sort_id=0,$page_no=0,$showline=30){
		if($this->input->post()){
			$content_id	=	$this->input->post('select_id');
			$channel_id	=	$this->input->post('channel_id');
		}
		if(is_array($content_id)){
			$_content_id	=	$content_id;
		}
		else{
			$_content_id[]	=	$content_id;
		}
		$channel		=	$this->channel->getchannel($channel_id);
		//删除文章
		$this->content->delete($channel->model_value,$channel_id,$_content_id);
		$this->content->deleteSearch($channel_id,$_content_id);
		$this->index($channel_id);

	}
	//删除附件
	function deleteannex($channel_id,$annex_id){
		$channel			=	$this->channel->getchannel($channel_id);
		$this->content->delete_annex($channel->model_value,$annex_id);
	}

	function auditing(){
		$audit		=	$this->input->post("audit");
		$conid		=	$this->input->post("select_id");
		$channel_id	=	$this->input->post("channel_id");
		$channel	=	$this->channel->getchannel($channel_id);
		$this->content->auditing($audit,$conid,$channel->model_value);	
		unset($_POST);
		$this->index($channel_id);
	}
	//发布内容
	function publish(){
		$channelList	=	$this->channel->getchannellist();
		$this->view		=	new View("content/publish");
		$this->view->channelList=$channelList;
		$this->display();
	}
}