<?php
 /**
 *      [XCECP] (C) Colorful Network Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class ArticleModel extends BaseModel{
	public $msg = '';
	function getInfo($id,$fields='*'){
		$fieldsArr = array();$tempArr = array();
		if($fields!='*'){
			$fieldsArr = explode(',',$fields);//print_r($fieldsArr);
			foreach($fieldsArr as $val){ if(in_array($val,array('id','name','parentId','posttime','title','content'))){ $tempArr[]=$val; } }
			$fields=implode(',',$tempArr);
		}
		$sql = "select $fields from `qk_article` where id='$id'";
		$articleInfo = $this->db->getRow($sql);
		if($articleInfo){
			$articleInfo=$this->getInfoExt($articleInfo,$fields);
			return $articleInfo;
		}
		return false;
	}
	function getInfoExt($articleInfo,$fields=""){
		$fieldsArr = array();$tempArr = array();
		if($fields!='' && $fields!="*"){
			$fieldsArr = explode(',',$fields);
			foreach($fieldsArr as $val){ if(in_array($val,array('id','name','parentId','posttime','title','catName','content'))){ $tempArr[]=$val; } }
			$fields=implode(',',$tempArr);
		}
		if($fields=='*' || in_array('catName',$fieldsArr)){
			if($articleInfo['catId'])$articleInfo['catName'] = $this->db->getOne("select name from qk_article_cat where id='".$articleInfo['catId']."'");
		}
		if($fields=='*' || in_array('thumb',$fieldsArr)){
			load_class("attachment");$am = new AttachmentModel();
			$articleInfo['thumbnail']['url'] = $am->getUrl($articleInfo['thumbId']);
		}
		if($fields=='*' || in_array('userInfo',$fieldsArr)){load_class("user");$um = new UserModel();$articleInfo['userInfo'] = $um->getInfo($articleInfo['userId']);}
		if($fields=='*' || in_array('catInfo',$fieldsArr))$articleInfo['catInfo'] = $this->getCatInfo($articleInfo['catId']);
		if($fields=='*' || in_array('nearby',$fieldsArr)){
			$articleInfo['prevId'] = $this->db->getOne("select id from qk_article where id<".$articleInfo['id']." order by id desc limit 1");
			$articleInfo['nextId'] = $this->db->getOne("select id from qk_article where id>".$articleInfo['id']." order by id asc limit 1");
		}
		$articleInfo['url']  = $articleInfo['externalLink'];
		if(!$articleInfo['url']){
			$articleInfo['url'] = $GLOBALS['baseUrl']."article/".$articleInfo['id'].'.html';
			$catInfo = $this->getCatInfo($articleInfo['catId']);
			if($catInfo['articleUrl']){$articleInfo['url']  = str_replace("{articleId}",$articleInfo['id'],$catInfo['articleUrl']);}
		}
		if($articleInfo['seoUrl']){$articleInfo['url'] = $articleInfo['seoUrl'];}
		$articleInfo['title'] = htmlspecialchars($articleInfo['title']);
		if(!$articleInfo['shortTitle']){$articleInfo['shortTitle']=$articleInfo['title'];}
		if(!trim($articleInfo['description'])){
			$articleInfo['description'] = substr(strip_tags($articleInfo['content']),0,60);
			$articleInfo['description'] = preg_replace("/\r\n/","",$articleInfo['description']);
		}
		return $articleInfo;
	}
	function del($param){
		$id = $param;
		if(is_array($param)){$id=$param['id'];}
		if($id && settype($id,"integer")){
			$sql = "delete from qk_article where id='".$id."'";
			if($this->db->query($sql)){
				$url = $GLOBALS['baseUrl']."article/view/id/".$id;$this->db->query("delete from qk_seo_url where url='$url'");
				return true;
			}
		}
		return false;
	}

	function getCats($catId=0){
			global $db;
			$wheres='';if(defined('SITE_ID') && !$GLOBALS['siteConf']['share']){$wheres .= " and (siteId='".SITE_ID."' or siteId=0)";}
			$tmp = array();
			$catInfo = $db->getRow("select * from qk_article_cat where id='".$catId."' $wheres order by sortId asc");
			if(!$catInfo['name'] && $catId!=0){return;}
			if($catId!==0){
					$grade=$this->getCatGrade($catId);
					$catInfo['grade'] = $grade;
				$tmp[] = $catInfo;// array("id"=>$catId,"name"=>$catInfo['name'],"parentId"=>$catInfo['parentId'],"grade"=>$grade,"sortId"=>$catInfo['sortId'],"id"=>$catInfo['id'],"posttime"=>$catInfo['posttime']);
			}
			$sql = "select * from qk_article_cat where parentId=".$catId." and iStatus=1 $wheres order by sortId asc,id asc";
			$res = $db->getAll($sql);
			if($res){
				foreach($res as $item){
					$tmp = array_merge($tmp,$this->getCats($item['id']));
				}
			}
			return $tmp;
	}

	function getCatGrade($catId){
		$grade = 0;
		$cats = $catId;
		$sql = "select parentId from qk_article_cat where id='".$catId."'";
		$res = $this->db->getRow($sql);
			if($res && $res['parentId']>0){
				$grade++;
				$grade += $this->getCatGrade($res['parentId']);
			}
		return $grade;
	}

	function delCat($id){
		if($id && settype($id,"integer")){
			$sql = "delete from qk_article_cat where id='$id'";
			if($this->db->query($sql)){
				$url = $GLOBALS['baseUrl']."article/list/catId/".$id;$this->db->query("delete from qk_seo_url where url='$url'");
				return true;
			}
		}
		return false;
	}

	function queryCat($param){
		if($param['name']){
			$act = $param['act'];
			$id = $param['id'];
			$name = $param['name'];
			$sortId = $param['sortId'];
			$parentId = $param['parentId'];
			$template = $param['template'];
			$templateView = $param['templateView'];
			$seoUrl = trim($param['seoUrl']);
			$externalLink = $param['externalLink'];
			$articleUrl = $param['articleUrl'];
			$title = $param['title'];
			$keywords = $param['keywords'];
			$description = $param['description'];
			$content = $param['content'];
			$thumbIds = $param['thumbIds'];
			if(!$parentId){$parentId=0;}
			if(!$sortId){$sortId=0;}
			if($act=="add"){
				$sql = "insert into qk_article_cat set ";
				$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
			}else if($act=='edit' && $id && is_numeric($id)){
				$sql = "select * from qk_article_cat where id='$id'";$catInfo=$this->db->getRow($sql);if(!$catInfo){$this->msg='分类'.$name.'不存在';return false;}
				$sql = "update qk_article_cat set ";
				$sqlEnd = " where id='$id'";
			}else{
				$this->msg='参数错误';return false;
			}
			if($thumbIds && is_array($thumbIds) && count($thumbIds)>0){
				$tmp=array();foreach($thumbIds as $val){if($val && $val>0)$tmp[]=$val;}$thumbIds=$tmp;
				$thumbIds=implode(',',$thumbIds);
			}else{
				$thumbIds='';
			}
			$sql .= "name='$name',parentId='$parentId',sortId='$sortid',template='$template',templateView='$templateView',externalLink='$externalLink',articleUrl='$articleUrl'";
			$sql .= ",title='$title',keywords='$keywords',description='$description',content='$content'";
			$sql .= ",thumbIds='$thumbIds'";
			if(defined('SITE_ID')){$sql .= " ,siteId='".SITE_ID."'";}
			$sql .= $sqlEnd;
			if($this->db->query($sql)){$this->msg='修改分类成功';
				if($act=="add"){$this->msg='添加分类成功';$id = $this->db->insert_id();}$url = $GLOBALS['baseUrl']."article/list/catId/".$id;
				if($seoUrl){load_class('seo');$sm=new SeoModel();if(!$sm->seoUrl($url,$seoUrl,$act)){$this->msg.= ', '.$sm->msg;}else{
					$this->db->query("update qk_article_cat set seoUrl='$seoUrl' where id='$id'");
				}}else{$this->db->query("update `qk_article_cat` set seoUrl='' where id='$id'");$this->db->query("delete from `qk_seo_url` where `seoUrl`='".$catInfo['seoUrl']."' and url='".$url."'");}
				return true;
			}
		}
		return false;
	
	}

	function addCat($param){
		$param['act'] = 'add';
		return $this->queryCat($param);
	}
	function editCat($param){
		$param['act'] = 'edit';
		return $this->queryCat($param);
	}

	function ajaxColEdit($param){
		$id = $param['id'];
		$col = $param['col'];
		$val = $param['val'];
		if($id && settype($id,"integer") && $col && $val!==''){
			$sql = "update qk_article set `$col`='$val' where id='$id'";
			if($this->db->query($sql)) return true;
		}
		return false;
	}

	function ajaxEditCat($param){
		$id = $param['id'];
		$col = $param['col'];
		$val = $param['val'];
		if($id && settype($id,"integer") && $col){
			$sql = "update qk_article_cat set `$col`='$val' where id='$id'";
			if($this->db->query($sql)){
				$this->msg='修改成功';
				return true;
			}
		}
		$this->msg='修改失败';
		return false;
	}

	function getCatName($id){
		return  $this->db->getOne("select name from qk_article_cat where id='$id'");
	}

	function getArticleCategory($catId=0){
		global $db;
		$tmp = array();
		$wheres='';if(defined('SITE_ID') && !$GLOBALS['siteConf']['share']){$wheres .= " and (siteId='".SITE_ID."' or siteId=0)";}
		$catInfo = $db->getRow("select name,parentId,sortId,id,posttime from qk_article_cat where id='".$catId."' $wheres order by sortId asc");
		if(!$catInfo['name'] && $catId!=0){return;}
		if($catId!==0){
				$grade=$this->getArticleCatGrade($catId);
		$tmp[] = array("id"=>$catId,"name"=>$catInfo['name'],"parentId"=>$catInfo['parentId'],"grade"=>$grade,"sortId"=>$catInfo['sortId'],"id"=>$catInfo['id'],"posttime"=>$catInfo['posttime']);
		}
		$sql = "select * from qk_article_cat where parentId=".$catId." and iStatus=1 $wheres order by sortId asc";
		$res = $db->getAll($sql);
		if($res){
			foreach($res as $item){
				$tmp = array_merge($tmp,$this->getArticleCategory($item['id']));
			}
		}
		return $tmp;
	}

	function getArticleCatGrade($catId){
		global $db;
		$grade = 0;
		$cats = $catId;
		$sql = "select parentId from qk_article_cat where id='".$catId."'";
		$res = $db->getRow($sql);
			if($res && $res['parentId']>0){
				$grade++;
				$grade += $this->getCatGrade($res['parentId']);
			}
		return $grade;
	}
	
	function getCatInfo($catId){
		if($catId && settype($catId,"integer")){
			$sql = "select * from qk_article_cat where id='$catId'";
			$info = $this->db->getRow($sql);if(!$info){return false;}
			$pInfo = $this->db->getRow("select * from qk_article_cat where id='".$info['parentId']."'");
			if(!$info['url']){
				$info['url'] = $info['seoUrl'];
			}
			if(!$info['url']){
				$info['url']=$GLOBALS['baseUrl'].'article/cat-'.$info['id'].'.html';
			}
			if(!$info['template']){$info['template']=$pInfo['template'];}
			if(!$info['templateView']){$info['templateView']=$pInfo['templateView'];}
			if(!$info['articleUrl']){$info['articleUrl']=$pInfo['articleUrl'];}
			
			if(!$info['title']){$info['title']=$info['name'];}
			$info['thumbIdsArr']=array();
			if($info['thumbIds']){ $info['thumbIdsArr']=explode(',',$info['thumbIds']);}
			$info['thumb']=array();
			if(count($info['thumbIdsArr'])>0){
				load_class('attachment');$at=new AttachmentModel();
				$i=0;
				foreach($info['thumbIdsArr'] as $thumbId){
					$info['thumb'][$i]['url'] = $at->getUrl($thumbId);
					$i++;
				}
			}

			return $info;
		}
		return false;
	}
	function add($params){ $params['act'] = 'add'; return $this->query($params); }
	function edit($params){ $params['act'] = 'edit'; return $this->query($params);	 }
	function query($params){
			global $baseUrl;
			$act = $params["act"];
			$id = $params["id"];
			$title = $params["title"];
			$shortTitle = $params['shortTitle'];
			$catId = $params["catId"];
			$sortId = $params["sortId"];
			$externalLink = $params["externalLink"];
			$from = $params["from"];
			$fromUrl = $params["fromUrl"];
			$iStatus = $params["iStatus"];
			$thumbId = $params["thumbId"];
			$content = $params["content"];
			$userId = $params["userId"];
			$seoUrl = $params["seoUrl"];
			$keywords = $params["keywords"];
			$description = $params["description"];
			$template = $params["template"];
			$siteId = $params["siteId"];
			if($iStatus!=1){$iStatus=0;}
			if(!$siteId || !is_numeric($siteId)){$siteId=0;}
			if($sortId=="" || settype($sortId,"integer")===false){$sortId=50;}
			if($act!='add' && $act!='edit'){$this->msg='动作不存在';return false;}
			if($title==''){$this->msg='文章标题不能为空';return false;}
			if($catId==''){$this->msg='请选择文章分类';return false;}
			if($title  && is_numeric($catId)){
				$_SESSION['catId'] = $catId;
				if($act=='add'){
					$sql = "insert into qk_article set ";$sqlEnd = ",posttime=UNIX_TIMESTAMP()";
				}else if($act=='edit' && $id && is_numeric($id)){
					$sql = "select * from qk_article where id='$id'";$articleInfo=$this->db->getRow($sql);if(!$articleInfo){$this->msg='文章不存在';return false;}
					$sql = "update qk_article set ";$sqlEnd = " where id='$id'";				
				}else{
					$this->msg='参数错误';return false;
				}
				$sql .= " title='$title',catId='$catId',sortId='$sortId',externalLink='$externalLink',`from`='$from',fromUrl='$fromUrl',iStatus='$iStatus',thumbId='$thumbId'";
				$sql .= ",content='$content',userId='$userId',keywords='$keywords',description='$description',template='$template',siteId='$siteId',shortTitle='$shortTitle'";
				if(!$siteId && defined('SITE_ID')){$sql .= " ,siteId='".SITE_ID."'";}
				$sql .= $sqlEnd;
				if($this->db->query($sql)){					
					$this->msg='修改文章成功';
					if($act=="add"){$this->msg='添加文章成功';$id = $this->db->insert_id();}$url = $GLOBALS['baseUrl']."article/view/id/".$id;
					if($seoUrl){load_class('seo');$sm=new SeoModel();if(!$sm->seoUrl($url,$seoUrl,$act)){$this->msg.= ', '.$sm->msg;}else{
						$this->db->query("update qk_article set seoUrl='$seoUrl' where id='$id'");
					}}
					return true;
				}else{
					if($act=='add'){ $act='添加'; }else if($act=='edit'){ $act='修改'; }
					$this->msg = '文章'.$act.'失败';return false;
				}
			}
	}

}
?>