Category Archives: WordPress

3 Reasons to use Interfaces in Object Oriented Programming

Although this is primarily a PHP/WordPress blog, this article should be instructive for most programming languages that support Object Oriented Programming. My hope is that it helps you decide to use Interfaces when writing your programming languages. Ultimately, this will help you write better code for yourself and for other developers.

Why use interfaces when writing Object Oriented code?

1. Better documentation

If all of your classes implement interfaces, your interfaces can contain documentation. If you use doc blocks for commenting and automatic documentation, this actually helps to generate comments on classes. Better still, interfaces create a set of instructions that are action-agnostic that allow programs to know exactly what kind of parameters are being requested and, in PHP 7+, exactly what kind of return value is going to be received. Documentation is an incredibly powerful feature that makes interfaces worthy of use all by themselves. But we aren’t done yet… It gets better.

2. Powerful way to conditionally inject dependencies

If you’re using Dependency Injection in your code, then interfaces make your job considerably easier. Because you can implement multiple interfaces on a single object, you can easily add a “UserInterface” with the methods setUser and getUser. In the back-end, you can set up a Factory like so:

class MyFactory
{
    private $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public static function getClass($classname)
    {
        $class = new $classname();

        if (!($class instanceof FactoryMember)) {
            return null;
        }

        if ($class instanceof UserInterface) {
            $class->setUser($this->user);
        }

        return $class;
    }
}

Crucially, this factory does not need to know whether a class has the UserInterface until it creates it. That means that this factory can store any class and auto-magically inject whatever is required.

3. Compatibility checking

If you take a look at the above code, you’ll see an additional interface, FactoryMember. In my example, I wanted to only create classes that implemented a FactoryMember interface. What’s in this interface? That’s up to you. There are cases where such an interface is blank, and you simply want to make sure that a class implements it for compatibility reasons.

In this case, you can think of an interface as also being an attribute of a class. Lets say you have Pet as a base class, with Cat and Dog as child classes. Here are some additional interfaces:

interface Furry {}

interface Playful {}

interface Shy
{
    function run();
}

Of the three interfaces above, only Shy has a method. That’s OK. Ultimately, these are attributes that help to describe pets. Now, you can write a custom message depending on the interfaces that an object has:

$dog = new Dog();

$msg[] = "You see a dog.";

if ($dog instanceof Furry) {
    $msg[] = "There's hair everywhere.";
}

if ($dog instanceof Playful) {
    $msg[] = "The dog's tail is wagging.";
} elseif ($dog instanceof Shy) {
    $msg[] = "The dog is shy and runs away!";
    $dog->run();
}

echo implode(" ", $msg);

Just like that, you’ve used interfaces to help you create a description of a dog. While you could implement each description as a method ($dog->getPlayfulMessage(), $dog->getShyMessage(), etc.), that may not always be desirable. If the messages change based on a situation (maybe when you pass a groomer, for example), then the interfaces can be a very quick way to determine attributes, and a compelling alternative to something like $dog->hasAttribute('hairy') when you’re building an application and don’t know how many methods you might want to call conditionally based on the attribute (aka, run for the Shy interface.

Conclusion

Programming with interfaces is not just a “best practices” convention. Like most best practices, it has a solid payoff for the developer who is willing and able to implement them. It not only allows for better documentation, but it also allows for more flexible use of design patterns and more inter-operable code. Finally, it enables a user to attach custom attributes that can grow with the application. For a little extra work at the beginning, interface programming will reap dividends as your codebase matures.

How and why to write Object Oriented WordPress plugins

Today I want to discuss an object oriented approach to plugin design that works no matter how small or large your plugin is going to become. Once I started doing this, I found it very difficult to return to the old way.

WordPress is… ahem… a “mature” codebase. It’s strength is not necessarily in its modern, lightweight design, but instead in its broad user base and ease of use. These two things are somewhat at odds, given how quickly programming languages evolve.

WordPress is fully compatible with PHP 5.2.9, which means that someone who set up a website 7 years ago at a cut-rate web host, will still get security updates, and, as of now, can still update WordPress to experience the latest and greatest core offerings (although maybe not the latest and greatest plugins) with no issue.

What’s changed between PHP 5.2.9 and now?

  • Introduction of Interfaces
  • Introduction of Namespaces
  • Anonymous functions
  • Anonymous classes

These are just to name a few.

And although PHP 5.2.9 does allow basic but solid object oriented programming techniques, WordPress has a developed enough codebase that a lot of WordPress is built with functions and global variables.

I don’t think you should follow their lead.

To illustrate the difference between the old “WordPress” way, and the new Object-Oriented way (which, in fairness, WordPress implements in many of its newer classes), take a look at these two code samples which do the same thing:


// Procedural
<?php
add_action('init', 'my_long_unique_hello_world_function');
function my_long_unique_hello_world_function() {
    echo "Hello World!";
    die();
}

add_action('admin_init','my_long_unique_admin_hello_world_function');
function my_long_unique_admin_hello_world_function() {
    echo "Hello Admin!";
    die();
}

// OOP
<?php
class My_Unique_Class {
    public function load() {
        add_action('init', array($this, 'init'));
        add_action('admin_init', array($this, 'admin_init'));
    }

    public function init() {
        echo "Hello World!";
        die();
    }

    public function admin_init() {
        echo "Hello Admin!";
        die();
    }
}

global $my_unique_class;
$my_unique_class = new My_Unique_Class();
$my_unique_class->init();

At first glance, the second example is much more verbose, so it’s probably a load worse, right? Granted, for an example with only one action hook, this is overkill. But most plugins do not have just one action hook. Most plugins have several.

And when you get to several action hooks, this becomes really, really helpful.

First of all, rather than having to write a very long function name for your action, you can often write exactly what it is. For example, in my classes, I try to add one function per action per class, so that the init hook always points to the class::init() method. This can make it easier for me to track down coding issues.

Second of all, you may have noticed my little global at the bottom. Because WordPress hasn’t offered a better solution, this is still unavoidable. However, it still dramatically reduces the amount of pollution many plugins would cause in the global scope. Remember, each function outside of a class is also part of the global scope! That increases the likelihood of collisions with other plugins.

Third, this allows you to make full use of object scoping, making things private and protected for internal use only. This may not seem like a big deal, but it can do wonders to remove your dependency on global variables. I’ve used this to build a number of plugins, a good example of which is a footnotes plugin, where each [cite] shortcode is added to a class property and printed as needed (Gist here). Is it strictly necessary to use classes to make something like this work? No. Does it make it a lot easier and dramatically reduce the chance for collisions? Yes!

There’s a lot more to love about Object Oriented programming, including Interfaces, Namespaces, and much more. I’m going to be diverging from the WordPress world to cover some of these concepts, but they should still apply pretty easily. Stay tuned!

Can’t Log In using HyperDB? Here’s how to fix it

I recently had an issue where a high availability server I was running with HyberDB and a master/slave relationship wasn’t letting me log in. I spent a lot of time digging around, and couldn’t see any issues. SHOW SLAVE STATUS on my MySQL replication server showed no errors either.

It turns out, the big issue was latency. WordPress seeks to verify your session after you’ve logged in. If you are verifying on a different server than the one from which you’re inserting, there is a chance that you may not actually get the data on time.

The solution? Add this to your db-config.php file:

/**
 * Add a sleep setting, to ensure that setting
 * cookies and all verification happens after
 * replication has already taken place.
 * If you replication is taking more than
 * 1 second, you may have a server latency issue.
 */
add_action('set_logged_in_cookie', function() {
    sleep(1);
}, 10, 0);

That should fix your issues.

Is WordPress/PHP Inherently Insecure?

I wanted to take the time to address something I hear all the time: WordPress is inherently insecure. Rather than bury the lead, I’m going to come right out and say that, no, WordPress is no more insecure than any other large-scale CMS in usage right now. There is a second question: Is PHP inherently more insecure than other web programming languages? Again, the answer is no. While PHP at one point spent no time considering security, many of the critiques of PHP security are no longer accurate.

Another, more honest answer to this question is: Yes, WordPress and PHP are both vulnerable to hacking. As is everything online. Make no assumptions about security. It is always possible to write bad code that leaves open a vulnerability. Instead of assuming security, understand how you can limit your exposure. And with WordPress and PHP, this is very possible.

So, let’s review, and deconstruct some common complaints about WordPress and PHP security:

#1 WordPress sites cannot be secured

I installed WordPress in a very large environment. The very first thing I did after switching the website to WordPress was review the logs. It may surprise some people that almost immediately I noticed automated attacks against the website. Of these attempts, any guesses to the percentage that were done against WordPress core? Bonus points, if you guess how many were done against plugins and themes that I had installed on my website.

The answer? 0. These vulnerabilities are all well documented and against themes and plugins that are no longer on the WordPress theme and plugin marketplace, or have been updated to address the underlying issue. The folks who contribute to WordPress put a lot of effort into making it easy to report vulnerabilities. In fact, when a vulnerability is discovered in WordPress Core, most websites receive a security update automatically. WordPress is so good at this that they backport updates to versions as old as 3.7 (as of writing this, 4.7 is being developed, and 3.7 is 3 years old. This is a more generous security support policy than PHP).

That’s not to say you’re secure! There are a lot more ways to make a WordPress site insecure than to keep it secure. Because most vulnerabilities are against plugins and themes, make sure you keep your plugins and themes updated. For many, it might be easier to enable automatic updates for plugins. The downside is that if a plugin introduces a new bug, it could cause an issue with your website. WordFence is a security plugin that warns you when your plugins are out of date, and is my favored approach. That way, you can test your plugin updates first.

#2 But if WordPress can be secure, why are WordPress sites hacked so often?

That’s simple: Because a plurality of websites online run on WordPress. I’m not going to get into numbers, because there are a lot out there. Suffice it to say that it’s the most popular CMS out there. Because it’s so easy that a user can set it up, there are many WordPress installs that are poorly set up. There are also a lot of cut-rate web hosts that offer WordPress because it’s free and popular, but they make no steps to update vulnerabilities. That means there are a lot of very, very old WordPress installs with very, very outdated plugins. This percentage may be higher than, say Drupal, or Django, but I am not convinced. Rather, the sheer number of outdated installs are higher.

The argument that other CMS’s are more secure reminds me of the old concept that Apple computers can’t be hacked. This was disproven as soon as Mac became widely used enough for it to be economically beneficial to discover exploits and take advantage of them. Meanwhile, Windows has recently had far fewer vulnerabilities than Mac or Linux. That is partially because of a long-fought struggle to become more secure after some very insecure releases, but partially because most websites run on Linux, and a lot more users are on Mac these days, including yours truly. In any case, I digress. The point is that WordPress exploits are created so often because it’s the biggest target. It also means that there’s a lot of white hat security reviewers out there who are constantly trying to stay ahead of the black hats.

#3 PHP is Inherently Insecure

I want to start by saying I’m not claiming PHP is the best web language. I am only addressing the core question of whether PHP is fundamentally more insecure than other languages.

This next two paragraphs are going to get technical. If you don’t understand it, that’s OK. Just let your eyes glaze over or skip them.

There was a time that PHP was primarily a webforms language run off of CGI. Its claim to fame was that it ran with very little special configuration, and could do web scripting very easily. It was a security nightmare. What’s worse, it was so easy to program that idiot hackers, like myself at the time, could write the worst code imaginable. What’s worst, is that it was difficult to write good code, because there was no object oriented programming. When PHP finally offered object oriented programming and eliminated some of the worst global variable threats (that made it possible to view and manipulate server variables), it still wasn’t great. The syntax was often ugly, scoping was brutal, etc. Want a MySQL query to run? Well, you’re asking for a great deal of trouble. SQL injection attacks were a constant concern, because there were no prepared statements.

PHP5 addressed many of these and other issues (while still leaving some unworked right now). And what PHP5 started, PHP7 is continuing.

How can you be hacked with PHP? Quite easily. Poorly written code and old code can still leave huge vulnerabilities. Just because you can write good code doesn’t mean you have to. Still, it is becoming harder to write bad code. Which is a good thing.

So… What can I do?

Ultimately, what you can do depends on your specific situation. Security should never be an afterthought, so read on and implement what you can. This could save you from an embarrassing, expensive, or business-destroying hack.

If you are on a hosted server:

  • Make sure you’re not going cut-rate. These days, you can find good hosting that keep their infrastructure updated and provide backups, GoDaddy ($8/mo with SSD storage) and InterServer ($8/mo with unlimited bandwidth/visitors).
  • For a little more money, WPEngine ($29/mo) offers excellent service, daily backups, and more. You still need to update your own plugins, and if you want more regular backups, you can use a plugin like Updraft Plus.

If you are self-hosting:

  • Make sure you get on a regular update schedule. Linux has received some bad publicity recently for very serious vulnerabilities, such as Dirty COW and POODLE. If you are running an old version of linux that doesn’t receive updates, or if you aren’t regularly applying updates, then you are asking to be hacked, and no matter how secure your PHP code and WordPress install are, you are very vulnerable.
  • Do not set your permissions to 777, or grwxrwxrwx. This means anyone who gains access to your server – absolutely anyone – can go in and delete your website, or get your MySQL username and password, or replace all of your uploaded images with porn and your uploaded files with viruses. Yes, you should be scared.
    • Set your permissions to 771 at most for web folders, and 664 at most for web files. That allows a web site to run, without allowing a user to do whatever they want. Ideally, your wp-config.php file (or wherever you store your passwords) should not have read permissions. If your file is owned by the Apache webserver (ex. www-data) then that should not break anything. But, test this before making the change live on your server.
  • Ensure you have a program like “fail2ban” installed, and configure it to monitor both web and SSH settings.
  • Use an SSH key, and disable password access.
  • If you have a static IP address, block port 22 everywhere except from that IP address.
  • There’s a lot more you can do – this is just the bare minimum. If you’re not sure what any of this means, do not self-host. If you get most of it, keep studying, and never assume you’ve figured it all out.

For Everyone

  • I will reiterate that plugin and theme updates are very important.
  • Do not keep plugins installed and deactivated. People will still be able to access these plugin files, so if there’s a vulnerability then they will be able to exploit it as long as it is on your system.
  • Install WordFence and follow reminders to update your plugins or WordPress core. Do this regularly to avoid old code becoming a vulnerability. Additionally, WordFence comes with a great firewall that blocks suspicious IP address logins.
  • If you don’t have regular backups on your server or through your host, install Updraft Plus or another backup plugin. I like Updraft Plus because it’s easy to set up and backs up straight to your Dropbox.
  • Do not install plugins that are not widely used without understanding what they do.
  • Do not install plugins that are not on the WordPress marketplace unless you are confident in the company’s commitment to updating their code for security.
  • Do not install plugins that are not under active development. If something goes wrong, you are going to be on your own in figuring out a replacement.
  • DO prefer plugins that have a wide user base. These plugins have a higher likelihood of remaining supported.

I hope I’ve made a convincing case that it is very possible to write good code in PHP, and to keep your WordPress installation protected, while making clear the large caveat that there is a LOT of bad code out there, and that, no matter how secure you aim to be, you are not 100% safe from being hacked. Even if you try to do everything right, we are fallible, and so the best code with any level of complexity will inevitably have a bug in it.

If you always assume there’s an exploit in your website, but keep yourself updated and select your plugins and theme carefully, you are likely no less vulnerable on WordPress than on any other CMS.

Do you have any security plugins/packages you like? Let me know! I’m learning how to keep my server more secure, just like everyone else.

How to Add a WordPress theme via composer with a Private GitLab Repository

I have been exploring using Composer for managing themes and plugins for WordPress. For public themes and plugins, this could not be easier using WordPress Packagist. However, I had a hard time finding a straightforward explanation for how to integrate a theme I am developing on a private GitLab repository.

It turns out that the solution is very simple. In your GitLab theme/plugin:

{
    "name": "<username>/<package>",
    "type": "wordpress-theme|wordpress-plugin",
    "require": {
        "composer/installers": "~1.0"
    }
}

Adding composer/installers as a require library allows you to set the type attribute to wordpress-theme or wordpress-plugin.

When you are including your theme/plugin in a composer file at your WordPress root, include these configurations:

{
    "repositories": [
        {
            "type": "git",
            "url": "git@gitlab.com:<username>/<package>.git"
        }
    ],
    "require": {
        "<username>/<package>": "<version>"
    }
}

Important: For a private repository, you need to add the private key beforehand by loading it into an SSH config file or using ssh-add.

Windows Users: I recommend using VVV for testing WordPress. If, however, you want to stick with Windows and a WAMP server, you can download Git-SCM and follow these instructions to add SSH keys. I was able to set up an SSH key when running Git Bash (not Git CMD). You can also run plink.exe by following the instructions.

Installing PHPBrew with VVV

VVV is awesome. For all its very impressive features, there are some things it doesn’t do (yet). One of those is run PHP 5.6, or PHP 7 (or, while we’re at it, older versions like PHP 5.3). PHPBrew makes this a walk in the park. If, that is, you use the right configurations and install the correct dependencies. I had a hard time finding a good step-by-step guide detailing missing dependencies and configuration options needed for PHPBrew. I’ve put one here to save others (and myself in the future) some time. And for those curious, many of these steps are helpful when installing on any Ubuntu dev server, not just VVV or WordPress.

Without further ado:

A Walkthrough for Installing PHPBrew on VVV

1. Install Dependencies

This was one of the most annoying things to discover. Every time I tried to install PHPBrew, it failed with a missing dependency.

On VVV, you can install these dependencies with the following command:

sudo apt-get install libxml2-dev libbz2-dev libmcrypt-dev libxslt-dev

2. Download & Install PHPBrew

Install PHPBrew using their recommended fashion (at least, as of March 2016, when this is written):

curl -L -O https://github.com/phpbrew/phpbrew/raw/master/phpbrew
chmod +x phpbrew
sudo mv phpbrew /usr/local/bin/phpbrew

And, as Lance Cleveland mentions in the comments, you should also type in:

phpbrew init

When this is complete, you can review available versions with phpbrew known. Here you will see a list of PHP versions, new and old. For example, I spotted the latest available version on phpbrew (again, as of March 2016), and installed it with options that are required for WordPress and VVV’s server configuration (note: cli is not strictly required, but I installed it so I could use WP-CLI):

phpbrew install 5.6.19 +default +fpm +mysql +cli

You can add other options, like +curl, for example.

Then, switch. I received a message which gave me a command that didn’t work, so here is the one that did:

phpbrew switch 5.6.19

Or whichever version you are installing.

3. (Optional) Install extensions

If you’re looking for xdebug, a feature that comes standard on VVV but gets overwritten with a new version of PHP, you can add the extension with:

phpbrew ext install xdebug stable

You can install APC and Memcache similarly, if you need to test it.

If you’re looking for any additional configuration options, there are a good number, as well as some helpful hints. These are not WordPress specific, so rather than try to copy them all, take a look at PHPBrew‘s web page, which has a lot of documentation.

I hope this helps you as much as it would have helped me when beginning my PHPBrew adventure.

Addendum

For a non-VVV server install, I needed to include these dependencies for Ubuntu as well when I installed PHP 5.3:

sudo apt-get install libreadline-dev libicu-dev

Your Guide to VVV

VVV, or Varying Vagrant Vagrants, is a tool which will make your life as a WordPress developer infinitely easier. After I learned about it at WordCamp NYC‘s Contributor Day, I found myself drawing a blank as to how I survived WordPress development without it.

Here are a few of my favorite features of VVV:

  • Install once, add as many WordPress websites as you want.
  • Extensions are available. Josh Lee, a WordPress extraordinaire I met at the event, told me about vv. This allows you to create WordPress installations on-the-fly.
  • Basic installation includes Stable, Developer, and Trunk so you can easily test your themes on the newest version of WordPress
  • Uses vagrant-hostsupdater and creates easy to remember host names for your base installations. I used to do this on my local machine, but this is better.
  • Built on Ubuntu. I love my Mac, but BSD is not the same as Linux, and my server runs Linux. I can use it the same as I use vagrant by simply typing `vagrant ssh`, and I can make any modifications that might exist on my server.
  • Like Vagrant, it is FREE and can run on almost any machine. All you need is VirtualBox.

So, how can you get started? VVV has made it very easy. Simply follow the instructions on GitHub and you’re good to go!