#!/usr/local/bin/perl

use CGI qw(:standard);
use DBI;
use DiaryLand;

$username = cookie(diary_login);
$password = cookie(diary_uniq);

$newpassword = param("newpassword");
$newpassword2 = param("newpassword2");
$oldpassword = param("oldpassword");


&DiaryLand::valid_login;           #if this doesn't work the program just exits

&choose_action;

sub choose_action {

        unless ($oldpassword && $newpassword && $newpassword2) {
		&DiaryLand::display_page(change_password);
        }

	&check_newinfo;		# if this is succesful the password gets updated
}

sub check_newinfo {

# first make sure that $newpassword = $newpassword2

	unless ($newpassword eq $newpassword2) {
		$error_message = "<P>those passwords don't actually match.</P>";
		&DiaryLand::display_page(change_password);
		}

# now check that the passwords are okay and don't contain messed up characters that will mess up the script later

	&character_check;

# now make sure the password they gave us is the actual real one!

	$pass_retrieve = "select plain_pass from diaryusers where username='$username'";
	$passretr_handle = $dbhandle -> prepare($pass_retrieve);
	$retr_exec = $passretr_handle -> execute();
	$correct_pass = $passretr_handle -> fetchrow_array();

	unless ($oldpassword eq $correct_pass){
		$error_message = "<P>oops, that's not the right password!</P>";
		&DiaryLand::display_page(change_password);
		}

# okay if they've got this far than they actually have the right password, let's change it!

	$salt = "substr($password,0,2)";
	$pass_toinsert = crypt($newpassword, $salt);

	$sql_update = "update diaryusers set password='$pass_toinsert', plain_pass='$newpassword' where username='$username'";
	$update_handle = $dbhandle -> prepare($sql_update);
	$update_password = $update_handle -> execute();

	&DiaryLand::display_page(password_changed);

}

sub character_check {

        # this checks that it's not over 12 characters
        if (length($newpassword) >12) {
        $error_message = "Sorry, that's too long, passwords need to be between 6 and 12 characters.";
        &DiaryLand::display_page(change_password);
        }

        # this checks that it's not under 6 characters
        if (length($newpassword) <6) {
        $error_message = "Sorry, that's too short, passwords need to be between 6 and 12 characters.";
        &DiaryLand::display_page(change_password);
        }

        # this makes sure it's only letters and numbers and underscores
        if ($newpassword =~ /\W/) {
        $error_message = "passwords can only contain letters, numbers or underscores. Kind of lame eh? We're working on it!";
        &DiaryLand::display_page(change_password);
        }

}

