<?php

require("mysql.inc.php");


/*************************************************************************************
Validate an email address.
Provide email address (raw input)
Returns true if the email address has the email 
address format and the domain exists.
*/
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) 
	  {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}
//*************************************************************************************

require("models.inc.php");

	
	$models_all_list = " ".implode(" ", $models_all)." ";	

	// File that we are saving the information to
	$save_file = "model_update_user_file/names.txt";
	// File Header/column headings separated by tabs
	$file_header = "Time\tName\tAffiliation\tEmail";
	foreach ($models_all as $model_name) {
   		$file_header .= "\t".$model_name;
	}
	$file_header .= "\n";

	// Thank you file where we send person after they submit their information
	$thanks_file = "update_thanks.html";

	// Get form variables
	$name = trim($_POST["name"]);
	$affiliation = trim($_POST["affiliation"]);
	$email = trim($_POST["email"]);
/*
	// get and parse list of models chosen
	$models = $_POST["models"];

	// Check if any models were chosen
	if( $models ) {
		// Yes, so sort the list
		sort($models);
		// Create string of models chosen
		$models_list = " ".implode(" ", $models)." ";
	}
*/	
	$models_list = " ";  	// List of models chosen

	if( $_POST["ALL"] )
		$models_list .= "ALL ";

	else {
		foreach ($_POST as $model_name => $model_value) {

			if( strpos($models_all_list, $model_name) )
				$models_list .= $model_name." ";
			
		}
	}

	// Check if form was submitted properly
	if( $_POST["form_submit"] == "SUBMIT" ) {
	
		$errors = array();
		
		// Check for a blank name
		if( $name == "") {
			$errors[] = "A name must be entered.";
		}
		
		// Check for a blank affiliation
		if( $affiliation == "") {
			$errors[] = "An affiliation must be entered.";
		}

		// Check for a blank email address
		if( $email == "") {
			$errors[] = "An email address must be entered.";
		} else {
			// Check for an invalid email address
			if( !validEmail($email) )
				$errors[] = "An invalid email address was entered.";
		}

		// Check if no models selected
		if( $models_list == " " ) {
			$errors[] = "No models or databases were selected.";
		}

		// Check if any errors were found
		if( count($errors) == 0 ) {
			// No errors
	
			// Find out which models the person has chosen and create a list of those models
					
			// Check if the person selected ALL
			if( strpos($models_list, "ALL") ) {
				$models_chosen = implode("\t", $models_all);
			} else {
			// Person did not select ALL so check each model individually
				$models_chosen = "";
				foreach ($models_all as $model_name) {
					if( strpos($models_list, $model_name) ) { 
						$models_chosen .= $model_name;
					}
					$models_chosen .= "\t";		
				} 	
			}
/*		
			// Save choices to text file
		
			// Remote extraneous spaces
			$models_chosen = str_replace(" ", "", $models_chosen);

			// Remove extranous comma inserted at end of line
			if( $models_chosen[strlen($models_chosen)-1] == "\t" )
				$models_chosen = substr($models_chosen, 0, strlen($models_chosen)-1);

			// Tab characters as separators intead of commas
		    $models_chosen = str_replace(",", "\t", $models_chosen);

			$file = fopen($save_file, 'a') or die("Can't open $save_file file");
			
			
			if (filesize($save_file) == 0 )
				fwrite($file, $file_header);
				
			fwrite($file, time()."\t".$name."\t".$affiliation."\t".$email."\t".$models_chosen."\n");

			fclose($file);
*/

			// Save choices to database

			$sql_text = "delete from model_updates where email='$email';";
//			echo $sql_text."<br>";		
		    mysql_query($sql_text) or die("Could not perform delete command");

			$date_added = date("Y-m-d");
			$sql_text = "insert into model_updates set name='$name', date_added='$date_added', ".
						"affiliation='$affiliation', email='$email'";
//			echo $sql_text."<br>";
			mysql_query($sql_text) or die("Could not perform insert command");
		
			
	if( $_POST["ALL"] ) {
		
		foreach( $models_all as $model_name) {
			$sql_text = "update model_updates set $model_name='X' where email='$email'";
//			echo $sql_text."<br>";
		    mysql_query($sql_text) or die("Could not perform update command");
		}
		
	}
	else {

		foreach ($_POST as $model_name => $model_value) {
	
			if( strpos($models_all_list, $model_name) ) {
				$sql_text = "update model_updates set $model_name='X' where email='$email'";
//				echo $sql_text."<br>";
			    mysql_query($sql_text) or die("Could not perform update command");
			}
		}			
	}

	mysql_close(); 

// Display thank you message
			
//			echo "location = "."Location: http://".$_SERVER["HTTP_HOST"]."/".$thanks_file;
 			header( "Location: http://".$_SERVER["HTTP_HOST"]."/".$thanks_file );
						
			// Done, exit the script
			exit();


}

	}
	

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>AER RTWEB Downloads - Update Notification Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>

<body text="#000000" bgcolor="#33CCFF" link="#0000EE" vlink="#551A8B" alink="#FF0000" background="light_blue_backg.jpg">

<!-- Display form  -->

<form name="update" action="http://<?php echo $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"]; ?>" method="post">
<table width="500" height="560" border="0">
<tr>
<td width="64" colspan="4" align="center"><h2>Model Update Notification</h2>
</tr>
<tr>
  <td colspan="4">
<?php
	// Check if any errors were found
	if( count($errors) > 0 ) {
		// Yes, so print out each error message
  		echo "<br><strong><font color='#FF0000'>The following errors were found. Please correct the 
			errors and resubmit this form.</font></strong><br>";
		foreach ($errors as $error_msg)
   			echo "<br><strong><font color='#FF0000'>".$error_msg."</font></strong>";
		echo "<br><br>";
	} else 
		echo "&nbsp;";
?>

</td>
</tr>

<tr>
<td width="64" colspan="4">Please select the AER radiative transfer models and databases for which you would like to receive email notification of updates by checking the appropriate boxes below.</td>
</tr>

<tr>
  <td height="23" colspan="4">&nbsp;</td>
</tr>
<tr>
  <td height="23">&nbsp;</td>
  <td>&nbsp;</td>
  <td><input type="checkbox" name="ALL" value="ALL" 
 <?php if( strpos($models_list, "ALL") ) echo "checked='checked'"; ?>>ALL</td>
  <td>&nbsp;</td>
</tr>
<?php

		foreach ($models_all as $model_name) {
?>

<tr>
  	<td height="23">&nbsp;</td>
  	<td>&nbsp;</td>
	<td><input type="checkbox" name="<?php echo $model_name ?>" value="<?php echo $model_name ?>" 
 <?php if( strpos($models_list, $model_name) ) echo "checked='checked'"; ?>><?php echo $model_name ?></td>
  	<td>&nbsp;</td>
</tr>


<?php
		}    // End of FOREACH loop 
		
?> 
  

<tr>
  <td height="23" colspan="4">&nbsp;</td>
  </tr>
<tr>
<td height="42" colspan="4">For each category, there are typically no more than a few such
  notifications per year.</td>
</tr>

    <tr >
      <td height="25" colspan="4"><hr></td>
    </tr>
    <tr >
      <td height="23" align="left">&nbsp;</td>
      <td colspan="2" align="left">Please provide the following information</td>
      <td align="right">&nbsp;</td>
    </tr>
    <tr >
      <td height="26" align="left">&nbsp;</td>
      <td align="left">Name:</td>
      <td align="left"><input type="text" name="name"  size="40" value="<?php echo $name; ?>">
</td>
      <td align="right">&nbsp;</td>
    </tr>
    <tr >
      <td height="26" align="left">&nbsp;</td>
      <td align="left">Affiliation:</td>
      <td align="left"><input type="text" name="affiliation"  size="40"	value="<?php echo $affiliation; ?>">
</td>
      <td align="right">&nbsp;</td>
    </tr>
    <tr >
      <td height="26" align="left">&nbsp;</td>
      <td align="left">Email:</td>
      <td align="left"><input type="text" name="email"  size="40" value="<?php echo $email; ?>">
</td>
      <td align="right">&nbsp;</td>
    </tr>
    <tr >
      <td height="23" colspan="4" align="left">&nbsp;</td>
    </tr>
    <tr >
      <td height="28" align="left"><input type="reset" name="reset" value="RESET"></td>
            <td colspan="2" align="left">&nbsp;</td>
            <td align="right"><input type="submit" name="form_submit" value="SUBMIT"></td>
          </tr>

</table>
<p>&nbsp;</p>
</form>

</body>
</html>
