<?php

require 'FileOperations.php';
$con = mysql_connect($website,$userid,$pw);
if (!$con) {
	die('Could not connect: ' . mysql_error());
}
mysql_query("SET foreign_key_checks = 0",$con);

$curDB = "../CurrentlyOpenedDBName.tmp";
if(file_exists ($curDB)){
	$f = fopen($curDB, "r");
	$db   = trim(fgets($f)); // linked database name
	fclose($f);
	mysql_select_db($db, $con);
}

// Importing from sql dump part 1 of 3
if(isset($_POST[import])){
	echo ("Browse for EnTrak project file on your computer and load<br/>
	<form action='ImportExport.php?import=yes' method='post' enctype='multipart/form-data'>
		<input type='file' name='fileToUpload' accept='.sql' style='font-family:ariel; font-size:100%;'/>
		<input type='submit' name='Upload' value='Load' />
	</form>
	");
	// Execution of import continues in the $_GET[import] == "yes" block (immediately below)

// Importing from sql dump part 2 of 3
}elseif($_GET[import] == "yes"){
	// If post tries to post file size bigger than post_max_size then catch the exception
	if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
        $postMax = ini_get('post_max_size'); //grab the size limits...
        echo "<p style=\"color: #F00;\">\n File could not be loaded <br> Please note files larger than {$postMax} will result in this error!<br>Please be advised this is not a limitation in the CMS, This is a limitation of the hosting server.<br>For various reasons they limit the max size of uploaded files, if you have access to the php ini file you can fix this by changing the post_max_size setting.<br> If you can't then please ask your host to increase the size limits.</p>"; // echo out error and solutions...
		$uploadOk = false;
	}

	$dumpFileName = str_replace(" ","_",basename($_FILES["fileToUpload"]["name"]));
	$dumpFileName = rtrim($dumpFileName,".sql");

	$target_dir = "../Uploads/";
	$target_file = $target_dir . $dumpFileName;
	$uploadOk = true;

	// Check if file already exists
	if(file_exists($target_file) && !is_dir($target_file)) {
	echo "Database by name >>>{$target_file}<<< exists change the name of your file and upload again <br/>";
		$uploadOk = false;
	}


	// Check if $uploadOk is set to false by an error
	if ($uploadOk == false) {
		echo "Sorry, your file was not uploaded <br/>";

	// if everything is ok, try to upload file
	} else {
		if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
			echo ("Importing file called ". basename($_FILES["fileToUpload"]["name"]));
			//echo (" creating database called {$dumpFileName} <br/>"); // User does not need to know db name

			// remove spaces from dumpFileName
			$dumpFileName = str_replace("-", " ", $dumpFileName);

			// Create new database by that name
			mysql_query("CREATE DATABASE {$dumpFileName}",$con);

            if($oper_sys == "windows"){
                $shell = new COM("WScript.Shell");
                $shell->Run("C:\Windows\System32\cmd.exe /A /Q /K import.bat {$dumpFileName}");
                $shell = null;
			}elseif($oper_sys == "linux"){
                shell_exec("bash importexport.bash -i {$dumpFileName}");
            }
			$placeholder = "Give database name (blank name not supported)";
			echo ("<form action='ImportExport.php?importDone=yes&dumpFileName={$dumpFileName}' method='post'>");
			echo ("<input type='text'  autocomplete='off' name='DBDesc' placeholder='{$placeholder}' maxlength = '60' size = '60'>");
			echo ("<br/>Wait for command window to close and press ");
			echo ("<button type='submit'>OK</button>");
			echo ("</form>");
		} else {
			echo "Sorry, there was an error uploading your file. Refresh the page to continue working";
		}
	}

// Importing from sql dump part 3 of 3
}elseif($_GET[importDone] == "yes"){
	$name = $_GET[dumpFileName];
	$desc = $_POST[DBDesc];
	echo "db name = {$name} and desc = {$desc}";
	// Add the database name to ProjectsList.csv and load it into EnTrak
	WriteProjectsListFile($name,$desc); // write DB name to ProjectsList.csv
	SelectDB($name);					// write DB name to CurrentlyOpenedDBName.tmp

	// Do full page reload
	header("Location: ImportExport.php?reload=yes");

// Exporting database
}elseif(isset($_POST[export])){

	// Make checks to see if export is possible
	if(CurrentlyFetchingData($con) == true){
		echo "Cannot export while data fetch is running, stop data fetch before exporting
		<a href='RightTop.php' > <button  type='button'>OK</button>  	</a>";
		exit;
	}
	if(CurrentlyRunningES($con) == true){
		echo "Cannot export while one or more services are running, stop service before exporting
		<a href='RightTop.php' > <button  type='button'>OK</button>  	</a>";
		exit;
	}

	if(file_exists($curDB)){
		//echo ("Exporting data base called {$db}");
		if($oper_sys == "windows"){
            $shell = new COM("WScript.Shell");
            $shell->Run("C:\Windows\System32\cmd.exe /A /Q /K export.bat {$db}");
            $shell = null;
            $usr_msg = "Wait for command window to close and then press the save button";
        }elseif($oper_sys == "linux"){
            $output = shell_exec("bash importexport.bash -e {$db}");
            $usr_msg = "Project has been exported";
        }

		// Now a file called {$db}.sql should be present in the IO folder
		// sleep for so many milliseconds
		usleep(5000000);
		echo "{$usr_msg}<a href='SaveNRedirect.html'><button type='button'>Save</button></a>";
	}else{
		WarnUser("Select database name first","RightTop.php");
	}
// Deleting database
}elseif(isset($_POST[delete])){
	if(file_exists($curDB)){
		$res = mysql_query("DROP DATABASE {$db}",$con);
		DeleteCurrentlyOpenedDBName();
		DelFromList($db);
		// delete this line from ProjectsList.csv
		if($res){
			echo "Database deleted successfully	<a href='ImportExport.php?reload=yes' > <button  type='button'>OK</button>  	</a>";
		}else{
			echo "There was a problem in database deletion	<a href='RightTop.php' > <button  type='button'>OK</button>  	</a>";
		}
	}else{
		WarnUser("Select database name first","RightTop.php");
	}

}elseif(isset($_GET[reload]) == "yes"){
	echo ("<script>parent.window.location.reload('../Projects.html')</script>");

}else{
	echo "ImportExport.php called improperly";
}


?>
