<?php
////////////////////////////////////////////////////////////////////////
// Breeze Website Builder
// Copyright Silver Dolphin Solutions, LLC, Edward Lemmers, P.E.
// For licensing, see license.txt.
// Created: 4/9/2013
// Revised: 12/13/2013	ELL
// Added refresh of main menu to update buttons and set to last selections.
// Revised: 9/28/2016	ELL
// Modified file copying to accomodate possibility that zip archive extracts to non-Breeze staging folder.
// Revised: 6/20/2017	ELL
// Added ability to deploy 'Console Only' plugins upon install.
//
	
	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);
	//////////////////////////////////////////
?>
<!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><?php echo INSTALL_PLUGIN_INSTALLING_PLUGIN; ?></h2>
<?php
	
	if (is_uploaded_file($_FILES['plugin_file']['tmp_name']))
	{	
		$source = $_FILES['plugin_file']['tmp_name'];
		$file_name = $_FILES['plugin_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_PLUGIN_WRONG_FILE_TYPE_MSG . " <a href='upload_plugin.php'>" . HERE_WORD . "</a> " . AND_TRY_AGAIN;
			exit;
		}
		$document_root = getenv('DOCUMENT_ROOT');
		$destination = $document_root . "/" . $file_name;
		move_uploaded_file( $source, $destination );
		$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";
		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";
		// 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";
		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");
		
		// Check for "Console Only" plugin and deploy now if so.
		$id = $bwb_dbh->lastInsertId();
		$query = "SELECT name, category, plugin_sql FROM " . BWB_TABLE_PREFIX . "plugins WHERE id = " . $id;
		$result = $bwb_dbh->query($query);
		$row = $result->fetch(PDO::FETCH_ASSOC);
		if ($row['category'] == "Console Only")	{
			$plugin_sql = $row['plugin_sql'];
			if (isset($plugin_sql) && ($plugin_sql != ""))
				$result = RunSQL($plugin_sql, $bwb_dbh, BWB_TABLE_PREFIX, false, UPLOAD_TEMPLATE_ROWS_AFFECTED_MSG);
		
			$query = "REPLACE INTO " . BWB_TABLE_PREFIX . "plugins_deployed SET `plugin_id`=$id, `deployed`=1";
			$cnt = $bwb_dbh->exec($query);
		}
		
		$_SESSION['button_group'] = "other_functions";
		$_SESSION['button'] = "btn_users_site_options";
		$_SESSION['sub_button'] = "btn_upload_plugin";
		$_SESSION['install_plugin_mode'] = time() + 600;
?>
		<h2><?php echo INSTALL_PLUGIN_PLUGIN_INSTALLATION_COMPLETE; ?></h2>
        <p><?php echo CLICK_WORD; ?> <a href="main.php" target="_top"><?php echo HERE_WORD; ?></a> <?php echo INSTALL_PLUGIN_ADD_NEW_BUTTON_TO_MENU_MSG; ?></p>
<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>
<?php
	}
	else
		echo INSTALL_PLUGIN_ERROR_UPLOADING_FILE_ERR . " " . CLICK_WORD . " <a href='upload_plugin.php'>" . HERE_WORD . "</a> ". TO_TRY_AGAIN;
?>