<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 14/14/2013
// Modified: 4/24/2015	ELL
// Added automatic 1-click update.
// Modified: 10/29/2018	ELL
// Added hook to run post-update operations if needed.
//
	
	include ("check_session.php");
	
	$enable_file_manager = $_SESSION['enable_file_manager'];
	if ($enable_file_manager != "100")
		header("Location: /index.php");
		
	include ("lib/copy_dir.php");
	
	//////////////////////////////////////
	ini_set('max_execution_time', 10000);
	set_time_limit(10000);
	//////////////////////////////////////////
	$document_root = getenv('DOCUMENT_ROOT');
?>
<!DOCTYPE html>
<html>
<head>
<title>Installing Update | Breeze Website Builder</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="theme/<?php echo $theme; ?>/manager.css" type="text/css">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
</head>
<body>
<h2><?php echo INSTALL_UPDATE_INSTALLING_UPDATE; ?></h2>
<?php
	$mode = $_GET['mode'];
	if (is_uploaded_file($_FILES['update_file']['tmp_name']) || ($mode == "automatic"))
	{
		if ($mode == "manual")
		{
			$source = $_FILES['update_file']['tmp_name'];
			$file_name = $_FILES['update_file']['name'];
			$file_parts = explode(".", $file_name);
			$file_ext = $file_parts[count($file_parts) - 1];
			
			if (!( (strcasecmp($file_ext, "tgz") == 0) || (strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "zip") == 0) || (strcasecmp($file_ext, "tar") == 0) ))
			{
				echo INSTALL_UPDATE_WRONG_FILE_TYPE_MSG . " <a href='upload_update.php'>" . HERE_WORD . "</a> " . AND_TRY_AGAIN;
				exit;
			}
			
			$destination = $document_root . "/" . $file_name;
			move_uploaded_file( $source, $destination );
			$source = $destination;
		}
		elseif ($mode == "automatic")
		{
			$url = "http://breezewebsitebuilder.com/download_page.php";
			$html = file_get_contents($url);
			$doc = new DOMDocument(); // create DOMDocument
			libxml_use_internal_errors(true);
			$doc->loadHTML($html); // load HTML you can add $html
			$update_file = $doc->getElementById('latest_update')->nodeValue;
			$previous_update_file = $doc->getElementById('previous_update')->nodeValue;
			$previous_ver = str_replace("breeze_update_", "", $previous_update_file);
			$search = array(".tar.gz", ".zip", ".tgz");
			$previous_ver = str_replace($search, "", $previous_ver);
			$version_file = $_GET['version_file'];
			
			$file_parts = explode(".", $update_file);
			$file_ext = $file_parts[count($file_parts) - 1];
			
			$query = "SELECT * FROM `" . BWB_TABLE_PREFIX . "version`";
			$result = $bwb_dbh->query($query);
			$row = $result->fetch(PDO::FETCH_ASSOC);
			$version = $row["version"];
			
			// Compare presious version with version in version file and version of database.  If they don't match, do not do automatic update.
			if (($version == $previous_ver) && ($version_file == $version))
			{
				$url = "http://breezewebsitebuilder.com/breeze_download";
				$source = $url . "/" . $update_file;
				$destination = $document_root . "/" . $update_file;
				copy($source, $destination);
				$source = $destination;
			}
			else
			{
				echo INSTALL_UPDATE_VERSION_ERROR_ERR;
				exit;
			}
		}
		else
			exit;	// Don't know how this module was accessed, so just fail.
		
		if ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0) || (strcasecmp($file_ext, "tar") == 0))
		// Note: phar->decompress removes the all of the file name after the FIRST dot "." then appends the ".tar"
			$tar_source =  $document_root . "/" . $file_parts[0] . ".tar";
		
		$destination = $document_root . "/tmp";
		if (!file_exists($destination))
			mkdir($destination, 0755);
		else
		{
			$bkup = $destination . date('YmdHis', time());
			rename($destination, $bkup);
			mkdir($destination, 0755);
		}
		
		echo INSTALL_PLUGIN_EXTRACTING_FILES . "<br><br>\n";
		// Extract contents of archive to disk
		if (strcasecmp($file_ext, "zip") == 0)
		{
			$zip = new ZipArchive;
			$res = $zip->open($source);
			if ($res === TRUE) {
			  $zip->extractTo($destination);
			  $zip->close();
			} else {
			  echo INSTALL_PLUGIN_ERROR_EXTRACTING_FILES_1_ERR . " " . CLICK_WORD . " <a href='upload_update.php'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN;
			  exit;
			}
		}
		elseif ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0))
		{
			// decompress from gz
			try {
				$p = new PharData($source);
				$p->decompress(".tar"); // creates /path/to/my.tar
			} catch (Exception $e) {
				echo INSTALL_PLUGIN_ERROR_EXTRACTING_FILES_1A_ERR . " " . CLICK_WORD . " <a href='upload_update.php'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN . "<br/>$e";
				exit;
			}
		}
		
		// unarchive from the tar
		if ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0) || (strcasecmp($file_ext, "tar") == 0))
		{
			try {
				$phar = new PharData($tar_source);
				$phar->extractTo($destination, null, true);
			} catch (Exception $e) {
				echo INSTALL_PLUGIN_ERROR_EXTRACTING_FILES_1B_ERR . " " . CLICK_WORD . " <a href='upload_update.php'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN . "<br/>$e";
				exit;
			}
		}

		// Copy files to correct folders.
		echo INSTALL_PLUGIN_COPYING_FILES . "<br><br>\n";
		$extracted_source = $document_root . "/tmp";
		$destination = $document_root;
		copydir($extracted_source, $destination, 0755, true);
		$scripts_source = $extracted_source . "/scripts";
		$lib_source = $extracted_source . "/php";
		if (BWB_BASE_DIR == '')
		{
			if (BWB_LIB_DIR != "php")	{
				$lib_dir = $document_root . "/" . BWB_LIB_DIR;
				copydir($lib_source, $lib_dir, 0755, true);
			}
			if (BWB_SCRIPTS_DIR != "scripts")	{
				$scripts_dir = $document_root . "/" . BWB_SCRIPTS_DIR;
				copydir($scripts_source, $scripts_dir, 0755, true);
			}
		}
		else
		{
			$lib_dir = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_LIB_DIR;
			$scripts_dir = $document_root . "/" . BWB_BASE_DIR . "/" . BWB_SCRIPTS_DIR;
			copydir($lib_source, $lib_dir, 0755, true);
			copydir($scripts_source, $scripts_dir, 0755, true);
		}
		unlink($source);
		unlink($tar_source);
		
		// Run template SQL
		$sql_file = "SQL/upgrade.sql";
		include ("run_sql_file.php");
		
		unlink($document_root . "/SQL/upgrade.sql");
		if (file_exists($document_root . "/SQL/_notes"))
			unlink($document_root . "/SQL/_notes");
		rmdir($document_root . "/SQL");
		
		$_SESSION['button_group'] = "other_functions";
		$_SESSION['button'] = "btn_users_site_options";
		$_SESSION['sub_button'] = "btn_upload_update";
		$_SESSION['update_breeze_mode'] = time() + 600;
		
		// If any exists, run post-update operations.
		if (file_exists($document_root . "/manage/update_post_operations.php"))
			include("update_post_operations.php");
?>
		<h2><?php echo INSTALL_UPDATE_UPDATE_INSTALLATION_COMPLETE; ?></h2>
        <p>Click <a href="main.php" target="_top"><?php echo HERE_WORD; ?></a> <?php echo INSTALL_UPDATE_REFRESH_MAIN_MENU; ?></p>

<?php
	}
	else
		echo INSTALL_PLUGIN_ERROR_UPLOADING_FILE_ERR . " " . CLICK_WORD . " <a href='upload_update.php'>" . HERE_WORD . "</a> ". TO_TRY_AGAIN;
?>