Reminder: Don’t Use the Short PHP Open Tag

Jetpack 2.0.1 was released last night, immediately followed by 2.0.2, which fixed a fatal error on some hosts, caused by a short PHP open tag. So here’s a reminder: never use the short form of the PHP opening tag:

<? _doing_it_wrong(); ?>

Always use the long form:

<?php _doing_it_right(); ?>

If your grep can do Perl regular expressions, you can search your entire codebase with a negative lookahead like this:

grep --include=*.php -rP '<\?(?!php|xml)' *

Joseph Scott has a simpler example that works without the -P flag. If you’re building WordPress themes, the Theme Check plugin will scan your theme for short tags automatically. Plugin Check will do the same thing for your plugins.

Stay safe.

Don’t Be Shy to Use sprintf with WordPress

Don’t be shy to use the printf and sprintf functions with WordPress. It makes code much easier to read. Take a look at the following examples.

echo '<a href="' . get_permalink() . '" class="link">' . get_the_title() . '</a>';

It looks quite dirty and it’s very easy to miss a quote or double-quote. Here’s one that looks a lot cleaner and easier to read:

printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title() );

And here’s a slightly less clean, but more secure example:

printf( '<a href="%s" class="link">%s</a>', esc_url( get_permalink() ), esc_html( get_the_title() ) );

You might think escaping the permalink and the post title is not necessary, and you’re right. However, it’s considered best practice to escape as late as possible, which is often right before the output. Here’s a more complex example, taken from the Twenty Twelve theme:

$date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a>',
    esc_url( get_permalink() ),
    esc_attr( get_the_time() ),
    esc_attr( get_the_date( 'c' ) ),
    esc_html( get_the_date() )
);

It also makes use of argument swapping, which is very common when working with translation functions, mainly because RTL languages would need to swap things around. It’s also very convenient to read when there are two or more placeholders.

You can learn more about sprintf (with a bunch of cool examples) in this article, and about escaping and data validation right here.

Thanks for reading and have a great day!

How To: Show Off Your Social Counters in WordPress

You know it’s all about social these days, and this post is about showing off how social you are on your WordPress website. I’m sure you’re using tonnes of social networks and all of them have friends, followers, fans and subscribers metrics, but let’s start from simple: Twitter, Facebook and RSS.

We’ll write code in this post, and you may ask me why. Of course there are loads of copy-paste javascript widgets available, but the first problem I encountered with those is they’re all different! What we’re going to do here is grab the numbers on the server, so then you’ll be able to display them however you like, with your own icons and captions.

I wrote a couple of posts on this topic last year:

We’ll be using some of those snippets in our code today, together with a few additions for Twitter followers count and RSS subscribers too. We will also adapt these to WordPress. Okay, enough talk, let’s get to the coding!


Icons Credit: Drink Web 2.0 by Bruno Maia

Twitter Followers Count

This one’s quite simple, since the Twitter API allows a non-authenticated call to public users. Assuming we’ve got JSON functions available (PHP5 or JSON Services in PHP4):

public function get_twitter_followers_count( $screen_name ) {
	if ( false === ( $followers = get_transient( 'twitter-followers-count' ) ) ) {
		$response = wp_remote_get( "http://api.twitter.com/1/users/show.json?screen_name={$screen_name}" );

		if ( is_wp_error( $response ) ) {
			$followers = 91;
		} else {
			$json = json_decode( wp_remote_retrieve_body( $response ) );
			$followers = $json->followers_count;
		}
		set_transient( 'twitter-followers-count', $followers, 60*60*24 );
	}
	return $followers;
}

As you can see I’m using the Transients API to cache the followers count for 24 hours, this reduced the load on the hosting server and serves pages faster. I’ll be using transients for Facebook fans and RSS subscribers too.

Line 5 might seem a little strange, we’re explicitly setting followers to 91. We do that when there’s an error with the API call so that we don’t show off a zero-count. You can go forward and extend it to double-cache values with a get_option and set_option call so that 91 is actually a figure retrieved from Twitter API and not hard-coded. But that’s extra, I’m fine with 91 ;)

The rest seems straightforward — we parse the response using json_decode and grab the followers count. If you’re into grabbing something else, go ahead and inspect the $json object using print_r, there’s so much interesting stuff there ;)

When the followers count is in our hands, we set a transient for it, so that next time it is served from cache, and finally return the count. Simple as that ;) The usage is easy — just pass a screen name to the function and you’ll get the results, as long as it is not a protected profile.

RSS Subscribers Count

As I already mentioned, transients will be used here as well, same method. Additionally we’ll be using Feedburner’s Awareness API. In order for that to work you’ll have to have your RSS feed setup with Feedburner and the Awareness API activated. Take a look at the “AwAPI Activation and the FeedCount Chicklet” section following the link above.

public function get_rss_subscribers_count($feed_url) {
	if (false === ($subscribers = get_transient('rss-subscribers-count'))) {
		$feed_url = urlencode($feed_url);
		$response = wp_remote_get("http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri={$feed_url}&dates=" . date('Y-m-d', strtotime('-2 days', time())));

		if (is_wp_error($response)) {
			$subscribers = 97;
		} else {
			$body = wp_remote_retrieve_body($response);
			$xml = new SimpleXMLElement($body);

			$status = $xml->attributes();

			if ($status == 'ok') {
				$subscribers = $xml->feed->entry->attributes()->circulation;
			} else {
				$subscribers = 98;
			}
		}

		$subscribers = (int) $subscribers;
		set_transient('rss-subscribers-count', $subscribers, 60*60*24);
	}
	return $subscribers;
}

As you can see, we’re fetching the RSS feed data using the feed URL via an HTTP request to the Feedburner API. The Awareness API returns an XML object, which is then parsed using the Simple XML methods. The circulation attribute is the one we’re looking for — it indicates the approximate subscribers count.

Again, I’ve hard-coded the 98 figure there for fallback purposes, you might want to extend it. The date magic simply asks Feedburner for stats of two days ago, since it sometimes yields 0 for “today” and “yesterday”. Could be changed according to your Feedburner stats if that matters.

Finally, we’ve set the transient and returned the subscribers count, voila. Usage: pass on your Feedburner feed URL to get_rss_subscribers_count(), an integer is returned.

Facebook Fans Count

Last but definitely not least — Facebook. We’ll use the Facebook PHP SDK, I’m using version 2.1.2 which seems to be the latest stable at the time of writing. We’ll be using the Graph API way, so no more FQL queries please. Here’s the code:

public function get_facebook_fans_count($page_name) {
	if (false === ($fans = get_transient('facebook-fan-count'))) {
		require_once("facebook/facebook.php");
		$facebook = new Facebook(array(
			'appId' => 'your-application-id',
			'secret' => 'your-application-secret'
		));

		$graph_obj = $facebook->api("/{$page_name}");
		$fans = $graph_obj['fan_count'];

		set_transient('facebook-fan-count', $fans, 60*60*24);
	}
	return $fans;
}

Note, that unlike the old-fashioned way, the Graph API uses your application ID, not your API key. You can obtain these when registering a new application at the Facebook Developers page. There’s a button that says “Set Up New App” which takes you through the rest of the process.

So once your app is in place, credentials are fine and the connection is good, we use facebook’s api method to request for a page name. Try “mashable” for example.

The returned Graph object contains quite a lot of stuff, including the number of fans. Use print_r on $graph_obj to learn more. So the fan count is obtained, a transient is saved, and the number is returned.

Conclusion

Note that if you’re going to use these for different profiles, you’ll have to change the names of your transients to include that data, otherwise there will only be one cache. I kept the code as simple as possible here, but I’ve illustrated the extra stuff in the final source that I did. I also wrapped these up in a single class called $social, I know it’s too generic for WordPress, but I’m not writing a plugin out of this (yet). The source could be downloaded right here. Feel free to use and extend the code with your own methods for other social networks and services.

Okay well, thank you so much for reading and retweeting this, oh and by the way…

Question: what other 3-5 services would you like to get your numbers from?

Happy 2011: In 10+ Different Programming Languages

The end of the year 2010 is near so I’ve prepared this post for all you coders, developers and other geeks. You know when you build applications (especially web applications) you often leave a copyright notice on every page saying “Copyright 2010, All Rights Reserved” or whatever? Right, but what developers tend to forget is that time passes by and that they have to go back and change 2010 to 2011 in January — so we often browse websites, especially in January and February that have last year’s copyrights.

The best trick is not to hardcode the year inside your templates and skins, but to write the current year dynamically using date functions, so below is a list of printing out the current year in 10 different programming languages.

And here’s a list of ones contributed by commentators:

Continue reading

October Quickie: A Little Bit of Everything

Well yeah, it started snowing today here in Moscow, but this post is not about snow. I remember I’ve done some quickie before, but couldn’t find it. Perhaps it was something I mentioned inside the blog post with a different title. But anyways, this is a short roundup of what I’ve been up to lately.

Let’s start with Python.. After reading a very popular book called Programming Collective Intelligence by Toby Segaran (review coming later), I had no choice but to peek at how Python is doing. I didn’t carry out much of the excercizes in the book while reading it, but I did run a few experiments afterwards. Some of the code examples were translated into PHP to immediately implement into my Twibots project, the juice was left for later.

This weekend I decided to gather some data from the Twitter Streaming API for some experimental purposes, and I decided to do this in Python. Of course I hadn’t had much time to read good books (still waiting from Amazon), but the plenty online tutorials, guides and articles out there are quite okay. So with a little trial and error I managed to write a script which gathers a little over 10,000 tweets in 30 minutes and dumps them into a database. That’s 20,000 tweets an hour, ~ half a million tweets a day. What am I going to do with those? I’ll give you an insight on this project a little bit later ;)

Twitter. I finally got #newtwitter. I thought it was a joke. It’s not a secret that I have multiple Twitter accounts, but I use them for development purposes, and guess what, those accounts were switched to the new Twitter three weeks before my account was. So yeah, I’m a little mad at Twitter, but their new look really rocks. They also need some updates to their mobile version.

.NET MVC. Some of you might be wondering (or not) what happened to that .NET MVC project of mine. Well it’s 99% finished, but we’re constantly coming up with changes to the content part, switching images around and other dirty work. Latest comment from the client was – okay so I open up Safari, click View and check the Zoom Text Only option. Then I zoom in and the whole design breaks! You guys promised me nice-looking XHTML in Opera, Safari, Chrome, IE and Firefox, what the heck?

PHP. I wrote an app in PHP that allows me to turn off my PC from my iPhone. I extended it to include volume up/down features a few days later. These are the kind of apps you write when you’re lazy ;)

And finally some goodies from all around the web for web designers and developers:

That’s it for today. Cheers!

A 60-Day Trip from PHP to .NET MVC

This is quite an unusual post I guess, something that came in to my mind a few days ago. If you’re familiar with my biography you know I’m in love with php, unix and the open source world. The reason I’m writing this post (or maybe set of posts) is that I found quite a good client, who’s very strict about technology, so the very basic website that they’re looking for should be written in .NET in a little less than two months.

I haven’t finished the whole project yet, but I’d like to give you a short overview of .NET MVC from a PHP developer’s perspective, as well as share some coding thoughts in general. Don’t treat me as a Microsoft hater though, I love what they’re doing, and there are a bunch of very rich web applications driven by Microsoft’s technology! But since I’m used to what I’m used to, I feel a little bit weird and disappointed.

Why did I pick MVC? Well, perhaps because it’s quite new compared to the rest, and a bit of a challange since I don’t have any friends familiar with this monster. So the only places to find help are Google and Stackoverflow. MSDN is pretty much useless, especially the localized versions.

There are several reasons why I called .NET MVC a monster, and here’s a short list based on the first few weeks of my experience:

  • Too many abstractions (week 1)
  • No SQL code at all (week 2)
  • Models are built using drag ‘n drop (week 3)
  • Name conventions are silly (week 3)
  • Confusing (week 4)

Getting used to LINQ

I started my trip by exploring the MVC Music Store Tutorial on the ASP website, which gives quite a clear overview of how to setup a basic website structure, handle some user input and work with the database using LINQ. Wow, I never thought SQL was so complicated that they had to reinvent it. I’ve seen some abstractions over SQL (PDO, Zend_Db) but LINQ is something different:

var shop = (from s in db.Shops where s.Slug == id select s).First();
var workingHours = (from m in shop.ShopMetas where m.Key == "working-hours" select m.Value).ToList();
var comments = (from c in db.Comments orderby c.PublishDate descending select c).Skip(page * 5).Take(5).ToList();

Third line shows my implementation of pagination on a page full of comments. Groups and joins are even more “fun”. I came across a handy resource for studying LINQ called Hooked on LINQ with an awesome section called 5 minute overviews.

But anyways, quoted from Wikipedia: Some benchmark on simple use cases tend to show that LINQ to Objects performance has a large overhead compared to normal operation.

Haven’t tested, haven’t benchmarked, maybe it’s different. But from what I’ve seen, same old SQL is under the hood. Now, a few words about models.

Building Models and Relations

We all know MVC doesn’t go around without models, yet, I never thought models could be designed using only your mouse! I was quite surprised when I saw the models being generated from a database schema in the Music Store tutorial, yet, that’s not as deep as it goes. More interesting is inheritence, mapping, foreign keys and relations, all this using only your mouse! I felt kinda dumb, really. For a second I thought this was programming for kids, but hey, it really makes life simpler! Kudos to Microsoft ;)

Visual Studio Data Model

Worth mentioning is that there’s a flag called Singularize model names when building models from a database schema, which converts the Shops table to a Shop model, a Comments table to a Comment model, (quite cool this one) a News table to a News model, and a (surprise) Movies table to a Movy model.. Whaa? ;)

Next is something that took me quite some time to sort out, so to save you that time, I’ll give you a quick tip.

The Master View

Master views are cool, but according to Google, one of the most frequently asked questions by .NET MVC newbies is “how on earth do I pass data into my master view”? Yup, I asked that question too, but didn’t get too much responses. So here’s a newbie response (how I see it): Master views are very similar to normal news, so they need data passed by a controller. You can go ahead and pass the same data for the master view with each and every controller that you create, but it would be difficult to manage, you need something more centralized.

So the answer would be to create an abstract class (OOP, remember?) which would derive from the standard Controller class, then change your controllers to derive from your newly created class. Easy as that:

public abstract class ApplicationController : Controller
{
    public ApplicationController()
    {
        // This is how you pass some data to your master view
        ViewData["my-key"] = "my value";
    }
}

Then make sure you derive your controllers from the new ApplicationController. Here’s my Home controller:

public class HomeController : ApplicationController
{
    public ActionResult Index()
    {
        return View(viewModel);
    }
}

Note that I dropped the namespace for both code pieces of code to make them shorter. The namespace used is MyApplication.Controllers. Let’s switch over to the actual Master view and here’s how you capture the data:

Response.Write(ViewData["my-key"].ToString());

That wasn’t very difficult, was it? You can pass all the data/objects you want in ViewData as well as run LINQ queries inside the Application Controller for your sidebar widgets, menus and other stuff that comes from the database.

Well folks! That’s about it. I’ll keep you posted on my experience in .NET MVC but honestly, I’m getting tired of it already, can’t wait to ride home and get my hands back onto php ;) Thanks for reading and sharing!