<?php
/**
 * phpaga
 *
 * Session validity check
 *
 * This file contains the necessary routine to check if a user
 * has already logged in and has a valid session.
 *
 * @author Till Gerken <till@tantalo.net>
 * @author Florian Lanthaler <florian@phpaga.net>
 *
 * @version $Id$
 *
 * Copyright (c) 2002, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

session_start();

if ((!isset($_SESSION['auth_session'])) || ($_SESSION['auth_session'] != 1)) {

    require_once(PHPAGA_LIBPATH.'dbtools.php');

    /* Check whether phpaga is set up and a user exists, in case redirect to initial setup */

    $struct = phpaga_db_checkstructure();
    if (PhPagaError::isError($struct))
        die('Unable to determine whether the database is initalized');
    elseif (!$struct) {
        header('Location: install.php');
        exit;
    }

    $numusers = phpaga_user_getNumUsers();
    if (PhPagaError::isError($numusers)) {
        $numusers->printMessage();
        exit;
    }

    if ($numusers == 0)
        header('Location: install.php');

    /* If we are on a (JSON) service page output the proper JSON with the
     * correct status that informs the user that they are not logged in */

    $current_page = basename($_SERVER['PHP_SELF']);
    if ((($current_page == 'service.php') && (phpaga_fetch_POST('saction')!=ACTION_SERVICE_LOGIN))|| ($current_page == 'data_service.php')) {
        $response = array('status' => 99, 'message' => _('You are not logged in.'), 'data' => null);
        header('Content-Type: text/javascript; charset=utf8');
        print json_encode($response);
        exit;
    }

    phpaga_config_read();

    /* Authenticate the user, then reload the current page. */

    if (($current_page != 'service.php') || (phpaga_fetch_POST('saction')!=ACTION_SERVICE_LOGIN)) {
        define('PHPAGA_TPLPATH', PHPAGA_BASETPLPATH.'phpaga');
        /* Configure smarty-gettext directory */
        if (!defined('SMARTYGETTEXT_DIR'))
            define('SMARTYGETTEXT_DIR', PHPAGA_EXTPATH.'/smarty-gettext/');

        /* Configure and include Smarty */
        if (!defined('SMARTY_DIR'))
            define('SMARTY_DIR', PHPAGA_EXTPATH.'smarty/libs/');

        include_once(PHPAGA_LIBPATH.'smarty.php');
        $tpl = new psmarty;
        $tpl->display('login.tpl.html');
        exit;
    }

} else {

    if (isset($REQUEST_DATA['logout'])) {
        phpaga_log(sprintf('LOGOUT: %s', $_SESSION['auth_user']['usr_login']));
        unset($_SESSION['auth_user']);
        unset($_SESSION['auth_session']);

        if (session_destroy()) {
            Header ('Location: ./');
            die();
        } else {
            phpaga_error('Huh? Unable to log out...');
            die();
        }
    }

    /* Increase security a little bit: generate a new session id at
     * each page request */

    /* This is currently DISABLED because it causes problems with
     * pages that open multiple scripts at the same time (like the
     * project page that contains multiple graphs) */
//
//    session_regenerate_id();

    $usr_id = $_SESSION['auth_user']['usr_id'];
    phpaga_config_read($usr_id);
    $auth_user = phpaga_user_getUserInfo($usr_id);

    if (!PhPagaError::isError($auth_user))
        $_SESSION['auth_user'] = $auth_user;

    /* Check if the user has just changed their skin settings */

    if (isset ($REQUEST_DATA['action']) && ($REQUEST_DATA['action'] == ACTION_UPDATE) && (isset($REQUEST_DATA['id'])) &&
        ($usr_id == $REQUEST_DATA['id'])) {

        if (isset($REQUEST_DATA['usr_skin']) && strlen($REQUEST_DATA['usr_skin']))
            $_SESSION['auth_user']['skin'] = $REQUEST_DATA['usr_skin'];
    }
}

?>
