Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

Monday, 17 January 2011

New Website to Write!

Great news! One of the best ways to learn, and definitely one of the best ways to teach yourself, is with real-world, practical situations. In many ways this blog and it's sister website are an excuse to do just that.

Even better though, someone has just asked me to re-write their whole site for them. The existing site is called www.terrificart.net. It's going to be a great way to learn a whole bunch of new things:

  • Site Design
  • Dealing with images
  • User-editable dynamic content
  • Slick, dynamic menus
  • XML
  • Advertising
  • Transactions

Site Design


I'm not going to go crazy here as I'm no designer. I just want something which looks fresh, modern and above all simple, intuitive and easy to use.

Dealing With Images


Right now I could write what I know about this on a stamp, so there's a long way to go. Obviously the images and there presentation is absolutely key to this project. I'll be looking to make cool slide-shows, expanding pop-outs and the like. I'm also interested in getting the images cached early for slicker usage.

User-editable dynamic content


Another key element in the design of the site. I want to set up a couple of forms where the site's owners can edit, add and delete artworks on the site.

Slick Dynamic Menus


As the content is dynamic the menus will need to be to.

XML


The key to managing the dynamic content and menus will be the use of XML. I'm hoping to use one simple XML element definition to refer to the artworks listed on the site. There is a massive amount of learning to do here, not just the XML itself but also the JAVA that handles the XML element(s) I set up.

Advertising


I want to get some simple advertising working on the site - again a totally new area for me.

Transactions


I want people to be able to order directly from the site and this will come when everything else is in place. Again, I have no idea about this just now, but I'm going to learn.


So there is an immense amount of learning to do here. I'm going to start with the XML, get my structure defined and some JAVA functions defined to access and modify the XML elements. Next up I'll probably look at the image handling and then the menus. Once these three main areas are sorted I should have the bones of a working site.

At this stage I'll take a look at the general design and feel of the site, like I said earlier - not going too mad. After that it's a case of bolting on the advertising and transactions.

It's going to take a while I reckon.

Saturday, 15 January 2011

Mail Validation And Sending


All the following is the text from the webpage www.RichsWebArchive.com/aboutthissite/mailvalidation/index.php and it reads as though you are viewing the actual page:

This page is the follow-up to Pop-up Mail Form and deals with the validation of the input from that form and the sending of the message it generates. It will hopefully outline a safe and secure method of implementing the sending of mail from a mail form.

There is an item on the blog previous to this page which talks about setting up the mail form, it's probably a good idea to check this or the Pop-up Mail Form page on this site out before reading the rest of this.

You can download a zip archive of the relevant files called rwa_mailform1.zip. Files in the archive are from 15.01.2011 and may not reflect he current state of the site. Any links in this page to sendmail.php will instead take you to a file called sendmail_publish.zip - this is a version of sendmail.php with my address and key removed.

I had several objectives to achieve when setting up the mail form, these are the ones which remain to be sorted:


The following original objectives still need some action to complete:

  • Pass a sub-string of the referring page's url forward
  • Enable a CAPTCHA box on the form.

First of all a word or two about the sendmail.php file which this page is about. It's basically a nested PHP structure which walks through the stages of validation. Error handling is all dealt with within the page. Once all validation is passed the page sends the message.

The first stage in the validation process is to check to see if the input from the CAPTCHA box on the mail form was correct. This is dealt with by the following code:

require_once('recaptchalib.php');
$privatekey = "YOUR_PRIVATE_KEY_GOES_HERE";
$resp = recaptcha_check_answer ($privatekey,
 $_SERVER["REMOTE_ADDR"],
 $_POST["recaptcha_challenge_field"],
 $_POST["recaptcha_response_field"]
);
if (!$resp-<is_valid) { // the CAPTCHA was entered incorrectly
 echo ">h4<Error - CAPTCHA words entered incorrectly.>/h4< \r\n";
 echo "Please  hit the button below and try again. >br/<>br/<";
 ?<
  >FORM<
   >INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"< 
  >/FORM<
 >?php
}

The first six lines do the check for you. They are taken from the code you are sent when you sign up for your access keys. The variable $resp will hold the value true if validation is good.

The line starting if (!$resp-<is_valid) is the beginning of the nested validation structure. The following lines are the error-handling for incorrect CAPTCHA input.

Once CAPTCHA input verification is true the following code comes into play:

else { // CAPTCHA verification ok, now read variables passed from mail form
 $name = $_REQUEST['name'] ;
 $address = $_REQUEST['address'] ;
 $subject = $_REQUEST['subject'] ;
 $subjectUser = $_REQUEST['subjectUser'] ;
 $subject .= "-";   //build subject string
 $subject .= $subjectUser;
 $to = "YOUR_EMAIL_ADDRESS_GOES_HERE";
 $message = $_REQUEST['message'] ;

This code sets up a bunch of local variables with the input from the mail form. It also joins the two fields subject and subjectUser with a - in between them.

The following code will prevent direct calling of this page:
if (!isset($_REQUEST['address'])) { //catch direct calling of this page
 echo ">h4<Direct calling of this page is prohibited.>/h4<";
 echo '>h4<Please >a href="JavaScript:window.close()"<Close>/a< this window to continue.>/h4<'; 
}

This test is now redundant as the CAPTCHA test would fail if the page was directly called, i.e. not called from the mail form. I've left it in here as it does no harm and I might like to use a version of this page without the CAPTCHA test in the future.

Now it's time to make sure that the Your Address and Message fields are not empty:
} // catch empty address or message fields
elseif (empty($address) || empty($message)) {
 echo ">h4<Error - missing information.>/h4< \r\n";
 echo "Either the >emph<Your Address>/emph< or >emph<Message>/emph< fields are empty.>br/<>br/<";
 echo "Please  hit the button below and fill in the missing information. >br/<>br/<";
 ?<
  >FORM<
   >INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"< 
  >/FORM<
 >?php
}

The code checks to see if either field is empty and if so throws the error handling code back to the user. This is followed by this code:

} // validation good so far
else {
 // In case any of our lines are larger than 70 characters, we should use wordwrap()
 $message = wordwrap($message, 70);
 // To send HTML mail, the Content-type header must be set
 $headers  = 'MIME-Version: 1.0' . "\r\n";
 $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
 $headers .= "To: $to" . "\r\n";
 $headers .= "From: $name >$address<" . "\r\n";

This does a little tidying up - it wraps the message field to lines of 70 characters and sets up $headers string that will be sent with the message.

Next comes the following code to prevent Injection Attacks:
// function to check for injection attack from spammers.
function isInjected($str) {
 $injections = array( //set array of characters/strings to detect
  '(\n+)',
  '(\r+)',
  '(\t+)',
  '(%0A+)',
  '(%0D+)',
  '(To:+)',
  '(cc:+)',
  '(boundary=+)',
  '(%08+)',
  '(%09+)'
 );
 $inject = join('|', $injections);
 $inject = "/$inject/i";
 if(preg_match($inject,$str)) {
  return true; // injection attack characters detected
 }
 else { 
  return false; // no injection attack characters detected
 }
}

// now check for injection attempt
if (isInjected($address)) { // injection attack detected 
 echo ">h4<Sorry - illegal characters in the Your Address field.>/h4< \r\n";
 echo 'Please hit back button below and edit the address. >br/<>br/<'; 
 ?<
  >FORM<
   >INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"< 
  >/FORM<
 >?php
}

Firstly this sets up the function isInjected which will check for the presence of a number of special characters and strings in the email address entered in the form. Then the function is called and if any illegal input is found the code throws the error handling at the user.

OK, so now all validation has been passed, it's time to send the email:
else { // all validation ok - so send message.
 if (mail( $to, $subject, $message, $headers )) { //on successful send
  echo ">h4<Mail Sent>/h4<";
  echo "From: $name - $address >br/<Subject: $subject";
  echo '>h4<Please >a href="JavaScript:window.close()"<Close>/a< this window to continue.>/h4<'; 
 }
 else { // send failed
  echo ">h4<Sorry - an error has occurred>/h4< \r\n";
  echo 'Please  hit back button below and try and send the message again. >br/<>br/<If that fails then please >a href="JavaScript:window.close()"<Close>/a< this window and try again.>/h4< >br/<>br/<'; 
  ?<
   >FORM<
    >INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);return true;"< 
   >/FORM<
  >?php

 };

The second line is the key here. If the email is successfully sent then a confirmation is sent to the user and they are asked to close the pop-up window. If sending fails error handing code is sent instead.

That's it. Hopefully you can now setup a fully functioning and secure mail form and send-mail script. Your eMail address is never visible to anyone - the PHP keeps it away from browsers and hopefully spiders too, the CAPTCHA mechanism should protect you from machine-based attacks and you are protected from injection attacks too.

Once again, all the preceding text is from the webpage www.RichsWebArchive.com/aboutthissite/mailvalidation/index.php and it reads as though you are viewing the actual page:

Friday, 14 January 2011

Pop-up Mail Form


All the following is the text from the webpage www.RichsWebArchive.com/aboutthissite/popupmailform/index.php and it reads as though you are viewing the actual page:

I wanted to replace the somewhat clunky message options on the site, as outlined on the Stopping Spambots page, with a safe and secure pop-up mail form.

There is an item on the blog previous to this page which talks about this a bit, it's probably a good idea to check it out before reading the rest of this.

You can download a zip archive of the relevant files called rwa_mailform1.zip. Files in the archive are from 15.01.2011 and may not reflect the current state of the site. Any links in this page to sendmail.php will instead take you to a file called sendmail_publish.zip - this is a version of sendmail.php with my address and key removed.

I had several objectives to achieve here:
  • Building the form
  • Open the form in pop-up window
  • Validate user input
  • Prevent Injection Attacks
  • Pass a sub-string of the referring page's url forward
  • Enable a CAPTCHA box on the form.

In tandem, almost, with making this page was the creation of another page called sendmail.php which does all the validation, error handling and sends the message. This page will not cover these issues. For a full run-down on sendmail.php please go to the Mail Validation & Sending page.

The first task was to create the pop-up window for the form to go in. There are two parts to this, the first is a link in the navbarlinks.htm file:

>a href="/contact/mailform.php" onClick="popUp(this.href, 'fixed', 495, 605);  
return false;" target="_blank"<Send me a message about this page>/a<

The href in the link targets the mailform.php page. The onClick part of the tag calls the JAVA function to open the href in a pop-up window. There are four parameters sent to the popUp function: this.href takes the href defined earlier in the link; 'fixed' tells the function to make a pop-up window of fixed dimensions, as defined by the last two parameters; width, and; height.

The second part is the JAVA function to open the pop-up window, which is placed in the sitewideheadcode.htm file, and thus loaded into every page on the site:

>script type="text/javascript"<
<!--
 var newWin = null;  
 function popUp(strURL, strType, strHeight, strWidth) {  
  if (newWin != null && !newWin.closed)  
   newWin.close();  
  var strOptions="";  
  if (strType=="console")  
   strOptions="resizable,height="+ 
   strHeight+",width="+strWidth;  
  if (strType=="fixed")  
   strOptions="status,height="+  
   strHeight+",width="+strWidth;  
  if (strType=="elastic")  
   strOptions="toolbar,menubar,scrollbars,"+  
   "resizable,location,height="+  
   strHeight+",width="+strWidth;  
  //set new window to open in centre of screen
  var left   = (screen.width  - strWidth)/2;
  var top    = (screen.height - strWidth)/2;
  strOptions += ",top="+top+",left="+left;
  //open window
  newWin = window.open(strURL, 'newWin', strOptions);  
  newWin.focus();  
 }
//-->
>/script<

This robust JAVA function for opening a pop-up window, came from a page at sitepoint.com. It does some clever tricks which are explained really well on their site. I added the three lines which centre the new window on the screen. Previous to this I had been using alternative code from this page at www.htmlcodetutorial.com. Check the link out, there is a fantastic Under The Hood link there also which explains the JAVA code line-by-line. Unfortunately this function stopped working properly - it either opened my mail-form in the same window or a new tab - so I replaced it with the one above.

The next task was to design the form itself. Forms are pretty straightforward in XHTML, a good explanation can be found at w3schools.com. Here is the code for the form from mailform.php:

<form id="thisform" method="post" action="sendmail.php">
<div class="bluetext" style="position:fixed; top:1%; bottom:1%; left:1%; background:#ebf5fc; right:1%; " >
 <fieldset>
  <legend style="color:black; ">  Send an email to Rich's Web Archive: </legend>
  Your Name:<br />
  <input type="text" name="name" size="20" tabindex="1" /><br />
  Your E-mail Address:<br />
  <input type="text" name="address" size="40" tabindex="2" /><br />
  <input type="hidden" name="subject" size="60" readonly />
  <script type="text/javascript" language="JavaScript">
   <!--
   // set subject to shortened url of referring page
   var refpage = new String(document.referrer.replace( "http://www.richswebarchive.com", "RWA"));
   document.forms['thisform'].elements['subject'].value = refpage;
  //--<
  </script>
  Subject:
  <script type="text/javascript" language="JavaScript" >
   <!--
   document.write(document.forms['thisform'].elements['subject'].value);
  //--<
  </script>
  <br />
  <input type="text" name="subjectUser" size="60" tabindex="3" /><br />
  Message:<br />
  <textarea name="message" cols="70" rows="5" wrap="soft" maxlength="500" tabindex="4" /></textarea><br />
  <p>Your message can include <code>html</code></p>
  <?php // set up CAPTCHA box
   require_once('recaptchalib.php');
   $publickey = "6LcldMASAAAAAJhgijHTLH-0JWhliBd_G6KdmCIQ";
   echo recaptcha_get_html($publickey);
  ?>
  <br/>
  <input type="submit" value="Send">
  <input type="reset" value="Reset">
 </fieldset>
</div>
</form>
<script type="text/javascript" language="JavaScript">
 <!--
 // set focus to first field 
 document.forms['thisform'].elements['name'].focus(); 
//-->
</script>

I'm not going to go into explaining about the form elements as others do it much better elsewhere. It's a simple form with 4 visible fields and 1 hidden field for passing the referring page's url.

The first thing of note then is the two lines of JAVA that deal with the url:

var refpage = new String(document.referrer.replace( "http://www.richswebarchive.com", "RWA"));
document.forms['thisform'].elements['subject'].value = refpage;

The first line creates a new var of type String called refpage with the referring page's url, stripped of the string http://www.richswebarchive.com which is replaced with RWA. The second line then puts refpage into the subject element of the form, which is hidden as a field on the form, although it is displayed after Subject: on the mail-form, above the subjectUser field. The subject and subjectUser fields will be combined into one in the sendmail.php page.

This is a neat feature of the mail-form as it means I'll always know what page a user was looking at when they felt motivated to send me a message.

The next thing to mention is setting up the CAPTCHA box on the form. You have to sign up with a CAPTCHA service first and get hold of the two keys, one public one private, which make the whole system work. The instructions given and the bit of code they send you are simple and easy to understand. The following PHP code is inserted at the bottom of your form, just before the submit button:

<?php // set up CAPTCHA box
 require_once('recaptchalib.php');
 $publickey = "6LcldMASAAAAAJhgijHTLH-0JWhliBd_G6KdmCIQ";
 echo recaptcha_get_html($publickey);
?>

All you have to do is edit in your own public key and that's it for this page. The verification of the input takes place in the sendmail.php page.

One final thing to note is the JAVA line at the end of the body section which sets the focus to the name field:

document.forms['thisform'].elements['name'].focus(); 

So that's it, the mail-form is set up, we're about half way there. Now it's time to look at the Mail Validation & Sending page to get the rest of the story.


Once again, all the preceding text is from the webpage www.RichsWebArchive.com/aboutthissite/popupmailform/index.php and it reads as though you are viewing the actual page:

Thursday, 13 January 2011

Forms and Sending Mail

Wow, turns out the whole mail form issue was a a fair bit more complex than I'd thought. A day in though and I think I've cracked it.

Lots of PHP, a bit of JAVA and a couple of new pages on the site.

I had to trawl round a whole load of different sites and tutorials to work out everything I needed to get it right. Definitely the leader of the pack is this page at TheSiteWizard.com. It's a great introduction into PHP programming and the subsequent two tutorials help you tidy things up and start protecting yourself from the spammers. Thanks very much to their author Christopher Heng.

There were a whole load of extra issues to sort out - stopping email injection attacks, validating the user input and a bunch of formatting things.

I'll write the whole lot up properly tomorrow.

Wednesday, 12 January 2011

Forms

OK, so next on the learning treadmill is forms.

I want to create a simple pop-up form to replace the current slightly clunky contact links. I've had a look at a few, supposedly simple, downloadable versions of code to do this and they seem remarkably complex. It has highlighted a few security issues though. The main one obviously is to hide my email address from the spambots.

There's also going to be some fun learning the JAVA to validate the form input.

Tuesday, 11 January 2011

Using JAVA To Resize Elements

I noticed a cool feature on a Google page while I was getting the custom search going. You can click on the divider between the left-hand bar and the main contents and it hides the left-hand bar. So I thought I'd try and get something similar going on my site.

I looked at the code on the Google page for a while but found it totally impenetrable. So I did a bit of searching around and decided that using some JAVA was the way to go. I found this page at w3scools.com. This is a fantastic site with clearly explained simple examples that you can run with quickly.

Rather than try and implement the ideas on my site straight away I though it best to try some sample bits of code to test the concepts needed.

The first of these is called test.htm. It's pretty simple - all it does is use 1 JAVA function to resize a box on the screen.

The second one is called test2.htm. This does quite a bit more. This has 4 JAVA functions. I have to admit I don't really understand the purpose of the getItem function but I left it in there as it's called by the second function toggleItem, which toggles the display status of box1 on and off.

There are two buttons on the screen, used to call the last two JAVA functions, which toggle the display status of box1 and re-size box2.

It didn't take to long to work it all out thanks to the helpful advice from w3scools.com. Now I need to implement the same ideas on my site.

Monday, 10 January 2011

Google Custom Search 1

Today I've been trying to set up a Google custom search on the site. Sounds simple doesn't it. It wasn't.

Actually setting up the custom search at Google was pretty straightforward. Integrating it into my site and getting the results to show up how I wanted them in a custom results page was not.

I've just about managed to get the search box how I want it in my title bar by cribbing various bits of other peoples code. I also have a results page. Now I need to edit this so that it sits with the rest of the site properly - tomorrow morning's first task.

The main thanks should go to Google employee Jeff S. His response to a query on a Google group 'Google AJAX Search APIs', item 4 on the page, is what finally made it all fall into place. Thanks Jeff.

His solution uses quite a bit of JAVA, which as yet I don't fully understand. But who cares, it works.