<?php
class Admin_ArticleController extends Zend_Controller_Action 
{	
	public $fenleiString;
	public function init()
	{	Zend_Loader::loadClass('Article');
		Zend_Loader::loadClass('Attachment');
		Zend_Loader::loadClass('Articleclass');
		$this->smarty=Zend_Registry::get('smarty');
		$this->config=Zend_Registry::get('config');
		$this->smarty->assign('baseUrl',$this->_request->getBaseUrl());
		
	}
	
	public function indexAction()
	{
			$article=new Article();
			$page=$this->_request->getParam('page');
			//if('0'>=$page) $page=1;
			$condition=NULL;
			$sortby='id DESC';
			Zend_Loader::loadClass('Custom_Controller_Plugin_Pager');
			$basePageIndex=0;
			$Pagers = new Custom_Controller_Plugin_Pager($article,$page,'10',$condition,$sortby,$basePageIndex) ;
			
			$pageInfo = $Pagers->getNavBar(WEB_ROOT.'admin/article/index/');
			$this->smarty->articles = $Pagers->findAll();
	    	$this->smarty->assign('arrArticles',$this->smarty->articles->toArray());
	    	
	    	$this->smarty->assign("pageInfo",$pageInfo);
             //显示模版
			$this->smarty->display('article/index.phtml');
             
	}
	public function searchAction()
	{
		$this->smarty->display('article/search.phtml');
	}
	
	
	public function addAction()
	{	
		if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$filter=new Zend_Filter_StripTags();
			$author=$filter->filter(($this->_request->getPost('author')));
			$title=$filter->filter(($this->_request->getPost('title')));
			$class=$filter->filter(($this->_request->getPost('sunid')));
			$show=$filter->filter(($this->_request->getPost('show')));
			$FCKcontent=$this->_request->getPost('FCKcontent');
			$tagstring=$filter->filter(($this->_request->getPost('tag')));
			$id=$filter->filter(($this->_request->getPost('id')));
			$showtime=$filter->filter($this->_request->getPost('showtime'));
			$urls=$this->_request->getPost('filenames');
			$attachdesc=$this->_request->getPost('attachdesc');
			$imgname=$this->_request->getPost('imgname');
			$attachment=new Attachment();
			$artist=new Article();
			if($author!=''&&$title!=''){
				//取到tags并分割为数组
				$Arrtags=array_filter(array_unique(preg_split ("/[,|:|\s]+/", $tagstring)));
				$attachment=new Attachment();
				$artist=new Article();
				$tags=new Tags();
				$itemtags=new Itemtags();
				$db = $artist->getAdapter();
				$dbtags = $tags->getAdapter();
				if(''==$id){
					$data=array(
					'author'=>$author,
					'title'=>$title,
					'class'=>$class,
					'show'=>$show,
					'content'=>$FCKcontent,
					'addtime'=>time(),
					'updatetime'=>time()
					);
					$artist->insert($data);
					$articleId = $db->lastInsertId();
					unset($data);
					//处理tags表.以及对应的日志表itemtags
					while(list($key , $val) = each($Arrtags)) {
						$tagflag=$tags->fetchAll('name='."'$val'")->toArray();
						if(count(array_filter($tagflag))=='0'){
							$Tagdata=array('name'=>$val);
							$tags->insert($Tagdata);
							$tagsId = $dbtags->lastInsertId();
							unset($Tagdata);
						}else{
							$tagsId=$tagflag[0]['id'];
						}
						$Itemdata=array(
									'tagid'=>$tagsId,
									'itemid'=>$articleId,
									'type'=>'article'
							);
						$itemtags->insert($Itemdata);
						unset($Itemdata);
						
					}
					
					$messages="您日志发布成功!";
				}else{
					$set=array(
					'author'=>$author,
					'title'=>$title,
					'class'=>$class,
					'show'=>$show,
					'content'=>$FCKcontent,
					'updatetime'=>time()
					);
					$where = $db->quoteInto('id = ?', $id);
					//更新表数据,返回更新的行数
					$typeid=$id;
					$rows=$artist->update($set, $where);
					unset($set);
					//删除存在的标签
					$itemtagflag=$itemtags->fetchAll("itemid=".$id." and type='article'")->toArray();
					if(count(array_filter($itemtagflag))!='0'){
						$wheretag = "itemid=".$id." and type='article'";
	                	$itemtags->delete($wheretag);
					}
                	
				 	//处理tags表.以及对应的日志表itemtags
				    while(list($key , $val) = each($Arrtags)) {
						$tagflag=$tags->fetchAll('name='."'$val'")->toArray();
						if(count(array_filter($tagflag))=='0'){
							$Tagdata=array('name'=>$val);
							$tags->insert($Tagdata);
							$tagsId = $dbtags->lastInsertId();
							unset($Tagdata);
						}else{
							$tagsId=$tagflag[0]['id'];
						}
						$Itemdata=array(
									'tagid'=>$tagsId,
									'itemid'=>$id,
									'type'=>'article'
							);
						$itemtags->insert($Itemdata);
						unset($Itemdata);
					}
					
					
					$messages="您编辑日志成功!";
				}
				if(0!=count($urls))
				{
					//增加文件
					$num=count(array_filter($urls));
					for ($i = 0; $i < $num; $i++) {
						$data=array(
						'typeid'=>$typeid,
						'type'=>'article',
						'url'=>$urls[$i],
						'attachdesc'=>$attachdesc[$i],
						'imgname'=>$imgname[$i],
						'downs'=>'0',
						'addtime'=>time()
						);
						$attachment->insert($data);
					
					}
				}
				
				Zend_Loader::loadClass('Custom_Controller_Plugin_Message');
				$Message = new Custom_Controller_Plugin_Message();
				$this->smarty->display('header.phtml');
				$Message->showMsg('<font color=\"red\">'.$messages.'</font>',WEB_ROOT.'admin/article/index/');
				$this->smarty->display('footer.phtml');
				//$this->_redirect('admin/article/addarticle');
				
			}
		}else{
			$this->fckAction();
			$class=new Articleclass();
			$this->smarty->articleclass = $class->fetchAll('pid=0');
			$classAll=$this->smarty->articleclass->toArray();
			$this->smarty->assign('classAll',$classAll);
			$this->smarty->assign('sunid',$classAll[0]['id']);
	      	$this->smarty->display('article/add.phtml');
		}
		
	}
	
	
	public function editAction()
	{	Zend_Loader::loadClass('Zend_Filter_StripTags');
		$filter=new Zend_Filter_StripTags();
		$article=new Article();
		$itemtags=new Itemtags();
		$dbitemtag = $itemtags->getAdapter();
		
		$id=$filter->filter(($this->_request->getParam('id')));
		$this->smarty->article = $article->fetchAll('id='.$id);
		$Articleone=$this->smarty->article->toArray();
		$attachment=new Attachment();
		$sortby='id DESC';
		$this->smarty->attachs = $attachment->fetchAll('typeid='.$id,$sortby);
		$attachs=$this->smarty->attachs->toArray();
		//print_r($attachs);
		$this->smarty->assign('Articleone',$Articleone);
		$this->smarty->assign('attachs',$attachs);
		//print_r($Articleone);
		$this->fckAction($Articleone[0]['content']);
		//取到tags列表
		$query="SELECT `".TABLE_PRE."itemtags`.*, `".TABLE_PRE."tags`.* FROM `".TABLE_PRE."itemtags` INNER JOIN `".TABLE_PRE."tags` ON ".TABLE_PRE."itemtags.tagid = `".TABLE_PRE."tags`.id  Where `".TABLE_PRE."itemtags`.itemid=$id and `".TABLE_PRE."itemtags`.type='article'";
		$this->smarty->assign('tagString',$dbitemtag->fetchAll($query));
		
		//取到分类
		$class=new Articleclass();
		$this->smarty->articleclass = $class->fetchAll('pid=0');
		$classAll=$this->smarty->articleclass->toArray();
		$this->smarty->assign('classAll',$classAll);
		$this->smarty->assign('sunid',$Articleone[0]['class']);
		//$this->allclassAction($Articleone[0]['class']);
		//echo $this->allclassAction($Articleone[0]['class']);
		$this->smarty->assign( 'fenleiString', $this->editclassAction($Articleone[0]['class']));
		$this->smarty->display('article/edit.phtml');
	}
	
	public function editclassAction($id)
	{	
		$class=new Articleclass();
		$this->smarty->articlepid= $class->fetchAll('id='.$id);
		$classpid=$this->smarty->articlepid->toArray();
		$thisString='';
		$pid=$classpid[0]['pid'];
		$this->smarty->articleclass = $class->fetchAll('pid='.$pid);
		$thisArray=$this->smarty->articleclass->toArray();
		//if(0==$pid){$innerid=1;}else{$innerid=$pid;}
		if(0==$pid){
			$classid=1;
		}else{
			$classid=$pid;
		}
		$thisString.='<select id="class'.$classid.'" name="class'.$classid.'" onchange="ChangeClass('.$classid.')">';
		for($i=0;$i<count($thisArray);$i++){
			if($thisArray[$i]['id']==$id){
				$thisString.='<option selected value="'.$thisArray[$i]['id'].'">'.$thisArray[$i]['name'].'</option>';
			}
			else{
				$thisString.='<option value="'.$thisArray[$i]['id'].'">'.$thisArray[$i]['name'].'</option>';
			}
		}
		$thisString.='</select>';
		if(0==$pid){
			$thisString.='<span id="inner1">';
		}else{
			$thisString.='<span id="inner'.$pid.'">';
		}
		$this->fenleiString=$thisString.$this->fenleiString;
		
		if($pid!=0){
		$this->editclassAction($pid);
		
		}
		return $class=$this->fenleiString;
		
		
		
	}	
	
	
	public function delAction()
	{		
		$article=new Article();
		$attachment=new Attachment();
		if (strtolower($_SERVER['REQUEST_METHOD'])=='post') {
            $id =$this->_request->getPost('id');
            
            $StringId = join ( ",", $id );
            $where = 'id IN ('.$StringId.')';
            $article->delete($where);
            
			$num=count(array_filter($id));
			for ($i = 0; $i < $num; $i++) {
				$this->smarty->attach = $attachment->fetchAll('typeid='.$id[$i]);
				$Articleone=$this->smarty->attach->toArray();
				//print_r($Articleone);
				$nums=count(array_filter($Articleone));
				for ($j = 0; $j < $nums; $j++) {
					$imgurl=ROOT_DIR.'/blog/public/upload/article/'.$Articleone[$j]['imgname'];
					@unlink($imgurl);
				}
			}
			$where = 'typeid IN ('.$StringId.')';
           	$attachment->delete($where);
        } else {
            $id = (int)$this->_request->getParam('id');
        	if ($id > 0) {
                $where = 'id = ' . $id;
                $article->delete($where);
            }
            $this->smarty->attach = $attachment->fetchAll('typeid='.$id);
			$Articleone=$this->smarty->attach->toArray();
        	$nums=count(array_filter($Articleone));
			for ($j = 0; $j < $nums; $j++) {
					$imgurl=ROOT_DIR.'/blog/public/upload/article/'.$Articleone[$j]['imgname'];
					@unlink($imgurl);
			}
			$where = 'typeid ='.$id;
           	$attachment->delete($where);
        }
		 //print_r('8787008');
		Zend_Loader::loadClass('Custom_Controller_Plugin_Message');
		$Message = new Custom_Controller_Plugin_Message();
		$this->smarty->display('header.phtml');
		$Message->showMsg('<font color=\"red\">您日志删除成功!</font>',WEB_ROOT.'admin/article/index/');
		$this->smarty->display('footer.phtml');
	}
	
	public function delattachAction()
	{		
		$attachment=new Attachment();
		if (strtolower($_SERVER['REQUEST_METHOD'])=='post') {
            $id =$this->_request->getPost('id');
            $typeid =$this->_request->getPost('typeid');
            $imgurl=ROOT_DIR.'/blog/public/upload/article/'.$this->_request->getPost('imgname');
			@unlink($imgurl);
			if ($id > 0) {
                $where = 'id = ' . $id;
                $attachment->delete($where);
            }
        }else {
            $id = (int)$this->_request->getParam('id');
        	if ($id > 0) {
                $where = 'id = ' . $id;
                $attachment->delete($where);
            }
        }
        $sortby='id DESC';
		$this->smarty->attachs = $attachment->fetchAll('typeid='.$typeid,$sortby);
		$attachs=$this->smarty->attachs->toArray();
		//print_r($attachs);
		$this->smarty->assign('attachs',$attachs);
		$this->smarty->display('article/attach.phtml');
		
	}

	public function fckAction($content='')
	{
		Zend_Loader::loadClass('Custom_Controller_Plugin_Fckeditor');
		$oFCKeditor = new Custom_Controller_Plugin_Fckeditor('FCKcontent') ;
        $oFCKeditor->BasePath = WEB_ROOT."public/scripts/fckeditor/";
       	$oFCKeditor->Config['SkinPath'] = WEB_ROOT.'public/scripts/fckeditor/editor/skins/silver/' ;
        $oFCKeditor->Width  = '100%';
        $oFCKeditor->Height = '300';
      	$oFCKeditor->Value = $content;
      	$this->smarty->assign("oFCKeditor",$oFCKeditor);
	}
	
	
	public function delimageAction()
	{	$imgurl=ROOT_DIR.'/blog/public/upload/article/'.$this->_request->getPost('url');
		@unlink($imgurl);
	}
	
	
	public function uploadAction()
	{	$fileid=$this->_request->getParam('fileid');
		
		$attachdesc=$this->_request->getPost('attachintro');
		$attachdesc=$attachdesc[0];
		
		
		Zend_Loader::loadClass('Custom_Controller_Plugin_Upload');
    	$uploadfile=new Custom_Controller_Plugin_Upload(ROOT_DIR.'/blog/public/upload/article/','uploadfile','10','2048000',array("gif","png","jpg","bmp","jpeg"),600,600);
		
		//$num = count ( array_filter ( $uploadfile->Error));
    	if(''==$uploadfile->Error){
			$imgUrl=WEB_ROOT.'public/upload/article/'.$uploadfile->lastFileName;
			echo "<script language=\"javascript\" type=\"text/javascript\">
			//parent.alert('上传成功！请返回！');
			parent.document.getElementById(\"$fileid\").innerHTML='上传的图片：<img src=\"$imgUrl\"  width=\"100px\" height=\"20px\"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;图片说明:".$attachdesc."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=InserImg(\"$imgUrl\");  href=\"#\" >插入</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a onclick=delImages(\"$fileid\",\"$uploadfile->lastFileName\");  href=\"#\" >删除</a><input name=\"filenames[]\" value=\"$imgUrl\" type=\"hidden\"  /><input name=\"imgname[]\" value=\"$uploadfile->lastFileName\" type=\"hidden\"  /><input name=\"attachdesc[]\" value=\"$attachdesc\" type=\"hidden\"  />';
			</script>";
		}else{
			echo "<script language=\"javascript\" type=\"text/javascript\">
			parent.alert('".$uploadfile->Error."');
			</script>";
		}
		
	}
}

