<?php
/*
 *    Copyright (c) 2010 VidiScript
 *
 *    This file is part of VidiScript.
 *
 *    VidiScript 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 3 of the License, or
 *    (at your option) any later version.
 *
 *    VidiScript 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 VidiScript.  If not, see <http://www.gnu.org/licenses/>.
 *
 *    File Name: login.php
 *    Description: The page the login form goes to after POST - redirects back to the same page or to the account management page depending on the setting in admin
 *    $Date: 2010-02-21 23:16:57 +0000 (Sun, 21 Feb 2010) $
 *    $Revision: 12 $
 */ 
session_start() ;
require_once '../includes/loginfunctions.inc' ;
function leavePage($logged) {
	global $db ;
	$sitefolder = getSetting("sitefolder", $db) ;
	$sitepath = "http://".$_SERVER['SERVER_NAME'].$sitefolder ;
	$path = "http://".$_SERVER['SERVER_NAME'] ;
	if (isset($_POST['refer']))
		$_SESSION['url'] = $_POST['refer'] ;
	if ($logged == 0) {
		if (getSetting("accountpageon", $db) == 1) {
			header('Location: '.$sitepath.'account') ;
		}
		else {
			if (isset($_SESSION['url'])) {
				$referrer = $_SESSION['url'] ;
				$referURL = !strpos($referrer, $sitepath) ? $referrer : $sitepath ;
				header('Location: '.$path.$referURL) ;
			}
			else if (isset($_SERVER['HTTP_REFERER'])) {
				$referrer = $_SERVER['HTTP_REFERER'] ;
				$referURL = !strpos($referrer, $sitepath) ? $referrer : $sitepath ;
				header('Location: '.$path.$referURL) ;
			}
		}
	}
	else {
		if ($logged == 2)
			$_SESSION['loginerr'] = "You have not activated your account yet, please check your e-mail and activate your account." ;
		elseif ($logged == 1)
			$_SESSION['loginerr'] = "Wrong User name and/or password." ;
		header("Location: ".$sitepath."index.php?loginFailed=$logged") ;
	}
}
$date = gmdate("'Y-m-d'") ;
$db = db_connect() ;
$user = new User($db) ;
if (isset($_GET['logout'])) {
	if ($_GET['logout'] == 1) {
		$user->_logout() ;
		leavePage(0) ;
	}
}
$username = $_POST['user'] ;
$password = $_POST['pass'] ;
$remember = true ;
if (isset($_POST['remember']))
	$remember = $_POST['remember'] ;
$isLogged = -1 ;
$isLogged = $user->_checkLogin($username, $password, $remember) ;
leavePage($isLogged) ;
?>