Kristian Lunde

www.klunde.net

Archive for the ‘Programming’ Category

Coding standard, coding style

without comments

In Orange Bus we have been looking at our coding style lately. We have created our very own coding standard. Since we base most of our applications on the drupal we chose to use the drupal coding standard as our main source of inspiration.
During our process of creating this coding standard we found a few good links I thought we should share.

Mike @ Orange Bus found these two articles about beautiful and practical code, both these are a must read:

http://www.wilshipley.com/blog/2007/05/pimp-my-code-part-14-be-inflexible.html

http://www.perforce.com/perforce/papers/prettycode.html

Another blog post about line density worth reading is:

http://paul-m-jones.com/?p=276

Written by Kristian Lunde

November 11th, 2008 at 12:53 am

Posted in Drupal, PHP, Programming

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

Posted in Drupal, Programming, web development

Tagged with ,

The View Helper pattern

without 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

Writing SOA applications with PHP

without comments

Lately I’ve been working a lot with data integration between several web applications, and a natural choice for the integration was to use a Service Oriented Architecture (SOA). I’ve built both SOA servers and clients before using the SOAP approach, which is a superb way of transferring data when not knowing who the user of the service is, or when you are a client of such a service. However in this setting I knew who the user was, I knew what the service would be used for, also had the chance to write both the client and server.

The choice fell on a simple implementation using the JSON (JavaScript Object Notation) data structure. This is really easy using the built in json library in php. The server use the json_encode() function and the implemented sub class of the client use the json_decode() function.

To simplify this further I implemented two abstract classes, a ServiceServer class and a ServiceClient class. The service server class contained a very simple displayJSONResult function, which sets the correct header, encode the data as json data and echo the data.

The service client class has two main functions, doGetRequest and doPostRequest, both functions use the cURL library in PHP.

Server

  1. <?php
  2.  
  3. abstract class ServiceServer
  4. {
  5.  
  6.  public function __construct(){}
  7.  
  8.  protected function displayJSONResult($data)
  9.  {
  10.   header('Content-type: text/plain');
  11.  
  12.   echo json_encode($data);
  13.  
  14.   exit();
  15.  }
  16. }

Client

  1. <?php
  2.  
  3. /**
  4.  * ServiceClient
  5.  *
  6.  *
  7.  * @author Kristian Lunde
  8.  *
  9.  */
  10.  
  11. class ServiceClient
  12. {
  13.  
  14.  public function __construct(){}
  15.  
  16.  /**
  17.   * do a post request to a service
  18.   *
  19.   * the params parameter must be a string with the format:
  20.   * key=val&key2=val2&key3=val3
  21.   *
  22.   * @param string $url
  23.   * @param string $params
  24.   */
  25.  protected function doPostRequest($url, $params)
  26.  {
  27.   $ch = curl_init($url);  
  28.   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
  29.   curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
  30.   curl_setopt($ch, CURLOPT_POST   , 1);
  31.    curl_setopt($ch, CURLOPT_POSTFIELDS     , $params);
  32.   $result = curl_exec($ch);
  33.   curl_close($ch);
  34.   return $result;
  35.  }
  36.  
  37.  /**
  38.   * do a get request to a service
  39.   *
  40.   * @param string $url
  41.   *
  42.   * @return mixed
  43.   */
  44.  protected function doGetRequest($url)
  45.  {
  46.   $ch = curl_init($url);  
  47.   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER , false);
  48.   curl_setopt($ch, CURLOPT_RETURNTRANSFER , true);
  49.   $result = curl_exec($ch);
  50.   curl_close($ch);
  51.   return $result;
  52.  }
  53.  
  54. }

Example

To illustrate the easiness and simplicity of this SOA approach I written a small example. In this example the server finds the country of a city using POST parameters or it can find cities using the country as a GET parameter.

Example server

  1. <?php
  2.  
  3. /**
  4.  * Example of using the ServiceServer class
  5.  *
  6.  * Returns countries or cities
  7.  *
  8.  * @author Kristian Lunde
  9.  */
  10.  
  11. require_once('ServiceServer.php');
  12.  
  13. class ExampleServer extends ServiceServer
  14. {
  15.  
  16.  
  17.  
  18.  public function __construct()
  19.  {
  20.   $this->countries = array('norway'  => array('Oslo',
  21.               'Trondheim',
  22.               'Bergen',
  23.               'Halden',
  24.               'Sarpsborg',
  25.               'Hammerfest'),
  26.          'sweden' => array('Stockholm',
  27.               'Gothenburg',
  28.               'Karlstad'),
  29.          'england' => array('London',
  30.               'Newcastle',
  31.               'Bath',
  32.               'Liverpool'));  
  33.  
  34.  
  35.   if(isset($_GET['country']))
  36.   {
  37.    $this->findCitiesByCountry(trim($_GET['country']));
  38.   }
  39.  
  40.   if(isset($_POST['city']))
  41.   {
  42.    $this->findCountryByCity(trim($_GET['city']));
  43.   }
  44.  }
  45.  
  46.  public function findCitiesByCountry($country)
  47.  {
  48.   $cities = 'Not found';
  49.   $country = strtolower($country);
  50.  
  51.   if(isset($this->countries[$country]))
  52.   {
  53.    $cities = $this->countries[$country];
  54.   }
  55.  
  56.   $this->displayJSONResult($cities);
  57.  }
  58.  
  59.  public function findCountryByCity($city)
  60.  {
  61.   $country = 'Not found';
  62.  
  63.   $break = false;
  64.   foreach($this->countries as $key => $val)
  65.   {
  66.    for($i = 0, $count = count($val); $i < $count; $i++)
  67.    {
  68.     if($city == $val[$i])
  69.     {
  70.      $country = $key;
  71.      $break = true;
  72.      break;
  73.     }
  74.    }
  75.    
  76.    if($break)
  77.    {
  78.     break;
  79.    }
  80.   }
  81.  
  82.   $this->displayJSONResult($country);
  83.  }
  84. }
  85.  
  86. $obj = new ExampleServer();
  87. ?>

Example client

  1. <?php
  2. /**
  3.  * Example of using the ServiceClient class
  4.  *
  5.  * does a request to the ExampleServer
  6.  *
  7.  * @author Kristian Lunde
  8.  */
  9.  
  10. require_once('ServiceClient.php');
  11.  
  12. class ExampleClient extends ServiceClient
  13. {
  14.  public function __construct()
  15.  {
  16.   $this->getCities('Norway');
  17.   $this->getCounty('Bath');
  18.  }
  19.  
  20.  public function getCities($country)
  21.  {
  22.   $url = 'http://files.klunde.net/files.klunde.net/ExampleServer.php?country=' . $country;
  23.   echo $this->doGetRequest($url);
  24.  }
  25.  
  26.  public function getCountry($city)
  27.  {
  28.   $url = 'http://files.klunde.net/files.klunde.net/ExampleServer.php';
  29.   $params = 'city=' . $city;
  30.  
  31.   echo $this->doPostRequest($url, $params);
  32.  }
  33. }
  34. $obj = new ExampleClient();
  35. ?>

I’m quite satisfied with this implementation because it is so easy to maintain and even more important, implementing new services and clients for the services is straight forward and supports rapid development.

Download

ServiceServer.phps

ServiceClient.phps

ExampleServer.phps

ExampleClient.phps

Written by Kristian Lunde

June 8th, 2008 at 10:28 pm

Writing exceptions in PHP

without comments

Fredrik Johan Holmström has a entry on his blog about writing exceptions in PHP. He points out that several of the large PHP framework assumes that an exception is a fatal error, and that this may be a flaw in the design.

An Exception is not necessarily a fatal error and it should be the responsibility of the code that catches the exception to determine if it is a fatal error or not.

The blog entry got me thinking, and yes I’ve done that mistake a few times myself, I’ll do it right  the next time I write an exception in PHP,

URL: http://loveandtheft.org/2008/05/23/exceptions-youre-doing-it-wrong/

Written by Kristian Lunde

May 24th, 2008 at 11:48 pm

Micro languages

without comments

Mats posted an interesting article about micro languages,

http://e-mats.org/2008/05/the-power-of-micro-languages/

Written by Kristian Lunde

May 5th, 2008 at 10:27 pm

My first introduction to java and databases

with 2 comments

The other day I did a complete reconfiguration of java on my system. Tonight I started to play around with java and postgresql. I installed PostgreSQL 8.2 (yes I know 8.3 is out there), and downloaded the jdbc driver for PosgreSQL.

PostgreSQL

After installing PostgreSQL, you have to add a user to the authorization file pg_hba.conf located in /etc/postgresql/8.x/main on a ubuntu system, remember to restart the postgreSQL server after editing pg_hba.conf. When that is done add the same user to the postgreSQL server either by using postgreSQL’s createuser function or by logging into the postgreSQL server and doing a SQL CREATE USER, I did the latter one.

  1. CREATE USER kristian WITH PASSWORD 'xxxxxxxx' CREATEDB;

This enables me to do a regular access of the database with:

  1. kristian@Saturn:~$ psql -U kristian crawler
  2. Welcome to psql 8.2.7, the PostgreSQL interactive terminal.</code>
  3.  
  4. Type:  \copyright for distribution terms
  5. \h for help with SQL commands
  6. \? for help with psql commands
  7. \g or terminate with semicolon to execute query
  8. \q to quit
  9.  
  10. crawler=#

My table:

  1. crawler=# \d document;
  2. TABLE "public.document"
  3. COLUMN     |            Type             |                       Modifiers
  4. —————+—————————–+————————
  5. id            | integer                     | NOT NULL DEFAULT NEXTVAL('document_id_seq'::regclass)
  6. url           | text                        | NOT NULL
  7. document      | text                        | NOT NULL
  8. ts_downloaded | timestamp without time zone | DEFAULT now()

Data in the table:

  1. crawler=# select * from document;
  2. id |          url          | document |       ts_downloaded
  3. —-+———————–+———-+—————————-
  4. 1 | http://www.klunde.net | jalla    | 2008-04-19 21:11:11.805482

Java

First thing to get the postgreSQL jdbc driver to work is to add it to the java classpath, and of course copy the actual jar file to its correct location, for instance /usr/lib/jvm/java-6-sun-1.6.0.03/jre/ext/lib/which is my java library path.
My classpath:

  1. /usr/lib/jvm/java-6-sun-1.6.0.03/lib:/usr/lib/jvm/java-6-sun-1.6.0.03/jre/ext/lib/postgresql-8.3-603.jdbc4.jar:.

Now its about time to write some actual code:

  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement; </code>
  7.  
  8. public class DatabaseTest
  9. {
  10. private Connection connection = null;
  11.  
  12. private static final String USERNAME = "XXXXX";
  13. private static final String PASSWORD = "XXXXX";
  14. private static final String URL = "jdbc:postgresql:";
  15. private static final String DATABASE = "crawler";
  16.  
  17. public DatabaseTest()
  18. {
  19. try
  20. {
  21. connection = DriverManager.getConnection(URL + DATABASE, USERNAME, PASSWORD);
  22. ResultSet rs = doQuery("SELECT * FROM document");
  23.  
  24. rs.next();
  25. System.out.println(rs.getString(2));
  26. }
  27. catch (SQLException e)
  28. {
  29. System.out.println("Database Exception!");
  30. System.out.println(e.toString());
  31. e.printStackTrace();
  32. }
  33.  
  34. }
  35.  
  36. public ResultSet doQuery(String sql)
  37. {
  38. ResultSet rs;
  39. try
  40. {
  41. Statement stmt = connection.createStatement();
  42. rs = stmt.executeQuery(sql);
  43. return rs;
  44. }
  45. catch (SQLException e) {
  46. e.printStackTrace();
  47. return null;
  48. }
  49. }
  50. }

Trying to execute my script:

  1. kristian@Saturn:~/workspace/crawler$  javac DatabaseTest.java
  2. kristian@Saturn:~/workspace/crawler$  java -Djdbc.drivers=org.postgresql.Driver DatabaseTest
  3. http://www.klunde.net

It works :D The installation and initial setup went pretty much by the book, but as a PHP developer I must say that I’m a little bit disappointed, JDBC cannot compare itself to the PHP PDO extension yet. But then again, maybe I just need to get to know the JDBC library better. Anyhow it was fun writing this little java app and refreshing some of my java skills.

Written by Kristian Lunde

May 5th, 2008 at 10:14 pm

Posted in Java, Linux, PostgreSQL, Programming

Tagged with , ,

Java on Ubuntu

without comments

The other day I decided that it was about time to refresh my java knowledge. I’ve done some java development at work lately, but besides that It has been about 3 years since I last wrote any decent java apps. I have a few ideas of some small cool apps I want to write, but first of all I had to check the java installation on my machine.

Im currently sitting on a Ubuntu 7.04 installation, so I started out by opening my console and typing

java -version

I was a bit surprised about the result, java version could not be determined, I found out that 4 different versions of java were installed and neither the classpath or java_home were set. The java version I wished to used were not among the installed versions. I used the java installation guide on help.ubuntu.com to install my preferred java version, the java 6 version from Sun. The guide was straight forward and the java installation seemed to work as expected after completing the guide.


kristian@Saturn:/usr/lib$ java -version
java version "1.6.0_03"
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Client VM (build 1.6.0_03-b05, mixed mode, sharing)

Looking good. So I tried typing:


kristian@Saturn:/usr/lib$ javac -version
javac: error while loading shared libraries: libjli.so: cannot open shared object file: No such file or directory

Not looking that good, something was wrong :P I googled the result and found my mistake. Earlier while I was trying to get it all together with the 4 different java versions I changed the symlink in /usr/bin/ and I forgot to add the -s when I created the link. Removing the symblink and recreating it did the trick.


kristian@Saturn:/usr/bin$ sudo ln -s /etc/alternatives/javac javac

The javac in /etc/alternatives is a symblink to the current java version. And trying the all famous javac -version now result in the anticipated result:


kristian@Saturn:~$ javac -version
javac 1.6.0_03

Now I’m all set to go and try out my java skills :P

Written by Kristian Lunde

May 2nd, 2008 at 10:04 am

Posted in Java, Linux, Programming

Tagged with ,