<?php

include "funcs.php";

if (!ValidateReferer()) {
	header("Location: index$Lingua.php");
	die();
}


$home = "index<<1-IDlingua>>.php";

$querystr = isset($HTTP_SERVER_VARS['QUERY_STRING']) ? $HTTP_SERVER_VARS['QUERY_STRING'] : '';

function checkdatum($datum,$pattern) {
	if (!$datum && $pattern['required']){
		$error['type'] = 1;
		$error['normalvalue'] = $pattern['required'];
		return $error;
	}
	elseif (!$datum && !$pattern['required']) {
		return 0;
	}
	else {
		if ($pattern['maxlength']) {
			if (strlen($datum)>$pattern['maxlength']) {
				$error['type'] = 2;
				$error['normalvalue'] = $pattern['maxlength'];
				return $error;
			}
		}
		if ($pattern['minlength']) {
			if (strlen($datum)<$pattern['minlength']) {
				$error['type'] = 3;
				$error['normalvalue'] = $pattern['minlength'];
				return $error;
			}
		}
		if ($pattern['maxvalue']) {
			if ($datum>$pattern['maxvalue']) {
				$error['type'] = 4;
				$error['normalvalue'] = $pattern['maxvalue'];
				return $error;
			}
		}
		if ($pattern['minvalue']) {
			if ($datum<$pattern['minvalue']) {
				$error['type'] = 5;
				$error['normalvalue'] = $pattern['minvalue'];
				return $error;
			}
		}
		if ($pattern['regexp']) {
			if (!ereg($pattern['regexp'],$datum)) {
				$error['type'] = 6;
				$error['normalvalue'] = $pattern['regexp'];
				return $error;
			}
		}
		return 0;
	}
}

function checkdata($data_array) {
	global $HTTP_POST_VARS;
	$user = Array("name"=>"<<4-nomeutente>>","required"=>"1","maxlength"=>"32","minlength"=>"3","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	if (isset($HTTP_POST_VARS['pw_conf'])) {
		$pw = Array("name"=>"<<4-password>>","required"=>"1","maxlength"=>"32","minlength"=>"5","maxvalue"=>"","minvalue"=>"","regexp"=>"^". quotemeta($HTTP_POST_VARS['pw_conf'])."$");
		$pw_conf = Array("name"=>"<<4-pass_conf>>","required"=>"1","maxlength"=>"32","minlength"=>"5","maxvalue"=>"","minvalue"=>"","regexp"=>"^".quotemeta($HTTP_POST_VARS['pw'])."$");
	}
	$full_name = Array("name"=>"<<4-ordine_nome>>","required"=>"1","maxlength"=>"","minlength"=>"2","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$corp = Array("name"=>"<<4-ordine_ragione_sociale>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$cf_piva = Array("name"=>"<<4-ordine_partita_iva>>","required"=>"0","maxlength"=>"20","minlength"=>"10","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$addr = Array("name"=>"<<4-ordine_indirizzo>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$zip = Array("name"=>"<<4-ordine_cap>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$city = Array("name"=>"<<4-ordine_localita>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$del_name = Array("name"=>"<<4-ordine_denominazione>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$del_addr = Array("name"=>"<<4-ordine_indirizzo>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$del_zip = Array("name"=>"<<4-ordine_cap>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$del_city = Array("name"=>"<<4-ordine_localita>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$country = Array("name"=>"<<4-ordine_stato>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$email = Array("name"=>"<<4-ordine_email>>","required"=>"1","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>'^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$');
	$phone = Array("name"=>"<<4-ordine_telefono>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$notes = Array("name"=>"<<4-ordine_note>>","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$news = Array("name"=>"Newsletter","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$new_usr = Array("name"=>"new_usr","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$refer = Array("name"=>"refer","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$Submit = Array("name"=>"submit","required"=>"0","maxlength"=>"","minlength"=>"","maxvalue"=>"","minvalue"=>"","regexp"=>"");
	$errors = Array();
	$i = 0;
	foreach($data_array as $key => $value) {
		if (isset($$key)) {
			$field = $$key;		
			if ($error = checkdatum($value, $field)) {			 
				$errors[$i] = Array("field"=>$field['name'],"errortype"=>$error['type'],"value"=>$error['normalvalue']);
				$i++;
			}
		}
	}	
	return $errors;
}

function checkUser($usr,$link) { 
	$query = "SELECT user FROM clienti WHERE user = '".MakeQuery($usr)."'";
	$result = mysql_query($query,$link);
	if (mysql_num_rows($result)!= 0){
		return false;
	}
	else {
		return true;
	}
}

function errorparse($errs) {
	$out = "";
	if (count($errs)>0) {
		$out = "<<4-login_err1>><br><br><ol>";
		foreach($errs as $key=>$value) {
			$out .= "<li>";
			switch ($value['errortype']) {
				case 1:
					$str = "<<4-login_err2>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
				case 2:
					$str = "<<4-login_err3>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
				case 3:
					$str = "<<4-login_err4>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
				case 4:
					$str = "<<4-login_err5>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
				case 5:
					$str = "<<4-login_err6>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
				case 6:
					$str = "<<4-login_err7>>";
					$out .= sprintf ($str,$value['field'],$value['value']);
					break;
			}
			$out .= "</li>";
		}
		$out .= "</ol>";
	}
	return $out;	
}

$allowedfields = "##user#pw#full_name#corp#cf_piva#addr#zip#city#del_name#del_addr#del_zip#del_city#country#email#phone#notes#news#";
$mail_shop = "<<1-negozio>>";
$mail_to = $HTTP_POST_VARS['mailto'];
if ($mail_to == "") {
	$mail_to = "<<1-email_ordini>>";
}

$ref =isset($HTTP_SERVER_VARS['HTTP_REFERER']) ? (strpos($HTTP_SERVER_VARS['HTTP_REFERER'],".php") ? basename($HTTP_SERVER_VARS['HTTP_REFERER'],$querystr) : $home) : $home;
$refref = isset($HTTP_POST_VARS['refer']) ? $HTTP_POST_VARS['refer'] : $home;

$ref = ereg_replace('\?.*$','',$ref);
$refref = ereg_replace('\?.*$','',$refref);

if (isset($HTTP_POST_VARS['user'])) {
	if (isset($HTTP_POST_VARS['pw'])) {
		if ($HTTP_POST_VARS['user'] && $HTTP_POST_VARS['pw']) {
			if (isset($HTTP_POST_VARS['new_usr']) && $HTTP_POST_VARS['new_usr']) {
				$err=errorparse(checkdata($HTTP_POST_VARS));
				if ($err) {
					die(Output($err));
				}
				if (!checkUser($HTTP_POST_VARS['user'],$conn)) {
					die(Output("<<4-login_err8>>"));
				}
				$HTTP_POST_VARS['Submit'] = "";
				$HTTP_POST_VARS['new_usr'] = "";
				$HTTP_POST_VARS['refer'] = "";
				$HTTP_POST_VARS['pw_conf'] = "";
				$HTTP_POST_VARS['list'] = "";
				$HTTP_POST_VARS['sconto_cl'] = "";
				$edisplay = "";
				$query = "insert into clienti (";
				foreach($HTTP_POST_VARS as $key => $value){
					if ($value && strpos($allowedfields,"#".$key."#") > 0) {
						$query .= $key.", ";
					} elseif (substr($key,0,9) == "edisplay_") {
						$edisplay .= substr($key,9) . ": " . $value . "\n\n";
					}
				}
				$query .= " subsc_date) values (";
				foreach($HTTP_POST_VARS as $key => $value){					
					if ($value && strpos($allowedfields,"#".$key."#") > 0) {
						$query .= "'".MakeQuery($value)."', ";
					}
				}
				$query .= " now())";
				$res = mysql_query($query);
				$usr = mysql_insert_id($conn);
				if ($edisplay != "") {
					$query = "update clienti set edisplay = '".MakeQuery($edisplay)."' where cust_id=$usr";
					$res = mysql_query($query);
					$edisplay = "$mail_shop\n\nDati aggiuntivi registrazione utente $user\n\n==================================================\n\n\n\n".$edisplay;
					mail($mail_to, "Registrazione utente - $mail_shop", $edisplay, "From: " . $mail_to . "\r\n" . "Reply-To: " . $mail_to . "");
				}
				$s1 = $usr . $UserName . $Password . $DbName;
				$firma = urlencode(md5($s1));
				CookieAndUrl($usr,0,$refref, $firma);
			}
			else {
				$user = $HTTP_POST_VARS['user'];
				$pw = $HTTP_POST_VARS['pw'];
				$query = "select cust_id, user, pw, list from clienti where user = '".MakeQuery($user)."' and pw = '".MakeQuery($pw)."'";
				$res = mysql_query($query);
				$rows = mysql_num_rows($res);
				if ($rows == 1) {
					$row = mysql_fetch_row($res);
					$usr = $row[0];
					$list = $row[3];
					$s1 = $usr . $UserName . $Password . $DbName;
					$firma = urlencode(md5($s1));
					CookieAndUrl($usr,$list,$ref,$firma);
				}			
				else {
					header("Location: ".$ref."?login=ko");
				}
			}
		}
		else {
			if (isset($HTTP_POST_VARS['new_usr']) && $HTTP_POST_VARS['new_usr']) {
				$err=errorparse(checkdata($HTTP_POST_VARS));
				die(Output($err));
			} else {
				header("Location: ".$ref."?login=ko");
			}
		}
	}			
	else {
		if (isset($HTTP_POST_VARS['new_usr']) && !$HTTP_POST_VARS['new_usr']) {
			$err=errorparse(checkdata($HTTP_POST_VARS));
			if ($err) {
				die(Output($err));
			}
			$HTTP_POST_VARS['Submit'] = "";
			$HTTP_POST_VARS['new_usr'] = "";
			$HTTP_POST_VARS['refer'] = "";
			$edisplay = "";
			$query = "update clienti set ";
			foreach($HTTP_POST_VARS as $key => $value){
				if ($key != "Submit" && $key != "new_usr" && $key != "refer" && $key != "list" && $key != "sconto_cl") {
					if (strpos($allowedfields,"#".$key."#") > 0) {
						$query .= $key."='".MakeQuery($value)."',";
					} elseif (substr($key,0,9) == "edisplay_") {
						$edisplay .= substr($key,9) . ": " . $value . "\n\n";
					}
				}
			}
			if(!isset($HTTP_POST_VARS['news'])) {
				$query .= "news='0',";
			}
			$usr = GetCliente();
			$query = substr($query, 0, -1);
			$query .= " where cust_id=$usr";
			$res = mysql_query($query);
			if ($edisplay != "") {
				$query = "SELECT * FROM clienti where cust_id=$usr";
				$res = mysql_query($query);
				if ($row = mysql_fetch_array($res)) {
					$query = "update clienti set edisplay = '".MakeQuery($edisplay)."' where cust_id=$usr";
					$res = mysql_query($query);
					$nome = $row["user"];
					$edisplay = "$mail_shop\n\nDati aggiuntivi modifica utente $nome\n\n==================================================\n\n\n\n".$edisplay;
					mail($mail_to, "Modifica utente - $mail_shop", $edisplay, "From: " . $mail_to . "\r\n" . "Reply-To: " . $mail_to . "");
				} else {
					$edisplay = "";
				}
			}
			print "<html><head><meta http-equiv='refresh' content='0;URL=".$refref."'></head></html>";
		}
		else {
			header("Location: ".$ref);
		}
	}
}
else {
	header("Location: ".$ref);
}

function CookieAndUrl($c1, $c2, $url, $f1) {

	echo "
<HTML>
<HEAD>
<SCRIPT LANGUAGE = \"JavaScript\">
<!--
    function Redirect() {
		document.cookie = \"eDenter_user=$c1\";
		document.cookie = \"eDenter_sign=$f1\";
		document.cookie = \"eDenter_list=$c2\";
    	self.location = \"$url\";
    }
//-->
</SCRIPT>
</HEAD>
<BODY onload=\"Redirect()\">
";

}

?>