<?php
/**
 * @package iCMS
 * @copyright 2007-2010, iDreamSoft
 * @license http://www.idreamsoft.cn iDreamSoft
 * @author coolmoo <idreamsoft@qq.com>
 */
class iCMS extends Template {
	var $config='';
	var $db='';
	var $id='';
	var $title='';
	var $cacheID='';
	var $compileID='';
	var $firstcount='0';
	var $pagenav='';
	var $pagesize='';
	var $date=array();
	var $mode='';
	var $dir='';
	var $url='';
	var $action='';
	var $actionSQL='';
	var $result='';
	var $get=array();
	var $iCache;
	//PHP5 Class
	Function __construct(){
		global $config,$db,$_iGLOBAL;
		$this->config			= $config;
		$this->db				= $db;
		$this->version			= Version;
		$this->template_dir		= iPATH.'templates';
		$this->compile_dir		= iPATH.'cache/templates';
		$this->cache_dir		= iPATH.'cache/templates';
//		$this->plugins_dir		= array("plugins",iPATH.'include/modifier');
		$this->cache			= false;
		$this->debugging		= false;
		$this->left_delimiter	= '<!--{';
		$this->right_delimiter	= '}-->';
		$this->assign("poweredby", '<a href="http://www.idreamsoft.cn" target="_blank">iCMS</a> '.iCMS_VER);
		$this->assign("version", iCMS_VER);
		$this->assign('site',array("title"=>$this->config['name'],"seotitle"=>$this->config['seotitle'],
					"keywords"	=>$this->config['keywords'],
					"description"=>$this->config['description'],
					"domain"	=>$this->config['domain'],
					"url"		=>$this->config['ishtm']?$this->config['htmlURL']:$this->config['url'],
					"dir"		=>substr($this->config['dir'],0,-1),
					"publicURL"	=>$this->config['publicURL'],
					"index"		=>$this->config['dir'],
					"tpl"		=>$this->config['template'],
					"tplpath"	=>$this->config['dir']."templates/".$this->config['template'],
					"tplurl"	=>$this->config['url']."/templates/".$this->config['template'],
					"email"		=>$this->config['masteremail'],
					"icp"		=>$this->config['icp']));
		$this->assign("cookie", $_iGLOBAL['cookie']);
		$this->dir				= $this->config['dir'];
		$this->register_modifier("date", 	"get_date");
		$this->register_modifier("cut", 	"csubstr");
		$this->register_modifier("htmlcut", "htmlSubString");
		$this->register_modifier("count", 	"cstrlen");
		$this->register_modifier("html2txt", "HtmToText");
		$this->register_modifier("pinyin", 	"GetPinyin");
		$this->register_modifier("unicode", "getUNICODE");
		$this->register_modifier("small","gethumb");
	}
	//PHP4 Class
	Function iCMS(){
		$this->__construct();
	}
	//Index
	Function Index($indexTPL='',$indexname=''){
		empty($indexname)&& $indexname=$this->config['indexname'];
		empty($indexTPL)&& $indexTPL=$this->config['indexTPL'];
		$url=$indexname.$this->config['htmlext'];
		$this->jumptohtml(iPATH.$url,FS::path($this->dir.$url));
		return $this->iPrint($indexTPL);
	}
	//Page
	Function page($p='',$id=0){
		$whereSQL=(empty($p)&&$id)?"`id`='{$id}'":"`dir`='{$p}'";
		$cp=$this->db->getRow("SELECT * FROM `#iCMS@__catalog` WHERE $whereSQL");
		if(empty($cp)){
			$this->error('error:page');
		}else{
			$this->purl=$this->iurl('page',(array)$cp);
			$this->jumptohtml($this->purl->path,$this->purl->href);
			if($pd=$this->db->getRow("SELECT * FROM `#iCMS@__page` WHERE cid='$cp->id'",ARRAY_A)){
				$this->assign(array('title'=>$pd['title'],
					'keywords'=>$pd['keyword'],
					'description'=>$pd['description'],
					'body'=>unhtmlspecialchars($pd['body']),
					'creater'=>$pd['creater'],
					'updater'=>$pd['updater'],
					'createtime'=>$pd['createtime'],
					'updatetime'=>$pd['updatetime']
				));
				$this->get['title']=$pd['title'];
			}
			$this->iList($cp->id,false);
			$pd['url']=$this->purl->href;
			$this->assign('page',$pd);
			return $this->iPrint($cp->tpl_index,'page');
		}
	}
	//List
	Function iList($id,$show=true,$act=true){
//		$sql= $this->linkmodeSQL('id','dir',$argv);
//		$rs	= $this->db->getRow("SELECT * FROM `#iCMS@__catalog` WHERE `id`='$id'",ARRAY_A);
		$_cache	= $this->cache(array('catalog.cache','catalog.rootid'),'include/syscache',0,true);
		$rs		= $_cache['catalog.cache'][$id];
		empty($rs) && $this->error('error:page');
		if($show && $rs['url']){return _Header($rs['url']);}
		$iurl	= $this->iurl('list',$rs);
		$rs['url']	= $iurl->href;
		$rs['link']	= "<a href='{$rs['url']}'>{$rs['name']}</a>";
		$rs['nav']	= $this->shownav($rs['id']);
		$rs['subid']= $_cache['catalog.rootid'][$id];
		$rs['subids']= @implode(',',$_cache['catalog.rootid'][$id]);
		$this->assign('sort',$rs);
		if($show){
			$act && $this->jumptohtml($iurl->path,$iurl->href);
			switch ($rs['attr']){
			   case 'channel':	return $this->iPrint($rs['tpl_index'],'channel');	break;
			   case 'list':		return $this->iPrint($rs['tpl_list'],'list');	break;
//			   case 'page':		return $this->iPrint($rs['tpl_index'],'page');	break;
			}
		}
	}
	//Show
	Function Show($id,$page=1,$tpl=true){
		$_cache	= $this->cache('catalog.cache','include/syscache',0,true);
//		$sql=$this->linkmodeSQL('a.id','a.clink',$argv);
		//$this->mode=="CreateHtml" && $sql.=" and a.url=''";
		$rs=$this->db->getRow("SELECT a.*,d.tpl,d.body,d.subtitle FROM #iCMS@__article as a LEFT JOIN #iCMS@__articledata AS d ON a.id = d.aid WHERE a.id='".(int)$id."' AND a.status ='1'");
		empty($rs) && $this->error('error:page');
		$C= $_cache[$rs->cid];
		if($C['ishidden'])	return false;
		if($rs->url){if($this->mode=="CreateHtml"){ return;}else{_header($rs->url);}}
		$rs->ext	= empty($C['htmlext'])?$this->config['htmlext']:$C['htmlext'];
		$_iurlArray	= array('id'=>$rs->id,'link'=>$rs->clink,'url'=>$rs->url,'cid'=>$rs->cid,'dir'=>$C['dir'],'pubdate'=>$rs->pubdate,'domain'=>$C['domain'],'ext'=>$rs->ext);
		$rs->iurl	= $this->iurl('show',$_iurlArray,$page);
		$rs->url	= $rs->iurl->href;
		$tpl && $this->jumptohtml($rs->iurl->path,$rs->iurl->href);
		$this->get['id']	= $rs->id;
		$this->get['title']	= $rs->title;
		$this->iList($rs->cid,false);
		if($this->config['ishtm']){
			$rs->hits	= "<script src=\"".$this->config['publicURL']."/action.php?do=hits&id={$rs->id}&action=show\" language=\"javascript\"></script>";
			$rs->digg	= "<script src=\"".$this->config['publicURL']."/action.php?do=digg&id={$rs->id}&action=show\" language=\"javascript\"></script>";
			$rs->comments="<script src=\"".$this->config['publicURL']."/action.php?do=comment&id={$rs->id}\" language=\"javascript\"></script>";
		}
		$picArray	= array();
		preg_match_all("/<img.*?src\s*=[\"|'|\s]*(http:\/\/.*?\.(gif|jpg|jpeg|bmp|png)).*?>/is",$rs->body,$picArray);
		$pA = array_unique($picArray[1]);
		foreach($pA as $key =>$pVal){
			$ipVal = uploadpath($pVal,'http2iPATH');
			file_exists($ipVal) && $rs->photo[]=trim($pVal);
		}
		$body	=explode('<div style="page-break-after: always"><span style="display: none">&nbsp;</span></div>',$rs->body);
		$rs->pagetotal=count($body);
		$nBody	=$body[intval($page-1)];
		$rs->body=$this->keywords($nBody);
		$rs->pagecurrent=$page;
		if($rs->pagetotal>1){
			$rs->pagebreak='<a href="'.$this->iurl('show',$_iurlArray,(($page-1>1)?$page-1:1))->href.'" class="pagebreak" target="_self">'.$this->language('page:prev').'</a> ';
			for($i=1;$i<=$rs->pagetotal;$i++){
				$cls=($i==$page)?"pagebreaksel":"pagebreak";
				$rs->pagebreak.='<a href="'.$this->iurl('show',$_iurlArray,$i)->href.'" class="'.$cls.'" target="_self">'.$i.'</a>';
			}
			$rs->pagebreak.='<a href="'.$this->iurl('show',$_iurlArray,(($rs->pagetotal-$page>0)?$page+1:$page))->href.'" class="pagebreak" target="_self">'.$this->language('page:next').'</a>';
		}
		$rs->page=array('total'=>$rs->pagetotal,'current'=>$rs->pagecurrent,'break'=>$rs->pagebreak);
	    if($rs->tags){
	    	$tagarray=explode(',',$rs->tags);
    		foreach($tagarray AS $tk=>$tag){
    			if($t = $this->getTag($tag)){
    				$rs->tag[$tk]['name']=$tag;
    				$rs->tag[$tk]['url']=$this->iurl('tag',$t)->href;
    				$rs->taglink.='<a href="'.$rs->tag[$tk]['url'].'" class="tag" target="_self">'.$rs->tag[$tk]['name'].'</a> ';
    			}
    		}
	    }
	    $rs->rel=$rs->related;
		$rs->prev=$this->language('show:first');
		if($prers=$this->db->getRow("SELECT * FROM `#iCMS@__article` WHERE `id` < '{$rs->id}' AND `cid`='{$rs->cid}' AND `status`='1' order by id DESC Limit 1")){
			$rs->prev='<a href="'.$this->iurl('show',array('id'=>$prers->id,'cid'=>$prers->cid,'link'=>$prers->clink,'url'=>$prers->url,'dir'=>$C['dir'],'domain'=>$C['domain'],'pubdate'=>$prers->pubdate))->href.'" class="prev" target="_self">'.$prers->title.'</a>';
			unset($prers);
		}
		$rs->next=$this->language('show:last');
		if($nextrs=$this->db->getRow("SELECT * FROM `#iCMS@__article` WHERE `id` > '{$rs->id}'  and `cid`='{$rs->cid}' AND `status`='1' order by id ASC Limit 1")){
			$rs->next='<a href="'.$this->iurl('show',array('id'=>$nextrs->id,'cid'=>$nextrs->cid,'link'=>$nextrs->clink,'url'=>$nextrs->url,'dir'=>$C['dir'],'domain'=>$C['domain'],'pubdate'=>$nextrs->pubdate))->href.'" class="next" target="_self">'.$nextrs->title.'</a>';
			unset($nextrs);
		}
		$this->mode!='CreateHtml'&&$this->db->query("UPDATE `#iCMS@__article` SET hits=hits+1 WHERE `id` ='{$rs->id}' LIMIT 1");
		$rs->link="<a href='{$rs->url}'>{$rs->title}</a>";		
		$this->result	= $rs;

		$this->assign(array(
			'id'		=>$rs->id,//文章ID
			'pic'		=>$rs->pic,//缩略图
			'url'		=>$rs->url,//URL
			'link'		=>$rs->link,//link
			'title'		=>$rs->title,//标题
			'keywords'	=>$rs->keywords,//关键字
			'description'=>$rs->description,//简介
			'source'	=>$rs->source,//出处
			'author'	=>$rs->author,//作　者
			'userid'	=>$rs->userid,//发布者ID
			'postype'	=>$rs->postype,//发布者类型 0用户
			'pubdate'	=>$rs->pubdate,//日期
			'subtitle'	=>$rs->subtitle,//标题
			'body'		=>$rs->body,//内容
			'pagetotal'=>$rs->pagetotal,//分页
			'pagecurrent'=>$rs->pagecurrent,//当前页码
			'pagebreak'=>$rs->pagebreak,//分页
			'hits'		=>$rs->hits,//点击数
			'digg'		=>$rs->digg,//点击数
			'comments'	=>$rs->comments,//回复数
	    	'tag'		=>$rs->tag,//标签 3.1
	    	'taglink'	=>$rs->taglink,//标签 3.1.2
	    	'rel'		=>$rs->related,//标签 3.1.2
			'prev'		=>$rs->prev,//上下一篇
			'next'		=>$rs->next//下一篇
		));
		$this->assign('show',(array)$rs);//3.1 所有内容

		if($tpl){
			$tpl=empty($rs->tpl)?$C['tpl_contents']:$rs->tpl;
			return $this->iPrint($tpl,'show');
		}
	}

	//content
	function content($mId,$id,$tpl=true){
		$_cache		= $this->cache('catalog.cache','include/syscache',0,true);
		//$sql		= $this->linkmodeSQL('id','clink',$argv);
		$__MODEL__	= $this->cache('model.id','include/syscache',0,true);
		$model		= $__MODEL__[$mId];
		$__TABLE__	= $model['table'].'_content';		
		$rs=$this->db->getRow("SELECT * FROM `#iCMS@__$__TABLE__` WHERE id='".(int)$id."' AND `status` ='1'");
		empty($rs) && $this->error('error:page');
		$C= $_cache[$rs->cid];
		if($C['ishidden'])	return false;
		$_iurlArray	= array('mId'=>$mId,'mName'=>$model['table'],'id'=>$rs->id,'link'=>$rs->clink,'url'=>$rs->url,'pubdate'=>$rs->pubdate,'cid'=>$rs->cid,'dir'=>$C['dir'],'domain'=>$C['domain'],'htmlext'=>$C['htmlext']);
		$rs->iurl	= $this->iurl('content',$_iurlArray,$page);
		$rs->url	= $rs->iurl->href;
		$tpl && $this->jumptohtml($rs->iurl->path,$rs->url);
		$rs->mid		= $mId;
		$this->get['id']	= $rs->id;
		$this->get['title']	= $rs->title;
//		if($this->config['linkmode']=='id'){
			$this->iList($rs->cid,false);
//		}elseif($this->config['linkmode']=='title'){
//			$this->iList($rs->catalogdir,false);
//		}
		if($this->config['ishtm']){
			$rs->hits	= "<script src=\"".$this->config['publicURL']."/action.php?do=hits&mid={$mId}&id={$rs->id}&action=show\" language=\"javascript\"></script>";
			$rs->digg	= "<script src=\"".$this->config['publicURL']."/action.php?do=digg&mid={$mId}&id={$rs->id}&action=show\" language=\"javascript\"></script>";
			$rs->comments="<script src=\"".$this->config['publicURL']."/action.php?do=comment&mid={$mId}&id={$rs->id}\" language=\"javascript\"></script>";
		}
	    if($rs->tags){
	    	$tagarray=explode(',',$rs->tags);
    		foreach($tagarray AS $tk=>$tag){
    			if($t = $this->getTag($tag)){
    				$rs->tag[$tk]['name']=$tag;
    				$rs->tag[$tk]['url']=$this->iurl('tag',$t)->href;
    				$rs->taglink.='<a href="'.$rs->tag[$tk]['url'].'" class="tag" target="_self">'.$rs->tag[$tk]['name'].'</a> ';
    			}
    		}
	    }
		if($fArray	= explode(',',$model['field'])){
			$SField	= getSystemField();
			$diff	= array_diff_values($fArray,$SField);
		    if($diff['+'])foreach($rs AS $field=>$val){
		    	if(in_array($field,$diff['+'])){
		    		$FV	= getFieldValue($mId,$field,$val);
		    		$FV!==Null && $rs->$field	= $FV;
		    	}
		    }
		}

		$prers=$this->db->getRow("SELECT * FROM `#iCMS@__$__TABLE__` WHERE `id` < '{$rs->id}' AND `cid`='{$rs->cid}' AND `status`='1' order by id DESC Limit 1");
		$rs->prev=$prers?'<a href="'.$this->iurl('content',array('mId'=>$mId,'id'=>$prers->id,'cid'=>$prers->cid,'link'=>$prers->clink,'dir'=>$C['dir'],'domain'=>$C['domain'],'pubdate'=>$prers->pubdate))->href.'" class="prev" target="_self">'.$prers->title.'</a>':$this->language('content:first');
		$nextrs=$this->db->getRow("SELECT * FROM `#iCMS@__$__TABLE__` WHERE `id` > '{$rs->id}'  and `cid`='{$rs->cid}' AND `status`='1' order by id ASC Limit 1");
		$rs->next=$nextrs?'<a href="'.$this->iurl('content',array('mId'=>$mId,'id'=>$nextrs->id,'cid'=>$nextrs->cid,'link'=>$nextrs->clink,'dir'=>$C['dir'],'domain'=>$C['domain'],'pubdate'=>$nextrs->pubdate))->href.'" class="next" target="_self">'.$nextrs->title.'</a>':$this->language('content:last');
		$this->mode!='CreateHtml'&&$this->db->query("UPDATE `#iCMS@__$__TABLE__` SET hits=hits+1 WHERE `id` ='{$rs->id}' LIMIT 1");
		$rs->link="<a href='{$rs->selfurl}'>{$rs->title}</a>";
		$this->result	= $rs;

		$this->assign(array(
			'id'		=>$rs->id,//内容ID
			'mid'		=>$rs->mid,//模型ID
			'selfurl'	=>$rs->selfurl,//URL
			'link'		=>$rs->link,//URL
			'title'		=>$rs->title,//标题
			'userid'	=>$rs->userid,//发布者ID
			'postype'	=>$rs->postype,//发布者类型 0用户
			'pubdate'	=>$rs->pubdate,//日期
			'hits'		=>$rs->hits,//点击数
			'digg'		=>$rs->digg,//点击数
			'comments'	=>$rs->comments,//回复数
	    	'tag'		=>$rs->tag,//标签 3.1
	    	'taglink'	=>$rs->taglink,//标签 3.1.2
			'prev'		=>$rs->prev,//上下一篇
			'next'		=>$rs->next//下一篇
		));
		$this->assign('content',	(array)$rs);//3.1 所有内容

		if($tpl){
			$tpl=empty($rs->tpl)?$C['tpl_contents']:$rs->tpl;
			return $this->iPrint($tpl,'content');
		}
	}
	//tag
	function getTagKey($name){
		if(strpos($name,',')===false){
			$key = substr(md5($name),8,16);
			$tp	 = 'tag/'.substr($key,0,3).'/'.substr(md5($name),8,16);
		}else{
			$TN = explode(',',$name);
    		foreach($TN AS $n){
				$key = substr(md5($n),8,16);
				$tp[]= 'tag/'.substr($key,0,3).'/'.substr(md5($n),8,16);
    		}
		}
    	return $tp;
	}
	function getTag($name){
		$c = $this->cache($this->getTagKey($name),$this->config['cachedir'],0,true);
		return $c['status']?$c:false;
	}
	function tag($name){
		empty($name) && alert($this->language('tag:empty'));
		$c = $this->getTag($name);
		$this->assign("tagName",$name);
		return $this->iPrint(empty($c['tpl'])?"iTPL":$c['tpl'],"tag");
	}
	//search
	function search($type='title',$keyword='',$sortid=""){
		$keyword==''&& alert($this->language('search:keywordempty'));
		empty($type) && alert($this->language('search:typempty'));
		$ikeyword=$keyword;
		$keyword=str_replace(array('%','_'),array('\%','\_'),$keyword);
		switch ($type) {
		   case 'title':
			   $this->actionSQL=" AND `title` like '%{$keyword}%' ";
		   break;
		   case 'content':
			   $this->actionSQL=" And CONCAT(title,keywords,description) like '%{$keyword}%' ";
		   break;
		   case 'author':
			   $this->actionSQL=" AND `author` like '%{$keyword}%' ";
		   break;
		   default:$field='title';
		}
		if($sortid){
			$this->actionSQL.=" AND `cid`='{$sortid}'";
			$this->assign("sortid",$sortid);
		}
		if($id=$this->db->getValue("SELECT id FROM `#iCMS@__search` where `search`='{$keyword}'")){
			$this->db->query("UPDATE `#iCMS@__search` SET `times`=times+1 WHERE `id`='$id'");
		}else{
			$this->db->query("INSERT INTO `#iCMS@__search` (`search`,`times`,`addtime`) VALUES ('{$keyword}','0','".time()."')");
		}
		$this->assign("keyword",$ikeyword);
		$this->iPrint("iTPL","search");
	}
	function comment($aid=0,$mId=0,$sortId=0){
		if(empty($aid)){
			$this->iList($sortId,false);
			$this->iPrint("iTPL","comment.sort");
		}else{
			//$catalog=$this->cache('catalog.cache','include/syscache',0,true);
			$total=$this->db->getValue("SELECT count(*) FROM `#iCMS@__comment` WHERE `mid`='$mId' and `sortId`='$sortId' and `isexamine`='1' AND aid='{$aid}'");
			$this->assign("total",$total);
			if(empty($mId)){
				$this->Show($aid,1,false);
				$this->iPrint("iTPL","comment.article");
			}else{
				$this->content($mId,$aid,false);
				$this->iPrint("iTPL","comment.content");
			}
		}
	}
//-------------------------------------------------------------------------------------------------
	function cache($cacheName,$cacheDir=Null,$cacheLevel=0,$iscachegzip=false){
		$this->cacheDir=$cacheDir;
		if($this->config['iscache']||$this->cacheDir){
			if($this->config['cacheEngine']=='memcached'){
				if(!isset($this->iCache)){
					$_servers = explode("\n",str_replace(array("\r"," "),"",$this->config['cacheServers']));
					$this->iCache = new memcached(array(
						'servers' =>$_servers,
						'compress_threshold' => 10240,
						'persistant' => true,
						//'debug' => true,
						'compress'	=> $iscachegzip?$iscachegzip:$this->config['iscachegzip']
					));
					unset($_servers);
				}
			}else{
				if(isset($this->iCache)) unset($this->iCache);//文件缓存目录结构不一致 清除缓存
				$this->iCache = new FileCache(array(
					'dirs'		=> iPATH.(empty($this->cacheDir)?$this->config['cachedir']:$this->cacheDir),
					'level'		=> $cacheLevel?$cacheLevel:$this->config['cachelevel'],
					'compress'	=> $iscachegzip?$iscachegzip:$this->config['iscachegzip']
				));
			}
		}
		if($cacheName){
			$_cName=implode('',(array)$cacheName);
			if(!isset($GLOBALS['_iCache'][$_cName])){
				$GLOBALS['_iCache'][$_cName]=is_array($cacheName)?
					$this->iCache->get_multi($cacheName):
						$this->iCache->get($cacheName);
			}
			return $GLOBALS['_iCache'][$_cName];
		}else{
			return $this;
		}
	}
	function addcache($cacheName,$rs,$cachetime="-1"){
		($this->config['iscache']||$this->cacheDir!="") && $this->iCache->add($cacheName,$rs,($cachetime!="-1"?$cachetime:$this->config['cachetime']));
	}
	//---plugins---
	Function value($key,$value){
		$this->assign($key,$value);
	}
	Function clear($key){
		$this->clear_assign($key);
	}
	Function output($tpl,$td='',$res=''){
//		$res=='' && $res='file:';
		$this->display($res.$td.'/'.$tpl.".htm",$this->cacheID,$this->compileID);
	}
	//------------------------------------
	Function tpl($tpl){
		if($this->mode=='CreateHtml'){
			return $this->fetch($tpl,$this->cacheID,$this->compileID);
		}else{
			$this->display($tpl,$this->cacheID,$this->compileID);
		}
	}
	Function iPrint($tpl,$p='index'){
		empty($tpl) && $this->error('error:notpl',$tpl);
		strpos($tpl,'{TPL}')!==false && $tpl = str_replace('{TPL}',$this->config['template'],$tpl);
		if(file_exists($this->template_dir."/".$tpl)){
			return $this->tpl($tpl);
		}elseif($this->config['template'] && file_exists($this->template_dir."/".$this->config['template']."/{$p}.htm")){
			return $this->tpl($this->config['template']."/{$p}.htm");
		}elseif($tpl=='iTPL'){
			return $this->tpl("system/{$p}.htm");
		}
	}
	function jumptohtml($fp,$url=''){
		$this->config['ishtm'] && $this->mode!='CreateHtml' && 
		file_exists($fp) && stristr($fp, '.php?') === FALSE && _Header($url);
	}
	function language($string){
		$langFile=$this->template_dir.'/'.$this->config['template'].'/language/'.$this->config['language'].'.php';
		if(!isset($GLOBALS['_iLang'])) $GLOBALS['_iLang']=include($langFile);
		if(strpos($string,':')!==false){
			list($s,$k)=explode(':',$string);			
			return isset($GLOBALS['_iLang'][$s][$k])?$GLOBALS['_iLang'][$s][$k]:$string;
		}else{
			return isset($GLOBALS['_iLang'][$string])?$GLOBALS['_iLang'][$string]:$string;
		}
	}
	Function error($string,$tpl=""){
		header('HTTP/1.1 404 Not Found');
		$this->assign('TPL_PATH',$this->config['dir']."templates/".$tpl);
		$this->assign('error',$this->language($string));
		$this->output('error','system');
		exit;
	}
	function linkmodeSQL($ifield,$tfield,$argv){
		if($this->config['linkmode']=='id'){
			$sql="{$ifield}='{$argv}'";
		}elseif($this->config['linkmode']=='title'){
			$sql="{$tfield}='{$argv}'";
		}
		return $sql;
	}
	function domain($cid="0",$p="",$Cdir=false,$dirType=null){
		$cache	= $this->cache('catalog.cache','include/syscache',0,true);
		$C		= $cache[$cid];
		$rootid = $C['rootid'];
		$htmdir = empty($dirType)?$this->config['listhtmdir']:$this->config['htmdir'];
		if($Cdir){
			$rootid && $dm.=$this->domain($rootid,$D,true);
			$dm.='/'.$C['dir'];
		}else{
			if($rootid && empty($C['domain'])){
				$_dir=empty($dirType)?'/'.$C['dir']:'';
				$dm.=$this->domain($rootid,$p,$Cdir,$dirType).$_dir;
			}else{
				$_dir=empty($dirType)?$C['dir']:'';
				if(empty($p)){
					$dm=$C['domain']?'http://'.$C['domain'].(empty($dirType)?'':'/'):$this->config['url'].'/'.$htmdir.$_dir;
				}else{
					$dm=$p.$htmdir.$_dir;
				}
			}
		}
		return $dm;
	}

	function irule($a,$b,$c,$p){
		switch($b){
			case 'PHP':
				switch($a){
					case 'channel':$e='channel.php?id='.$c['id'];break;
					case 'list':$e='list.php?id='.$c['id'];break;
					case 'show':$e='show.php?id='.$c['id'];break;
					case 'content':$e='content.php?id='.$c['id'].'&mid='.$a['mId'];break;
					case 'tag':$e=$this->config['publicURL'].'/tag.php?name='.irawurldecode($c['name']);break;
					case 'page':$e='page.php?name='.$c['dir'];break;
				}
			break;
			case 'CID':$e=$c['id'];break;
			case 'CDIR':$e=$c['dir'];break;
			case 'CPDIR':$e=substr($this->domain($c['id'],'',true), 1);break;
			case 'LINK':$e=$c['link'];break;
			case 'P':$e=$p;break;
			case 'MD5':
				$e=md5($c['id']);
				$a=='tag' && $e=md5($c['name']);
				$e=substr(md5($e),8,16);
			break;
			case 'TIME':$e=$c['pubdate'];break;
			case 'YY':$e=get_date($c['pubdate'],'y');break;
			case 'YYYY':$e=get_date($c['pubdate'],'Y');break;
			case 'M':$e=get_date($c['pubdate'],'n');break;
			case 'MM':$e=get_date($c['pubdate'],'m');break;
			case 'D':$e=get_date($c['pubdate'],'j');break;
			case 'DD':$e=get_date($c['pubdate'],'d');break;
			case 'AID':$e=$c['id'];break;
			case '0xID':$e=sprintf("%08s",abs(intval($c['id'])));break;
			case '0x3ID':$e=substr(sprintf("%08s",abs(intval($c['id']))), 0, 4);break;
			case '0x3,2ID':$e=substr(sprintf("%08s",abs(intval($c['id']))), 4, 2);break;
			case 'MID':$e=$c['mId'];break;
			case 'MNAME':$e=$c['mName'];break;
			case 'TID':$e=$c['id'];break;
			case 'SID':$e=$c['sortid'];break;
			case 'EXT':$e=empty($c['htmlext'])?$this->config['htmlext']:$c['htmlext'];break;
		}
		return $e;
	}
	function iurl($uri,$a=array(),$p=1){
		switch($uri){
			case in_array($uri,array('channel','list')):
				$rule=$this->config['cRule'];
			break;
			case 'show':$rule=$this->config['aRule'];break;
			case 'page':$rule=$this->config['pRule'];break;
			case 'tag': $rule=$this->config['tRule'];break;
		}
		!$this->config['ishtm'] && $rule='{PHP}';
		$i = (object) NULL;
		$url	= preg_replace ("/\{(.*?)\}/e",'$this->irule($uri,"\\1",$a,$p)',$rule);
		if(strstr($rule,'{PHP}')===false){
			$i->path	= FS::path(iPATH.$this->config['htmldir'].'/'.$url);
			$i->href	= FS::path($this->config['htmlURL'].'/'.$url);
			$i->hdir	= dirname($i->href);
			$i->file	= basename($i->path);
			if(empty($i->file)||substr($url,-1)=='/'){
				$i->name	= 'index';
				$i->ext		= empty($a['htmlext'])?$this->config['htmlext']:$a['htmlext'];
				$i->file	= $i->name.$i->ext;
				$i->path	= $i->path.'/'.$i->file;
				$i->hdir	= dirname($i->href.'/'.$i->file);
			}else{
				$i->name	= substr($i->file,0,strrpos($i->file,'.'));
				empty($i->name) && $i->name=$i->file;
				$i->ext		= strrchr($i->file, ".");
			}
			$i->dir		= dirname($i->path);
			if($uri=='show' && strstr($rule,'{P}')===false && $p>1){
				$fn	= $i->name.'_'.$p.$i->ext;
				$i->path = $i->dir.'/'.$fn;
				$i->href = $i->hdir.'/'.$fn;
			}
//			var_dump($i);
//			exit;
		}else{
			$i->href	= $url;
		}
		$uri=='index' && $i->http='javascript:void(0);';
		if($a['url']){
			if($uri=='show'){
				$i->http=$this->config['publicURL']."/link.php?id=".$a['id']."&url=".irawurldecode($a['url']);
			}elseif(in_array($uri,array('channel','list','page'))){
				$i->http=$a['url'];
			}
		}
		return $i;
	}
	function iPageUrl($o,$p,$pn=''){
		return stristr($o->href,'.php')===false?$o->hdir.'/'.$o->name.'_'.$p.'.'.$o->ext:$o->href.'&'.$pn.'='.$p;
	}
	//翻页函数
	function multi($array){
		include_once iPATH.'include/multi.class.php';
		$multi=new multi($array);
		if($multi->totalpage>1){
			$this->assign($array['pagenav'],$multi->show($pnstyle));
			$this->assign('pageA',array('total'=>$multi->totalpage,'current'=>$multi->nowindex,'break'=>$multi->show($pnstyle)));
			$this->assign('multi',$multi);
		}
		$offset	=$multi->offset;
		unset($multi);
		return $offset;
	}
	function shownav($cid="0"){
		$cache= $this->cache('catalog.cache','include/syscache',0,true);
		$C	  = $cache[$cid];
		$_nav = '<a href="'.$this->iurl($C['attr'],$C)->href.'">'.$C['name'].'</a>';
		$C['rootid'] && $nav.=$this->shownav($C['rootid']).$this->language('navTag');
		$nav.= $_nav;
		return $nav;
	}
	function keywords($a){
		if($this->config['kwCount']==0) return $a;
		$kw		= $this->cache('keywords.cache','include/syscache',0,true);
		$_count	= count($kw);
		for($i=0;$i<$_count;$i++){
			if($kw[$i]['status']){
				$s[]=$kw[$i]['keyword'];
				$r[]=$kw[$i]['replace'];
			}
		}
		return $this->str_replace_limit($s, $r, stripslashes($a),$this->config['kwCount']);
	}
	function str_replace_limit($search, $replace, $subject, $limit=-1) {
	    // constructing mask(s)...
	    if (is_array($search)) {
	        foreach ($search as $k=>$v) {
	            $search[$k] = '`' . preg_quote($search[$k],'`') . '`';
	        }
	    }else {
	        $search = '`' . preg_quote($search,'`') . '`';
	    }
	    // replacement
	    return preg_replace($search, $replace, $subject, $limit);
	}
}
?>