<?php
/**
 * $Horde: horde/login.php,v 2.129 2003/06/19 18:47:27 chuck Exp $
 *
 * Copyright 1999-2003 Charles J. Hagenbuch <chuck@horde.org>
 * Copyright 1999-2003 Jon Parise <jon@horde.org>
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 */

define('HORDE_BASE', dirname(__FILE__));
require_once HORDE_BASE . '/lib/base.php';
require_once HORDE_BASE . '/lib/Secret.php';

/* Map the various values for $reason to more descriptive status messages. */
$reason = '';
$reason_map = array(
    '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.")
);

/* Initialize the Auth credentials key. */
Secret::setKey('auth');

/* Get an Auth object. */
$auth = &Auth::singleton($conf['auth']['driver']);

/* Get parameters. */
$reason_param = Horde::getFormData('reason');
$url_param = Horde::getFormData('url');

if ($reason_param == 'logout' || $reason_param == 'session') {
    if ($auth->hasCapability('loginscreen')) {
        $login_screen = $auth->getLoginScreen();
        if (Horde::removeParameter($login_screen, array('url', 'nocache')) !=
            Horde::removeParameter(Horde::url(Horde::selfUrl(), true), array('url', 'nocache'))) {
            $url = Horde::addParameter($login_screen, 'url', $url_param ? $url_param : Horde::selfURL());
            $url = Horde::addParameter($url, 'reason', 'logout');
            header('Location: ' . $url);
            exit;
        }
    }

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

    $entry = sprintf('User %s [%s] logged out of Horde',
                     Auth::getAuth(), $_SERVER['REMOTE_ADDR']);
    Horde::logMessage($entry, __FILE__, __LINE__, PEAR_LOG_NOTICE);
    Auth::clearAuth();
    session_destroy();

    /* If logout has a set initial page, redirect to that. Check that
       it is not a looping redirect. */
    if (isset($registry->applications['logout']['initial_page']) &&
        $registry->applications['logout']['initial_page'] != 'login.php?reason=logout') {
        header('Location: ' . Horde::applicationUrl($registry->applications['logout']['initial_page']));
        exit;
    }

    Horde::setupSessionHandler();
    @session_start();

    NLS::setLang($language);

    /* Hook to preselect the correct language in the widget. */
    $_GET['new_lang'] = $language;
}

if (isset($_POST['horde_user']) && isset($_POST['horde_pass'])) {

    /* Destroy any existing session on login and make sure to use a
     * new session ID, to avoid session fixation issues. */
    Horde::getCleanSession();
    if ($auth->authenticate(Horde::getPost('horde_user'),
                            array('password' => Horde::getPost('horde_pass')))) {
        $entry = sprintf('Login success for %s [%s] to Horde',
                         Auth::getAuth(), $_SERVER['REMOTE_ADDR']);
        Horde::logMessage($entry, __FILE__, __LINE__, PEAR_LOG_INFO);

        if ($url_param) {
            header('Location: ' . Horde::url(Horde::removeParameter($url_param, session_name()), true));
        } else {
            header('Location: ' . Horde::applicationUrl('index.php', true));
        }
        exit;
    } else {
        $reason = $auth->getAuthError();
        $entry = sprintf('FAILED LOGIN for %s [%s] to Horde',
                         Horde::getFormData('horde_user'), $_SERVER['REMOTE_ADDR']);
        Horde::logMessage($entry, __FILE__, __LINE__, PEAR_LOG_ERR);
    }
}

if (empty($reason)) {
    if (!empty($reason_param) && isset($reason_map[$reason_param])) {
        $reason = $reason_map[$reason_param];
    }
}

if (Auth::isAuthenticated()) {
    if ($browser->isMobile()) {
        require HORDE_BASE . '/mobile.php';
    } else {
        require HORDE_BASE . '/portal.php';
    }
    exit;
}

if ($auth->hasCapability('loginscreen')) {
    $login_screen = $auth->getLoginScreen();
    if (Horde::removeParameter($login_screen, array('url', 'nocache')) !=
        Horde::removeParameter(Horde::url(Horde::selfUrl(), true), array('url', 'nocache'))) {
        $url = Horde::addParameter($auth->getLoginScreen(), 'url', $url_param ? $url_param : Horde::selfURL());
        header('Location: ' . $url);
        exit;
    }
}

if ($browser->isMobile()) {
    require_once HORDE_BASE . '/lib/Mobile.php';
    require HORDE_TEMPLATES . '/login/mobile.inc';
    exit;
}

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

$title = _("Log in");
$js_onLoad = 'setFocus()';

// Get a list of applications guests can use, so we can link to
// the guest page if we should.
$apps = $registry->listApps();
$guestapps = array();
$problem = false;
foreach ($apps as $app) {
    if ($registry->allowGuests($app) &&
        $app != 'horde') {
        if ($app == 'problem') {
            $problem = true;
        } else {
            $guestapps[] = $app;
        }
    }
}

require HORDE_TEMPLATES . '/common-header.inc';
$notification->notify();
require HORDE_TEMPLATES . '/login/login.inc';
require HORDE_TEMPLATES . '/common-footer.inc';
