<?php
 /**
 * Magic CMS 自定义标签解析库
 * ============================================================================
 * Copyright 2014 大秦科技，并保留所有权利。
 * 网站地址: http://www.qintech.net；
 * ----------------------------------------------------------------------------
 * 未获商业授权之前，不得将Magic CMS用于商业用途（包括但不限于企业网站、经营性网站
 * 以营利为目的或实现盈利的网站）未经官方许可，禁止在Magic CMS的整体或任何部分基础
 * 上以发展任何派生版本、修改版本或第三方版本用于重新分发。如果您未能遵守本协议的
 * 条款，您的授权将被终止，所被许可的权利将被收回，并承担相应法律责任。
 * ============================================================================
 * Date:2014/12/31
**/
if (!defined('APP_PATH')) exit('No direct script access allowed');

class TaglibModule extends CommonModule{

	static public $page;
	public function __construct(){
		 parent::__construct();
	}

	/**
     * 解析channel标签
     */
	static public function channelTag($attr){
		//获取栏目ID
		$catid =  empty($attr['catid']) ?  self::$catid : $attr['catid'];

		//type类型判断
		$type = empty($attr['type']) ? 'sun' : $attr['type'];

		//level判断
		$level = empty($attr['level']) ? 1 : $attr['level'];

		//栏目标识
		$flag = empty($attr['flag']) ? false : $attr['flag'];

		//多id筛选，会重置数组主键
		if (stristr($catid,',')){
			foreach (explode(',',$catid) as $key=>$value){
				$result[$key]=self::$category[intval($value)];
				$result[$key]['url'] = self::url($value);
			}

		}else{

			//魔术方法，{mac:channel type='mac:1-sun,2-self'  level='2'} ... {/mac:channel}
			//一级栏目使用type='sun',二级栏目使用type='self'依次类推，
			$status = preg_match_all('#([0-9]+)-([a-z_]+),#i', $type, $info, PREG_SET_ORDER);
			if(strstr($type,'mac:') && $info){
				foreach ($info  as $vo) {
					if (($vo[1]+($level-1)) == self::$category[$catid]['_level']) {
						$type = $vo[2];
					}
				}

			//只支持到三级栏目，如果是一级栏目页调用，点击进入二级栏目页时则自动调用该一级栏目的子栏目，
			//如果点击二级栏目则自动调用该二级栏目的上级栏目,如果开始栏目不是顶级栏目是配合level 属性定位当前栏目的级别

			}elseif($type=='mac'){
				$category = self::$category[$catid];
				if($level == self::$category[$catid]['_level']){
					$type = 'sun';
				}elseif((self::$category[$catid]['_level']-$level)==1){
					$type = 'self';
				}
			}

			switch ($type){

				 //获取导航
				case 'menu':

					//指定栏目下所有子栏目
					if (strstr($attr['catid'],':sunall')) {
						$category = Data::channelList(self::$category,$attr['catid']);

					//仅指定栏目下子栏目
					}elseif (isset($attr['catid'])) {
						foreach (self::$category  as $mk=>$mv) {
							if ($mv['pid']==$attr['catid']) {
								$category[$mk] = $mv;
							}
						}
					//不限定栏目
					}else{
						$category = self::$category;
					}

					foreach ($category as $key=>$value){
						if ($value['ismenu']==1){
							$result[$key] = $value;
							$result[$key]['id'] = $value['catid'];
							$result[$key]['url'] = self::url($value);
						}
					}
					break;

				//获取顶级栏目
				case 'top':
					$topcate = Data::topChannel($catid,self::$category,'catid');
					$condition = $topcate['catid'];
					break;
				//获取下级栏目
				case 'sun':
					$condition = $catid;
					break;
				 //获取同级栏目
				case 'self':
					$condition = self::$category[$catid]['pid'];
					break;
				//获取上级分类
				case 'sup':
					$condition = self::$category[$catid]['pid'];
					$condition = self::$category[$condition]['pid'];
					break;
			}

			foreach (self::$category as $key=>$value){
				if ($value['pid'] == $condition){
					$result[$key] = $value;
					$result[$key]['id'] = $value['catid'];
					$result[$key]['url'] = self::url($value);
				}
			}

		}

		//栏目标示
		if($flag && empty($result)){
			foreach($result as $k=>$v){
				if (stride($flag,$v['flag'])){
					$result[$k] = $v;
					$result[$k]['id'] = $v['catid'];
					$result[$k]['url'] = self::url($v);
				}
			}
		}

		if (isset($attr['limit'])) {

		}

		return $result;
	}

	/**
     * 解析arclist标签
	 *{suke:arclist type='sun' catid='1' order='hits' flag='a' limit='10' image='true' titlelen='20' infolen='100' model='image' field='abstract'}
	 *<li><a href="{$field.url}" title="{$field.title}">{$field.title}</li>
	 *{/suke:arclist}

	 * @param string $catid 栏目ID  可指定单个栏目ID（如：catid='1'）也可指定多个栏目ID（如：catid='1,2,3'），同时也可指定数据库字段名获取获取符合该条件的内容
	 *								（如 ：catid='pid:1,2,3'  表示获取pid字段值等于1,2,3的记录，当值为'auto'时，自动读取当前栏目ID，不定义则不限制栏目
	 * @param string $type 类型   定义$catid时有效，sun:指定栏目的子栏目,不包含子栏目的下级栏目，sunall：指定栏目的所有子栏目,含子栏目的下级栏目
	 * @param string $top  置顶文章  为-1时获取所有得置顶的文章，为下列值时获取对于置顶天数的文章。1->置顶一天,2->置顶两天,3->置顶三天,4->置顶一周,5->置顶半个月，6->置顶一个月,7->置顶三个月,8->置顶半年,9->置顶一年,
	 * @param string $order  排序方式  默认按pubtime发布时间排序，可指定数据库任意字段
	 * @param string $orderway  排序方式:desc/asec
	 * @param string $field    扩展读取的数据库字段，自动判断文章模型
	 * @param string $flag     自定义属性值：头条[h] 推荐[c] 幻灯[f] 跳转[j] 特荐[a]
	 * @param integer $limit    限制读取的数据条数或限定的记录范围（如：limit='1,10'  表示从ID为1的记录开始，取10条记录)
	 * @param boolean $image    是否获取图集 True/False
	 * @param integer $titlelen   限制标题长度
	 * @param integer $infolen    限制摘要长度
	 * @param string  $model      指定栏目模型
	 * @param string  $date       发布时间范围,t->今天,y->昨天,w->最近一个星期,m->最近一个月
	 * @return string  成功后返回解析后的标签内容
     */
	static public function arclistTag($attr){
		$condition = 'a.status = 1';
		$catidpre  = 'catid';
		$image     = isset($attr['image'])      ? $attr['image']        : '';
		$top       = isset($attr['top'])        ? $attr['top']          : false;
		$page      = isset($attr['page'])       ? $attr['page']         : false;
		$catid     = isset($attr['catid'])      ? $attr['catid']        :  self::$catid;
		$order     = isset($attr['order'])      ? $attr['order']        : 'pubtime';
		$orderby   = isset($attr['orderby'])    ? ' '.$attr['orderby']  : ' desc';
		$where     = isset($attr['where'])      ? ' '.$attr['where']    : false;

		//相关文章
		if (isset($attr['about'])){
			switch (trim($attr['about'])){
				//当前文章栏目下的文章
				case '1':
					$catid = self::$catid;

				break;
			}
		}
		if (!empty($catid)) {

			//判断是否自定义数据库字段,默认为pid
			if (strrpos($catid,':')){
				$catidarr = explode(':',$attr['catid']);
				$catidpre =  $catidarr[0];
				$catid    =  $catidarr[1];
			}

			switch (trim($attr['type'])){
				//仅获取下级栏目内容
				case 'sun':
					//如果是多ID则遍历所有的ID
					if (strpos($catid,',')){
						foreach (explode(',',$catid) as $tv){
							//遍历查找栏目的子栏目，并组合成新的数组
							foreach (self::$category as $key=>$value){
								if ($value['pid'] == $tv){
									$ncatid[] = $value['catid'];
								}
							}
						}
					}else{
						//单个ID时遍历查找子栏目
						foreach (self::$category as $k=>$v){
							if ($v['pid'] == $catid){
								$ncatid[] = $v['catid'];
							}
						}
						if(empty($ncatid)){
							$ncatid = $catid;
						}
					}

					$imntype = implode(',',$ncatid);
					if(!empty($imntype)){
						if($attr['self']){
							$selfid = $catid . ',';
						}
						 $catid = $selfid . $imntype;
					};
					break;
				//获取所有下级栏目内容
				case 'sunall':
					$catid_arr = array($catid);
					$channarr = Data::channelList(self::$category,$catid);
					if (!empty($channarr)){
						foreach ($channarr as $ntvo){
							$catid_arr[] = $ntvo['catid'];
						}
					}
					$catid = implode(',',$catid_arr);

				break;
			}

			//构造SQL语句
			$condition .= ' AND a.'.$catidpre.' IN ('.($catid).')';
		}

		if (isset($attr['field'])){
			$channelid = strpos($catid,',')  ? substr($catid,0,strpos($catid,',')) : $catid;
			if (isset($model)){
				$extable = $model;
			}elseif($channelid){
				$extable = self::$category[$channelid]['model'];
			}else{
				$extable = 'article';
			}

			$extsql   =	' INNER JOIN __art_'.$extable.self::$category[$channelid]['model'].'__ b ON a.id =b.pid';
			$extfield = ',b.'.str_replace(',',',b.',$attr['field']);
		}

		//rand：随机文章，hits：点击量（热门文章），pubtime：发表时间（最新文章），
		if ($order=='rand'){
			$order = 'rand()';
		}

		//获取置顶文章
		if ($top){
			if ($top==-1) {
				$condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') !=  FROM_UNIXTIME(sortrank,'%Y-%m-%d')";
			}else{
				$sortrank = array('1'=>1,'2'=>2,'3'=>3,'4'=>7,'5'=>15,'6'=>30,'7'=>90,'8'=>180,'9'=>365);
				$sortrank = empty($sortrank[$top]) ? 1 : $sortrank[$top];
				$condition .= " AND  FROM_UNIXTIME(sortrank,'%Y-%m-%d') = date_sub(curdate(),interval ".$sortrank." day)";
			}
		}

		$condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') <=  FROM_UNIXTIME(sortrank,'%Y-%m-%d')";

		if (isset($attr['model'])){
			$condition .= " AND model='".$attr['model']."'";
		}

		//发布时间范围
		if (isset($attr['date'])){
			switch ($attr['date']){
				case 't'://今天
				  $condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') = date_format(now(),'%Y-%m-%d') ";
				  break;
				case 'y': //昨天
				  $condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') = date_sub(curdate(),interval 1 day) ";
				  break;
			    case 'w': //近一个星期
			      $condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') <= date_sub(curdate(),interval 7 day) ";
			     break;
			    case 'm': //近一个月
			     $condition .= " AND  FROM_UNIXTIME(pubtime,'%Y-%m-%d') <= date_sub(curdate(),interval 30 day) ";
			     break;
			}
		}

		if ($where){
			$condition .= $attr['where'];
		}

		//自定义属性
		if (isset($attr['flag'])){
			$condition .= ' AND FIND_IN_SET("'.$attr['flag'].'",a.flag)';
		}


		if ($page) {

			//执行SQL查询
			$count = M()
					->join('__art_library__ a'.$extsql)
					->field('a.id')
					->where($condition)
					->count();
			self::$page = new Page($count,$page);

			if (C('URL_REWRITE')){
				Page::$staticUrl = strtolower(MODULE).'-{page}';
			}else{
				Page::$staticUrl = strtolower(MODULE).'&id='.$catid.'&page={page}';
			}

			$limit = self::$page->limit();

		}else{

			//限制条数，定义page属性后limit将失效
			if ($limit){
				if (strrpos($limit,','))
					$limit = $limit;
				else
					$limit= ' 0,'.$limit;
			}else{
				$limit = 10;
			}
		}

		//执行SQL查询
		$result = M()
				->join('__art_library__ a'.$extsql)
				->field('a.id,a.catid,a.title,a.model,a.linkurl,a.sortrank,a.abstract,a.pubtime,a.image,a.hits'.$extfield)
				->where($condition)
				->order('a.weight,a.sortrank desc, '.$order.$orderby)
				->limit($limit)
				->all();

		if (!empty($result)){
			foreach ($result as $k=>$v){

				//生成URL
				$result[$k]['url'] = self::url($v,2);

				//生成缩略图
				if (C('THUMB_ON')){
					$result[$k]['thumb'] = thumb($v['image']);
				}
				//获取图集
				if ($image){
					$result[$k]['imglist'] = M('batimages')->where('pid='.$v['id'])->order('sorter asc')->select();
				}

				//判断文章是否被置顶
				if ($v['pubtime']!=$v['sortrank']) {
					$ctime  = round(($v['sortrank'] - $v['pubtime'])/3600/24);
					$sortrank = array('1'=>1,'2'=>2,'3'=>3,'7'=>4,'15'=>5,'30'=>6,'90'=>7,'180'=>8,'365'=>9);
					$result[$k]['top'] = $sortrank[$ctime];
				}else{
					$result[$k]['top'] = 0;
				}

				//判断是否限制标题长度
				if (isset($attr['titlelen'])){
					$result[$k]['title'] = String::msubstr($v['title'],$attr['titlelen']);
				}

				//判断是否限制内容简介长度
				if (isset($attr['infolen'])){
					$result[$k]['abstract'] = String::msubstr($v['abstract'],$attr['infolen']);
				}
			}
		}

		return $result;
	}




	/**
	 * Field  标签
	 * @param string $type 类型
	 * @param string $catid 栏目ID
	 * @param string $name  返回的内容
	 * @return string  成功后返回解析后的标签内容
	 */
	static public function fieldTag($attr){

		switch (trim($attr['name'])){

			//栏目位置导航
			case 'position':
				$type    = isset($attr['type'])   ?  $attr['type']   : ' >> ';
				$catid  = isset($attr['catid']) ?  $attr['catid'] : self::$catid;
				if (!empty($catid)) {

					$postree = Data::parentChannel(self::$category,$catid);

					foreach ($postree as $k=>$v){
						if ($v['listoption'] == 3){
							$result .= '<a href="'.U(strtolower(MODULE).'&id='.$v['catid'],$v['savepath']).'" title="'.$v['name'].'">'.$v['name'].'</a>';
						}else{
							//判断是否连接到第一列表页
							if ($v['listoption']==1){
								foreach (self::$category as $value){
									if ($value['pid'] == $v['catid']){
										$suncat[$k] = $value;
										break;
									}
								}
							}else{
								$suncat[$k]['catid']       = $v['catid'];
								$suncat[$k]['savepath']    = $v['savepath'];
							}
							$result .=  '<a href="'.U(strtolower(MODULE).'&id='.$suncat[$k]['catid'],$suncat[$k]['savepath']).'" title="'.$v['name'].'">'.$v['name'].'</a>';
						}
						if ($k < count($postree)-1){
							$result .= $type;
						}
					}
				}
				break;

			case 'arcpre': //获取上一篇文档
				if (CONTROLLER=='Content'){
					$id       = Q('get.id',1,'intval');
					$empty    = isset($attr['empty'])   ?  $attr['empty'] : '没有了';

					if (!empty(self::$catid) && !empty($id)) {
						$artprev = M('art_library')->field('id,catid,title')->where('catid='.self::$catid.' and id > '.$id)->order('id asc')->limit(1)->find();
						$artprev['title']  = isset($attr['title']) ? $attr['title'] : $artprev['title'];
						if (!empty($artprev['id'])){
							$result  = "<a href=\"";
							$result .=U(strtolower(MODULE).'-content&id='.$artprev['id'],self::$category[$artprev['catid']]['savepath'].$artprev['id']);
							$result .= "\" title=\"{$artprev['title']}\">{$artprev['title']}</a>";
						}elseif(empty($artprev['id']) && $empty=='false'){
							$result = self::creaURL($artprev,'" '.str_replace("&nbsp;"," ",$attr['param']),4);
						}else{
							$result = $empty;
						}
					}
				}
				break;
			case 'arcnext': //获取下一篇文档
				if (CONTROLLER=='Content'){
					$id       = Q('get.id',1,'intval');
					$empty    = isset($attr['empty'])   ?  $attr['empty'] : '没有了';

					$artnext = M('art_library')->field('id,catid,title')->where('catid='.self::$catid.' and id < '.$id)->order('id desc')->limit(1)->find();
					$artnext['title']  = isset($attr['title']) ? $attr['title'] : $artnext['title'];
					if (!empty($artnext['id'])){
						$result  = "<a href=\"";
						$result .=U(strtolower(MODULE).'-content&id='.$artnext['id'],self::$category[$artnext['catid']]['savepath'].$artnext['id']);
						$result .= "\" title=\"{$artnext['title']}\">{$artnext['title']}</a>";
					}elseif(empty($artnext['id']) && $empty=='false'){
						$result = self::creaURL($artnext,'" '.str_replace("&nbsp;"," ",$attr['param']),4);
					}else{
						$result = $empty;
					}
				}
				break;
			case 'verify': //显示验证码
				$result = '<img src="/?r=verify" id="qintech_verify" alt="看不清？点击刷新" onclick="javascript:this.src=\'/?r=verify\'" style="cursor:pointer" >';
				break;
			default:
				//内容调用
				if (CONTROLLER=='Content' && !isset($attr['type'])){
					$result = M()
							->join('__art_library__ a LEFT JOIN __art_'.self::$category[self::$catid]['model'].'__ b ON a.id = b.pid'.$condition)
							->field('a.*,b.*'.$field)
							->where('a.id='.self::$catid)
							->find();
				//栏目调用
				}else{
					$catid = isset($attr['catid']) ? $attr['catid'] : self::$catid;

					//获取顶级分类
					if ($attr['type']=='top'){
						$topchannel = Data::topChannel($catid,self::$category,'catid');
						$catid      = $topchannel['catid'];
					//获取上级分类
					}elseif($attr['type']=='sup'){
						$catid= self::$category[$catid]['pid'];
					}
					$category = self::$category[$catid];
					$category['url'] = self::url($category);
					$result = $category[trim($attr['name'])];
				}
		}

		if (isset($attr['length'])){
			$result = String::msubstr(strip_tags($result),$attr['length']);
		}

		return $result;
	}


	/**
     * 解析pageshow标签
     */
	static public function pageshowTag($attr){
		$style = isset( $attr['style'] ) ? $attr['style'] : 2;
		$row   = isset( $attr['row'] ) ? intval( $attr['row'] ) : 8;
		return  self::$page->show($style,$row);
	}


	/**
     * 解析Slide标签
     */
	static public function slideTag($attr){
		//加载幻灯片缓存
		$slide = self::readcache('slide');

		//默认幻灯片组
		$group = isset($attr['group']) ?  $attr['group'] : 1;

		//限制条数
		if (isset($attr['limit'])){
			if ($attr['limit']>count($slide)){
				$limit = count($slide)-1;
			}else{
				$limit = $attr['limit'];
			}
		}else{
			$limit = count($slide)-1;
		}

		for ($i=0;$i<=$limit;$i++){
			if ($slide[$i]['sgroup']==$group && $slide[$i]['status']==1){
				$result[$i] = $slide[$i];
			}

			if (isset($attr['titlelen'])){
				$result[$i]['title'] = String::msubstr($result[$i]['title'],$attr['titlelen']);
			}
		}
		return $result;
	}

	/**
     * 解析Flink标签
     */
	static public function flinkTag($attr){
		//加载友情链接缓存
		$flink = self::readcache('links');
		//限制条数
		if (isset($attr['limit'])){
			if ($attr['limit']>count($flink)){
				$limit = count($flink)-1;
			}else{
				$limit = $attr['limit'];
			}
		}else{
			$limit = count($flink)-1;
		}
		for ($i=0;$i<=$limit;$i++){
			if ($flink[$i]['status']==1){
				$result[$i] = $flink[$i];
			}
			if (isset($attr['titlelen'])){
				$result[$i]['title'] = String::msubstr($result[$i]['title'],$attr['titlelen']);
			}
		}
		return $result;
	}

	/**
     * 解析Kefu标签
     */
	static public function kefuTag($attr){

		$info = self::readcache('kefu');

		$KeFu = '';
		if ($info['status']==0){
			$KeFu.='<link rel="stylesheet" type="text/css" href="'.__PUBLIC__.'/kefu/skins/style.css"/>';
			$KeFu.='<script type="text/javascript" src="'.__PUBLIC__.'/kefu/kefu.js"></script>';
			$KeFu.='<script language="javascript">';
			$KeFu.='$(function(){';
			$KeFu.='$("#fixedBox").fix({';
			$KeFu.='position:"'.$info['position'].'",';
			$KeFu.='horizontal:'.$info['horizontal'].',';
			$KeFu.='vertical:'.$info['vertical'].',';
			$KeFu.='halfTop:'.$info['halfTop'].',';
			$KeFu.='minStatue:'.$info['minStatue'].',';
			$KeFu.='hideCloseBtn:'.$info['hideCloseBtn'].',';
			$KeFu.='skin: "'.$info['skin'].'",';
			$KeFu.='showBtnWidth:28,contentBoxWidth:154,durationTime: 1000});});</script>';
			$KeFu.='<div class="fixed_box" id="fixedBox"><div class="content_box"><div class="content_inner"><div class="close_btn"><a title="关闭"><span>关闭</span></a></div><div class="content_title"><span>客服中心</span></div><div class="content_list"><div class="qqserver">';

			$content_arr = explode(';',str_replace('，',',',str_replace('；',';',$info['content'])));

			foreach($content_arr as $key=>$vo){
				if (strstr($vo,'|')){
					$KeFu_Arr1=explode('|',$vo);
					$KeFu.='<div class="fixed_ground">'.$KeFu_Arr1[0].'</div>';
					$KeFu_Str1 = $KeFu_Arr1[1];
				}else{
					$KeFu_Str1 = $vo;
				}
				$KeFu_Arr=explode(',',$KeFu_Str1);
				foreach($KeFu_Arr as $key2=>$vo2){
					if (strstr($vo2,':')){
						$KeFu_Arr2=explode(':',$vo2);
						$KeFu_QQ=$KeFu_Arr2[1];
						$KeFu_Name=$KeFu_Arr2[0];
					}else{
						$KeFu_QQ=$vo2;
						$KeFu_Name='';
					}
					$KeFu.='<p><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&amp;uin='.$KeFu_QQ.'&amp;site=qq&amp;menu=yes">';
					if (!empty($KeFu_Name)){
						$KeFu.='<span>'.$KeFu_Name.'</span>';
					}
					$KeFu.='<img border="0" src="http://wpa.qq.com/pa?p=2:'.$KeFu_QQ.':41" alt="点击这里给我发消息" title="点击这里给我发消息"></a></p>';
				}
			}
			$KeFu.='</div>';

			if ($info['rx_status']==0 && !empty($info['kfrx'])){

				$kfrx =str_replace('，',',',$info['kfrx']);

				if (strstr($kfrx,',')){
					$kfrx_info =str_replace(',','<br>',$kfrx);
				}else{
					$kfrx_info=$kfrx;
				}
				$KeFu.='<hr><div class="phoneserver"><h5>客户服务热线</h5><p>'.$kfrx_info.'</p></div>';
			}

			if ($info['gb_status']==0){
				$KeFu .= '<hr><div class="msgserver"><p><a href="'.U('guestbook').'">给我们留言</a></p></div>';
			}

			$KeFu.='</div><div class="content_bottom"></div></div></div><div class="show_btn"><span>展开客服</span></div></div>';
		}

		if ($info['ot_status']==0){
			$KeFu.=$info['ot_content'];
		}

		return $KeFu;
	}
}
?>