<?php
session_start();

include 'settings.inc';

?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <link href="<?php echo $stylesheet;?>" rel="stylesheet" type="text/css">
  
  <script type="text/javascript">
    function validate(allow_text){
	    submitFlag = true;
	    //regAlph = /^\s*[a-zA-Z\-]+\s*$/;
	    //regAlphBc = /^[a-zA-Z\- ]+$/;
	    // both B and Bc look OK
	    regAlphB = /^\s*[a-zA-Z][a-zA-Z\-\s\.]*$/;
	    regEm = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	    regPhone = /^\+?([0-9]+\s?)+$/;
	    regPhoneB = /^[+0]([0-9]+\s?)+$/;
	    
	    if (!regAlphB.test(document.contact.contact_name.value) ) {
		    document.getElementById("error_ln").style.visibility="visible";
		    submitFlag=false;
	    } else {
		    document.getElementById("error_ln").style.visibility="hidden";
	    }
	    
	    if (!regEm.test(document.contact.email.value)) {
		    document.getElementById("error_email").style.visibility="visible";
		    submitFlag=false;
	    } else {
		    document.getElementById("error_email").style.visibility="hidden";
	    }
	    
	    if (document.contact.message.value.length > <?php echo $max_message_length;?>) {
		    document.getElementById("error_message").style.visibility="visible";
		    submitFlag=false;
	    } else {
		    document.getElementById("error_message").style.visibility="hidden";
	    }
	    
	    if (!submitFlag) {
        document.contact.attempts.value++;
        if (document.contact.attempts.value>2) {
           document.getElementById("alternative").style.display="inline";
        }
      }
	    return submitFlag;
	  }
	  
  </script>
	
	
  <title>Contact form</title>
  </head>
  <body class="approach">
  <a name="top"></a>
  <table align="center">
  
     <col width="*" />
     <col width="700px" />
     <col width="*" />
  
    <tbody>
      
    <tr>
      
      <td valign="top" style="text-align:center;" colspan="3">
        <h1>Get in touch with Chris Clarke</h1>
        &nbsp;<br />
     </td>
   </tr>
   <tr>
     <td>&nbsp;<br /></td>
     <td>
<?php

function echoc ($message,$line) {
  global $email_body, $file_body;
  $email_body .= $message;
  $file_body .= $message;
  if ($line=='nl') {
    $email_body .= "\n";
    $file_body .= "<br />\n";
  }
}

function do_form () {

  global $contact_name, $email, $message, $attempts, $max_message_length;

  echo "<form method=\"post\" name=\"contact\" onsubmit=\"return validate()\" ".
       "action=\"{$_SERVER['PHP_SELF']}\">\n";
  echo "<table><tbody>\n";
  echo "<tr><td>Name&nbsp;</td><td><input type=\"text\" name=\"contact_name\" ".
       "value=\"$contact_name\"> ".
       "<span id =\"error_ln\" style=\"color:red; visibility:hidden\">
		   You need to enter a name
	     </span></td></tr>\n ";
  echo "<tr><td>Email address&nbsp;</td><td><input type=\"text\" name=\"email\" ". 
       "value=\"$email\">".
       "<span id =\"error_email\" style=\"color:red; visibility:hidden\">
			 Please supply a valid email address
       </span></td></tr>\n ";
  echo "</tbody></table>\n";
  echo "<table><tbody>\n";
  echo "<tr><td \colspan=\"2\"> &nbsp;<br />Please enter your message below</td></tr>\n".
       "<tr><td><textarea id=\"message\" name=\"message\" 
           style=\"width:350px; height:120px\" >".
       "$message</textarea></td>\n<td> (maximum $max_message_length characters.)<br />".
       "<span id =\"error_message\" style=\"color:red; visibility:hidden\">
			 The message is longer than $max_message_length characters.</span></td></tr>
       </tbody></table\n";
  //echo "<input type=\"hidden\" name=\"attempts\" value=\"$attempts\">";
  echo "<input type=\"hidden\" name=\"attempts\" value=\"$attempts\">";
  echo "&nbsp;<br />\nIn order to exclude automated spamming, please could you 
        type the letters (all lower case) and numbers shown below in the box indicated<br />\n";// **** here
  echo "<p><img src=\"./kcaptcha/?"; // start the captcha
  echo session_name();
  echo "=";
  echo session_id();
  echo "\">\n";
  echo "&nbsp;&nbsp; enter here:- &nbsp;&nbsp;<input type=\"text\" 
            name=\"keystring\"></p>";
  echo "<br />\n<input type=\"submit\" value=\"Submit message\">";

  echo "</form>";


}
$retry = false;
$contact_name = '';
$email = '';
$message = '';
$attempts = 0;

if (count($_POST)==0)  { // FIRST USE OF FORM
                                                        
  ?>

<p>
Please enter your details and message below and click the 'Submit message' 
button at the end. (Please supply all the entries, including a valid eamil 
address.)<br />
</p>


<?php
  do_form ();

} else { // process form

  $contact_name = $_POST['contact_name'];
  $email = $_POST['email'];
  $message = $_POST['message'];
  $attempts = $_POST['attempts'];
   
  // validate again in case not stopped by java
  $omitted = array();
  if (!$contact_name) $omitted[]='name';
  if (!$email) $omitted[]='email address';
  if (!$message) $omitted[]='message';
  else $message = substr($message,0,$max_message_length);
   
  $captcha = (isset($_SESSION['captcha_keystring']) && $_SESSION['captcha_keystring'] 
     == $_POST['keystring']) ; 
  
  if ($nomits=count($omitted)|| !$captcha >0) {
    $attempts++;
    echo "<span style=\"color:#f00\">";
    if (!$captcha) echo "The security 
    letters typed do not match the original.<br />\n";
    else {
      echo "You need to include your $omitted[0]";
      for ($i=1;$i<$nomits;$i++) { // loop runs if there is more than 1 omission
        if ($i==$nomits-1) echo " and"; // starting last omission
        else echo ",";
        echo " {$omitted[$i]}";
      }
    }
    
    if ($attempts<4) {
      echo " Please try again.</span>";
      echo "<br />&nbsp;<br />\n";
      do_form();
    }
    else echo "I am sorry: the maximum number of attempts has been 
      exceeded.</span><br />\n";
  }  // end of error not trapped by javascript
  
   else // data OK
  {        
    echo "Thank you: your message has been received and I will reply soon.<br />";
    //$results['time']
    //$results['time'] = date('d/m/y H:i:s');  // date already supplied below
    $results['name'] = $contact_name;
    $results['email'] = $email;
    $results['message'] = $message;
    
    
    //prepare data for recording and emailing
  
    $email_body = '';
    $file_body='';
    foreach ($results as $type => $result) {
      echoc( "$type: $result",'nl');
    } 
    echoc( "",'nl');
    
    // check that there is no spam-surge
    $block=false;
    // file consists of first line: time leset reset, second line: traffic since then
    if (file_exists($traffic_log)) {
      $traffic = fopen($traffic_log,'r+');
      $valid_record =  ($last_reset=trim(@fgets($traffic))) &&
                         (($num_events = trim(@fgets($traffic))) >=0 );                       
    } else $valid_record=false;
    
    if ($valid_record) { // update record values
      $num_events++;
      if ($num_events >$traffic_limit)  {  // too many events
        $block=true;
        echoc("number of events = $num_events, exceeding traffic limit",'nl');
      } else  if (($now=time())- $last_reset>$traffic_period_seconds) { // do a reset
        $last_reset=$now;
        $num_events=0;
      }
    } else {
      echoc('trafic file nonexistent or invalid','nl');
      $traffic = fopen($traffic_log,'w+');
      $last_reset=time();
      $num_events=1;
    }
    
    rewind($traffic);
    //echo "<br />Writing $last_reset and $num_events to traffic file<br />";
    fwrite($traffic,$last_reset."\n".$num_events."\n");
    fclose($traffic);
      
    // now send an email 
    $e_preamble = "The following enquiry had been made from the form \n".
                "on the scispirit website\n\n";
    
    $message = wordwrap($e_preamble.$email_body,70);
    $from_address = "\"{$results['name']}\" <{$results['email']}>";
    $ext_header = "From: $from_address";
    mail ($mail_recipient,"Contact from {$results['name']}",
          $message,$ext_header);
          
    // and write to a file
    
    if (file_exists($record_file)) {
      $textfile=file_get_contents($record_file);
      $endpos=strpos($textfile,'</body>');
      $file_stump=substr($textfile,0,$endpos);
    } else {
      $file_stump = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  </head>
  <body><h2>Enquiries from scispirit website</h2>
  ';
    }
    $date = date(DATE_RSS);
    $file_body = $file_stump."Date: $date<br />\n".$file_body."<br />&nbsp;</body></html>";
    $handle = fopen($record_file,'w');
    fwrite($handle,$file_body);  
    fclose($handle);  
   
  } // end of case data OK

}   // ebnd of form processing

unset($_SESSION['captcha_keystring']);
?>

</td>

</tr>

      
      </tbody>
  </table>
  </body>
</html>
