<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/core.php');
include_once($_SERVER['DOCUMENT_ROOT']."/inc/utils.php");
include_once($_SERVER['DOCUMENT_ROOT']."/inc/formUtils.php");
include_once($_SERVER['DOCUMENT_ROOT'].'/inc/session.php');
$content['settings'] = 'loginpage';

$content['windowTitle'] = 'Phoebe — pedagogic planner login';
$content['main'] = '<h1 id="mainTitle"><a href="/" class="titleLink">Phoebe</a></h1>';
$content['main'] .= $topNav;

$content['main'] .= '<h2>Register/login</h2>';
$content['main'] .= "";

$showForms = true;
// Array to store submission validation errors
$validateResult = array();

function doneLogin() {
    prefsToSession();
    //echo $_SERVER['SERVER_NAME'];
    // Redirect to somewhere other than the login page

    if ($_SESSION['curFileOnly']) {
        // The previous page
        header("Location: http://".$_SERVER['SERVER_NAME'].$_SESSION['curFileOnly']);
    } else {
        // The homepage
        header("Location: http://".$_SERVER['SERVER_NAME'].'/');
    }
}

if(isset($_POST['register'])) {
    // Register new user
    while (list($name, $value) = each($_POST)) {
        $html[$name] = html_encode($value);
    }
    $required = array("username_register", "password", "password_check", "email", "email_check");
    $validate = array("username_register" => "existing_user", "email" => "email", "email_check" => "email",
                      "password" => "password");
    $verify = array("email" , "password");

    $validateResult = validateForm($_POST, $required, $validate, $verify);
    //print_r($validateResult );

    if($validateResult == "valid") {
        $showForms = false;
        // Hash password
        $pSalt = substr(md5(uniqid(rand(), true)), 0, SALT_LENGTH);
        $pHash = generateHash($_POST["password"]);

        // Create account
        $values = $mdb2->quote(date('Y-m-d H:i:s')).', '.
                  $mdb2->quote($_POST["email"]).', '.
                  $mdb2->quote($_POST["fullname"]).', '.
                  $mdb2->quote($_POST["username_register"]).', '.
                  $mdb2->quote($_POST["username_register"]).', '.
                  $mdb2->quote($pHash).', '.
                  $mdb2->quote($_POST["website"]);

        $sql = 'INSERT INTO users (user_created, email, fullname, login_name, nickname, password_hash, website) '.
               'VALUES ('.$values.')';
        //echo $sql.'<br><br>';
        $insert = $mdb2->exec($sql);

        // Always check that result is not an error
        if (PEAR::isError($insert)) {
            $result = 'Error creating new user - '.$insert->getMessage();
        } else {
            // Get the new design id
            $newUserId = $mdb2->lastInsertID();
            $_SESSION['userid'] = $newUserId;
            doneLogin();
        }
    }

} else if(isset($_POST['login'])) {
    // Login existing user
    while (list($name, $value) = each($_POST)) {
        $html[$name] = html_encode($value);
    }
    $required = array("username_login", "password",);
    $validate = array();

    if($_POST['username_login'] != '') {
        // Check username/password
        $sql = 'SELECT user_id, password_hash FROM users'.
               ' WHERE login_name = '.$mdb2->quote($_POST['username_login']);
        //echo 'select'.$sql;

        $user = $mdb2->queryRow($sql);
        if (PEAR::isError($user)) {
            die('Error accessing database - '.$user->getMessage());
        } else {
            if(sizeof($user) <= 0) {
                // No user found
                $incorrectLogin = true;
            } else {
                $newhash = generateHash($_POST["password"], $user['password_hash']);
                $expectedHash = substr($user['password'], SALT_LENGTH, strlen($user['password_hash']) - SALT_LENGTH);
                $expectedHash = $user['password_hash'];

                if ($newhash == $expectedHash) {
                    $showForms = false;
                    echo "match: ".$user['user_id'];
                    $_SESSION['userid'] = $user['user_id'];
                    doneLogin();
                } else {
                    // Password doesn't match
                    $incorrectLogin = true;
                    //echo "no match";
                }
            }
        }
    }

    $validateResult = validateForm($_POST, $required, $validate);
    //print_r($validateResult);
}

if ($showForms) {
    //print_r($validateResult);
    if (isset($msg)) { print "<div class=\"alert\">$msg</div>"; }
    if (isset($error)) { print "<div class=\"error\">$error</div>"; }
    if (isset($success)) { print "<div class=\"success\">$success</div>"; }

    $content['main'] .= '
        <p>Fields marked * are required.</p>
        <div id="login">
            <form method="post" action="">
                <fieldset>
                    <legend>Phoebe login</legend>';
    if($incorrectLogin) {
        $content['main'] .= '<p>Username and/or password incorrect.</p>';
    }
    $content['main'] .= '<dl class="form">
                        <input type="hidden" name="login" value="login" />';

    $content['main'] .= '<dt>Username:</dt> <dd><input type="text" name="username_login" id="username_login" value="'.
                        $html['username_login'].'"/>* '.
                        fieldValidMessage("username_login", $validateResult).'</dd>';

    $content['main'] .= '<dt>Password:</dt> <dd><input type="password" name="password" value="'.
                        $html['password'].'"/>* '.
                        fieldValidMessage("password", $validateResult).'</dd>';

    $content['main'] .= '<dd class="submitButton"><input type="submit" value="Login" /><br>
                        <a href="/login/passReset.php">Forgotten password?</a></dd>
                    </dl>
                </fieldset>
            </form>
        </div>';

    // Registration form, hidden by default
    $class = ' class="hidden"';
    if(isset($_POST['register'])) {
        // Show registration form.
        $class = '';
    }
    if(isset($_GET['register'])) {
        // Show registration form.
        $class = '';
    }
    $content['main'] .= '<br/>
        <div id="register">
            <form method="post" action="">
                <input type="hidden" name="register" value="register" />
                <fieldset>
                    <legend><a href="index.php?register=1';
    if($_SESSION['curFileOnly']) {
        $content['main'] .= '&curfile='.$_SESSION['curFileOnly'];
    }
    $content['main'] .= '" onclick="toggleHide(\'registerFields\'); return false;">Register new account <img width="16" height="16" src="/inc/img/eye.gif" alt="Click to show/hide"></a></legend>
                    <div id="registerFields"'.$class.'><dl class="form">';

    $content['main'] .= '<dt>Username:</dt> <dd><input type="text" name="username_register" id="username_register" value="'.
                        $html['username_register'].'"/>* '.
                        fieldValidMessage("username_register", $validateResult).'</dd>';
    $content['main'] .= '<dt>Password:</dt> <dd><input type="password" name="password" value="'.
                        $html['password'].'"/>* '.
                        fieldValidMessage("password", $validateResult).'<br>(Must be at least six characters, comprising both letters and numbers.)</dd>';
    $content['main'] .= '<dt>Validate password:</dt> <dd><input type="password" name="password_check" value="'.
                        $html['password_check'].'"/>* '
                        .fieldValidMessage("password_check", $validateResult).'</dd>';
    $content['main'] .= '<dt>Email address:</dt> <dd><input type="text" name="email" id="email_register" value="'.
                        $html['email'].'"/>* '.
                        fieldValidMessage("email", $validateResult).'</dd>';
    $content['main'] .= '<dt>Validate email:</dt> <dd><input type="text" name="email_check" id="email_check" value="'.
                        $html['email_check'].'"/>* '
                        .fieldValidMessage("email_check", $validateResult).'</dd>';

    $content['main'] .= '<dt>Full name:</dt> <dd><input type="text" name="fullname" id="fullname_register" value="'.
                        $html['fullname'].'"/></dd>
                        <dt>Website:</dt> <dd><input type="text" name="website" id="website_register" value="'.
                        $html['website'].'"/></dd>
                        <dd class="submitButton"><input type="submit" value="Register" /></dd>
                    </dl></div>
                </fieldset>
            </form>
        </div>';


    $content['main'] .= '<br/>
        <div id="verify-form">
            <form method="get" action="try_auth.php">
                <fieldset>
                    <legend>OpenID register/login</legend>
                    <p>Sorry, OpenId login is currently unavailable.</p>';
/*
                    <p>If you have an OpenID you can use it for your Phoebe account.</p>
                    <dl class="form">
                        <dt>Identity&nbsp;URL:</dt> <dd>
                        <input type="hidden" name="action" value="verify" />
                        <input type="hidden" name="openid.sreg.required" value="nickname"/>
                        <input type="hidden" name="openid.sreg.policy_url" value="http://www.admin.ox.ac.uk/councilsec/privacy.shtml"/>
                        <input type="hidden" name="required" value="nickname"/>
                        <input type="hidden" name="policy_url" value="http://www.admin.ox.ac.uk/councilsec/privacy.shtml"/>
                        <input type="text" name="openid_identifier" id="openid_identifier" class="openidInput" value=""/>
                        <input type="submit" value="Login" /></dd>
                    <dl>

                    <p>If you would like to use <a href="http://www.openid.net/">OpenID</a>, but do not yet have one, visit <a href="http://www.myopenid.com/">myOpenID</a>, or one of the many other <a href="http://openid.net/wiki/index.php/OpenIDServers">OpenID providers</a> to get started.</p>
                    <p>Once you have an OpenID, you will be able to use it for single sign-on in Phoebe and many other sites.</p>
                    <p><strong>Note:</strong> please be aware that we are having problems with authentication with some OpenID providers.</p>
*/
$content['main'] .= '</fieldset>
            </form>
        </div>';

}

// Write via template
include_once($CNF->template);
?>
