<?php

error_reporting (E_ALL & ~E_NOTICE);

header( 'Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($filename) ) . ' GMT');


/* get afian's root folder */
$sys['root'] =  str_replace("\\","/",getcwd());

require_once($sys['root']."/system/class/lib.strings.php");
$str = new strings;
require_once($sys['root']."/system/functions/misc.inc");
require_once($sys['root']."/system/class/lib.csv.php");
require_once($sys['root']."/system/class/lib.settings.php");
$settings = new settings();


define('ADODB_DIR',gluePath($sys['root'],"/system/class/adodb"));
require_once($sys['root']."/system/class/adodb/adodb.inc.php");
require_once($sys['root']."/system/class/adodb/adodb-errorhandler.inc.php");
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$ADODB_CACHE_DIR = $sys['root']."/system/data/temp/adodbcache";
$db = NewADOConnection($settings->config['dbtype']);
if (!@$db->Connect($settings->config['server'], $settings->config['dbuser'], $settings->config['dbpass'], $settings->config['dbname'])) {
	exit("Database connection failed!");
}

require_once($sys['root']."/system/class/lib.config.php");
$config = new config();
/* checking GPCS data */
require_once($sys['root']."/system/includes/inputchk.inc");
require_once($sys['root']."/system/class/lib.fileman.php");
require_once($sys['root']."/system/class/lib.quota.php");
require_once($sys['root']."/system/class/lib.sharing.php");
require_once($sys['root']."/system/class/lib.log.php");
require_once($sys['root']."/system/class/email/htmlmimemail.inc");
require_once($sys['root']."/system/class/auth/lib.auth.sql.php");



/* utils */
$fm = new fileman;

/* aici ia informatiile userului dupa uid */
$uid = $str->fromHTML($_GET['uid']);

ob_start();

header("Content-type: text/plain");

if(!$uid) {
	echo "CANCEL|Invalid parameters.";
} else {
	
	$config->settings['adminemail'] = $db->GetOne("SELECT email FROM ".$settings->config['optinfo_tablename']." WHERE uid='1'");
	
	$completeUserInfo = $db->GetRow("
	SELECT 
	
	* 
	
	FROM 
	
	
	
	".$settings->config['users_tablename']." AS users , 
	".$settings->config['auth_tablename']." AS auth, 
	".$settings->config['interauth_tablename']." AS interauth, 
	".$settings->config['optinfo_tablename']." AS optional_info
	
	WHERE 
	
	auth.username=interauth.username 
	AND 
	interauth.id=users.id 
	AND 
	users.id='".$uid."' 
	AND 
	optional_info.uid=users.id 
	
	");
	
	
	
	$groupInfo = auth::getGroupInfo($completeUserInfo['gid']);
	
	
	function choosePerm($userPerm, $groupPerm) {
		if ($userPerm != "") {
			return $userPerm;
		} else {
			if ($groupPerm == "") {
				return 0;
			} else {
				return $groupPerm;
			}
		}
	}
	
	
	$permissions['suspended'] = choosePerm($completeUserInfo['suspended'], $groupInfo['suspended']);
	$permissions['path'] = choosePerm($completeUserInfo['path'], $groupInfo['path']);
	$permissions['upload'] = choosePerm($completeUserInfo['upload'], $groupInfo['upload']);
	$permissions['readonly'] = choosePerm($completeUserInfo['readonly'], $groupInfo['readonly']);
	$permissions['byemail'] = choosePerm($completeUserInfo['sendbyemail'], $groupInfo['sendbyemail']);
	$permissions['sharing'] = choosePerm($completeUserInfo['sharing'], $groupInfo['sharing']);
	$permissions['shareAccess'] = choosePerm($completeUserInfo['shareaccess'], $groupInfo['shareaccess']);
	$options['uploadNotice'] = choosePerm($completeUserInfo['uploadnotice'], $groupInfo['uploadnotice']);
	$options['downloadNotice'] = choosePerm($completeUserInfo['downloadnotice'], $groupInfo['downloadnotice']);
	
	
	/* quotas */
	if ($completeUserInfo['spacequota'] == "-") {
		$permissions['unlimitedSpace'] = true;
	} elseif($completeUserInfo['spacequota'] == "") {
		if ($groupInfo['spacequota'] == "") {
			$permissions['unlimitedSpace'] = true;
		} else {
			$permissions['spaceQuota'] = $groupInfo['spacequota'];
		}
	} else {
		$permissions['spaceQuota'] = $completeUserInfo['spacequota'];
	}
	
	
	
	if ($completeUserInfo['trafficquota'] == "-") {
		$permissions['unlimitedTraffic'] = true;
	} elseif($completeUserInfo['trafficquota'] == "") {
		if ($groupInfo['trafficquota'] == "") {
			$permissions['unlimitedTraffic'] = true;
		} else {
			$permissions['trafficQuota'] = $groupInfo['trafficquota'];
		}
	} else {
		$permissions['trafficQuota'] = $completeUserInfo['trafficquota'];
	}
	
	
	if ($completeUserInfo['path'] == "") {
		$userpath = $groupInfo['path'];
	} else {
		$userpath = $completeUserInfo['path'];
	}
	
	
	$topath = $str->fromHTML($_GET['path']);
	
	$sys['fullPath'] = gluePath($userpath,$flagInfo['path'], $topath);
	
	
	function recalcUsedSpace() {
		global $sys,$fm,$permissions,$completeUserInfo, $settings;
		$trash = gluePath((($settings->config['trashpath'])?$settings->config['trashpath']:gluePath($sys['root'], "/system/data/trash/")), $completeUserInfo['username']);
		$currentUsedSpace = $fm->getDirSize($userpath) + $fm->getDirSize($trash);
		$userHaveFreeSpace = ($currentUsedSpace <= $permissions['spaceQuota'])?1:0;
		return $userHaveFreeSpace;
	}
	
	$userHaveFreeSpace = recalcUsedSpace();
	
	
	
	echo "---REPLY START---";
	
	
	if (!$permissions['upload']) {
		echo "CANCEL|You are not allowed to upload files";
		echo "\n</html>";
		$output = ob_get_clean();
		header("Connection: close;");
		echo $output;
		exit();
	}
	
	
	if (!isCleanPath($topath)) {
		echo "CANCEL|Ilegal path: ".$topath;
		echo "\n</html>";
		$output = ob_get_clean();
		header("Connection: close;");
		echo $output;
		exit();
	}
	
	/*//problema cu quota
	if ($permissions['unlimitedTraffic'] == false && $quota->canAddTraffic() == false) {
		echo "CANCEL|Traffic quota excedeed";
		echo "\n</html>";
		$output = ob_get_clean();
		header("Connection: close;");
		echo $output;
		exit();
	}
	*/
	
	if (!is_dir($sys['fullPath'])) {
		echo "CANCEL|The folder where you want to upload files does not exist any more.";
		echo "\n</html>";
		$output = ob_get_clean();
		header("Connection: close;");
		echo $output;
		exit();
	}
	
	
	
		$uploadFile = $_FILES['userfile'];
		$uploadFilename = $uploadFile['tmp_name'];
		$niceFilename = $uploadFile['name'];
		$niceFilename = $str->fromHTML($niceFilename);
		$relativePath = $fm->dirname($_GET['relative_path']);
		$absoluteFolder = gluePath($sys['fullPath'], $relativePath);
		$toFile = gluePath($absoluteFolder, $niceFilename);
		$filesize = $uploadFile['size'];
	
	
	
	if ($uploadFile && !$uploadFile['error']) {
		//$folder = $fm->dirname($_GET['relative_path']);
		
		
		if ($_GET['jupart'] >= 0) {
			if (file_exists($toFile) && $_GET['jupart'] < 1) {
				echo "CANCEL|Upload failed: '".gluePath($relativePath, $niceFilename)."' already exists.";
			} else {
				//chunk
				$chunk = file_get_contents($uploadFilename);
				if (!is_file($toFile)) {
					if (!is_dir($absoluteFolder)) {
						$fm->createPath($absoluteFolder);
					}
					
					$rs = $fm->newFile($toFile, "");
					if (!$rs) {
						echo $fm->errorMsg;
					}
				}
				if ($permissions['unlimitedSpace'] || $userHaveFreeSpace) {
					$rs = $fm->appendData($toFile, $chunk, "bottom");
					unlink($uploadFilename);
					
					
					
					if ($_GET['jufinal'] == "1") {
						$fileSize = filesize($toFile);
						
						$auth = (object) 'auth';
						$auth->currentUserInfo = $completeUserInfo;
						$log = new logging($auth->currentUserInfo['username']);
						
						$actionInfo = "";
						$actionInfo .= "\r\n\tFile name: " . $niceFilename ."\n";
						$actionInfo .= "\tFile size: " . $fm->formatFileSize($fileSize) ."\n";
						$logInfo = $actionInfo;
						$logInfo .= "\tUploaded to folder: " . $absoluteFolder ."\n";
						$log->act("0", "upload", $logInfo);
						
						$log->lastUpload($toFile);
						
						
						/* send email notice to admin */
						if ($options['uploadNotice'] && $config->settings['adminemail']) {
							$mail = new htmlMimeMail();
							$message = "\n";
							$message .= "User \"".$auth->currentUserInfo['username']."\" uploaded:\n";
							$message .= "Date: " . date("n/d/Y H:i") ."\n";
							$message .= $actionInfo;
							$message .= "\tUploaded to folder: " . $topath ."\n";
							$mail->setText($message);
							$customFrom = "";
							if ($customFrom) {
								$mail->setFrom($customFrom);
							} else {
								$mail->setFrom(($sys['license']['unbranded']?$sys['license']['unbranded']:"Afian"));
							}
							$mail->setSubject("Upload from ".$auth->currentUserInfo['username']);
							$result = $mail->send(array($config->settings['adminemail']));
							if (!$result) {
								print_r($mail->errors);
							}
						}
					}
					
				} else {
					echo "CANCEL|Not enough space available to upload '".$niceFilename."'";
				}
			}
		} else {
			//entire file
		}
	} else {
		echo "CANCEL|Please specify a file for upload.";
	}
	echo "\n</html>";
}
$output = ob_get_clean();
header("Connection: close;");
echo $output;
/*
ob_start();
echo $output;
print_r($_FILES);
print_r($_GET);
$output .= ob_get_clean();
error_log($output, 3, "log.txt");
*/
exit();
?>