<?php
class Auth_Acl_Model extends Model{
	function __construct(){
		parent::__construct();
		$this->db	=	new Database();
	}
	function addacl($data){
		return $this->db->insert("acl",$data);
	}
	//检查模块同名
	function checkAcl($data){
		$this->db->from('acl')
		->where('acl_value',$data['acl_value']);
		return $this->db->get()->count();
	}
	//取得所有资源
	function getAclList($acl_id=false){
		if($acl_id!==false){
			$this->db->where('acl_id',$acl_id);
		}
		return $this->db->get("acl");
	}
	function deleteAcl($aclId){
		$this->db->in("acl_id",$aclId);
		return $this->db->delete('acl');
	}
	function updateAcl($acl,$acl_id){
		return $this->db->update("acl",$acl,array("acl_id"=>$acl_id));
	}
	//查询子资源
	function childrenAcl($acl_id,$field="acl_id",$return="array"){
		$this->db->select($field);
		$this->db->where('acl_parent_id',$acl_id);
		if($return=="array"){
			return $this->db->get('acl')->result_array(false);
		}
		else{
			return $this->db->get("acl")->result_array();
		}
	}
	function children_id($acl_id=array()){
		
	}
	//删除关系
	function delete_acl_group($group_id=false){
		$this->db->in("group_id",$group_id);
		return $this->db->delete("acl_group");
	}
	//新建关系
	function insert_acl_group($data){
		return $this->db->insert("acl_group",$data);
	}
	//取得用户组的资源
	function getGroupAcl($group_Id){
		return $this->db->where("group_id",$group_Id)
		->get("acl_group")
		->result_array();
	}
	function getAcl($group_id){
		$sql	=	"SELECT a.acl_value,a.acl_children
			FROM ".DBFIX."acl AS a 
			JOIN ".DBFIX."acl_group AS a_g ON a_g.acl_id=a.acl_id 
			JOIN ".DBFIX."user_group AS u_g ON a_g.acl_id=a.acl_id 
			WHERE a_g.group_id=u_g.group_id	AND u_g.group_id=$group_id";
		$result	=	$this->db->query($sql);
		$acl	=	$result->result_array();
		if(count($acl)>0){
			foreach ($acl as $tmp){
				$aclArray[]	=	$tmp->acl_value;
				if($tmp->acl_children!=""){
					list($control)	=	explode("+",$tmp->acl_value);
					$arrAcl		=	explode("|",$tmp->acl_children);
					if(count($arrAcl)>=1){
						foreach ($arrAcl as $cil){
							$aclArray[]	=	$control."+".$cil;
						}
					}
				}
			}
		}
		else{
			$aclArray	=	array();
		}
		return $aclArray;
	}
	function cache(){
		//取得用户组
		$groups	=	$this->db->get("user_group")->result_array();
		foreach ($groups	as $tmp){
			$acls	=	$this->getAcl($tmp->group_id);
			$cacheAcl[$tmp->group_id]	=	$acls;
			$cacheAcl[$tmp->group_name]	=	$acls;
		}
		if(file_put_contents(DATADIR."cache/groupacl.php","<?php \r\n return ".var_export($cacheAcl,true)."?>")){
			return true;
		}
		else{
			return false;
		}
	}
}