Blog

WordPress custom blog page

As of this writing I have finally decided to create a custom blog page for this WordPress installation to provide users with a more handy access to all blog posts rather than solely relying on the recent post category on the right hand side.

In order to create a custom blog page in WP simple create a new page as you would do normally. Then, as administrator open the Settings menu and navigate to the Reading section. There you can select the front and post page to be displayed. I have selected my “Home” page as front page and a newly created “Blog” page for postings. Voila – sometimes things can be pretty easy 🙂

Zend_Date and MySQL’s datetime format

Despite Zend_Date‘s power and elegance to handle all kinds of different date and time formats, it (still) lacks the ability to cope with MySQL’s datetime formated strings out-of-the-box.

Thus, instead of being able to simply do something like

$date = new Zend_Date();
echo $date->toString(Zend_Date::MYSQL_DATETIME);

one has to manually define MySQL’s datetime syntax, as shown in the following:

$date = new Zend_Date();
echo $date->toString('YYYY-MM-dd HH:mm:ss');

I personally don’t quite see why this commonly used format has not yet been added to Zend_Date.

In the meantime, I have found it to be the most convenient to define the MySQL datetime format string as a constant. Although this is no big deal but still, I would rather like to see this simple piece of formating code inside Zend_Date.

UPDATE
I have come across a strange problem when trying to create new Zend_Date objects using custom formats, such as the MySQL datetime format shown above, e.g.:

$date = new Zend_Date($mysqlDatetimeString, MYSQL_DATETIME); //will create a wrong date...

Instead it seems best to create custom format dates/times using a two way approach:

$date = new Zend_Date(); //create new object, by default time()
$date->set($mysqlDatetimeString, MYSQL_DATETIME); //will create correct date

Zeitsynchronisation von Zend_Date mittels Zend_TimeSync und mehrerer TimeserverSynchronizing Zend_Date using Zend_TimeSync and multiple time servers

This post describes a simple approach to implement time synchronization using Zend_TimeSync for Zend_Date using multiple time servers.

First of all you will need to create a new Zend_TimeSync instance, specifying a list of possible time servers. You may use the server pool provided by ntp.org for this purpose. In case you specifiy multiple servers (which generally is a good idea for fallback reasons, etc.), the ZF manual advises to name these servers individually in order to be able to refer to them by name later on. Following is an excerpt from application.ini file specifying the list of available time servers, ordered by preference.

timeservers.ntp.generic = "0.europe.pool.ntp.org"
timeservers.ntp.fallback = "1.europe.pool.ntp.org"
timeservers.ntp.reserve = "2.europe.pool.ntp.org"
timeservers.ntp.additional = "3.europe.pool.ntp.org"

Note that the default protocol used by Zend_TimeSync is NTP. In order to specifiy a different protocol please refer to the ZF manual: http://framework.zend.com/manual/en/zend.timesync.working.html.

Once the list of available time servers has been defined it is time to setup Zend_TimeSync to use it:

$timeserverConfig = $this->getOption('timeservers); //get options from application.ini
$timeservers = new Zend_TimeSync($timeservers['ntp']); //use "named" timeservers

Note that I have kept the time server naming schema as shown in ZF manual.

The next step is to configure Zend_Date to use a primary time server from this list. Hereby, Zend_Date accepts a single timeserver using the timesync option, as shown in the following code snippet:

Zend_Date::setOptions(array(
  'timesync' => $timeSyncServers->getServer()));

This means that once the current time server is set (using a call to getDate() on the Zend_TimeSync instance) Zend_Date‘s timesync option can be successfully specified.

As setting up Zend_Date with the correct time server is a repetitive task, it is best and easiest to put this code into your bootstrap file.

The following piece of code shows the complete initialisation of Zend_Date using Zend_TimeSync and multiple time servers based on the NTP protocol:

protected function _initDate() {
  try {
    $timeServers = $this->getOption('timeservers');
    $timeSyncServers = new Zend_TimeSync($timeServers['ntp']);

    if (!$timeSyncServers->getDate()) {
      throw new Zend_TimeSync_Exception('Failed to get date from current time server');
    }

    Zend_Date::setOptions(array(
      'timesync' => $timeSyncServers->getServer()));
  } catch (Zend_TimeSync_Exception $e) {
      // handle error...
  }
}

Note that it is good practice for bigger projects to setup caching for Zend_Date to improve performance, but this is a topic for another post 🙂

Doctrine_Pager error “Invalid parameter number” when using “IN” in “WHERE” clause

This post is just to inform fellow users of Doctrine about a problem with Doctrine_Pager using “IN” for “WHERE” clauses.

Simply put: Just don’t use it (at the moment), as it will result in the following error:

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

Instead, use orWhere() for instance to get the desired result.

jQuery Multi File Upload

A couple of days ago I accidently discovered https://blueimp.net/‘s jQuery File Upload.

Update
Finally I found some time to post back on jQuery File Upload. As of this writing I have successfully integrated blueimp’s jQuery multi file uploader plugin into a Zend-based web application. The plugin has proven to be quite valuable as it provides a bunch of out of the box functionality, such as handling chunked uploads using a simple PHP script. Of course this script only serves as a starting point for more serious projects, but still it is quite helpful.

The API and the corresponding documentation for the plugin is available via the project’s homepage (https://github.com/blueimp/jQuery-File-Upload/wiki). They are both very well written and easy to understand. Furthermore, in case you are interested in the code, the inline documentation is also pretty exhaustive. Details on the file upload can be managed on both sides of the application, i.e. using the JavaScript code during instantiation of the plugin and on the server side when processing upload requests.

Styling of the plugin can be extended pretty easy too. The author has provided template stylesheets that can be overwritten and extended. One of the core aspects of this plugin is the templating plugin used to display uploaded files. The JSON used to update these templates can be altered on the server side, thus making it possible to add further functionality to the UI, such as adding checkboxes to select certain files. The event hooks provided by the UI part of the plugin allow to modify the uploader’s behavior even more.

All in all, I am glad I stumbled across the well written and documented jQuery plugin, available from the project’s homepage: http://aquantum-demo.appspot.com/file-upload.

Automatische Größenanpassung von Bildern mit TCPDFAuto-fit images onto current page using TCPDF

Recently I had to fit images onto the current page of a dynamically generated PDF document using the functionality provided by the (superb) TCPDF toolkit.

Due to the fact that I had to include HTML content in the PDFs I was bound to use the writeHTML function. The HTML content was basically structured using plain old <div> containers, that again were seperated into

  1. title
  2. text and
  3. image

sections. The idea was to dynamically add the title and the text content and use the remaining space to auto-fit the image onto the current page, thus not causing a page-break.

Using the functions provided by TCPDF, my idea was to basically calculate the current Y-offset after including the PDF-header, title and text sections and calculate the optimal image height based on the beginning of the footer section.

The following code snippets presents a working prototype. Hereby, $pdf is an instance of TCPDF and the constant MY_PDF_FOOTER_YOFFSET refers to the custom value of the footer height (represented by a negative y-offset).

$pageDimensions = $pdf->getPageDimensions();
$yOffset = ceil($pdf->GetY());
$beginFooter = floor($pageDimensions['hk'] + MY_PDF_FOOTER_YOFFSET - 15);
$maxImgHeight = floor($beginFooter - $yOffset);

In case you are wondering about the -15 in the calculation of the beginning of the footer area – I was using an additional image description section right below the image, with a height of (around) 15mm.

Concluding, this functionality can be easily put into a separate function to calculate the optimal (auto-fitting) image size for your (dynamically) generated PDF documents.

Install Pdftk under Windows 7

Although the official installation guide recommends you to install Pdftk by copying the 2 required files** to c:\windows\system32, I personally prefer to keep application specific files outside Windows’ core directory.

Thus, in order to do so simply create a program directory such as C:\Program Files (x86)\pdftk and extract all files from the downloaded zip into it, resulting in the following folder structure:

C:\Program Files (x86)\pdftk
  -> .\bin\
  -> .\docs
  -> .\license_gpl_pdftk

Now you can simple add the bin-folder to the system PATH and you are ready to go. Using this approach it’s easier to update the core Pdftk files without the need to access any Windows’ core folders.

** libiconf2.dll and pdftk.exe

Zend 1.11.6 and Doctrine 1.2

Recently, our project team spent quite some time figuring out a way to get Zend (ZF) working together with Doctrine ORM. Although there are a lot of howtos and guides out there it seems like everybody has his/her own way of merging these two frameworks.

In order to get most out of Doctrine one has to get the command line tool running, which provides a handy set of predefined functions to manage the underlying model schema. From what we’ve read so far there are major differences between Doctrine 1.2 and 2.x, especially when it comes to setting up the command line script. Again, although there are plenty of different approaches to get Zend working with Doctrine 2.x no ideal solution could be found so far…

For compatibility reasons we opted for Doctrine 1.2, as it seems much easier to get it working with ZF. Once the command line script (doctrine.php) was setup (which took quite some time, as the bootstrapping process needs to be tweaked a bit), the next step was to figure out a way to autoload Doctrine’s models using Zend’s bootstrapper.

As we are using a module based architecture and are keeping the models outside this module structure (in application/models) we needed a way to autoload the modules separately from the models, without running into the problem of loading anything twice (which would happen when using the default setup, i.e. Doctrine’s model loader together with Zend’s autoloader…).

Anyway, the solution was to use Zend’s module autoloader and use module bootstrap files on the one hand, and additionally use Doctrine’s modelsAutoload function via a callback:

public function _initDoctrine() {
  $this->getApplication()->getAutoloader()
                ->pushAutoloader(array('Doctrine', 'autoload'));

  spl_autoload_register(array('Doctrine', 'modelsAutoload'));

  $doctrineConfig = $this->getOption('doctrine');
  $manager = Doctrine_Manager::getInstance();
  $manager->setAttribute(Doctrine::ATTR_AUTO_ACCESSOR_OVERRIDE, true);
  $manager->setAttribute(Doctrine::ATTR_MODEL_LOADING, $doctrineConfig['model_autoloading']);
  $manager->setAttribute(Doctrine::ATTR_AUTOLOAD_TABLE_CLASSES, $doctrineConfig['table_autoloading']);
  $manager->setAttribute(Doctrine::ATTR_DEFAULT_TABLE_CHARSET, 'utf8');

  //loading of Doctrine's models is done by Zend's autoloader -> @see _initAppAutoload
  //Doctrine_Core::loadModels($doctrineConfig['models_path']);

  $conn = Doctrine_Manager::connection($doctrineConfig['dsn'], 'doctrine');
  $conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);
  $conn->setCharset('UTF8');
  return $conn;
}

The above code loads Doctrine and sets up the connection details. In order to bootstrap the modules use the following autoloader function:

protected function _initAppAutoload() {
        $moduleLoader = new Zend_Application_Module_Autoloader(array(
                    'namespace' => '',
                    'basePath' => dirname(__FILE__)));
}

This setup parses all of the applications script and models. This setup can also be used for Doctrine’s command line script (doctrine.php).

The settings used for Doctrine are shown in the following:

doctrine.cache = true
doctrine.dsn = "mysql://user@localhost/some_db"
doctrine.data_fixtures_path = APPLICATION_PATH "/configs/data/fixtures"
doctrine.sql_path = APPLICATION_PATH "/configs/data/sql"
doctrine.migrations_path = APPLICATION_PATH "/configs/migrations"
doctrine.yaml_schema_path = APPLICATION_PATH "/configs/schema.yml"
doctrine.models_path = APPLICATION_PATH "/models"

doctrine.generate_models_options.pearStyle = true
doctrine.generate_models_options.generateTableClasses = true
doctrine.generate_models_options.generateBaseClasses = true
doctrine.generate_models_options.baseClassPrefix = "Base_"
doctrine.generate_models_options.baseClassesDirectory =
doctrine.generate_models_options.classPrefixFiles = false
doctrine.generate_models_options.classPrefix = "Model_"

doctrine.table_autoloading = true

; Doctrine needs to use Aggressive autoloading for the CLI to generate prefixed models appropriately
; MODEL AUTOLOADING: 1 = aggressive, 2 = conservative
doctrine.model_autoloading = 2

[doctrineCLI : production ] 
doctrine.model_autoloading = 1

This setup shown above creates a Base folder inside the application/models folder and puts the auto-generated Doctrine models in there. We believe this setup is more convenient to use in comparison to put the base-model files in the core models folder too.

Additionally, the setup specifies that model-classes should be prefixed with “Model_” to make them more distinct from other Zend classes. Bear in mind that this approach comes with certain changes when using fixtures for instance, as you have to explicitely prefix model-class references.

html is null” error using set(‘value’) for dijit.Editor

Be aware of the fact the using editorDijit.set('value', null) will result in an error (“html is null”) rather than setting an empty value.

I’ve experienced this behavior when trying to update a dijit.Editor using dijit.form.Form generated data. It seems like only an empty string can be set for an empty value and not null. You might want to keep that in mind when retrieving data from a database that by default uses NULL-values.

Calculate next auto-increment value for MySQL tables

Sometimes it is necessary to determine the next auto-increment value that will be used by MySQL for inserting values into tables.

First off, there are several different approaches to determine it. Most people use the MAX() function and simply add 1 to the value. Although this is fine is most cases, you may run into problems when forced to retain data consistency after deleting rows.

Another approach is to determine the AUTO_INCREMENT value directly:

SHOW TABLE STATUS LIKE 'your_table'

In order to determine the next auto-increment value used by MySQL you simply have to get the value of the field called ‘Auto_increment’.

Using PHP, this can be achieved like so:

$result = mysql_query("SHOW TABLE STATUS LIKE 'your_table'");
$row = mysql_fetch_assoc($result);
return $row['Auto_increment'];

Scrollbar in dijit.layout.ContentPane aktivierenActivate scrollbar in dijit.layout.ContentPane

It seems that if dijit.layout.ContentPanes are nested inside other containers, such as dijit.layout.BorderContainer they do not automatically display the scrollbar when content overflows their visible area.

In order to force a scrollbar simply specifiy the CSS directive overflow:auto, e.g.

<div dojoType="dijit.layout.ContentPane" style="height:300px;overflow:auto;">

Timeout problem using FileZilla FTP client with multiple simultaneous file uploads

For some strange reason FileZilla FTP client (version 3.3.5.1) kept producing timeout errors when trying to process multiple simultaneous file uploads. I was able to reproduce this behavior on Windows 7 Pro 64bit and Ubuntu Linux 11.04 64bit using the same version of FileZilla.

By default, FileZilla sets a maximum of 2 concurrent uploads. In my case, a quick fix was to simply set this value to 1, which directs FileZilla to upload files sequentially rather than simultaneously.

At this point I am not sure what causes this timeout problem, since it only occurs with one specific FTP server. Strange side fact: Other users are not reporting any symptoms of this kind on this server.

Anyhow, settings the max. concurrent upload count to 1 fixed the problem – for now.

Emulate sleep-command in Windows batch files

Windows’ command line is not shipped with pre-installed sleep functionality, or at least I was unable to find it on older systems such as the target system (Windows 2003 server) I had to use.

The main goal of the task was to restart a (Windows) service on a regular basis. In order to give the service shutdown sequence some time to complete before being started again I wanted to integrate some seconds of sleep time. Unfortunately, the target Windows 2003 server did not have a built-in sleep command. After some thought I recalled the Windows 2003 resource toolkit and hoped to find the missing functionality in there – with success!

sleep.exe offered everything I needed to implement the sleep functionality for the service restart batch file. Simply download and install the toolkit from Microsoft’s homepage and it will add itself to the PATH.

The final solution is shown in the following:

net stop service xyz
sleep.exe 10
net start service xyz

An optimization for this script would be for instance to check in advance if the service is started. For more information have a look at these solutions.

How to control error pages in WordPress

By default WordPress searches for error pages, such as error 404 (file not found) or error 403 (permission denied), in the current active theme (e.g. 404.php or 403.php). If the theme does not provide default error pages WordPress’ built-in ones will be used instead.

Since I tend to deploy other web applications alongside WordPress, my overall goal was to have the same error pages independent of the application context in order to achieve a standardized representation. Thus, for instance if a page cannot be found the current WordPress layout will be used to present the error.

Using Apache default error pages can be controlled via .htaccess files. So first, create these custom links to your error pages:

ErrorDocument 403 http://your.server/error-403-permission-denied
ErrorDocument 404 http://your.server/error-404-file-not-found
ErrorDocument 500 http://your.server/error-500-internal-server-error

The next step is to create these WordPress error pages:

error-403-permission-denied
error-404-file-not-found
error-500-internal-server-error

Finally, in your currently active theme create the corresponding error pages:

403.php
404.php
500.php

Finally, all you need to do is to redirect to the link specified in .htaccess inside your theme’s error pages, e.g. for 404.php:

header('Location: http://your.server/error-404-file-not-found');
exit;

That’s it. Now you have a standard layout for error pages independent of the application context on your server.

You can try it on this site by requesting a non-existing file, such as https://www.kerstner.at/does_not_exist_on_this_page.

Further improvements could be made for sites with multiple languages, for instance by prepending the language when redirecting via the corresponding error pages.