<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 2/11/2016	ELL
// Revised: 7/11/2016	ELL
// Revised destination to deconmpress files to to accomodate changes in backup file tree.
// Revised: 7/27/2016	ELL
// Added switch to empty all image and media folders.
//
	
	include ("check_session.php");
	
	$enable_file_manager = $_SESSION['enable_file_manager'];
	if ($enable_file_manager != "100")
		header("Location: /index.php");
		
	$password = $_REQUEST['password'];
		
	include ("lib/copy_dir.php");
	
	//////////////////////////////////////////
	ini_set('max_execution_time', 43200);
	set_time_limit(43200);
	ini_set('post_max_size', '640M');
	ini_set('upload_max_filesize', '512M');
	ini_set('memory_limit','2048M');
	$document_root = $_SERVER['DOCUMENT_ROOT'];
	//////////////////////////////////////////
	
	function empty_folder($folder)
	{
		$bad_folders = array("/root", "/etc", "/usr", "/var", "/boot", "/opt", "/mnt", "/dev", "/bin", "/proc", "/run", "/sys", "/backup", "/lib", "/lib64", "/media", "/sbin", "/srv", "/root/", "/etc/", "/usr/", "/var/", "/boot/", "/opt/", "/mnt/", "/dev/", "/bin/", "/proc/", "/run/", "/sys/", "/backup/", "/lib/", "/lib64/", "/media/", "/sbin/", "/srv/");
		
		$bad_files = array("prepare_4_wizard.php", "index.html", "construction.html", "breeze_copywrite.html");
		
		if (($folder != "") && ($folder != "/") && ($folder != "/home") && ($folder != "/home/") && !in_array($folder, $bad_folders) && file_exists($folder) && is_dir($folder))
		{
			if (substr($folder, strlen($folder) - 1, 1) != "/")
				$folder .= "/";
			$files = glob($folder . '{,.}*', GLOB_BRACE);
			foreach ($files as $file){ // iterate files
			  if (is_file($file) && (basename($file) != ".htaccess") && !in_array(basename($file), $bad_files) && (strpos($file, ".tgz", strlen($file) - 4) === false) && (strpos($file, ".tar", strlen($file) - 4) === false) && (strpos($file, ".zip", strlen($file) - 4) === false) && (strpos($file, ".tar.gz", strlen($file) - 7) === false))
				unlink($file); // delete file
			}
		}
	}
?>
<!DOCTYPE html>
<html>
<head>
<title>Installing Plugin | 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 id="restoring_site_heading"><?php echo BACKUP_RESTORE_RESTORING_WEBSITE; ?></h2>
<img src="theme/<?php echo $theme; ?>/images/uploading.gif" alt="<?php echo BACKUP_RESTORE_RESTORING_WEBSITE; ?>" id="uploading_gif" style="margin-top:50px; margin-bottom:50px; margin-left:100px;" />
<br />
<?php
	if (isset($_GET['backup_file']) && ($_GET['backup_file'] != ""))
	{
		$file_name = $_GET['backup_file'];
		$file_parts = explode(".", $file_name);
		$file_ext = $file_parts[count($file_parts) - 1];
		$file_pre = $file_parts[count($file_parts) - 2];
		$file_pre = str_replace("backup_", "tmp", $file_pre);
		$source = $document_root . "/backup/" . $file_name;
		$destination = $document_root . "/" . $file_name;
		copy ($source, $destination);
	}
	elseif (is_uploaded_file($_FILES['backup_file']['tmp_name']))
	{	
		$source = $_FILES['backup_file']['tmp_name'];
		$file_name = $_FILES['backup_file']['name'];
		$file_parts = explode(".", $file_name);
		$file_ext = $file_parts[count($file_parts) - 1];
		$file_pre = $file_parts[count($file_parts) - 2];
		$file_pre = str_replace("backup_", "tmp", $file_pre);
		if (!((strcasecmp($file_ext, "tgz") == 0) || (strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "zip") == 0) || (strcasecmp($file_ext, "tar") == 0)))
		{
			echo BACKUP_RESTORE_WRONG_FILE_TYPE_1_MSG . " <a href='backup_restore.php?password=$password'>" . HERE_WORD . "</a> " . AND_TRY_AGAIN;
			echo "<script>\n	document.getElementById('uploading_gif').style.display = 'none';\n	document.getElementById('restoring_site_heading').style.display = 'none';\n</script>\n";
			exit;
		}
		$destination = $document_root . "/" . $file_name;
		move_uploaded_file( $source, $destination );
	}
	else
	{
		echo INSTALL_PLUGIN_ERROR_UPLOADING_FILE_ERR . " " . CLICK_WORD . " <a href='backup_restore.php?password=$password'>" . HERE_WORD . "</a> ". TO_TRY_AGAIN;
		echo "<script>\n	document.getElementById('uploading_gif').style.display = 'none';\n	document.getElementById('restoring_site_heading').style.display = 'none';\n</script>\n";
		exit;
	}
	
	$source = $destination;
	if ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0) || (strcasecmp($file_ext, "tar") == 0))
	// Note: phar->decompress removes all of the file name after the FIRST dot "." then appends the ".tar"
		$tar_source =  $document_root . "/" . $file_parts[0] . ".tar";
	
	$destination = $document_root . "/" . $file_pre;

	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='backup_restore.php?password=$password'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN;
		  echo "<script>\n	document.getElementById('uploading_gif').style.display = 'none';\n	document.getElementById('restoring_site_heading').style.display = 'none';\n</script>\n";
		  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='backup_restore.php?password=$password'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN . "<br/>$e";
			echo "<script>\n	document.getElementById('uploading_gif').style.display = 'none';\n	document.getElementById('restoring_site_heading').style.display = 'none';\n</script>\n";
			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='backup_restore.php?password=$password'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN . "<br/>$e";
			echo "<script>\n	document.getElementById('uploading_gif').style.display = 'none';\n	document.getElementById('restoring_site_heading').style.display = 'none';\n</script>\n";
			exit;
		}
	}
		
	// Copy files to correct folders.
	echo INSTALL_PLUGIN_COPYING_FILES . "<br><br>\n";
	$extracted_source = $document_root . "/" . $file_pre;
	$files_source = $extracted_source . "/files";
	$images_source = $extracted_source . "/images";
	$css_source = $extracted_source . "/css";
	$media_source = $extracted_source . "/media";
	$flash_source = $extracted_source . "/flash";
	$scripts_source = $extracted_source . "/scripts";
	$lib_source = $extracted_source . "/php";
	$fonts_source = $extracted_source . "/fonts";
	
	if (BWB_BASE_DIR == "")	{
		if (BWB_WEBPAGE_DIR == "")
			$files_destination = $document_root;
		else
			$files_destination = $document_root . "/" . BWB_WEBPAGE_DIR;

		$images_destination = $document_root . "/" . BWB_IMAGE_DIR;
		$css_destination = $document_root . "/" . BWB_CSS_DIR;
		$media_destination = $document_root . "/" . BWB_MEDIA_DIR;
		$flash_destination = $document_root . "/" . BWB_FLASH_DIR;
		$scripts_destination = $document_root . "/" . BWB_SCRIPTS_DIR;
		$lib_destination = $document_root . "/" . BWB_LIB_DIR;
		$fonts_destination = $document_root . "/" . BWB_FONTS_DIR;
	}
	else	{
		if (BWB_WEBPAGE_DIR == "")
			$files_destination = $document_root . "/" . BWB_BASE_DIR;
		else
			$files_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_WEBPAGE_DIR;

		$images_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_IMAGE_DIR;
		$css_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_CSS_DIR;
		$media_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_MEDIA_DIR;
		$flash_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_FLASH_DIR;
		$scripts_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_SCRIPTS_DIR;
		$lib_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_LIB_DIR;
		$fonts_destination = $document_root . "/" . BWB_BASE_DIR  . "/" . BWB_FONTS_DIR;
	}
	
	if ($_REQUEST['retain_media'] != 1)
	{
		empty_folder($files_destination);
		empty_folder($images_destination);
		empty_folder($images_destination . "/orig");
		empty_folder($images_destination . "/gallery/orig");
		empty_folder($images_destination . "/gallery/fs");
		empty_folder($images_destination . "/gallery/tn");
		empty_folder($images_destination . "/icons");
		empty_folder($css_destination);
		empty_folder($media_destination);
		empty_folder($flash_destination);
	}
	
	copydir($files_source, $files_destination, 0755, true);
	copydir($images_source, $images_destination, 0755, true);
	copydir($css_source, $css_destination, 0755, true);
	copydir($media_source, $media_destination, 0755, true);
	copydir($flash_source, $flash_destination, 0755, true);
	copydir($scripts_source, $scripts_destination, 0755, true);
	copydir($lib_source, $lib_destination, 0755, true);
	if (file_exists($fonts_destination))	{
		if (!file_exists($fonts_source))
			mkdir($fonts_source);
		copydir($fonts_source, $fonts_destination, 0755, true);
	}

	try	{
		unlink($source);
	} catch (Exception $e) {
		echo $e;
	}
	try	{
		unlink($tar_source);
	} catch (Exception $e) {
		echo $e;
	}
	
	// Clear out any editing cache.
	$query = "TRUNCATE " . BWB_TABLE_PREFIX . "blogs_draft";
	$cnt = $bwb_dbh->exec($query);
	
	$query = "TRUNCATE " . BWB_TABLE_PREFIX . "page_data_draft";
	$cnt = $bwb_dbh->exec($query);
	
	$query = "TRUNCATE " . BWB_TABLE_PREFIX . "page_cache";
	$cnt = $bwb_dbh->exec($query);
	
	if (BWB_BASE_DIR == '')
		$userfiles_path = '';
	else
		$userfiles_path = "/" . BWB_BASE_DIR;
		
	if (BWB_WEBPAGE_DIR == '')
		$website_path = $userfiles_path;
	else
		$website_path = $userfiles_path . "/" . BWB_WEBPAGE_DIR;

	$path = ".." . $website_path . "/";
	if ($handle = opendir($path))
	{
		while (false !== ($file = readdir($handle)))
		{
			if ((!(strpos($file, "sitemap.xml") === false) && (strlen($file) > 20)) || ((substr($file, strlen($file) - 5, 5) == "_save") && (substr($file, 0, 1) == ".")) || (substr($file, 0, 7) == "pREVIEW"))
			{
				$file_path = $path . $file;
				unlink($file_path);
			}
		}
		closedir($handle);
	}
	
	$path = ".." . $userfiles_path . "/" . BWB_CSS_DIR . "/";
	if ($handle = opendir($path)) 
	{
		while (false !== ($file = readdir($handle)))
		{
			if ((strpos($file, ".css") !== false) && (strpos($file, ".css") < (strlen($file) - 5)))
			{
				$file_path = $path . $file;
				unlink($file_path);
			}
		}
		closedir($handle);
	}
	
	$path = ".." . $userfiles_path . "/" . BWB_SCRIPTS_DIR . "/";
	if ($handle = opendir($path)) 
	{
		while (false !== ($file = readdir($handle)))
		{
			if ((!(strpos($file, "menu_items.js") === false) || !(strpos($file, "menu_tpl.js") === false)) && (strlen($file) > 20))
			{
				$file_path = $path . $file;
				unlink($file_path);
			}
		}
		closedir($handle);
	}
	
	// Run template SQL
	if (!file_exists($document_root . "/tmp"))
		mkdir($document_root . "/tmp");
	copy($extracted_source . "/backup.sql", $document_root . "/tmp/backup.sql");
	$sql_file = "backup.sql";
	include ("run_sql_file.php");
	
	$command = "rm -r -f " . $extracted_source;
	exec($command);
	$command = "rm -r -f " . $document_root . "/tmp";
	exec($command);
	
	$_SESSION['button_group'] = "other_functions";
	$_SESSION['button'] = "btn_users_site_options";
	$_SESSION['sub_button'] = "btn_backup_restore";
?>
	<h2><?php echo BACKUP_RESTORE_RESTORE_COMPLETE; ?></h2>
	
    <div class="button_console" style="width:360px; margin-bottom:30px;" onClick="window.location='backup_restore.php?password=<?php echo $password; ?>';"><span class='button_console_text'><?php echo CLICK_WORD . " " . HERE_WORD . " " . BACKUP_RESTORE_RETURN_TO_MSG ; ?></span></div>
    
<script>
	document.getElementById("uploading_gif").style.display = "none";
</script>
</body>
</html>