<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// Copyright (C) 2003, 2005 Barnraiser
// http://www.barnraiser.org/
// info@barnraiser.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, 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 program; see the file COPYING. If not, write to the Free
// Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
// 02111-1307, USA.
// -----------------------------------------------------------------------



class GroupAdmin {
	// CLASS FUNCTIONS
	// GroupAdmin
	// createGroup
	// insertGroup
	// insertGroupAdministrator
	// insertAcsRoles (should be moved to ACS class)
	// setGroupStatus
	// sendMessages ('get user_id for roles' section of this function should move to ACS class)
	// deleteGroup
	// getAllGroups
	// getCountMembers
	// updateAdminGroup
	
	
	
	// GroupAdmin --------------------------------------------------------------------
	// the constuctor
	// tom calthrop - 5th December 2004
	//
	function GroupAdmin($db, $me) {
		$this->db = $db;
		$this->me = $me;
	} //EO GroupAdmin
	
	
	
	// createGroup --------------------------------------------------------------------
	// creates a group
	// tom calthrop - 5th December 2004
	//
	function createGroup() {
		$this->insertGroup(); //ok
		
		if (isset($this->group_id)) {
			$this->insertAcsRoles();
			$this->insertGroupAdministrator();
			
			//set status_id and send messages if required
			if ($this->data['group_visibility'] == "1") { // visible
				if ($this->setup['allow_auto_visible_approval'] != 1) {
				    $this->setGroupStatus($this->status_ids['pending']);
					$this->sendMessages();
					return 1;
				}
				else { //got to group
					$this->setGroupStatus($this->status_ids['active']);
					//header("Location: g_group.php?group_id=" . $this->group_id . "&" . SID);
					return 2;
				}
			}
			elseif ($this->data['group_visibility'] != "1") { // visible
				if ($this->setup['allow_auto_hidden_approval'] != 1) {
					$this->setGroupStatus($this->status_ids['pending']);
				    $this->sendMessages();
					return 1;
				}
				else { //go to group
					$this->setGroupStatus($this->status_ids['active']);
					//header("Location: g_group.php?group_id=" . $this->group_id . "&" . SID);
					return 2;
				}
			}
		}
	}//EO createGroup
	
	
	
	// insertGroup --------------------------------------------------------------------
	// insert group into DB
	// tom calthrop - 5th December 2004
	//
	function insertGroup() {
		$data = $this->data;
		
		//insert the group (make inactive if awaiting admin approval)
		if (empty($data['group_from_age']) || $data['group_from_age'] <= 0) {
		    $data['group_from_age'] = "null";
		}
	
		if (empty($data['group_to_age']) || $data['group_to_age'] <= 0) {
		    $data['group_to_age'] = "null";
		}
		
		if ($data['group_visibility'] == "1") { // visible
			$group_rules = $this->lang['txt_group_visible_rules'];
			$group_visibility = 1;
		}
		else {
		    $group_rules = $this->lang['txt_group_hidden_rules'];
			$group_visibility = "null";
		}
	
		if (empty($data['group_registration_type']) || $data['group_registration_type'] <= 0) {
		    $data['group_registration_type'] = "null";
		}
		
		//insert group
		$rec = array();
		$rec['group_title'] = $data['group_title'];
		$rec['group_synopsis'] = $data['group_synopsis'];
		$rec['group_home_synopsis'] = $data['group_synopsis'];
		$rec['group_rules'] = $data['group_rules'];
		$rec['language_id'] = $data['language_id'];
		$rec['group_create_datetime'] = time();
		$rec['group_registration_type'] = $data['group_registration_type'];
		$rec['group_from_age'] = $data['group_from_age'];
		$rec['group_to_age'] = $data['group_to_age'];
		$rec['user_id'] = $this->me['user_id'];
		$rec['group_file_allocation'] = $this->group_file_allocation;
		$rec['group_visibility'] = $group_visibility;
		
		$table = $this->db->prefix . "_group";
			
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
		
		if (isset($result)) {
		    //we get the insert ID
			$this->group_id = $this->db->Insert_ID();
		}
		else {
			$error_info = "function=insertGroup class=GroupAdmin.class.php -- " . $query . " -- " . $this->db->ErrorMsg();
			$GLOBALS['am_error_log'][] = array(1, 1, $error_info);
		}
	}//EO insertGroup
	
	
	
	// insertGroupAdministrator --------------------------------------------------------------------
	// insert group administrator into DB
	// tom calthrop - 5th December 2004
	//
	function insertGroupAdministrator() {
		
		$rec = array();
		$rec['group_id'] = $this->group_id;
		$rec['role_id'] = $this->role_id;
		$rec['membership_create_datetime'] = time();
		$rec['user_id'] = $this->me['user_id'];
		$rec['status_id'] = $this->member_status_ids['active'];
		$rec['profile_id'] = $this->profile_id;
		$rec['node_id'] = $this->node_id;
		
		$table = $this->db->prefix . "_group_membership";
		
		$query = $this->db->GetInsertSQL($table, $rec, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	}//EO insertGroupAdministrator
	
	
	
	// insertAcsRoles --------------------------------------------------------------------
	// insert default ACS roles into DB
	// tom calthrop - 5th December 2004
	//
	function insertAcsRoles() {
		$this->acs->group_id = $this->group_id;
		
		//insert roles
		foreach($this->default_acs_ids['section_role'][2] as $key => $i):
			$role_name_array = array("role_name" => $this->default_acs_role_names[$i]);
			
			if ($i == $this->default_acs_ids['arr_acs']['group_join_role_default']) {
			    $this->acs->insertGroupRole($role_name_array, 1);
			}
			else {
				$this->acs->insertGroupRole($role_name_array);
			}
			
			
		endforeach;
		
		//get the roles
		$group_roles = $this->acs->getGroupRoles();
		
		//get admin role_id
		foreach($group_roles as $key => $i):
			if ($this->default_acs_role_names[$this->default_acs_ids['arr_acs']['group_administrator_role']] == $i['role_name']) {
			    $role_id = $i['role_id'];
				$this->role_id = $role_id; //needed for inserting administrator
			}
		endforeach;
		
		//insert permissions
		foreach($this->default_acs_ids['section_resource'][2] as $key => $i):
			$resource_id = $i;
			$privs = $this->default_acs_ids['resource_privilege'][$i];
			
			foreach($privs as $key => $r):
				$this->acs->insertPermission($role_id, $i, $r); //role, resource, privilege
			endforeach;
		endforeach;
	}//EO insertAcsRoles
	
	
	
	// setGroupStatus --------------------------------------------------------------------
	// sets the groups staus (active, pending, inactive, hold)
	// tom calthrop - 5th December 2004
	//
	function setGroupStatus($status_id) {
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_group 
			WHERE 
			group_id=" . $this->group_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['status_id'] = $status_id;
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
	}//EO setGroupStatus
	
	
	
	// sendMessages --------------------------------------------------------------------
	// sends messages to anyone who has node priv to edit groups
	// tom calthrop - 5th December 2004
	//
	function sendMessages() {
		$admin_message_text = $this->admin_message_text;
		$admin_message_text = str_replace("\\\"", "\"", $admin_message_text);
		$admin_message_text = str_replace("ID_OF_GROUP", $this->group_id, $admin_message_text);
		$admin_message_text = str_replace("NOTE", $this->data['note'], $admin_message_text);
		
		//get node roles where they have priv to edit groups
		$query = "
			SELECT role_id
			FROM " . $this->db->prefix . "_acs_permission 
			WHERE 
	 		privilege_id=" . $this->default_acs_ids['arr_acs']['privilege']['allow_edit_group']
		;
		
		$result = $this->db->Execute($query);

		if (isset($result->fields)) {
			$role_ids = "";
			while (!$result->EOF) {
				$role_ids .= $result->fields['role_id'] . ",";
				$result->MoveNext();
			}
			
			$result->Close();
		}
		
		//get the user id's for users with these roles and send message
		if (isset($role_ids)) {
			$role_ids = substr($role_ids, 0, strlen($role_ids)-1); //trim off the last comma
			
			$query1 = "
				SELECT distinct user_id
				FROM " . $this->db->prefix . "_user 
				WHERE 
		 		role_id in(" . $role_ids . ")"
			;
			
			$result1 = $this->db->Execute($query1);

			if (isset($result1)) {
				while (!$result1->EOF) {
					$this->im->sendMessage($result1->fields['user_id'], "group application", $admin_message_text);
					$result1->MoveNext();
				}

				$result1->Close();
			}
		}
	}//EO sendMessages
	
	
	
	// deleteGroup --------------------------------------------------------------------
	// deletes group from db
	// tom calthrop - 5th December 2004
	//
	function deleteGroup($group_id) {
		$query = "
			DELETE FROM " . $this->db->prefix . "_group
			WHERE
			group_id=" . $group_id
		;
		
		$result = $this->db->Execute($query);
		$result->Close();
		
		header("Location: node_admin.php?list_groups=1"."&amp;".SID);
		exit;

	}//EO deleteGroup;
	
	
	
	// getAllGroups --------------------------------------------------------------------
	// returns all rows from groups - only use if in admin section
	// tom calthrop - 7th December 2004
	//
	function getAllGroups() {
		
		$query = "
			SELECT g.group_id, g.group_title, g.group_synopsis,
			g.group_from_age, g.group_to_age, g.group_create_datetime, 
			g.group_registration_type, g.status_id, g.group_election_date 
			FROM " . $this->db->prefix . "_group g 
			order by g.group_id";
		;
		
		$result = $this->db->Execute($query);
		
		if (isset($result->fields)) {

			$temp = array();

			while (!$result->EOF) {
				$temp1 = $result->fields;
				$temp1['display_group_create_datetime'] = $this->date->formatDate($temp1['group_create_datetime']);
				$temp1['display_group_election_date'] = $this->date->formatDate($temp1['group_election_date']);
				$temp1['group_total_members'] = $this->getCountMembers($temp1['group_id']);
			
				array_push($temp, $temp1);
				$result->MoveNext();
			}

			$result->Close();
			return $temp;
		}
		else {
			$GLOBALS['am_error_log'][] = array(1, 1, $query . "-" . $this->db->ErrorMsg());
		}
	}//EO getGroups;
	
	
	
	// getCountMembers --------------------------------------------------------------------
	// returns all rows from groups - only use if in admin section
	// tom calthrop - 7th December 2004
	//
	function getCountMembers($group_id) {

		$query = "
			SELECT count(membership_id) as total
			FROM " . $this->db->prefix . "_group_membership 
			WHERE
			group_id=" . $group_id . " and
			status_id=" . $this->member_status_id
		;
		
		$result = $this->db->Execute($query);
	
		if (isset($result->fields)) {
		
			if (isset($result->fields['total']) && $result->fields['total'] > 0) {
			    $total = $result->fields['total'];
			}
			else {
				$total = 0;
			}
			
			$result->Close();
			
			return $total;
		}
		else {
			$GLOBALS['am_error_log'][] = array(1, 1, $query . "-" . $this->db->ErrorMsg());
		}
	}//EO getCountMembers();
	
	
	
	// updateAdminGroup --------------------------------------------------------------------
	// update administration columns in group
	// tom calthrop - 23rd Nov 2004
	//
	function updateAdminGroup($data) {
		
		if (isset($_POST['year'])) {
		    $group_election_date = "'" . $_POST['year']."-".$_POST['month']."-".$_POST['day'] . "'";
		}
		else {
			$group_election_date = "null";
		}
		
		if (isset($data['group_visibility']) && $data['group_visibility'] == 1) {
		    $group_visibility = 1;
		}
		else {
			$group_visibility = "null";
		}
		
		if (isset($data['group_file_allocation']) && $data['group_file_allocation'] > 0) {
		    $group_file_allocation = $data['group_file_allocation'];
		}
		else {
			$group_file_allocation = "null";
		}
		
		$query = "
			SELECT * FROM " . $this->db->prefix . "_group 
			WHERE 
			group_id=" . $this->group_id
		;
		
		$result = $this->db->Execute($query);
		
		$rec = array();
		$rec['group_election_date'] = $group_election_date;
		$rec['group_visibility'] = $group_visibility;
		$rec['group_file_allocation'] = $group_file_allocation;
		$rec['status_id'] = $data['status_id'];
		
		$query = $this->db->GetUpdateSQL($result, $rec, false, get_magic_quotes_gpc());
		$result = $this->db->Execute($query);
		
	} //EO updateAdminGroup;
}

?>
