Phil Brown's Web Development Blog

Base64 encoded SVG gradient backgrounds in LESS

So, CSS3 gradients are cool. Sure, you need to use a couple of different vendor prefixes but the syntax is pretty nice

.my-gradient {
    background: -moz-linear-gradient(top, #00b7ea 0%, #009ec3 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#00b7ea), color-stop(100%,#009ec3)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #00b7ea 0%,#009ec3 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #00b7ea 0%,#009ec3 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, #00b7ea 0%,#009ec3 100%); /* IE10+ */
    background: linear-gradient(to bottom, #00b7ea 0%,#009ec3 100%); /* W3C */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00b7ea', endColorstr='#009ec3',GradientType=0 ); /* IE6-8 */}

The only caveat here is the filter declaration for IE. You’re limited to a straight top-to-bottom linear gradient (no multi-stops) but more importantly, the gradient background will overflow any border radius you may have defined.

No problem, IEs 7 and 8 don’t support border-radius anyway but what about IE9? The solution…

SVG background images

The standard SVG gradient background definition looks something like this

<?xml version="1.0" ?>
<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">
  <linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="0%" y2="100%">
    <stop offset="0%" stop-color="#00b7ea" stop-opacity="1"/>
    <stop offset="100%" stop-color="#009ec3" stop-opacity="1"/>
  </linearGradient>
  <rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" />
</svg>

You can then base64 encode this and set it as a data URI background image which will work beautifully in IE9. For example

background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2l...);

Doing it with LESS

I’ve been using LESS lately and was almost going to move to SASS + Compass in order to achieve the above but found a way to stick with LESS. Enter the base64DataUriBackground mixin. This can be made very simple if your LESS parsing environment has access to the btoa() function.

.base64DataUriBackground (@encode, @type: ~"image/svg+xml") {
    @dataUriPrefix: ~"url(data:@{type};base64,";
    @dataUriSuffix: ~")";
 
    // with btoa()
    @b64DataUri: ~`(function(a,b,c){return a+btoa(b)+c})('@{dataUriPrefix}','@{encode}','@{dataUriSuffix}')`;
 
    // without
    @b64DataUri: ~`(function(a,b,c){function e(a){a=a.replace(/\r\n/g,'\n');var b='';for(var c=0;c<a.length;c++){var d=a.charCodeAt(c);if(d<128){b+=String.fromCharCode(d)}else if(d>127&&d<2048){b+=String.fromCharCode(d>>6|192);b+=String.fromCharCode(d&63|128)}else{b+=String.fromCharCode(d>>12|224);b+=String.fromCharCode(d>>6&63|128);b+=String.fromCharCode(d&63|128)}}return b}function f(a){var b='';var c,f,g,h,i,j,l;var m=0;a=e(a);while(m<a.length){c=a.charCodeAt(m++);f=a.charCodeAt(m++);g=a.charCodeAt(m++);h=c>>2;i=(c&3)<<4|f>>4;j=(f&15)<<2|g>>6;l=g&63;if(isNaN(f)){j=l=64}else if(isNaN(g)){l=64}b=b+d.charAt(h)+d.charAt(i)+d.charAt(j)+d.charAt(l)}return b}var d='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';return a+f(b)+c})('@{dataUriPrefix}','@{encode}','@{dataUriSuffix}')`;
 
    background: @b64DataUri;
}

Here’s an example gradient mixin

.gradient (@gradient-top, @gradient-bottom) {
    @svg: ~'<?xml version="1.0" ?><svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none"><linearGradient id="grad-ucgg-generated" gradientUnits="userSpaceOnUse" x1="0%" y1="0%" x2="0%" y2="100%"><stop offset="0%" stop-color="@{gradient-top}" stop-opacity="1"/><stop offset="100%" stop-color="@{gradient-bottom}" stop-opacity="1"/></linearGradient><rect x="0" y="0" width="1" height="1" fill="url(#grad-ucgg-generated)" /></svg>';
 
    .base64DataUriBackground(@svg);
 
    background: -moz-linear-gradient(top, @gradient-top 0%, @gradient-bottom 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,@gradient-top), color-stop(100%,@gradient-bottom)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, @gradient-top 0%,@gradient-bottom 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, @gradient-top 0%,@gradient-bottom 100%); /* Opera 11.10+ */
    background: -ms-linear-gradient(top, @gradient-top 0%,@gradient-bottom 100%); /* IE10+ */
    background: linear-gradient(to bottom, @gradient-top 0%,@gradient-bottom 100%); /* W3C */
    filter: ~"progid:DXImageTransform.Microsoft.gradient( startColorstr='@{gradient-top}', endColorstr='@{gradient-bottom}',GradientType=0 )"; /* IE6-8 */
}

One final thing you will need to do is disable the filter declaration for IE9 (and above). You can achieve this simply through a conditional stylesheet

<!--[if gte IE 9]>
  <style type="text/css">.my-gradient-class{filter: none;}</style>
<![endif]-->

All CSS examples courtesy of the most awesome Ultimate CSS Gradient Generator.

Where’s my Front Controller?

I’ve been spending a bit of time on StackOverflow lately and have even earned myself a bronze “Zend Framework” badge.

One thing I continually see in questions surrounding the bootstrap process and resource plugins is this…

protected function _initSomething()
{
    $front = FrontController::getInstance();
 
    // and so on

This is not the right way to fetch the Front Controller. For starters, at this stage it may not have been bootstrapped, meaning options supplied via configuration may not have been applied.

Following the Zend Application – Theory of Operation – Dependency Tracking documentation, this is the correct method…

protected function _initSomething()
{
    $this->bootstrap('FrontController');
    $front = this->getResource('FrontController');
 
    // and so on

The same logic applies to any required resource; Bootstrap it first then fetch it from the application container. Simple.

Awesome Pagination with ZF, Paginator, AjaxContext and the HTML5 History API

One of my favourite components in Zend Framework is the AjaxContext action helper. This little beauty allows you to intercept AJAX requests and deliver a different view based on request parameters, all without touching a single line of action code.

One scenario where this has always appealed to me is in paginating data. Why reload an entire document each time you page through a dataset when you can use AJAX to fetch just the next page.

Now introduce the HTML5 History API, and all of a sudden you’ve got AJAX data updates with navigable, bookmarkable URLs.

In this article, I’m going to step through creating a paging controller action that updates the paged data via AJAX and maintains URL location for browsers that support the History API.

If you want to play along at home, all code used in this demo is available on github, with each stage represented by its own branch. Get the code at https://github.com/philBrown/Awesome-Pagination-Demo and checkout the “html-only” branch

git clone git://github.com/philBrown/Awesome-Pagination-Demo.git
cd Awesome-Pagination-Demo
git checkout -b origin/html-only

To start with, we have a vanilla ZF project with a layout and simple controller action that instantiates a paginator object (using the array adapter for this demo), grabs the “page” parameter from the request and assigns the paginator to the view.

public function indexAction()
{
    $paginator = Zend_Paginator::factory($this->getModels());
    $paginator->setCurrentPageNumber($this->getRequest()->getParam('page', 1));
    $this->view->paginator = $paginator;
}

Our view then displays the paginationControl helper

<?php $paginationControl = $this->paginationControl(
    $this->paginator, 'All', '_partials/paginator.phtml') ?>
 
<div class="pagination-control">
    <?php echo $paginationControl ?>
</div>

and a table with our data, looping over each item in the paginator.

What we end up with is something like this

Clicking on each paginator link loads an entirely new page with the requested data. Not horrible, but could be better.

Now checkout the “ajax-loading” branch

git checkout -b origin/ajax-loading

Our layout now includes the inlineScript helper with a link to jQuery on the Google CDN. The controller now initialises the AjaxContext helper to allow “html” AJAX requests for the index action.

public function init()
{
    $this->_helper->ajaxContext->addActionContext('index', 'html')
                               ->initContext();
}

The view has also been changed. We’ve added a link to our pagination JavaScript file (more on this later) and the guts of the view (pagination controls and data) has been moved into a new file index.ajax.phtml which is referenced using the render method.

// index.phtml
<?php $this->inlineScript()->appendFile('js/paginator.js') ?>
 
<div class="paged-data-container">
    <?php echo $this->render('index/index.ajax.phtml') ?>
</div>

The index.ajax.phtml file is the one delivered via the AjaxContext helper when an XMLHTTPRequest is intercepted with the “html” format parameter present. Including it in the default template caters for the first page load.

Now on to our JavaScript file. All this file needs to do is catch click events on any of the paginator links and fetch the contents via AJAX, repopulating the paginator controls and data.

In essence, it looks like this.

jQuery(function($){
    $('.pagination-control').find('a').live('click', function(){
        var link = $(this);
        var container = link.parents('.paged-data-container');
        $.get(link.attr('href'), { format: 'html' }, function(data){
            container.html(data);
        }, 'html');
        return false;
    });
});

We’re using the “live” binding as each AJAX load replaces the paginator controls. The { format: 'html' } parameter is added to the request to trigger the right context switch in the controller.

So now we have a basic AJAX paginator. The only problem here is that each page loads under the same URL. There’s also little visual feedback to let the user know the data is changing.

Taking a leaf out of GitHub’s “Tree Slider”, if you checkout the “ajax-loading-animations” branch, you’ll see some nifty left (next) and right (previous) scrolling.

So now we come to the final stage, utilising the HTML5 History API to add stateful URLs for each AJAX data load.

Checkout the master branch to see the code.

The gist of this is to use the history.pushState method to add history records on click and bind an event handler to the “popstate” event to catch navigation (back / forward) button presses.

The end result looks like this – http://apps.philipbrown.id.au/awesome-pagination/

Whilst it’s certainly not as snazzy as GitHub’s Tree Slider, it’s a step in the right direction.

LabelFor helper with custom text

It’s been a long time between posts and as evidenced by the new category, I’ve been busy.

Of late, I’ve been really getting into the .NET MVC framework and for some things, it’s been an absolute wonder. For others, I’d love to point the developers to some Zend Framework features.

In keeping with the tradition of blogging about things that I discover in my day-to-day development work, I’d like to contribute this little snippet of code that’s come in very handy for me.

The LabelFor helper in .NET MVC gives you a nice, easy way to set a strongly typed label for your model properties. One problem though, you can’t set the label text.

Whilst you can use the [DisplayName] component model attribute, this doesn’t help if say, your model is part of a collection and needs a unique label. It also feels a bit odd putting presentation data in the model but that’s just me.

So here’s my very simple override

public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, string text)
{
    string propertyName = ExpressionHelper.GetExpressionText(expression);
    TagBuilder label = new TagBuilder("label");
    label.SetInnerText(text);
    label.MergeAttribute("for", helper.ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName));
    return MvcHtmlString.Create(label.ToString());
}

Enjoy.

Zend Framework and Doctrine Part 1

I’ve begun to investigate the Doctrine ORM library and how to integrate it into Zend Framework applications. I figure this post and any subsequent ones on the topic can grow into some sort of discovery series.

So, my first post is going to be a simple one – bootstrapping with Doctrine 1.2.

I figured the most robust and consistent way to get Doctrine into my applications was to create an application resource plugin so without further delay, here it is.

// library/Tolerable/Application/Resource/Doctrine.php
 
class Tolerable_Application_Resource_Doctrine extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @var Doctrine_Manager
     */
    protected $_manager;
 
    /**
     * @var Doctrine_Cache_Interface
     */
    protected $_cacheDriver;
 
    /**
     * @var string|array
     */
    protected $_cache;
 
    /**
     * @var array
     */
    protected $_connections = array();
 
    /**
     * Set cache options
     * 
     * @param string|array $cache
     * @return Tolerable_Application_Resource_Doctrine
     */
    public function setCache($cache)
    {
        $this->_cache = $cache;
        return $this;
    }
 
    /**
     * @return string|array
     */
    public function getCache()
    {
        return $this->_cache;
    }
 
    /**
     * Set connection configuration
     * 
     * @param array $connections
     * @return Tolerable_Application_Resource_Doctrine
     */
    public function setConnections(array $connections)
    {
        $this->_connections = $connections;
        return $this;
    }
 
    /**
     * Initialise and return Doctrine_Manager instance
     * 
     * @return Doctrine_Manager
     */
    public function getManager()
    {
        if (null === $this->_manager) {
            $manager = Doctrine_Manager::getInstance();
            $manager->setAttribute(Doctrine_Core::ATTR_MODEL_LOADING,
                                   Doctrine_Core::MODEL_LOADING_CONSERVATIVE);
            $manager->setAttribute(Doctrine_Core::ATTR_VALIDATE,
                                   Doctrine_Core::VALIDATE_ALL);
            $manager->setAttribute(Doctrine_Core::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
            $manager->setAttribute(Doctrine_Core::ATTR_AUTOLOAD_TABLE_CLASSES, true);
            $manager->setAttribute(Doctrine_Core::ATTR_USE_DQL_CALLBACKS, true);
            $manager->setAttribute(Doctrine_Core::ATTR_AUTO_FREE_QUERY_OBJECTS, true);
 
            if ($cacheDriver = $this->_getCacheDriver()) {
                $manager->setAttribute(Doctrine_Core::ATTR_QUERY_CACHE, $cacheDriver);
            }
 
            $this->_manager = $manager;
        }
        return $this->_manager;
    }
 
    /**
     * Initialise and return query cache driver if configured
     * 
     * @return Doctrine_Cache_Interface|null
     */
    protected function _getCacheDriver()
    {
        if (null === $this->_cacheDriver) {
            $options = $this->getCache();
            if (empty($options)) {
                return null;
            }
 
            if (is_array($options)) {
                if (!array_key_exists('driver', $options)) {
                    throw new Zend_Application_Resource_Exception('Missing Doctrine cache driver');
                }
                $driver = $options['driver'];
                unset($options['driver']);
            } else {
                $driver = (string) $options;
                $options = array();
            }
 
            if (!class_exists($driver)) {
                Zend_Loader::loadClass($driver);
            }
 
            $this->_cacheDriver = new $driver($options);
        }
        return $this->_cacheDriver;
    }
 
    /**
     * Initialise any configured connections
     * 
     * @return void
     */
    protected function _initConnections()
    {
        foreach ($this->_connections as $name => $options) {
            if (!is_array($options)) {
                $options = array('dsn' => $options);
            }
 
            if (array_key_exists('charset', $options)) {
                $charset = $options['charset'];
                unset($options['charset']);
            } else {
                $charset = 'utf8';
            }
 
            // Attempt to find "dsn" or "connection_string" keys
            // falling back to an array of connection options
            if (array_key_exists('dsn', $options)) {
                $adapter = $options['dsn'];
            } else if (array_key_exists('connection_string', $options)) {
                $adapter = $options['connection_string'];
            } else {
                $adapter = $options;
            }
 
            $connection = $this->getManager()->openConnection($adapter, $name);
            $connection->setAttribute(Doctrine_Core::ATTR_USE_NATIVE_ENUM, true);
            $connection->setCharset($charset);
        }
    }
 
    /**
     * Initialise and return Doctrine manager
     * 
     * @return Doctrine_Manager
     */
    public function init()
    {
        $this->_initConnections();
        return $this->getManager();
    }
}

This class provides a reusable component to use in any ZF 1.8+ application. To enable the plugin, add the following to your application.ini file.

; Add the Doctrine and Tolerable namespaces to the autoloader
autoloaderNamespaces[] = "Doctrine_"
autoloaderNamespaces[] = "Tolerable_"
 
; Add our custom application resource plugin path to the plugin loader
pluginPaths.Tolerable_Application_Resource = "Tolerable/Application/Resource"

Configure the Doctrine query cache (if desired)

; Simple examples, no driver options
resources.doctrine.cache = "Doctrine_Cache_Apc"
 
; or with options
resources.doctrine.cache.driver = "Doctrine_Cache_Apc"
resources.doctrine.cache.option = ...
resources.doctrine.cache.option = ...
resources.doctrine.cache.option = ...

See here for drivers and options.

Configure the connections

; Simple connection strings
resources.doctrine.connections[] = "mysql://user1:pass@localhost/db1"
resources.doctrine.connections[] = "mysql://user2:pass@localhost/db2"
 
; or specify connection name and options
resources.doctrine.connections.default.dsn     = "mysql://user1:pass@localhost/db1"
resources.doctrine.connections.default.charset = "utf8"
 
; or specify Doctrine connection parameters
resources.doctrine.connections.default.scheme = "mysql"
resources.doctrine.connections.default.user   = "user1"
resources.doctrine.connections.default.pass   = "pass"
resources.doctrine.connections.default.host   = "localhost"
resources.doctrine.connections.default.path   = "db1"

This is assuming that your custom (Tolerable in these examples) and Doctrine libraries are under your application’s “library” path. If not, simply add them to the application’s include path configuration, for example

includePaths.library = APPLICATION_PATH "/../library"
includePaths.doctrine = "/path/to/doctrine/lib"
includePaths.custom = "/path/to/custom/library"

A lot of the code in the plugin has been taken from Matthew Weier O’Phinney’s blog post on Autoloading Doctrine and Doctrine entities from Zend Framework.

2009-11-19 Update

Some extra inspiration came from Juozas Kaziukenas’ post on Zend Framework and Doctrine. Part 2 as well as the twitter-verse and now the plugin handles multiple connections and caching.

Overriding Zend form element default decorators, for good!

I’m sure everybody who has used Zend_Form has, at one time or another, wished they could change the default form element decorators in one fell swoop, simply and efficiently.

Up until now, I’ve been using one of two methods to override the default “definition list” style; set each element’s decorator scheme on instantiation or, use the form’s “setElementDecorators” method to reset the scheme for nominated elements. No longer!

Using just a few simple classes, I’ll show you how to permanently alter the default decorator scheme, thus simplifying your code and making it ultimately more flexible.

For the following example, I’ll assume a decorator scheme like the following

form
  fieldset
    ol
      li
        label
        element
      li
        button

Lets start by extending Zend_Form_Element. I’d also like to take this opportunity to introduce my new “Tolerable” library.

// library/Tolerable/Form/Element.php
 
class Tolerable_Form_Element extends Zend_Form_Element
{
    /**
     * Load default decorators
     *
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }
 
        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('ViewHelper')
                 ->addDecorator('Errors')
                 ->addDecorator('Description', array('tag' => 'p',
                                                     'class' => 'description'))
                 ->addDecorator('Label', array('requiredSuffix' => ' *'))
                 ->addDecorator('HtmlTag', array('tag' => 'li',
                                                 'id'  => $this->getName() . '-element'));
        }
    }
}

Don’t forget to add your library namespace to the auto loader

; application/configs/application.ini
 
autoloaderNamespaces.1 = "Tolerable_"

Zend_Form_Element_Submit also needs some treatment

// library/Tolerable/Form/Element/Submit.php
 
class Tolerable_Form_Element_Submit extends Zend_Form_Element_Submit
{
    /**
     * Default decorators
     *
     * Uses only 'Submit' and 'li' decorators by default.
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }
 
        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('Tooltip')
                 ->addDecorator('ViewHelper')
                 ->addDecorator('HtmlTag', array('tag' => 'li'));
        }
    }
}

We’ll also need to provide our own display group class to support the desired scheme

// library/Tolerable/Form/DisplayGroup.php
 
class Tolerable_Form_DisplayGroup extends Zend_Form_DisplayGroup
{
    /**
     * Load default decorators
     * 
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }
 
        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('Description', array('tag'   => 'li',
                                                     'class' => 'group_description'))
                 ->addDecorator('FormElements')
                 ->addDecorator('HtmlTag', array('tag' => 'ol'))
                 ->addDecorator('Fieldset');
        }
    }
}

as well as a custom form class

// library/Tolerable/Form.php
 
class Tolerable_Form extends Zend_Form
{
    /**
     * Default display group class
     * @var string
     */
    protected $_defaultDisplayGroupClass = 'Tolerable_Form_DisplayGroup';
 
    /**
     * Constructor
     *
     * Add custom prefix path before parent constructor
     *
     * @param mixed $options
     * @return void
     */
    public function __construct($options = null)
    {
        $this->addPrefixPath('Tolerable_Form', 'Tolerable/Form');
        parent::__construct($options);
    }
 
    /**
     * Load the default decorators
     *
     * @return void
     */
    public function loadDefaultDecorators()
    {
        if ($this->loadDefaultDecoratorsIsDisabled()) {
            return;
        }
 
        $decorators = $this->getDecorators();
        if (empty($decorators)) {
            $this->addDecorator('FormElements')
                 ->addDecorator('Form');
        }
    }
}

Now that we’ve laid the way for our custom decorator scheme, there’s only one item remaining and I can’t say that I’m proud but hey, it works.

All front facing (HTML) Zend form elements extend the empty, abstract class Zend_Form_Element_Xhtml. We’re going to override this class in its current form. This method works well if the Zend Framework is not in the application’s “library” which should have a higher “include path” setting than the framework itself. Otherwise, you’ll just have to override the existing Zend Framework file.

// library/Zend/Form/Element/Xhtml.php
 
abstract class Zend_Form_Element_Xhtml extends Tolerable_Form_Element
{
}

That’s it. Get ready to start writing leaner, meaner forms

$form = new Tolerable_Form;
$form->addElement('text', 'foo', array(
    'label'    => 'Foo',
    'required' => true
))->addElement('textarea', 'bar', array(
    'label'    => 'Bar'
))->addElement('submit', 'submit_btn', array(
    'label'    => 'Submit'
))->addDisplayGroup(
    array('foo', 'bar', 'submit_btn'),
    'baz',
    array('legend' => 'My Form')
);

Roundcube 0.3-stable on PHPsuExec hosts

I’ve been using Roundcube as my webmail client since the early alpha days and was happy to see the recent release of 0.3-stable. I did have to tweak some PHP configuration items so, for the benefit of other Roundcube users, here’s how to get it up and running on a PHPsuExec enabled host.

As outlined in a previous post, I created my custom configuration file under /home/user/etc/php.d/roundcube/custom.ini using the php_flag and php_value properties from the Roundcube .htaccess file.

display_errors              = Off
log_errors                  = On
upload_max_filesize         = 5M
post_max_size               = 6M
memory_limit                = 64M
 
zlib.output_compression     = Off
magic_quotes_gpc            = 0
zend.ze1_compatibility_mode = 0
suhosin.session.encrypt     = Off
 
session.auto_start          = 0
session.gc_maxlifetime      = 21600
session.gc_divisor          = 500
session.gc_probability      = 1
 
mbstring.func_overload      = 0

This file is then merged into the server configuration file as /home/user/etc/php.d/roundcube/php.ini.

Then you just need to edit the Roundcube .htaccess file and add

SetEnv PHPRC /home/user/etc/php.d/roundcube

PHP suExec and custom php.ini files

Lately, I’ve noticed more and more shared web hosts making the switch to running PHP under suExec. The benefits of this are:

  • PHP scripts run as the owning user
  • No more file system permission juggling
  • Scripts are generally sandboxed to the owner’s home directory

Unfortunately, this poses a problem for any custom PHP configuration changes as the usual .htaccess php_flag and php_value properties are no longer supported. The recommended method of setting a custom configuration is to place a php.ini file under each directory where required.

This method works fine for any properties set in the custom php.ini file however there appears to be one devastating omission. Server configuration properties do not cascade into the custom file. What this means is that for any property not set in your custom file, PHP will revert to the PHP default.

For example, say your host has enabled PDO (as any decent host should). The instant you introduce a custom php.ini file, PDO will be lost. Sure, you could just include the relevant extension_dir and extension properties but consider this example (from my host)

extension_dir = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613"

That property is awfully specific and your custom entry wouldn’t fare too well in the event of an upgrade.

In a perfect world, the host would have compiled PHP with the --with-config-file-scan-dir=/some/dir option that allows an environmentally settable directory to be scanned for additional config files. Unfortunately, this is rarely the case.

My solution is a little hacky and hardly perfect but it certainly gets the job done for me.

1. Create your custom.ini file with the options you want. Mine is /home/user/etc/php.d/custom.ini and looks like this

register_globals = Off
magic_quotes_gpc = Off

Do not name this file php.ini.

2. Locate your host’s php.ini file. This information is available from phpinfo(). In the below examples it is /usr/local/lib/php.ini

3. Add a cron job to create a full php.ini file in a location of your choosing (/home/user/etc/php.d) that is the concatenation of the server php.ini file and your custom.ini file. The below example is set to run hourly with any errors displayed on stdout which should be mailed to the crontab owner.

0 * * * * /usr/bin/test -f /usr/local/lib/php.ini && /bin/cat /usr/local/lib/php.ini /home/user/etc/php.d/custom.ini > /home/user/etc/php.d/php.ini || echo '/usr/local/lib/php.ini NOT FOUND'

The reason for the cron job is to keep your full, custom php.ini file in sync with any server changes. The job will also inform you in the unlikely event that the host php.ini file is moved.

If you’ve got shell access, you can create this file immediately by running

cat /usr/local/lib/php.ini /home/user/etc/php.d/custom.ini > /home/user/etc/php.d/php.ini

otherwise, wait for the hour to come around in which case your cron job should have done the work for you.

4. Add the following to your web application’s .htaccess file

SetEnv PHPRC /home/user/etc/php.d

The PHPRC environment variable informs any PHP scripts of the location of the preferred php.ini file.

Enjoy.

Editor themes for Eclipse PDT – Obsidian

My PHP IDE of choice is Eclipse with the PDT plugin.

The thing is, I always feel a little snow blind after a day’s coding, staring at that white screen all day. So much so that I’ve undertaken the arduous task of tweaking my colour preferences to match the Obsidian theme found in the more recent versions of Notepad++. Why Eclipse can’t take some lead from Notepad++ and Aptana and make this process much easier, I don’t know but here’s the end result.

PHP file with Obsidian theme
PHP file with Obsidian theme

Mixed PHP and HTML file with Obsidian theme
Mixed PHP and HTML file with Obsidian theme

I’ve also created some preference files so you can play along at home. Please note that whilst I’ve made sure the preference files only contain colour data, I’ve only done minor testing but so far, everything has gone well. My setup is Eclipse Galileo with PDT 2.1 however I don’t think there’s any version specific stuff in the files.

To install the colour preferences:

  1. Download one of the below packages and extract the contents to a temporary directory
  2. Fire up Eclipse
  3. Backup your current preferences by going to File -> Export -> General -> Preferences. Follow the instructions from there to create a preferences file. Make sure you choose “Export all”.
  4. Go to File -> Import -> General -> Preferences and select the Obsidian/eclipse.epf file. Click “Finish”

I’ve also included some Aptana colourisation files for CSS and JavaScript however I haven’t yet created preferences for other Aptana editors.

Enjoy and keep watching for more themes.

Obsidian.tar.gz
Obsidian.zip

Extending Zend Framework Application Resource Plugins

With the arrival of Zend Framework version 1.8 came the application resource plugins. These nifty little classes help bootstrap your application’s resources (views, layouts, database connections, etc). The default behaviour is suitable for most needs however, occasionally, you’re going to want to perform some extra functionality.

Take for example the following use case – the standard DB resource plugin instantiates a database connection based on supplied parameters and registers it with Zend_Db_Table_Abstract::setDefaultAdapter(). What if you want to register the connection in the Zend_Registry as well? You could create a bootstrap method (_initRegistry() for example) and pull the adapter out of Zend_Db_Table_Abstract or you could simply extend the resource plugin.

// library/My/Application/Resource/Db.php
 
class My_Application_Resource_Db extends Zend_Application_Resource_Db
{
    public function init()
    {
        if (null !== ($db = $this->getDbAdapter())) {
            Zend_Registry::set('dbAdapter', $db);
        }
        return parent::init();
    }
}

This class simply adds the created database adapter to the registry before continuing on with the default behaviour.

To let the application know about your custom plugin, you simply add the plugin path to your application.ini file, eg

includePaths.library = APPLICATION_PATH "/../library"
pluginPaths.My_Application_Resource = "My/Application/Resource"

More reading is available here – http://framework.zend.com/manual/en/zend.application.theory-of-operation.html

Further examples here – http://framework.zend.com/manual/en/zend.application.examples.html