<?php
/*
 * $Horde: imp/login.php,v 2.128.2.23 2004/03/26 22:43:24 jan Exp $
 *
 * Copyright 1999-2004 Charles J. Hagenbuch <chuck@horde.org>
 * Copyright 1999-2004 Jon Parise <jon@horde.org>
 *
 * See the enclosed file COPYING for license information (GPL).  If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 */

@define('IMP_BASE', dirname(__FILE__));
require_once IMP_BASE . '/lib/base.php';

/* Additional configuration (dependent on the above code libraries). */
require IMP_BASE . '/config/servers.php';

/* Map the various values for $reason to more descriptive status messages. */
$reasons = array('login'   => '',
                 'session' => sprintf(_("Your %s session has expired. Please login again."), $registry->getParam('name')),
                 'logout'  => _("You have been logged out.<br />Thank you for using the system."),
                 'failed'  => _("Login failed for some reason. Most likely your username or password was entered incorrectly."));

/* Default to 'login' if no $reason is set. */
$actionID = Horde::getFormData('actionID');
$reason = Horde::getFormData('reason', 'login');

if (array_key_exists('imp', $_SESSION) && is_array($_SESSION['imp'])) {
    if ($reason == 'logout') {
        $entry = sprintf('Logout for %s [%s] from {%s:%s}',
                         $_SESSION['imp']['uniquser'],
                         $_SERVER['REMOTE_ADDR'], $_SESSION['imp']['server'],
                         $_SESSION['imp']['port']);
        Horde::logMessage($entry, __FILE__, __LINE__, LOG_NOTICE);

        $language = isset($prefs) ? $prefs->getValue('language') : Lang::select();

        unset($_SESSION['imp']);

        if ($registry->getMethod('auth/logout') == 'imp') {
            $prefs->cleanup(true);
            Auth::clearAuth();
            session_destroy();
            if (in_array('setupsessionhandler', get_class_methods('Horde'))) {
                Horde::setupSessionHandler();
            }
            @session_start();
        } else {
            $prefs->cleanup();
        }

        Lang::setLang($language);

        /* Hook to preselect the correct language in the widget. */
        $_GET['new_lang'] = $language;
    } elseif ($reason == 'failed') {
        unset($_SESSION['imp']);

        if ($registry->getMethod('auth/login') == 'imp') {
            Auth::clearAuth();
        }
    } else {
        $url = Horde::applicationUrl('mailbox.php', true);
        /* If there is an existing session, redirect the user to the mailbox. */
        if ($actionID == IMP_LOGIN) {
            $url = IMP::addParameter($url, 'actionID=' . IMP_LOGIN);
        } elseif (($actionID == LOGIN_COMPOSE) ||
                  (Horde::getFormData('action') == 'compose')) {
            $url = IMP::addParameter($url, 'actionID=' . LOGIN_COMPOSE);
            $url = IMP::addParameter($url, IMP::getComposeArgs());
        }
        header('Location: ' . $url);
        exit;
    }
}

/* Log session timeouts. */
if ($reason == 'session') {
    $entry = sprintf('Session timeout for client [%s]', $_SERVER['REMOTE_ADDR']);
    Horde::logMessage($entry, __FILE__, __LINE__, LOG_INFO);

    // Make sure everything is really cleared.
    Auth::clearAuth();
    unset($_SESSION['imp']);
}

/* Redirect the user on logout if redirection is enabled. */
if (($reason == 'logout') && $conf['user']['redirect_on_logout']) {
    $url = IMP::addParameter($conf['user']['redirect_on_logout'], 'reason=logout');
    header('Location: ' . $url);
    exit;
}

/* Redirect the user if an alternate login page has been specified. */
if (in_array($reason, array('login', 'failed', 'session', 'logout')) &&
    $conf['user']['alternate_login']) {
    $url = IMP::addParameter($conf['user']['alternate_login'], 'reason=' . $reason);
    header('Location: ' . $url);
    exit;
}

/* Initialize the password key. */
Secret::setKey('imp');

/* Set the actionID of the login form. */
if ((Horde::getFormData('action') == 'compose') ||
    ($actionID == LOGIN_COMPOSE)) {
    $actionID = LOGIN_COMPOSE;
} else {
    $actionID = IMP_LOGIN;
}

/* Get the default preferences values. */
require_once HORDE_BASE . '/lib/Prefs.php';
$prefs = &Prefs::factory('none', $registry->getApp());
$prefs->setDefaults(IMP_BASE . '/config/prefs.php');

/* Iterate through the servers in an attempt to locate a preferred
   server for this web server/virtualhost. If none are found, we
   default to the first entry in the $servers array that isn't a
   prompt (key begins with '_'). */
foreach ($servers as $key => $curServer) {
    if (!isset($server_key) && substr($key, 0, 1) != '_') {
        $server_key = $key;
    }
    if (IMP::isPreferredServer($curServer, $key)) {
        $server_key = $key;
        break;
    }
}

/* Grab some default values from the preferred or otherwise default
   server. */
$server_value = $servers[$server_key]['server'];
$protocol_value = $servers[$server_key]['protocol'];
$port_value = $servers[$server_key]['port'];
$folders_value = $servers[$server_key]['folders'];
$namespace_value = $servers[$server_key]['namespace'];
$maildomain_value = $servers[$server_key]['maildomain'];
$realm_value = $servers[$server_key]['realm'];

/* Build the <select> widget for the servers list. */
if ($conf['server']['server_list'] == 'shown') {
    $servers_list = '';

    foreach ($servers as $key => $curServer) {
        $sel = (IMP::isPreferredServer($curServer, $key)) ? ' selected="selected"' : '';
        $servers_list .= "<option value=\"$key\"$sel>";
        $servers_list .= $curServer['name'] . '</option>';
    }
}

/* Build the <select> widget containing the available languages. */
if (!$prefs->isLocked('language')) {
    $horde_language = $_SESSION['horde_language'] = Lang::select();
    $langs = '<select name="new_lang" onchange="selectLang()">';
    foreach ($nls['languages'] as $key => $val) {
        $sel = ($key == $horde_language) ? ' selected="selected"' : '';
        $langs .= "<option value=\"$key\"$sel>$val</option>";
    }
    $langs .= '</select>';
}

$title = sprintf(_("Welcome to %s"), ($registry->getMethod('auth/login') == 'imp') ? $registry->getParam('name', 'horde') : $registry->getParam('name'));
$js_onLoad = 'setFocus()';

include IMP_TEMPLATES . '/common-header.inc';
include IMP_TEMPLATES . '/login/login.inc';
if (@is_readable(IMP_BASE . '/config/motd.php')) {
    include IMP_BASE . '/config/motd.php';
}
include IMP_TEMPLATES . '/common-footer.inc';
