<?php 
error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED ^E_STRICT); 
$rootPath = is_file("../../../../library/document.php") ? "../../../../" : "../../";
define("CMS", "korCMS");
session_set_cookie_params( null, null, null, false, true);
session_start();
include($rootPath."config/odyssey.ini.php");

if(isset($_GET['secure_protocol'])){
$protocol = ($_GET['secure_protocol'] == "1") ? "https" : "http";
}else{
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https" : "http";
}

$domainPath = $protocol."://".$_SERVER['HTTP_HOST']."/";

function getFPath(){
	$parts = explode("/", $_SERVER["PHP_SELF"]);
	array_shift($parts); // the first element will be empty to we get rid of it
	array_pop($parts); // get rid of script name
	$fPath =implode("/", $parts);
	if(substr($fPath, -1) != "/") $fPath.="/";
	$fPath = ($fPath == "/") ? null : $fPath;	
	return $fPath;	
}

function getBase(){
	global $domain_name;
	if($_SERVER['SERVER_NAME'] == "localhost") return str_replace("localhost", NULL, $domain_name)."/";	
	global $domainPath;
	$www = preg_match('/^www/', $_SERVER['SERVER_NAME']) ? 'www.' : null;
	$parts = explode("/", $_SERVER["PHP_SELF"]);
	array_shift($parts); // the first element will be empty to we get rid of it
	array_pop($parts); // get rid of script name
	$fPath =implode("/", $parts);
	$newPath = $domainPath.$fPath;
	if(substr($newPath, -1) != "/") $newPath.="/";
	return $newPath; // for sef urls, must be a base tag in html HEAD with this value
}

function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
    $escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
    $replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
    $result = str_replace($escapers, $replacements, $value);
    return $result;
}

include($rootPath."library/db.php");
include($rootPath."library/system.php");
include($rootPath."library/messages.php");
include($rootPath."library/variables.php");
include($rootPath."library/language.php");
include($rootPath."library/authentication.php");
include($rootPath."library/dates.php");
include($rootPath."library/parameters.php");
include($rootPath."library/content.php");
include($rootPath."library/eshop.php");
include($rootPath."library/sef.php");
$sef = new sef();
$db = new db();
$system = new system();
$messages = new messages();
$variables = new variables();
$language = new language();
$auth = new authentication(false);
$dates = new dates();
$parameters = new parameters();
$content = new content();
$eshop = new eshop();
$db->query("SET NAMES 'utf8mb4'");
$variables->getSafeVars(array_keys($_REQUEST));

global $langID;

function displayMessage($jsMessage){
	$jsMessage = escapeJsonString($jsMessage);
	echo '[{ "msg": "'.$jsMessage.'" }]';
	exit;
}
function t($key, $langID=NULL, $context=NULL){
	global $language;
	return $language->getText($key, $langID, $context);
}
if(!$langID) displayMessage("Language not defined");
if($action != "add" && $action != "get" && $action != "get_rate") displayMessage("Invalid action");
if($action == "add"){
	if(!isset($message) || !isset($sectionID) || !isset($articleID) || !isset($userID)) displayMessage("Access Denied");
	if(empty($sectionID)) displayMessage("sectionID is empty");
	if(empty($articleID)) displayMessage("articleID is empty");
	if(!empty($userID)){ // check if user has already rated this product
		$q = "select id from comments where userID='$userID' and articleID='$articleID'";
		$alreadyReated = $db->getRecord($q)->id;
		if($alreadyReated) displayMessage(t("Έχετε ήδη αξιολογήσει αυτό το προϊόν"));
	}
	if(empty($message)) displayMessage(t("Πρέπει να πληκτρολογήσετε κάποιο μήνυμα"));

	if($useCaptcha){
		$_POST['security_code'] = strtoupper( $_POST['security_code']); // μονο κεφαλαια στο capcha
		if($_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'])) {
			unset($_SESSION['security_code']); // ολα ok με το captcha image
		}else{
			displayMessage(t("Ο κωδικός ταυτοποίησης που πληκτρολογήσατε δεν είναι σωστός"));
		}
	}
	
	// save comment	
	$nextID = ""; // do not remove!!!
	$published = time();	
	$name = str_replace("'", "&#039;", $name);	
	if(empty($name)){
		$name = ($auth->getLoginStatus() == 2) ? "Guest" : $content->getValue("users", $userID, "title", $langID);
	}		
	$title = $name." | ".$variables->unicode_substr($message, 0, 50)." | ".$dates->makeDatefromTimestamp($published);
	$alias = $variables->toLatin($title);
	$body = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $message); // the comment without empty lines
	$body = str_replace("'", "&#039;", $body);	
	//$originalBody = $body; // for later use, see in multilingual saving	
	$active= (empty($saveAsInactive)) ? 1 : 0;
	$private=0;
	$sort=0;
	$rate = (empty($rate)) ? 0 : (int)$rate;
	$rate = ($rate > 5) ? 5 : $rate;
	$vars = array('nextID','active', 'private', 'sort', 'alias', 'userID', 'published', 'sectionID', 'articleID', 'rate');
	$db->addRecord('comments', $vars);
	global $mainID;
	$mainID = $db->lastID();
	$currentLangID = $langID;
	$Lresult = $db->query("SELECT * FROM languages WHERE active=1 ");
	$LRecords = $db->getRows($Lresult);
	foreach($LRecords as $Lrow) {
		$extension = ($Lrow->extension) ? $Lrow->extension : '_gr';
		$langID = $Lrow->id;
		$title = $name." | ".$variables->unicode_substr($message, 0, 50)." | ".$dates->makeDatefromTimestamp($published)." | ".str_replace("_", NULL, $extension);
		/*
		if($langID != $currentLangID){
			$body = "Comment is not available in current language...";
		}else{
			$body = $originalBody;
		}
		*/
		$vars = array('id', 'mainID', 'langID', 'title', 'body', 'name');
		$db->addRecord('content_comments', $vars);
	}	
	$langID = $currentLangID;
								
	if($sendMail){
		global $domain_name; // get value from config ini
		global $email_address; // get value from config ini

		// mail headers
		$header = "Reply-To: $domain_name <".$email_address.">\n"; 
		$header .= "Return-Path: $domain_name <".$email_address.">\n"; 
		$header .= "From: $domain_name <".$email_address.">\n";
		$header .= "Organization: $domain_name\n"; 
		$header .= "Content-Type: text; charset=utf-8\n";

		
		$msg = null;
		$subject="A comment has published at ".$domain_name;
		$msg=t("Καταχωρήθηκαν τα ακόλουθα στοιχεία στη φόρμα σχολίων").":\n\n";
		$msg.=t("Όνομα").": ".$name."\n\n";
		$msg.=t("Σχόλιο").": \n".stripslashes($body)."\n\n";
		$msg.=t("Μπορείτε να διαχειριστείτε το σχόλιο αυτό στο")." ".$variables->makeURL($domain_name)."/admin/sections.php?action=form&section=comments&itemID=$mainID";
		@mail($email_address, $subject, $msg, $header);
	}
	if($saveAsInactive) {
		$saveMessage = "ok_inactive";
	}else{
		$saveMessage = "ok_active";
	}
	$json_result.='[{ "msg": "'.$saveMessage.'", "id": "'.$mainID.'" }]';
	echo $json_result;
	//displayMessage($saveMessage);
}


if($action == "get"){
	$msg = "ok";
	$startrecord = (int)$startrecord;
	if(!$presults) $presults = $system->getPresults("comments");
	if(empty($presults)) displayMessage("pagination is empty");
	if(empty($articleID)) displayMessage("articleID is empty");
	$comments = $content->getContent("comments", " comments.articleID=".$articleID." ", "*", "*", $langID, " published desc LIMIT $startrecord, $presults");
	$json_result = '[ ';
	foreach($comments as $comment){
		$published = $dates->makeDateFromTimestamp($comment->published);
		$text = escapeJsonString($comment->body);
		$commentID = $comment->id;
		$json_result.='{ "msg": "ok", "id": "'.$comment->id.'", "name": "'.$comment->name.'", "published": "'.$published.'", "text": "'.$text.'" }, ';
	}
	$json_result = substr($json_result ,0 ,-2); // remove trailing comma
	$json_result.=' ]';
	echo $json_result;		
}

if($action == "get_rate"){
	if(empty($commentID)) displayMessage("commentID is empty");
	$q = "select rate from comments where id='$commentID'";
	$value = $db->getRecord($q)->rate;
	$json_result = '[{ "rate": "'.$value.'" }]';
	echo $json_result;		
}



?>