<?php
/**
 * Phoebe pedagogic planner
 *
 * PHP version 5
 *
 * LICENSE: The GNU General Public License (GPL), version 2. See LICENSE.txt
 *
 * Copyright (c) 2006-2008 JISC/HEFCE/University of Oxford
 *
 * @author      David Balch <david.balch@conted.ox.ac.uk>
 * @license     http://opensource.org/licenses/gpl-license.php GPL2
 * @link        http://phoebe-project.conted.ox.ac.uk/
 */

// Initialise user session
session_start();

// Regenerate session id for arriving visitors, to avoid session fixation.
if (!isset($_SESSION['sess-initiated'])) {
    session_regenerate_id();
    $_SESSION['sess-initiated'] = true;
}

if ($_SERVER['PHP_SELF'] == '/login/index.php') {
    // When logging in. save referring page address, so we can return there after logging in.
    $_SESSION['curFileOnly'] = $_GET['curfile'];
    $_SESSION['curfile'] = $_SERVER['DOCUMENT_ROOT'].$_GET['curfile'];
} else {
    if ($openid) {
        // If successfully logged in via OpenID
        $_SESSION['openid'] = $openid;

        $sql = "SELECT * FROM users WHERE openid = '".$openid."'";
        //echo $sql;

        $user = $mdb2->queryRow($sql);
        if (PEAR::isError($user)) {die($user->getMessage());}

        if ($user) {
            // If OpenID account already exists in Phoebe, use it
            $_SESSION['userid'] = $user['user_id'];
        } else {
            // If OpenID account doesn't already exists in Phoebe, create one
            if (!$openid_email) $openid_email = $openid;
            if (!$openid_fullname) $openid_fullname = $openid;
            if (!$openid_nickname) $openid_nickname = $openid;

            $sql = 'INSERT INTO users (openid,email,fullname,nickname,user_created)'.
                   " VALUES ('".$openid."','".$openid_email."','".$openid_fullname."','".$openid_nickname."',".$mdb2->quote(date('Y-m-d H:i:s')).")";
            $add_user = $mdb2->exec($sql);
            if (PEAR::isError($add_user)) {die($add_user->getMessage());}

            $sql = "SELECT * FROM users WHERE openid = '".$openid."'";
            $user = $mdb2->queryRow($sql);
            if (PEAR::isError($user)) {die($user->getMessage());}

            $_SESSION['userid'] = $user['user_id'];
        }
    }

    if (!$openid && !$_SESSION['userid'] && strpos($content['settings'], 'dbWrite') !== false) {
        header('Location: /login/index.php?curfile='.$_SERVER['PHP_SELF']);
    }

    if ($_SESSION['userid']) $user_id = $_SESSION['userid'];
}
?>