Latest Entries »

A bug in Apple’s code for exchaning SSL keys has been found and published. Even when you only take a quick look the issue here is pretty clear.

The code is implementing a bunch of if-statements followed by only a sinlge action each time. In C -as well as PHP- you don’t have to wrap a lonely action into curly brackets – as you would have to when you’re dealing with more than one.

Though it’s a known best practice to always wrap your code into such curly brackets, no matter how silly you think this is, you can see this kind of laziness all the time.

The problem is that as soon as you’re adding more code you might not see what still belongs to if-statement and what doesn’t.

And this is what happend here: At some point the SSL code always jumps to a sub routine and doesn’t even execute any code below that.

opensource.apple.com-20140224-0805


if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
        goto fail;
        goto fail;

What should have been written instead was either


if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {
        goto fail;
        goto fail;
}

in which case everything would have been just fine. Or


if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0) {
        goto fail;
}
        goto fail;

in which case the bug would still be there but would have been found much easier since it’s clear that the second goto fail running on its own.

To me it looks like this has been a simple copy/paste mistake. It’s not Apple specific by any means but I think it’s great if you can argue by pointing to such a prominent reference!

Again and to sum it up: Always wrap your conditionals into curly brackets!

Related Links

I’ve heard this question at least a million times now: How do I sort a custom query or a category list just the way I want it?

I’ve actually written a little helper function ages ago. And I’m aware there are other ways but this one works just fine in almost every case.

Just add this function to your theme’s function.php or your plugin code:


/**
 * Sorts a WordPress result array by custom criterias
 * Works for all kinds of results that are arrays of the form $result[0]->memberVariable1 etc.
 *
 * By Chris Doerr (http://wordpress.org/support/profile/zenation)
 *
 * @param   array   $results    WordPress results
 * @param   string  $by         Member variable to sort by.
 * @param   string  $order      (optional) 'desc' for 'descending', everything else will be treated as 'ascending'
 * @return  array               The newly sorted results array.
 */
if( !function_exists( 'sortWPResults' ) ) {
  function sortWpResults( $results, $by, $order = 'asc' ) {

    $by         = strtolower( $by );

    $orderComp  = ( strtolower( $order ) == 'desc' ) ? ' -1 : +1' : ' +1 : -1';

    usort( $results, create_function( '$a,$b', 'return ( $a->' . $by . ' > $b->' . $by  . ' ) ? ' . $orderComp . ';' ) );

    return $results;

  }
}

“WordPress results” can be a lot of things: Custom queries (WP_Query), get_post(), get_the_category(), to name just a few. A demo usage could then be something like

$categories = sortWpResults( get_the_category(), 'slug', 'asc' );

which would get a list of all categories, sorted by the SLUG (not name!).

Software Versioning

There are many, many ways for naming versions of your software but only a few that really make sense to me. And I’m not saying this in an absolute term but with a specific idea in mind.

As a developer you will (or at least should) track your code with version control software like Git, Mercurial, SVN, etc. These applications have their own way to generate version numbers which are usually far from being intuitive, like generating random hashes.

If you would write your own software that only you would ever use this might already be enough. But as soon as there are multiple persons involved, people outside your developer circle, offering a human readable version number is a must.

There are basically three groups of target audiences that require that approach:

  1. Third-party developers
  2. Software/Usability testers
  3. Customers, users, admins

It’s been a trend lately to kinda pervert the versioning system by increasing the numbers so fast that they lose all the abilities to get at least some information other than “this version seems to be newer than the other”. The web browsers Chrome and Firefox are shiny (negative) examples of that! I would highly recommend either getting rid of version numbers completely or using a system that can make sense to almost everyone.

By far, the most common versioning pattern is {full version}.{feature}.{bug(fix)}({stage})

So when you update from version 1.2.0 to 1.5.2 you can immediately see that a few features have been added (or were being removed) and even some bug fixes have already been made. Or if you’re about to install 1.5.3b you should be aware that this software is still in a beta stage and that it might not be working 100% at this point. And so on and so on.

Often developers struggle with how to assign what number for what achievement. And there also seems to be a fear of making full version releases. When you take look at directories like WordPress.org/extend/plugins/ you will see a vast number of software that might even be out there for years that never seems to have reached version 1.0! It’s only my personal opinion but I think that’s just stupid. Maybe some developers think that a software still being a 0.5.22 is a better excuse if something’s wrong (“Dude, it’s not even the final version!”). But if you would take the term “final” literally that’ll be the stage of your software when it’s no longer being developed at all or supported. That’s ‘final’!

When you start a new software project you should do some planning ahead. And one part of that process is to make a list of features or functionalities that you think the first public release should have. Every software has a purpose and this core can be expected to be working when someone is installing your software.

So what I do is to rank the features in terms of importance and other dependencies and assign a number to each of them. So until the software is being released, the {full version} number will be 0 and the {feature} number will increase according to the number of finished features. If each feature of your list has been implemented you can do a major round of testing and documentation etc and if that’s also done, you can (and should) release version 1.0.

From here on, you can either react on feedback (bug reports and feature requests) or implement some new ideas by increasing the {feature} and {bug(fix)} numbers to an open end. And if you make some major changes like to the architecture or you’re implementing some new bigger features you might think (twice) about going for a new {full version} number.

Just as a reminder: Version numbers are not necessarily for you and your team of developers but for all the other people out there. So make them as clear and understandable as possible!

Other Versioning Patterns

So why are there even other patterns if the one mentioned above is meant to be so great? Well, other patterns have other intentions, simple as that.

For example, when using {yy}.{mm}.{dd}.{n} you can instantly see when a release has been made. This might be handy if you know that your environment has changed at some point in time. Or you can see when product has not been updated in ages – which then might be a good indicator that it’s not being supported any longer.

You can also combine these two aspects to a certain extend by adding the release year to your product name or starting the {full version} number with the year but keeping the rest as mentioned above.

And if you can be sure that the version number won’t matter to the average Joe or Jane you can get a bit more technical and include build numbers (which of course also depends on the type of programming you’re using).

So to draw a resume: Think about how you what the versioning should communicate and to whom this might be useful and don’t be clever about it, simplicity’s king here!

Programming Fonts

In September of last year (2012) Adobe released a free font that was especially created for software developers. Not only do I like the new font, called “Source Code Pro”, the blog post that went along with the publishing (http://blogs.adobe.com/typblography/2012/09/source-code-pro.html) was interesting to read, too.

I know a thing or two about fonts and typography (I highly recommend the documentary “Helvetica”!) and I even bought a book about this topic a while ago. But I’m far from being an enthusiast, especially when it comes to “new fonts” – mainly because there are way too many blog posts like “20 hottest fonts for X and Y”.

But like many things in life, you sometimes have a feeling about something being good or bad but you can’t put the finger on it why exactly to you it is. But the blog post is giving a nice, brief introduction to what’s important about a font developers use in a terminal application or an IDE, for example.

Well, the most obvious criterion might be that certain characters should be distinct so you wouldn’t confuse them with each other, like the letter i, l and also the | character (like in the OR operator ||) or the letter O and the digit 0 (zero). For example, the Adobe font has a little dot inside the digit 0 which might not be, well, beautiful but it definitely helps a lot!

Also all the different kinds of brackets (curly, round, square) should be distinct and so on and so on…

Maybe it’s just a personal taste but for example, I prefer the asterix to be centered, not superscript. And last but not least, and since code indention is an important part of creating clean code that’s easy read, the font type should be a monospace type.

“Source Code Pro” can be downloaded on the Adobe website so you can install it in your operating system but -and I really like that option a lot- it’s also available as a webfont (via Adobe Typekit as well as Google Web Fonts) so you can style your HTML <code> blocks, too.

What’s nice about PHP (among other things) is that code blocks can easily be nested inside the HTML of a page. This way you in insert dynamic content just like that. Of course you can also go the other way and echo out HTML via PHP.

My simple rule is: When you have a clear overweight of one or the other use this as your main code and nest-in the other.

This makes source code way more readable than, for example, when you have orgies of opening and closing PHP tags inside “some” HTML tags!

Let me give you an example (do you recognize where it’s from?).

Original Code

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<div>
<?php the_content('Read the rest of this entry &raquo;'); ?>
</div>
<?php endwhile; ?>
<?php else : ?>
 <b>Not Found</b>
<?php _e("Sorry, but you are looking for something that isn't here."); ?>
<?php endif; ?>

Cleaned up code

<?php
if( have_posts() ) {

  while( have_posts() ) {
    
    the_post();

    echo "<div>\n";

    the_content( 'Read the rest of this entry &raquo;' );

    echo "</div>\n";

  }
}
else {
  
  echo "<b>Not Found</b>\n";
  echo __( 'Sorry, but you are looking for something that isn't here.' );

}
?>

Well, I’ve also done some more formatting (according to my coding standard) and replaced the (in my mind) horrible and old-school : ENDIF ENDWHILE grammar. But you get my point, right?

When you’re writing new code, always keep that in mind. And if you’re refactoring old (legacy) code this cleaning up should be your absolute first step!

It’s pretty common behavior to use the $ symbol (variable) as a shortcode instead of always writing “jQuery”.

But other JS libraries use this character as well. And sooner or later this might cause some weird and nerve-wracking-to-find bugs. And even if you’re not using other libraries at the moment, who says you won’t in the future…

To avoid potential conflicts you can simply decalare a local (scope) variable inside your document-ready block and then you’re good to go:


jQuery(document).ready(function(){
  var $ = jQuery;
  ...
});

And if you’re starting by selecting a certain element, you can speed up things checking its existence before letting the parser run all your code:


jQuery(document).ready(function(){

  var test = $('#myElement');

  /* if the element does not exist, don't even bother running the rest of the code... */
  if( test.length < 1 ) {
    return;
  }

  ...

}

To get rid of a WordPress plugin you basically have 2.5 choices:
1. Deactivate the plugin in the backend
2. Uninstall the plugin via the link in the backend
2.5 Simply delete the plugin’s folder on your server

Best Practice: Create and then make use of the uninstall.php

For the most cases, 2.5 is kind of the worst way to handle this. Yes, the plugin “core” files will be deleted and even WP will recognize that the plugin has been removed.

But many plugins will also leave tracks behind in your database and maybe even files in other locations as well. “But I’m not saving anything in the database!”… Does your plugin has options? See!

WP does offer the usage of a dedicated function to handle an uninstall operation but it is recommended using a separate file, uninstall.php (in your custom plugin directory). Maybe it’s because of staying compatible to lower versions or it’s just in order to stay true to the principle of “separation of concerns”. I haven’t actually looked that up because to me it doesn’t even matter.

Simply create the PHP file and treat it like it was a script on its own and that only contains all your uninstall routines. Meaning: Don’t expect anything to be available. E.g. if you want to run custom SQL queries you should make the database object available by declaring it “global”.

gloabl $wpdb;

WP functions are, of course, available since the uninstall.php (if exists) will be included into the WordPress application code at some point.

While you’re developing a theme or a plugin you should have this uninstall.php ready and always enter routines in parallel to your development cycle.

So, for example, if you’re introducing a new plugin option in your plugin code

add_option( 'someExtraOption', 'someExtraValue', '', 'no' );

also write the uninstall code at the same time

/* Remove Option 'someExtraOption' */
delete_option( 'someExtraOption' );

Also make sure to also delete files that are stored outside your theme or plugin directory!

There a many scenarios where plugins and themes can or even should have options to customize certain behaviors. WordPress provides a bunch of functions to easily handle these options for you:

  • add_option( 'option_name', 'option_value', '', '(autoload this option)yes/no' );
  • update_option( 'option_name', 'opttion_value' );
  • get_option( 'option_name' );
  • delete_option( 'option_name' );

A bad and very unefficient approach would be to store your options in simple key/value pairs like add_option( 'option_name', 'option_value', '', 'yes' );

Best Practice: Only create ONE option variable but make an ARRAY

 
 $customOptions = array( 'option1' => 'value1, 'option2' => 'value2', ...);
 add_option( 'myAwesomePluginSlug', $customOptions, '', 'no' );
 

Not only does this lead to much cleaner code, it also saves db requests and resources.

When you’re reading options by using the WP function get_option( 'iHaveTheChoice' ) you will hit the database each time you call this function. Even when your db server will cache recurring requests this is not very efficient.

The simple solution: Instead of storing only one value in one option (field), save all your options in one multidimensional array like

$customOptions = array( 'option1' => 'value1, 'option2' => 'value2', ...);

and then let WP store this whole array:

update_option( 'myAwesomePluginSlug', $customOptions );

WordPress stores plugin and theme options in -who would have thought- the “options” table. There, the options data will all be stored in one field only.

To do this, the array is being serialized so it actually looks like one specially formatted string.

When you then load your options $myOptions = get_option( 'myAwesomePluginSlug' ); you’ll only receive one dataset that WP, kindly enough, will even unserialize so your result is an array again.

This approach also has another advantage: Only having one ‘option_name’ to store all your options makes it very easy and robust when it comes to deleting options, respectively uninstalling plugins and themes. But this will be the topic of a following post…

I’m for sure far from being a perfect coder. But I’ve seen lots of sleazy 3rd party WordPress code lately and so I decided to start a little series: Best Coding Practices for PHP in general and WordPress in particular. Most of this stuff is acutally just about NOT being lazy but being DISCIPLINED.

Best Practice: ALWAYS check before declaring new functions, including classe files, or defining constants.


// Constant
if( !defined( 'ROBOST_CONSTANT' ) ) {
  define( 'ROBOST_CONSTANT', 'anAbsolutePathNameForExample' );
}

// Function
if( !function_exists( 'myShinyFunction' ) ) {
  function myShinyFunction() {
  }
}

// Class file containing class declaration
if( !class_exists( 'myImpressiveClass' ) ) {
  include_once( ROBOST_CONSTANT . '/myImpressiveClass.php' );
}

Class Files

Especially when you’re writing WordPress plugins and you don’t want them to depend on other plugins/code you might end up delivering classes that maybe are already in use in other plugins – but maybe they’re not. You just can’t know that for sure. Which, again, is the reason you want to include them in your plugin package.

including_once() won’t help because this PHP function only checks if an absolute file location has already been included. (You know that relative paths will be resolved into absolute paths internally, right?). So if the same class is located in different files and/or in different locations it won’t count as “once” and therefore being included, again.

Functions

I’m not a big fan of declaring too many function because you easliy run into the problem of giving them names that are “human readable” and descritive but still unique. Also, testing functions can be a bit tricky. So in most cases, putting functions inside of an object context should be the better solution.

And it’s mainly because of the naming horror that you should always use function_exists() before declaring your own functions. But of course, the scenario as described for using classes – including the same function in multiple WordPress plugins – also applies here.

Constants

Constants are not the best way to make data globally available. For once, you will blow up your system because they will always stay in your runtime-memory even if they’re not in use. And you also have to remember all the names – and there already are A LOT of constants to remember!

I’m not sure how exact this is but when I run echo count( get_defined_constants() ); in my first plugin to be loaded (more on the loading order in WordPress in another post), I get the impressive number of 1347 constants!!!

So if you’ve decided you need to define a constant you should check if the name is not already taken. Even more, when you want to use a constant that hasn’t been defined by YOU, you should also always check if this constant even exists. That alone makes the usage quite complicated.

But I know that when you’re developing with a framework like WordPress you will end up using (existing) constants every now and then. So to minimize the effort you should apply the principle of “dependency injection” (also, more on that in a later post) and then pass on references to that constant instead.

The standard function for including a navigation in WP 3.x is to call the function wp_nav_menu(). But sometimes you might not be fully satisfied with the code that WordPress is generating.

Depending on what you had in mind it might be enough to use the configuration array and, for example, wrap the menu in a custom DIV container.

But I recently had a scenario where a customer was using the WordPress MultiLanguage Plugin WPML and also wanted to include little icons for the menu items.

To keep the number of HTTP requests as low as possible I suggested using a CSS sprite (one big image that includes all the icons and their different states).

But this lead to another problem: When WordPress is generating a menu it generates menu item IDs according to their content ID (like a page ID, link ID or category ID). When you only have one menu it won’t be a problem. But when you’re using WPML and have many different menus (in this case 1 menu for each of 10 languages) you end up getting a very large amount of different IDs you have to style via CSS.

This particular site I was building had one advantage though: The menu structure stayed the same in each language version. So I decided to generate my own menu item IDs with a new custom plugin, after the simple pattern “p” for parent item and “c” for child item, combined with am ongoing position number. For example: id=”p1-c4″ would be the 4th child item of the 1st parent item and so forth.

With this new kind of “global” ID it would be possible to only once style an “absolute” menu item, no matter what language menu version is currently being pulled.

To inject those new IDs it was necessary to hook into the menu generating process. And luckily, WordPress has a nice little class for this already in place, called “Walker” (http://codex.wordpress.org/Function_Reference/Walker_Class)

A walker object can be included in the configuration array that’s being used to call wp_nav_menu() and will then be run while generating the menu.

To create a custom walker you have to create a new class that’s extending from the original walker class:

class MyCustomWalker extends Walker {}

By extending from the original you inherit 4 methods that you can overwrite (re-define) and use to customize a menu: start_lvl(), end_lvl(), start_el() and end_el().

What WordPress does is that it gets the menu (hierarchy) from the database and then decides for each item what to do if the current item level is different from the one before.

For example: If the previous item level (or “depth) was 1 and the current is 2, the current item is (most probably) meant to start a sub-menu for the previous item. If the current level is one and the previous was 2, the previous item seems to be the last one of a sub-menu and the current item is “a next” parent item, etc.

In general, a WordPress menu is nothing but a nested, unordered HTML list, like:

<ul>
 <li>Parent Item 1
  <ul>
   <li>Child Item 1-1</li>
   <li>Child Item 1-2</li>
  </ul>
 </li>
 <li>Parent Item 2</li>
 <li>Parent ITem 3
  <ul>
   <li>Child Item 3-1</li>
   <li>Child Item 3-2</li>
  </ul>
 </li>
</ul>

(public) start_lvl() is being called when a new <ul> is being started (the first and overall wrapping <ul> not counting!)

(public) end_lvl() is being called when a list is being closed again </ul>

(public) start_el() is being called when a new item is being started <li>

(public) end_el() is being called when an item is being closed </li>

But remember: You still have to produce the list and list-item HTML code! And start/end_lvl does not include the overall wrapping <ul> elements. These can be customized by using the configuration array for wp_nav_menu().

The arguments for these functions are documented in the codex and are mostly a string to output the HTML, the current element and its depth (level).

A nice way to simplify the output flow is to call the output string by reference, not by value. You then can add you newly generated output to this string. E.g.:


start_lvl( &$output, $depth ) {
  $output .= str_repeat( ' ', $depth ) . "<ul>\n";
}

In my case, I implemented some additional methods and member variables to do the parent/child detection and counting and then a method for generating the custom HTML ID attribute.

When your new class logic has been written and tested you can implement it into the wp_nav_menu() call like this:


$myCustomWalkerObj = new MyCustomWalker();
wp_nav_menu( array( 'Walker' => $myCustomWalkerObj ) );

Typically the wp_nav_menu funcion is being placed inside a theme file, like the header.php

But some premium themes, like Genesis, offer their own hooks so you don’t even have to touch the theme code. I like this approach a lot because this way, you can still update the theme without getting into trouble.

I also like this Walker class a lot and I can only recommend playing around with it. With some additional class logic this can be a very powerful tool.

Follow

Get every new post delivered to your Inbox.