<?php require($_SERVER['DOCUMENT_ROOT'] . '/admin/inc/sessionStart.php'); ?>

<?php
include("config.inc.php");
// upload
$startingFolder = _folder . "img/";
$canChange = false;
$errorClass = "alert-success";

function checkFolder($userFolder){
	if(strpos($userFolder, "Kickstrap/img/") !== false){
		return true;
	}
	
	return false;
}

function checkFileType($theFile){
	$allowed_extensions = array('jpg','jpeg','png','gif','bmp', 'pdf');
	$ext = strtolower(substr(strrchr($theFile['name'], '.'), 1));
	if(in_array($ext, $allowed_extensions)){
		
		if($theFile['type'] == "text/php"){
			return false;
		}
		return true;
	}
	return false;
}

function modifyName($string){
	
	$string = preg_replace('/\s+/', '-', trim(preg_replace('!\s+!', ' ',$string)));
	$string = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $string);
	// Remove any runs of periods (thanks falstro!)
	$string = mb_ereg_replace("([\.]{2,})", '.', mb_ereg_replace("([\.]{2,})", '.', mb_ereg_replace("([\.]{2,})", '.',$string)));
	
	return $string;
}

if(isset($_GET['action'])){
	if ($_GET['action']=="upload") {
		$file_name=modifyName($_FILES["ffoto"]["name"]);
		$file_size=$_FILES["ffoto"]["size"];
		$file_type=$_FILES["ffoto"]["type"];
		$path=$_SERVER['DOCUMENT_ROOT'] . "/" . $_POST['folder'];
		$canChange = checkFolder($path);
		$rightType = checkFileType($_FILES['ffoto']);
		
		if($canChange && $rightType){
			move_uploaded_file($_FILES['ffoto']['tmp_name'], $path.$file_name);
			putenv("PATH=" .$_ENV["PATH"]. ':/Users/adam/bin:/usr/bin/curl:/Applications/MAMP/bin/php/php5.6.10/bin:/Users/adam/.composer/vendor/bin:/Users/adam/local/node/bin:/usr/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin');
			$shellPath = shell_exec('echo $PATH 2>&1');
			$username = isset($_SESSION['Username']) ? $_SESSION['Username'] : "No User";
			$addEXIF = shell_exec('exiftool -keywords+="retailer - ' . $username . '" ' . $path.$file_name . ' -overwrite_original_in_place 2>&1');
			
			$message='<p class="centerText"><b>Your file has been uploaded successfully</b></p>';
			$startingFolder = $_POST['folder'];
			$errorClass = "alert-success";
		}else{
			$message='<p class="centerText"><b>Your file path is not in a writeable location or is not a supported file type.</b></p>';
			$startingFolder = _folder . "img/";
			$errorClass = "alert-error";
		}
	} else if ($_GET['action']=="delete") {
		$path=$_SERVER['DOCUMENT_ROOT'] . "/" . $_GET['file'];
		$canChange = checkFolder($path);
		if($canChange){
			unlink($path);
			$message='<p class="centerText"><b>The file was deleted successfully</b></p>';
			
			$deletedFile = $_GET['file'];
			$lastChar = substr($deletedFile, -1);
			if($lastChar == "/"){
				$deletedFile = substr($deletedFile, 0 , -1);
			}
			$lastSlash = substr(strrchr($deletedFile, '/'), 1);
			$startingFolder = substr($deletedFile, 0, - strlen($lastSlash));
			$errorClass = "alert-success";
		}else{
			$message='<p class="centerText"><b>Your file path is not in a writeable location and cannot be deleted.</b></p>';
			$startingFolder = _folder . "img/";
			$errorClass = "alert-error";
		}
		
	} else if ($_GET['action']=="create_folder") {
		$path=$_SERVER['DOCUMENT_ROOT'] . "/" . $_POST['folder'];
		$canChange = checkFolder($path);
		$_POST['fname'] = modifyName($_POST['fname']);
		if($canChange){
			mkdir($path.$_POST['fname'], 0777);
			$message='<p class="centerText"><b>The folder was created successfully</b></p>';
			$startingFolder = $_POST['folder'] . $_POST['fname'] . "/";
			$errorClass = "alert-success";
		}else{
			$message='<p class="centerText"><b>Your file path is not in a writeable location and the folder cannot be created.</b></p>';
			$startingFolder = _folder . "img/";
			$errorClass = "alert-error";
		}
	}else if($_GET['action']=="delete_folder") {
		//echo 'folder deleted:'.$_GET['id'];
		$path = $_SERVER['DOCUMENT_ROOT'] . "/" . $_GET['id'];
		$canChange = checkFolder($path);
		if($canChange){
			rmdir($path);
			$message='<p class="centerText"><b>The folder was deleted successfully</b></p>';
			
			$deletedFolder = $_GET['id'];
			$lastChar = substr($deletedFolder, -1);
			if($lastChar == "/"){
				$deletedFolder = substr($deletedFolder, 0 , -1);
			}
			$lastSlash = substr(strrchr($deletedFolder, '/'), 1);
			$startingFolder = substr($deletedFolder, 0, - strlen($lastSlash));
			$errorClass = "alert-success";
		}else{
			$message='<p class="centerText"><b>Your file path is not in a writeable location and the folder cannot be deleted.</b></p>';
			$startingFolder = _folder . "img/";
			$errorClass = "alert-error";
		}
	}
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>File Manager</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script language="javascript" src="js/jqueryFileTree.js"></script>
<script language="javascript" src="js/jquery.form.js"></script>
<link href="css/jqueryFileTree.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/file_manager.css" rel="stylesheet" type="text/css" />
<link href="/Kickstrap/themes/addonLess/fileManager.css" rel="stylesheet" type="text/css" />
<style>
	body #fileWrapper #fileDetails #theMessage.alert-error{
		background-color:red;
	}

	.alert-danger, .alert-error {
	    background-color: #F2BDB1;
	    border-color: #f0a5a4;
	    color: #bd4247;
	}
	.alert, .alert h4 {
	    color: #DD5600;
	}
	.alert {
	    padding: 8px 35px 8px 14px;
	    margin-bottom: 19px;
	    margin-top:10px;
	    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
	    background-color: #F1CEAB;
	    border: 1px solid #efb99e;
	    -webkit-border-radius: 4px;
	    -moz-border-radius: 4px;
	    border-radius: 4px;
	    font-size:16px;
	    line-height: 1.3em;
	}
</style>

<?php
	if(isset($_GET['target'])){
		$target = $_GET['target'];
	}else{
		$target = "";
	}
?>
<script language="javascript">
	$(document).ready(function(){
		var target = '<?php echo $target; ?>';
		$('#navBar').fileTree({ 
			root: '<?php echo _folder; ?>',
			startingFolder: '<?php echo $startingFolder; ?>',
			script: 'fileTreeDirs.php',
			target: target,
			exts: 'jpeg,jpg,png,gif,tiff,pdf'
		});
		
		$("#navBar").prepend("<h3 class='sectionHeader'>Folders</h3>");
		
		$("#fileDetails").on("click", ".aFile", function(){
			var file = $("a", this).attr("rel");
			$.get('file_details.php?file=' + file + '&target=' + target, '#fileDetails', function(data){
				$("#fileFunctions").html(data).css("display", "block");
				$("#fileDetails").animate({scrollTop: 0},500);
			});
		});
	});
</script>
</head>
<body>
<div id="fileWrapper" src="#">		
	<!-- <div class="alert alert-danger">
		By uploading files to your website, you agree to accept responsibility that you have permission to use the photo from the copyright holder.
	</div> -->

	<h2>File Manager</h2>
    <div id="navBar" class="demo" src="#">
	</div>
    <div id="fileDetails">
    	<div id="fileFunctions"></div>
		<?php
			if(isset($message)){
		?>
			<div id="theMessage" class="<?php echo $errorClass; ?>">
				<?php echo $message; ?>
			</div>
			<script>
				setTimeout(function(){
					$("#theMessage").remove();
				}, 3500);
			</script>
		<?php
			}
		?>
		<div id="fileContainer"></div>
    </div>
</div>	
</body>
</html>
