<?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['windowTitle'] = 'Phoebe — password reset';
$content['main'] = '<h1 id="mainTitle"><a href="/" class="titleLink">Phoebe</a> <span id="strapLine">Pedagogic planner</span></h1>';

$content['main'] .= '<h2>Password reset</h2>';

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

function checkResetCredentials($rc, $cc) {
    global $CNF, $mdb2, $login_name;
    if (ctype_digit($rc) && ctype_alnum($cc)) {
        $user_id = $rc;
        $confirmationCode = $cc;
        //echo $confirmationCode.'<br>';
        //echo $user_id.'<br>';

        // Get account data
        $sql = 'SELECT * FROM users'.
               ' WHERE user_id = '.$mdb2->quote($user_id);
        //echo $sql.'<br>';
        $user = $mdb2->queryRow($sql);
        if (PEAR::isError($user)) {
            die('Error: '.$user->getMessage());
        } else {
            // Check that the code is correct and not too old
            $confirm = explode('|', $user['confirmation_code']);
            //print_r($confirm);
            //echo $confirm[1].'<br>';
            if($confirm[1] == $confirmationCode) {
                //echo "vaild code";
                if(time() < ($confirm[0] + $CNF->confirmationLifespan)) {
                    // Code is recent enough
                    $login_name = $user['login_name'];
                    $verified = array('rc'=>$user_id, 'cc'=>$confirmationCode);
                } else {
                    // Code expired
                    //echo "Expired".'<br>';
                    $verified = false;
                }
            } else {
                // Not valid code
                //echo "Not valid code".'<br>';
                $verified = false;
            }
            
        }
    } else {
        $verified = false;
    }

    return $verified;
}

if (isset($_GET['rc'])) {
    if ($cred = checkResetCredentials($_GET['rc'], $_GET['cc'])) {
        $user_id = $cred['rc'];
        $confirmationCode = $cred['cc'];
        $showForms = false;
        $showResetForm = true;
    } else {
        // Invalid values
        $content['main'] .= "<p>Invalid reset code.</p>";
    }

} else if(isset($_POST['pass'])) {
    // This is a request to reset the password relating to an  email address
    while (list($name, $value) = each($_POST)) {
        $html[$name] = html_encode($value);
    }
    $required = array("email");
    $validate = array("email" => "existing_email");

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

    if($validateResult == "valid") {
        // Send reset email
        $showForms = false;

        $sql = 'SELECT * FROM users'.
               ' WHERE email = '.$mdb2->quote($_POST['email']).
               " AND login_name != ''";
        //echo $sql;

        $user = $mdb2->queryAll($sql);
        if (PEAR::isError($user)) {
            die('Error: '.$user->getMessage());
        } else {
            // Construct email
            $to = $user[0]['email'];
            $subject = "Phoebe password reset";
            $message = "Dear ".$user[0]['fullname'].",\n\n";
            $message.= "Someone requested a password reset for the Phoebe account relating to this\n".
                       "email address. If you do not want to reset your Phoebe password, just ignore\n".
                       "this message.\n\n";

            if(sizeof($user) == 1) {
                $message.= "To reset your account, open the following link in your web browser:\n";
                    $message.= " ".createResetLink($user[0])."\n\n";
            } else if(sizeof($user) > 1) {
                $message.= "Several accounts were found with this email address.\n".
                           "Choose the account you wish to reset, and load the adjoining link to reset the password:\n";
                foreach($user as $userRecord) {
                    $message.= " ".$userRecord['login_name'].": ".createResetLink($userRecord)."\n\n";
                }
            } else {
                $message.= "Error, could not find account. Please reply to this email investigate the problem.\n\n";
            }

            $message.= "\nThe Phoebe project <http://phoebe-app.conted.ox.ac.uk/>\n";

            $headers = "MIME-Version: 1.0\n".
                       "Content-Type: text/plain; charset=utf-8\n".
                       "From: Phoebe project <".$CNF->phoebeEmail.">\n".
                       "X-Mailer: PHP/".phpversion()."\n".
                       "X-conted-source: ".$_SERVER['SERVER_NAME'];

            // Send email
            mail($to, $subject, $message, $headers);

            // Confirm on page
            $content['main'] .= '<p>An email has been sent to your mail address "'.$html['email'].'".</p>';
            $content['main'] .= '<p>Click the URL in the email to reset your password.</p>';
        }

    }
} else if(isset($_POST['password'])) {
    // Reset account password
    while (list($name, $value) = each($_POST)) {
        $html[$name] = html_encode($value);
    }
    $required = array("password", "password_check");
    $validate = array("password" => "password");
    $verify = array("password");

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

    if($validateResult == "valid") {
        // Reset password
        if ($cred = checkResetCredentials($_POST['rc'], $_POST['cc'])) {
            $user_id = $cred['rc'];
            $confirmationCode = $cred['cc'];
            $reset = setPassword($_POST['rc'], $_POST['password']);
            if($reset) {
                $content['main'] .= '<p>Password reset, please <a href="/login/index.php?curfile=/index.php">log in</a>.</p>';
            } else {
                $content['main'] .= '<p>Sorry, the password reset failed, please <a href="#">try again</a>.</p>';
            }
        } else {
            // Invalid values
            $content['main'] .= "<p>Invalid reset code.</p>";
        }
    } else {
        $user_id = $_POST['rc'];
        $confirmationCode = $_POST['cc'];
        $showForms = false;
        $showResetForm = true;
    }
}

function createResetLink($user) {
    global $mdb2;
    // Generate codes
    $reset = $user['user_id'];
    $confirmationCode = md5(uniqid(rand(), true));

    // Add to database
    $now = time();
    $confirmation = $now.'|'.$confirmationCode;
    $sql = 'UPDATE users'.
           ' SET confirmation_code = '.$mdb2->quote($confirmation).
           ' WHERE user_id = '.$mdb2->quote($user['user_id']);
    //echo $sql.'<br>';
    $insert = $mdb2->exec($sql);

    // Return reset URL
    $url = "http://".$_SERVER['SERVER_NAME']."/login/passReset.php?rc=$reset&cc=$confirmationCode";
    //echo $url.'<br>';
    return $url;
}

if ($showForms) {
    $content['main'] .= '
    <p>Fields marked * are required.</p>
    <div id="login">
        <form method="post" action="/login/passReset.php">
            <input type="hidden" name="pass" value="reset">
            <fieldset>';
    $content['main'] .= '<p>Enter your email address and we will send you an email enabling you to reset it.</p>';
    $content['main'] .= '<p>This form is only for Phoebe logins - not OpenID logins.</p>';
    $content['main'] .= '<dl class="form">';
    $content['main'] .= '<dt>Email address:</dt> <dd><input type="text" name="email" id="email" value="'.
                    $html['email'].'"/>* '.
                    fieldValidMessage("email", $validateResult).'</dd>';
    $content['main'] .= '<dd class="submitButton"><input type="submit" value="Reset password" /></dd>
                </dl>
            </fieldset>
        </form>
    </div>';
}

if($showResetForm) {
    $content['main'] .= '
    <p>Fields marked * are required.</p>
    <div id="login">
        <form method="post" action="/login/passReset.php">
            <input type="hidden" name="rc" value="'.$user_id.'" />
            <input type="hidden" name="cc" value="'.$confirmationCode.'" />
            <fieldset>
                <legend>Reset password</legend>
                <p>Enter your new password for your account <strong>'.$login_name.'</strong> in the fields below.<p>
                </p>It must be at least six characters long, comprising both letters and numbers.</p>
                <div id="registerFields"><dl class="form">';
$content['main'] .= '<dt>Password:</dt> <dd><input type="password" name="password" value=""/>* '.
                    fieldValidMessage("password", $validateResult).'</dd>';
$content['main'] .= '<dt>Validate password:</dt> <dd><input type="password" name="password_check" value=""/>* '
                    .fieldValidMessage("password_check", $validateResult).'</dd>'.
                    '<dd class="submitButton"><input type="submit" value="Reset" /></dd>
                </dl></div>
            </fieldset>
        </form>
    </div>';
}

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