#!/usr/bin/perl
# EasyHost
# Built by CyberScript
# Website: http://www.cyberscript.net
# Email: rcampbell@cyberscript.net
# (C) Copyright 2001, All Rights Reserved.
#####################################################
# The following code may not be modified            #
# or redistributed by anyone other then CyberScript #
#####################################################

$pwd = ($0 =~ /^(.+)[\/\\]/)[0] || '.';
require ("$pwd/cs-lib.pl");

&prepare() if ($ENV{REQUEST_METHOD} eq 'POST');

print &ct("text/html").&display("forgot_password");

exit (0);

sub prepare {
	srand(time);

	if ($tokens{name}) {
		&error("The username field contains invalid characters","name") if ($tokens{name} !~ /^[\w\-]+$/);
		&error("The username you entered wasn't found in our database","name") if (!&user_exist($tokens{name}));

		&retrieve($tokens{name}) if (!$tokens{error_message});
	} elsif ($tokens{email}) {
		&error("The email address field contains invalid characters","email") if ($tokens{email} !~ /.+\@[\w\-\.]{4,}/);

		my $count=0;
		foreach (&index_display('email',$tokens{email})) {
			$count++;
			&retrieve($_);
		}

		&error("The email address you entered wasn't found in our database","email") if ($count == 0);
	} else {
		&error("You must enter either your username or email address to retrieve your password");
	}
}

sub retrieve {
	($tokens{name}) = @_;

	$tokens{password} = undef;
	@idset = ('0'..'9','a'..'z');
	for ($i=1;$i<=10;$i++) { $tokens{password} .= $idset[int(rand($#idset + 1))]; }

	my %data = ();

	$data{password} = $tokens{password};

	&user_modify($tokens{name},%data);

	my %user = &user_display($tokens{name});

	my %mail = ();

	$mail{from} = $tokens{site_email};
	$mail{to} = $user{email};
	$mail{subject} = "$tokens{site_title} Account";
	$mail{message} = &file("$tokens{data_dir}/mail/user_retrieve");

	&mail(%mail);

	&notice('forgot_password','forgot their password');

	$tokens{c} = "done";
}