<?php
/**
 * Login Screen
 *
 * Handles the login process
 *
 * @package Multiuser
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: login.php,v 1.00 2006/10/25 22:30:05
 */
 
require_once './core/functions.php';
require_once './core/template.php';
require_once './core/session.php';
require_once './core/setupfunctions.php';



// get script folder for cookie path
$subdir = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'],'/')) . '/';


// Cookie exists but user and pass wasn't given? ->logout
if (!isset($username) && !isset($password) && 
    isset($_COOKIE['PCSusername']) && isset($_COOKIE['PCSpassword'])) 
{
	setcookie('PCSpassword', '', time()-7200, $subdir);
	setcookie('PCSusername', '', time()-7200, $subdir);
    setcookie('PCSuserid',   '', time()-7200, $subdir);
    $_SESSION['pcs'] = array();
	redirect('login.php?error='.urlencode($lang['msg_loggedoff']));
}

// login not yet successful
$login = false;

// Check that user entered stuff in username and password boxes
if (!empty($username) && !empty($password))
{
	// Lets check the format of username to make sure its ok
	if (!eregi ('[a-z]', $username)) 
    {
		$error = $lang['msg_invalidchar'];
	} 
    else 
    {
        $row = runSQL("SELECT passwd, id FROM ".TBL_USERS." WHERE name='".$username."'");

		// if the md5 of the entered password = whats in the database then
		// set all the cookies up again
		if (md5($password) == $row[0]['passwd'])
		{
			$userid = $row[0]['id'];
			$RandNumber = rand (100000000, 999999999);
			if ($permanent) {
				$validtime = time() + 60*60*24*365; //permanent cookie: 1 year
			} else {
				$validtime = null; // no time -> session only
			}
            setcookie('PCSusername', getUserName($userid), $validtime, $subdir);
			setcookie('PCSpassword', $RandNumber, $validtime, $subdir);
			setcookie('PCSuserid', $userid, $validtime, $subdir);
            runSQL("UPDATE ".TBL_USERS." SET cookiecode='$RandNumber' WHERE id=$userid");
			
			$login = true;
		}
        else
        {
			$error = $lang['msg_loginfailed'];
		}
	}
}


if($login)
{
	if (empty($refer)) $refer = 'index.php';
	// update session variables
    update_session();
	// reload config
	loadconfig(true, $userid);
	//exit;
	redirect($refer);
}
else
{
    // prepare templates
    tpl_page('multiuser');

	$smarty->assign('error',$error);
	$smarty->assign('refer',$refer);

    // display templates
    tpl_display('login.tpl');
	// caching enabled?
	if ($config['httpcaching'])
	{
		httpCacheOutput('login', httpCacheCaptureEnd());
	} 
}

?>
