<?php
class Admin_FeedController 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()
	{
			$feedlink=new Feedlink();
			$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($feedlink,$page,'10',$condition,$sortby,$basePageIndex) ;
			
			$pageInfo = $Pagers->getNavBar(WEB_ROOT.'admin/feed/index/');
			$this->smarty->feeds = $Pagers->findAll();
	    	$this->smarty->assign('arrFeed',$this->smarty->feeds->toArray());
	    	
	    	$this->smarty->assign("pageInfo",$pageInfo);
             //显示模版
			$this->smarty->display('feed/index.phtml');
             
	}
	
	
	public function addfeedAction()
	{		
		if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){
		  	$url =$this->_request->getPost('url');
		  	//print_r($url);
			require_once 'Zend/Feed.php';
			foreach ($url as $channel) {
				$this->redRssFeedAction($channel);
			}
			$messages='您的Feed已增加到数据库中';
			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/feed/addfeed/');
			$this->smarty->display('footer.phtml');

		}else{
		
			    $feedlink=new Feedlink();
				$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($feedlink,$page,'10',$condition,$sortby,$basePageIndex) ;
				
				$pageInfo = $Pagers->getNavBar(WEB_ROOT.'admin/feed/addfeed/');
				$this->smarty->feeds = $Pagers->findAll();
		    	$this->smarty->assign('arrFeed',$this->smarty->feeds->toArray());
		    	
		    	$this->smarty->assign("pageInfo",$pageInfo);
	             //显示模版
				$this->smarty->display('feed/addfeed.phtml');
		}
		
		
             
	
	}
	
	
	public function searchAction()
	{
		$this->smarty->display('article/search.phtml');
	}
	
	
	public function redRssFeedAction($feedAddress)
	{
		try {
			$rss = Zend_Feed::import($feedAddress);
		    } catch (Zend_Feed_Exception $e) {
	        		 // Feed 导入失败
	           		$msg = "Exception caught importing feed: {$e->getMessage()}\n ";
	                $dateTime = date("Y-m-d H:i:s",time());
	                $errMsg = $msg.' '.$dateTime."\n\n";
	                echo $errMsg;  
	              exit;
	        }
	        // 初始化保存 channel 数据的数组，$rss内部数据只能通过调用类方法才能访问
	    	$channel = array(
	         'title'       => $rss->title(),
	         'link'        => $rss->link(),
	         'description' => $rss->description(),
	         'items'       => array()
	        );

            $count=0;    
        	// 循环获得channel的item并存储到相关数组中
        	foreach ($rss as $item) {
             $channel['items'][] = array(
                'title'       => $item->title(),
                'link'        => $item->link(),
                'description' => $item->description()
                );
            $feedarticle=new Feed();
    		$feeddb=$feedarticle->getAdapter();
             //标题和内容都需要转义
            $title = $item->title();
            $link = strip_tags($item->link());         
            $description = $item->description();
             //先查询数据库看记录是否已经存在，存在则不操作，否则向数据库添加新记录
             $feedquery=" SELECT *  FROM `".TABLE_PRE."feed` WHERE `".TABLE_PRE."feed`.title = '$title' ";
    		 $feeds=$feeddb->fetchAll($feedquery);
             $num_rows =count($feeds);

               if($num_rows<='0') {
                 $feeddata=array(
						'title'=>$title,
						'link'=>$link,
                 		'title'=>$title,
						'description'=>$description,
                 		'addtime'=>time(),
	    				);
				$feedarticle->insert($feeddata);
                 $count++;
              }            
        } //zend::dump($channel); 
	
	}
	
	public function addAction()
	{	
		if(strtolower($_SERVER['REQUEST_METHOD'])=='post'){
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$filter=new Zend_Filter_StripTags();
			$url=$filter->filter(($this->_request->getPost('url')));
			$title=$filter->filter(($this->_request->getPost('title')));
			$class=$filter->filter(($this->_request->getPost('sunid')));
			$FCKcontent=$this->_request->getPost('FCKcontent');
			//$tagstring=$filter->filter(($this->_request->getPost('tag')));
			$id=$filter->filter(($this->_request->getPost('id')));
		
		
			
			if($url!=''&&$title!=''){
				//取到tags并分割为数组
				//$Arrtags=array_filter(array_unique(preg_split ("/[,|:|\s]+/", $tagstring)));
				$feedlink=new Feedlink();
				$db = $feedlink->getAdapter();
			
				if(''==$id){
					$data=array(
					'url'=>$url,
					'title'=>$title,
					'class'=>$class,
					'content'=>$FCKcontent,
					'addtime'=>time(),
					'updatetime'=>time()
					);
					$feedlink->insert($data);
					$FeedId = $db->lastInsertId();
					unset($data);
					$messages="您Feed网站列表增加成功!";
				}else{
					$set=array(
					'url'=>$url,
					'title'=>$title,
					'class'=>$class,
					'content'=>$FCKcontent,
					'updatetime'=>time()
					);
					$where = $db->quoteInto('id = ?', $id);
					//更新表数据,返回更新的行数
					
					$feedlink->update($set, $where);
					unset($set);
					
					$messages="您Feed网站编辑成功!";
				}
			
				
				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/feed/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('feed/add.phtml');
		}
		
	}
	
	
	public function editAction()
	{	Zend_Loader::loadClass('Zend_Filter_StripTags');
		$filter=new Zend_Filter_StripTags();
		$feedlink=new Feedlink();
	
		$id=$filter->filter(($this->_request->getParam('id')));
		$this->smarty->article = $feedlink->fetchAll('id='.$id);
		$Feedone=$this->smarty->article->toArray();
		
		//print_r($attachs);
		$this->smarty->assign('Feedone',$Feedone);
	
		$this->fckAction($Feedone[0]['content']);

		
		//取到分类
		$class=new Articleclass();
		$this->smarty->articleclass = $class->fetchAll('pid=0');
		$classAll=$this->smarty->articleclass->toArray();
		$this->smarty->assign('classAll',$classAll);
		$this->smarty->assign('sunid',$Feedone[0]['class']);
		//$this->allclassAction($Articleone[0]['class']);
		//echo $this->allclassAction($Articleone[0]['class']);
		$this->smarty->assign( 'fenleiString', $this->editclassAction($Feedone[0]['class']));
		$this->smarty->display('feed/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 Feedlink();
		
		if (strtolower($_SERVER['REQUEST_METHOD'])=='post') {
            $id =$this->_request->getPost('id');
            $StringId = join ( ",", $id );
            $where = 'id IN ('.$StringId.')';
            $article->delete($where);
            
        } else {
            $id = (int)$this->_request->getParam('id');
        	if ($id > 0) {
                $where = 'id = ' . $id;
                $article->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\">您Feed列表删除成功!</font>',WEB_ROOT.'admin/feed/index/');
		$this->smarty->display('footer.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);
	}
	
	
	
	
	
	
}

