<commit_before><?php

/*
 *  FileTrader - Web based file sharing platform
 *  Copyright (C) 2011 <NAME> <<EMAIL>>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class Files {
	private $config;
	private $dbh;
	private $fsd; /* points to file storage directory from configuration */

	function __construct($config) {
		$this->config = $config;
		$this->fsd = getConfig($config, 'file_storage_dir', TRUE);

		try {
			$this->dbh = new PDO(
					"sqlite:" . getConfig($this->config, 'token_file', TRUE),
					NULL, NULL, array(PDO::ATTR_PERSISTENT => TRUE));

			/* FIXME: maybe this should be placed somewhere else, inefficient?!... */
			$this->dbh
					->query(
							'CREATE TABLE IF NOT EXISTS downloadTokens (token TINYTEXT, filePath TEXT, PRIMARY KEY (token), UNIQUE(token))');
			$this->dbh
					->query(
							'CREATE TABLE IF NOT EXISTS   uploadTokens (token TINYTEXT, filePath TEXT, fileSize INT, PRIMARY KEY (token), UNIQUE(token))');
		} catch (Exception $e) {
			throw new Exception("database connection failed");
		}
	}

	function __destruct() {
		$this->dbh = NULL;
	}

	function getDownloadToken() {
		/* FIXME: token should expire, based on server request? */

		if ($_SERVER['REQUEST_METHOD'] != 'POST') {
			throw new Exception("invalid request method, should be POST");
		}

		$absPath = $this
				->validatePath(getRequest('relativePath', TRUE), FTS_FILE);
		if ($absPath === FALSE) {
			throw new Exception("invalid path");
		}

		$token = generateToken();

		try {
			$stmt = $this->dbh
					->prepare(
							"INSERT INTO downloadTokens (token, filePath) VALUES (:token, :filePath)");
			$stmt->bindParam(':token', $token);
			$stmt->bindParam(':filePath', $absPath);
			$stmt->execute();

			$downloadLocation = getProtocol() . $_SERVER['SERVER_NAME']
					. $_SERVER['PHP_SELF']
					. "?action=downloadFile&token=$token";

			return array("downloadLocation" => $downloadLocation,
					"absPath" => $absPath);
		} catch (Exception $e) {
			throw new Exception("database query failed");
		}
	}

	function getUploadToken() {
		/* FIXME: token should expire, based on server request? */
		/* FIXME: what if upload size is not known in time? transcode web service for example... */
		/* FIXME: maybe transparently fix the file name on duplicate upload */

		if ($_SERVER['REQUEST_METHOD'] != 'POST') {
			throw new Exception("invalid request method, should be POST");
		}

		$absPath = $this
				->validatePath(getRequest('relativePath', TRUE), FTS_PARENT);
		if ($absPath === FALSE) {
			throw new Exception("invalid path");
		}
		/* in case of upload the file should *not* exist */
		if (file_exists($absPath)) {
			throw new Exception("file already exists");
		}

		/* verify fileSize
		 * 
		 * NOTE: fileSize *is* required, but 0 is a valid file size, but also 
		 * seen as "empty" by PHP, so we work around it like this...
		 */
		$fileSize = (int) getRequest('fileSize', FALSE, 0);
		if ($fileSize < 0) {
			throw new Exception("invalid filesize");
		}

		$token = generateToken();

		try {
			$stmt = $this->dbh
					->prepare(
							"INSERT INTO uploadTokens (token, filePath, fileSize) VALUES (:token, :filePath, :fileSize)");
			$stmt->bindParam(':token', $token);
			$stmt->bindParam(':filePath', $absPath);
			$stmt->bindParam(':fileSize', $fileSize);
			$stmt->execute();

			$uploadLocation = getProtocol() . $_SERVER['SERVER_NAME']
					. $_SERVER['PHP_SELF'] . "?action=uploadFile&token=$token";
			return array("uploadLocation" => $uploadLocation,
					"absPath" => $absPath);
		} catch (Exception $e) {
			throw new Exception("database query failed");
		}
	}

	function downloadFile() {
		/* FIXME: delete token after download, but still support range requests, pickle?! */
		/* FIXME: delete token immediately on first request? */

		if ($_SERVER['REQUEST_METHOD'] != 'GET') {
			throw new Exception("invalid request method, should be GET", 405);
		}

		if (!isset($_GET['token']) || empty($_GET['token'])
				|| !ctype_xdigit($_GET['token']))
			throw new Exception("invalid token", 400);
		$token = $_GET['token'];

		$stmt = $this->dbh
				->prepare(
						"SELECT token, filePath FROM downloadTokens WHERE token=:token");
		$stmt->bindParam(':token', $token);
		$stmt->execute();
		$row = $stmt->fetch();
		if (empty($row)) {
			throw new Exception("token not found", 404);
		}

		$absPath = $row['filePath'];

		$finfo = new finfo(FILEINFO_MIME_TYPE);
		header("X-Sendfile: " . $absPath);
		header("Content-Type: " . $finfo->file($absPath));
		header(
				'Content-Disposition: attachment; filename="'
						. basename($absPath) . '"');
		exit(0);
	}

	function uploadFile() {
		/* FIXME: limit content-length to something reasonable, max file upload size from PHP? */

		if ($_SERVER['REQUEST_METHOD'] != 'PUT'
				&& $_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
			throw new Exception("invalid request method, should be PUT", 405);
		}

		/* This is to allow "preflight" XMLHttpRequests, 
		 * see https://developer.mozilla.org/En/HTTP_access_control */
		/* FIXME: maybe move this to after the token verification? */
		/* FIXME: maybe be more restrictive in where to allow requests from? */
		if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {<commit_msg>dont offer download box when content is text/plain but show in browser<commit_after><?php

/*
 *  FileTrader - Web based file sharing platform
 *  Copyright (C) 2011 <NAME> <<EMAIL>>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

class Files {
	private $config;
	private $dbh;
	private $fsd; /* points to file storage directory from configuration */

	function __construct($config) {
		$this->config = $config;
		$this->fsd = getConfig($config, 'file_storage_dir', TRUE);

		try {
			$this->dbh = new PDO(
					"sqlite:" . getConfig($this->config, 'token_file', TRUE),
					NULL, NULL, array(PDO::ATTR_PERSISTENT => TRUE));

			/* FIXME: maybe this should be placed somewhere else, inefficient?!... */
			$this->dbh
					->query(
							'CREATE TABLE IF NOT EXISTS downloadTokens (token TINYTEXT, filePath TEXT, PRIMARY KEY (token), UNIQUE(token))');
			$this->dbh
					->query(
							'CREATE TABLE IF NOT EXISTS   uploadTokens (token TINYTEXT, filePath TEXT, fileSize INT, PRIMARY KEY (token), UNIQUE(token))');
		} catch (Exception $e) {
			throw new Exception("database connection failed");
		}
	}

	function __destruct() {
		$this->dbh = NULL;
	}

	function getDownloadToken() {
		/* FIXME: token should expire, based on server request? */

		if ($_SERVER['REQUEST_METHOD'] != 'POST') {
			throw new Exception("invalid request method, should be POST");
		}

		$absPath = $this
				->validatePath(getRequest('relativePath', TRUE), FTS_FILE);
		if ($absPath === FALSE) {
			throw new Exception("invalid path");
		}

		$token = generateToken();

		try {
			$stmt = $this->dbh
					->prepare(
							"INSERT INTO downloadTokens (token, filePath) VALUES (:token, :filePath)");
			$stmt->bindParam(':token', $token);
			$stmt->bindParam(':filePath', $absPath);
			$stmt->execute();

			$downloadLocation = getProtocol() . $_SERVER['SERVER_NAME']
					. $_SERVER['PHP_SELF']
					. "?action=downloadFile&token=$token";

			return array("downloadLocation" => $downloadLocation,
					"absPath" => $absPath);
		} catch (Exception $e) {
			throw new Exception("database query failed");
		}
	}

	function getUploadToken() {
		/* FIXME: token should expire, based on server request? */
		/* FIXME: what if upload size is not known in time? transcode web service for example... */
		/* FIXME: maybe transparently fix the file name on duplicate upload */

		if ($_SERVER['REQUEST_METHOD'] != 'POST') {
			throw new Exception("invalid request method, should be POST");
		}

		$absPath = $this
				->validatePath(getRequest('relativePath', TRUE), FTS_PARENT);
		if ($absPath === FALSE) {
			throw new Exception("invalid path");
		}
		/* in case of upload the file should *not* exist */
		if (file_exists($absPath)) {
			throw new Exception("file already exists");
		}

		/* verify fileSize
		 * 
		 * NOTE: fileSize *is* required, but 0 is a valid file size, but also 
		 * seen as "empty" by PHP, so we work around it like this...
		 */
		$fileSize = (int) getRequest('fileSize', FALSE, 0);
		if ($fileSize < 0) {
			throw new Exception("invalid filesize");
		}

		$token = generateToken();

		try {
			$stmt = $this->dbh
					->prepare(
							"INSERT INTO uploadTokens (token, filePath, fileSize) VALUES (:token, :filePath, :fileSize)");
			$stmt->bindParam(':token', $token);
			$stmt->bindParam(':filePath', $absPath);
			$stmt->bindParam(':fileSize', $fileSize);
			$stmt->execute();

			$uploadLocation = getProtocol() . $_SERVER['SERVER_NAME']
					. $_SERVER['PHP_SELF'] . "?action=uploadFile&token=$token";
			return array("uploadLocation" => $uploadLocation,
					"absPath" => $absPath);
		} catch (Exception $e) {
			throw new Exception("database query failed");
		}
	}

	function downloadFile() {
		/* FIXME: delete token after download, but still support range requests, pickle?! */
		/* FIXME: delete token immediately on first request? */

		if ($_SERVER['REQUEST_METHOD'] != 'GET') {
			throw new Exception("invalid request method, should be GET", 405);
		}

		if (!isset($_GET['token']) || empty($_GET['token'])
				|| !ctype_xdigit($_GET['token']))
			throw new Exception("invalid token", 400);
		$token = $_GET['token'];

		$stmt = $this->dbh
				->prepare(
						"SELECT token, filePath FROM downloadTokens WHERE token=:token");
		$stmt->bindParam(':token', $token);
		$stmt->execute();
		$row = $stmt->fetch();
		if (empty($row)) {
			throw new Exception("token not found", 404);
		}

		$absPath = $row['filePath'];

		$finfo = new finfo(FILEINFO_MIME_TYPE);
                header("Content-Type: " . $finfo->file($absPath));
		header("X-Sendfile: " . $absPath);
		if($finfo->file($absPath) != "text/plain") {
			header(
					'Content-Disposition: attachment; filename="'
							. basename($absPath) . '"');
		}
		exit(0);
	}

	function uploadFile() {
		/* FIXME: limit content-length to something reasonable, max file upload size from PHP? */

		if ($_SERVER['REQUEST_METHOD'] != 'PUT'
				&& $_SERVER['REQUEST_METHOD'] != 'OPTIONS') {
			throw new Exception("invalid request method, should be PUT", 405);
		}

		/* This is to allow "preflight" XMLHttpRequests, 
		 * see https://developer.mozilla.org/En/HTTP_access_control */
		/* FIXME: maybe move this to after the token verification? */
		/* FIXME: maybe be more restrictive in where to allow requests from? */
		if ($_SERVER['REQUEST_METHOD'] == "OPTIONS") {
{'fraction_non_alphanumeric': 0.14897042623506482, 'fraction_numerical': 0.0035590204219981356, 'mean_word_length': 3.711377245508982, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 78, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 21, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2241886', 'n_tokens_mistral': 4110, 'n_tokens_neox': 3550, 'n_words': 1149}