<?php

// -----------------------------------------------------------------------
// This file is part of aroundme
// 
// Copyright (C) 2003 - 2006 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., 51 Franklin St, Fifth Floor, Boston, MA
// 02110-1301, USA.
// -----------------------------------------------------------------------



class GroupAdmin extends Group {
	// 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
	// checkGroupUnixTitle
	
	
	
	// 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)) {
			if (!empty($this->data['group_custom_items'])) {
				$this->insertGroupCustomItems($this->data['group_custom_items']);
			}
			$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";
		}
		
		if (empty($data['group_unix_title'])) {
		    $data['group_unix_title'] = "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;
		$rec['group_unix_title'] = $data['group_unix_title'];
		
		$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['group_member_create_datetime'] = time();
		$rec['user_id'] = $this->me['user_id'];
		$rec['status_id'] = $this->member_status_ids['active'];
		$rec['profile_id'] = $this->profile_id;
		
		$table = $this->db->prefix . "_group_member";
		
		$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_role_names as $key => $i):
			$role_name_array = array("role_name" => $i);
			
			
			if ($key == $this->c_acs['arr_acs']['group_join_role_default']) {
				// insert default role
				$this->acs->insertGroupRole($role_name_array, 1);
			}
			elseif ($key == $this->c_acs['arr_acs']['group_join_role_visitor']) {
				// insert visitor role
				$this->acs->insertGroupRole($role_name_array, null, 1);
			}
			else {
				$this->acs->insertGroupRole($role_name_array);
			}
			
			
			// insert permissions for role
			if ($key == $this->default_acs_admin_id) {
				//insert permissions (all permissions for maintainer)
				foreach($this->c_acs['arr_acs']['resource']['group'] as $pkey => $p):
					$resource_id = $p;
					
					if (!empty($this->c_acs['resource_privilege'][$p])) {
						$privs = $this->c_acs['resource_privilege'][$p];
					
						foreach($privs as $rkey => $r):
							$this->acs->insertPermission($this->acs->role_id, $p, $r); //role, resource, privilege
						endforeach;
					}
				endforeach;
				
				$this->role_id = $this->acs->role_id;
			}
			elseif ($key == $this->c_acs['arr_acs']['group_join_role_visitor']) {
				// do nothing
			}
			else {
				//insert permissions
				foreach($this->c_acs['arr_acs']['resource']['group'] as $pkey => $p):
					$resource_id = $p;
					
					if (!empty($this->c_acs['resource_group_create_privilege'][$p])) {
						$privs = $this->c_acs['resource_group_create_privilege'][$p];
						
						foreach($privs as $rkey => $r):
							$this->acs->insertPermission($this->acs->role_id, $p, $r); //role, resource, privilege
						endforeach;
					}
				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("SYS_KEYWORD_GROUP_ID", $this->group_id, $admin_message_text);
		$admin_message_text = str_replace("SYS_KEYWORD_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  
			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['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(group_member_id) as total
			FROM " . $this->db->prefix . "_group_member 
			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;
	
	
	
	// checkGroupUnixTitle --------------------------------------------------------------------
	// checks that the group unix title is unique
	// tom calthrop - 21st Feb 2004
	//
	function checkGroupUnixTitle($group_unix_title) {
		$query = "
			SELECT g.group_id 
			FROM " . $this->db->prefix . "_group g
			where
			g.group_unix_title=" . $this->db->qstr($group_unix_title, get_magic_quotes_gpc())
		;
		
		$result = $this->db->SelectLimit($query, 1);
		
		if (isset($result->fields['group_id'])) {
			return false;
		}
		else {
			return true;
		}
	}//EO checkGroupUnixTitle
}

?>
