<?php
header('Cache-Control: no-store');
header('Expires: Wed, 09 Sep 2009 09:09:09 GMT');
if (!@chdir('../../')) die('server is fuck');

function sanitize_filename($fn, $sum)
{
	$fn = preg_replace('/[^a-zA-Z0-9]/', '_', $fn);

	if (strlen($fn) <= 2)
		return '';
	
	$whitelist = [ "jpg","png","gif","txt","exe","mp3","aac","m4a",
		"ogg","opus","flac","wav","webm","zip","7z","rar","tgz","mkv","mp4" ];
	
	$ofs = strrpos($fn, '_');
	if ($ofs > 0 && $ofs < strlen($fn))
	{
		$ext = strtolower(substr($fn, $ofs + 1));
		if (in_array($ext, $whitelist, true))
			$fn = substr($fn, 0, $ofs) .'.'. substr($fn, $ofs + 1);
	}
	if (file_exists($fn))
	{
		$ofs = max(strrpos($fn, '_'), strrpos($fn, '.'));
		if ($ofs > 0)
		{
			$fn1 = substr($fn, 0, $ofs);
			$fn2 = substr($fn, $ofs);
		}
		else
		{
			$fn1 = $fn;
			$fn2 = '';
		}
		$ofs = 1;
		while (file_exists($fn))
		{
			if ($ofs > strlen($sum) - 2) break;
			$fn = $fn1 .'-'. substr($sum, 0, $ofs) . $fn2;
			$ofs += 1;
		}
	}
	return $fn;
}

function sanitize_hash($hash)
{
	return preg_replace('/[^a-zA-Z0-9_-]/', '#', $hash);
}

function croak($msg)
{
	error_log($msg);
	header('HTTP/1.1 409 Conflict');
	//echo $msg;
	echo json_encode(["err" => $msg]);
	exit(0);
}
