<?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 CommonModule{
	static public $category,$website,$uid,$uname,$nickname,$utype,$linkage,$catid;
	public function __construct(){

		//加载缓存
		$cache = self::readcache(array('class','setting'));
		self::$category  = $cache['class'];
		self::$website   = $cache['setting'];
		$this->assign('site',self::$website);
	}

	/**
     * 获取文档列表页
     * @access protected
	 * @param $catid  栏目ID
     * @return array
    */
	protected function get_arclist($catid=''){

		self::$catid  = empty($catid) ? Q('get.id',0,'intval') : $catid;
		if (empty(self::$catid)) {
			$channel = self::$category['channel'][strtolower(MODULE)];
			self::$catid = $channel['catid'];
		}else{
			$channel = self::$category[self::$catid];
		}

		if (empty($channel)){_404('对不起，您访问的页面不存在！');}

		$channel = array_merge($channel,$this->get_tpl($channel));

		if ($channel['attribute']==1){
			$tpl = $channel['listtpl'];
		}elseif ($channel['attribute']==2 || $channel['attribute']==4){
			$tpl = $channel['channeltpl'];
		}

		$result['tpl'] = str_replace('.html','',$tpl);

		self::$website['title']       = empty($channel['seotitle'])    ? $channel['name'].'-'.self::$website['title'] : $channel['seotitle'];
		self::$website['keywords']    = empty($channel['keywords'])    ? self::$website['keywords']                   : $channel['keywords'];
		self::$website['description'] = empty($channel['description']) ? self::$website['description']                : $channel['description'];

		$result['content'] = $channel;  //详细内容
		$result['site']    = self::$website; //站点信息
		$result['tpl']     = str_replace('.html','',$tpl); //页面模板

		return $result;
	}

	/**
     * 获取文档详细内容
     * @access protected
	 * @param $art_id  文档ID
     * @return array
    */
	protected function get_archives($art_id=''){

		$art_id  = empty($art_id) ?  Q('get.id','') : $art_id;

		$site = self::$website;

		$art_id = isset($art_id) ? htmlspecialchars(trim($art_id)) : '0';
		$art_id = trim(urldecode($art_id));
		$art_id = preg_match('/^[\d\.]+$/',$art_id) ? $art_id : '';
		$art_id = empty($art_id) ? '' : explode('.', $art_id);

		if (MODULE == 'List') {
			$exres = M('art_library')->field('model')->find($art_id[0]);
			$extable = $exres['model'];
		}else{
			$extable = MODULE;
		}

		if(!empty($extable)) {
		$content = M()
			    ->join('__art_library__ a LEFT JOIN __art_'.strtolower($extable).'__ b ON a.id = b.pid')
			    ->field('a.*,b.*'.$field)
			    ->where('a.id='.$art_id[0])
			    ->find();
		}
		self::$catid = $content['catid'];

		$channel = self::$category[$content['catid']];

		if (empty($art_id) || empty($channel)){_404('对不起，您访问的页面不存在！');}

		$channel = array_merge($channel,$this->get_tpl($channel));

		//更新浏览量
		if (Q('get.page','','intval')==''){
			M('art_library')->inc('hits','id='.$art_id[0],1);
		}

		//还原序列化的字段
		foreach($content as $key=>$fields){
			if(is_serialized($fields)){
				$content[$key] = unserialize($fields);
			}
		}

		//生成浏览量
		$content['hits'] = '<script src="/?r=hits&id='.$content['id'].'" language="javascript"></script>';

		$site['title']         = $content['title'].'-'.$channel['name'];
		$site['keywords']      = empty($content['keywords'])    ?  $channel['keywords']    : $content['keywords'];
		$site['description']   = empty($content['description']) ?  $channel['description'] : $content['description'];

		$result['content'] = $content;  //详细内容
		$result['site']    = $site;		//站点信息
		$result['tpl']     = str_replace('.html','',$channel['contenttpl']); //页面模板

		return $result;
	}

	/**
	 * 获取模板
	 * @access public
	 * @param $data
	 * @return array
	*/
	public function get_tpl($data){

		//顶级栏目模板
		if ($data['tplattr']==1) {
			$channel = Data::topChannel($data['catid'],self::$category);

		//自定义模板
		}elseif($data['tplattr']==3){
			$channel = $data;

		//上级栏目模板
		}elseif($data['tplattr']==2){
			$channel = $this->get_tpl(self::$category[$data['pid']]);
		}

		return array(
			'channeltpl' => $channel['channeltpl'],
			'listtpl'    => $channel['listtpl'],
			'contenttpl' => $channel['contenttpl'],
		);
	}

    /**
     * 视频播放器
     * @access protected
	 * @param $v  当前剧集
	 * @param $type  播放器类型，目前支持优酷或CMS自带的播放器,默认使用自带播放器
	 * @param $playerlist  播放器剧集列表
     * @return string
     */
	protected function player($playerlist,$type='oneself'){

		$v = Q('get.v',1,'intval');//获取当前集数

		if (empty($type)) return false;
		if (empty($playerlist)) return false;

		$videowidth  = empty($playerlist[$v]['videowidth'])  ? C('PLAYER_WIDTH'): $playerlist[$v]['videowidth'] ;
		$videoheight = empty($playerlist[$v]['videoheight']) ? C('PLAYER_HEIGHT') : $playerlist[$v]['videoheight'];
		$autostart   = $playerlist[$v]['autostart'] == 'true' ? 'true' : 'false';

		if ($type == 'youku' || $type == 'tudou'){

			$playerstr =
<<<Eof
			<embed src="{$playerlist[$v]['path']}" allowFullScreen="true" quality="high" width="{$videowidth}" height="{$videoheight}" flashvars ="isAutoPlay={$autostart}" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>
Eof;

		}elseif ($type == 'oneself'){

			$videokey=encode($playerlist[$v]['path'],md5(C('PLAYER_AUTH_KEY'))); //生成播放地址key;
			$baseuri = __PUBLIC__;
			$voice = C('PLAYER_VOICE');
			$playerstr =
<<<Eof
			<div id="video"></div>
			<script type="text/javascript" src="{$baseuri}/player/player.js" charset="utf-8"></script>
			<script type="text/javascript">

				var flashvars={
					f:'?r=video-path&vid={$videokey}',
					a:88,
					s:1,
					c:0,
					p:{$autostart},
					i:'chushihuatupian',
					h:3,
					v:{$voice},
					my_url:encodeURIComponent(window.location.href),
					my_title:encodeURIComponent(document.title),
					b:0
				};
				var params={bgcolor:'#FFF',allowFullScreen:true,allowScriptAccess:'always',wmode:'transparent'};
				CKobject.embed('{$baseuri}/player/player.swf','video','video','{$videowidth}','{$videoheight}',false,flashvars,video,params);
			</script>
Eof;
		}
		return $playerstr;
	}

	/**
     * 生成链接地址
     * @access function
	 * @param $data  相关数据
	 * @param $type  返回URL的类型，1为栏目页URL，2为内容页URL，3直接返回$data内容
     * @return string
     */
	static public function url($data=array(),$type=1){

		if(empty($data)) return '';

		if($type==1){
			$urlroute = $data['catroute'];
		}elseif($type==2){
			$data['savepath'] = self::$category[$data['catid']]['savepath'];
			$urlroute         = self::$category[$data['catid']]['artroute'];
		}

		//替换URL中的变量
		$route_arr = array('{cpath}'=>$data['savepath'],'{cid}'=>$data['catid'],'{aid}'=>$data['id'],'{y}'=>date('Y',$data['pubtime']),'{m}'=>date('m',$data['pubtime']),'{d}'=>date('d',$data['pubtime']));

		foreach ($route_arr as $key=>$value){
			$urlroute = str_ireplace($key,$value,$urlroute);
		}

		$suri = C('SYSTEM_MODE')== 2 ? 2 : 1;

		//判断是否连接到第一列表页
		if ($data['listoption']==1) {
			foreach (self::$category  as $vo) {
				if ($vo['pid']==$data['catid']) {
					$data = $vo;
					break;
				}
			}
		}

		$uri=array(
			'1'=>array(
				'list'   =>'list'.'&id='.$data['catid'],
				'content'=>'list-content&id='.$data['id'],
			),
			'2'=>array(
				'channel'=>$data['model'],
				'list'   =>$data['model'].'&id='.$data['catid'],
				'content'=>$data['model'].'-content&id='.$data['id'],
			)
		);

		if($type==1){
			//判断是否是外链
			if ($data['attribute']==3){
				$url =  $data['savepath'];
			}elseif($data['attribute']==4){
				$url = U($uri[$suri]['channel'],$urlroute);
			}else{
				//判断是否连接到第一列表页
				if ($data['listoption']==1) $data = self::$category[$data['catid']];
				//判断是否是频道封面页
				$url = U($uri[$suri]['list'],$urlroute);
			}
		}elseif($type==2){
			//如果是外链则直接返回
			if (!empty($data['linkurl'])){
				$url = $data['linkurl'];
			}else{
				$url = U($uri[$suri]['content'],$urlroute);
			}
		}else{
			$url = $data;
		}

		return $url;
	}



	/**
     * 读取缓存数据
     * @access public
	 * @param string $files 文件名
     * @return array
     */
	static public function readcache($files){
		$path = ROOT_PATH.'Data/Cache/Site';
		$files = is_array($files) ? $files : array($files);
		foreach ($files as $file){
			$data[$file] = F(strtolower($file),false,$path);
		}
		if (count($data)==1) {
			$data = $data[$file];
		}
		return $data;
	}


	/**
     * 成功提示
     * @access protected
	 * @param $content  提示信息
	 * @param $url   自动跳转的URl
	 * @param $tip   提示类型
	 * @param $icon  ICO图标
	 * @param $time  等待时机
     * @return json数据
     */
    protected function success($content,$url='',$tip=1,$icon=1,$time=3){
		if (IS_AJAX) {
			if (!headers_sent()) header("Content-type: text/html; charset=utf-8");
			echo json_encode(array("content"=>$content,"url"=>$url,"tip"=>$tip,"time"=>$time,"icon"=>$icon,"status" =>'1'));
			exit;
		}else{
			$this->tips($content,$url,'',true,$time);
		}
    }

	/**
     * 错误提示
     * @access protected
	 * @param $content  提示信息
	 * @param $url   自动跳转的URl
	 * @param $tip   提示类型
	 * @param $icon  ICO图标
	 * @param $time  等待时机
     * @return json数据
     */
    protected function error($content,$url='',$tip=2,$icon=2,$time=3){
		if (IS_AJAX) {
			if (!headers_sent()) header("Content-type: text/html; charset=utf-8");
			echo json_encode(array("content"=>$content,"url"=>$url,"tip"=>$tip,"time"=>$time,"icon"=>$icon,"status" =>'0'));
			exit;
		}else{
			$this->tips($content,$url,'',true,$time);
		}
    }

	/**
     * 显示信息提示页面
     * @access public
	 * @param string $content 提示信息
	 * @param string $url  自动跳转的URl
	 * @param string $links 手动跳转的URl
	 * @param string $auto_redirect 是否 自动跳转
	 * @param string $time 自动跳转时间
     * @return array
     */
	protected function tips($content,$url='',$links='',$auto_redirect=true,$auto_time=1){
		$msg['content'] = $content;
		$msg['url']     = empty($url)   ? 'javascript:window.history.back()' : $url;
		$msg['link']    = empty($links) ? '../'                       : $link;
		$this->assign('msg',$msg);
		$this->assign('auto_redirect',$auto_redirect);
		$this->assign('auto_time',$auto_time);
		exit($this->display('tips'));
    }

	/**
     * 弹出信息
     * @access public
	 * @param string $content 提示信息
	 * @param string $url  自动跳转的URl
     * @return array
     */
	protected function alert($content, $url = NULL){
		header("Content-type: text/html; charset=utf-8");
		$alert_msg="alert('$msg');";
		if( empty($url) ) {
			$gourl = 'history.go(-1);';
		}else{
			$gourl = "window.location.href = '{$url}'";
		}
		echo "<script>$alert_msg $gourl</script>";
		exit;
	}

	/**
     * 获取模板对象
     * @access protected
     */
	protected  function view(){
		static $view = NULL;
        if (is_null($view)) {
            $view = new View();
        }
		return $view;
	}

	/**
     * 模板赋值
     * @access protected
     */
	protected function assign($name, $value){
		return $this->view()->assign($name, $value);
	}

	/**
     * 模板显示
     * @access protected
     */
	protected function display($tplfile='', $cachetime, $cachepath = null, $contenttype = "text/html", $show = true){
		if($show){
			$tplfile = empty($tplfile) ? ACTION : $tplfile;
		}
		return $this->view()->display($tplfile, $cachetime, $cachepath, $contenttype, $show);
	}
}