10 Apr

CMS Design with jQuery and PHP: moving a recaptcha form

reCAPTCHA is a free captcha service which lets you use their captchas for your programs.

I wanted to create a login/password-reminder page, with recaptcha used in both forms.

Unfortunately, you can’t have two recaptcha images on the same page, as every time the image is displayed, it is a new image and the old one is no longer valid (which means that if it’s used in two forms, you can only ever submit the second one.)

A solution that came to me is to “move” the captcha from one form to the other, so you’re only ever actually using one recaptcha.

So how is it done?

demo

In the demo, I’m using jQuery UI to separate the forms into two tabs.

If you look at the source, you will see there is one recaptcha object, in the first table. The table row has the ID “captcha”.

The entire JavaScript used in the demo is this:

$(function(){
	// remove the captcha's script element
	$('#captcha script').remove();
	// set up tabs
	$('.tabs').tabs({
		show:function(event,ui){
			// if the captcha is already here, return
			if($('#captcha',ui.panel).length)return;
			// move the captcha into this panel
			$('table tr:last',ui.panel).before($('#captcha'));
		}
	});
});

The first thing that’s done is that the captcha’s <script> element is removed. If you don’t remove it, then when the table row is moved, the script will be re-interpreted, causing breakage.

Now, the tabs are initialised. We set the show event to run a little function. That function checks to see if the captcha row is contained in the newly-shown panel. If it’s not, then it’s moved there using this line:

$('table tr:last',ui.panel).before($('#captcha'));

The above line means “insert/move the #captcha element in front of the last tr in the table contained in ui.panel“.

This is part of the User Management And Access Control chapter of the up-coming book “CMS Design using jQuery and PHP” ( a sequel, sort-of, to my jQuery 1.3 with PHP).

09 Mar

CMS Design with jQuery and PHP: postage and packaging prices

This article is based on work which will be expanded more fully in the book, when I get to that chapter.

Every time we do an online store here in webworks, the postage/packaging is different. In one case, for example, postage is free over €50 euro, in another, it depends on where it’s going, and in the latest, it depends on a load of factors including where it’s going, what the weight of the products is, and what delivery option was chosen.

Up until now, hand-coded the postage rules. Everything else was handled by user-friendly parts of our CMS, but postage was such a random thing that we couldn’t find anything common enough that we could make a generic P&P handler.

The finished product is more complex than this example, but I’ll describe a cut-down version of what we’ve done, with countries and parcel-types removed.

admin demo – demo of UI for generating P&P rules

The first demo shows how the postage-and-packaging rule-set is created, using an “if-else” flow generator to build up the logic of the thing, and after each major action, convert the current state into a JSON string which can be saved.

The PHP is not really important in this one. The JavaScript handles everything. It translates a “seed” JSON string into a graphical representation of the rules, which can then be manipulated and finally translated back (automatically) into a JSON string to be saved in a DB (or session in this case). source for the PHP, source for the JS.

The frontend does its work in the background:

frontend demo – using those rules to evaluate P&P (visit admin first).

In this case, we enter values – total, weight – and run through the rule-set to find out what the P&P ends up as.

The source is suprisingly small, using a small recursive function to dig through the rules, no matter how deep and complex they go.

Here’s the recursive function (see source for rest of file):

function os_getPostageAndPackagingSubtotal($cstrs,$total,$weight){
  foreach($cstrs as $cstr){
    if($cstr->type=='total_weight_less_than_or_equal_to' && $weight<=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_weight_more_than_or_equal_to' && $weight>=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_less_than_or_equal_to' && $total<=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
    if($cstr->type=='total_more_than_or_equal_to' && $total>=$cstr->value)return os_getPostageAndPackagingSubtotal($cstr->constraints,$total,$weight);
  }
  $val=str_replace('weight',$weight,$cstr->value);
  $val=str_replace('total',$total,$val);
  $val=preg_replace('#[^0-9*/\-+.\(\)]#','',$val);
  if(preg_match('/[^0-9.]/',$val))eval('$val=('.$val.');');
  return (float)$val;
}

The switch block goes through the various “if” types that can exist in the flow model, handling each of them recursively and return their values to the caller.

If no “if”s are encountered, then the ruleset has found an answer, and we return that answer.

Before returning it, though, we parse the value of the answer. This is in case the answer is a math formula to do with the weight or total of the item.

For example, An Post have definite prices for packets to Europe up to 2kg (which is 10.75), and beyond that, it’s 3 euro extra for every extra kg.

That translates to a load of definite “if” statements, and an end value of “(weight-2)*3+10.75” for the final “else”.

So, we convert recognisable words such as “weight” or “total” to numbers, make sure that we’re only left with parseable characters (and not something that can be used to hack), and eval it to produce the result.

Obviously, the full product is more complete than this, with safeguards against faulty formulas, extras to handle countries and envelope types (parcel/packet/envelope), but this example should give you a few ideas if you’re building your own P&P handler.

27 Feb

new irish plans (a construction industry thing)

We’ve just released newirishplans.com, a site for finding commencement notices. This is extremely useful for people in the construction industry, as I’ll explain.

Companies that work in construction need to be constantly on the lookout for new projects that are starting up. If you find a project just before it starts, you can call up and advertise your business, instead of waiting for the project manager to get around to finding someone else when the time comes.

As an example, if you sell bricks, it is better to call the manager of a house-building project just before they start building the house, than to not call at all, and realised when the house is built that the manager found a different brick supplier and didn’t realise you even existed.

You need to time the call as well – if you call too late, it’s obviously too late, but if you call months before the project starts, then the manager may totally forget you exist by the time the build actually needs your wares.

One way to find these builds that are starting up is to go around to all the planning authorities in your area of interest, and inspect any “commencement notices” that have been submitted since the last time you visited. A “commencement notice” is notification that you are about to start work on your build. All planning applications have this as a requirement.

Obviously, this can take hours out of your working week (and therefore, money), and even after you have the notice, you need to match the notice to the application and see if you’re actually interested in it at all.

The new irish plans project does this all for you. At the moment, the project covers about 17 counties, but we are always adding to this. For example, I’m working on getting Fingal added to the mix at the moment.

An account on the site costs 35 euro a month, and with that, you get an email once a week telling you of any commencements that the system has uncovered during that week.

But anyway – €35 euro a month. Just over one euro a day, and it’s all emailed to you.

If you know anyone in construction (does windows, landscapes, roofs, electrics, etc.) that is looking for work, tell them to go to newirishplans.com – the information is handed to you on a plate.

On the programming side, we wanted to make the search engine stand out, so we used the inline multiselect jQuery plugin (with a few small modifications) to help make selection of features and dates easier.

When I first came across that plugin, I was surprised and kinda proud to find that it’s based on some of my own work from 5 years ago! Open source is brilliant – you write a small piece of code and give it away, then 5 years later you find that someone has taken it and improved it vastly.

Commencements go through a “vetting” process. When a commencement is found, details about it are placed in a system where someone reads through the planning application, and marks down any interesting features about it. Those that have been vetted are then imported once a day into the main site itself, where you can search for them online, filtered by whatever interests you.

The system has been very long in the building, and has changed quite a bit over time. We’re very happy to finally make it public!

There’s still a few things that need to be completed on it (for example, we’re still organising WorldPay integration, but in the meantime we have PayPal), but on the whole, it’s ready for public use.

01 Feb

CMS Design using PHP and jQuery

I’m happy this week. Last week, I spent some time and organised myself a bit more. In work, things are going smoothly – managed to get over a tricky piece of work and the rest is simply a list of small tasks.

For the last few weeks, I’ve been emailing and messaging Darshana at Packt Publishing, about writing a second book (jQuery 1.3 with PHP is going very well – list of reviews).

I initially wanted to write about file management, to explain how KFM works, and to help force me to improve on it. But there’s just not enough of an interested market in that – it’s too specialised.

So instead, I’ll be writing about CMS design using PHP and jQuery.

We (webworks.ie) have a CMS engine which we’ve written and improved for the last 6 or so years. We’ve open-sourced it a number of times, but never managed to generate much interest in it. We never had the time to spend on publicising it.

The book will not be specifically about that engine, but rather about the concepts that went into creating it – how a CMS works, how to manage plugins, administration, user management, and all the other little bits and pieces that every PHP developer needs to eventually address.

By way of explanation, I will be demonstrating various parts of our CMS, and explaining how and why it was built that way. I will be closely examining the other major CMSes as well, and giving alternative methods where good ones exist.

The proposed chapter list is:

  1. Introduction
  2. CMS core design
  3. User management and access control
  4. Page creation and Navigation
  5. Template Management
  6. Plugins
  7. Form creation
  8. Image Gallery
  9. Panels
  10. Search and Polls
  11. RSS and News
  12. Online Store
  13. Products

I’m really excited about this project!

17 Dec

novelrank

Because it’s difficult to know exactly how well my book is doing, I went looking for online apps that might be able to help.

I came across NovelRank a few weeks ago, which keeps track of your Amazon SalesRank and uses the fluctuations in the value to try figure out when a sale happens.

At first I was a bit disappointed, as my own ratings should not many sales going on, but I realised that this was because there were no reviews out there so people a) didn’t know about the book, and b) didn’t know if it was worth buying.

Since the reviews have started coming in, sales have picked up, as can be seen in the NovelRank graph for my book.

I like this application – it’s a simple idea, and the author has made it freely available (I assume he makes money from affiliate links).

Want to see it in action? Buy JQuery 1.3 with PHP and then view NovelRank graph for my book the graph a few hours later to see your very own blip appear on it.

It’s interesting to see that the book is not selling at all in Canada. What’s wrong with you Canadians?? 😉

On a very related note, I’m in talks with Packt to produce another book. More on this later when details are more concrete.

13 Dec

jQuery 1.3 With PHP; buy it!

Christmas is coming, as most of us (especially parents and people that have wallets) know, so it’s time for ye all to dig deep and buy the perfect gift for that favourite web developer in your life.

Not knowing what that perfect gift could possibly be, I’ll recommend instead that you invest in a copy of my book, JQuery 1.3 with PHP.

Reviews are just starting to come in. I only know of two on-line ones so far, my favourite of which is this one:

The author does a great job of introducing complicated theories and breaking them down into manageable steps, whilst always taking very thorough considerations for applying jQuery knowledge into CMS ’s and web applications.

I noticed that the same reviewer posted this on Twitter: thoroughly impressed with reading jQuery 1.3 with PHP. writing a review on it, will be available soon!

The other one that I’m aware of is more of a list of notes than a review. The only thing he says in general about the book is “Overall a good book.”

There are a few minor criticisms in the second review that I don’t agree with – that I didn’t use inline functions in all cases, didn’t use Google’s functions to load jQuery from its CDN, and used document.getElementById in some cases instead of using jQuery’s $ function.

My reaction to those points are: inline functions are explained later in the book as I didn’t want to throw the reader head-first into understanding them, there’s no point in loading three libraries (google, jquery and jquery-ui) when you only need jquery and jquery-ui, and for the purposes of getting an element by its ID, document.getElementByID is much quicker than $.

I think the real problem with my decisions with the above points is that, after having had them pointed out as mistakes, I feel I should really have explained more clearly in the book why I chose to do things in those ways in the first place. Well, that’s something for edition 2 😀

So far, though, the reactions are positive, and I hope this continues – there haven’t been any “this is crap” reviews so far, which is good.

I know of a few other people that are writing reviews, and can’t wait to see them. So reviewers, please do criticise it – it makes the end-product better.

And christmas shoppers, it’s a great book 😉

10 Nov

scramble solver

A few days ago I wrote a WordDrop solver. Today, I’ve amended that code to produce a Scramble solver.

here it is (code) – what I do is to have that page open, and the Scramble game open, in two windows side-by side. Then start a new game, type the letters into the top input box. That’ll fill in the grid. For “qu”, type “q” in the input box and correct it in the grid. Then click “do it” and cheat your way to a high score.

Also discovered a small bug in my binary search algorithm 😉 I’ve fixed it in this new script but couldn’t be bothered with the last one – I’m done with that.

09 Nov

cheating at worddrop

Yesterday, I cheated at WordDrop, which is a Facebook game. I already had the highest score of my own network of friends, so I feel okay about this. But now that I’ve cheated, the game’s no fun any more!

WordDrop is a game where an 11×8 grid of letters is shown, and you build up words from that grid, where each letter should be linked to the one before it, with longer words getting higher scores.

I wrote a little script which basically plays the game itself, and comes up with the longest words possible.

My current score on the game is more than 500,000, and that was for a single 10-letter word. The second word the program came up with was “reselected”, which was not in the WordDrop dictionary. I just stuck with the first word and submitted that. With one word, I got a score that was about 8 times higher than my previous high score.

my script, and all files – don’t worry about the .php file – I just wrote a small scripty bit to print out the table – just download the HTML and JavaScript if you want your own copy.

01 Nov

notation viewer, day 2

notation-screenie

Spent an hour and added new abilities – you can now view music in the bass clef (and notes will be placed correctly based on that), note stems will be automatically up or down depending on staff position, and you can zoom in or out.

demo (source)

If you want to try it with your own files, create a MusicXML export (I’m using Rosegarden and NoteEdit for my own stuff), and gzip it, then place the gzipped file into the “tests” directory (for example, here).

Next step is multiple staffs, to show left and right hands simultaneously.