<?php
class admin_permissionControl extends skymvc{
	
	public function __construct(){
		parent::__construct();
		$this->loadModel("permission");
	}
	
	public function onDefault(){
		$data=$this->permission->select(array("order"=>"id asc"));
		$this->smarty->assign(
			array(
				"data"=>$data,
			)
		);
		$this->smarty->display("permission/index.html");
	}
	
	public function onAdd(){
		$id=get_post('id','i');
		if($id){
			$this->smarty->assign("data",$this->permission->selectRow(array("where"=>array('id'=>$id))));
		}
		$this->smarty->display("permission/add.html");
	}

	public function onSave(){
		$id=get_post('id','i');
		$data['m']=strtolower(post('m','h'));
		$data['access']=strtolower(post('access','h'));
		$data['title']=post('title','h');
		if($id){
			$this->permission->update($data,array("id"=>$id));
			$this->gomsg($this->lang['edit_success']);
		}else{
			$this->permission->insert($data);
			$this->gomsg($this->lang['add_success']); 
		}
	}
	
	public function onSaveConfig(){
		 set_time_limit(0);
		 $data=$this->permission->select(array());
		  
		 if($data){
			 foreach($data as $k=>$v){
				 $permission[$v['m']][]=array("title"=>$v['title'],"access"=>$v['access']);
			 }
		 }
		 $str="<?php";
		 if($permission){
			 foreach($permission as $k=>$v){
				 $str.="\r\n\$config['$k']=array(\r\n";
				 
				 foreach($v as $d){
					$str.="      array('title'=>'{$d['title']}','access'=>'{$d['access']}'),\r\n";
				 }
				 
				 $str.="\r\n);\r\n";
			 }
		 }
		 $str.="?>";
		 file_put_contents(ROOT_PATH."config/permission.php",$str);
		 $this->gomsg($this->lang['permission_write_success']);
		break;
	}
	
	public function onDelete(){
		$id=get('id','i');
		//$this->permission->delete(array("id"=>$id));
		echo json_encode(array("error"=>0,"message"=>$this->lang['delete_success']));
	}
	
	/*获取权限*/
	public function onGetPermission(){
		$this->loadModel("permission");
		$dir=ROOT_PATH."source/index";
		$dh=opendir($dir);
		while($file=readdir($dh)){
			if($file!="." && $file!=".."){
				$temp=$dir."/".$file;
				$data=file_get_contents($temp);
				preg_match_all("/function on(\w+)\(/i",$data,$arr);
				if(isset($arr[1])){
					$m=substr($file,0,strpos($file,"."));
					$access="";
					foreach($arr[1] as $k=>$v){
						if($k==0){
							$access .=$v;
						}else{
							$access .=",".$v;
						}
						
					}
					if(!$this->permission->selectRow(array('where'=>"m='".$m."'"))){
						$this->permission->insert(array(
							'm'=>$m,
							'access'=>strtolower($access), 
							'title'=>$file,
							'siteid'=>SITEID
						));
					}
				}
			}
		}
		
		$this->gomsg("权限生成成功");
		
	}

	
}
?>