How to add an AJAX function / URL to WordPress

Put this function in your theme’s functions.php (or even better, in an ajax.php file in the theme that is require’d in):

/* The function ajax_read_more() will be called when the following URL is requested
 * from WordPress:
 *
 * http://www.yoursite.com/wp-admin/admin-ajax.php?action=read_more&limit=5
 */
function ajax_read_more() {
    // Take in a few input parameters from $_GET or $_POST (depending on how you're passing the values) about
    // what data to retrieve and display.
    $num_limit = (int) $_POST['limit'];
    $str_category_name = filter_var($_POST['category_name'], FILTER_SANITIZE_STRING);
  
    // Call some built-in WordPress functions just to demonstrate that we can.
    $user_id = get_current_user_id();
  
    // Now let's return some JSON data to whatever called this URL (we can return HTML, XML or whatever else too,
    // just make sure to set the appropriate Content-Type header).
    $arr_sample_data = array('key' => 'value');
    echo json_encode($arr_sample_data);
    exit; // You must use exit to end an AJAX function in WordPress, or it'll append a 0 to the output.
}
add_action( 'wp_ajax_read_more', 'ajax_read_more' ); // This action exposes the AJAX action "read_more" to logged-in WordPress users.
add_action( 'wp_ajax_nopriv_read_more', 'ajax_read_more' ); // This action exposes the AJAX action "read_more" to anonymous (not logged in) WordPress users.

Then all you need to do is write a jQuery or even just a regular HTML form that submits a request to your new AJAX URL:

jQuery.ajax({
    type: 'get',
    url: '/wp-admin/admin-ajax.php?action=read_more&limit=5',
    dataType: 'json'
})
.done( function( response ) {
    console.log(response);
});

One last thing – visit your WordPress site’s Permalinks page in order to rebuild the list of URLs WordPress will respond to. This will make your new URL (for the AJAX function) active.

Forcing images to conform to a 16:9 aspect ratio

In the Bootstrap front-end framework, you can add the classes embed-responsive embed-responsive-16by9 or embed-responsive embed-responsive-4by3 on a DIV that wraps an IFRAME, EMBED or OBJECT element to ensure that video players always conform to a 16:9 aspect ratio on your responsive website (more info).

But what about images? In cases where content has been migrated onto a WordPress site, re-creating all thumbnails in the proper aspect ratio may just not be doable – or you may simply not have the controls in place to ensure that all images are of the correct aspect ratio. Luckily there appears to be a trick in CSS that can force aspect ratios. To get it to work, you’ll need to write CSS for a DIV that wraps the actual IMG tag like so:

.img-responsive-16by9 {
    display: block;
    height: 0;
    padding-bottom: 56.25%;
    overflow: hidden;
}

That’ll force the image output with the HTML illustrated below to respect a 16:9 aspect ratio:

<div class="img-responsive-16by9">
    <img src="http://www.570news.com/wp-content/blogs.dir/sites/3/2015/04/1429827607_NSD502266764_low.jpg">
</div>

Why I mostly hire generalists

I’ve had the pleasure of getting to build the in-house web development team at Rogers Media for a few years now up from just myself and one other developer to a staff of fifteen. I’m of the school of thought that software development teams are best kept small: It requires a smaller web of communication, individual team members maintain a high level of impact on the product they’re building (avoiding a loss of motivation due to the Ringelmann effect), and team stability (that is, people constantly joining or leaving the team) is usually greatly improved.

But there’s a potential downside that has to be addressed: Software is complex, and the requirements of web development often extremely so. How does a small team come through with everything that’s needed to make a project work? My answer has been to build the core of the team around generalists – people who tend to be very good in one area of development, but also knowledgeable and capable in most others as well.

Here’s an excerpt from the Pragmatic Programmer series titled Be A Generalist that speaks to why generalists are the answer to meeting a modern business product’s software needs:

For at least a couple of decades, desperate managers and business owners have been pretending that software development is a manufacturing process at heart. Requirements specifications are created, and architects turn these specifications into a high-level technical vision. Designers fill out the architecture with detailed design documentation, which is handed to robot-like coders, who hold pulp-fiction novels in one hand while sleepily typing in the design’s implementation with the other. Finally, Inspector 12 receives the completed code, which doesn’t receive her stamp of approval unless it meets the original specifications.

It’s no surprise that managers want software development to be like manufacturing. Managers understand how to make manufacturing work. We have decades of experience in how to build physical objects efficiently and accurately. So, applying what we’ve learned from manufacturing, we should be able to optimize the software development process into the well-tuned engine that our manufacturing plants have become.

In the so-called software factory, the employees are specialists. They sit at their place in the assembly line, fastening Java components together or rounding the rough edges of a Visual Basic application on their software lathes. Inspector 12 is a tester by trade. Software components move down the line, and she tests and stamps them in the same way each day. J2EE designers design J2EE applications. C++ coders code in C++. The world is very clean and compartmentalized.

Unfortunately, the manufacturing analogy doesn’t work. Software is at least as malleable as software requirements. Things change in business, and businesspeople know that software is soft and can be changed to meet those requirements. This means architecture, designs, code, and tests must all be created and revised in a fashion more agile than the leanest manufacturing processes can provide.

In this kind of rapidly changing environment, the flexible will survive. When the pressure is on, a smart businessperson will turn to a software professional can solve the problem at hand. So, how do you become that person whose name comes up when they’re looking for a superhero to save the day? The key is to be able to solve the problems that may arise.

What are those problems? That’s right: you don’t know. Neither do I. What I do know is that those problems are as diverse as deployment issues, critical design flaws that need to be solved and quickly reimplemented, heterogenous system integration, and rapid, ad hoc report generation. Faced with a problem set as diverse as this, poor Inspector 12 would be passed over pretty quickly.

The label jack-of-all-trades—master of none is normally meant to be derogatory, implying that the labelee lacks the focus to really dive into a subject and master it. But, when your online shopping application is on the fritz, and you’re losing orders by the hundreds as each hour passes, it’s the jackof-all-trades who not only knows how the application’s code works but can also do low-level UNIX debugging of your web server processes, analyze your RDBM’s configuration for potential performance bottlenecks, and check your network’s router configuration for hard-to-find problems.

And, more important, after finding the problem, the jack-of-all-trades can quickly make architecture and design decisions, implement code fixes, and deploy a new fixed system to production. In this scenario, the manufacturing scenario seems quaint at best and critically flawed at worst.

Another way in which the software factory breaks down is in that, although in an assembly line the work keeps coming in a steady flow, software projects are usually very cyclical. Not only is the actual flow of projects cyclical, but the work inside a project is cyclical. A coder sits on the bench while requirements are being specified, architected, and designed, or the coder multitasks across many projects. The problem with multitasking coders is that, despite the software factory’s intentions, when the rubber meets the road, the coders rely a great deal on context and experience to get their jobs done. Requirements, architecture, and design documents can be a great head start, but ultimately if the programmers don’t understand what the system is supposed to do, they won’t be able to create a good implementation of the system.

Of course, I’m not just picking on coders here. The same is true at nearly every spot on the software assembly line. Context matters, and multitasking doesn’t quite work. As a result, we have an inefficient manufacturing system. There have been various attempts to solve this problem of inefficiency without departing from the manufacturing-inspired system, but we have not yet figured out how to optimize our software factories to an acceptable level.

If you are just a coder or a tester or a designer or an architect, you’re going to find yourself sitting idle or doing busywork during the ebbs of your business’s project flow. If you are just a J2EE programmer or a .NET programmer or a UNIX systems programmer, you’re not going to have much to contribute when the focus of a project or a company shifts, even temporarily, out of your focus area. It’s not about where you sit on the perceived value chain of project work (where the architect holds the highest spot of royalty). It’s about how generally useful you make yourself.

References:

 

Hacking the Budweiser Red Light (Part I): Identifying the network traffic that activates the light

The Budweiser Red Light is one of the best pieces of marketing I’ve ever seen. And while I’m enough of a hockey fan to want to pick up one of these anyways, the real prize is in figuring out how to make the thing go off whenever I choose.

Where to get started? While I’ve seen an attempt to use/modify the Electric Imp card inside the light to accept requests, I thought my approach might be simpler: Sniff the network traffic to and from the light, replicate it to sound the alarm.

The instruments used to sniff the traffic were as follows:

  • A MacBook Pro (to set up Internet Sharing upon for the Red Light to connect to)
  • My Android OS smartphone (to install and pair to the Red Light using the app Budweiser developed for that purpose)
  • WireShark (a network protocol analyzer) installed on the MacBook Pro, which also requires XQuartz

Instructions

I kept careful notes in case someone else wanted to replicate this experiment; those instructions are:

  1. Enable Internet Sharing on the MacBook Pro, and make sure you set no password or key. (At home where I have an Windows 8.1 PC, I had attempted to set up a Wi-Fi hotspot but the Red Light appeared to have difficulty getting on that network.) I named my new Wi-Fi access point “BudRedLight”.
  2. I had my Android OS smartphone join the Wi-Fi access point of “BudRedLight”, which it did without issue.
  3. In order to sniff its traffic, we’ll need to get the Red Light on the “BudRedLight” access point as well. This means installing and setting up the official Budweiser Red Lights app, and using the interesting flashing light method of sending the Wi-Fi connection details from the phone to the Red Light.
  4. Once that’s done, I left the app open on the phone, specifically staying on the screen that provided the “TEST YOUR LIGHT” button. The plan was to capture what was received by the Red Light once this was pressed.
  5. Now that the Red Light and my phone were both on the “BudRedLight” access point, it was time to boot up WireShark on the MacBook Pro (I had to start XQuartz first so WireShark would run).
  6. Let’s get WireShark listening to the traffic coming in and out of “BudRedLight”: Select the Capture menu option, and then Options. Unclick the “Use promiscuous mode on all interfaces option” (this will cut down on the amount of noise being captured). Instead, double-click on the Wi-Fi listing, and within it check the “Capture packets in promiscuous mode” option and hit OK. (Need a visual guide? Here’s a screenshot.)
  7. Okay – we’re now capturing traffic! Tap the “TEST YOUR LIGHT“; this will make your phone send a HTTPS request up to some remote server, which in turn appears to send a TCP [PSH, ACK] packet to the Red Light. In the screenshot of WireShark below, I pressed the “TEST YOUR LIGHT” twice, resulting in the two [PSH, ACK] packets listed:bud-red-light-tcp-psh-ack-traffic
  8. So what’s in that packet? Only 234 bytes of it contain actual data, so let’s see what that looks like (via WireShark):bud-red-light-packet-inspection

Next Steps

So we’ve got an example of the data used to set off the Red Light, but we don’t really know what’s contained in that data.

Deep packet inspection isn’t really my thing, so at this point I’ve started asking around for possibilities. Here are the early contenders:

  • Use tcpreplay, Ostinato or some other application to “replay” sending of the packet shown above to the Red Light; maybe we don’t really even need to know what’s in the packet and this will set it off.
  • Find and use some other utility (or person!) that can tell us how to further decipher what’s in the data seen above.

If you’d like to help out, you certainly can! I’ve uploaded a zipfile of a PCAP file containing the packet I’ve displayed above. Feel free to try and dicipher or replay sending of that packet on your own! Please leave a comment if you do so; it’d be great to solve this for everyone.

Where all of my placeholder images come from

Years back, I happened upon fractalsponge.net, a one-man effort in creating extremely high resolution Star Wars renders of the various spacecraft in that fictional universe.

Checking Akamai cache expiry times on your website’s pages

This involves sending some custom headers along with your HTTP GET request, so utilize either the wget command line tool:

wget -S -O /dev/null --header="Pragma: akamai-x-cache-on, akamai-x-cache-remote-on, akamai-x-check-cacheable, akamai-x-get-cache-key, akamai-x-get-extracted-values, akamai-x-get-nonces, akamai-x-get-ssl-client-session-id, akamai-x-get-true-cache-key, akamai-x-serial-no" http://www.sportsnet.ca/

Or the curl command line tool:

curl -H "Pragma: akamai-x-cache-on, akamai-x-cache-remote-on, akamai-x-check-cacheable, akamai-x-get-cache-key, akamai-x-get-extracted-values, akamai-x-get-nonces, akamai-x-get-ssl-client-session-id, akamai-x-get-true-cache-key, akamai-x-serial-no" -IXGET http://www.sportsnet.ca/

The X-Cache-Key setting will contain the amount of time the URL is cached for; in this example, the time is 1 minute (“1m”):

X-Cache-Key: /L/370/77322/1m/www.sportsnet.ca/

Running Windows? No problem – grab a compiled version of wget for Windows.

Source: Stack Overflow – What’s the best way to troubleshoot Akamai headers these days?

Fast 404s for missing images in WordPress

If you’re looking to replace WordPress’s long load time for a 404 error page for at least the missing images on your website, consider adding the following to the .htaccess file that sits in the root of your WordPress installation airblown inflatables canada:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$
RewriteRule .* /wp-content/themes/your-theme/images/placeholder.png [L]

In practice, this looks something like:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_URI} \.(gif|jpg|jpeg|png)$ 
RewriteRule .* /wp-content/themes/your-theme/images/placeholder.png [L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Working with Nginx? No problem, here’s the equivalent commands that go into your site configuration file:

location ~* (jpg|jpeg|gif|png) {
	expires 30d;
	access_log off;

	error_page 404 /wp-content/themes/your-theme/images/placeholder.png;
}

Mark Lynas repudiates the anti-genetically modified crops movement

This is a blockbuster speech – in the link, there is a video of Mark Lynas making a speech to the Oxford Farming Conference confessing that he’s been quite wrong on opposing genetically modified crops for reasons of not much more than being obstinately anti-science/progress.

It’s an incredible eye opener, and peaks the hopes that environmentalists who deride others for being anti-science when it comes to climate change indulge in some humility and take a good look at if they themselves are being anti-science in another sphere (anti-GMO).

Mark Lynas – Lecture to Oxford Farming Conference, 3 January 2013

I want to start with some apologies. For the record, here and upfront, I apologise for having spent several years ripping up GM crops. I am also sorry that I helped to start the anti-GM movement back in the mid 1990s, and that I thereby assisted in demonising an important technological option which can be used to benefit the environment.

As an environmentalist, and someone who believes that everyone in this world has a right to a healthy and nutritious diet of their choosing, I could not have chosen a more counter-productive path. I now regret it completely.

So I guess you’ll be wondering – what happened between 1995 and now that made me not only change my mind but come here and admit it? Well, the answer is fairly simple: I discovered science, and in the process I hope I became a better environmentalist.

When I first heard about Monsanto’s GM soya I knew exactly what I thought. Here was a big American corporation with a nasty track record, putting something new and experimental into our food without telling us. Mixing genes between species seemed to be about as unnatural as you can get – here was humankind acquiring too much technological power; something was bound to go horribly wrong. These genes would spread like some kind of living pollution. It was the stuff of nightmares.

These fears spread like wildfire, and within a few years GM was essentially banned in Europe, and our worries were exported by NGOs like Greenpeace and Friends of the Earth to Africa, India and the rest of Asia, where GM is still banned today. This was the most successful campaign I have ever been involved with.

This was also explicitly an anti-science movement. We employed a lot of imagery about scientists in their labs cackling demonically as they tinkered with the very building blocks of life. Hence the Frankenstein food tag – this absolutely was about deep-seated fears of scientific powers being used secretly for unnatural ends. What we didn’t realise at the time was that the real Frankenstein’s monster was not GM technology, but our reaction against it.

Read More

Profiling a MySQL query to optimize performance

The Query Profiler in MySQL isn’t something I’ve spent much time in recently – with more sites making use of popular CMSes like WordPress, query performance isn’t something that’s top of mind anymore (Automatic seems to do a good job in this area). But it’s still a useful tool when you’ve already picked the low hanging fruit off of the optimization tree.

Profiling is enabled on an individual basis for each MySQL session; when the session ends, all profiling information is lost.

To check to see if profiling is currently enabled for your session, do:

mysql> SELECT @@profiling;
+-------------+
| @@profiling |
+-------------+
|           0 |
+-------------+
1 row in set (0.00 sec)

Next, enable profiling for all queries:

mysql> SET profiling = 1;
Query OK, 0 rows affected (0.00 sec)

And run the query you’d like to see a breakdown for:

mysql> SELECT COUNT(*) FROM wp_posts;
+----------+
| count(*) |
+----------+
|   238121 |
+----------+
1 row in set (18.80 sec)

Get the numeric ID of the profile we want to see:

mysql> SHOW PROFILES;
+----------+----------+---------------------------------------+
| Query_ID | Duration | Query                                 |
+----------+----------+---------------------------------------+
|        1 | 18.80000 | SELECT COUNT(*) FROM wp_posts;        |
+----------+----------+---------------------------------------+
1 row in set (0.00 sec)

Finally, actually see the query profiled:

mysql> SHOW PROFILE FOR QUERY 1;
+--------------------------------+-----------+
| Status                         | Duration  |
+--------------------------------+-----------+
| starting                       |  0.000027 |
| checking query cache for query |  0.000041 |
| checking permissions           |  0.000017 |
| Opening tables                 |  0.000018 |
| System lock                    |  0.000008 |
| Table lock                     |  0.000037 |
| init                           |  0.000014 |
| optimizing                     |  0.000008 |
| statistics                     |  0.000016 |
| preparing                      |  0.000013 |
| executing                      |  0.000008 |
| Sending data                   | 18.802902 |
| end                            |  0.000015 |
| end                            |  0.000008 |
| query end                      |  0.000006 |
| storing result in query cache  |  0.000453 |
| freeing items                  |  0.000009 |
| closing tables                 |  0.000007 |
| logging slow query             |  0.000007 |
| logging slow query             |  0.000031 |
| cleaning up                    |  0.000005 |
+--------------------------------+-----------+
21 rows in set (0.00 sec)

To get even more in depth, check out the optional type values for the SHOW PROFILE command, or use SHOW PROFILE ALL FOR QUERY 1; and view everything MySQL’s got at once.

Why the liberal arts are important: Learning to reflect

I hold a degree in computer science. I’ve been employed for 10+ years as a software developer. When the occasional news story comes out about liberal arts majors having trouble finding employment in today’s economy, there’s a part of me that feels smug. It says, “Yeah. All right. Go us. We made the right choice. We were rational about the job market.” And it is indeed very easy to indulge that part of myself by lapping up news that confirms my life choices.

But I’m also something of a contrarian. (Actually what’s probably more accurate is I hate to be wrong, so I feel compelled to understand the pro-arts side of the argument to prepare for it.) What is the appeal of the liberal arts in 2012? Are they necessary? In the end, I think my final position is that the liberal arts are important, and if a comparison must be done, they’re likely to  be more important than computer science or engineering. My reasoning: Engineering may allow us to live longer and better, but liberal arts let us find understanding in others and ourselves.

As evidence, I offer portions of a piece from 1997 by the late Earl Shorris. It’s about his attempt to teach a group of impoverished Americans about the humanities. It’s really quite profound and, I think, one of the only true ways to permanently solve poverty in the world. Enjoy the read.

Harper’s Magazine – On the Uses of a Liberal Education, Part II: As a weapon in the hands of the restless poor

We had never met before. The conversation around us focused on the abuse of women. [Viniece Walker]’s eyes were perfectly opaque—hostile, prison eyes. Her mouth was set in the beginning of a sneer.

“You got to begin with the children,” she said, speaking rapidly, clipping out the street sounds as they came into her speech.

She paused long enough to let the change of direction take effect, then resumed the rapid, rhythmless speech. “You’ve got to teach the moral life of downtown to the children. And the way you do that, Earl, is by taking them downtown to plays, museums, concerts, lectures, where they can learn the moral life of downtown.”

I smiled at her, misunderstanding, thinking I was indulging her. “And then they won’t be poor anymore?”

She read every nuance of my response, and answered angrily, “And they won’t be poor no more.”

“What you mean is—”

“What I mean is what I said—a moral alternative to the street.”

She didn’t speak of jobs or money. In that, she was like the others I had listened to. No one had spoken of jobs or money. But how could the “moral life of downtown” lead anyone out from the surround of force? How could a museum push poverty away? Who can dress in statues or eat the past? And what of the political life? Had Niecie skipped a step or failed to take a step? The way out of poverty was politics, not the “moral life of downtown.”

But to enter the public world, to practice the political life, the poor had first to learn to reflect. That was what Niecie meant by the “moral life of downtown.” She did not make the error of divorcing ethics from politics. Niecie had simply said, in a kind of shorthand, that no one could step out of the panicking circumstance of poverty directly into the public world.

Although she did not say so, I was sure that when she spoke of the “moral life of downtown” she meant something that had happened to her. With no job and no money, a prisoner, she had undergone a radical transformation. She had followed the same path that led to the invention of politics in ancient Greece. She had learned to reflect.

In further conversation it became clear that when she spoke of “the moral life of downtown” she meant the humanities, the study of human constructs and concerns, which has been the source of reflection for the secular world since the Greeks first stepped back from nature to experience wonder at what they beheld.

If the political life was the way out of poverty, the humanities provided an entrance to reflection and the political life. The poor did not need anyone to release them; an escape route existed. But to open this avenue to reflection and politics a major distinction between the preparation for the life of the rich and the life of the poor had to be eliminated.

Read More