<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
 * SugarCRM is a customer relationship management program developed by
 * SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
 * 
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License version 3 as published by the
 * Free Software Foundation with the addition of the following permission added
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
 * 
 * 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
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * 
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
 * 
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU General Public License version 3.
 * 
 * In accordance with Section 7(b) of the GNU General Public License version 3,
 * these Appropriate Legal Notices must retain the display of the "Powered by
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
 * technical reasons, the Appropriate Legal Notices must display the words
 * "Powered by SugarCRM".
 ********************************************************************************/
/*********************************************************************************

 * Description:
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
 * Reserved. Contributor(s): ______________________________________..
 * *******************************************************************************/

// LEGACY for old versions - emulating upload.php
// aw: make this better for later versions.
if (version_compare(substr($sugar_version, 0, 5), '4.5.0', '<')) {
	logThis('emulating upload.php');
	getValidPatchName(false);
}

logThis('at preflight.php');
//set the upgrade progress status.
set_upgrade_progress('preflight','in_progress');


$stop = true; // flag to show "next"
if(isset($_SESSION['files'])) {
	unset($_SESSION['files']);
}

$errors = preflightCheck();

$diffs = '';
$schema = '';
$anyScriptChanges = '';
$db =& PearDatabase::getInstance();

//If version less than 500 then look for modules to be upgraded

if(substr($sugar_version,0,1) < 5 && is_file('modules/UpgradeWizard/upgradeMetaHelper.php')) {
	require_once('modules/UpgradeWizard/upgradeMetaHelper.php');
	$helper = new UpgradeMetaHelper('upgraded451to500Files',$_SESSION['unzip_dir'].'/'.$_SESSION['zip_from_dir']);
}
if((count($errors) == 1)) { // only diffs
	logThis('file preflight check passed successfully.');
	$stop = false;
	$out  = $mod_strings['LBL_UW_PREFLIGHT_TESTS_PASSED'];
	$stop = false;

	$disableEmail = (empty($current_user->email1)) ? 'DISABLED' : 'CHECKED';

	if(count($errors['manual']) > 0) {
		$preserveFiles = array();

		$diffs =<<<eoq
			<script type="text/javascript" language="Javascript">
				function preflightToggleAll(cb) {
					var checkAll = false;
					var form = document.getElementById('diffs');

					if(cb.checked == true) {
						checkAll = true;
					}

					for(i=0; i<form.elements.length; i++) {
						if(form.elements[i].type == 'checkbox') {
							form.elements[i].checked = checkAll;
						}
					}
					return;
				}
			</script>

			<table cellpadding='0' cellspacing='0' border='0'>
				<tr>
					<td valign='top'>
						<input type='checkbox' name='addTask' id='addTask' CHECKED>
					</td>
					<td valign='top'>
						{$mod_strings['LBL_UW_PREFLIGHT_ADD_TASK']}
					</td>
				</tr>
				<tr>
					<td valign='top'>
						<input type='checkbox' name='addEmail' id='addEmail' $disableEmail>
					</td>
					<td valign='top'>
						{$mod_strings['LBL_UW_PREFLIGHT_EMAIL_REMINDER']}
					</td>
				</tr>
			</table>

			<form name='diffs' id='diffs'>
			<p><a href='javascript:void(0); toggleNwFiles("diffsHide");'>{$mod_strings['LBL_UW_SHOW_DIFFS']}</a></p>
			<div id='diffsHide' style='display:none'>
				<table cellpadding='0' cellspacing='0' border='0'>
					<tr>
						<td valign='top' colspan='2'>
							{$mod_strings['LBL_UW_PREFLIGHT_FILES_DESC']}
							<br />&nbsp;
						</td>
					</tr>
					<tr>
						<td valign='top' colspan='2'>
							<input type='checkbox' onchange='preflightToggleAll(this);'>&nbsp;<i><b>{$mod_strings['LBL_UW_PREFLIGHT_TOGGLE_ALL']}</b></i>
							<br />&nbsp;
						</td>
					</tr>
eoq;
		foreach($errors['manual'] as $diff) {
			$diff = clean_path($diff);
			$_SESSION['files']['manual'][] = $diff;

			$checked = (isAutoOverwriteFile($diff)) ? 'CHECKED' : '';

			if(empty($checked)) {
				$preserveFiles[] = $diff;
			}

			$diffs .= "<tr><td valign='top'>";
			$diffs .= "<input type='checkbox' name='diff_files[]' value='{$diff}' $checked>";
			$diffs .= "</td><td valign='top'>";
			$diffs .= str_replace(getcwd(), '.', $diff);
			$diffs .= "</td></tr>";
		}
		$diffs .= "</table>";
		$diffs .= "</div></p>";
		$diffs .= "</form>";

		// list preserved files (templates, etc.)
		$preserve = '';
		foreach($preserveFiles as $pf) {
			if(empty($preserve)) {
				$preserve .= "<table cellpadding='0' cellspacing='0' border='0'><tr><td><b>";
				$preserve .= $mod_strings['LBL_UW_PREFLIGHT_PRESERVE_FILES'];
				$preserve .= "</b></td></tr>";
			}
			$preserve .= "<tr><td valign='top'><i>".str_replace(getcwd(), '.', $pf)."</i></td></tr>";
		}
		if(!empty($preserve)) {
			$preserve .= '</table><br>';
		}
		$diffs = $preserve.$diffs;
	} else { // NO FILE DIFFS REQUIRED
		$diffs = $mod_strings['LBL_UW_PREFLIGHT_NO_DIFFS'];
	}
} else {
	logThis('*** ERROR: found too many preflight errors - displaying errors and stopping execution.');
	$out = "<b>{$mod_strings['ERR_UW_PREFLIGHT_ERRORS']}:</b><hr />";
	$out .= "<span class='error'>";

	foreach($errors as $error) {
		if(is_array($error)) { // manual diff files
			continue;
		} else {
			$out .= "{$error}<br />";
		}
	}
	$out .= "</span><br />";
}

$diffs ='';

///////////////////////////////////////////////////////////////////////////////
////	SCHEMA SCRIPT HANDLING
logThis('starting schema preflight check...');
//Check the current and target versions and store them in session variables
if(!isset($sugar_db_version) || empty($sugar_db_version)) {
	include('./sugar_version.php');
}
if(!isset($manifest['version']) || empty($manifest['version'])) {
	include($_SESSION['unzip_dir'].'/manifest.php');
}
$current_version = substr(preg_replace("#[^0-9]#", "", $sugar_db_version),0,3);
$targetVersion =  substr(preg_replace("#[^0-9]#", "", $manifest['version']),0,3);

//save the versions as session variables
$_SESSION['current_db_version'] = $current_version;
$_SESSION['target_db_version']  = $targetVersion;
$_SESSION['upgrade_from_flavor']  = $manifest['name'];
// aw: BUG 10161: check flavor conversion sql files
$sqlFile = ''; // cn: bug
if($current_version == $targetVersion) {
	switch($manifest['name']){
		case 'SugarCE to SugarPro':
			$sqlFile = $current_version.'_ce_to_pro_'.$db->dbType;
			break;
		case 'SugarCE to SugarEnt':
			$sqlFile = $current_version.'_ce_to_ent_'.$db->dbType;
			break;
		case 'SugarPro to SugarEnt':
			$sqlFile = $current_version.'_pro_to_ent_'.$db->dbType;
			break;
		default:
			break;
	}
} else {
	$sqlFile = $current_version.'_to_'.$targetVersion.'_'.$db->dbType;
}

$newTables = array();

if($db->dbType == 'oci8') {



} else {
	$sqlScript = $_SESSION['unzip_dir'].'/scripts/'.$sqlFile.'.sql';
}



$alterTableSchema = '';
logThis('looking for schema script at: '.$sqlScript);
if(is_file($sqlScript)) {
	logThis('found schema upgrade script: '.$sqlScript);

	logThis('schema preflight using MySQL');
	$fp = fopen($sqlScript, 'r');
	$contents = fread($fp, filesize($sqlScript));
    $anyScriptChanges =$contents;

	// remove __uw_temp tables
	testCleanUp($db->dbType);
	fclose($fp);

	$customTables = getCustomTables($db->dbType);
	if ( !empty($customTables) ) {
		$_SESSION['alterCustomTableQueries'] = alterCustomTables($db->dbType, $customTables);
	} else {
		$_SESSION['alterCustomTableQueries'] = false;
	}

	$_SESSION['allTables'] = getAllTables($db->dbType);

   //if db is mssql then add the drop constraints sql
    $contents_drop_constraints = '';
    if($db->dbType == 'mssql') {
	  if(substr($sugar_version,0,1) < 5){
		 require_once($_SESSION['unzip_dir'].'/scripts/upgrade_sqlsvr5.php');
		 $contents_drop_constraints = upgrade5_sqlsvr(true);
	  }
    }

	$schema  = "<p><a href='javascript:void(0); toggleNwFiles(\"schemashow\");'>{$mod_strings['LBL_UW_SHOW_SCHEMA']}</a>";
	$schema .= "<div id='schemashow' style='display:none;'>";
	if($db->dbType == 'mssql' && $contents_drop_constraints != null){
		$schema .= "<textarea readonly cols='80' rows='5'>{$contents_drop_constraints}</textarea>";
    }
	$schema .= "<textarea readonly cols='80' rows='10'>{$contents}</textarea>";
	$schema .= "</div></p>";

	if(version_compare($current_version, '450', "<")) {
		if(isset($_SESSION['allTables']) && !empty($_SESSION['allTables'])) {
			$alterTableContents = printAlterTableSql($_SESSION['allTables']);
			$alterTableSchema  = "<p><a href='javascript:void(0); toggleNwFiles(\"alterTableSchemashow\");'>{$mod_strings['LBL_UW_CHARSET_SCHEMA_CHANGE']}</a>";
			$alterTableSchema .= "<div id='alterTableSchemashow' style='display:none;'>";
			$alterTableSchema .= "<textarea readonly cols='80' rows='10'>{$alterTableContents}</textarea>";
			$alterTableSchema .= "</div></p>";
		}
	} else {
		$alterTableSchema = '<i>'.$mod_strings['LBL_UW_PREFLIGHT_NOT_NEEDED'].'</i>';
	}

	if(!empty($sqlErrors)) {
		$stop = true;
		$out = "<b class='error'>{$mod_strings['ERR_UW_PREFLIGHT_ERRORS']}:</b> ";
		$out .= "<a href='javascript:void(0);toggleNwFiles(\"sqlErrors\");'>{$mod_strings['LBL_UW_SHOW_SQL_ERRORS']}</a><div id='sqlErrors' style='display:none'>";
		foreach($sqlErrors as $sqlError) {
			$out .= "<br><span class='error'>{$sqlError}</span>";
		}
		$out .= "</div><hr />";
	}
} else {
	$customTableSchema = '';
	logThis('no schema script found - all schema preflight skipped');
}
logThis('schema preflight done.');
////	END SCHEMA SCRIPT HANDLING
///////////////////////////////////////////////////////////////////////////////

////BEGIN EDIT VIEW & DETAIL VIEW METAPARSER
///////////////////////////////////////////////////////////////////////////
/*
logThis('Running EditView and DetailView Metaparser.');
if(file_exists('modules/UpgradeWizard/upgradeMetaHelper.php'))
	require_once('modules/UpgradeWizard/upgradeMetaHelper.php');
$helper = new UpgradeHelper();
//echo "<h1>Session['unzip_dir']</h1><br>";
//echo $_SESSION['unzip_dir'];
//echo "<h1>Session['zip_from_dir']</h1><br>";
//echo $_SESSION['zip_from_dir'];

$helper->init(array(), $_SESSION['unzip_dir'], $_SESSION['zip_from_dir'] ); //pass modules array from getChangedModules()
*/

/*
 * Get a list of changed modules.
 * Compare 451f client's md5 with the md5 file in cache/upload directory
 * If md5's are different, include module for parsing.
 */
function getChangedModules()
{
	//stub out. for now use only studio enabled modules.
	return array();
}

logThis('EditView and DetailView Metaparser done.');
////END EDIT VIEW & DETAIL VIEW METAPARSER
///////////////////////////////////////////////////////////////////////////


$final =<<<eoq
<table cellpadding="3" cellspacing="0" border="0">
	<tr>
		<th colspan="2" align="left">
			<b>{$mod_strings['LBL_UW_PREFLIGHT_COMPLETE']}</b><hr />
		</th>
	</tr>
	<tr>
		<td colspan="2" align="left" valign="top">
			{$out}
		</td>
	</tr>
	<tr>
		<td align="left" valign="top">
			<b>{$mod_strings['LBL_UW_MANUAL_MERGE']}</b>
		</td>
		<td align="left" valign="top">
			{$diffs}
		</td>
	</tr>
	<tr>
		<td colspan="3">&nbsp;</td>
	</tr>
	<tr>
		<td align="left" valign="top">
			<b>{$mod_strings['LBL_UW_SCHEMA_CHANGE']}</b>
		</td>
		<td align="left" valign="top">
			{$schema}
		</td>
	</tr>

	<tr>
		<td align="left" valign="top">
			<b>{$mod_strings['LBL_UW_CHARSET_SCHEMA_CHANGE']}</b>
		</td>
		<td align="left" valign="top">
			{$alterTableSchema}
		</td>
	</tr>

	<tr>
		<td>
		</td>
		<td valign="top">
			<div>
			<b>{$mod_strings['LBL_UW_DB_METHOD']}</b><br />
			<select name="schema_change" id="select_schema_change" onchange="checkSqlStatus(false);">
				<option value="sugar">{$mod_strings['LBL_UW_DB_CHOICE1']}</option>
				<option value="manual">{$mod_strings['LBL_UW_DB_CHOICE2']}</option>
			</select>
			</div>
			<div id='show_sql_run' style='display:none'>
				<input type='checkbox' name='sql_run' id='sql_run' onmousedown='checkSqlStatus(true);'> {$mod_strings['LBL_UW_SQL_RUN']}
			</div>
		</td>
	</tr>
</table>

eoq;
$form5 =<<<eoq5
<br>
<div id="upgradeDiv" style="display:none">
    <table cellspacing="0" cellpadding="0" border="0">
        <tr><td>
           <p><img src='modules/UpgradeWizard/processing.gif'> <br>{$mod_strings['LBL_UPGRADE_TAKES_TIME_HAVE_PATIENCE']}</p>
        </td></tr>
     </table>
 </div>

eoq5;
if($anyScriptChanges != null){
	$uwMain = $final.$form5;
}
else{
	$uwMain = $form5;
}

//set the upgrade progress status.
set_upgrade_progress('preflight','done');


$showBack		= false;
$showCancel		= true;
$showRecheck	= true;
$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';
?>
