<?php
/* $Id: index.php,v 1.135 2003/12/11 14:27:19 k-fish Exp $ */

// This line is not standard module a line...do not use it elsewhere
// --------------------------------------------------------------------
if(!file_exists("config.inc.php")) exit("<html><head><title>Error</title><link rel='stylesheet' type='text/css' href='./setup/templates/default/css/setup.css'></head><body bgcolor='#c8c9d4'><table align='center' width='500'><tr><td><br /><table border='0' cellpadding='6' cellspacing='1' bgcolor='black'><tr><td align='center' bgcolor='#ededed'style='font: 12px Arial;'><strong>ERROR</strong></td></tr><tr><td bgcolor='#ededed'style='font: 12px Arial;'><br />Please <a href='setup/index.php'>run setup</a> first.<br /><br />Have a <a href='docs/html/en/index.html'>look at the manual</a> for more information. Chances are, that you need to <a href='http://www.moregroupware.org/manual/mgw-manual-en.tar.gz'>download</a> it first - or <a href='http://www.moregroupware.org/manual/en/index.html'>read it online</a>.</td></tr></table></td></tr></table></body></html>");
// --------------------------------------------------------------------

$myEnv["module"] = "general";
$myEnv["output"] = "html";
$myEnv["translate"] = true;
$myEnv["stdsmenu"] = false;
$myEnv["auth"] = false;

include('config.inc.php');
include(INCLUDEPATH ."container.inc.php");

$num = 0;
$conn = connect_database();

// change language setting
if($_SERVER["REQUEST_METHOD"] == "POST"){
    $loginlang = $_POST["language"];
    $lsql = "SELECT charset FROM mgw_languages WHERE langcode=".$conn->QMagic($_POST["language"]);
    if (!$lres = $conn->Execute($lsql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    $lrow = $lres->FetchRow();
    $logincharset = $lrow["charset"];
}
else{
    $loginlang = $appconf["def_language"];
    $logincharset = $appconf["def_charset"];
}
Lang::setLocaledText($loginlang,"general");
if (!$appconf["encrypt_pwd"]) { $smarty->assign("encrypt_pwd","hex_md5"); }
// send header for used charset
header('Content-Type: text/html; charset='.$logincharset);
$smarty->assign("charset",$logincharset);

// logout
if(isset($_GET["view"]) && $_GET["view"]=="logout"){
    if(!empty($_SESSION["MGW"]->userid)){
	$sql = "UPDATE mgw_users SET lu_date=lu_date, lastin=".$conn->DBTimeStamp(time())." WHERE id=".$_SESSION["MGW"]->userid;
	if (!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
    }

    $_SESSION = array();
    $_SESSION["MGW"]= new MGW();
    session_destroy();
}

// NTLM auth
elseif (isset($_SERVER["REMOTE_USER"]) && $appconf["use_ntlm_auth"]) {
    // FIXME move NTLM auth code into this file, might make more
    // sense?!?
    redirect("index_ntlm.php");
}

// already logged in
elseif (isset($_SESSION['MGW']) && isset($_SESSION['MGW']->userid) && !empty($_SESSION["MGW"]->userid) && !isset($_POST["login"])) {
    redirect(ROOTURL."modules/".$_SESSION["MGW"]->settings["def_module"]."/index.php?".SID);
}

// process login
elseif (isset($_POST["login"])) {
    $row = false;
    $login = $_POST["login"];
    $password = (isset($_POST["password"]) ? $_POST["password"] : "");
    $encrypted_pwd = (isset($_POST["encrypted_pwd"]) ? $_POST["encrypted_pwd"] : "");

    // check for user being in the database
    $sql = "SELECT id, is_ldap FROM mgw_users WHERE username=".$conn->QMagic($login);
    if (($res = $conn->GetRow($sql))===false) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

    if (isset($res['is_ldap']) && $res['is_ldap']==0)
	// we want to use SQL auth for this user (enable admin from db)
	include(INCLUDEPATH ."Auth/sql.inc.php");
    else
	// use the preferred auth method
	include(INCLUDEPATH ."Auth/". $appconf["auth_method"] . ".inc.php");

    if (count($res)==0) { //the username is not present in the database
	if (isset($appconf["create_accounts_on_login"]) && $appconf["create_accounts_on_login"]) {
	    if (authentify_user($login, $password, $encrypted_pwd)) {
		//user does not exists, but was authentified
		//lets create an account for this user if create_accounts_on_login
		// is defined in the config
		create_user_account($login);
		$row = get_user_info($login);
	    }
	}
	else { //the user is not allow to create a new account
	    $smarty->assign('loginerrortext', Lang::getLanguageString("loginerror"));
	}
    }
    elseif(authentify_user($login, $password, $encrypted_pwd)) {
	$row = get_user_info($login);
    }
    else{
	$smarty->assign('loginerrortext', Lang::getLanguageString("loginerror"));
    }

    if(is_array($row)) {
        // Login sucessful
        $_SESSION = array();
        $_SESSION["MGW"]= new MGW();

        $_SESSION["lastin"] = $conn->UnixDate($row["lastin"]);
        $sql = "UPDATE mgw_users SET lu_date=lu_date, lastin=".$conn->DBTimeStamp(time())." WHERE id=".(int)$row["id"];
        if (!$conn->Execute($sql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));

        $_SESSION["checkip"] = (isset($_POST["checkip"]) && $_POST["checkip"]==1) ? 1 : 0;
        $_SESSION["remoteip"] = get_remote_addr();
        $_SESSION["http_user_agent"] = $_SERVER["HTTP_USER_AGENT"];
        if($row["lang"] != "login"){
            $_SESSION["MGW"]->spkz = $row["lang"];
            $_SESSION["MGW"]->charset = $row["charset"];
        }
        else{
            $_SESSION["MGW"]->spkz = $_POST["language"];
            $lsql = "SELECT charset FROM mgw_languages WHERE langcode=".$conn->QMagic($_POST["language"]);
            if (!$lres = $conn->Execute($lsql)) exit(showSQLerror($sql, $conn->ErrorMsg(), __LINE__, __FILE__));
            $lrow = $lres->FetchRow();
            $_SESSION["MGW"]->charset = $lrow["charset"];
        }
        $_SESSION["MGW"]->fullusername = $row["firstname"] . " " . $row["lastname"];
	$_SESSION["MGW"]->email = $row["email"];
        $_SESSION["MGW"]->username = $row["username"];
        $_SESSION["MGW"]->userid   = $row["id"];
        $_SESSION["MGW"]->login = $login;
        $_SESSION["MGW"]->password = $password;
        $_SESSION["MGW"]->modules = array();
        $_SESSION["MGW"]->modules = getInstalledModules();
        $_SESSION["MGW"]->groups = get_user_groups();
        $_SESSION["MGW"]->browser = browser_detect();
        $smarty->assign("charset", $_SESSION["MGW"]->charset);

        getUserSettings();

        redirect("modules/".$_SESSION["MGW"]->settings["def_module"]."/index.php?".SID);
    }
    // Login not successfull
    else {
	$_SESSION = array();
	$_SESSION['MGW']=new MGW();
	$smarty->assign('loginerrortext', Lang::getLanguageString("loginerror"));
    }
}

// plain GET request, no logout, no login
include(INCLUDEPATH . "mSelectBox.class.php");

$lsb = new mSelectBox("language");
$lsb->setContentType("sql");
$lsb->setSQLvalue("langcode");
$lsb->setSQLcontent("description");
$lsb->addContent("SELECT langcode, description FROM mgw_languages ORDER BY description");
$smarty->assign("lsb", $lsb->draw($loginlang, 'onchange="document.f1.submit()"'));

$smarty->display("login.tpl");
?>
