<?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: upgrade.php,v $ - $Revision: 1.57.2.1 $
// | $Date: 2004/08/20 20:39:36 $ - $Author: tubedogg $
// +-------------------------------------------------------------+

error_reporting(E_ALL & ~E_NOTICE);
define('ALLOW_LOGGED_OUT', true);
define('ALLOW_INSTALL_FOLDER', true);
define('SKIP_LANG', true);
require_once('../includes/init_vars.php');
require_once('../includes/config.php');
require_once('../includes/db_mysql.php');
require_once('../includes/functions.php');
require_once('../includes/functions_install.php');
require_once('../includes/functions_file.php');
require_once('../includes/functions_admin.php');
require_once('../includes/functions_template.php');
require_once('../includes/init.php');
define('CP_IGNORE_COOKIES', true);

// ############################################################################
// Connect to database
$DB_site = new DB_MySQL($config);
$DB_site->setup_options();
$DB_site->showerror = false;
cp_header(' &raquo; Upgrade Script');

// ############################################################################
// Define versions
$versions = array(
	0 => array('1.0', '1.0'),
	1 => array('1.1', '1.1'),
	2 => array('1.1.1', '1.1.1'),
	3 => array('1.2', '1.2'),
	4 => array('1.2.2', '1.2.2 Stable'),
	5 => array('1.3 Beta', '1.3 Beta'),
	6 => array('1.3 RC1', '1.3 RC1'),
	7 => array('', '1.3 RC2 (Step 1 of 2)'), //1.3 RC2 BPR1
	8 => array('', '1.3 RC2 (Step 2 of 2)'), //1.3 RC2 BPR2
	9 => array('1.3 RC2', '1.3 RC2'),
	10 => array('', '1.3 Final (Step 1 of 1)'), // 1.3 Final BPR1
	11 => array('1.3', '1.3 Stable or 1.3.1 Stable'),
);

// ############################################################################
// Define steps
$steps = array(
	1 => 'Table Alteration & Populate Tables',
	2 => 'Data Manipulation',
	3 => 'Update Template Information',
	4 => 'Complete Upgrade',
);

// ############################################################################
// Header
install_header(2);

// ############################################################################
// Welcome screen
if (!is_numeric($step)) {
	echo '<p>Welcome to the HiveMail&trade; upgrade script!<br />
	This script will guide you through the process of upgrading HiveMail&trade;. These are the steps you will be going through in this script:
	<ul type="1">';
	foreach ($steps as $stepname) {
		echo "<li>$stepname</li>\n";
	}
	echo '</ul>
	It is very important that you follow the on-screen instructions precisely and not skip over any steps. We recommend that you use Upgrade for guidance.<br />
	This script will shut down HiveMail&trade; when you proceed to the first step, and restart the system once you reach the final step. If at any time you are stuck or feel like you need help, please do not hesitate and contact us at Support Hivemail for help.<br /><br />
	
	Before proceeding, we <span class="cp_temp_edit"><b>STRONGLY</b></span> recommend that you make a backup of your database. (See the HiveMail&trade; manual for detailed instructions on making a backup of your database.)</p>';

	echo "<p>Please choose below the version you are <i>currently</i> using:\n<ul>\n";
	foreach ($versions as $vercode => $vernum) {
		if (!empty($vernum[0])) {
			if ($vernum[0] == HIVEVERSION) {
				break;
			}

			echo '<li>'."Version $vernum[0]: <a href=\"upgrade.php?upgrade_base=".($vercode+1)."&step=1\">click here</a>."."</li>\n";
		}
	}
	echo "</ul>";
	echo '</p>';
}

// ############################################################################
// Table Alteration
if ($step == 1) {
	// Shut down system
	$DB_site->query('
		UPDATE hive_setting
		SET value = 1
		WHERE variable = "maintain"
	');

	// We will always run this query to get rid of old default phrases
	if ($upgrade_base > 10) {
		$DB_site->query("
			DELETE FROM hive_phrase
			WHERE languageid = -1
		");
	}

	$tables = array();
	$inserts = array();
	foreach ($versions as $vercode => $vernum) {
		if ($vercode < $upgrade_base) {
			continue;
		}

		$filename = "sql_upgrade_$vercode.php";
		if (file_exists("./$filename") and is_readable("./$filename")) {
			require_once("./$filename");
		} else {
			die('<span class="cp_temp_edit"><b>ERROR</b></span>: Cannot find or read <tt>'.$filename.'</tt>. Please ensure that it is in the <tt>/install</tt> directory and refresh the page.');
		}
	}

	if (!array_empty($tables) or !array_empty($inserts)) {
		echo "<p>The script will now alter the table structure in your database:\n<ul>\n";
		foreach ($versions as $vercode => $vernum) {
			if ($vercode < $upgrade_base) {
				continue;
			}
			echo '<li>Performing operations to upgrade from '.$versions[($vercode-1)][1].' to '.$versions[$vercode][1].":\n<ul>\n";
			if (!array_empty($tables["$vercode"])) {
				foreach ($tables["$vercode"] as $tablename => $tablecreate) {
					echo "<li>".iif(substr($tablecreate, 0, 5) == 'Alter', 'Altering', 'Creating')." table <tt>$tablename</tt> ... ";
					$DB_site->query($tablecreate);
					report_mysql_error();
					echo "</li>\n";
				}
			}
			if (!array_empty($inserts["$vercode"])) {
				foreach ($inserts["$vercode"] as $insert) {
					if (substr($insert, 0, strlen('EVAL ')) == 'EVAL ') {
						$insert = substr($insert, strlen('EVAL '));
						eval('$insert = "'.str_replace('"', '\"', $insert).'";');
					}

					if (substr($insert, 0, strlen('INSERT INTO ')) == 'INSERT INTO ') {
						$isinsert = 1;
						$tablename = substr($insert, strlen('INSERT INTO '));
						$tablename = substr($tablename, 0, strpos($tablename, ' '));
					} elseif (substr($insert, 0, strlen('UPDATE ')) == 'UPDATE ') {
						$isinsert = 0;
						$tablename = substr($insert, strlen('UPDATE '));
						$tablename = substr($tablename, 0, strpos($tablename, ' '));
					} else {
						$isinsert = 0;
						$tablename = substr($insert, strlen('DELETE FROM '));
						$tablename = substr($tablename, 0, strpos($tablename, ' '));
					}

					echo '<li>'.iif($isinsert, 'Adding data to', 'Updating data in')." <tt>$tablename</tt> ... ";
					$DB_site->query($insert);
					report_mysql_error();
					echo "</li>\n";
				}
			}
			echo "\n</ul></li>\n";
		}
		echo '</ul>';
	} else {
		echo 'No changes were made to the database schema. Please proceed to the next step.';
	}

	// Rebuild all languages to incorporate new phrases
	rebuild_language(-1);
	// Rebuild all styles in case settings have been added/removed
	rebuild_skin(-1);

	if (defined('GOTO_NEXT')) {
		echo 'It seems that at least one error occurred while altering table structure and updating data. Only proceed if you are sure these errors are not critical.';
	} else {
		define('GOTO_NEXT', true);
	}
	echo '</p>';
}

// ############################################################################
// PHP stuff
if ($step == 2) {
	if ($upgrade_base < 6 and (empty($do) or $do == 'group1')) {
		$start = iif(empty($start), 0, $start);
		$perpage = iif(empty($perpage), 1, $perpage);
		if (empty($total)) {
			$count = $DB_site->query("
				SELECT *
				FROM hive_iplog
				GROUP BY userid
			");
			$total = $DB_site->num_rows($count);
		}
		$ips = $DB_site->query("
			SELECT ipaddr, userid
			FROM hive_iplog
			GROUP BY userid
			ORDER BY datefirstseen ASC
			LIMIT $start, $perpage
		");
		$i = 0;
		echo "<p>The script will now update the system data in your database and populate it with new information:\n<ul>\n";
		while ($ip = $DB_site->fetch_array($ips)) {
			$i++;
			echo "<li>Updating user ID: <tt>$ip[userid]</tt> ...";
			$DB_site->query("
				UPDATE hive_user
				SET regipaddr = '$ip[ipaddr]'
				WHERE userid = $ip[userid]
			");
			report_mysql_error();
			echo "Done.</li>\n";
		}
		echo "</ul>Done.\n</p>\n";
		if ($start < $total and !defined('GOTO_NEXT')) {
			$start = $start + $perpage;
			$do = 'group1';
			define('GOTO_LOOP', true);
		} else {
			unset($start, $total, $do);
		}
		$changes = 1;
	}

	// Contact groups were introduced in 1.3 beta, so we need to check for bad group contacts if we are upgrading from
	// any 1.3 version
	if ($upgrade_base > 4 and $upgrade_base < 12 and (empty($do) or $do == 'group2') and !defined('GOTO_LOOP')) {
		$start = iif(empty($start), 0, $start);
		$perpage = iif(empty($perpage), 1, $perpage);
		if (empty($total)) {
			$count = $DB_site->query("
				SELECT *
				FROM hive_user AS u
				LEFT JOIN hive_contactgroup AS g ON u.userid = g.userid
				WHERE contactgroupid <> ''
				GROUP BY c.userid
			");
			$total = $DB_site->num_rows($count);
		}
		if ($total > 0) {
			$users = $DB_site->query("
				SELECT u.userid
				FROM hive_user AS u
				LEFT JOIN hive_contact AS c ON u.userid = c.userid
				LEFT JOIN hive_contactgroup AS g ON u.userid = g.userid
				WHERE contactid <> '' AND contactgroupid <> ''
				GROUP BY c.userid
				ORDER BY u.userid ASC
				LIMIT $start, $perpage
			");
			echo "<p>The script will now update the system data in your database and modify it if necessary...\n<ul>\n";
			$userids = array();
			while ($u = $DB_site->fetch_array($users)) {
				$userids[] = $u['userid'];
			}
			if (!empty($userids)) {
				$toget = implode(',', $userids);
				$contacts = $DB_site->query("
					SELECT *
					FROM hive_contact
					WHERE userid IN ($toget,0)
				");
				while ($c = $DB_site->fetch_array($contacts)) {
					$allcontacts["$c[userid]"]["$c[contactid]"] = $c['email'];
				}
				$groups = $DB_site->query("
					SELECT *
					FROM hive_contactgroup
					WHERE userid IN ($toget)
				");
				while ($g = $DB_site->fetch_array($groups)) {
					$allgroups["$g[userid]"]["$g[contactgroupid]"] = $g['contacts'];
				}

				foreach ($userids as $userid) {
					echo "<li>Updating user ID: <tt>$userid</tt> ...";
					foreach ($allgroups["$userid"] as $contactgroupid => $contacts) {
						$groupcontacts = explode(',', $contacts);
						$badcontacts = array();
						foreach ($groupcontacts as $key => $contactid) {
							if ((!isset($allcontacts["$userid"]["$contactid"]) or empty($allcontacts["$userid"]["$contactid"])) and (!isset($allcontacts[0]["$contactid"]) or empty($allcontacts[0]["$contactid"]))) {
								$badcontacts[$key] = $contactid;
							}
						}
						if (!empty($badcontacts)) {
							foreach ($badcontacts as $key => $contactid) {
								unset($groupcontacts[$key]);
							}
							if (!empty($groupcontacts)) {
								$groupcontacts = implode(',', $groupcontacts);
							} else {
								$groupcontacts = '';
							}
							$DB_site->query("
								UPDATE hive_contactgroup
								SET contacts = '".addslashes($groupcontacts)."'
								WHERE contactgroupid = $contactgroupid
							");
							report_mysql_error(true, false);
						}
						unset($groupcontacts, $badcontacts);
					}
					echo "Done.</li>\n";
				}
			}
			echo "</ul>\nDone.</p>\n";
		}
		if ($start < $total and !defined('GOTO_NEXT')) {
			$start = $start + $perpage;
			$do = 'group2';
			define('GOTO_LOOP', true);
		} else {
			unset($start, $total, $do);
		}
		$changes = 1;
	}

	if ($upgrade_base == 7 and !defined('GOTO_LOOP')) {
		$rule = $DB_site->query_first("
			SELECT *
			FROM hive_rule
			WHERE cond NOT LIKE '1~%' AND cond NOT LIKE '2~%'
		");
		if (!empty($rule)) {
			$DB_site->query("
				UPDATE hive_rule
				SET cond = CONCAT('1~', SUBSTRING_INDEX(cond, '~', 2))
			");
			$changes = 1;
		}
	}

	if ($changes == 0) {
		echo 'No changes are required to your system information. Please proceed to the next step.';
	}
	if (defined('GOTO_NEXT')) {
		echo 'It seems that at least one error occurred while updating the data in the database. Only proceed if you are sure these errors are not critical.';
	} elseif (!defined('GOTO_LOOP')) {
		define('GOTO_NEXT', true);
	}
	echo '</p>';
}

// ############################################################################
// Update Template Information
if ($step == 3) {
	$templates = array();
	foreach ($versions as $vercode => $vernum) {
		if ($vercode < $upgrade_base) {
			continue;
		}

		$filename = "templates_upgrade_$vercode.php";
		if (file_exists("./$filename") and is_readable("./$filename")) {
			require_once("./$filename");
		} else {
			die('<span class="cp_temp_edit"><b>ERROR</b></span>: Cannot find or read <tt>'.$filename.'</tt>. Please ensure that it is in the <tt>/install</tt> directory and refresh the page.');
		}
	}

	if (!array_empty($templates)) {
		$upgradetemplates = array();
		echo "<p>The script will now load the database with the new default templates:\n<ul>\n";
		foreach ($templates as $forversion => $realtemplates) {
			if (!array_empty($realtemplates)) {
				echo '<li>Performing changes from '.$versions[($forversion-1)][1].' to '.$versions[$forversion][1].":\n<ul>\n";
				foreach ($realtemplates as $name => $tempinfo) {
					$DB_site->query('
						DELETE FROM hive_template
						WHERE title = "'.addslashes($name).'" AND templatesetid = -1
					');
					echo '<li>'.iif(mysql_affected_rows() == 0, 'Creating', 'Updating')." template <tt>$name</tt> ... ";
					$DB_site->query('
						INSERT INTO hive_template
						(templateid, templatesetid, templategroupid, title, user_data, parsed_data)
						VALUES
						(NULL, -1, '.$tempinfo['templategroupid'].', "'.addslashes($name).'", "'.addslashes($tempinfo['user_data']).'", "'.addslashes($tempinfo['parsed_data']).'")
					');
					report_mysql_error();
					echo "</li>\n";
					$upgradetemplates[] = '"'.addslashes($name).'"';
				}
				echo "\n</ul></li>\n";
			}
		}
		echo '</ul>';
		$DB_site->query('
			UPDATE hive_template
			SET upgraded = 1
			WHERE title IN ('.implode(', ', $upgradetemplates).') AND templatesetid <> -1
		');
	} else {
		echo 'No changes were made to the templates. Please proceed to the next step.';
	}

	if (defined('GOTO_NEXT')) {
		echo 'It seems that at least one error occurred while loading the templates. Only proceed if you are sure these errors are not critical.';
	} else {
		define('GOTO_NEXT', true);
	}
	echo '</p>';
}


// ############################################################################
// Complete Upgrade
if ($step == 4) {
	$DB_site->query('
		UPDATE setting
		SET value = "'.addslashes(HIVEVERSION).'"
		WHERE variable = "versionnum"
	');
	// Restart system
	$DB_site->query('
		UPDATE hive_setting
		SET value = 0
		WHERE variable = "maintain"
	');

	echo 'Congratulations, you have successfully upgraded your installation of HiveMail&trade; and are now running version 1.3.1!<br /><br />';
	if ($upgrade_base > 5 and $upgrade_base < 10) {
		$sub = $DB_site->query_first("
			SELECT *
			FROM hive_plan
			LIMIT 1
		");
		if (!empty($sub)) {
			echo '<b>Important note</b>: Subscription plans have been affected by this upgrade. A new feature of the version you are now running is that you can select which user group(s) can upgrade to any given subscription plan. Because of this, you will need to modify your subscription plan(s) and set which user group(s) can upgrade to each one. We suggest you do this first, as until you do, nobody will be able to subscribe to any plan.<br /><br />';
		}
	}
	echo 'Please remove the <tt>/install</tt> folder from your web site (for security reasons). We strongly recommend that you revert any custom templates that have had their default versions changed in the upgrade process. You can view a list of such templates <a href="../admin/template.php?cmd=upgrade">here</a>. Otherwise you may proceed to the Administrator\'s Control Panel <a href="../admin">here</a>.';
}

// ############################################################################
// Footer
if (defined('GOTO_NEXT') and GOTO_NEXT == true) {
	starttable('', '90%', true, 2, false, 4, false);
	tablehead(array('<a href="upgrade.php?upgrade_base='.$upgrade_base.'&step='.($step + 1).'">&raquo; Continue to next step: '.$steps[($step + 1)].' &raquo;</a>'), 1, true);
	endtable();
} elseif (defined('GOTO_LOOP') and GOTO_LOOP == true) {
	starttable('', '90%', true, 2, false, 4, false);
	tablehead(array("<script type=\"text/javascript\">\n" . "window.location=\"upgrade.php?upgrade_base=$upgrade_base&step=$step&total=$total&do=$do&start=$start&perpage=$perpage\";" . "\n</script>\n" . '<a href="upgrade.php?upgrade_base='.$upgrade_base.'&do='.$do.'&step='.$step.'&start='.$start.'">&raquo; Continue processing &raquo;</a>', '&nbsp;'), 1, true);
	endtable();
}

cp_footer();
?>