Fixing Drush to work with Custom Drupal modules

I’ve mentioned that I consider Drush to be an absolutely essential tool if you’re running more than one Drupal site.  However, I recently ran across an issue that took a little while to figure out.  First of all, the latest update to Firefox seems to have broken something in the FCKEditor module.  I may talk about that later, but it’s not the main point here.  The fix is to disable FCKEditor, and switch to the newer CKEditor.  Using Drush, that’s a simple matter of two commands

1
2
drush disable fckeditor
drush enable ckeditor

However, when trying to run Drush, I got the following error:

1
Drush command terminated abnormally due to an unrecoverable error.

That’s right, Drush wouldn’t even run.  It turns out that the problem was caused by a custom module that I had written for the site that does a redirect.  When Drush accessed the Drupal core, it was being redirected to a static page, which caused it to barf.  So, I needed to figure out a way to make sure the redirection doesn’t happen if the request is being made by Drush.  I tried for quite a while to use the Apache $SERVER global to check the request origination, but I just couldn’t figure out what the value should be to check for Drush.

What I finally settled on was checking for the existence of one of Drush’s methods.  Due to the way that php operates in Drupal, once a method (function) is defined, it’s essentially a global function (Drupal’s not object oriented, so there’s no real concept of access modifiers).  So simply making the following check fixed the issue:

1
2
3
4
5
if(function_exists('drush_main')){
  //don't redirect
}else{
  //redirect
}

Easy!