<?php
//print_r($_GET);

$max_weight = 8*1024*1024; // Poids max de l'image en octets 8 Mo (1Ko = 1024 octets)
$dir = './posts/'; // Repertoire d'upload


function normalize ($string) {
    $m = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿŔŕ ';
    $r = 'AAAAAAACEEEEIIIIDNOOOOOOUUUUYTsaaaaaaaceeeeiiiidnoooooouuuyybyRr_';
    $string = utf8_decode($string);
    $string = strtr($string, utf8_decode($m), $r);
    $string = strtolower($string);
    return utf8_encode($string);
}

$page = 'default';

if (isset($_FILES['f'])) {

// Checking filetype
	if 	(	$_FILES['f']['type'] != 'image/png'
		&& 	$_FILES['f']['type'] != 'image/jpeg'
		&& 	$_FILES['f']['type'] != 'image/jpg'
		&& 	$_FILES['f']['type'] != 'image/gif'
		) {

		$err = 'File must be *.jpeg, *.gif or *.png .';
		// Checking image weight
	} elseif ($_FILES['f']['size'] > $max_weight) {
		$err = 'File must be less than ' . $max_weight/1024 . 'Ko.';
		// Checking upload dir
	} elseif (!file_exists($dir)) {
		$err = $dir.' does not exist.';
	}

	if(isset($err)) {
		echo '' . $err . '<br><a href="javascript:history.back(1)">Back</a>';
	} else {

		// Setting extension
		if ($_FILES['f']['type'] == 'image/jpeg') { $ext = '.jpg'; }
		if ($_FILES['f']['type'] == 'image/png')  { $ext = '.png'; }
		if ($_FILES['f']['type'] == 'image/gif')  { $ext = '.gif'; }
		$name = empty($_POST['name']) ?
			dechex(time()) :
			(file_exists($_POST['name'].$ext) ? $_POST['name'].dechex(time()) : $_POST['name']);

		$name = normalize($name);

		if (preg_match('/^[a-z0-9_-]+$/', $name)==0) $name = dechex(time());

		$filename = $name.$ext;
		$fullfilename = $dir.$filename;

		// Uploading file
		if (move_uploaded_file($_FILES['f']['tmp_name'], $fullfilename)) {
			$logline = date("Y-m-d@H:i:s/T")."\t".$_SERVER['REMOTE_ADDR']."\t".$filename."\n";
			$log = fopen("uploads.log", "a");
			fwrite($log, $logline);
			fclose($log);

			// if ($_SERVER['REMOTE_ADDR']!=trim(file_get_contents('https://media.gregseth.net/current_ip'))) {
			$pagelink = 'https://pix.gregseth.net/0/'.$filename;

            $from       = 'epiphyte@gregseth.net';
            $to         = 'greg.seth+imageupload@gmail.com';
            $subject    = 'A new image has been uploaded on pix.gregseth.net';
            $body       = '<p>The log is:</p><pre>'."\t".$logline.'</pre><p>The picture is available on <a href="'.$pagelink.'">'.$pagelink.'</a>:</p><p style="text-align:center"><a href="'.$pagelink.'"><img src="https://pix.gregseth.net/400/'.$filename.'" style="border:0;"></a></p>';

            $headers    = array();
            $headers[]  = 'MIME-Version: 1.0';
            $headers[]  = 'Content-type: text/html';
            $headers[]  = 'From: epiphyte@gregseth.net';
            $headers[]  = 'Reply-To: epiphyte@gregseth.net';
//            $headers[]  = 'Subject: '.$subject;
            $headers[]  = 'X-Mailer: PHP/'.phpversion();

            mail($to, $subject, $body, implode("\r\n", $headers));
			// }

			header("Location: https://pix.gregseth.net/0/".$name.$ext);
		} else {
			echo 'Upload failed!';
		}
	}
 } elseif (isset($_GET['id']) && isset($_GET['type']) && !empty($_GET['size'])) {
	$img=$dir.$_GET['id'].'.'.$_GET['type'];

	$type=str_replace('jpg','jpeg',$_GET['type']);

	$imgcr='imagecreatefrom'.$type;
	$imgecho='image'.$type;

	$src = (file_exists($img)) ? $imgcr($img) : imagecreatefromjpeg('404.jpg');
	$sx = imagesx($src);
	$sy = imagesy($src);


	if (max($sx, $sy) <= $_GET['size']) {
		$dx = $sx;
		$dy = $sy;
	} else {
		$r=$sx/$sy;
		$dx = round($_GET['size'] * (($sx > $sy) ? 1 : $r));
		$dy = round($_GET['size'] * (($sx > $sy) ? 1/$r : 1));
	}

	$dest=imagecreatetruecolor($dx, $dy);
	if ($type=='png'||$type=='gif') {
		imagealphablending($dest, false);
		imagesavealpha($dest, true);
	}
	imagecopyresampled($dest, $src, 0, 0, 0, 0, $dx, $dy, $sx, $sy);

	header("Content-type: image/".$type);
	$imgecho($dest);

	exit;

} elseif (isset($_GET['size']) && ($_GET['size']==0)) {
	$page = 'display';
}

function getUrl ($size='') {
	$size = ($size==='') ? '' : $size.'/';
	return 'https://pix.gregseth.net/'.$size.$_GET['id'].'.'.$_GET['type'];
}
?>
<!DOCTYPE html>
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="shortcut icon" href="https://www.gregseth.net/img/icons/pix.png" />
<title>pix : gregseth : net</title>

<base href="https://pix.gregseth.net/" />
<link rel="stylesheet" href="default.css" />

<script src="jquery.js"></script>
<script type="text/javascript" src="global.js"></script>

<script>

$(function() {
	var offset = 0;
	var limit = 5;


	function updateContent() {
		var dataUpdated = true;

		$.get('get-list.php', { 'offset':offset, 'limit':limit }, function (data) {
			prevData = $('#last_uploads').html();

			$('#last_uploads').empty();
			$('#last_uploads').html(data);

			if (data == prevData) {
				dataUpdated = false;
			}


		});


		return dataUpdated;
	}

	$('#prev').click(function () {
		offset -= limit;

		if (offset < 0) {
			offset = 0;
		} else {
			if (offset == 0) {
				$('#prev').css('cursor','default');
			} else {
				$('#prev').css('cursor','pointer');
			}

			updateContent();
		}
	});

	$('#next').click(function () {
		offset += limit;

		if (updateContent()) {
		} else {
			offset -= limit*2;
		}
	});


	$('#terms').click(function() {
		$('#terms').toggle();
	});

	updateContent();
});

</script>


</head>

<body>

<div id="header"><a href="https://pix.gregseth.net"><img src="title.png" alt="pix.gregseth.net" /></a></div>
<div id="mini"></div>
<? if ($page == "display"): ?>
<?
$f = file_exists($dir.$_GET['id'].'.'.$_GET['type']);
$url = ($f) ? getUrl('posts') : "https://pix.gregseth.net/404.jpg";
$disable = ($f) ? "" : 'disabled="disabled"';
?>

<p><img src="<?=$url;?>" alt="<?=$url;?>" id="picture" onload="resize(this)" onclick="resize(this)" title="This picture has been downscaled to fit your browser window. Click to view full size picture." /></p>
<ul id="links">
	<li>This page</li>
	<li><input type="text" value="<?=getUrl(0)?>" onclick="this.select()"<?=$disable?>></li>
	<li>Full size picure</li>
	<li><input type="text" value="<?=getUrl()?>" onclick="this.select()"<?=$disable?>></li>
	<li>Thumbnail (300px) with BBCODE</li>
	<li><input type="text" value="[url=<?=getUrl(0)?>][img]<?=getUrl(300)?>[/img][/url]" onclick="this.select()"<?=$disable?>></li>
	<li>Thumbnail (300px) with HTML</li>
	<li><input type="text" value="&lt;a href=&quot;<?=getUrl(0)?>&quot;&gt;&lt;img src=&quot;<?=getUrl(300)?>&quot; alt=&quot;Image hosted by pix.gregseth.net&quot; /&gt;&lt;/a&gt;" onclick="this.select()"<?=$disable?>></li>
</ul>

<? else: ?>

<form method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_weight; ?>">

<ul id="upload">
	<li>Select a picture on your computer (GIF, JPEG or PNG)</li>
	<li><input type="file" name="f"></li>
	<li>You can also choose the name of your file (don't provide extension)</li>
	<li><input type="text" name="name" /></li>
	<li>Click 'Send' to upload your picture</li>
	<li><input type="submit" value="Send"></li>
</ul>

</form>

<ul id="last_cont">

	<li class="nav"><img src="prev.png" alt="Previous" id="prev" class="nav" /></li>

	<li>
		<ul id="last_uploads">

		<!-- TODO: import initial list here. -->

		</ul>
	</li>

	<li class="nav"><img src="next.png" alt="Next" id="next" class="nav" /></li>

</ul>

<? endif; ?>

<div id="footer">A free picture hosting service, powered by <a href="https://www.gregseth.net">gregseth.net</a>. <a href="terms.php" onclick="return terms()">Terms of use</a>.</div>

<div id="terms">

	<h2>Be aware that...</h2>
	<p>This picture hosting service comes with no warranty. That is the availability of the picture you upload is not guaranteed by any means, and can be deleted at any moment.</p>
	<p>Your IP address is logged and linked with every upload.</p>

</div>

<!--begin: Google Analytics-->
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-3754826-3");
pageTracker._initData();
pageTracker._trackPageview();
</script>
<!--end: Google Analytics-->

</body>
</html>
