<?php

/********************************************************************************
	- MemHT Portal -
	
	Copyright (C) 2007-2008 by Miltenovik Manojlo
	http://www.memht.com
	
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your opinion) any later version.
	
	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.
	
	You should have received a copy of the GNU General Public License along
	with this program; if not, see <http://www.gnu.org/licenses/> (GPLv2)
	or write to the Free Software Foundation, Inc., 51 Franklin Street,
	Fifth Floor, Boston, MA02110-1301, USA.
		
********************************************************************************/

if (stristr(htmlentities($_SERVER['PHP_SELF']), "inc_login.php")) {
	die("<table style='padding: 2px; border: 1px solid #999; background-color: #EEE; font-family: Verdana; font-size: 10px;' align='center'><tr><td><b>Error:</b> This file cannot be opened directly!</td></tr></table>");
}

global $dblink,$page,$tzNOW;

//==================================
// Find IP
//==================================
if (@getenv("HTTP_CLIENT_IP")) {
	$visitorInfo['ip'] = getenv("HTTP_CLIENT_IP");
} else if (@getenv("HTTP_X_FORWARDED_FOR")) {
	$visitorInfo['ip'] = getenv('HTTP_X_FORWARDED_FOR');
} else if (@getenv('REMOTE_ADDR')) {
	$visitorInfo['ip'] = getenv('REMOTE_ADDR');
} else if (isset($_SERVER['REMOTE_ADDR'])) {
	$visitorInfo['ip'] = $_SERVER['REMOTE_ADDR'];
} else {
	$visitorInfo['ip'] = "Unknown";
}
if (!preg_match("`^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$`is",$visitorInfo['ip']) AND $visitorInfo['ip']!="Unknown") {
	$pos = strpos($visitorInfo['ip'],",");
	$visitorInfo['ip'] = substr($visitorInfo['ip'],0,$pos);
	if ($visitorInfo['ip']=="") { $visitorInfo['ip'] = "Unknown"; }
}

function clear() {
	global $cookiecontent,$cookieitem,$cookie_id,$cookie_user,$cookie_pass,$cookcheck,$dblogin_user,$dblogin_pass,$user,$userid,$admin;
	unset ($cookiecontent,$cookieitem,$cookie_id,$cookie_user,$cookie_pass,$cookcheck,$dblogin_user,$dblogin_pass,$user,$userid,$admin);
}

//===========================================
//Post LoginForm
//===========================================
if (memRunHooks('UserPostLoginCheck',array(&$privs))) {
	if (!function_exists("inCode_t")) {
		function inCode_t($string) {
			if (get_magic_quotes_gpc()) { $string = stripslashes($string); }
			$string = htmlentities($string,ENT_QUOTES);
			return mysql_real_escape_string($string);
		}
	}

	if (isset($_POST['login']) AND isset($_POST['post_username']) AND isset($_POST['post_password'])) {
		if ($dblink->get_num("SELECT attempts FROM memht_login_flood WHERE ip='".$visitorInfo['ip']."' AND attempts>=5")) {
			die(_YOUMUSTWAITTOLOGINAGAIN_);
		} else {
			if ($chk = $dblink->get_row("SELECT id,user,enabled FROM memht_utenti WHERE user='".inCode_t($_POST['post_username'])."' AND pass='".md5($_POST['post_password'])."'")) {
				//Login Correct
				$login_id = intval($chk['id']);
				$login_user = $chk['user'];
				$login_enabled = intval($chk['enabled']);
				if ($login_enabled) {
					//Update account lastlogin and lastip
					$dblink->query("UPDATE memht_utenti SET lastip='".$visitorInfo['ip']."',lastlogin=$tzNOW WHERE id=$login_id");
					//Account Ok
					$cookiecontent = $login_id."#".md5($login_user)."#".md5($_POST['post_password']);
					setcookie("login_user",$cookiecontent,time()+604800); //1week
					$userid = $login_id;
					$privs['user'] = $cookiecontent;
				} else {
					//Account Disabled
					clear();
					$userid = 0;
					$privs['user'] = false;
					setcookie("login_user","",time()-31536000); //-1year
				}
			} else {
				clear();
				$userid = 0;
				$privs['user'] = false;
				setcookie("login_user","",time()-31536000); //-1year
				//Login Failed -> Antiflood/hack system (Attempts Limiter)
				if ($dblink->get_num("SELECT ip FROM memht_login_flood WHERE ip='".$visitorInfo['ip']."'")>0) {
					$dblink->query("UPDATE memht_login_flood SET time=$tzNOW,attempts=attempts+1 WHERE ip='".$visitorInfo['ip']."'");
				} else {
					$dblink->query("INSERT INTO memht_login_flood (ip,time,attempts) VALUES ('".$visitorInfo['ip']."',$tzNOW,'1')");
				}
			}
			@session_start();
			$redirect_url = @$_SESSION['redirect_url'];
			$redirect_age = @$_SESSION['redirect_age']+90;
			if ($redirect_url!="" AND $redirect_age>=time()) {
				$_SESSION['redirect_url'] = "";
				$_SESSION['redirect_age'] = 0;
				header("Location: $redirect_url");
			} else {
				$_SESSION['redirect_url'] = "";
				$_SESSION['redirect_age'] = 0;
				header("Location: index.php?page=users");
			}
		}
	}
	
	memRunHooks('UserPostLoginCheckEnd',array(&$privs));
}

//===========================================
//Stored Cookie
//===========================================
if (memRunHooks('UserCookieLoginCheck',array(&$privs))) {
	if (isset($_COOKIE['login_user'])) {
		$cookiecontent = $_COOKIE['login_user'];
		$cookieitem = explode("#",$cookiecontent);
		$cookie_id = intval($cookieitem[0]);
		$cookie_user = $cookieitem[1]; //md5
		$cookie_pass = $cookieitem[2]; //md5
		
		//Database Account Control
		$cookcheck = $dblink->get_row("SELECT user,pass FROM memht_utenti WHERE id=$cookie_id");
		if ($cookcheck) {
			$dblogin_user = $cookcheck['user'];
			$dblogin_pass = $cookcheck['pass']; //md5
			
			if ($cookie_user==md5($dblogin_user) AND $cookie_pass==$dblogin_pass) {
				//Login Correct
				$userid = $cookie_id;
				$privs['user'] = $cookiecontent;
				//Update account lastlogin and lastip
				$dblink->query("UPDATE memht_utenti SET lastip='".$visitorInfo['ip']."',lastlogin=$tzNOW WHERE id=$userid");
			} else {
				//Delete Cookie (Error? Hack?)
				clear();
				$userid = 0;
				$privs['user'] = false;
				setcookie("login_user","",time()-31536000); //-1year
			}
		}
	} else {
		$userid = 0;
		$privs['user'] = false;
	}
	
	memRunHooks('UserCookieLoginCheckEnd',array(&$privs));
}

//===========================================
//User logout
//===========================================
if (memRunHooks('UserLogout',array(&$privs))) {
	if (isset($_GET['logout']) && $_GET['logout']==1) {
		clear();
		$privs['user'] = false;
		setcookie("login_user","",time()-31536000); //-1year
		header("Location: index.php");
	}
	
	memRunHooks('UserLogoutEnd',array(&$privs));
}

?>