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

	public function __construct(){

		//后台登录验证
		if(MODULE !== 'Login' && !session('uid')){
			echo '<script language="javascript" type="text/javascript">window.top.location.href="?r=login"</script>';
		}

		//验证后台权限
        if (!$this->checkAccess()) {
			$dd = Q('multisid');
			$this->alert($dd.'没有操作权限');
        }

		Maclic::check();
    }

	/**
     * 后台权限验证
     * @return bool
     */
    public function checkAccess($super){

		$super = session('super_admin');

		//解决flash批量上传session丢失的问题
		$super = (empty($super) && PHPSESSID && Q('post.multisid')) ?  Q('post.multisuper') : $super;

		if ($super || MODULE == 'Login') {
			return true;
		}else{

			//普通管理员权限检查
			$node = M('node')
				  ->where(array('module'=>MODULE, 'controller'=>CONTROLLER, 'action'=>ACTION, 'param'=>Q('get.param','')))
				  ->field('nid')
				  ->find();

			 //当节点不存时，表示不需要验证
			if (!$node && MODULE=='Index') {
				return true;
			} else {
				$map['nid'] = $node['nid'];
				$map['rid'] = session('rid');
				return M('access')->where($map)->find();
			}
			return false;
		}
    }

	/**
     * 栏目列表
     * @access public
     */
	public function channeltree($model='',$field='catid,pid,name,model,status,sorter,ismenu'){
		$where = 'status=1';
		if (!empty($model))
			$where .= " AND model='".$model."'";
		$data = M('class')->field($field)->where($where)->order('sorter asc')->all();
		$list = Data::tree($data,'name','catid','pid');
		return $list;
	}

	/**
     * 写入缓存
     * @access public
     */
	public function writecache(){

		$path     = ROOT_PATH.'Data/Cache/Site'; //缓存路径
		$action   = strtolower(MODULE.'-'.CONTROLLER.'-'.ACTION);
		$filename = MODULE;
		switch ($action){
			//栏目缓存
			case 'class-index-sorter':
			case 'class-index-ajaxsub':
			case 'class-index-save':
			case 'class-index-del':
			case 'archives-index-show_page':

				$datacache=$this->channeltree('','catid,pid,name,subname,savepath,attribute,ico,subico,seotitle,keywords,description,content,contenttpl,channeltpl,listtpl,listoption,model,status,sorter,ismenu,flag,catroute,artroute,tplattr');
				foreach ($datacache as $k=>$v){
					$data[$v['catid']] = $v;
					$data[$v['catid']]['content'] = compress_html($v['content']);
					if ($v['attribute']==4) {
						$data['channel'][$v['model']] = $v;
					}
				}
				$filename = 'class';
				break;

			//站点信息缓存
			case 'setting-index-save':
				$site = M('setting')->where('type=0')->all();
				foreach ($site as $v){
					$data[$v['name']] = $v['value'];
				}
				$data['title']= $data['title'].'\u0020\u002d\u0020\u0050\u006f\u0077\u0065\u0072\u0065\u0064\u0020\u0062\u0079\u0020\u004d\u0061\u0067\u0069\u0063\u0020\u0043\u004d\u0053';
				$data['copyright']= $data['copyright'].'\u0026\u0023\u0033\u0039\u003b\u0026\u006e\u0062\u0073\u0070\u003b\u6280\u672f\u652f\u6301\uff1a\u0026\u006c\u0074\u003b\u0061\u0020\u0068\u0072\u0065\u0066\u003d\u0026\u0071\u0075\u006f\u0074\u003b\u0068\u0074\u0074\u0070\u003a\u002f\u002f\u0077\u0077\u0077\u002e\u0071\u0069\u006e\u0074\u0065\u0063\u0068\u002e\u006e\u0065\u0074\u0026\u0071\u0075\u006f\u0074\u003b\u0020\u0074\u0061\u0072\u0067\u0065\u0074\u003d\u0026\u0071\u0075\u006f\u0074\u003b\u005f\u0062\u006c\u0061\u006e\u006b\u0026\u0071\u0075\u006f\u0074\u003b\u0026\u0067\u0074\u003b\u6d4e\u5b81\u7f51\u7ad9\u5efa\u8bbe\u0026\u006c\u0074\u003b\u002f\u0061\u0026\u0067\u0074\u003b';
			    break;

			//模型缓存
			case 'fields-index-save':
				$filename = Q('get.type');
				if($filename=='model'){
					$model = M('fields')->where("utype='' AND status=1")->order('sorter asc')->all();
					foreach ($model as $m){
						$data[$m['value']] = $m;
					}
				}
			    break;

			//推荐位缓存
			case 'flag-index-save':
			case 'flag-index-del':
				$data = M('flag')->where('status=1')->all();
			    break;

			//幻灯片缓存
			case 'slide-index-savedit':
			case 'slide-index-saveadd':
			case 'slide-index-del':
				$data = M('addslide')->where('status=1')->order('sorter asc')->all();
				break;

			//友情链接缓存
			case 'links-index-save':
			case 'links-index-del':
				$data = M('addlinks')->all();
				break;

			//客服缓存
			case 'kefu-index-save':
				$data =compress_html(M('addkefu')->find());
				break;
		}

		if(!empty($data)) {
			F(strtolower($filename),$data,$path);
		}
	}

	/**
     * 错误提示
     * @access protected
	 * @param $content  提示信息
	 * @param $url   自动跳转的URl
	 * @param $tip   提示类型
	 * @param $icon  ICO图标
	 * @param $time  等待时机
     */
    protected function error($msg,$url="",$time=1500,$icon=2){
		 @header('Content-type: text/html; charset=utf-8');
		 if(!empty($url))
			$gourl = ',end: function(){parent.parent.$("iframe").attr("src","'.$url.'");parent.parent.layer.closeAll("iframe");}';
		exit('<script type="text/javascript">parent.parent.parent.layer.msg("'.$msg.'",{icon:'.$icon.',time:'.$time.',shade:0.3'.$gourl.'});</script>');
    }

    /**
     * 成功提示
     * @access protected
	 * @param $content  提示信息
	 * @param $url   自动跳转的URl
	 * @param $tip   提示类型
	 * @param $icon  ICO图标
	 * @param $time  等待时机
     * @return json数据
     */
    protected function success($msg,$url="",$time=1500,$icon=1){
		$this->writecache();
        if(!empty($url))
			$gourl = ',end: function(){parent.parent.$("iframe").attr("src","'.$url.'");parent.parent.layer.closeAll("iframe");}';
		exit('<script type="text/javascript">parent.parent.parent.layer.msg("'.$msg.'",{icon:'.$icon.',time:'.$time.',shade:0.3'.$gourl.'});</script>');
    }

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

 	/**
     * 获取模板对象
     * @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,$cacheName= null, $contenttype = "text/html", $show = true){
		$tplfile = empty($tplfile) ?  MODULE .'/'. ACTION : $tplfile;

		return $this->view()->display($tplfile, $cachetime, $cachepath,$cacheName= null, $contenttype, $show);
	}

}