<?php
/*********************************************************************************
 * 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-2005 SugarCRM, Inc.;
 * All Rights Reserved.
 * Contributor(s): ______________________________________.
 ********************************************************************************/

// $Id: index.php,v 1.38 2005/09/26 08:02:13 jacob Exp $

error_reporting(E_ALL ^ E_NOTICE);
chdir( ".." );

@require_once('log4php/LoggerManager.php');
if (class_exists('LoggerManager')) {
	$GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');	
}

session_start();

if (substr(phpversion(), 0, 1) == "5"){
	ini_set("zend.ze1_compatibility_mode", "1");
}

require_once( "upgrade/dir_inc.php" );
if(!file_exists('config.php')){
	// add something here
}
require_once('config.php');
$current_version    = "3.5.1";
$current_patch      = "";


require_once('include/utils.php');
require_once('include/database/PearDatabase.php');
$db = new PearDatabase();
$db->resetSettings();

// increase the cuttoff time to 1 hour
ini_set("max_execution_time", "3600");

//$result = $db->query( "SELECT value FROM config WHERE category='info' AND name='sugar_version'" );
$result = $db->query( "SELECT file_version FROM versions WHERE name = 'App Version'" );
if (!empty($result)) {
	$row = $db->fetchByAssoc( $result );
	if (!empty($row)) {
		if( $row['file_version'] == $current_version ){
	    	die( "Database already upgraded to current version: $current_version." );
		}		
	}	
}
/*$rowCount = $db->getRowCount($result);
$rows = $db->fetchByAssoc($result);
print_r("chris.".$rows);

if($rowCount > 0) {
	$row = $db->fetchByAssoc( $result );

	if( $row['file_version'] == $current_version ){
	    die( "Database already upgraded to current version: $current_version." );
	}
}*/



$upgrade_script = true;



// form validation/conversion to boolean
function get_boolean_from_request( $field ){
    if( !isset($_REQUEST[$field]) ){
        return( false );
    }

    if( ($_REQUEST[$field] == 'on') || ($_REQUEST[$field] == 'yes') ){
        return(true);
    }
    else {
        return(false);
    }
}

function stripslashes_checkstrings($value){
   if(is_string($value)){
      return stripslashes($value);
   }
   return $value;
}

if(get_magic_quotes_gpc() == 1){
   $_REQUEST = array_map("stripslashes_checkstrings", $_REQUEST);
   $_POST = array_map("stripslashes_checkstrings", $_POST);
   $_GET = array_map("stripslashes_checkstrings", $_GET);
}

function print_debug_array( $name, $debug_array ){
    ksort( $debug_array );

    print( "$name vars:\n" );
    print( "(\n" );

    foreach( $debug_array as $key => $value ){
        if( stristr( $key, "password" ) ){
            $value = "WAS SET";
        }
        print( "    [$key] => $value\n" );
    }

    print( ")\n" );
}

function print_debug_comment(){
    if( !empty($_REQUEST['debug']) ){
        $_SESSION['debug'] = $_REQUEST['debug'];
    }

    if( !empty($_SESSION['debug']) && ($_SESSION['debug'] == 'true') ){
        print( "<!-- debug is on (to turn off, hit any page with 'debug=false' as a URL parameter.\n" );

        print_debug_array( "Session",   $_SESSION );
        print_debug_array( "Request",   $_REQUEST );
        print_debug_array( "Post",      $_POST );
        print_debug_array( "Get",       $_GET );

        print_r( "-->\n" );
    }
}

function getUpgradeFromVersion( $version_file = "sugar_version.php" ){
    require_once( $version_file );
    if( preg_match( "/^3\.0\.1/", $sugar_version ) ){
        $_SESSION['upgrade_from_version'] = "3.0.1";
    }
    else if( preg_match( "/^3\.0/", $sugar_version ) ){
        $_SESSION['upgrade_from_version'] = "3.0";
    }
    else if( preg_match( "/^2\.5\.1/", $sugar_version ) ){
        $_SESSION['upgrade_from_version'] = "2.5.1";
    }
    return( $_SESSION['upgrade_from_version'] );
}

function validate_settings(){
    global $sugar_config;
    global $current_version;
    global $current_patch;

    $errors = array();

    if( $_SESSION['upgrade_target_dir'] == '' ){
        $errors[] = 'Current Sugar Directory cannot be empty.';
    }
    else if( !is_dir( $_SESSION['upgrade_target_dir'] ) ){
        $errors[] = 'The specified Current Sugar Directory does not exist.';
    }
    else if( !is_file( $_SESSION['upgrade_target_dir'] . "/sugar_version.php" ) ){
        $errors[] = 'The specified Current Sugar Directory does not appear to be the base directory.';
    }
    else{
        $upgrade_from_version = getUpgradeFromVersion( $_SESSION['upgrade_target_dir'] . "/sugar_version.php" );
        if(
            ($upgrade_from_version != "3.0.1")  &&
            ($upgrade_from_version != "3.0")    &&
            ($upgrade_from_version != "2.5.1")      ){
                $errors[] = "Sugar Directory is version $sugar_version, but only upgrades from 2.5.1 through 3.0.1 are currently supported.";
        }

        if( count($errors) == 0 ){
            $original_dir   = getCwd();

            chdir( $_SESSION['upgrade_target_dir'] );
            $all_dest_files = findAllFiles( ".", array() );

            foreach( $all_dest_files as $dest_file ){
                if( !is_writable( $dest_file ) ){
                    $errors[] = "All files under " . $_SESSION['upgrade_target_dir'] . " need to be writable.";
                    break;
                }
            }
            chdir( $original_dir );
        }
    }

    if( $_SESSION['upgrade_source_dir'] == '' ){
        $errors[] = "Sugar $current_version Directory cannot be empty.";
    }
    else if( !is_dir( $_SESSION['upgrade_source_dir'] ) ){
        $errors[] = "The specified Sugar $current_version Directory does not exist.";
    }
    else if( !is_file( $_SESSION['upgrade_source_dir'] . "/sugar_version.php" ) ){
        $errors[] = "The specified Sugar $current_version Directory does not appear to be the base directory.";
    }
    else{
        include_once( $_SESSION['upgrade_source_dir'] . "/sugar_version.php" );
        if( "$current_version$current_patch" != $sugar_version ){
            $errors[] = "Sugar Directory is version $sugar_version, but should be $current_version$current_patch.";
        }
    }

    if( $_SESSION['upgrade_db_admin_username'] == '' ){
        $errors[] = 'Privileged database account name cannot be empty.';
    }

    if( count($errors) == 0 ){
        $db_name = $sugar_config['dbconfig']['db_host_name'];
        $db_user = $_SESSION['upgrade_db_admin_username'];
        $db_pass = $_SESSION['upgrade_db_admin_password'];

        $link = @mysql_connect( $db_name, $db_user, $db_pass );
        if( $link ){
            // check mysql minimum version requirement
            $query = "select version()";
            $result = mysql_query($query, $link);
            $row = mysql_fetch_row( $result );
            $db_version = $row[0];
            if( !preg_match( "/^4.*/", $db_version ) && !preg_match( "/^5.*/", $db_version ) ){
                $errors[] = "MySQL version $db_version is not supported.  Only MySQL 4.0.x and higher is supported.";
            }

            mysql_close($link);
        }
        else{
            $errors[] = "Could not instantiate db connection to database $db_name as user $db_user and the supplied password.";
        }
    }
    return $errors;
}

print_debug_comment();


$next_clicked = false;
$next_step = 0;

// increment/decrement the workflow pointer
if(!empty($_REQUEST['goto'])){
    switch($_REQUEST['goto']){
        case 'Re-check':
            $next_step = $_REQUEST['current_step'];
            break;
        case 'Back':
            $next_step = $_REQUEST['current_step'] - 1;
            break;
        case 'Next':
        case 'Start':
            $next_step = $_REQUEST['current_step'] + 1;
            $next_clicked = true;
            break;
    }
}



// use a simple array to map out the steps of the upgrade page flow
// building the array is not so simple, but 
$workflow = array(
                'checklist.php',
                'settings.php',
                'copyFiles.php',
                'configFile.php',
            );

if( !empty($_SESSION['upgrade_from_version']) ){
    switch( $_SESSION['upgrade_from_version'] ){
        case "2.5.1":
            array_push( $workflow,
                        '30runSql.php',
                        '30phpCalls.php' );
        case "3.0":
            array_push( $workflow,
                        '301runSql.php' );
        case "3.0.1":
            array_push( $workflow,
                        'runSql.php',
                        'phpCalls.php' );
            break;
        default:
            die( "Unable to upgrade from version " . $_SESSION['upgrade_from_version'] );
    }
}

array_push( $workflow, 
                'gmtupgradeto3_5.php',



                'fin.php' );

$validation_errors = array();

// process the data posted
if($next_clicked){
    // store the submitted data because the 'Next' button was clicked
    switch($workflow[$_REQUEST['current_step']]){
        case 'checklist.php':
            $_SESSION['upgrade_checklist_submitted']    = true;
            $_SESSION['upgrade_checklist_accept']       = get_boolean_from_request( 'upgrade_checklist_accept' );
            break;
        case 'settings.php':
            $_SESSION['upgrade_settings_submitted']     = true;
            $_SESSION['upgrade_target_dir']             = $_REQUEST['upgrade_target_dir'];
            $_SESSION['upgrade_source_dir']             = $_REQUEST['upgrade_source_dir'];
            $_SESSION['upgrade_db_admin_username']      = $_REQUEST['upgrade_db_admin_username'];
            $_SESSION['upgrade_db_admin_password']      = $_REQUEST['upgrade_db_admin_password'];

            $validation_errors = validate_settings();
            if( count($validation_errors) > 0 ){
                $next_step--;
            }

            break;
    }
}

$the_file = $workflow[$next_step];

require( $the_file );
print_debug_comment();
?>
