Kristian Lunde

www.klunde.net

Archive for the ‘web’ Category

Javascript snippets

with one comment

Lately I have been doing some javascript development and I have written a couple of functions which I find really useful. I almost find the code snippets to be used on all sites I work on so I thought I would share them with you. Both the snippets are written using the jQuery library.

Opening urls in a separate window/tab in a xhtml strict environment

The target attribute is not a valid attribute in xhtml strict and your site will fail to validate if you use it, so to get around this you can use replace your target attribute with the rel attribute. Adding the rel=”external” attribute on your anchors that points to an external source and adding some javascript solves the problem.

  1. <a href="http://www.klunde.net" rel="external" title="Klunde.net">Kristian Lunde</a>
  1. function externalLinks() {
  2.         $("a[rel='external']").each(function() {
  3.   $(this).attr('target', '_blank');
  4.         });
  5. };

The code here is pretty self explaining, but to describe it briefly, the javascript function must be invoked once the DOM is loaded (see code further down on the page). The function loops through all anchors that have the rel=”external” attribute and add the attribute target=”_blank”. I guess this is a bit of a hack, but it works and it keeps the clients happy ;)

Creating spam proof mailto: anchors

It is a well known fact that if you add your email address on a site in a plain mailto anchor you will be flooded by spam after a while. You can easily avoid this by adding a little bit of javascript on your site.

It works simply by printing out the email address as plain text replacing the @ with a ” AT ” and add the email addresses in a div or which ever element you prefer and add a set class to that tag. Then you run a small snippet of javascript that find all the elements with that class, I have chosen the class name “email”. The script replaces the content in all the elements with the email class with the proper html anchor. This can not be picked up by web crawlers and it displays the links properly for the user. All browsers without javascript support / enabled will of course only see the post AT somesite.com.

  1. <div class="email">post AT  somesite.com</div>
  1. function createMailTo() {
  2.         var c_email_field = $('.email');
  3.  if($(c_email_field).length > 0) {
  4.   $(c_email_field).each(function()
  5.   {
  6.    var email = $(this).html().replace(' AT ', '@');
  7.    $(this).html('<a href="mailto:' + email + '" rel="nofollow" title="' + email + '">' + email + '</a>');
  8.   });
  9.  };
  10. };

Running this script would transform the code into:

  1. <a href="mailto:post@somesite.com" rel="nofollow" title="post@somesite.com">post@somesite.com</a>

Putting it all together

I have but together a simple example to illustrate the functions in action with all code and functionality. You should be able to copy this code save it as a .html file and run it in your browser.

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html>
  3. <head>
  4.   <title>Javascript snippets</title>
  5. </head>
  6. <body>
  7.  
  8. <a href="http://www.klunde.net" rel="external" title="Klunde.net">Kristian Lunde</a>
  9. <div class="email">post AT somesite.com</div>
  10.  
  11. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  12. <script type="text/javascript">
  13.  
  14. function externalLinks() {
  15.         $("a[rel='external']").each(function() {
  16.   $(this).attr('target', '_blank');
  17.         });
  18. };
  19.  
  20. function createMailTo() {
  21.         var c_email_field = $('.email');
  22.  if($(c_email_field).length > 0) {
  23.   $(c_email_field).each(function()
  24.   {
  25.    var email = $(this).html().replace(' AT ', '@');
  26.    $(this).html('<a href="mailto:' + email + '" rel="nofollow" title="' + email + '">' + email + '</a>');
  27.   });
  28.  };
  29. };
  30.  
  31. $(function() {
  32.         externalLinks();
  33.         createMailTo();
  34. });
  35. </script>
  36. </body>
  37. </html>

Written by Kristian Lunde

June 18th, 2009 at 10:55 pm

Posted in web,web development

Tagged with , ,

On the move

without comments

I am currently switching both domain host and web host, and in that case this site might be down for a little while. I am about to replicate the site to my new web host so hopefully it will be a minimum of down time.

I have chosen to leave servetheworld.net which has been my web host since 2003, they have done a great job, but the time has now come to move to a web host which can provide me with some more advanced features.

I have chosen webfaction.com as my new web host. I chose them because they offer a multitude of different applications, for instance svn, python, ruby on rails and of course PHP. They also offer ssh access.

I chose 123-reg.com to host my domain names, that was done out of convenience, they are well known, large and hopefully know what they are doing :P

Written by Kristian Lunde

June 3rd, 2009 at 8:00 pm

Posted in Misc,web

Tagged with , ,

Getting the default option of a ubercart product attribute

with 2 comments

In Orange Bus we are currently busy building a new web shop for a clothing company. We are building this web shop on Drupal 6 and Ubercart 2. While I was doing some tuning of the product page (built as a node template) on this site I suddenly realized that even though you can get most of the information needed in from the $node object, you are unable to get the default options of each attribute.

In my case this attribute was the sizes of the products (small, medium, large and so on), the node object contained all the attributes but not the default options. It is not at all complicated to get this information but you do need to add some custom code to get a hold of the default options. I would argue that this should be included in the default node object, which really should not be a big deal adding. I guess I should add a patch for this, instead of going around the problem which is what I do and describe here.

To get a hold of this I had to call a ubercart specific function called uc_product_get_attributes function. This function takes a node id as parameter and return all an array of all the attributes related to the node. The array contain a set of attributes objects and these object contain all the information available on each attribute.

My solution was to call the uc_product_get_attributes function and get the default_option variable from the attribute object, see code example below.

  1. //get all attributes related to the node
  2. $attributes = uc_product_get_attributes($node->nid);
  3.  
  4. //get the id of default size of the product
  5. $default_size = $attributes[1]->default_option;

It is simple, but it took me about an 30 minutes to determine the problem and adding a solution. Hopefully this will save someone the job of solving the same problem.

Written by Kristian Lunde

February 20th, 2009 at 10:02 pm

Posted in Drupal,PHP,Programming,web

Tagged with ,

Flowplayer, https and the streamnotfound “problem”

with 4 comments

Lately I have been working on a project which used Amazon S3 to provide videos to Flowplayer on a website. This was working superbly until we added a link to a video using the https protocol. This broke the Flowplayer on Internet explorer 6 and 7 and Safari, and we got a:

  1. streamNotFound, clip: 'https://someurl'

Solution: Amazon S3 supports both http and https, so replacing https with http solved the problem. This problem probably occurs because the web browser is unable to cache the data from the https url and therefore the Flowplayer is unable to play the video.

Interestingly enough Firefox had no problem at all running Flowplayer and https urls.

Written by Kristian Lunde

January 16th, 2009 at 4:25 pm

Posted in web,web development

Tagged with ,

All frameworks sucks…. ?

without comments

I’ve been hearing this a lot lately, that most framework sucks, well do they?

Mr. Paul M. Jones has a really good article about the subject, he says that when a developer has to do a major change in his mindset and development routines to get used to a new framework, the developer often think that the “framework sucks”.

Personally I’ve been the kind of developer who like to write my own frameworks from scratch, and yes that also mean that I’ve written a couple of frameworks for myself, and threw them away. Since I like to write things from the scratch I’ve also been a bit critical to other frameworks,and I do understand term “all frameworks sucks”. When you’ve written your own framework, you know how it works, and it works just the way you want it to, at least that was the goal of writing it in the first place. It also gives you the possibility to change or add functionality in the core of the framework rather easily.

The advantages with a “off the shelf” framework can sometimes be intriguing, with a little bit of effort you can become darn efficent with this kind of framework, that will of course require a bit from the developer to learn the framework. Another bonus about learning a new framework is that you pick up on some of the bright ideas the developers have implemented in their framework.

I do not think that all frameworks sucks but, there are some frameworks out there that do not match my mindset at all, there is no secret that I’m not a huge fan of large enterprise frameworks with a wide extent of xml files and structures (I’m not naming any names, but the Java world have a few of these). Why on earth would you need to define a new page in three different xml files to get it working?

I’ve heard a lot about Code Ignitor and it sounds like a promising framework, I have not had the time to have a look at it yet. I am familiar with the Zend framework and EZ components which probably are more of a set of building bricks than frameworks, both of these are quite good and comfortable to work with.

Recently I’ve started to look at the Drupal. I realize that Drupal is more of a content management system than a framework, but it has its similarities to a framework. So far I still think Drupal “sucks” ;) but I do however like the simplicity of writing modules. What I do not like at all is the “lack” of OOP, and yes I know Drupal have its own way of implementing OOP, but I still feels thats is a little bit awkward, I am a bit of a OOP junkie :P
Anyway I see the potential of Drupal and look forward to getting to know it better. I believe I eventually will like Drupal because it is easy to extend, you get a lot of stuff for free because someone has already written it for you and it is a big community around it with a lot of smart developers. There is probably a reason why Drupal is one of the largest PHP framework out there.

Written by Kristian Lunde

October 25th, 2008 at 12:40 am

Orange Bus wallpaper

without comments

Orange bus wallpaper

Torunn in Orange Bus submitted a wallpaper for Smashing Magazines October wallpaper download, and it got in :) Congratulations Torunn and Orange Bus, and good work Torunn :)

Guess what wallpaper I’ve got on my computer this month? :P

Written by Kristian Lunde

October 4th, 2008 at 1:06 pm

Posted in Misc,web design

Tagged with

Templating with Eclipse

without comments

Today I came over a a post on dzone.com about Eclipse and templating. It turns out that you can write small templates of code snippets you use a lot and bind them to a keyword. When typing the keyword, press “ctrl” and “space” and a list of possible templates available will appear, select the prefered template, press “enter” and the code snippet is inserted into your working code. I works just the same way code completion. This actually means that you do not have to write the boring “for” loops or “if” tests anymore, just write a template and become a more efficient developer.

The original post explains how to set up templates, so I will not go into that in this post, but since I am primarily a PHP developer and the post describes templating for Java, I’ll just give a description of where to go if you use the PHPEclipse.
To edit and create templates for PHP, HTML or css, even javascript you have to use this path:

window -> preferences -> PHPeclipse Web Development -> PHP -> Templates.

To write and edit the templates, just follow the guidelines from Mr. Graversen, or have a look at the links below.

For further reading have a look these sites.

I guess if I had read the PHPEclipse manual when I first started using Eclipse, I would probably been using it from the start :P

Good luck with your Eclipse templates, I know I will be using them extensively.

Written by Kristian Lunde

August 20th, 2008 at 10:18 pm

The View Helper pattern

with 4 comments

Developing MVC (Model View Controller pattern) applications in PHP or any other language often require a lot from the view tier. The view needs to process data received from the model tier and form it into presentable data, it also has to manage user input and form that into data understandable for the model tier.
This might not be a big issue while working with small application, but when it comes to midscale and large applications the view helper pattern can be of great help. The view helper pattern is one of the J2EE core patterns and the documentation can be found on:

http://java.sun.com/blueprints/corej2eepatterns/Patterns/ViewHelper.html

What does the helper pattern do?
First of all the helper pattern adds an extra tier to the system, this tier can be seen as a mid tier which has some understanding of the logic of the system, it knows a little bit about the view and a little bit about the model. Another cool thing is that the view helper pattern makes your code more reusable. When moving complex structures from the view and into a view helper it can with ease be used by other views.

Example:

You are writing a web application where the user writes a review of some product, the application should do auto saving of the user input every 20 second using Ajax functionality. The application should of course also save the user input then the user submits the data. The ajax request and the user submit does almost the same thing but the when the user submits the data the view should also store a rating of the product. This require the ajax request and the user submit to be two different views, or one complex view.

In an ordinary MVC system you would have to implement two views with very much of the similar behavior or one complex view. Using the view helper pattern you extract the storage of the user review in a helper which can be reused by both the ajax request view and the user submit view.

I have written a very simple implementation of the example in PHP. The implementation is not complete at all, but it is meant as a proof of concept that the reusability of code in your application can increase using the view helper pattern.

  1. <?php
  2.  
  3. class ProductReviewHelper
  4. {
  5.  public function __construct(){}
  6.  
  7.  /**
  8.    * save the review
  9.   **/
  10.  public function save($user_input)
  11.  {
  12.   //validate input
  13.   $input = $this->validate($user_input);
  14.  
  15.   //saves the review and return the result of the save
  16.   return $review_manager->save($input['product_id'], $input['review']);
  17.  }
  18.  
  19.  /**
  20.   * validate the input
  21.   **/
  22.  public function validate($user_input)
  23.  {
  24.   $filter_args = array('product_id' => FILTER_VALIDATE_INT,
  25.          'review'   => FILTER_SANITIZE_STRING);
  26.   $input = filter_var_array($user_input, $filter_args);
  27.  
  28.   //do validation
  29.   return $input;
  30.  }
  31. }
  1. <?php
  2.  
  3. //Ajax view
  4. $review_helper = new ProductReviewHelper();
  5. $result = $review_helper->save($_POST);
  6. echo $result;
  7. exit();
  8. ?>
  1. <?php
  2.  
  3. //User submit view
  4. $review_helper = new ProductReviewHelper();
  5. $review_result = $review_helper->save($_POST);
  6.  
  7. $rating_helper = new ProductRatingHelper();
  8. $rating_result = $rating_helper->save($_POST);
  9.  
  10. //manage the result from the helpers
  11. ?>

I am sure that the view helper pattern has helped me to write better and more organized code, which is easily understandable and very reusable.

If you do not use the view helper pattern, and still have solved the problem with reusability of code in the view tier please feel free to leave me a comment describing your solution.

Written by Kristian Lunde

July 20th, 2008 at 11:11 pm

Unsecure password practices

without comments

Dansnetwork has a short an simple article explaining the simplest way of securing user passwords on the web. If you are new to authorization on the web, this article will give you a quick introduction to hashing methods and what not to do when dealing with authorization information.

URL: http://blog.dansnetwork.com/2008/07/15/unsafe-password-storage-practices/

Still this article is a bit to basic, since it does not discuss rainbow table attacks, which could with ease break most of the passwords. My previous article discuss how to avoid rainbow table attacks.

Written by Kristian Lunde

July 18th, 2008 at 9:37 am

Password encryption using PHP

without comments

A recent post on dzone.com linked to a article about “password encryption using PHP” written by Stefan Ashwell on total.php.com. In this article he illustrate a how to save user passwords and authenticating users using the sha1 hashing algorithm.

First of all lets all agree that hashing passwords are basics requirements for a secure web application, but is a simple hashing of the password enough? I do not think so.

Here is the scenario, Someone breaks into your system (not through the web application, but for instance through an ssh connection), they get access to your user database or file where you store user account information.  The intruder is now in possession of the password and user name of all your users, but still the passwords are hashed with md5, sha1 or an similar hashing method. If the intruder is determined to get into your system and mess up, he may now try to decrypt the passwords using a  dictionary word file and brute force (also known as rainbow tables). This method is quite common and is not advanced at all, all it does is looping through the dictionary file, which contains all words and common password phrases, do a md5 or sha1 hashing of these words and see if it matches up to the hashed password, if it does it has found a match, and the intruder is able to log into the account.

Even though this brute force method might take some time, he will eventually get the passwords and get full access to the users account. There are however methods to complicate this and even make it impossible for the intruder to get the password using brute force method and that is called salting your password.

Example:

  1.  
  2. $salt = '2glkpe895';
  3. $password = $_POST['password'];
  4.  
  5. $encrypted_password = sha1($salt . $password . $salt);

As you can see the salt is an secret string which is only used by your application, it is prepended and appended to the password. You could of course also go the extra mile and split the password in two and add the salt in the middle of the password, but there might not be any point in doing that.

This makes the word not like any word you will find in an dictionary and therefore the brute force method will not find the password.

The point is that if the intruder get a partial access to some of your system, for instance the user database, it will not be enough to get access to the total system because the security system is layered, one layer in your code, and one layer in your user database.

I do not say that this method is a 100 percent secure but it is is way more secure than not using a salted password.

Written by Kristian Lunde

July 10th, 2008 at 10:28 am

Get Adobe Flash player