<?php
/**
 * Upgrade Wizard
 *
 * 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: UpgradeWizard.php,v 1.26 2005/09/26 07:34:02 jacob Exp $

require_once('modules/Administration/UpgradeWizardCommon.php');
global $mod_strings;
$uh = new UpgradeHistory();

// make sure dirs exist
foreach( $subdirs as $subdir ){
    mkdir_recursive( "$base_upgrade_dir/$subdir" );
}

// get labels and text that are specific to either Module Loader or Upgrade Wizard
if( $view == "module") {
	$uploaddLabel = $mod_strings['LBL_UPLOAD_MODULE'];
	$descItemsQueued = $mod_strings['DESC_MODULES_QUEUED'];
	$descItemsInstalled = $mod_strings['DESC_MODULES_INSTALLED'];
}
else {
	$uploaddLabel = $mod_strings['LBL_UPLOAD_UPGRADE'];
	$descItemsQueued = $mod_strings['DESC_FILES_QUEUED'];
	$descItemsInstalled = $mod_strings['DESC_FILES_INSTALLED'];
}

//
// check that the upload limit is set to 6M or greater
//

define('SUGARCRM_MIN_UPLOAD_MAX_FILESIZE_BYTES', 6 * 1024 * 1024);  // 6 Megabytes

$upload_max_filesize = ini_get('upload_max_filesize');
$upload_max_filesize_bytes = return_bytes($upload_max_filesize);
if($upload_max_filesize_bytes < constant('SUGARCRM_MIN_UPLOAD_MAX_FILESIZE_BYTES'))
{
	$GLOBALS['log']->debug("detected upload_max_filesize: $upload_max_filesize");
	print('<p class="error">' . $mod_strings['MSG_INCREASE_UPLOAD_MAX_FILESIZE'] . ' '
		. get_cfg_var('cfg_file_path') . "</p>\n");
}

//
// process "run" commands
//

if( isset( $_REQUEST['run'] ) && ($_REQUEST['run'] != "") ){
    $run = $_REQUEST['run'];

    if( $run == "upload" ){
        if( empty( $_FILES['upgrade_zip']['tmp_name'] ) ){
            echo "Please specify a file and try again!<br>\n";
        }
        else{
            $manifest_file = extractManifest( $_FILES['upgrade_zip']['tmp_name'] );
            require_once( $manifest_file );
            validate_manifest( $manifest );

            $upgrade_zip_type = $manifest['type'];

            // exclude the bad permutations
            if( $view == "module" && $upgrade_zip_type != "module" ){
                die( "You can only upload module packs on this page." );
            }
            else if( $view == "default" && $upgrade_zip_type == "module" ){
                die( "You cannot upload module packs on this page." );
            }

            $base_filename = urldecode( $_REQUEST['upgrade_zip_escaped'] );
            $base_filename = preg_replace( "#\\\\#", "/", $base_filename );
            $base_filename = basename( $base_filename );

            mkdir_recursive( "$base_upgrade_dir/$upgrade_zip_type" );
            $target_path = "$base_upgrade_dir/$upgrade_zip_type/$base_filename";
            $target_manifest = remove_file_extension( $target_path ) . "-manifest.php";

            if( isset($manifest['icon']) && $manifest['icon'] != "" ){
                $icon_location = extractFile( $_FILES['upgrade_zip']['tmp_name'], $manifest['icon'] );
                $path_parts = pathinfo( $icon_location );
                copy( $icon_location, remove_file_extension( $target_path ) . "-icon." . $path_parts['extension'] );
            }

            if( move_uploaded_file( $_FILES['upgrade_zip']['tmp_name'], $target_path ) ){
                copy( $manifest_file, $target_manifest );
                echo "The file $base_filename has been uploaded.<br>\n";
            }
            else{
                echo "There was an error uploading the file, please try again!<br>\n";
            }
        }
    }
    else if( $run == "Delete Package" ){
        if( !isset($_REQUEST['install_file']) || ($_REQUEST['install_file'] == "") ){
            die( "File to install not specified." );
        }
        $delete_me = urldecode( $_REQUEST['install_file'] );
        if( unlink( $delete_me ) ){
            print( "Package $delete_me has been removed.<br>" );
        }
        else{
            die( "Problem removing package $delete_me." );
        }
    }
}

print( "<p>\n" );
if( $view == "module") {
	print( get_module_title($mod_strings['LBL_MODULE_NAME'], $mod_strings['LBL_MODULE_NAME'].": ".$mod_strings['LBL_MODULE_LOADER_TITLE'], true) );
}
else {
	print( get_module_title($mod_strings['LBL_MODULE_NAME'], $mod_strings['LBL_MODULE_NAME'].": ".$mod_strings['LBL_UPGRADE_WIZARD_TITLE'], true) );
}
print( "</p>\n" );

// upload link
?>

<form name="the_form" enctype="multipart/form-data" action="<?php print( $form_action ); ?>" method="post"  >
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="tabForm">
<tr><td>
<table width="450" border="0" cellspacing="0" cellpadding="0">
<tr><td>
<?php print( $uploaddLabel ); ?><input type="file" name="upgrade_zip" size="40" />
</td>
<td>
<input type=button value="Upload" onClick="document.the_form.upgrade_zip_escaped.value = escape( document.the_form.upgrade_zip.value );document.the_form.submit();" />
<input type=hidden name="run" value="upload" />
<input type=hidden name="upgrade_zip_escaped" value="" />
</td>
</tr>
</table></td></tr></table>
</form>


<table width="100%" border="0" cellspacing="0" cellpadding="0" class="tabForm">
<tr><td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td>
<?php
// scan for new files (that are not installed)
print( "$descItemsQueued<br>\n"); 
print( "<ul>\n" );
$upgrade_contents = findAllFiles( "$base_upgrade_dir", array() );
$upgrades_available = 0;

print( "<table>\n" );
print( "<tr><th></th><th align=left>Name</th><th>Type</th><th>Version</th><th>Date Published</th><th>Uninstallable</th><th>Description</th></tr>\n" );
foreach($upgrade_contents as $upgrade_content)
{
	if(!preg_match("#.*\.zip\$#", $upgrade_content))
	{
		continue;
	}
	
	$upgrade_content = clean_path($upgrade_content);
	$the_base = basename($upgrade_content);
	$the_md5 = md5_file($upgrade_content);
	$md5_matches = $uh->findByMd5($the_md5);
	
	if(0 == sizeof($md5_matches))
	{
		$target_manifest = remove_file_extension( $upgrade_content ) . '-manifest.php';
		require_once($target_manifest);

		$name = empty($manifest['name']) ? $upgrade_content : $manifest['name'];
		$version = empty($manifest['version']) ? '' : $manifest['version'];
		$published_date = empty($manifest['published_date']) ? '' : $manifest['published_date'];
		$icon = '';
		$description = empty($manifest['description']) ? 'None' : $manifest['description'];
		$uninstallable = empty($manifest['is_uninstallable']) ? 'No' : 'Yes';
		$type = getUITextForType( $manifest['type'] );

		if(($view == 'module' && $manifest['type'] != 'module') ||
			($view == 'default' && $manifest['type'] == 'module'))
		{
			continue;
		}

		if(empty($manifest['icon']))
		{
			$icon = getImageForType( $manifest['type'] );
		}
		else
		{
			$path_parts = pathinfo( $manifest['icon'] );
			$icon = "<img src=\"" . remove_file_extension( $upgrade_content ) . "-icon." . $path_parts['extension'] . "\">";
		}

		$upgrades_available++;
		print( "<tr><td>$icon</td><td>$name</td><td>$type</td><td>$version</td><td>$published_date</td><td>$uninstallable</td><td>$description</td>\n" );
?>
            <form action="<?php print( $form_action . "_prepare" ); ?>" method="post">
            <td><input type=submit name="mode" value="Install" /></td>
            <input type=hidden name="install_file" value="<?php print( urlencode( "$upgrade_content" ) ); ?>" />
            </form>

            <form action="<?php print( $form_action ); ?>" method="post">
            <td><input type=submit name="run" value="Delete Package" /></td>
            <input type=hidden name="install_file" value="<?php print( urlencode( "$upgrade_content" ) ); ?>" />
            </form>
            </tr>
<?php
    }
}
print( "</table>\n" );

if( $upgrades_available == 0 ){
    print( "<i>None</i><br>\n" );
}
print( "</ul>\n" );

?>
</td>
</tr>
</table></td></tr></table>

<table width="100%" border="0" cellspacing="0" cellpadding="0" class="tabForm">
<tr><td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr><td>
<?php

// TODO: contact sugar server to look for available upgrades
// TODO: heartbeat config (need sugar server to post data to)

// display installed pieces and versions
print("$descItemsInstalled<br>\n"); 
$installeds = $uh->getAll();
$upgrades_installed = 0;

print( "<ul>\n" );
print( "<table>\n" );
print( "<tr><th></th><th align=left>Name</th><th align=left>Type</th><th align=left>Version</th><th align=left>Date Installed</th><th>Description</th><th>Action</th></tr>\n" );

foreach($installeds as $installed)
{
	$filename = from_html($installed->filename);
	$date_entered = $installed->date_entered;
	$type = $installed->type;
	$version = $installed->version;
	$upgrades_installed++;
	$link = "";

	switch($type)
	{
		case "theme":
		case "langpack":
		case "module":
		case "patch":
			$manifest_file = extractManifest($filename);
			require_once($manifest_file);
			
			$name = empty($manifest['name']) ? $filename : $manifest['name'];
			$description = empty($manifest['description']) ? 'None' : $manifest['description'];
			if(($upgrades_installed==0 || $uh->UninstallAvailable($installeds, $installed))
				&& is_file($filename) && !empty($manifest['is_uninstallable']))
			{
				$link .= "<input type=submit name=\"mode\" value=\"Uninstall\" />";
				$link .= "<input type=hidden name=\"install_file\" value=\"" . urlencode( $filename ) . "\" />";
			}
			else
			{
				$link = "Not Available";
			}
			
			break;
		default:
			break;
	}

	if(($view == "module" && $type != "module") || ($view == "default" && $type == "module"))
	{
		continue;
	}
	
	$target_manifest = remove_file_extension( $filename ) . "-manifest.php";
	require_once( "$target_manifest" );

	if(isset($manifest['icon']) && $manifest['icon'] != "")
	{
		$path_parts = pathinfo($manifest['icon']);
		$icon = "<img src=\"" . remove_file_extension( $upgrade_content ) . "-icon." . $path_parts['extension'] . "\">";
	}
	else
	{
		$icon = getImageForType( $manifest['type'] );
	}
	print( "<form action=\"" . $form_action . "_prepare\" method=\"post\">\n" );
	print( "<tr><td>$icon</td><td>$name</td><td>$type</td><td>$version</td><td>$date_entered</td><td>$description</td><td>$link</td></tr>\n" );
	print( "</form>\n" );
}

print( "</table>\n" );

if( $upgrades_installed == 0 )
{
	print( "<i>No recorded upgrades.</i><br>\n" );
}

print( "</ul>\n" );

$GLOBALS['log']->info( "Upgrade Wizard view");

?>
</td>
</tr>
</table></td></tr></table>
