England Test Cricket – Currently Very Good

A bit of a break from the dev stuff. We’re half way through the 3rd test against India and I am already comfortable enough (weather obliging) to say England are about to become the No 1 ranked test side in the world. If/when this happens I am sure a lot will be made of it by the media and rightly so, in my 30ish years of following English cricket there have been a lot of lows and very few highs. It seems almost strange that rightly England will be the best team in the world, and we could consider them that even if they don’t claim the spot of the coming 1 1/2 tests.

If you look at the side its not hard to see why they are the best in the world, and in true geek fashion and an indulgence of my love of statistics here’s concrete proof why.

England are a very good side

Notice I have said a very good side and not a great side. They may go on to become a great side (more on that later) but for now they are just very good.

Lets start by looking at the batting. Currently if you look at the batting line up they have great/good/competent batsman all the way through the side right down to number 11. Each and every batsman has a batting average in double figures.

England batting averages – Test matches
Player Span Mat Inns NO Runs HS Ave BF SR 100 50 0 4s 6s
JM Anderson 2003-2011 62* 80 33 559 34 11.89 1563 35.76 0 0 6 69 1
IR Bell 2004-2011 68* 115 15 4792 199 47.92 9170 52.25 15 28 8 562 19
RS Bopara 2007-2011 11* 15 0 502 143 33.46 936 53.63 3 0 4 64 2
TT Bresnan 2009-2011 9* 7 0 265 91 37.85 603 43.94 0 2 0 33 0
SCJ Broad 2007-2011 40* 53 7 1335 169 29.02 2101 63.54 1 8 7 173 9
AN Cook 2006-2011 71* 124 8 5640 235* 48.62 11540 48.87 19 26 3 654 5
EJG Morgan 2010-2011 12* 16 1 513 130 34.20 897 57.19 1 3 3 59 4
KP Pietersen 2005-2011 77* 131 7 6123 227 49.37 9844 62.20 18 24 7 730 55
MJ Prior 2007-2011 46* 68 12 2526 131* 45.10 3768 67.03 6 18 8 287 12
AJ Strauss 2004-2011 88* 156 6 6300 177 42.00 12666 49.73 19 25 13 780 10
GP Swann 2008-2011 35* 40 6 800 85 23.52 979 81.71 0 4 2 98 10

How often through the 2001 tests can that have been said, not often I would guess. And if you look at the averages for most of the batsmen, Ravi Bopara aside they are all averaging 40+. Take Ravi out and bring the usual Trott only strengthens the situation Trott has an average of 57+. These aren’t the averages of people at the start of their careers they are highly established batsmen with 5000+ test runs.

At the moment any team would struggle to contain a team which can realistically get a 50 from anyone down to number 10.

Ok on to the bowling:

England bowling averages – Test matches
Player Span Mat Inns Overs Mdns Runs Wkts BBI BBM Ave Econ SR 5 10 Ct St
JM Anderson 2003-2011 62* 113 2206.3 499 7150 233 7/43 11/71 30.68 3.24 56.8 11 1 28 0
IR Bell 2004-2011 68* 6 18.0 3 76 1 1/33 1/33 76.00 4.22 108.0 0 0 56 0
RS Bopara 2007-2011 11* 7 49.2 7 199 1 1/39 1/39 199.00 4.03 296.0 0 0 5 0
TT Bresnan 2009-2011 9* 16 300.0 84 865 36 5/48 7/96 24.02 2.88 50.0 1 0 3 0
SCJ Broad 2007-2011 40* 71 1332.5 285 4102 126 6/46 8/76 32.55 3.07 63.4 4 0 12 0
AN Cook 2006-2011 71* 1 1.0 0 1 0 1.00 0 0 62 0
EJG Morgan 2010-2011 12* 8 0
KP Pietersen 2005-2011 77* 47 167.3 11 666 5 1/0 1/10 133.20 3.97 201.0 0 0 47 0
MJ Prior 2007-2011 46* 139 5
AJ Strauss 2004-2011 88* 106 0
GP Swann 2008-2011 35* 63 1401.5 282 4114 142 6/65 10/217 28.97 2.93 59.2 10 1 30 0

Not as great here if you look over the averages, mid 20’s to low 30’s for a wicket isn’t that good, but there is a decent total number of wickets between them so in reality pretty good.

So not the strongest attack in the world but far from the weakest either.

Why England Deserve to be No 1

Here’s where things start to get interesting. The above shows that currently England have a very good side but not a great side in terms of overall career figures. If you take Indias big 5 batman, Tendulkar, Dravid, Sehwag, Laxman and Gambhir they have countless runs between them and career averages that most teams can only boast of having 1-2 of per team. That’s why they are currently no 1 and why they are a great batting team.

So how come England are destroying them and other teams if they don’t have great batsmen? Well lets take a look over the past 2 years at the players averages.

Overall figures
AN Cook 2009-2011 24 39 3 2155 235* 59.86 4156 51.85 10 6 0 240 3 investigate this query
IJL Trott 2009-2011 23 38 4 1965 226 57.79 4050 48.51 6 7 1 215 0 investigate this query
IR Bell 2009-2011 20 29 5 1724 159 71.83 3021 57.06 7 8 1 203 6 investigate this query
KP Pietersen 2009-2011 23 35 4 1488 227 48.00 2459 60.51 2 9 3 195 7 investigate this query
MJ Prior 2009-2011 24 33 5 1222 126 43.64 1749 69.86 4 8 4 133 7 investigate this query
AJ Strauss 2009-2011 22 35 1 1164 110 34.23 2319 50.19 1 10 4 144 2 investigate this query
PD Collingwood 2009-2011 16 24 1 719 145 31.26 1524 47.17 1 4 2 79 8 investigate this query
SCJ Broad 2009-2011 19 24 1 634 169 27.56 977 64.89 1 3 6 79 5 investigate this query
GP Swann 2009-2011 24 28 2 527 85 20.26 610 86.39 0 2 1 62 8 investigate this query
EJG Morgan 2010-2011 12 16 1 513 130 34.20 897 57.19 1 3 3 59 4 investigate this query
TT Bresnan 2010-2011 7 6 0 256 91 42.66 587 43.61 0 2 0 32 0 investigate this query
JM Anderson 2009-2011 21 26 7 162 29 8.52 482 33.60 0 0 6 23 1 investigate this query
MA Carberry 2010-2010 1 2 0 64 34 32.00 140 45.71 0 0 0 9 0 investigate this query
CT Tremlett 2010-2011 7 6 3 47 24* 15.66 98 47.95 0 0 0 5 0 investigate this query
JC Tredwell 2010-2010 1 1 0 37 37 37.00 63 58.73 0 0 0 6 0 investigate this query
ST Finn 2010-2011 12 13 9 35 19 8.75 128 27.34 0 0 2 6 0 investigate this query
A Flintoff 2009-2009 1 2 0 29 22 14.50 37 78.37 0 0 0 5 0 investigate this query
RJ Sidebottom 2010-2010 1 2 0 15 15 7.50 23 65.21 0 0 1 2 0 investigate this query
SJ Harmison 2009-2009 1 1 1 12 12* 12 100.00 0 0 0 3 0 investigate this query
G Onions 2009-2010 3 5 5 11 4* 45 24.44 0 0 0 2 0 investigate this query
A Shahzad 2010-2010 1 1 0 5 5 5.00 12 41.66 0 0 0 1 0 investigate this query
RS Bopara 2011-2011 1 investigate this query

Those averages now are pretty much as good as India and in some cases so much better. Bell averaging 71 over the past 2 years, which includes playing Australia twice! Those are the averages of great players.

Look now at the bowling averages and the picture gets much prettier.

Overall figures
GP Swann 2009-2011 24 44 966.0 185 2813 102 6/65 10/217 27.57 2.91 56.8 8 1 investigate this query
JM Anderson 2009-2011 21 39 818.4 204 2342 93 6/17 11/71 25.18 2.86 52.8 4 1 investigate this query
SCJ Broad 2009-2011 19 36 669.0 156 1920 68 6/46 8/76 28.23 2.86 59.0 2 0 investigate this query
ST Finn 2010-2011 12 24 345.4 74 1346 50 6/125 9/187 26.92 3.89 41.4 3 0 investigate this query
CT Tremlett 2010-2011 7 14 283.3 67 872 36 6/48 8/150 24.22 3.07 47.2 2 0 investigate this query
TT Bresnan 2010-2011 7 13 269.0 77 768 33 5/48 7/96 23.27 2.85 48.9 1 0 investigate this query
G Onions 2009-2010 3 6 115.0 23 366 8 3/86 4/136 45.75 3.18 86.2 0 0 investigate this query
JC Tredwell 2010-2010 1 2 65.0 13 181 6 4/82 6/181 30.16 2.78 65.0 0 0 investigate this query
A Shahzad 2010-2010 1 2 17.0 4 63 4 3/45 4/63 15.75 3.70 25.5 0 0 investigate this query
SJ Harmison 2009-2009 1 2 20.0 6 69 3 3/54 3/69 23.00 3.45 40.0 0 0 investigate this query
PD Collingwood 2009-2011 16 14 64.0 11 173 2 1/3 1/5 86.50 2.70 192.0 0 0 investigate this query
RJ Sidebottom 2010-2010 1 1 31.0 6 98 2 2/98 2/98 49.00 3.16 93.0 0 0 investigate this query
IJL Trott 2009-2011 23 12 44.0 3 185 2 1/5 1/5 92.50 4.20 132.0 0 0 investigate this query
A Flintoff 2009-2009 1 2 24.5 5 77 1 1/35 1/77 77.00 3.10 149.0 0 0 investigate this query
KP Pietersen 2009-2011 23 16 45.0 2 148 1 1/10 1/10 148.00 3.28 270.0 0 0 investigate this query
IR Bell 2009-2011 20 investigate this query
RS Bopara 2011-2011 1 investigate this query
MA Carberry 2010-2010 1 investigate this query
AN Cook 2009-2011 24 investigate this query
EJG Morgan 2010-2011 12 investigate this query
MJ Prior 2009-2011 24 investigate this query
AJ Strauss 2009-2011 22 investigate this query

England have 6 bowlers all averaging in the low to mid 20’s. To have a team like that shows why all teams are being blown away, and england only play 4 of them in a game!

All these stats are backed up by the ICC rankings where England have 2 batsman in the top 10 and 5 in the top 20, as well as well as 4 bowlers in the top 10 and 5 in the top 20. After this test these are likely to improve as well.

Will England go on to be a great team?

So currently we England are a very good side playing great cricket. To be considered a great side they need to maintain their current form over many years. The West Indies dominated in the 80’s, Australia dominated in the 90’s/00’s. England must dominate the next 5 years to be considered a great side. They also need to up their game in other formats of the game, particularly ODI where they are wildly inconstant, the great Aussie sides dominated both formats of the game.

They may just have the personnel to do that. Most of the bowling attack are young and have many years of cricket ahead of them. Not so much with the batting side but there are players who can form the spine of the team for years to come, Cook and Bell, allowing other batsmen to come in and bed themselves into the team when the likes of Strauss and Pietersen inevitably retire.

A special mention must go to Matt Prior who is currently without doubt the best wicketkeeper batsman in the world. Replacing him when he goes will be pretty difficult but not impossible. I am not as up on the county scene to know whether there are any promising keepers coming through.

Finally I guess we should always have one eye on a good spinner, Swann isn’t young so it would be good to have backup for him. I hear Rashid has lots of potential though.

For now enjoy the good times, and long may they live!

All stats have come from cricinfo which is an amazing source. I wish other sports had such great publicly available information!

Getting CakePHP database session data for an external script

I have a requirement for a current project to be able access the CakePHP session data for a script which is running outside of the framework. In normal circumstances this would be as simple as:

session_name('CAKEPHP');
session_start()
print_r($_SESSION);

However in my case the session data is stored in the database. In this situation you need to do a slight bit more to retrieve the session data. Thought I would share the code here for anyone who may need it.

The data is stored in the database in a serialised form and the session_key is essentially stored in a cookie. Therefore the equivalent of the above is:

include_once('../config/database.php');
$db = new DATABASE_CONFIG();

$dbh = mysql_connect($db->default['host'],$db->default['login'],$db->default['password']);
$dbn = mysql_select_db($db->default['database'], $dbh);

$session_qry = mysql_query('SELECT `data` FROM `sessions` WHERE `id`="'.$_COOKIE['CAKEPHP'].'"', $dbh);
$session_data = mysql_result($session_qry, 0, 'data');

session_start();
session_decode($session_data);
print_r($_SESSION);

Hope this comes in useful.

CakePHP Auth Component and Multiple Models

It seems recently all I have been doing is chasing things that are hard to debug :-( This may or may not be a bug but has had me chasing things for a while. I have a system which has two (three) different types of user, a system for users and a group user. They have very different use cases and it didn’t make sense to have a user type. One person may be either a user, a group admin or both. The features for each type were completely separate, i.e. if you were a group admin you wouldn’t automatically be a user as well.

As this was the case I decided to create a separate login system for both functions. Different tables, different models. Both had a login page and both used the Auth component. I did a simple switch in the app_controller to set up the Auth components variables and everything worked on an individual level, i.e. if you visited each login page without having first visited the other login page during the session. However if you went to one login page first and then to the other login page you couldn’t login to the second area.

After a few hours debugging I discovered that setting the $this->Auth->loginRedirect property isn’t enough to control the Auth component. When you first visit a page in a session cakephp sets the Auth.redirect session variable to the Auth::loginRedirect property. The Auth component then checks against this session variable when you login. If they don’t match then you are redirected to the session variable, which you probably don’t have access to as you haven’t logged in to this area.

The solution to this is to manually set this session variable when you change any Auth component properties.

function beforeFilter() {

  if($this->params['controller'] == 'groups' or $this->params['controller'] == 'group_users') {
  
    $this->Auth->userModel = 'GroupUser';
    $this->Auth->loginAction = array('controller' => 'group_users', 'action' => 'login');
    $this->Auth->loginRedirect = array('controller' => 'groups', 'action' => 'index');
    $this->Auth->logoutRedirect = array('controller' => 'group_users', 'action' => 'logout');
    $this->Auth->allow('display','login','logout');
    $this->Auth->authorize = 'controller';
    $this->Auth->userScope = array('GroupUser.active' => 1);
    
    $this->Session->write('Auth.redirect','/groups/index');
    
  }
  else {
  
    $this->Auth->userModel = 'User';
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
    $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'index');
    $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
    $this->Auth->allow('display','login','logout');
    $this->Auth->authorize = 'controller';
    $this->Auth->userScope = array('User.active' => 1);
    
    $this->Session->write('Auth.redirect','/users/index');
    
  }
  
}

At the moment I can’t decide whether this is a bug or whether my use case is a bit wrong. Obviously just setting the loginRedirect property of the Auth component shouldn’t affect the session. Maybe there needs to be a method to set this property instead which handles the session?

Apache, .htaccess, mod_rewrite, git and CRLF

Today I came across a frustrating and ultimately difficult to debug situation brought about by a cocktail of circumstances. Working on a site the rewrite rules suddenly stopped working when I made a small change to the .htaccess file. Nothing unusual here, back up the change and carry on. Except backing up the change made no difference. Ultimately the site still wouldn’t work.

Two fruitless hours later checking and rechecking syntax, conf directives and even the changing of DOCUMENT_ROOT just in case and still the issue wouldn’t resolve. The only thing left to do was to start again.

Delete the files, check the repos back out of git and see what happened. Magically it started working again, obviously something I had done had broken the site but what could it be. I retraced my steps and got once again to the .htaccess file and again the site broke. Instead of backing up the change I simply rechecked it out of git, which again fixed the issue. I then opened the file, made no changes and saved it, and this broke the site.Watch Full Movie Online Streaming Online and Download

So basically it worked fine from the checkout of git, but not once my text editor had touched it. This of course screamed line endings at me, and indeed this was the culprit. CRLF in the repos, LF when it hit my editor.

What was strange here was that it worked when it was from git, but not when my editor had touched it. Even stranger was that Apache couldn’t tell me if anything was wrong no matter what steps I took to debug. Nothing in the logs the .htaccess file was simply ignored silently. Not very helpful.

The answer lay on github, where setting a global config setting in git would handle this situation gracefully but tracking down the issue was very hard.

git config --global core.autocrlf input

Fixing it was a simple matter of using dos2unix, a utility I had experience with due to similar issues with Perl scripts back in my early days as a programmer.

As ever Google turned out to be my friend, but only after I had diagnosed the issue, searching for issues with .htaccess files had a far too high signal to noise ratio.

Another one to chalk up to experience.

CakePHP Self Referencing User Model

I recently needed to create a data model which included a friend-type system. Not a social network type thing but simply the ability to tag other users of a system. Sounds simple enough!

The application is written in CakePHP which has some fairly good ORM facilities but what I wanted wasn’t really simple to implement. The relationship I wanted to configure was a hasAndBelongsToMany relationship with a single table. In other words the join table referenced just one table. The join table looked like this:

CREATE TABLE IF NOT EXISTS `users_tags` (
  `user_id` INT(11) NOT NULL,
  `tag_id` INT(11) NOT NULL
);

And here is where things get a bit harder. There is no tags table which by convention the HABTM would usually join up to. What I really wanted was this:

CREATE TABLE IF NOT EXISTS `users_users` (
  `user_id` INT(11) NOT NULL,
  `user_id` INT(11) NOT NULL
);

Which obviously won’t work as you can’t have two columns named the same. Fortunately everything in CakePHP is configurable so setting the table up like this:

CREATE TABLE IF NOT EXISTS `users_users` (
  `user_id` INT(11) NOT NULL,
  `tag_id` INT(11) NOT NULL
);

Then configuring the User model with this relationship:

var $hasAndBelongsToMany = array(
    'Tag' => array(
      'className' => 'User',
      'join_table' => 'users_users',
      'foreignKey' => 'user_id',
      'associationForeignKey' => 'tag_id'
    )
  );

Enabled me to pull out all the tagged users for a particular user. This is where the fun started for me. I now needed the ability to tag players. I set up a list of users you could tag with a controller action like this /users/tag/$id. As I was logged in I already had the user_id bit and was passing the tag_id into the controller action. I expect to be able to do:

$this->User->UserUser->set('tag_id', $tag_id);
$this->User->UserUser->set('user_id', $user_id);
$this->User->UserUser->save();

But no matter what I tried the data wouldn’t save as one row. For some reason two rows were inserted, both with a blank user_id and the two ids supplied as tag_ids. I know that HABTM calls delete before saving but I didn’t see how it would be affecting the code as above. I tried for a while to get the CakePHP way of doing this but couldn’t work it out. In the end I just used a plain old query() to achieve what I wanted:

$this->User->query('INSERT IGNORE INTO `users_users` SET `user_id`='.$id.', `tag_id`='.$tag_id);

Whilst this does the job I would rather have worked out why it wasn’t working in the CakePHP way, so if any experts out there can shed some light please do!

This wasn’t the end of my woes tho. The application also uses the Auth component. The HABTM relationship seemed to be causing the Auth component some issues, when it logged in it was issuing a save() call which resulted in all my tags being wiped out. The solution to this was to unbind the model in the beforeFilter() method:

function beforeFilter() {
    
    $this->Session->start();
    
    $this->User->unbindModel(array('hasAndBelongsToMany' => array('Tag')));

    $this->Auth->autoRedirect = false;
    $this->Auth->loginAction = array('controller' => 'users', 'action' => 'login');
    $this->Auth->loginRedirect = array('controller' => 'games', 'action' => 'grid');
    $this->Auth->logoutRedirect = array('controller' => 'users', 'action' => 'login');
    $this->Auth->allow('display','login','logout');
    $this->Auth->authorize = 'controller';
    $this->Auth->userScope = array('User.active' => 1);

  }

After this the tagging relationship seems to work a treat. Hopefully this will post will prove useful to anyone trying to achieve a similar result.

Code From Hell

There are a lot of code zealots out there who pretend to think that their chosen language is the best language ever and anyone who uses another language is dumb. I’ve lost count of the PHP vs Java, or ‘language a’ vs ‘language b’ debates I’ve seen. Sometimes it comes down to personal choice, sometimes a certain language is a better option for the task at hand and sometimes it really doesn’t matter. Personally whilst I do like certain languages I have never ruled out other languages simply because I don’t like them. Better is nearly always a matter of opinion.

What does hold universal though is that no matter what language you use there are always people who produce poor code in them. And then there are people who produce code so bad that they give programmers a bad name. As a long time reader of the blog Daily WTF you can find so many examples of bad code in just about any language, and during my career I’ve come across code which could make many an article. Recently however I have been cursed with working on a code base that is so monumentally bad that I feel compelled to share some of the best snippets. Warning: what follows may make you weep!

Has it been obfuscated?

There are functions (but not all) in the code base that simply look like they have been obfuscated, variable names have been replaced with what looks like machine generated names. That is until you look closer and you realise that no obfuscation program could be so inconsistent. Mixed amongst the seemingly generated variable names is the odd variable name that makes sense. Take this example below:

get_page_game() {
  if(isset($_SESSION['auth']['uid'])) {
    $uid=$_SESSION['auth']['uid'];
    $ip=$_SERVER['REMOTE_ADDR'];
    $date=date('Y-m-d');
    if(isset($_POST['gameID'])) {
      $i0l1101=isset($_POST['userID'])? preg_replace('/[^\d]/','',$_POST['userID']) : 0;
      $i0l11010=isset($_POST['gameID'])? preg_replace('/[^\d]/','',$_POST['gameID']) : 0;
      $i0l110101=isset($_POST['highscore'])? preg_replace('/[^\d]/','',$_POST['highscore']) : 0;
      $i0l1101010=isset($_POST['wpm'])? preg_replace('/[^\d]/','',$_POST['wpm']) : 0;
      $i0l11010101=isset($_POST['userStage'])? preg_replace('/[^\d]/','', $_POST['userStage']) : 0;
      $i0l110101010=isset($_POST['userSpeed'])? preg_replace('/[^\d]/','', $_POST['userSpeed']) : 0;
      $i0l1101010101=isset($_POST['userUnlocked'])? preg_replace('/[^\d]/','', $_POST['userUnlocked']) : 0;
      $i0l11010101010=isset($_POST['incrementLevel'])? preg_replace('/[^\d]/','', $_POST['incrementLevel']) : 0;
      $i0l110101010101=isset($_POST['wpmTarget'])? preg_replace('/[^\d]/','', $_POST['wpmTarget']) : 0;
      $il1l1l1010101011=isset($_POST['lettersTyped'])? preg_replace('/[^\d]/','', $_POST['lettersTyped']) : 0;
      $ill00=database::query("SELECT `nickname`,`grpname`,`stage`,`lvldata`,`maximum_score` FROM `ft_account_members` WHERE `uid`='$i0l1101'");
      while($ill001=mysql_fetch_array($ill00)) {
        $i00l1101010101010=$ill001['nickname'];
        $i00l11010101010101=$ill001['grpname'];
        $hlvldata=$ill001['lvldata'];
        $i00l110101010101=$ill001['maximum_score'];
      }
      $i1l01ll0= 'ft_64m3'.$i0l11010;
      $ill0010=database::query("SELECT `highscore` FROM `".$i1l01ll0."` WHERE `nickname`='$i00l1101010101010'");
      if(mysql_num_rows($ill0010)>0) {
        $ill00101=mysql_fetch_array($ill0010);
        if(mysql_error()=='') {
        }
        else { 
          echo mysql_error();
          exit();
        }
        ...
      }
    }
  }
}

Variables look generated, $i, $i1i, $i10 etc but then you look closer and realise some of 1’s are actually l’s, which conceivably could be generated, but then right in the middle is $hlvldata. Huh? either it has been obfuscated and the obfuscater is unbelievable or the variable names have been purposely chosen!

Ever heard of a loop?

So what do you do if you want to assign 32 variable names in ascending numerical order. Why you write it our 32 times of course, and of course you do this in at least 10 functions as well just for good measure.

$mpm->assign('gs0',$mp->get_game0score());
$mpm->assign('gs1',$mp->get_game1score());
$mpm->assign('gs2',$mp->get_game2score());
$mpm->assign('gs3',$mp->get_game3score());
$mpm->assign('gs4',$mp->get_game4score());
$mpm->assign('gs5',$mp->get_game5score());
$mpm->assign('gs6',$mp->get_game6score());
$mpm->assign('gs7',$mp->get_game7score());
$mpm->assign('gs8',$mp->get_game8score());
$mpm->assign('gs9',$mp->get_game9score());
$mpm->assign('gs10',$mp->get_game10score());
$mpm->assign('gs11',$mp->get_game11score());
$mpm->assign('gs12',$mp->get_game12score());
$mpm->assign('gs13',$mp->get_game13score());
$mpm->assign('gs14',$mp->get_game14score());
$mpm->assign('gs15',$mp->get_game15score());
$mpm->assign('gs16',$mp->get_game16score());
$mpm->assign('gs17',$mp->get_game17score());
$mpm->assign('gs18',$mp->get_game18score());
$mpm->assign('gs19',$mp->get_game19score());
$mpm->assign('gs20',$mp->get_game20score());
$mpm->assign('gs21',$mp->get_game21score());
$mpm->assign('gs22',$mp->get_game22score());
$mpm->assign('gs23',$mp->get_game23score());
$mpm->assign('gs24',$mp->get_game24score());
$mpm->assign('gs25',$mp->get_game25score());
$mpm->assign('gs26',$mp->get_game26score());
$mpm->assign('gs27',$mp->get_game27score());
$mpm->assign('gs28',$mp->get_game28score());
$mpm->assign('gs29',$mp->get_game29score());
$mpm->assign('gs30',$mp->get_game30score());
$mpm->assign('gs31',$mp->get_game31score());
$mpm->assign('gs32',$mp->get_game32score());

For the love of Deity man have you never heard of a loop? Perhaps he’d tried it as dynamic method calls and it didn’t work for him, oh wait no he’s already used a dynamic method call in another function, so that can’t be right.

Oh yeah and check out the variable names, no $iiii this time, and unbelievably where this is used multiple times the variable names are different, so it isn’t just a cut and paste jobbie???

Ever heard of date functions?

Damn you MySQL and your weirdly formatted dates, I don’t understand them, if only I could make them more friendly? I know I can split the date up and then change it – how could this be coded?

switch($hMonth) {
  case 1: 
    $hMonth='Jan';
    $hValue=1;
  break;
  case 2: 
    $hMonth='Feb';
    $hValue=2;
  break;
  case 3: 
    $hMonth='March';
    $hValue=3;
  break;
  case 4: 
    $hMonth= 'April';
    $hValue=4;
  break;
  case 5: 
    $hMonth='May';
    $hValue=5;
  break;
  case 6: 
    $hMonth='June';
    $hValue=6; 
  break;
  case 7: 
    $hMonth='July';
    $hValue=7;
  break;
  case 8: 
    $hMonth='Aug';
    $hValue=8;
  break;
  case 9: 
    $hMonth='Sep';
    $hValue=9;
  break;
  case 10: 
    $hMonth='Oct';
    $hValue=10;
  break;
  case 11: 
    $hMonth='Nov';
    $hValue=11;
  break;
  case 12: 
    $hMonth='Dec';
    $hValue=12;
  break;
}

Maybe its because he wanted to be as inconsistent with the date month display as he is with his variable names? There are so many shorter ways of doing this, let MySQL spit the date out in a correct format, use strtotime() coupled with date()? Argghh it hurts its too painful.

Ever heard of a sane data structure?

This last example takes the biscuit though. As far as I can tell what the coder wanted to do was store a set of 3 data points representing level scores. How did he choose to do this? in the date format 1_1.1_2.1_3.2_1.2_2.2_3….. thats right as a ‘.’ separated list with a ‘.’ set separator! How the hell would this be read in and updated… like this:

$a0=array("a00"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));
$a1=array("a11"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));
$a2=array("a22"=>array(
  0=>0,1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,
  9=>0,10=>0,11=>0,12=>0,13=>0,14=>0,15=>0,16=>0,
  17=>0,18=>0,19=>0,20=>0,21=>0,22=>0,23=>0,24=>0,
  25=>0,26=>0,27=>0,28=>0,29=>0,30=>0,31=>0,32=>0
));

$hlvldataii=$hlvldata;
$hlvldatatok0=strtok($hlvldataii,".");
$hCntTok0=0;
$hCntTok1=0;

while($hlvldatatok0 !== false) {
  if($hCntTok1==0)$a0["a00"][$hCntTok0]=$hlvldatatok0;
  if($hCntTok1==1)$a1["a11"][$hCntTok0]=$hlvldatatok0;
  if($hCntTok1==2){
    $a2["a22"][$hCntTok0]=$hlvldatatok0;
    $hCntTok0++;
    $hCntTok1=0;
    $hlvldatatok0=strtok(".");
    continue;
  }
  $hlvldatatok0=strtok(".");
  $hCntTok1++;
}

$hlvl=$hCntTok0-1;
$hFlg=0;

for($i=0;$i<$user_stage;$i++) {
  $hlvlSrch.=$a0["a00"][$i].'.'.$a1["a11"][$i].'.'.$a2["a22"][$i].'.';
}

$hlvlSrch .= $user_stage.'.'.$wpm.'.'.$wpm_target;

I don't even know where to begin with this, have a go yourself, of course the variable names have been designed to help legibility. I wanted so badly to re-write it but in the end I opted to leave it as is and grab a beer.

Kill me now!

I could go on, these examples are just insane, the rest of the code is no better, if statements 20 levels deep, the same code repeated in a dozen functions, a single file with over 4000 lines of code. I can honestly say this is some of the worse code I've ever had the misfortune to work on.

Unfortunately I had to inform the client of how bad the code was, embarrassed at the level of incompetence displayed by my profession. Fortunately she was very understanding and guided by me has taken the wise decision to let me throw it away and start again. Hopefully a happy ending!!!

Facebook Send

In a recent post on the Facebook blog they announced updates to their group functionality, which currently isn’t really a function I use, although I can see the benefit of using groups. Buried near the bottom of the post and later picked up by Mashable was an announcement about a new piece of functionality not for the Facebook site but to be found on sites outside of Facebook.

In addition to the other new group features, we’re also introducing the Send button.

Similar to the “Like” button, it seems a “Send” button has been developed which can be placed on your site. At the moment it appears only on a small number of sites (about 50), but if it is successful on these sites I don’t see any reason why it wouldn’t be rolled out as a social plug-in in a similar fashion to the “Like” button.

This new functionality interests me for two reasons:-

  • Functionality such as this is abundant on sites and microsites in the form of a forward to a friend.
  • It further cements Facebook as a facilitator of communication.

Forward to a Friend

I’ve lost count of the times I’ve implemented this functionality on a site. Its not particularly challenging to implement functionally, but it is actually pretty hard to make it work well technically. Forget the fact that IMO this functionality rarely gets used, it is nevertheless added to so many sites alongside the almost equally as pointless share icons. What you don’t really tend to see is whether the form you submit ever actually ever reaches its recipient.

The reason for this is that web servers don’t make very good email servers. Sure it is easy to actually send email but to make it get to its destination is very unlikely to happen. The reason for this is that the email has to come from someone, usually the person filling out the form. When this email is sent the receiving server checks where the email has come from and if it isn’t from where the email domain should be coming from it is likely to mark it as spam.

The benefit of using Facebook for this is therefore two-fold, you reduce the implementation cost as it will essentially just be a quick plug-in, and you also increase the likelihood of it actually working! Whether it will actually be used is another thing entirely.

Facebook Replacing Email

Email is old, and if you believe some statistics 45% of all emails sent are spam. Communication has moved on considerably over the last few years and the one-size fits all solution which is email doesn’t really fit anymore.

Don’t believe me then I ask you when was the last time you tried to arrange something over email? And when was the last time you did it through Facebook, be it via an event of via FB message? Which was more successful? Our social worlds live on Facebook and for most people its just easier to communicate through Facebook than through email now, but only for this specific use-case.

Now I’m not suggesting that email will entirely be replaced, it use is so varied especially in business but you could say that it may be replaced for certain types of communication. Up until now the only Facebook mail has really only been used within Facebook, moving it into a wider context broadens the scope for its use, Forward to a Friend is just one use-case there may be many more for which Facebook may be a “better” solution than email.

Of course there is an argument that such an important channel should not be in the control of one corporation but I think we are far beyond the point where that argument is even relevant anymore, Facebook simply is the social channel.

Perch CMS

When it comes to CMSes you could say I have a fair amount of experience. Practically every site I have ever worked on has had some aspect of content management, most of which I or my ex-team has built from the ground up. You could say that I am a big fan of bespoke content management systems.

The reason I am such a big fan is that when it comes to adding content management you can make a fair bet that an off the shelf package or an open source CMS would only work for 90% of the sites functionality. What you end up having to do is customise the packaged CMS for your purposes or have to compromise on functionality for the site. Customisation is usually in the form of a plug-in, and these come with their own headaches. Your upgrade path is compromised, security is even further out of your control and the quality of plug-ins is rarely as high (or low) as the original package.

This is all well and good if you have budget to play with, but in my experience 75%+ of the time content management is overkill for a site and never actually used by the client. They pay the bills though and usually against advice it is required, and on every page! Can I add a CMS for every page, you bet I can and with the use of a good MVC framework it is a lot simpler and quicker to implement than it used to be. But lets face it its tedious, of no technical challenge and budget could be better spent elsewhere on the UI.

This is obviously an issue which isn’t confined to just me and one I guess a number of people have tried to fix. What I need is a simple CMS that can be quickly implemented for a simple site. Step into the light Perch.

Perch has been developed by edgeofmyseat and its tagline is

a really little content management system

I’ve heard good things about this off the shelf package so on a recent project after debating whether I would find myself having an awful time wrestling with yet another system which didn’t do what I wanted I decided to give it a go. Lets just say I wasn’t disappointed.

Lets also be clear from the start the use-case for this was a very simple site with what amounted to one template over a fixed number of pages. I didn’t need the ability to add new pages, I controlled the layout, and the template was fixed into three types, a heading, body content and an image/video.

After buying a very reasonably priced license I set about installing the system. Given I am very comfortable in using frameworks, wordpress, drupal, joomla and the myriad of other similar packages the installation was very simple. A config file, a slight customisation to the URL and the CMS was installed. Total time from starting to having it up and running 12 minutes. Even in comparison with wordpress that was quick!

Now I had the system running I needed to see if it did what I needed. Having already built the site template I looked at the example page the CMS came with and amazingly it satisfied 2/3rds of my needs. Copy and paste later and the page was defined. Visit the page in my browser and Perch picked up on this installation and displayed the content to be edited in the admin screen. Simple as that. I won’t go into details as to how it worked as the documentation does a much better job than I ever could.

So far everything had been ridiculously easier but the last part was not an out of the box solution, the dammit I wish I could do this moment I had been dreading. The requirement was to be able to upload either a video or an image to display next to the content.

Perch has certain types of content, and templates which define collections of content types. I decided to create my own template that utilised the file and image types with a conditional to define which one to use. My first thought was that I could use a radio button to determine which of the two types to display, unfortunately I couldn’t work out how to target a specific content value through the conditional tag, it seemed only to define if the the option had a value of any type. I changed it to a checkbox which meant the page defaulted to an image but could be overridden with a video.

The template was defined like this (content has been slightly mangled by the syntax highlighter):



  
    <script src="/js/flowplayer-3.2.6.min.js"></script>
    
<script> flowplayer("player", "/flash/flowplayer-3.2.7.swf", { clip: { url: "<perch:content id="file" type="file" label="Video" order="2" />", autoPlay: false } }); </script>

This was saved as template and could then be assigned to the content region when I added it to the page. This worked very well for me and I had essentially finished the CMS in less than 2 hours! What more could I ask for than that. Well I would of course have preferred my original template implementation, and the ability to restrict the file type for upload would also have been nice but I could trade-off these requirements for the speed of implementation.

So would I recommend Perch? In a word yes, in a sentence it would be yes if your use case hits the demographic its aimed at? My use case was simple, very simple and even with a custom template it practically worked out of the box. If your CMS requirements are more complex I would think twice about using Perch. Now that’s not to say Perch cannot but manipulated to your needs, its got a great API and some great looking plug-ins but then you are back to where you are with most off the shelf CMSes. If you need a lot of custom pages and custom CMS flows then I would probably go back to bespoke in a flash. Maybe thats because I haven’t had the chance to get deeper into Perch and perhaps I should.

However if you get a chance to use Perch I would highly recommend it.

Anti-Social Games

I’ve waited a while to write this blog post, and it really has been a while. 18 months ago I wanted to see what all the fuss was about with regards to Facebook games such as FarmVille, little did I know how much it would suck me in. The idea of planting virtual crops didn’t really appeal to me, still doesn’t, so I chose another of Zynga’s social games Mafia Wars. This post has been inspired by the fact I am approaching Level 1000!

Now what you need to bear in mind with this is that on an average day as a player I am lucky to advance 2 levels. It is a game which gets harder to level the higher you get. I have literally had to play the game everyday for 18 months, and when I say everyday it really is practically everyday (just ask my long suffering wife), my current streak is about 300 consecutive days. Yes over this period of time at least once a day I have logged on to Facebook and into the MW app and performed the same monotonous tasks.

You see I joined to see if it was fun to play games socially and what has actually happened is that I pretty much play the game by myself, largely ignoring the social options and actually hating the fact that the game would be easier if I had a lot of friends as addicted as I was who would actively get social about it.

Its not the first time I’ve been taken in by this sort of thing, I also got sucked in by the spymaster twitter game which consumed many an hour of my life. Both of these games tapped into something I didn’t expect, an OCD of sorts which makes me want to complete collections.

For the un-initiated amongst you MW basically has two main actions, fighting and jobs (there’s more than this but at its basic level this is it). The game is currently compartmentalised into cities, in each city you have a number of tasks to complete. Complete the tasks and complete the city.

You have two stats to spend in the game, energy and stamina, energy is use for jobs and stamina is used in fights. You have a finite amount of each stat which recharges over time. So basically if you have used all your energy/stamina you can’t do anything till it recharges which generally takes a long time. There are other vital stats as well such as health, attack and defense points which define how good you are at fighting.

The fighting aspect of the game is I guess what you can call the social side of the game and its largely the part I dismissed. I am essentially addicted to the game play, not because it is difficult but because it is obscenely simple, repetitive and seemingly never ending.

The point here is that whilst the social aspect of games such as MW is what a lot of people focus on I think Zynga need to be given a bit more credit here. Yes the game is popular because of the social aspect and its ability to tap into the long-tail of users, but the actual mechanic is brilliant (well for me). Social is obviously all the rage but its good to know there’s still room for a good old fashioned game concept. I’ve tried other Zynga games such as CityVille, but these games require me and my friends to get social to progress at any rate, something I’m not prepared to do.

Like most addicts, admitting I have a problem is the first step. The next step is to break the addiction. I’m so close to finishing the game it should be over for me soon, but no Zynga have gone and released a new city… DAMN YOU ZYNGA!

No Such Thing as a Free Lunch

So Twitter has cause a mini storm by turning on its developer ecosystem. Anyone who didn’t see this coming have been very naive. Any business who utilises a third-party system such as the APIs/Platforms/Marketplaces in order to make money doesn’t have a business built on solid foundations.

Sure you can argue that it is the developers who have made Twitter or Facebook or Apple or ANother service popular but at the end of the day these are the companies who hold all the cards. They are free to change their terms and conditions as they see fit. People may call foul but ultimately these companies are here to make money and they will do so as they please. The only way around this is to be the company holding the cards.

Would I still develop a Facebook App for a client, or an iOS app etc. You bet I would, but if it was for me my eyes are open, if it is for a client then I would have a duty to open their eyes as well. Don’t like this then vote with your feet, don’t utilise this platform, or except the risks. Beware the third-party, especially if the service is “free”.