<?php
session_start();

/* --------------------------------------------------------- functions ------------------------------------------------------ */

if (!function_exists('file_get_contents')) {
	function file_get_contents($filename) {
		if ($handle = @fopen($filename, 'rb')) {
			$data = fread($handle, filesize($filename));
			fclose($fh);
			return $data;
		}
	}
}


if (!function_exists('file_put_contents')) {
    function file_put_contents($filename, $data) {
        $f = @fopen($filename, 'w');
        if (!$f) {
            return false;
        } else {
            $bytes = fwrite($f, $data);
            fclose($f);
            return $bytes;
        }
    }
}

function sendAmail($to, $betreff, $content){
	global $ki_admin_mail_from;
				
	$content = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>".$betreff."</title></head><body><div style=\"font:13px Arial,Verdana,sans-serif;\">".nl2br($content)."</div></body></html>";
	
	$header  = "MIME-Version: 1.0\r\n";
	$header .= "Content-type: text/html; charset=UTF-8\r\n";
	$header .= "Content-Transfer-Encoding: 8bit\r\n";
	$header .= "From: ".$ki_admin_mail_from."\r\n";

	// verschicke die E-Mail
	@ini_set(sendmail_from, $ki_admin_mail_from);	
	@mail($to, $betreff, $content, $header);
	@ini_restore(sendmail_from);
}



/* ---------------------------------------------------------- end functions -------------------------------------------------- */

if (get_magic_quotes_gpc()) {
    function stripslashes_gpc(&$value)
    {
        $value = stripslashes($value);
    }
    array_walk_recursive($_GET, 'stripslashes_gpc');
    array_walk_recursive($_POST, 'stripslashes_gpc');
    array_walk_recursive($_COOKIE, 'stripslashes_gpc');
    array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}

if(isset($_POST['file']))
	$file = rawurldecode($_POST['file']);
else
	exit;
	
if(isset($_POST['gallery']))
	$gallery = $_POST['gallery'];
else
	exit;

// -------------- Sicherheitsabfragen!
if(preg_match("/[\.]*\//", $file))exit();
if(preg_match("/[\.]*\//", $gallery))exit();
if(!is_file("../ki_galleries/".$gallery."/".$file))exit();
// ---------- Ende Sicherheitsabfragen!

include_once("../ki_config/ki_setup.php");
if(is_file("../ki_config/".$gallery."_ki_setup.php"))include_once("../ki_config/".$gallery."_ki_setup.php");

$pwok = 0;
if(isset($_SESSION['pwquery'])){
	if($_SESSION['pwquery'] === $ki_pw)$pwok = 1;
}

$commfile = "../ki_galleries/".$gallery."/viewercomments/".substr($file, 0, -4).".txt";

if(!isset($_POST['get'])){

	if(isset($_POST['email']))
		$name = addslashes(htmlentities(rawurldecode($_POST['email']), ENT_QUOTES, "UTF-8"));
	else
		exit;
		
	if(isset($_POST['assystem']))
		$comment = addslashes(htmlentities(rawurldecode($_POST['assystem']), ENT_QUOTES, "UTF-8"));
	else
		exit;
	
	if(isset($_POST['address']))
		$address = rawurldecode($_POST['address']);
	else
		exit;
	
	if (!ini_get('date.timezone') && function_exists("date_default_timezone_set"))date_default_timezone_set('Europe/Berlin');
	
	if( stripos($name, "@") !== false ){
		echo "2";
		exit();
	}
	
	$ip = $_SERVER["REMOTE_ADDR"];
	$date = date("m/d/Y");
	$time = date('H').":".date('i');
	
	$moderate = "";
	if($ki_moderate_posts == 1)$moderate = "._.1";
	$post = $name."._.".$date."._.".$time."._.".$ip.$moderate."\r\n".$comment."\r\n:_:\r\n";
	
	$oldcomments = "";
	if(is_file($commfile)){
		$oldcomments = file_get_contents($commfile);
		$handle = @fopen($commfile, "r");
		if($handle) {
			$lastcomment = fgets($handle);
			$data = explode("._.", $lastcomment, 4);
			$lastip = rtrim($data[3]);
			$lastdate = $data[1];
			$lasttime = substr($data[2], 0, 2)*60+substr($data[2], 3, 2);
			$newtime = substr($time, 0, 2)*60+substr($time, 3, 2);
			if($lastip === $ip && $lastdate === $date){
				if($newtime - $lasttime < 3){
					echo "1";
					exit();
				}
			}
		}
		fclose($handle);
	}
	file_put_contents($commfile, $post);
	if($oldcomments !== ""){
		file_put_contents($commfile, $oldcomments, FILE_APPEND);
	}
	
	if($ki_admin_mail != 0){
		$s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : "";
		$address = "http".$s."://".$address;
		$message = stripslashes($comment);
		
		$betreff = "New comment on picture (".$_SERVER['HTTP_HOST'].")";
		if($ki_moderate_posts == 1){
			$content = "A new comment has been made for one of your images. Visit '<a href='".$address."'>".$address."</a>' and flip the picture to read all comments for this image.\nThis is the last comment:\n\n\"".$message."\"\n\nThis comment is moderated and is not readable in public yet. You have the option publish this comment when you login as admin.\n\n\n<small>E-Mail generated by KoschtIT Image Gallery.\n<a href='http://koschtit.tabere.net/en/'>http://koschtit.tabere.net/en/</a></small>";
		} else {
			$content = "A new comment has been made for one of your images. Visit '<a href='".$address."'>".$address."</a>' and flip the picture to read all comments for this image.\nThis is the last comment:\n\n\"".$message."\"\n\n\n<small>E-Mail generated by KoschtIT Image Gallery.\n<a href='http://koschtit.tabere.net/en/'>http://koschtit.tabere.net/en/</a></small>";
		}
		sendAmail($ki_admin_mail_to, $betreff, $content);
	}
}

if(isset($_POST['counter']) || isset($_POST['publish'])){
	$newfile = "";	
}
$counter = 0;
$handle = @fopen($commfile, "r");
if($handle) {
	while(!feof($handle)){
		$head = fgets($handle);
		$headdata = explode("._.", $head);
		$comment = "";
		while($acommentline = fgets($handle)){
			if($acommentline === ":_:\r\n")break;
			$comment .= $acommentline;
		}
		if(sizeof($headdata) == 4 || ($pwok == 1 && sizeof($headdata) == 5)){
			$buttons = "";
			if($pwok == 1){
				if(isset($_POST['publish'])){
					if($counter == $_POST['publish']){
						array_pop($headdata);
						$newfile .= $headdata[0]."._.".$headdata[1]."._.".$headdata[2]."._.".$headdata[3]."\r\n".$comment.":_:\r\n";
					} else {
						$newfile .= $head.$comment.":_:\r\n";					
					}
				}
				$buttons = "<input type='button' value='Delete' style='float:right; margin:0px; padding:0px; cursor:pointer; border:1px solid #000; height:26px; width:100px; background:#bd8b8b; color:#fff;' onclick='kiv.deleteVComm(".$counter.")' />";
				if($ki_moderate_posts == 1 && sizeof($headdata) == 5)$buttons .= "<input type='button' value='Publish' style='float:right; margin:0px; padding:0px; margin-right:10px; cursor:pointer; border:1px solid #000; height:26px; width:100px; background:#658342; color:#fff;' onclick='kiv.publishVComm(".$counter.")' />";
			}
			$skip = 0;
			if(isset($_POST['counter'])){
				if($_POST['counter'] != $counter){
					$newfile .= $head.$comment.":_:\r\n";
				} else {
					$skip = 1;	
				}
			}
			if($skip == 0){
?>
<div style='margin:0px 0px 5px 0px; padding:4px; text-align:left; <?php if($counter != 0)echo "margin-top:10px;" ?>'><?php echo nl2br(stripslashes($comment)) ?></div><div style='font-size:10px; text-align:left; padding:0px 0px 10px 0px;'>&raquo; <span style='padding-left:0px; margin-bottom:10px; color:<?php echo $ki_vcomm_timedate_color ?>;'><?php echo $headdata[1] ?> <?php echo $headdata[2] ?> </span><?php echo $buttons.stripslashes($headdata[0]) ?></div>
<?php
			}
			$counter++;
		}
	}
	fclose($handle);
} else {
	echo "<p style='margin-top:20px; text-align:center; font-weight:bold;'>".$ki_vcomm_ncy."</p>";	
}
if(isset($_POST['counter']) || isset($_POST['publish'])){
	if($pwok == 1){
		if(strlen($newfile) > 2){
			file_put_contents($commfile, $newfile);
		} else {
			@unlink($commfile);
			echo "<p style='margin-top:20px; text-align:center; font-weight:bold;'".$ki_vcomm_ncy."</p>";	
		}
	}
}
?>



