<?php
	@error_reporting(0);
	ini_set("display_errors", 0);

	include("touuchutils.php");
	include("inc/DownloadableFile.php");

	$id = $_GET['id'];
	$firstview = true;
	$idext = '';

	if ($id == 'y3SgZ7') // IP Record
	{
		$filepath = 'lol-tyrone.jpg';
		header('Content-Type: image/jpeg');
		header("Content-Length: " . filesize($filepath));
		header('Content-Disposition: inline; filename=' . $filepath);

		file_put_contents("tyrones-ips.txt", $_SERVER['REMOTE_ADDR'] . " - " . date('M j, Y @ g:i A') . "\n", FILE_APPEND);

		fpassthru(fopen($filepath, "rb"));
		exit;
	}

	if ($id == 'y2SgZ7') // IP Record
	{
		file_put_contents("new-ips.txt", $_SERVER['REMOTE_ADDR'] . " - " . date('M j, Y @ g:i A') . "\n", FILE_APPEND);

		echo('You do not have permission to view the requested image.');
		exit;
	}

	if (isset($_COOKIE[$id]))
	{
		$firstview = false;
	}
	else
	{
		setcookie($id, $id, time() + 60*60*24*365*20);
	}

	if (substr_count($id, '.') == 1)
	{
		$exp = explode('.', $id);
		$id = $exp[0];
		$idext = $exp[1];
	}

	$filepath = getImagePath($id, $firstview);
	$ext = pathinfo($filepath, PATHINFO_EXTENSION);

	if (!$filepath || $filepath == "")
	{
		goHome();
		die();
	}

	if (!file_exists($filepath))
	{
		goHome();
		die();	
	}

	/*if ($idext != '')
	{
		if (strtolower($idext) != strtolower($ext))
		{
			goHome();
			die();
		}
  }*/

	$vLimit = 0;
	$views = getFileViews($id, $vLimit);

	$owner = getFileOwner($id);

	if ($vLimit > 0 && $views > $vLimit && currentUser() != $owner)
	{
		die("File view limit exceeded!  If the file belongs to you, log in and try again.");
	}

	$extra_mime = array(
	'txt'	=>	'text/plain',
	'csv'	=>	'text/plain',
	'webm'	=>	'video/webm',
	'mp3'	=>	'audio/mp3',
	'wav'	=>	'audio/wav',
	'apk'	=>	'application/vnd.android.package-archive',
	'html'	=>	'text/html',
	'pdf'	=>	'application/pdf',
	'webp'	=>	'image/webp',
	'svg'	=>	'image/svg+xml'
	);

	$size = getimagesize($filepath);
	$ctype = $size['mime'];

	if (!$ctype || $ctype == '')
	{
		$ctype = 'application/octet-stream';
		if (array_key_exists($ext, $extra_mime))
			$ctype = $extra_mime[$ext];
	}

	//debugError('->' . $ctype);	

	if (strtolower(substr($ctype, 0, 5)) == 'image')
	{
		header('Cache-Control: max-age=86400, public');
		header('Content-Type: ' . $ctype);
		header("Content-Length: " . filesize($filepath));
		header('Content-Disposition: inline; filename="' . getOriginalName(basename($filepath), $id) . '"');

		fpassthru(fopen($filepath, "rb"));
	}
	else
	{
		$dlf = new Model_DownloadableFile($filepath, $ctype, getOriginalName(basename($filepath), $id));
		$dlf->download_file_in_browser();

		//serveFilePartial($filepath, $ctype, getOriginalName(basename($filepath), $id)); // alternate
	}

	exit;
?>
