<?php
defined('IN_YUNYECMSAdmin') or exit('No permission.');
core::load_admin_class('admin');
class membergroup extends YUNYE_admin {
	function __construct() {
		parent::__construct();
		$this->db = core::load_model('membergroup_model');
		 if(!getroot('member','membergroup')){
			messagebox(Lan('no_permission'),'back',"warn");			
		 } 
	}
	 //加载首页
	 public function init() {
		  $parnav='<li><a href=\"'.url_admin('init',"membergroup").'\" target=\"maincontent\">系统</a></li><li><a href=\"'.url_admin('init','membergroup').'\" target=\"maincontent\">会员组管理</a></li><li class=\"active\">会员组列表</li>';
		   if(!getroot('users','logs')){
			  messagebox(Lan('no_permission'),'back',"warn");			
		   }
		 $pagesize=20;
		 $sqlquery="select * from `#yunyecms_membergroup`  ";
		 $where=" where  groupname<>'' ";
		 $sqlcnt=" select count(*) from `#yunyecms_membergroup` ";
		 $order=" order by `ordernum` asc ";
		  if(isset($_REQUEST)){
		   if(!empty($_REQUEST["searchkey"])){
		        $searchkey=usafestr(trim($_REQUEST["searchkey"]));
		        $where=$where." and ( `groupname`  like '%{$searchkey}%' )";
			  }
		 }
		 $pagearr=$this->db->pagelist($sqlcnt,$sqlquery,$where,$order,$pagesize);
		 if($pagearr["count"]!=0){
			 $list=$pagearr["query"];
			 $page=$pagearr["page"];
		 }
		 require tpl_adm('membergroup_list');
	  }
	
	
 public function add(){
		    if(!empty($_GET["id"])){
					$parnav='<li><a href=\"'.url_admin('init','membergroup').'\" target=\"maincontent\">会员组管理</a></li><li class=\"active\">修改会员组</li>';
					$id=trim($_GET["id"]);
					 if(!is_numeric($id)){
					   messagebox("会员组参数错误",url_admin('init'));
					 }
					 $rsinfo=$this->db->find("select * from `#yunyecms_membergroup` where `id`= {$id}");
					 if(empty($rsinfo)){
						   messagebox("会员组不存在",$_SERVER['HTTP_REFERER']);			
					  }
					$yyact="edit";
			}else{
				$yyact=yyact_get("add");
				$parnav='<li><a href=\"'.url_admin('init','member').'\" target=\"maincontent\">用户</a></li><li><a href=\"'.url_admin('init','membergroup').'\" target=\"maincontent\">会员组管理</a></li><li class=\"active\">增加会员组</li>';
				$sqlordermax="select max(ordernum) as maxordernum from `#yunyecms_membergroup`";
				$ordermaxquery=$this->db->find($sqlordermax);
				$ordermax=$ordermaxquery["maxordernum"]+1;
				}
	        if(isset($_POST["yyact"])){
				      $_POST=ustripslashes($_POST);
				 	  $data["groupname"]=usafestr(trim($_POST["groupname"]));
				 	  $data["isdefault"]=usafestr(trim($_POST["isdefault"]));
				 	  $data["isvisitor"]=usafestr(trim($_POST["isvisitor"]));
				      $data["remark"]=uhtmlspecialchars(trim($_POST["remark"]));
				 	  $data["ordernum"]=usafestr(trim($_POST["ordernum"]));
				 	  $data["groupname_en"]=usafestr(trim($_POST["groupname_en"]));
				 	  $data["remark_en"]=usafestr(trim($_POST["remark_en"]));
				 	  $data["status"]=1;
					  if(empty($data["groupname"])){
							messagebox("会员组名称不能为空，谢谢!");		
					   }
			 if($_POST["yyact"]=="add"){
			        $check=$this->db->GetCount("select count(*) from `#yunyecms_membergroup`  where isdefault=1");
				    if($check>=1){
					  	if($data["isdefault"]==1){
							messagebox("您只能设置一个默认会员组，谢谢!");		
						}
					}
				 	$checknm=$this->db->GetCount("select count(*) from `#yunyecms_membergroup`  where isvisitor=1");
				    if($checknm>=1){
					  	if($data["isvisitor"]==1){
							messagebox("您只能设置一个游客会员组，谢谢!");		
						}
					}
					 $retres=$this->db->insert($data);
					 if($retres){
								$doing="添加会员组—".$data["groupname"];
								$yyact="Add_MemberGroup";
								insert_admlogs($doing,$yyact);
								messagebox("添加会员组成功！",url_admin('init'),"success");
					 }else{
								messagebox("添加会员组失败！",url_admin('init'),"error");
					 }
			  }
		      if($_POST["yyact"]=="edit"){
					   $id=$_POST["id"];
					   if(!$this->check_exist($id)){
							messagebox("该会员组不存在！",url_admin('init'),"warn");
					   }
				    $groupdefault=$this->db->find("select * from `#yunyecms_membergroup`  where isdefault=1");
			        $check=$this->db->GetCount("select count(*) from `#yunyecms_membergroup`  where isdefault=1");
				    if($check>=1){
					  	if($data["isdefault"]==1){
							if($groupdefault["id"]!=$id){
							     messagebox("您只能设置一个默认会员组，谢谢!");		
							 }
						}
					}
				    $groupnm=$this->db->find("select * from `#yunyecms_membergroup`  where isvisitor=1");
			        $checknm=$this->db->GetCount("select count(*) from `#yunyecms_membergroup`  where isvisitor=1");				  
				  	 if($checknm>=1){
					  	if($data["isvisitor"]==1){
							if($groupnm["id"]!=$id){
							     messagebox("您只能设置一个游客会员组，谢谢!");		
							 }
						}
					}
					   $retres=$this->db->update($data,"id={$id}","membergroup");
						if($retres){
									$doing="更新会员组—".$data["groupname"];
									$yyact="Update_MemberGroup";
									insert_admlogs($doing,$yyact);
									messagebox("会员组更新成功！",url_admin('init'),"success");
						 }else{
									messagebox("会员组更新失败！",url_admin('init'),"error");
						 }
			  }			  
		  }
		require tpl_adm('membergroup_add');
	 }
	
	
	public function addpower(){
		  if(!getroot('users','role')){
			  messagebox(Lan('no_permission'),'back',"warn");			
		   }
		 if(!empty($_GET["id"])){
			$parnav='<li><a href=\"'.url_admin('init','member','').'\" target=\"maincontent\">会员管理</a></li><li><a href=\"'.url_admin('init','membergroup','').'\" target=\"maincontent\">会员组管理</a></li><li class=\"active\">权限修改</li>';
			$roleid=trim($_GET["id"]);
			 if(!is_numeric($roleid)){
			     messagebox(Lan('id_notnumber'),url_admin('init'),"warn");
			 }
			 $crole=$this->db->find("select * from `#yunyecms_membergroup` where `id`= {$roleid}");
			 if(empty($crole)){
				  messagebox("该会员组不存在！",url_admin('role_add','membergroup',array('id'=>$roleid)),"warn");			
			  }else{
				 $powersarr=array();
				 $powers=yunyecms_strrange_decode($crole["powers"],$crole["salt"],$crole["range"]);
				 if(!empty($powers)){
					   $powersarr=json_decode($powers,true);
					 }
				  }
		    $yyact="edit";
			}else{
		    $yyact=yyact_get("add");
			$parnav='<li><a href=\"'.url_admin('init','member','').'\" target=\"maincontent\">会员管理</a></li><li><a href=\"'.url_admin('init','membergroup','').'\" target=\"maincontent\">会员组管理</a></li><li class=\"active\">增加权限</li>';
				}
	       if(isset($_POST["yyact"])){
				 $groupname=$_POST["groupname"];
				 if(array_key_exists("powers",$_POST)){
					 $powers=$_POST["powers"];
					 }else{
				   $powers=NULL;
				  }
			if($_POST["yyact"]=="add"){
				   $this->add_member_power($groupname,$powers);
			  }
		    if($_POST["yyact"]=="edit"){
			       $id=$_POST["id"];
			       $oldgroupname=$_POST["oldgroupname"];
				   $this->edit_member_power($id,$groupname,$oldgroupname,$powers);
			  }			  
		  }
		require tpl_adm('membergroup_poweradd');
	 }
		
	
	 public function categorypower(){
		  if(!getroot('users','role')){
			  messagebox(Lan('no_permission'),'back',"warn");			
		   }
		 if(!isset($_POST["yyact"])){ 
			  if(!empty($_GET["id"])){
				$parnav='<li><a href=\"'.url_admin('init','member','').'\" target=\"maincontent\">会员管理</a></li><li><a href=\"'.url_admin('init','membergroup','').'\" target=\"maincontent\">栏目权限</a></li><li class=\"active\">权限修改</li>';
				 $roleid=trim($_GET["id"]);
				 if(!is_numeric($roleid)){
					 messagebox(Lan('id_notnumber'),url_admin('init'),"warn");
				 }
				 $crole=$this->db->getbyid($roleid,'membergroup','id');
				 if(empty($crole)){
					 messagebox("该会员组不存在",url_admin('init','membergroup'),"warn");			
				  }else{
						 $powercatarr=array();
						 if(!empty($crole["powercat"])){
						   $powercat=yunyecms_strdecode($crole["powercat"]);
						   $powercatarr=unserialize($powercat);
						 }
					  }
				$list=$this->db->select("select c.* from `#yunyecms_category` as c inner join `#yunyecms_model`  m on c.modelid=m.modelid   where c.pid=0 and m.modeltype in(1,2,3) order by  c.`ordernum` asc");
				$yyact="edit";
				}else{
				  messagebox("参数错误",'back',"warn");			
				}
		     }else{
				     $groupname=usafestr($_POST["groupname"]);
					 if(array_key_exists("powercat",$_POST)){
						 $powercat=$_POST["powercat"];
						 }else{
					   $powercat=NULL;
					  }
				if($_POST["yyact"]=="edit"){
					        $id=$_POST["id"];
							 if(!is_numeric($id)){
								  messagebox(Lan('id_notnumber'),url_admin('init'),"warn");
							 }
				             $crole=$this->db->getbyid($id,'membergroup','id');;
							 if(empty($crole)){
								 messagebox("会员组不存在",url_admin('addpower','membergroup',array('id'=>$roleid)),"warn");		
							  }else{
								     $powersarr=array();
									 if(!empty($crole["powers"])){
									 $powers=yunyecms_strrange_decode($crole["powers"],$crole["salt"],$crole["range"]);
									 $powersarr=json_decode($powers,true);
									 }	 
								  }
						   if(empty($powersarr["info"])){
							    messagebox("请先在权限设置里面配置信息管理权限",url_admin('addpower','membergroup',array('id'=>$id)),"warn");
						    }elseif(empty($powersarr["info"]['browse'])&&empty($powersarr["info"]['add'])&&empty($powersarr["info"]['edit'])&&empty($powersarr["info"]['del'])){
							    messagebox("请先在权限设置里面配置信息管理权限",url_admin('addpower','membergroup',array('id'=>$id)),"warn");
						    }
					    
					    if(!empty($powercat)){
							foreach($powercat as $key=>$var){
								if(!empty($var['view'])){
								   $checkview[]=$var['view'];
								}
								if(!empty($var['add'])){
								   $checkadd[]=$var['add'];
								}
								if(!empty($var['edit'])){
								   $checkedit[]=$var['edit'];
								}
								if(!empty($var['delete'])){
								   $checkdelete[]=$var['delete'];
								}
							}
							
							if(empty($powersarr["info"]['view'])){
                               if(!empty($checkview)){
							       messagebox("该用户不能设置栏目内容查看权限，您必须先在权限设置里面为该用户开通信息查看权限",'back',"warn",'','',5000);
							    }
							}	
							if(empty($powersarr["info"]['add'])){
                               if(!empty($checkadd)){
							       messagebox("该用户不能设置内容投稿权限，您必须先在权限设置里面为该用户开通内容投稿权限",'back',"warn",'','',5000);
							    }
							}
							if(empty($powersarr["info"]['edit'])){
                               if(!empty($checkedit)){
							       messagebox("该用户不能设置内容编辑权限，您必须先在权限设置里面为该用户开通内容编辑权限",'back',"warn",'','',5000);
							    }
							}	
							if(empty($powersarr["info"]['del'])){
                               if(!empty($checkdelete)){
							       messagebox("该用户不能设置栏目内容删除权限，您必须先在权限设置里面为该用户开通内容删除权限",'back',"warn",'','',5000);
							    }
							}								
						 }else{
							    //messagebox("您至少应该选择一项栏目内容管理权限");
						 }
					   $oldgroupname=usafestr($_POST["oldgroupname"]);
					   $this->edit_member_categorypower($id,$groupname,$oldgroupname,$powercat);
				  }	
		 }

		require tpl_adm('category_member_power');
	 }		
	
	
	private function add_member_power($groupname,$powers) {
		 $groupname=usafestr(trim($groupname));
		 $salt=make_rand(20);
		 $range['md5']['min']=mt_rand(0,10);
		 $range['md5']['max']=mt_rand(1,22);
		 $range['sha1']['min']=mt_rand(0,15);
		 $range['sha1']['max']=mt_rand(1,25);
		 $rangearr=yunyecms_json_encode($range);
		 $powers=yunyecms_strrange_encode(json_encode($powers),$salt,$rangearr);
		 if(empty($groupname)){
			   messagebox("会员组名不能为空",url_admin('addpower','',''),"error");			
			 }
		 	if(empty($powers)){
			    messagebox("权限不能为空",url_admin('addpower','',''),"error");			
			 }
		 if($this->checkrole_exist($groupname)){
				       messagebox("该会员组已存在",url_admin('addpower','',''),"warn");			
					}else{
				    $strsql="insert into `#yunyecms_membergroup`(`groupname`,`powers`,`salt`,`range`) values('$groupname','$powers','$salt','$rangearr')";
					$query=$this->db->query($strsql);
	                $roleid=$this->db->insert_id();
					if($roleid){
				        messagebox("会员组权限添加成功",url_admin('init'),"success");			
					}
		    }
	 }	
	private function edit_member_power($id,$groupname,$oldgroupname,$powers){
		 $groupname=usafestr(trim($groupname));
		 $oldgroupname=usafestr(trim($oldgroupname));
		 $id=usafestr(intval(trim($id)));
		 if(empty($groupname)||empty($id)){
			   messagebox("会员组名不能为空",url_admin('addpower','membergroup',array('id'=>$id)),"warn");				
			 }
		   if(!is_numeric($id)){
				 messagebox(Lan('id_notnumber'),url_admin('init'),"warn");
						 }
			 if(empty($powers)){
			   messagebox("权限不能为空",url_admin('addpower','membergroup',array('id'=>$id)),"error");			
			 }
			   $salt=make_rand(20);
			   $range['md5']['min']=mt_rand(0,10);
			   $range['md5']['max']=mt_rand(1,22);
			   $range['sha1']['min']=mt_rand(0,15);
			   $range['sha1']['max']=mt_rand(1,25);
		       $rangearr=yunyecms_json_encode($range);
		       $powers=yunyecms_strrange_encode(json_encode($powers),$salt,$rangearr);
		       if($groupname!=$oldgroupname){
			   $num=$this->db->GetCount("select count(*) as total from `#yunyecms_membergroup` where groupname='$groupname' and id<>$id limit 1");
			   if($num){ messagebox("该用户组已存在",url_admin('addpower','',''),"warn");}
				   }
				$strsql="update `#yunyecms_membergroup`  set `groupname`='$groupname',`powers`='{$powers}',`salt`='{$salt}',`range`='{$rangearr}' where id=$id";
				$query=$this->db->query($strsql);
				 if($query){
					 messagebox("会员组权限设置成功",url_admin('init'),"success");			
					}
	     }
	
	private function edit_member_categorypower($id,$groupname,$oldgroupname,$powercat){
		 $groupname=usafestr(trim($groupname));
		 $oldgroupname=usafestr(trim($oldgroupname));
		 $id=usafestr(intval(trim($id)));
		 if(empty($groupname)||empty($id)||!is_numeric($id)){
			   messagebox("权限不能为空",url_admin('addpower','membergroup',array('id'=>$id)),"error");			
			 }
			 if(empty($powercat)){
			 //  messagebox("权限不能为空",url_admin('categorypower','membergroup',array('id'=>$id)),"error");		
			 }
		       $powercat=yunyecms_strencode(serialize($powercat));
		       if($groupname!=$oldgroupname){
			   $num=$this->db->GetCount("select count(*) as total from `#yunyecms_membergroup` where groupname='$groupname' and id<>$id limit 1");
			   if($num){ messagebox("该用户组已存在",url_admin('categorypower','',''),"warn");}
				   }
				$strsql="update `#yunyecms_membergroup`  set `groupname`='$groupname',`powercat`='{$powercat}' where id=$id";
				$query=$this->db->query($strsql);
				 if($query){
					 messagebox("会员信息栏目权限设置成功",url_admin('init'),"success");			
					}
	     }		
	
  public function finaldelete() {
		  if(!getroot('info','del')){
			    messagebox(Lan('no_permission'),'back');			
		   }
            $id = $_REQUEST["id"];
			$id=yytrim($id);
			if(!is_array($id)){
			  $id=compact('id');
			}
			$idarray=$id;
            if(isset($idarray)){
				       foreach($idarray as $key=>$var){
				 		if(!is_numeric($var)){
					        messagebox("错误的参数！",'back',"warn");			
					    }
				        $idarray[$key]=usafestr($var);
						}
				 $idarray=implode(",",$idarray);
				 $retres =$this->db->delete("id in ({$idarray})","membergroup");
                if ($retres !== false) {
						$yyact="Notice_Del";
						$logcontent['tablename']="membergroup";
						$logcontent['action']=$yyact;
						$logcontent['ids']=serialize($id);
						$logcontent=serialize($logcontent);
						$doing="删除会员组：{$idarray} ";
						insert_admlogs($doing,$yyact,$logcontent);
				    messagebox(Lan('admin_delete_success'),$_SERVER['HTTP_REFERER'],"success");
                } else {
				    messagebox(Lan('admin_delete_error'),$_SERVER['HTTP_REFERER'],"warn");
                }
            } else {
				    messagebox(Lan('admin_delete_error'),$_SERVER['HTTP_REFERER'],"warn");
            }
    }	
	
	
    public function check(){
        parent::infocheck("membergroup",$this->db);
    }	
	
    public function nocheck() {
        parent::infonocheck("membergroup",$this->db);
    }	
	
	private function checkrole_exist($groupname) {
		$groupname =  usafestr(trim($groupname));
		 if(empty($groupname)){
		     return false;
			 }else{
			  if ($this->db->find("select `rolename` from `#yunyecms_membergroup` where `groupname`= '{$groupname}'")){
				  return true;
			  }				 
		  }
	  }
	
	private function check_exist($id) {
		 $id = trim($id);
		 if(empty($id)){
		     return false;
			 }else{
			    if(!is_numeric($id)){
					  return false;
				 }
			  if ($this->db->find("select count(*) as cnt from `#yunyecms_membergroup` where `id`= {$id}")){
				  return true;
			  }				 
		  }
	  }	

	 
}
?>
