<?php
/////////////////////////////////////////////
// Upload Template /////
////////////////////////////////////////////////////////////////////////
//	Breeze Website Builder
//	Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
//	For licensing, see license.txt.
//	Created: 10/2/2011	ELL
//	Revised: 2/10/2012	ELL
//  Added table prefix handling.  Added references to images folder configuration.
// 	Revised: 4/9/2013	ELL
//  Added call out of SQL file name and changed reference to sql file run module.
//  Revised: 7/13/2016	ELL
//  Replaced archive class and archive.php include with PharData class.
//	Revised: 1/13/2017	ELL
//	Added installation of plugin zip files that may be bundled with template tgz file.
//	Revised: 2/6/2018	ELL
//	Added deployment of custom fonts.
//
// 
//
	include ("check_session.php");
	include ("lib/copy_dir.php");
	include("lib/build_css_string.php");
	
	//////////////////////////////////////
	ini_set('max_execution_time', 10000);
	set_time_limit(10000);
	//////////////////////////////////////////
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Template | 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 UPLOAD_TEMPLATE_BUILDING_SITE_MSG; ?><br />
&nbsp;&nbsp;<?php echo UPLOAD_TEMPLATE_WHEN_COMPLETE_SCROLL_TO_BOTTOM_MSG; ?></h2>
<?php	
	$source = $_FILES['template_file']['tmp_name'];
	$file_name = $_FILES['template_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, "tar") == 0) ))
	{
		echo UPLOAD_TEMPLATE_ALLOWED_FILE_TYPE_MSG . " <a href='browse_template.php'>" . HERE_WORD . "</a> " . AND_TRY_AGAIN;
		exit;
	}
	$document_root = getenv('DOCUMENT_ROOT');
	$destination = $document_root . "/" . $file_name;
	$move_rslt = move_uploaded_file( $source, $destination );
	if ($move_rslt !== true)	{
		echo UPLOAD_TEMPLATE_ERROR_UPLOADING_FILE_ERR . " " . CLICK_WORD . " <a href='browse_template.php'>" . HERE_WORD . "</a> " . TO_TRY_AGAIN;
		
		switch($_FILES['template_file']['error']){
		case 0: //no error; possible file attack!
		  echo "There was a problem with your upload. It is giving the appearance of being a posible file attack.";
		  break;
		case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini
		  echo "The file you are trying to upload is too big. Exceeds upload_max_filesize in php.ini. ";
		  break;
		case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form
		  echo "The file you are trying to upload is too big. Exceeds MAX_FILE_SIZE directive.";
		  break;
		case 3: //uploaded file was only partially uploaded
		  echo "The file you are trying upload was only partially uploaded.";
		  break;
		case 4: //no file was uploaded
		  echo "You must select an image for upload. (That's funny, we don't want to upload an image here.)";
		  break;
		default: //a default error, just in case!  :)
		  echo "There was a problem with your upload.";
		}
		exit;
	}
	
	if (strtolower($file_ext) == "gz")
		$tar_file_name = $file_parts[count($file_parts) - 3] . ".tar";
	else
		$tar_file_name = $file_parts[count($file_parts) - 2] . ".tar";
	
	$delete_all_pages = $_POST['delete_all_pages'];
	
	if ($delete_all_pages == 1)
	{
		if ((BWB_BASE_DIR == '') && (BWB_WEBPAGE_DIR == ''))
			$webpage_dir = "/";
		elseif ((BWB_BASE_DIR == '') || (BWB_WEBPAGE_DIR == ''))
			if (BWB_BASE_DIR == '')
				$webpage_dir = "/" . BWB_WEBPAGE_DIR . "/";
			elseif (BWB_WEBPAGE_DIR == '')
				$webpage_dir = "/" . BWB_BASE_DIR . "/";
		else
			$webpage_dir = "/" . BWB_BASE_DIR . "/" . BWB_WEBPAGE_DIR . "/";
				
		$query = "SELECT page_name FROM " . BWB_TABLE_PREFIX . "page_data";
		$result = $bwb_dbh->query($query);
		while ($row = $result->fetch(PDO::FETCH_ASSOC))
		{
			$page_name = $row['page_name'];
			$page_path = $document_root . $webpage_dir . $page_name . ".php";
			try	{
				unlink($page_path);
			}	catch (Exception $e) {
				$e = 0;
			}
		}
		
		$query = "TRUNCATE TABLE " . BWB_TABLE_PREFIX . "page_data";
		$cnt = $bwb_dbh->exec($query);
		
		$template_mode = 1;
		include("delete_custom_classes.php");
	}

	if ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0))
	{
		if (file_exists($document_root . "/" . $tar_file_name))
			unlink($document_root . "/" . $tar_file_name);
	}
		
	if (file_exists($document_root . "/tmp"))	// If tmp folder already exists, back it up.
	{
		$bkup = $document_root . "/tmp" . date('YmdHis', time());
		rename($document_root . "/tmp", $bkup);
	}
	
	if ((strcasecmp($file_ext, "gz") == 0) || (strcasecmp($file_ext, "tgz") == 0))
	{
		try {
			$p = new PharData($destination);
			$p->decompress(".tar"); // creates /path/to/my.tar
		} catch (Exception $e) {
			echo $e;
			exit;
		}
	}
	
	try {
		$phar = new PharData($document_root . "/" . $tar_file_name);
		$phar->extractTo($document_root . "/tmp", null, true);
	} catch (Exception $e) {
		echo $e;
		exit;
	}
	
	if (BWB_BASE_DIR == '')
		$userfiles = '';
	else
		$userfiles = "/" . BWB_BASE_DIR;
		
	if (BWB_WEBPAGE_DIR == '')
		$website_dir = '';
	else
		$website_dir = "/" . BWB_WEBPAGE_DIR;
	
	// Copy files to correct folders.
	echo UPLOAD_TEMPLATE_COPYING_USER_FILES_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_PAGES_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/file/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . $website_dir ."/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_IMAGES_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/image/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_IMAGE_DIR . "/";
		copydir($source, $destination, 0755, true);
	}
	echo UPLOAD_TEMPLATE_COPYING_CSS_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/css/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_MEDIA_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/media/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_MEDIA_DIR . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_FLASH_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/flash/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_FLASH_DIR . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_SCRIPTS_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/scripts/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_SCRIPTS_DIR . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_FONTS_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/userfiles/fonts/";
	if (file_exists($source))	{
		$destination = $document_root . $userfiles . "/" . BWB_FONTS_DIR . "/";
		copydir($source, $destination);
	}
	echo UPLOAD_TEMPLATE_COPYING_XML_MSG . "<br><br>\n";
	$source = $document_root . "/tmp/ckeditor/";
	if (file_exists($source))	{
		$destination = $document_root . "/ckeditor/";
		copydir($source, $destination);
	}
	
	// Look for any plugin zip files and install them.
	$plugin_files = glob($document_root . '/tmp/*.{zip,tgz,gz,tar}', GLOB_BRACE);
	foreach ($plugin_files as $plugin_file_path)
	{
		$plugin_file = basename($plugin_file_path);
		$destination = $document_root . "/" . $plugin_file;
		copy($plugin_file_path, $destination);
		/********************** Install Plugin **************************************/
		echo "<h2>" . INSTALL_PLUGIN_INSTALLING_PLUGIN . "</h2>";
		
		$file_parts = explode(".", $plugin_file);
		$file_ext = $file_parts[count($file_parts) - 1];
		$source = $destination;
		
		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_plugin";
		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_plugin.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_plugin.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_plugin.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_plugin";
		// Examine to see if files zipped to archive including some staging directory.  If so, then need to include that folder in the source path to get correct paths.
		$breeze_dirs = array("manage", "ckeditor", "kfm", "connect", "scripts", "php");
		$dir_arr = array();
		$got_breeze_dir = 0;
		if ($handle = opendir($extracted_source)) 
		{
			while (false !== ($file = readdir($handle)))
			{
				if (is_dir($extracted_source . "/" . $file) && ($file != ".") && ($file != ".."))
				{
					if (in_array($file, $breeze_dirs))
						$got_breeze_dir++;
					$dir_arr[] = $file;
				}
			}
			closedir($handle);
		}
		if (($got_breeze_dir < 1) && (count($dir_arr) == 1))	// Zip file must be extracting to some containing folder that has nothing to do with Breeze file tree.  Include in path.
			$extracted_source .= "/" . $dir_arr[0];
		
		$destination = $document_root;
		copydir($extracted_source, $destination, 0755, true);
		unlink($document_root . "/plugin.sql");
		unlink($source);
		if (file_exists($tar_source))
			unlink($tar_source);
		
		// Run template SQL
		$sql_file = "plugin.sql";
		$tmp_folder = "tmp_plugin";
		if (($got_breeze_dir < 1) && (count($dir_arr) == 1))	// If extracted to additional containing folder, include that foler in path to SQL file.
			$sql_file = $dir_arr[0] . "/" . $sql_file;
		include ("run_sql_file.php");
		
		echo "<h2>" . INSTALL_PLUGIN_PLUGIN_INSTALLATION_COMPLETE . "</h2>";
	/********************** Install Plugin **************************************/
	}
	
	// Run template SQL
	$sql_file = "template.sql";
	$tmp_folder = "tmp";
	include ("run_sql_file.php");
	
	/////////////////////////////////////////////////////////////////////////////////////
	// Build new style-sheet files in case user selected custom background colors or images,
	// or if style and image folders differ from template download site.
	$query = "SELECT * FROM " . BWB_TABLE_PREFIX . "style_sheets";
	$result = $bwb_dbh->query($query);
	while ($row = $result->fetch(PDO::FETCH_ASSOC))
	{
		$style_sheet = $row['name'];
		echo BUILDING_WORD . " " . $style_sheet . " " . STYLE_SHEET_WORD . " ...<br />\n";
		$css_file = $style_sheet . ".css";
		
		$css_string = BuildCSSString($style_sheet, $bwb_dbh, BWB_BASE_DIR, BWB_IMAGE_DIR, BWB_TABLE_PREFIX);
		$file_name = $document_root . $userfiles . "/" . BWB_CSS_DIR . "/" . $css_file;
		
		if (file_exists($file_name))
		{
			$bkup_file_name = $file_name . time();
			if (!rename($file_name, $bkup_file_name))
				echo UPLOAD_TEMPLATE_COULD_NOT_RENAME_ERR . " " . $file_name . " " . TO_WORD . " " . $bkup_file_name . ".<br>";
			@chmod($bkup_file_name, 0644);
		}
		
		// Create file.
		$fh = fopen($file_name, 'x') or die(UPLOAD_TEMPLATE_CANT_CREATE_ERR . " $file_name: $php_errormsg");
		$put_result = (fputs($fh, $css_string));
		fclose($fh) or die($php_errormsg);
		@chmod($file_name, 0644);
	}
	
	// Create cust font CSS file.
	include("write_custom_font_css.php");
?>
		<h2><?php echo UPLOAD_TEMPLATE_UPLOAD_TEMPLATE_COMPLETE; ?></h2>
        <h2><?php echo CLICK_WORD; ?> <a href="/manage/main.php?mode=wizard" target="_parent"><?php echo HERE_WORD; ?></a> <?php echo UPLOAD_TEMPLATE_TO_CONTINUE_MSG; ?></h2>
<script>
	var bottom = document.body.scrollHeight;
	var from_height = 0;
	var step = parseInt(bottom/100);
	var to_height = 0;
	var code = "AnimateScroll();";
	
	function AnimateScroll()
	{
		if (to_height < bottom)
		{
			to_height = to_height + step;
			window.scrollTo(from_height, to_height);
			setTimeout(code, 10);
			from_height = to_height;
		}
	}
	AnimateScroll();
</script>
</body>
</html>