<?php defined('SYSPATH') or die('No direct script access.');
class Memberauth_Core{
	function __construct(){
		$this->session	=	Session::instance();
		$this->db		=	new Database();
		$this->uri		=	new URI();
	}
	//认证用户
	function authUser(){
		//取得资源
		$allAcl		=	$this->getAllAcl();
		//取得访问默认资源
		$defaultAcl	=	$allAcl['访客'];
		$defaultAcl	=	array_merge($defaultAcl,array("member+login","index+index","index+installsite","front+report"));
		//取得当前控制器
		$controller	=	$this->uri->segment(1);
		$module		=	$this->uri->module();
		if(!$controller){
			list($controller,$action)	=	explode("/",Kohana::config("routes._default"));
			if(!$action){
				$action	=	"index";
			}
		}
		else{
			$action		=	$this->uri->segment(2)?$this->uri->segment(2):"index";
		}
		$currentUri		=	$controller."+".$action;
		@define("MODULE",$module);
		@define("CONTROLLER",$controller);
		@define("ACTION",$action);
		//取得用户数据
		$user			=	$this->session->get('user');
		if(@$user->user_id){
			//刷新SESSION数据
			$this->setUserSession($user->user_id);
			$user		=	$this->session->get('user');
			$userAcl	=	$allAcl[$user->group_id];
			if(!$user->status){
				unset($_SESSION['user']);
				url::redirect(BASEURI.'front/report/no_auditing/'.base64_encode("member/login")."/true");
			}
		}
		else{
			$userAcl	=	array();
		}
		//合并资源
		$allAcl			=	array_merge($userAcl,$defaultAcl);
		if(!in_array($currentUri,$allAcl)){
			if(!@$user){	url::redirect(BASEURI.'member/login');		}
			if(@$user){	url::redirect(BASEURI.'front/report/group_no_auth/'.base64_encode("member/index")."/true");		}
		}
	}
	//设置用户数据SESSION
	function setUserSession($user_id=false){
		$result	=	$this->db->select("m.*,m_g.group_name,m_g.group_id")
		->from("member as m")
		->join("member_group as m_g","m.group_id","m_g.group_id")
		->where("m.user_id",$user_id)
		->get();
		$this->session->set('user',$user=$result->current());
	}
	function getAllAcl(){
		$groupacl	=	DATADIR."cache/membergroupacl.php";
		if(file_exists(DATADIR."cache/membergroupacl.php")){
			return include($groupacl);
		}
		else{
			$cacheAcl	=	new Member_Group_Model();
			$cacheAcl->cache();
			return include($groupacl);
		}
	}
}