<?php
require_once('user.php');
require_once('common.php');

if ( $session->loggedIn() ) {
  $referer = $_SERVER['HTTP_REFERER'];
  redirect_to("profile.php");
}

$recoverid = $_GET['r'];
$vericode = $_GET['v'];

if( $recoverid && $vericode ) {
  $do_verify = true;
  $userid = $userdb->recoverVerify($recoverid, $vericode);
  if( $userid ) {
    $verify_ok = true;
  }
}

$action = $_POST['action'];
if( $verify_ok && $action=="resetpassword" ) {

  $passwd1 = $_POST['passwd1'];
  $passwd2 = $_POST['passwd2'];

  $check_ok=true;

  $username = $userinfo['username'];

  if( !$passwd1 ) {
    $passwd1_error = "This field is required";
  } else if ( strlen($passwd1) < 5 ) {
    $passwd1_error = "Password is too short. Must be at least 5 characters.";
  }

  if( !$passwd2 ) {
    $passwd2_error = "This field is required";
  } else if( $passwd1 != $passwd2 ) {
    $passwd2_error = "The two passwords do not match";
  }

  $check_ok = !isset($passwd_error) && !isset($passwd1_error) && !isset($passwd2_error);
  if($check_ok) {
    if( $userdb->changePassword($userid, $passwd1)) {
      $session->loginForUser($userid);
      redirect_to("profile.php");
    }
  }
}

require_once('commonheader.php');

?>

<div id="wrap">
  <div id="main">
    <h3>
    My ImageNet Account
    </h3>

    <br clear="all">
    <div class="hr"></div>
    <?php

    $recover_ok = false;

    $action = $_POST['action'];
    if( $action=="recoverpasswd" ) {
      $username = $_POST['username'];
      $userid = $userdb->getUserID($username);

      $captcha = $_POST['g-recaptcha-response'];
      $captcha_valid = check_captcha($captcha);
      if( !$captcha_valid) {
        $recaptcha_error="The reCAPTCHA wasn't entered correctly. Please try again.";
      }

      if( !$userid ) {
        $username_error = "The username does not exists";
      }

      $check_ok = !isset($username_error) && !isset($recaptcha_error);
      if( !$check_ok ) {
        $recover_ok = false;
      } else {
        $userdb->recoverPasswdRequest($userid);
        $recover_ok = true;
      }
    }

    ?>

    <div id="about_content" class="aboutoverview">

      <ul id="about_menu">
      <?php
      print_accountmenu_notloggedin("recoverpasswd");
      ?>
      </ul>

      <div id="about_content_border_fixed">

      <h5>Recover Password</h5>


      <?php
      if( $do_verify ) {
        if( !$verify_ok ) {
          echo "Sorry the URL is not valid or has expired. ";
        } else {
          require("recoverpasswdinclude2.php");
        } 
       } else if( $recover_ok ) {
        echo "We have sent you an email with a link for you to continue. The link will expire in 48 hours. ";
       } else {
        require("recoverpasswdinclude1.php");
       }
      ?>
      </div><!--about_count-->
    </div><!--/about_content_overview-->
  </div><!--/main-->
</div><!--/wrap-->

<br clear="all">
<p>

<?php
require('commonfooter.php');
?>
