<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
//  This program is free software; you can redistribute it and/or modify     //
//  it under the terms of the GNU General Public License as published by     //
//  the Free Software Foundation; either version 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  This program is distributed in the hope that it will be useful,          //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  You should have received a copy of the GNU General Public License        //
//  along with this program; if not, write to the Free Software              //
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //
// Author of File: 							     //
// Kazumi Ono (http://www.mywebaddons.com/ , http://www.myweb.ne.jp/)        //
// ------------------------------------------------------------------------- //
include_once(XOOPS_ROOT_PATH."/class/xoopsobject.php");
class XoopsGroup extends XoopsObject{

	var $admin_right_modules = array();
	var $read_right_modules = array();
	var $read_right_blocks = array();

	function XoopsGroup($id = NULL){
		$this->XoopsObject();
		$this->initVar("groupid", "int", NULL, false);
		$this->initVar("name", "textbox", NULL, true, 100, false);
		$this->initVar("description", "textarea", NULL, true);
		$this->initVar("type", "other", NULL, false);
		if ( !empty($id) ) {
			if ( is_array($id) ) {
				$this->set($id);
			} else {
				$this->load(intval($id));
			}
		}
	}

	function load($groupid) {
		$sql = "SELECT * FROM ".$this->db->prefix("groups")." WHERE groupid=".$groupid."";
		$arr = $this->db->fetchArray($this->db->query($sql));
		$this->set($arr);	
	}

	function setAdminRightModules($arr=array()){
		$this->admin_right_modules = $arr;
	}

	function setReadRightModules($arr=array()){
		$this->read_right_modules = $arr;
	}

	function setReadRightBlocks($arr=array()){
		$this->read_right_blocks = $arr;
	}

	function store(){
		if ( !$this->isCleaned() ) {
			if ( !$this->cleanVars() ) {
				return false;
			}
		}
		foreach ( $this->cleanVars as $k=>$v ) {
			$$k = $v;
		}
		if ( empty($type) ) {
			if ( is_array($this->admin_right_modules) && count($this->admin_right_modules)>0 ) {
				$type = "Admin";
			} else {
				$type = "Custom";
			}
		}
		if ( empty($groupid) ) {
			$groupid = $this->db->genId($this->db->prefix("groups")."_groupid_seq");
			$sql = "INSERT INTO ".$this->db->prefix("groups")." (groupid, name, description, type) VALUES ($groupid, '".$name."', '".$description."','".$type."')";
		}  else {
			$sql = "DELETE FROM ".$this->db->prefix("groups_modules_link")." WHERE groupid=".$groupid."";
        		if ( !$result = $this->db->query($sql) ) {
				exit();
			}
			$sql = "DELETE FROM ".$this->db->prefix("groups_blocks_link")." WHERE groupid=".$groupid."";
        		if ( !$result = $this->db->query($sql) ) {
				exit();
			}
			$sql = "UPDATE ".$this->db->prefix("groups")." SET name='".$name."', description='".$description."', type='".$type."' WHERE groupid=".$groupid."";
		}
		//echo $sql;
		if ( !$result = $this->db->query($sql) ) {
			$this->setErrors("Could not store data in database.");
			return false;
		}
		if ( empty($groupid) ) {
			$groupid = $this->db->getInsertId();
		}
		foreach($this->admin_right_modules as $admin_right_module){
			$sql = "INSERT INTO ".$this->db->prefix("groups_modules_link")." (groupid, mid, type) VALUES ($groupid, $admin_right_module, 'A')";
			$result = $this->db->query($sql);
			$sql = "INSERT INTO ".$this->db->prefix("groups_modules_link")." (groupid, mid, type) VALUES ($groupid, $admin_right_module, 'R')";
			$result = $this->db->query($sql);
		}
		foreach($this->read_right_modules as $read_right_module){
			if ( !in_array($read_right_module, $this->admin_right_modules ) ) {
				$sql = "INSERT INTO ".$this->db->prefix("groups_modules_link")." (groupid, mid, type) VALUES ($groupid, $read_right_module, 'R')";
				$result = $this->db->query($sql);
			}
		}
		foreach($this->read_right_blocks as $read_right_block){
			$sql = "INSERT INTO ".$this->db->prefix("groups_blocks_link")." (groupid, block_id, type) VALUES ($groupid, $read_right_block, 'R')";
			$result = $this->db->query($sql);
		}
		return $groupid;
	}

	function delete(){
		if ( !$result = $this->db->query("DELETE FROM ".$this->db->prefix("groups")." WHERE groupid=".$this->getVar("groupid")."") ) {
			exit();
		}
		$result = $this->db->query("DELETE FROM ".$this->db->prefix("groups_users_link")." WHERE groupid=".$this->getVar("groupid")."");
		$result = $this->db->query("DELETE FROM ".$this->db->prefix("groups_modules_link")." WHERE groupid=".$this->getVar("groupid")."");
		//$result = $this->db->query("DELETE FROM ".$this->db->prefix("groups_cats_link")." WHERE groupid=".$this->getVar("groupid")."");
		$result = $this->db->query("DELETE FROM ".$this->db->prefix("groups_blocks_link")." WHERE groupid=".$this->getVar("groupid")."");
		return true;
	}

	// public static
	function checkRight($which, $id, $groupid=0, $type="R"){
		$db =& Database::getInstance();
		if ( $which == "module" ) {
			$table = "groups_modules_link";
			$column = "mid";
		//} elseif ( $which == "category" ) {
		//	$table = "groups_cats_link";
		//	$column = "category_id";
		} elseif ( $which == "block" ) {
			$table = "groups_blocks_link";
			$column = "block_id";
		}
		$sql = "SELECT COUNT(*) FROM ".$db->prefix($table)." WHERE  type='".$type."'";
		if ( !empty($id) ) {
			$sql .= " AND ".$column."=".$id."";
		}
		if ( is_array($groupid) ) {
			$sql .= " AND (groupid=".$groupid[0]."";
			$size = sizeof($groupid);
			if ( $size > 1 ) {
				for ( $i = 1; $i < $size; $i++ ) {
					$sql .= " OR groupid=".$groupid[$i]."";
				}
			}
			$sql .= ")";
		} elseif ( $groupid != 0 ) {
			$sql .= " AND groupid=".$groupid."";
		} else {
			$grouparray = XoopsGroup::getByType("Anonymous");
			$sql .= " AND groupid=".$grouparray[0]."";
		}
		list($count) = $db->fetchRow($db->query($sql));
		if ( $count > 0 ) {
			return true;
		}
		return false;
	}

	// public static
	function getByUser(&$user, $asobject=false){
		$db =& Database::getInstance();
		$ret = array();
		if ( get_class($user) == "xoopsuser" ) {
			$sql = "SELECT g.* FROM ".$db->prefix("groups")." g LEFT JOIN ".$db->prefix("groups_users_link")." l ON l.groupid=g.groupid WHERE l.uid=".$user->getVar("uid")."";
			$result = $db->query($sql);
			if ( !$db->getRowsNum($result) ) {
				$group_arr = XoopsGroup::getByType("User", true);
				$group_arr[0]->addMember($user);
				if ( $asobject ) {
					$ret[] = $group_arr[0];
				} else {
					$ret[] = $group_arr[0]->getVar("groupid");
				}
			} else {
				while ( $myrow = $db->fetchArray($result) ) {
					if ( $asobject ) {
						$ret[] = new XoopsGroup($myrow);
					} else {
						$ret[] = $myrow['groupid'];
					}
				}
			}
		}
		return $ret;
	}

	// public static
	function getByType($type="", $asobject=false, $sort="groupid", $order="ASC"){
		$db =& Database::getInstance();
		$ret = array();
		$where_query = "";
		if ( !empty($type) ) {
			$where_query = " WHERE type='".$type."'";
		}
		if ( !$asobject ) {
			$sql = "SELECT groupid FROM ".$db->prefix("groups")."".$where_query." ORDER BY $sort $order";
			$result = $db->query($sql);
			while ( $myrow = $db->fetchArray($result) ) {
				$ret[] = $myrow['groupid'];
			}
		} else {
			$sql = "SELECT * FROM ".$db->prefix("groups")."".$where_query." ORDER BY $sort $order";
			$result = $db->query($sql);
			while ( $myrow = $db->fetchArray($result) ) {
				$ret[] = new XoopsGroup($myrow);
			}
		}
		return $ret;
	}

	// public static
	function getAllGroupsList($criteria=array(), $sort="groupid", $order="ASC"){
		$db =& Database::getInstance();
		$ret = array();
		$where_query = "";
		if ( is_array($criteria) && count($criteria) > 0 ) {
			$where_query = " WHERE";
			foreach ( $criteria as $c ) {
				$where_query .= " $c AND";
			}
			$where_query = substr($where_query, 0, -4);
		}
		$sql = "SELECT groupid, name FROM ".$db->prefix("groups")."$where_query ORDER BY $sort $order";
		$result = $db->query($sql);
		while ( $myrow = $db->fetchArray($result) ) {
			$ret[$myrow['groupid']] = $myrow['name'];
		}
		return $ret;
	}

	// public
	function getMembers($asobject=false){
		$ret = array();
		if ( !$asobject ) {
			$sql = "SELECT uid FROM ".$this->db->prefix("groups_users_link")." WHERE groupid=".$this->getVar("groupid")."";
			$result = $this->db->query($sql);
			while ( $myrow = $this->db->fetchArray($result) ) {
				$ret[] = $myrow['uid'];
			}
		} else {
			$sql = "SELECT u.* FROM ".$this->db->prefix("groups_users_link")." l, ".$this->db->prefix("users")." u WHERE l.groupid=".$this->getVar("groupid")." AND u.uid=l.uid";
			$result = $this->db->query($sql);
			while ( $myrow = $this->db->fetchArray($result) ) {
				$obj = new XoopsUser($myrow);
				$ret[] = $obj;
			}
		}
		return $ret;
	}

	// public
	function addMember(&$user){
		if ( get_class($user) == "xoopsuser" ) {
			$this->db->queryF("INSERT INTO ".$this->db->prefix("groups_users_link")." (groupid, uid) VALUES (".$this->getVar("groupid").", ".$user->getVar("uid").")");
			return true;
		}
		return false;
	}

}
?>