<?php

$password = "your-password";

// folder in which to store uploads
$destdir = "../events";

function logError($msg)
{
	file_put_contents('../upload_log.txt', $msg . PHP_EOL, FILE_APPEND | LOCK_EX);
}

function fatalError($code, $msg)
{
	// clear the old headers
	header_remove();

	// set the actual code
	http_response_code($code);

	// set the header to make sure cache is forced
	header("Cache-Control: no-transform,public,max-age=300,s-maxage=900");

	header('Content-Type: text/plain; charset=utf-8');
	echo $msg;
	logError($msg);
	exit();
}

$id = $_POST["id"];
$request = $_POST["request"];
$filename = $_POST["filename"];
$chksum = $_POST["md5"];
$key = $_POST["key"];

// check client authentication string is correct
$localKey = "breeze" . $id . $password . $filename . $chksum;
if (sha1($localKey) != $key) {
	fatalError(401, "Not authorized $key, " . sha1($localKey) . " id=$id, filename=$filename");
}

if ($request == "get_status")
{
	// check whether file already exists on the server
	$destFile = "$destdir/$filename";
	$arr = array('exists' => file_exists($destFile), 'filename' => $filename);
	fatalError(400, json_encode($arr));
}
else if ($request != "upload")
{
	// check whether it is an upload request
	fatalError(400, "Invalid request: $request");
}

try {
	// Undefined | Multiple Files | $_FILES Corruption Attack
	// If this request falls under any of them, treat it invalid.
	if (!isset($_FILES['fileToUpload']['error']) || is_array($_FILES['fileToUpload']['error'])) {
		fatalError(400, "Invalid parameters");
	}

	// Check $_FILES['fileToUpload']['error'] value.
	switch ($_FILES['fileToUpload']['error']) {
	case UPLOAD_ERR_OK:
		break;
	case UPLOAD_ERR_NO_FILE:
		fatalError(400, 'No file sent');
	case UPLOAD_ERR_INI_SIZE:
	case UPLOAD_ERR_FORM_SIZE:
		fatalError(400, 'Exceeded form file size limit');
	default:
		fatalError(400, 'Unknown error');
	}

	// Check MIME type
	$finfo = new finfo(FILEINFO_MIME_TYPE);
	$mimeType = $finfo->file($_FILES['fileToUpload']['tmp_name']);
	if (false === array_search(
		$mimeType,
		array(
			'image/jpeg',
			'image/gif',
			'video/mp4',
			'video/quicktime',
			'text/xml',
		)
	)) {
		fatalError(400, "Unexpected MIME type: " . $mimeType);
	}

	$srcFile = $_FILES["fileToUpload"]["tmp_name"];

	// check file is JPEG, GIF, MP4 or XML
	$fileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
	if ($fileType != "jpg" && $fileType != "gif"  && $fileType != "mp4" && $fileType != "xml" ) {
		fatalError(400, "File type not allowed");
	}

	// check MD5 checksum matches uploaded file
	if (strcasecmp(md5_file($_FILES["fileToUpload"]["tmp_name"]), $chksum) != 0) {
		fatalError(400, "MD5 checksum incorrect");
	}

	// read filename and dir from $filename and create dir if it doesn't already exist
	[ 'basename' => $basename, 'dirname' => $dirname ] = pathinfo($filename);
	$destFile = "$destdir/$basename";
	if (strlen($dirname) > 0)
	{
		$dir = "$destdir/$dirname";
		if (!file_exists($dir)) {
			mkdir($dir, 0777, true);
		}
		if (file_exists($dir)) {
			$destFile = "$dir/$basename";
		}
	}

	// move the uploaded file to the upload folder
	if (move_uploaded_file($srcFile, $destFile)) {
		header('Content-Type: text/plain; charset=utf-8');
		echo "File: $filename";
	} else {
		logError("move_uploaded_file($srcFile, $destFile) failed");
		fatalError(400, "Error copying file to upload folder: $destFile");
	}
} catch (RuntimeException $e) {
	fatalError(400, $e->getMessage());
}

?>
