Tuesday, August 11, 2009

Regular expression are hard, let's go shopping

After looking at a Tweet from Charles Arthur of The Guardian and I decided to hunt down his blog. I typed "Charles Arthur" into Google and the first link was to his blog.

But there was something strange about it. All the letter t's following an apostrophe were highlighted. Here's a screen shot:

Yet, if I typed the exact same URL into Firefox the highlighted t's were not there. Odd. Since the URL was there this had to be something inside the HTTP headers sent when I was clicking through from Google.

I fired up HTTPFox and watched the transaction. Here's a screen shot of the HTTP headers of the GET request for his page. The interesting thing to look at is the Referer header.

It immediately jumped out to me that one of the parameters was aq=t. Looked to me like something on his blog was reading that parameter and using it to highlight. Poking around I discovered that his site is written using WordPress and there's a plugin for WordPress (that hasn't been updated for years) that's intended to highlight search terms when the visitor comes from a search engine.

Looking into the source of his web page it looked from the CSS like he was using that plugin. So I downloaded the source of the plugin and took a look. There's a bug in the way in which it extracts the query parameters from the Referer header for Google.

Here's the code:

$query_terms = preg_replace('/^.*q=([^&]+)&?.*$/i','$1',

That regular expression is buggy. It's looking for the right-most instance of a string that begins q= followed by anything other than the & symbol or the end of the Referer header. It's getting the right-most because the ^.* at the beginning means skip over anything from the start of the Referer header until you find q= and be greedy about it: skip over as much stuff as possible.

In the Referer string that are two parameters with q= in them. The first one is the correct one, the second one is the aq=. Since the regular expression isn't written to check that before the q= there's a ? or & it gets the wrong one.

I did a bunch of tests with wget to confirm that I'm right. It's a bug.

The aq=t parameter was added in 2006, here are the details. It's only present when you use the Firefox Google search box. Unfortunately, the plugin hasn't been updated since 2005.

It can be fixed by changing that line above to:

$query_terms = preg_replace('/^.*[\?&]q=([^&]+)&?.*$/i','$1',

But the right thing to do here is to rewrite this so that it didn't use regular expressions at all. After all, PHP has parse_url and parse_str functions that can do all the URL and query string parsing for you.

No comments: