<?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: option.php,v $ - $Revision: 1.43.2.1 $
// | $Date: 2004/08/18 16:02:54 $ - $Author: tubedogg $
// +-------------------------------------------------------------+

error_reporting(E_ALL & ~E_NOTICE);
require_once('./global.php');
if ($cmd == 'gateway' or $_POST['cmd'] == 'updatetype' or $gateway) {
	cp_header(' &raquo; Email Gateway');
	cp_nav('emailgateway');
} elseif ($group == 'hivepop3') {
	cp_header(' &raquo; HivePOP3 Options');
	cp_nav('emailhivepop');
} elseif ($group == 'subs') {
	cp_header(' &raquo; Subscription Options');
	cp_nav('suboptions');
} else {
	cp_header(' &raquo; Program Options');
	cp_nav('hiveop');
}

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

// ############################################################################
// Update options
if ($_POST['cmd'] == 'updatevalues') {
	foreach ($options as $varname => $value) {
		if ($value != getop($varname)) {
			switch($varname) {
				case 'supportemail':
					$toupgab1 = array(getop($varname), $value);
					break;
				case 'appname':
					$toupgab2 = $value;
					break;
				default:
					$toupgab1 = null;
					$toupgab2 = null;
			}
			$updated_options .= ",$varname";
			$DB_site->query("
				UPDATE hive_setting
				SET value = '".addslashes($value)."'
				WHERE variable = '".addslashes($varname)."'
			");
		}
	}

	if (is_array($toupgab1)) {
		if ($DB_site->query_first('SELECT * FROM hive_contact WHERE email = "'.addslashes($toupgab1[0]).'" AND userid = 0')) {
			$DB_site->query('
				UPDATE hive_contact
				SET email = "'.addslashes($toupgab1[1]).'"
				WHERE email = "'.addslashes($toupgab1[0]).'"
			');
		} else {
			$usergroupids = implode(',', $_usergroupids).',0';
			$DB_site->query('
				INSERT INTO hive_contact
				SET contactid = NULL, email = "'.addslashes($toupgab1[1]).'", name = "'.addslashes(getop('appname')).' Support", usergroupids = "'.addslashes($usergroupids).'", userid = 0, timezone = -13, emailinfo = "a:0:{}", nameinfo = "a:0:{}", addressinfo = "a:0:{}", phoneinfo = "a:0:{}"
			');
		}
	}
	if ($toupgab2) {
		$DB_site->query('
			UPDATE hive_contact
			SET name = "'.addslashes($toupgab2.' Support').'"
			WHERE email = "'.addslashes(getop('supportemail')).'"
		');
	}

	adminlog(0, true, 'updatevalues', 'Updated options: '.substr($updated_options, 1));
	cp_redirect('The options were successfully updated.', 'option.php?'.iif($gateway, 'cmd=gateway', iif($hivepop, 'cmd=hivepop', iif($subs, 'cmd=subs'))));
}

// ############################################################################
// Display settings
if ($cmd == 'modify') {
	adminlog();

	if (!empty($group)) {
		$groupinfo = $DB_site->query_first("SELECT * FROM hive_settinggroup WHERE grouptitle = '".addslashes($group)."'");
		if (empty($groupinfo)) {
			$group = '';
		}
	}

	if (empty($group)) {
		$getgroups = $DB_site->query('
			SELECT *
			FROM hive_settinggroup
			'.iif(!defined('HIVE_DEV') or HIVE_DEV != true, 'WHERE display > 0', 'WHERE display > -1').'
			ORDER BY display, grouptitle
		');

		starttable('HiveMail&trade; Options', '350');
		$i = 1;
		while ($group = $DB_site->fetch_array($getgroups)) {
			$labels[] = "$i. <a href=\"option.php#group$group[grouptitle]\">$group[title]</a>".iif(defined('HIVE_DEV') and HIVE_DEV == true, " [<a href=\"option.php?cmd=editgroup&grouptitle=$group[grouptitle]\">edit</a>]");
			if ($i++%2 == 0) {
				tablerow($labels, true);
				$labels = array();
			}
		}
		unset($group);
		if (!empty($labels)) {
			$labels[] = '&nbsp';
			tablerow($labels, true);
		}
		endtable();

		if (defined('HIVE_DEV') and HIVE_DEV == true) {
			echo "<div align=\"center\" style=\"font-weight: bold; font-size: 12px;\"><a href=\"option.php?cmd=edit\">Create new setting</a><br /><a href=\"option.php?cmd=editgroup\">Create new setting group</a></div>\n";
		}
		echo '<br /><br />';
	}

	$lastgroupid = -1;
	$settings = $DB_site->query('
		SELECT setting.*, settinggroup.description AS groupdescription, settinggroup.grouptitle AS sggrouptitle, settinggroup.title AS sgtitle
		FROM hive_setting AS setting
		LEFT JOIN hive_settinggroup AS settinggroup USING (grouptitle)
		WHERE 1=1
		'.iif((!defined('HIVE_DEV') or HIVE_DEV != true) and $group != 'subs' and $group != 'hivepop3', 'AND settinggroup.display > 0').'
		'.iif(!empty($group), "AND setting.grouptitle = '$group'").'
		ORDER BY settinggroup.display, setting.grouptitle, setting.display
	');

	startform('option.php', 'updatevalues');
	$i = 1;
	while ($setting = $DB_site->fetch_array($settings)) {
		if ($lastgroupid != $setting['sggrouptitle']) {
			if ($lastgroupid != -1) {
				tablehead(array('<input class="button" type="submit" value="  Update Options  " />'), 2);
				endtable();
				echo '<br /><br />';
			}
			echo '<a name="group'.$setting['sggrouptitle'].'"></a>';
			starttable($i.'. '.$setting['sgtitle'].iif(defined('HIVE_DEV') and HIVE_DEV == true, " [<a href=\"option.php?cmd=editgroup&grouptitle=$setting[sggrouptitle]\">edit</a>]"));
			if (!empty($setting['groupdescription'])) {
				textrow($setting['groupdescription'], 2, true);
			}
			$i++;
		}
		settingfield($setting);
		$lastgroupid = $setting['sggrouptitle'];
	}
	endform('Update Options');
	endtable();
}

// ############################################################################
// Update options
if ($_POST['cmd'] == 'updatetype') {
	$DB_site->query("
		UPDATE hive_setting
		SET value = '".addslashes($type)."'
		WHERE variable = 'gatewaytype'
	");
	$gatewaytype = $_options['gatewaytype'] = $type;

	adminlog(0, true, 'updatetype', 'New gateway: '.$type);
	$cmd = 'gateway';
}

// ############################################################################
// Email gateway options
if ($cmd == 'gateway') {
	adminlog();

	$gatewaytype = getop('gatewaytype');
	startform('option.php', 'updatetype', 'Are you SURE you want to change the type of email gateway?');
	starttable('Switch Email Gateway', '450');
	selectbox('Type of gateway:', 'type', array('pop3' => 'POP3 Gateway', 'pipe' => 'Pipe Gateway'), $gatewaytype);
	endform('Change Gateway');
	endtable();
	echo '<br />';

	$gt = iif($gatewaytype == 'pipe', 'pipeg', 'pop3g');
	$settings = $DB_site->query("
		SELECT *
		FROM hive_setting AS setting
		WHERE grouptitle = '$gt'
		ORDER BY display
	");

	getclass();
	if ($gatewaytype == 'pipe') {
		starttable('Gateway Settings', '450');
		textrow('There are no settings for this type of gateway. For information on installing and configuring the pipe gateway installation manual.');
		endtable();
	} else {
		startform('option.php', 'updatevalues');
		hiddenfield('gateway', '1');
		starttable('Gateway Settings');
		while ($setting = $DB_site->fetch_array($settings)) {
			settingfield($setting);
		}
		endform('Save Changes');
		endtable();
		echo '<div align="center"><b>Please see the installation guide for help regarding these settings.</b></div>';
	}
}

// ############################################################################
// Off limits!
if (!defined('HIVE_DEV') or HIVE_DEV != true) {
	cp_footer();
	exit;
}

// ############################################################################
// Remove setting group
if ($_POST['cmd'] == 'killgroup') {
	$settinggroup = $DB_site->query_first("SELECT * FROM hive_settinggroup WHERE grouptitle = '".addslashes($grouptitle)."'");

	if (empty($settinggroup)) {
		cp_error('The setting group specified was not found.', 'option.php');
	}

	$query = "
		DELETE FROM hive_settinggroup
		WHERE grouptitle = $grouptitle
	";
	$DB_site->query($query);

	adminlog($grouptitle, true);
	cp_error('The setting group has been removed. Query:<br /><pre>'.$query.'</pre>', 'option.php');
}

// ############################################################################
// Remove setting group
if ($cmd == 'removegroup') {
	$settinggroup = $DB_site->query_first("SELECT * FROM hive_settinggroup WHERE grouptitle = '".addslashes($grouptitle)."'");

	if (empty($settinggroup)) {
		cp_error('The setting group specified was not found.', 'option.php');
	}

	adminlog($grouptitle);
	startform('option.php', 'killgroup', 'Are you sure you want to remove this setting group?');
	starttable('Remove setting group "'.$settinggroup['title'].'" (ID: '.$grouptitle.')', '450');
	textrow('Are you <b>sure</b> you want to remove this setting group? This procedure <b>cannot</b> be reversed!');
	hiddenfield('grouptitle', $grouptitle);
	endform('Remove Setting Group', '', 'Go Back');
	endtable();
}

// ############################################################################
// Create a new setting group or update an existing one
if ($_POST['cmd'] == 'updategroup') {
	if ($todo == 'add') {
		$newgrouptitle = $settinggroup['grouptitle'];
		$settinggroup['display'] = iif(empty($settinggroup['display']) and $settinggroup['display'] != '0', $DB_site->get_field("SELECT MAX(display) FROM hive_settinggroup") + 1, $settinggroup['display']);
		$query = $DB_site->build_query('settinggroup', $settinggroup);
		$DB_site->query($query);
		adminlog($newgrouptitle, true);
		$msg = 'The setting group has been created';
	} else {
		$oldsettinggroup = unserialize($oldsettinggroup);
		$oldgrouptitle = $oldsettinggroup['grouptitle'];
		$newgrouptitle = $settinggroup['grouptitle'];
		foreach ($oldsettinggroup as $key => $value) {
			if ($settinggroup["$key"] == $value) {
				unset($settinggroup["$key"]);
			}
		}
		$query = $DB_site->build_query('settinggroup', $settinggroup, "grouptitle = '$oldgrouptitle'");
		$DB_site->query($query);
		adminlog($newgrouptitle, true);
		$msg = 'The setting group has been updated';
	}
	echo '<br />';
	starttable('', '400');
	textrow('<div align="center"><br />'.$msg.'. Query:<br /><pre>'.str_replace(array('<', '>', '&trade;'), array('&lt;', '&gt;', '&amp;trade;'), $query).'</pre>'.makelink('proceed', 'option.php?cmd=modify#group'.$newgrouptitle).'</div>');
	endtable();
}

// ############################################################################
// Create a new setting group or update an existing one
if ($cmd == 'editgroup') {
	startform('option.php', 'updategroup');

	$settinggroup = $DB_site->query_first("SELECT * FROM hive_settinggroup WHERE grouptitle = '".addslashes($grouptitle)."'");
	adminlog($grouptitle);
	if (empty($settinggroup)) {
		$grouptitle = '';
		starttable('Create new setting group', '600');
	} else {
		starttable('Update setting group "'.$settinggroup['title'].'" (ID: '.$grouptitle.')', '600');
	}

	hiddenfield('todo', iif(!empty($grouptitle), 'edit', 'add'));
	hiddenfield('oldsettinggroup', serialize($settinggroup));
	inputfield('Group variable title:', 'settinggroup[grouptitle]', $settinggroup['grouptitle']);
	inputfield('Title:', 'settinggroup[title]', $settinggroup['title']);
	textarea('Description:', 'settinggroup[description]', $settinggroup['description'], 6, 55);
	if (!empty($grouptitle)) {
		inputfield('Display order:', 'setting[display]', $settinggroup['display'], 4);
	}

	endform(iif(empty($grouptitle), 'Create', 'Update').' setting group');
	endtable();
}

// ############################################################################
// Remove setting
if ($_POST['cmd'] == 'kill') {
	$setting = getinfo('setting', $settingid);

	$query = "
		DELETE FROM hive_setting
		WHERE settingid = $settingid
	";
	$DB_site->query($query);

	adminlog($settingid, true);
	cp_error('The setting has been removed. Query:<br /><pre>'.$query.'</pre>');
}

// ############################################################################
// Remove setting
if ($cmd == 'remove') {
	$setting = getinfo('setting', $settingid);

	adminlog($settingid);
	startform('option.php', 'kill', 'Are you sure you want to remove this setting?');
	starttable('Remove setting "'.$setting['title'].'" (ID: '.$settingid.')', '450');
	textrow('Are you <b>sure</b> you want to remove this setting? This procedure <b>cannot</b> be reversed!');
	hiddenfield('settingid', $settingid);
	endform('Remove Setting', '', 'Go Back');
	endtable();
}

// ############################################################################
// Create a new setting or update an existing one
if ($_POST['cmd'] == 'update') {
	$grouptitle = $setting['grouptitle'];
	if ($settingid == 0) {
		$setting['display'] = $DB_site->get_field("SELECT MAX(display) FROM hive_setting WHERE grouptitle = '$setting[grouptitle]'") + 1;
		$query = $DB_site->build_query('setting', $setting);
		$DB_site->query($query);
		adminlog($settingid, true);
		$msg = 'The setting has been created';
	} else {
		$oldsetting = unserialize($oldsetting);
		$varname = $oldsetting['variable'];
		$opttype = $setting['type'];
		foreach ($oldsetting as $key => $value) {
			if ($key == 'typeoptions' and $opttype == 'select' and substr($value, 0, 5) != 'hive_') {
				$setting["$key"] = str_replace(iif(strstr($setting["$key"], "\r\n") !== false, "\r\n\r\n", "\n\n"), '//', $setting["$key"]);
				$setting["$key"] = str_replace(iif(strstr($setting["$key"], "\r\n") !== false, "\r\n", "\n"), '||', $setting["$key"]);
			}
			if ($setting["$key"] == $value) {
				unset($setting["$key"]);
			}
		}
		if (!empty($setting)) {
			$query = $DB_site->build_query('setting', $setting, "variable = '$varname'");
			$DB_site->query($query);
			adminlog($settingid, true);
			$msg = 'The setting has been updated';
		} else {
			cp_redirect('You did not change the setting.', 'option.php?cmd=modify#group'.$grouptitle);
		}
	}
	echo '<br />';
	starttable('', '400');
	textrow('<div align="center"><br />'.$msg.'. Query:<br /><pre>'.str_replace(array('<', '>', '&trade;'), array('&lt;', '&gt;', '&amp;trade;'), $query).'</pre>'.makelink('proceed', 'option.php?cmd=modify#group'.$grouptitle).'</div>');
	endtable();
}

// ############################################################################
// Create a new setting or update an existing one
if ($cmd == 'edit') {
	startform('option.php', 'update');

	$setting = getinfo('setting', $settingid, false, false);
	adminlog($settingid);
	if ($setting === false) {
		$settingid = 0;
		starttable('Create new setting', '600');
	} else {
		starttable('Update setting "'.$setting['title'].'" (ID: '.$settingid.')', '600');
		$oldsetting = serialize($setting);
		if ($setting['type'] == 'select' and substr($setting['typeoptions'], 0, 5) != 'hive_') {
			$setting['typeoptions'] = str_replace('//', "\n\n", $setting['typeoptions']);
			$setting['typeoptions'] = str_replace('||', "\n", $setting['typeoptions']);
		}
	}

	hiddenfield('settingid', $settingid);
	hiddenfield('oldsetting', $oldsetting);
	inputfield('Title:', 'setting[title]', $setting['title']);
	tableselect('Setting group:', 'setting[grouptitle]', 'settinggroup', $setting['grouptitle'], '1=1', false, '', 'title', 'grouptitle');
	textarea('Description:', 'setting[description]', $setting['description'], 6, 55);
	inputfield('Variable name:', 'setting[variable]', $setting['variable']);
	inputfield('Setting value:', 'setting[value]', $setting['value']);
	inputfield('Field type:', 'setting[type]', iif(!empty($setting['type']), $setting['type'], 'text'));
	textarea('Options:', 'setting[typeoptions]', $setting['typeoptions']);
	if ($settingid != 0) {
		inputfield('Display order:', 'setting[display]', $setting['display'], 4);
	}

	endform(iif($settingid == 0, 'Create', 'Update').' setting');
	endtable();
}

cp_footer();
?>