<?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. If the session
 * is valid, then the user may proceed, otherwise she is redirected
 * to the login page. Also, the configuration settings are loaded.
 *
 * @author Till Gerken <till@tantalo.net>
 * @author Florian Lanthaler <florian@phpaga.net>
 *
 * @version $Id: sessions.php 863 2007-09-28 19:08:38Z florian $
 *
 * 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();

/* Do we have an authenticated session? */

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 = 0;

    $numusers = phpaga_user_getNumUsers();

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

    /* If no user is in the database it might be convenient to set one
     * up */

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

    /* If we are on the service page output the proper XML with the
     * correct status that informs the user that she is not logged
     * in */

    if (basename($_SERVER["PHP_SELF"]) == "service.php") {

        header("Content-type: text/xml");
        print("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<response>\n".
              "<status>10</status>\n<message>"._("You are not logged in.")."</message></response>");
        exit;
    }

    /* If we are not on the login page, redirect to the login page to
       authenticate the user, otherwise load the default config
       settings */

    if (basename($_SERVER["PHP_SELF"]) != "login.php") {
        header("Location: login.php");
        die();
    } else {
        phpaga_config_read();
    }
}
else
{

    /* Are we trying to log out? */

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

        if (session_destroy()) {
            Header ("Location: login.php");
            die();
        } else {
            phpaga_error("Huh? Unable to logout...");
            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();

    phpaga_config_read($_SESSION["auth_user"]["usr_id"]);

    $auth_user = phpaga_user_getUserInfo($_SESSION["auth_user"]["usr_id"]);

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

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

    if (isset ($_REQUEST["action"]) && ($_REQUEST["action"] == ACTION_UPDATE) &&
        (isset($_REQUEST["id"])) &&
        ($_SESSION["auth_user"]["usr_id"] == $_REQUEST["id"])) {

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

?>