Christer’s blog o’ fun

July 3, 2008

A bit late

Filed under: Personal — Tags: , — christer @ 4:20 pm

I’m a bit late with the second part of the PHP_CodeSniffer series. I have had lots of stuff to do at work and at home this week, so I’ll hopefully get to finish the post this week. The fact that the weather keeps getting warmer (which also makes the beer seem colder) may also be a part of the problem…

Cheers!

June 30, 2008

AOTW 27, 2008: Bert Jansch - The Black Swan

Filed under: AOTW, Music — Tags: , , , — christer @ 8:00 am

This week I have chosen the latest album from the great Scottish folk musician (Her)bert Jansch. Some of you might know him from the band Pentangle, which he was a founding member of.

The Black Swan is not his best album IMO, but I have listened to it quite a lot the last months. This album has a tendency to bring back some good memories for me and since the last couple of months have not been too great in my personal life I have listened to it more than usual.

My three favorite songs are:

  • Hey Pretty Girl
  • High Days
  • Watch the Stars

“Watch the Stars” is also featured on Pentangles Sweet Child album from ‘68. The Black Swan version of this song features Beth Orton on vocals together with Jansch. She also sings on some of the other tracks on The Black Swan album.

Expect more from Jansch on my AOTW series!

June 28, 2008

Zend_Service_ReCaptcha in the standard incubator

Filed under: PHP, Technology — Tags: , , , , — christer @ 11:24 am

I imported the Zend_Service_ReCaptcha stuff to the Zend Framework standard incubator yesterday. You can access it from the subversion repository at http://framework.zend.com/svn/framework/standard/incubator/library/Zend/Service/.

The component also includes a class to use the mail hide feature over at recaptcha.net that allows you to render an email address as something like user…@foo.com and the reader has to solve a recaptcha to see the complete email address.

No documentation has been made yet but I will include some basic usage of the component in this post.

Display a ReCaptcha in a form

First you need to register at recaptcha.net to get a set of public/private keys for the domain you want to use the recaptcha on. If you develop something locally and you use localhost as hostname you will need to register localhost on the recaptcha site to get the keys. Once you have the keys you are good to go!

When displaying the captcha you will only need the public key. The private key will be used when you verify the user input to see if a user has solved the captcha or not.


<?php
/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha.php';

$publicKey = 'my public key from recaptcha.net';
$reCaptcha = new Zend_Service_ReCaptcha($publicKey);
?>

<html>
    <head>
        <title>ReCaptcha test</title>
    </head>
    <body>
        <form action="" method="post">
            <?= $reCaptcha ?>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

Replace the public key with your own public key and you will see something that hopefully resembles this screenshot:

Zend_Service_ReCaptcha

Verify the user input

Now that we have our recaptcha in place we need to verify the user input. To do that we have to expand the block of php code at the top of our example here a bit.

PS! The syntax highlight plugin manages to write !emptyempty in the code below, so you’ll need to fix that if you copy the code.


<?php
/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha.php';

$publicKey = 'my public key from recaptcha.net';
$reCaptcha = new Zend_Service_ReCaptcha($publicKey);

// See if the form has been posted and that the two fields from the
// recaptcha are not empty
if (isset($_POST['submit']) &&
    !empty($_POST['recaptcha_challenge_field']) &&
    !empty($_POST['recaptcha_response_field']) ) {
    // Set the private key. We need this to verify user input
    $privateKey = 'my private key';
    $reCaptcha->setPrivateKey($privateKey);

    // See if the input is valid
    $response = $reCaptcha->verify($_POST['recaptcha_challenge_field'],
                                   $_POST['recaptcha_response_field']);

    if (!$response->isValid()) {
        // Not valid. Add the error message from the recaptcha web service
        // to the recaptcha object so it will be shown in the recaptcha
        $reCaptcha->setParam('error', $response->getErrorCode());
    } else {
        // Success! The recaptcha has been solved
    }
}
?>

<html>
    <head>
        <title>ReCaptcha test</title>
    </head>
    <body>
        <form action="" method="post">
            <?= $reCaptcha ?>
            <input type="submit" name="submit" value="Submit" />
        </form>
    </body>
</html>

And thats it!

Hide email addresses with Zend_Service_ReCaptcha_MailHide

If you need to display an email address you can hide parts of it using the Zend_Service_ReCaptcha_MailHide component. You need a separate pair of public/private keys for this so head over to recaptcha.net and grab those keys.

Lets say we want to hide mynewemailaddress@domain.com. Do something like the following piece of code:


/** @see Zend_Service_ReCaptcha */
require_once 'Zend/Service/ReCaptcha/MailHide.php';

$publicKey = 'my public key';
$privateKey = 'my super duper private key';

$mailHide = new Zend_Service_ReCaptcha_MailHide($publicKey,
                                                $privateKey,
                                                'mynewemailaddress@domain.com');

print($mailHide);

The output of this will be myne…@domain.com except that the “…” part will have link to a JavaScript popup that displays a recaptcha, and once the user solves it, the complete email address will be displayed.

So … feel free to play around with the component and if you find some errors or feel that something is missing, let me know! I will add some more stuff about custom themes the next couple of days and maybe make a Zend Framework theme for the recaptcha.

June 27, 2008

More HDR madness

Filed under: Photography — Tags: , — christer @ 7:39 pm

Stumbled over a couple of blog posts with lots of cool HDR pictures:

  1. 20 beautiful hdr pictures
  2. 20 beautiful hdr pictures part 2
  3. 20 beautiful hdr pictures part 3

I still haven’t been able to try out some HDR stuff though, but when I get some more time on my hands I’ll give it a shot!

June 26, 2008

And the new CEO of VG Multimedia is…

Filed under: Work related — Tags: , , — christer @ 11:20 pm

…not me, that’s for sure! My employer, VG Multimedia, announced the new CEO today, and it’s none other than Jo Christian Oterhals! Congratulations oter!

June 25, 2008

Enforcing a PHP coding standard using PHP_CodeSniffer - Part 1

Filed under: PHP, Technology — Tags: , , , , , , — christer @ 9:45 pm

This is the first part of a rather exciting trilogy (a thriller if you may) on how to use the PHP_CodeSniffer component from the PEAR repository to force developers to follow a set of coding standards before allowing them to commit code to a Subversion repository. This can also be accomplished using other Version Control Systems (VCS’s) but I will focus on Subversion. In this part of the trilogy I will explain the importance of having a coding standard, and I will give you a short introduction on how the PHP_CodeSniffer component works and some basic usage of it.

Let’s get on with the show!

When working together with other developers it’s important to agree on some sort of coding standard (not only in PHP). Why is this important you say? You don’t always get to play with stuff you have written yourself. Whenever you are to debug code that someone else wrote, wouldn’t it be great to know that he/she writes code that at least looks like your own?

Using a coding standard doesn’t force developers to solve problems the exact same way, but it might make the solution easier to read for other developers. It might also help developers from doing some pretty nasty errors. Let’s say you have the following piece of code:


if (isset($_COOKIE['userId']) && isset($_COOKIE['userSecret'])) {
    $actualUserSecret = fetchUserSecretCode($_COOKIE['userId']);

    if ($actualUserSecret = $_COOKIE['userSecret']) {
        // ok … the secret code in the cookie is the same as the one
        // returned from the fetchUserSecretCode function. Let's login
        // the user

        // …
    }
}

Now … the code above is all valid, but it contains a pretty nasty bug. The line that says:


if ($actualUserSecret = $_COOKIE['userSecret']) {

is missing an equal sign, so it will always evaluate to true, which in this case will log in the user with the user id from the cookie. If you want to log in as other users you could just change the user id in the cookie, and make a new request, and voila!

This bug is pretty hard to identify since the developer who wrote it probably just didn’t press the equal sign hard enough the second time and the code produced it still valid. The developer “knows” that the error has to be somewhere else and doesn’t even look in the right place. Some of you reading this is probably saying something like: “Come on, nobody will ever manage to do something that stupid!?”. The reason I chose this as an example is because yours truly exploited this “bug” in someone’s code once, so yeah … it’s possible to write something like the example above.

Another issue is when users start to mix up tabs and spaces for indentation and have different editor settings. If you open up a script that has both tabs and spaces used for indentation and your editor has a different tab width than the one who used spaces as indentation all hell breaks loose. Suddenly you won’t even get to order breakfast from your favorite Whammy Burger because you had to spend five extra minutes removing someone’s tabs and, well, we all know what happens next…

What has this got to do with a coding standard? What if the coding standard you were said to follow specified that doing assignments inside an if-test was illegal or that the use of tabs as indentation (or tabs in your code at all) were strictly forbidden? Wouldn’t that fix this issue? That depends on how you deploy the code you are writing. To be able to enforce a standard you need to attach a check that finds out if the code you are sharing with other developers adheres to some standard. Subversion (and other VCS’s) will let you add “hooks” to different events that occur. The event we would like to attach the coding standard check to is the one that occurs before the changes in code actually gets pushed to the repository: the pre-commit event. This event, as it’s name clearly specifies, happens before the commit is done, and it has the power to stop the commit from happening.

The next question is how do we actually check the code against a standard? This is where the PHP_CodeSniffer component comes into play. As its name implies, it will actually sniff PHP code. You might have heard Ramones singing something about wanting to sniff some glue… I’ll let you in on a little secret: The original lyrics actually went a little something like this:

Now I wanna sniff some code
Now I wanna have strings to explode
All the kids wanna sniff some code
All the kids want strings to explode

Let’s get on with the show and start sniffing that code!

PHP_CodeSniffer uses something called sniffs and tokens to pull this off. A Sniff is actually a PHP class that checks one part of the coding standard only. A coding standard in PHP_CodeSniffer is a collection of these sniff classes. One example of a sniff is: “Disallow Tab Indentation”.

A token is an internal representation of a part of userland PHP code. Most of you have probably seen a token in an error message. If you do something like:


$foo = 'foo'
$foobar = $foo . 'bar';

you will get “syntax error, unexpected T_VARIABLE in … ” because you forgot to end the first line with a semi-colon. This actually shows us that some error messages in PHP aren’t all fun and games, but that’s a different story…

The T_VARIABLE part of the error message is as some of you might have guessed a token. PHP_CodeSniffer uses the Tokenizer extension in PHP to generate tokens of the PHP scripts it gets as input and the sniff classes you implement can use these tokens to analyze the input and see if it is correct according to the coding standard.

PHP_CodeSniffer comes with some complete coding standards and enough predefined sniff classes to let you define your own standard by using only predefined sniffs. If you simply want to follow the PEAR coding standard you can use the one that comes with the component. The component also includes a couple of command line scripts (Linux and Windows) that will let you examine your code with little effort.

Since the component belongs to PEAR, the default coding standard is PEAR (no shit Sherlock!). If you also want to use the PEAR standard on your code you can issue the following command (on Linux):

php /path/to/phpcs /path/to/script.php

PHP_CodeSniffer will then analyze script.php and see if it follows the PEAR standard. If not, you will get a bunch of errors informing you on the parts of your code that is different from the standard. If you have lots of code inside a directory you can simply use the name of the directory as argument to the phpcs script instead of the single script name. If you want to use some of the other coding standards that comes with the component you can do so by adding the –standard=<standard> argument. To use the “Zend” standard on a directory of code you can do something like this:

php /path/to/phpcs –standard=Zend /path/to/your/code/

And that’s it for this part actually. In the next part, which I hope to finish sometime this weekend or early next week,  I will create a coding standard in the PHP_CodeSniffer component and show you how to use some of the many sniff classes already defined to get you up and running with a shiny “new” coding standard. I will also show you how to extend some of them to do something a little different.

In the last part I will show you how to implement new sniff classes. The last part will also contain information on how to become the least popular guy on the development team: Add a check to the pre-commit hook so no one can commit code unless it follows the standard 100%!

June 24, 2008

Lego Vault

Filed under: Personal — Tags: — christer @ 10:16 am

So I was going through my RSS feeds to see if there was something interesting, and then I found something on Digg: Lego Secret Vault Contains All Sets In History (VIDEO).

I played a lot with Lego when I was a kid. I loved the town sets and the castles. I remember building up and taking it down again just so I could build it up once more. I wish I knew better when I was a kid and had taken better care of all the stuff I had. Looking at this video actually made me shed a tear. So yeah … I’m a sucker for Lego’s.

June 23, 2008

AOTW 26, 2008: Television - Marquee Moon

Filed under: AOTW, Music — Tags: , , — christer @ 6:41 pm

Apart from programming and climbing I really enjoy listening to music. From this day on I will try to present to you an (A)lbum (O)f (T)he (W)eek, every week. The albums will be picked from my collection.

Since I spend lots of hours every week listening to all sorts of stuff I thought I could share some of it with you. Well … not share as in letting you download the music from my blog … but share the name of an album (and artist) that I think is worthy of the ATOW award so you can pick it up from your favorite music store! I won’t write huge reviews but I’ll do something as simple as presenting my own personal favourites of the songs on the album. If you for some reason follow my advice and buy the album I’m presenting (or perhaps you already have it in your collection?), feel free to comment on what you think about it and if you (dis)agree with my own personal favorites, let me have it!

The first AOTW award goes the brilliant Marquee Moon album, by Television. Some regard them as one of the founders of punk rock. I regard them as makers of music full of win!

My three favorite tracks on the album are:

  • Friction
  • See no evil
  • Torn Curtain

Thats it really… :) If you haven’t gotten around to ordering the album yet, you have failed miserably! Happy listening!

Edit:
Dave (who added a comment here) has written an article about why he likes this album so much. Read the article at his blog.

June 19, 2008

WTF?! Que pasa?!

Filed under: Technology — Tags: , , , — christer @ 7:35 pm

A couple of Norwegian guys has just released a Norwegian translation of Twitter over at qpsa.no. Oh wait … it just looks like Twitter! Almost had me fooled there!

They seem to believe that this “new” service will revolutionize social networking in Norway… well … I truly believe that Angelina Jolie will dump Brad Pitt and come over to Oslogata to meet me instead… Let’s see what happens first!

Mats just published a post about the same thing over at his blog!

Zend_Service_Recaptcha is accepted

Filed under: PHP, Technology — Tags: , , — christer @ 5:33 pm

Just received a mail from Matthew Weier O’Phinney saying that the Zend_Service_Recaptcha proposal is accepted for inclusion in standard/incubator. So Paddy … you wanna update me on what changes you have done to the initial code soon? :p

Older Posts »

Blog at WordPress.com.