<?php
if(!defined('sugarEntry') || !sugarEntry)
	die('Not A Valid Entry Point');
/*********************************************************************************
 * The contents of this file are subject to the SugarCRM Public License Version
 * 1.1.3 ("License"); You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at http://www.sugarcrm.com/SPL
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied.  See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * All copies of the Covered Code must include on each user interface screen:
 *    (i) the "Powered by SugarCRM" logo and
 *    (ii) the SugarCRM copyright notice
 * in the same form as they appear in the distribution.  See full license for
 * requirements.
 *
 * The Original Code is: SugarCRM Open Source
 * The Initial Developer of the Original Code is SugarCRM, Inc.
 * Portions created by SugarCRM are Copyright (C) 2004-2006 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/
/*********************************************************************************

 * Description:
 * Portions created by SugarCRM are Copyright(C) SugarCRM, Inc. All Rights
 * Reserved. Contributor(s): ______________________________________..
 * *******************************************************************************/
$_SESSION['upgrade_complete'] = '';

logThis('[At commit.php]');
$stop = true; // flag to show "next"

$standardErrorLevel = error_reporting();
logThis("Setting error_reporting() to E_ERROR while running upgrade");
error_reporting(E_ERROR);

set_time_limit(0);
/*
 * [unzip_dir] => /Users/curisu/www/head/cache/upload//upgrades/temp/QSugp3
 * [zip_from_dir]  => SugarEnt-Upgrade-4.0.1-to-4.2.1
 * rest_dir: /Users/curisu/www/head/cache/upload/SugarEnt-Upgrade-4.0.1-to-4.2.1-restore
 */

// flag upgradeSql script run method
$_SESSION['schema_change'] = $_REQUEST['schema_change'];

// prevent "REFRESH" double commits
if(!isset($_SESSION['committed'])) {
	$_SESSION['committed'] = true; // flag to prevent refresh double-commit
	unset($_SESSION['rebuild_relationships']);
	unset($_SESSION['rebuild_extensions']);

	$unzip_dir			= $_SESSION['unzip_dir'];
	$zip_from_dir		= $_SESSION['zip_from_dir'];
	$install_file		= urldecode($_SESSION['install_file']);
	$file_action		= "";
	$uh_status			= "";
	$errors				= array();
	$out				= '';
	$backupFilesExist	= false;
	$rest_dir			= clean_path(remove_file_extension($install_file) . "-restore");

	///////////////////////////////////////////////////////////////////////////////
	////	MAKE BACKUPS OF TARGET FILES
	$errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
	////	END MAKE BACKUPS OF TARGET FILES
	///////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////////////////////////////////
	////	HANDLE PREINSTALL SCRIPTS
	if(empty($errors)) {
		$file = "$unzip_dir/" . constant('SUGARCRM_PRE_INSTALL_FILE');
		if(is_file($file)) {
			$out .= "{$mod_strings['LBL_UW_INCLUDING']}: {$file} <br>\n";
			include($file);

			logThis('Running pre_install()...');
			pre_install();
			logThis('pre_install() done.');
		}
	}
	////	HANDLE PREINSTALL SCRIPTS
	///////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////////////////////////////////
	////	COPY NEW FILES INTO TARGET INSTANCE
	$split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
	$copiedFiles = $split['copiedFiles'];
	$skippedFiles = $split['skippedFiles'];
	////	END COPY NEW FILES INTO TARGET INSTANCE
	///////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////////////////////////////////
	////	HANDLE POSTINSTALL SCRIPTS
	logThis('Starting post_install()...');
	if(empty($errors)) {
		$file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
		if(is_file($file)) {
			include($file);
			post_install();

			// cn: only run conversion if admin selects "Sugar runs SQL"
			if(!empty($_SESSION['allTables']) && $_SESSION['schema_change'] == 'sugar')
				executeConvertTablesSql($db->dbType, $_SESSION['allTables']);
		}
		logThis('Performing UWrebuild()...');
		UWrebuild();
		logThis('UWrebuild() done.');

		require("sugar_version.php");

		if(!rebuildConfigFile($sugar_config, $sugar_version)) {
			logThis('*** ERROR: could not write config.php! - upgrade will fail!');
			$errors[] = $mod_strings['ERR_UW_CONFIG_WRITE'];
		}
	}
	logThis('post_install() done.');
	//// END POSTINSTALL SCRIPTS
	///////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////////////////////////////////
	////	REGISTER UPGRADE
	logThis('Registering upgrade with UpgradeHistory');
	if(empty($errors)) {
		$file_action = "copied";
		// if error was encountered, script should have died before now
		$new_upgrade = new UpgradeHistory();
		$new_upgrade->filename = $install_file;
		$new_upgrade->md5sum = md5_file($install_file);
		$new_upgrade->type = 'patch';
		$new_upgrade->version = $sugar_version;
		$new_upgrade->status = "installed";
		$new_upgrade->manifest =(!empty($_SESSION['install_manifest']) ? $_SESSION['install_manifest'] : '');
		$new_upgrade->save();
	}
	////	REGISTER UPGRADE
	///////////////////////////////////////////////////////////////////////////////
}else{
    $backupFilesExist = false;
    $copiedFiles = array();
    $skippedFiles = array();
}

// flag to prvent double-commits via refresh
$_SESSION['committed'] = true;

///////////////////////////////////////////////////////////////////////////////
////	FINISH AND OUTPUT
if(empty($errors)) {
	$stop = false;
}

$backupDesc = '';
if($backupFilesExist) {
	$backupDesc .= "<b>{$mod_strings['LBL_UW_BACKUP_FILES_EXIST_TITLE']}</b><br />";
	$backupDesc .= $mod_strings['LBL_UW_BACKUP_FILES_EXIST'] . ': ' . $rest_dir;
}
$copiedDesc = '';
if(count($copiedFiles) > 0) {
	$copiedDesc .= "<b>{$mod_strings['LBL_UW_COPIED_FILES_TITLE']}</b><br />";
	$copiedDesc .= "<a href='javascript:void(0); toggleNwFiles(\"copiedFiles\");'>{$mod_strings['LBL_UW_SHOW']}</a>";
	$copiedDesc .= "<div id='copiedFiles' style='display:none;'>";

	foreach($copiedFiles as $file) {
		$copiedDesc .= $file . "<br />";
	}
	$copiedDesc .= "</div>";
}
$skippedDesc = '';
if(count($skippedFiles) > 0) {
	$skippedDesc .= "<b>{$mod_strings['LBL_UW_SKIPPED_FILES_TITLE']}</b><br />";
	$skippedDesc .= "<a href='javascript:void(0); toggleNwFiles(\"skippedFiles\");'>{$mod_strings['LBL_UW_SHOW']}</a>";
	$skippedDesc .= "<div id='skippedFiles' style='display:none;'>";

	foreach($skippedFiles as $file) {
		$skippedDesc .= $file . "<br />";
	}
	$skippedDesc .= "</div>";
}

$rebuildResult = "<b>{$mod_strings['LBL_UW_REBUILD_TITLE']}</b><br />";
$rebuildResult .= "<a href='javascript:void(0); toggleRebuild();'>{$mod_strings['LBL_UW_SHOW']}</a> <div id='rebuildResult'></div>";

unlinkTempFiles();

///////////////////////////////////////////////////////////////////////////////
////	HANDLE REMINDERS
commitHandleReminders($skippedFiles);
////	HANDLE REMINDERS
///////////////////////////////////////////////////////////////////////////////


logThis("Resetting error_reporting() to system level.");
error_reporting($standardErrorLevel);

///////////////////////////////////////////////////////////////////////////////
////	OUTPUT
$uwMain =<<<eoq
<script type="text/javascript" language="javascript">
	function toggleRebuild() {
		var target = document.getElementById('rebuildResult');
		
		if(target.innerHTML == '') {
			target.innerHTML = rebuildResult; // found in UWrebuild()
		} else {
			target.innerHTML = '';
		}
	}
</script>
<table cellpadding="3" cellspacing="0" border="0">
	<tr>
		<th align="left">
			{$mod_strings['LBL_UW_TITLE_COMMIT']}
		</th>
	</tr>
	<tr>
		<td align="left">
			<p>
			{$backupDesc}
			</p>
			<p>
			{$copiedDesc}
			</p>
			<p>
			{$skippedDesc}
			</p>
			<p>
			{$rebuildResult}
			</p>
		</td>
	</tr>
</table>
eoq;

$showBack = false;
$showCancel = false;
$showRecheck = false;
$showNext =($stop) ? false : true;

$stepBack = $_REQUEST['step'] - 1;
$stepNext = $_REQUEST['step'] + 1;
$stepCancel = -1;
$stepRecheck = $_REQUEST['step'];

$_SESSION['step'][$steps['files'][$_REQUEST['step']]] =($stop) ? 'failed' : 'success';
?>
