<?php 

include ('../config.php');
session_start();

    $length = 10;
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $newpass = "";    
    for ($p = 0; $p < $length; $p++) {
        $newpass .= $characters[mt_rand(0, strlen($characters))];
}

	$sitequery = 'select * from settings;';
	$siteresult = mysql_query($sitequery,$connection) or die(mysql_error());
	
	//Create site settings variables		
	$siteinfo = mysql_fetch_array($siteresult);
	$sitetitle = $siteinfo['title'];
	$siteurl = $siteinfo['url'];

	$adminquery = 'select * from admins;';
	$adminresults = mysql_query($adminquery,$connection) or die(mysql_error());
	$admininfo = mysql_fetch_array($adminresults);
	$adminemail = $admininfo['email'];

// Update the settings 
if(isset($_POST['getpass'])) { 
	
	$email = $_POST['email'];
	$checkforemails = mysql_query("SELECT * FROM admins WHERE email = '".$email."'");
	
if(mysql_num_rows($checkforemails) != 0){
	$query = "select * from admins where email ='".$email."'";
	$result = mysql_query($query,$connection) or die(mysql_error());
	$info = mysql_fetch_array($result);
	$id = $info['id'];
	$username = $info['username'];

	$sql = "UPDATE `admins` SET `password`='".md5($newpass)."' WHERE `id`=".$id;
	$query = mysql_query($sql);
			
	// send e-mail to ...
	$to=$email; 

	// Your subject 
	$subject="Temporary Admin Password for ".$sitetitle; 

	// From 
	$header="from: Admin <".$adminemail.">"; 

	// Your message 
	$messages ="Your temporary password is $newpass \r\n\n";
	$messages.="You may now login  and update your password from the Account Settings page: \r\n";
	$messages.="Username: $username \r\n";
	$messages.="Password: $newpass \r\n";
	$messages.= $siteurl."/admin/login.php \r\n";

	// send email 
	$sentmail = mail($to,$subject,$messages,$header);

			
	header('Location: forgot.php?emailed=true');
	exit();
	} else {
	header('Location: forgot.php?error=noemail');
	}
	
} 

$metatitle = "Forgot Password - Admin Control Panel";
include ('includes/document_head.php');

	if ($_GET['emailed'] == "true") {
	// if they've tried and failed to log in 
	$errormessage = '<center><p><b>New password has been sent!</b></p></center>';
	} 

?>
		<form method="post" action="forgot.php" id="login_box" class="round_all clearfix">
			<?php echo $errormessage; ?>
			<br/>
			<center><p><b>Enter your email address below</b> and a new auto-generated password will be sent to you. You may then login to your account and update your password from the Admin Settings page.
</p></center>
			<label class="fields"><strong>Email:</strong><input name="email" type="text" id="userid" class="indent round_all"></label>
<input name="getpass" type="hidden" id="getpass" />
			<button class="button_colour round_all"><img width="24" height="24" alt="Locked 2" src="images/icons/small/white/Locked%202.png"><span>Get Password</span></button>
			<div id="bar" class="round_bottom">
			</div>		
		</form>
<?php include 'includes/closing_items.php'?>