<?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): ______________________________________..
 * *******************************************************************************/
$_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'];
if(didThisStepRunBefore('commit')){
	$_SESSION['committed'] = true;
}
else{
	set_upgrade_progress('commit','in_progress','commit','in_progress');
}
//Initialize session errors array
if(!isset($_SESSION['sqlSkippedQueries']) && !is_array($_SESSION['sqlSkippedQueries'])){
	$_SESSION['sqlSkippedQueries'] = array();
}
// prevent "REFRESH" double commits
if(!isset($_SESSION['committed'])) {
	//$_SESSION['committed'] = true; // flag to prevent refresh double-commit
	//set the flag at the end though
	unset($_SESSION['rebuild_relationships']);
	unset($_SESSION['rebuild_extensions']);
    //put checks for follwing files

	if(!isset($_SESSION['unzip_dir']) || empty($_SESSION['unzip_dir'])) {
		logThis('unzipping files in upgrade archive...');
		$errors					= array();
		$base_upgrade_dir		= $sugar_config['upload_dir'] . "/upgrades";
		$base_tmp_upgrade_dir	= "$base_upgrade_dir/temp";
		$unzip_dir = '';
		//also come up with mechanism to read from upgrade-progress file
		if(!isset($_SESSION['install_file']) || empty($_SESSION['install_file']) || !is_file($_SESSION['install_file'])) {
			if (file_exists(clean_path($base_tmp_upgrade_dir)) && $handle = opendir(clean_path($base_tmp_upgrade_dir))) {
		    		while (false !== ($file = readdir($handle))) {
		    		if($file !="." && $file !="..")	{
					 //echo $base_tmp_upgrade_dir."/".$file.'</br>';
					 if(is_file($base_tmp_upgrade_dir."/".$file."/manifest.php")){
					 	require_once($base_tmp_upgrade_dir."/".$file."/manifest.php");
					 	$package_name= $manifest['copy_files']['from_dir'];
					 	//echo file_exists($base_tmp_upgrade_dir."/".$file."/".$package_name).'</br>';
					 	if(file_exists($base_tmp_upgrade_dir."/".$file."/".$package_name) && file_exists($base_tmp_upgrade_dir."/".$file."/scripts") && file_exists($base_tmp_upgrade_dir."/".$file."/manifest.php")){
					 		//echo 'Yeah this the directory '. $base_tmp_upgrade_dir."/".$file;
					 		$unzip_dir = $base_tmp_upgrade_dir."/".$file;
					 		if(file_exists($sugar_config['upload_dir'].'/upgrades/patch/'.$package_name.'.zip')){
					 			$_SESSION['install_file'] = $sugar_config['upload_dir'].'/upgrades/patch/'.$package_name.'.zip';
					 			break;
					 		}
						}
					  }
		    		}
		    	}
			}
		}
        if(!isset($_SESSION['install_file']) || empty($_SESSION['install_file'])){
        	unlinkTempFiles();
        	resetUwSession();
        	echo 'Upload File not found so redirecting to Upgrade Start ';
        	$redirect_new_wizard = $sugar_config['site_url' ].'/index.php?module=UpgradeWizard&action=index';
        	echo '<form name="redirect" action="' .$redirect_new_wizard. '"  method="POST">';
$upgrade_directories_not_found =<<<eoq
	<table cellpadding="3" cellspacing="0" border="0">
		<tr>
			<th colspan="2" align="left">
				<span class='error'><b>'Upload file missing or has been deleted. Refresh the page to go back to UpgradeWizard start'</b></span>
			</th>
		</tr>
	</table>
eoq;
$uwMain = $upgrade_directories_not_found;
				return '';
        }
		$install_file			= urldecode( $_SESSION['install_file'] );
		$show_files				= true;
		if(empty($unzip_dir)){
			$unzip_dir				= mk_temp_dir( $base_tmp_upgrade_dir );
		}
		$zip_from_dir			= ".";
		$zip_to_dir				= ".";
		$zip_force_copy			= array();

		if(!$unzip_dir){
			logThis('Could not create a temporary directory using mk_temp_dir( $base_tmp_upgrade_dir )');
			die($mod_strings['ERR_UW_NO_CREATE_TMP_DIR']);
		}

		//double check whether unzipped .
		if(file_exists($unzip_dir ."/scripts") && file_exists($unzip_dir."/manifest.php")){
        	//already unzipped
		}
		else{
			unzip( $install_file, $unzip_dir );
		}

		// assumption -- already validated manifest.php at time of upload
		require_once( "$unzip_dir/manifest.php" );

		if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
		    $zip_from_dir   = $manifest['copy_files']['from_dir'];
		}
		if( isset( $manifest['copy_files']['to_dir'] ) && $manifest['copy_files']['to_dir'] != "" ){
		    $zip_to_dir     = $manifest['copy_files']['to_dir'];
		}
		if( isset( $manifest['copy_files']['force_copy'] ) && $manifest['copy_files']['force_copy'] != "" ){
		    $zip_force_copy     = $manifest['copy_files']['force_copy'];
		}
		if( isset( $manifest['version'] ) ){
		    $version    = $manifest['version'];
		}
		if( !is_writable( "config.php" ) ){
			return $mod_strings['ERR_UW_CONFIG'];
		}

		$_SESSION['unzip_dir'] = clean_path($unzip_dir);
		$_SESSION['zip_from_dir'] = clean_path($zip_from_dir);
		logThis('unzip done.');
	} else {
		$unzip_dir = $_SESSION['unzip_dir'];
		$zip_from_dir = $_SESSION['zip_from_dir'];
	}

    //check if $_SESSION['unzip_dir'] and $_SESSION['zip_from_dir'] exist
	if(!isset($_SESSION['unzip_dir']) || !file_exists($_SESSION['unzip_dir'])
		|| !isset($_SESSION['install_file']) || empty($_SESSION['install_file']) || !file_exists($_SESSION['install_file'])){
		    //redirect to start
	    unlinkTempFiles();
		resetUwSession();
		echo 'Upload File not found so redirecting to Upgrade Start ';
		$redirect_new_wizard = $sugar_config['site_url' ].'/index.php?module=UpgradeWizard&action=index';
		echo '<form name="redirect" action="' .$redirect_new_wizard. '"  method="POST">';
$upgrade_directories_not_found =<<<eoq
	<table cellpadding="3" cellspacing="0" border="0">
		<tr>
			<th colspan="2" align="left">
				<span class='error'><b>'Upload file missing or has been deleted. Refresh the page to go back to UpgradeWizard start'</b></span>
			</th>
		</tr>
	</table>
eoq;
$uwMain = $upgrade_directories_not_found;
				return '';
	}
	$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
	if(!didThisStepRunBefore('commit','commitMakeBackupFiles')){
		set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','in_progress');
		$errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
		set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','done');
	}
	////	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()...');
			if(!didThisStepRunBefore('commit','pre_install')){
				set_upgrade_progress('commit','in_progress','pre_install','in_progress');
				pre_install();
				set_upgrade_progress('commit','in_progress','pre_install','done');
			}
			logThis('pre_install() done.');
		}
	}

	////	HANDLE PREINSTALL SCRIPTS
	///////////////////////////////////////////////////////////////////////////////

        //require_once('modules/Administration/cleanup50.php');
        // All the Studio customized modules should be preserved in pre_500 folder
		$customized_mods = '';
        if(substr($sugar_version,0,1) < 5){
	         if(isset($_SESSION['Customized_Modules']) && $_SESSION['Customized_Modules'] != null){
	        	$customized_mods = $_SESSION['Customized_Modules'];
	        	$dir = clean_path(getcwd().'/customized451modules');
				if(!file_exists($dir)) {
					mkdir($dir, 0755);
				}
				$customizedModulesdir = $dir.'/modules';
				if(!file_exists($customizedModulesdir)) {
					mkdir($customizedModulesdir, 0755);
				}
	        	foreach($customized_mods as $module_name=>$files) {
					if(is_dir($customizedModulesdir)){
					 //put the customized files from 451
					 mkdir($customizedModulesdir.'/'.$module_name,0755);
					 copyRecursiveBetweenDirectories(clean_path(getcwd()).'/modules/'.$module_name,$customizedModulesdir.'/'.$module_name);
					}
				}
	         }
		}

        //Force clean files not required for MVC. This is to make sure if a file which shouldn't
        //be in MVC is removed even though customized. All the customized files are save anyway.
        //Also check if the current version is same as target version
        if(substr($sugar_version,0,1) < 5){
	        if(!didThisStepRunBefore('commit','cleaningNonMVCFiles')){
	        	set_upgrade_progress('commit','in_progress','cleaningNonMVCFiles','in_progress');
	        	logThis('Start cleaning Non MVC files...');
		        	cleaningNonMVCFiles();
		        logThis('End cleaning Non MVC files...');
		        set_upgrade_progress('commit','in_progress','cleaningNonMVCFiles','done');
	         }
	        //Removing file which match the md5
	        if(!didThisStepRunBefore('commit','removingMD5MatchingFiles')){
		        set_upgrade_progress('commit','in_progress','removingMD5MatchingFiles','in_progress');
		        logThis('Start cleaning matching md5 files...');
			        $deleteNot=array('en_us.lang.php','company.jpg','Forms.php');
			        //removeMd5MatchingFiles($deleteNot);
			        if(!isset($_SESSION['removingMD5MatchingFiles']) && empty($_SESSION['removingMD5MatchingFiles'])){
				        removeMd5MatchingFiles($deleteNot);
			         }
			        else{
				        foreach($_SESSION['removingMD5MatchingFiles'] as $f){
							if(file_exists($f) && !in_array(basename($f),$deleteNot)){
								unlink($f);
							}
						}
			        }
			    set_upgrade_progress('commit','in_progress','removingMD5MatchingFiles','done');
		        logThis('End cleaning matching md5 files...');
	        }
        }
        //Clean smarty from cache
        if(is_dir('cache/smarty')){
        	$allModFiles = array();
        	$allModFiles = findAllFiles('cache/smarty',$allModFiles);
           foreach($allModFiles as $file){
	           	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
	           	if(file_exists($file)){
					unlink($file);
	           	}
           }
        }
         //COPY ALL FILES FROM UPLOADED UPGRADE PACKAGE

         if(!didThisStepRunBefore('commit','commitCopyNewFiles')){
				set_upgrade_progress('commit','in_progress','commitCopyNewFiles','in_progress');
				$split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
		 		$copiedFiles = $split['copiedFiles'];
		 		$skippedFiles = $split['skippedFiles'];
				set_upgrade_progress('commit','in_progress','commitCopyNewFiles','done');
		 }
		 //END COPY NEW FILES INTO TARGET INSTANCE

         if($customized_mods != null){
	    	foreach($customized_mods as $module_name=>$files) {
				mkdir(clean_path(getcwd().'/modules/'.$module_name.'/.pre_500'), 0755);
				mkdir(clean_path(getcwd().'/modules/'.$module_name.'/.500'), 0755);
				if(is_dir(clean_path(getcwd().'/modules/'.$module_name.'/.pre_500'))){
				 //put llthe files from module into pre_500
				 copyRecursiveBetweenDirectories(clean_path(getcwd()).'/customized451modules/modules/'.$module_name,clean_path(getcwd()).'/modules/'.$module_name.'/.pre_500');
			     //run these only in pre_500 modules
			     $cur_dir =clean_path(getcwd()).'/modules/'.$module_name.'/.pre_500';
			     if(!file_exists($cur_dir.'/metadata/subpaneldefs.php')){
			     	rename($cur_dir.'/layout_defs.php', $cur_dir.'/metadata/subpaneldefs.php');
			     }
			     if(!file_exists($cur_dir.'/metadata/subpanels')){
			     	rename($cur_dir.'/subpanels', $cur_dir.'/metadata/subpanels');
			     }
			     //Copy 500 dashlet files to the pre_500 module dashlet directory
			     if(file_exists($cur_dir.'/Dashlets')){
			     	//first clean the directory
			     	rmdir_recursive($cur_dir.'/Dashlets');
			     	//then copy from 500 to pre_500
			     	if(file_exists(clean_path(getcwd()).'/modules/'.$module_name.'/Dashlets')){
			     		copyRecursiveBetweenDirectories(clean_path(getcwd()).'/modules/'.$module_name.'/Dashlets',$cur_dir.'/Dashlets');
			     	}
			     }
				}
			 }
          }

        $upgraded_mods = '';
        if(substr($sugar_version,0,1) < 5){
	        if(isset($_SESSION['Upgraded_Modules']) && $_SESSION['Upgraded_Modules']){
	  			$upgraded_mods = $_SESSION['Upgraded_Modules'];
	        }
        }

	///////////////////////////////////////////////////////////////////////////////

	///////////////////////////////////////////////////////////////////////////////
	////	HANDLE POSTINSTALL SCRIPTS
	logThis('Starting post_install()...');
	if(empty($errors)) {
		if(!didThisStepRunBefore('commit','post_install')){
			$file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
			if(is_file($file)) {
				//set_upgrade_progress('commit','in_progress','post_install','in_progress');
				$progArray['post_install']='in_progress';
				post_install_progress($progArray,'set');
				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']);
				//set process to done
				$progArray['post_install']='done';
				//set_upgrade_progress('commit','in_progress','post_install','done');
				post_install_progress($progArray,'set');
			}
		}

    if(substr($sugar_version,0,1) < 5){
	    //delete yui2
		if(file_exists(clean_path(getcwd()).'/include/javascript/yui2')){
			copyRecursiveBetweenDirectories(clean_path(getcwd()).'/include/javascript/yui2',clean_path(getcwd()).'/include/javascript/yui');
			rmdir_recursive(clean_path(getcwd()).'/include/javascript/yui2');
		}
		//also copying the customized modules to the custom modules for upgrade
		if(file_exists(clean_path(getcwd()).'/upgraded451to500Files')){
			//copyRecursiveBetweenDirectories(clean_path(getcwd()).'/upgraded451to500Files/modules',clean_path(getcwd()).'/modules');
		    if(!file_exists(clean_path(getcwd()).'/custom')){
		    	mkdir(clean_path(getcwd()).'/custom', 0755);
		    }
		    if(!file_exists(clean_path(getcwd()).'/custom/modules')){
		    	mkdir(clean_path(getcwd()).'/custom/modules', 0755);
		    }
			copyRecursiveBetweenDirectories(clean_path(getcwd()).'/upgraded451to500Files/modules',clean_path(getcwd()).'/custom/modules');
			rmdir_recursive(clean_path(getcwd()).'/upgraded451to500Files');
		 }
		if(file_exists(clean_path(getcwd()).'/customized451modules')){
			rmdir_recursive(clean_path(getcwd()).'/customized451modules');
		 }
    }
       if($_SESSION['current_db_version'] != $_SESSION['target_db_version']){
			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
	///////////////////////////////////////////////////////////////////////////////
if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){

	$_SESSION['license_seats_needed'] = '';
	//Clean modules from cache
    if(is_dir('cache/modules')){
    	$allModFiles = array();
    	$allModFiles = findAllFiles('cache/modules',$allModFiles);
       foreach($allModFiles as $file){
           	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
           	if(file_exists($file)){
				unlink($file);
           	}
       }
    }
    //Clean jsLanguage from cache
    if(is_dir('cache/jsLanguage')){
    	$allModFiles = array();
    	$allModFiles = findAllFiles('cache/jsLanguage',$allModFiles);
       foreach($allModFiles as $file){
           	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
           	if(file_exists($file)){
				unlink($file);
           	}
       }
    }
}
//cleanup cache modules
if(substr($sugar_version,0,1) == 5){
		//Clean modules from cache
    if(is_dir('cache/modules')){
    	$allModFiles = array();
    	$allModFiles = findAllFiles('cache/modules',$allModFiles);
       foreach($allModFiles as $file){
           	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
           	if(file_exists($file)){
				unlink($file);
           	}
       }
    }
}
	///////////////////////////////////////////////////////////////////////////////
	////	REGISTER UPGRADE

	logThis('Registering upgrade with UpgradeHistory');
	if(!didThisStepRunBefore('commit','upgradeHistory')){
		set_upgrade_progress('commit','in_progress','upgradeHistory','in_progress');
		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();
		}
		set_upgrade_progress('commit','in_progress','upgradeHistory','done');
	}
	////	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;
}
if(substr($sugar_version,0,1) < 5){
	//check for customized or upgraded modules
	if($customized_mods != null || $upgraded_mods != null){
		$customized_mods_Desc .= "<b>{$mod_strings['LBL_UW_CUSTOMIZED_OR_UPGRADED_MODULES']}</b><br />";
		$customized_mods_Desc .= "<a href='javascript:void(0); toggleNwFiles(\"customizedModules\");'>{$mod_strings['LBL_UW_SHOW']}</a>";
		$customized_mods_Desc .= "<div id='customizedModules' style='display:none;'>";
	    if($upgraded_mods != null){
		     $customized_mods_Desc .= $mod_strings['LBL_UW_FOLLOWING_MODULES_UPGRADED']. "<br />";
		     foreach($upgraded_mods as $upgraded_module_name=>$files) {
				$customized_mods_Desc .= $upgraded_module_name . "<br />";
			 }
	    }
	    if($customized_mods != null){
			$customized_mods_Desc .= $mod_strings['LBL_UW_FOLLOWING_MODULES_CUSTOMIZED']. "<br />";
			foreach($customized_mods as $customized_module_name=>$files) {
				$customized_mods_Desc .= $customized_module_name . "<br />";
			}
		}
		$customized_mods_Desc .= "</div>";
	}
}

$customized_mods_Desc = '';
$old_schema= '';
$old_schema_opt = '';
$skipped_queries = '';
if($_SESSION['current_db_version'] != $_SESSION['target_db_version']){
    global $sugar_version;
    $origVersion = substr(preg_replace("/[^0-9]/", "", $_SESSION['current_db_version']),0,3);
	$destVersion = substr(preg_replace("/[^0-9]/", "", $_SESSION['target_db_version']),0,3);

	//old schema to be dropped
	$old_schema_contents = '';
	if(file_exists($_SESSION['unzip_dir'].'/scripts/drop_'.$origVersion.'_schema_after_upgrade_'.$destVersion.'.php')){
		require_once($_SESSION['unzip_dir'].'/scripts/drop_'.$origVersion.'_schema_after_upgrade_'.$destVersion.'.php');
		ob_start();
			$old_schema_contents=@drop_preUpgardeSchema(true);
		ob_end_clean();
	}
	if($old_schema_contents != null && strlen($old_schema_contents) >0){
		$old_schema  = "<p><a href='javascript:void(0); toggleNwFiles(\"old_schemashow\");'>{$mod_strings['LBL_UW_SHOW_OLD_SCHEMA_TO_DROP']}</a>";
		$old_schema .= "<div id='old_schemashow' style='display:none;'>";
		$old_schema .= "<textarea readonly cols='80' rows='10'>{$old_schema_contents}</textarea>";
		$old_schema .= "</div></p>";

		$old_schema_opt="<b>{$mod_strings['LBL_UW_DROP_SCHEMA_METHOD']}</b>
						<select name=\"schema_drop\" id=\"select_schema_drop\" onchange=\"checkSchemaDropStatus();\">
							<option value=\"manual\">{$mod_strings['LBL_UW_DROP_SCHEMA_MANUAL']}</option>
							<option value=\"sugar\">{$mod_strings['LBL_UW_DROP_SCHEMA_UPGRADE_WIZARD']}</option>
						</select>
					";
	}
}

$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>";

$rebuildResult = '';

//moving unlink files to last
//unlinkTempFiles();


$skipped_queries_Desc='';
if(isset($_SESSION['sqlSkippedQueries']) && $_SESSION['sqlSkippedQueries'] != null && is_array($_SESSION['sqlSkippedQueries']) && sizeof($_SESSION['sqlSkippedQueries'])>0){
	$skipped_queries_Desc .= "<b>{$mod_strings['LBL_UW_SKIPPED_QUERIES_ALREADY_EXIST']}</b><br />";
	$skipped_queries_Desc .= "<a href='javascript:void(0); toggleNwFiles(\"skippedQueries\");'>{$mod_strings['LBL_UW_SHOW']}</a>";
	$skipped_queries_Desc .= "<div id='skippedQueries' style='display:none;'>";
	if($_SESSION['sqlSkippedQueries'] != null){
	     $skipped_queries_Desc .= $mod_strings['LBL_UW_SKIPPED_QUERIES_ALREADY_EXIST']. "<br />";
	     foreach($_SESSION['sqlSkippedQueries'] as $skippedQ) {
			$skipped_queries_Desc .= $skippedQ . "<br />";
		 }
	}
 }


///////////////////////////////////////////////////////////////////////////////
////	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>
			{$customized_mods_Desc}
			</p>
			<p>
			{$copiedDesc}
			</p>
			<p>
			{$skippedDesc}
			</p>
			<p>
			{$skipped_queries_Desc}
			</p>
			<p>
			{$rebuildResult}
			</p>
		</td>
	</tr>
	<tr><td>
		<p>
		{$old_schema}
		</p>
	</td></tr>
	<tr><td>
		{$old_schema_opt}
	</td></tr>
</table>
<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>
 <script>
function checkSchemaDropStatus() {
	if(document.getElementById('select_schema_drop') != null){
		var schemaSelect = document.getElementById('select_schema_drop');
		var schemaDropMethod = document.getElementById('schema_drop');
		if(schemaSelect.options[schemaSelect.selectedIndex].value == 'manual') {
			schemaDropMethod.value = 'manual';
		} else {
			schemaDropMethod.value = 'sugar';
		}
   }
}
 checkSchemaDropStatus();
 </script>
eoq;

//set the upgrade progress status.
set_upgrade_progress('commit','done','commit','done');
$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';
?>
