<?php
// +-------------------------------------------------------------+
// | HiveMail™ version 1.3.1
// +-------------------------------------------------------------+
// | HIVEMAIL™ IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than Hivemail or if you have otherwise received
// | this software from someone who is not a representative of
// | this organization you are involved in an illegal activity.
// +-------------------------------------------------------------+
// | $RCSfile: addbook.php,v $ - $Revision: 1.15 $
// | $Date: 2004/08/03 04:28:44 $ - $Author: tubedogg $
// +-------------------------------------------------------------+

error_reporting(E_ALL & ~E_NOTICE);
require_once('./global.php');
cp_header(' &raquo; Global Address Book', true, true, '<script type="text/javascript" src="../misc/checkall.js"></script>');
cp_nav('userbook');

// ############################################################################
// Set the default cmd
default_var($cmd, 'modify');

// ############################################################################
// Add contacts
if ($_POST['cmd'] == 'doadd') {
	extract($newcontact);
	if (!is_email($email)) {
		adminlog(0, false);
		cp_error('You must provide a valid email address.');
	} elseif (empty($name)) {
		$name = $email;
	}

	if (is_array($_POST['newcontact']['usergroups'])) {
		$ugs = implode(',', $_POST['newcontact']['usergroups']).',0';
	}


	// Create contact
	$DB_site->query('
		INSERT INTO hive_contact
		SET contactid = NULL, email = "'.addslashes($email).'", name = "'.addslashes($name).'", userid = 0, usergroupids = "'.addslashes($ugs).'", timezone = -13, emailinfo = "a:0:{}", nameinfo = "a:0:{}", addressinfo = "a:0:{}", phoneinfo = "a:0:{}"
	');

	adminlog($DB_site->insert_id(), true);
	cp_redirect('The contact has been added to the address book.', 'addbook.php');
}

// ############################################################################
// Add contacts
if ($_REQUEST['cmd'] == 'add') {
	startform('addbook.php', 'doadd', '', array('newcontact_name' => 'name', 'newcontact_email' => 'email'));
	starttable('Create New Global Address Book Entry', '500');
	inputfield('Full name:', 'newcontact[name]');
	inputfield('Email address:', 'newcontact[email]');
	$checkboxes = '';
	$theclass = getclass();
	$groups = $DB_site->query('SELECT * FROM hive_usergroup');
	while ($group = $DB_site->fetch_array($groups)) {
		$checkboxes .= "<input type=\"checkbox\" name=\"newcontact[usergroups][]\" class=\"radio_$theclass\" id=\"group_$group[usergroupid]\" value=\"$group[usergroupid]\" checked=\"checked\"";
		$checkboxes .= " /> <label for=\"group_$group[usergroupid]\">$group[title]</label><br />\n";
	}
	echo "	<tr class=\"$theclass\">\n";
	echo "		<td valign=\"top\">Usergroup permissions: <a href=\"#\" onClick=\"alert('Only the groups you select here will be able to see this contact in their address book. You can modify permissions for a contact at any time.'); return false;\"><img src=\"../images/help.gif\" border=\"0\" /></a></td>\n";
	echo "		<td valign=\"top\">$checkboxes</td>\n";
	echo "	</tr>\n";

	endform('Create contact');
	endtable();
}

// ############################################################################
// Kill contacts
if ($_POST['cmd'] == 'kill') {
	// Delete contacts
	$DB_site->query('
		DELETE FROM hive_contact
		WHERE contactid IN ('.$deleteids.') AND userid = 0
	');

	adminlog(0, true, 'kill', 'Deleted contacts: '.$deleteids);
	cp_redirect('The selected contacts were removed from the address book.', 'addbook.php');
}

// ############################################################################
// Remove contacts
if ($_REQUEST['cmd'] == 'remove') {
	$deleteids = array();
	$rows = array();
	if (is_array($_REQUEST['contact_select'])) {
		foreach ($_REQUEST['contact_select'] as $contactid => $doit) {
			if ($doit == 'yes') {
				$contact = getinfo('contact', $contactid, false, true, false);
				$rows[] = $contact['name'].' ('.$contact['email'].')';
				$deleteids[] = $contactid;
			}
		}
	} else {
		$contact = getinfo('contact', $contactid);
		$rows[] = $contact['name'].' ('.$contact['email'].')';
	}

	adminlog(0, false, 'remove', implode(', ', $deleteids));
	startform('addbook.php', 'kill', 'Are you sure you want to remove '.iif(count($deleteids) > 1, 'these entries', 'this entry').'?');
	starttable('Remove Global Address Book '.iif(count($deleteids) > 1, 'Entries', 'Entry'));
	textrow('Are you <b>sure</b> you want to remove the following Global Address Book '.iif(count($deleteids) > 1, 'entries', 'entry').'? This procedure <b>cannot</b> be reversed!');
	foreach ($rows AS $row) {
		echo "	<tr class=\"".getclass()."\">\n";
		echo "		<td colspan=\"2\">$row</td>\n";
		echo "	</tr>\n";
	}
	hiddenfield('deleteids', implode(', ', $deleteids));
	endform('Remove Global Address Book '.iif(count($deleteids) > 1, 'Entries', 'Entry'), '', 'Go Back');
	endtable();
}


// ############################################################################
// Update or delete contacts
if ($_POST['cmd'] == 'update') {
	foreach ($contact_emails as $contactid => $email) {
		$name = $contact_names["$contactid"];

		if (empty($name)) {
			$name = $email;
		}

		// Delete or update
		if (empty($email)) {
			$DB_site->query('
				DELETE FROM hive_contact
				WHERE contactid = '.intval($contactid).' AND userid = 0
			');
		} elseif (is_email($email)) {
			$DB_site->query('
				UPDATE hive_contact
				SET email = "'.addslashes($email).'", name = "'.addslashes($name).'"
				WHERE contactid = '.intval($contactid).' AND userid = 0
			');
		}
	}

	adminlog(0, true);
	cp_redirect('The address book has been saved.', 'addbook.php');
}

// ############################################################################
// Save permission changes
if ($_POST['cmd'] == 'doeditperms') {
	$todelete = array();
	foreach ($_POST['contact'] as $contactid => $info) {
		if ($info['delete'] == 'yes') {
			$todelete[] = $contactid;
		} else {
			$info['usergroupids'] = addslashes(implode(',', $info['usergroupids']).',0');
			if (empty($info['email']) or empty($info['name'])) {
				cp_error('You did not specify a name and/or email address for contact #. A contact must contain, at a minimum, a name and email address. Please press back to correct the error.');
			}
			$info['name'] = addslashes($info['name']); $info['email'] = addslashes($info['email']);
			$DB_site->auto_query('contact', $info, 'contactid = '.intval($contactid).' AND userid = 0');
		}
	}
	if (!empty($todelete)) {
		$todelete = '('.implode(',', $todelete).')';
		$DB_site->query('
			DELETE FROM hive_contact
			WHERE contactid IN '.$todelete.' AND userid = 0
		');
	}
	cp_redirect('The Global Address Book has been updated.', 'addbook.php');
}


// ############################################################################
// Edit permissions
if ($_REQUEST['cmd'] == 'editperms') {
	$contacts = array();
	foreach ($_REQUEST['contact_select'] as $contactid => $doit) {
		if ($doit == 'yes') {
			$contact = getinfo('contact', $contactid, false, true, false);
			$contacts["$contactid"] = $contact;
		}
	}

	$grou = $DB_site->query('SELECT * FROM hive_usergroup');
	while ($group = $DB_site->fetch_array($grou)) {
		$groups["$group[usergroupid]"] = $group['title'];
	}

	startform('addbook.php', 'doeditperms');

	foreach ($contacts as $contactid => $contactinfo) {
		starttable('Edit Global Address Book Entry "'.$contactinfo['name'].'" (ID: '.$contactid.')');
		inputfield('Full name:', "contact[$contactid][name]", $contactinfo['name']);
		inputfield('Email address:', "contact[$contactid][email]", $contactinfo['email']);
		if (!empty($contactinfo['usergroupids'])) {
			$ugroups = explode(',', $contactinfo['usergroupids']);
		} else {
			$ugroups = array();
		}
		$checkboxes = '';
		$theclass = getclass();
		foreach ($groups as $groupid => $title) {
			$checkboxes .= "<input type=\"checkbox\" name=\"contact[$contactid][usergroupids][]\" class=\"radio_$theclass\" id=\"$contactid_group_$groupid\" value=\"$groupid\"";
			if (in_array($groupid, $ugroups)) {
				$checkboxes .= ' checked="checked"';
			}
			$checkboxes .= " /> <label for=\"$contactid_group_$groupid\">$title</label><br />\n";
		}
		echo "	<tr class=\"$theclass\">\n";
		echo "		<td valign=\"top\">Usergroup permissions: <a href=\"#\" onClick=\"alert('Only the groups you select here will be able to see this contact in their address book. You can modify permissions for a contact at any time.'); return false;\"><img src=\"../images/help.gif\" border=\"0\" /></a></td>\n";
		echo "		<td valign=\"top\">$checkboxes</td>\n";
		echo "	</tr>\n";
		$theclass = getclass();
		echo "  <tr class=\"$theclass\">\n";
		echo "		<td valign=\"top\">Delete contact:<br /><span class=\"cp_small\">Check the box to delete this contact when you click Update Contacts.</span></td>\n";
		echo "		<td valign=\"top\"><input type=\"checkbox\" name=\"contact[$contactid][delete]\" class=\"radio_$theclass\" id=\"$contactid_delete\" value=\"yes\" /> <label for=\"$contactid_delete\">Yes, delete this contact</label></td>\n";
		echo "	</tr>\n";
		tablehead(array('<input class="button" type="submit" value="  Update Contacts  " />&nbsp;<input class="button" type="reset" value="  Reset Fields  " />'), 2);
		endtable();
	}
	endform();
}


// ############################################################################
// Show address book
if ($cmd == 'modify') {
	adminlog();

	?><script language="JavaScript">
	<!--
	function popEdit(contactID) {
		var hWnd = window.open("../addressbook.update.php?cmd=edit&contactid="+contactID, "ContactEdit", "width=650,height=435,resizable=yes,scrollbars=yes");
		if ((document.window != null) && (!hWnd.opener)) {
			hWnd.opener = document.window;
		}
	}
	// -->
	</script><?php

	startform('addbook.php', 'update');
	$cells = array(
		'Name <span class="cp_small">(click to edit)</span>',
		'Email',
		'<input name="allbox" type="checkbox" value="Check All" title="Select/Deselect All" onClick="checkAll(this.form);" />',
	);
	$contacts = $DB_site->query('
		SELECT *
		FROM hive_contact
		WHERE userid = 0
	');
	if ($DB_site->num_rows($contacts) < 1) {
		starttable('Error', '500');
		tablehead($cells);
		textrow('No contacts found', count($cells), 1);
	} else {
		starttable('Existing Global Address Book Entries', '500');
		tablehead($cells);
		while ($contact = $DB_site->fetch_array($contacts)) {
			$cells = array(
				'<a href="#" onClick="popEdit('.$contact['contactid'].'); return false;">'.htmlchars($contact['name']).'</a>',
				htmlchars($contact['email']),
				'center1' => "<input type=\"checkbox\" name=\"contact_select[$contact[contactid]]\" value=\"yes\" onClick=\"checkMain(this.form);\" />",
			);
			tablerow($cells);
		}
		tablehead(array('<div align="center"><input type="submit" value="  Edit Permissions For Selected  " class="button" onClick="this.form.cmd.value = \'editperms\';" />&nbsp;<input type="submit" value="  Delete Selected  " class="button" onClick="this.form.cmd.value = \'remove\';" /></div>'), count($cells));
	}
	endtable();
	endform();

	button('', 'Create New Global Address Book Entry', "window.location='addbook.php?cmd=add'", true);

	starttable('Help', '500');
	textrow('The <b>global address book</b> in HiveMail&trade; can be used to fill your users\' address books with predefined email addresses that are worth knowing. For example, the webmaster email address for support or feedback about the website. Each contact can be set to only be visible to certain user groups.<br /><br />
	
	To create a new contact, enter their full name and email address in the table above and press Create Contact button. To modify an existing contact, click on their name or email address in the top table and change the information and press the Update Contacts button to submit your changes when you are done. To delete a contact, check the box besides their email address and press the Delete Selected button.<br /><br />
	
	You can set permissions for each contact, so that only the groups you allow will see it in their Address Book. To modify permissions for a contact, select its\' checkbox and press Edit Permissions For Selected.');
	endtable();
}

cp_footer();
?>