Update to the Keyword Link Plugin
After getting quite a bit of feedback on the keyword link plug in, I hereby present the updated version.
This simple plug in allows you to specify keyword and link pairs. If the keyword is found in the article it will automatically be linked.
My original replacement routine did a simple string replace, which was fine if the words were noun’s ; but if you started to apply grammar things went wrong. (”Stonehenge” doesn’t quite change like “magic”, “magically”). The new routine checks for word boundaries which should solve nearly all problems.
To allow for styling the links, I have added a around each link to allow for modifying the link in any way you can imagine (or not). For example to make the link bold add the following to your style.css file:
.bm_keywordlink { font-weight: bold; }
Two more requests were for only linking the first mention of a link in the article, and for some links to be tagged as “nofollow”. Both are now possible.
Subscribe to this blog's RSS feed
BM Gallery 1.3
I found some time and updated the BM Gallery plug-in to include some requested features.
- The plugin has been internationalised to include a PO file for all message strings
- Better support for Wordpress installations in sub directories
- Updated & tested the plugin for Wordpress 2.5
- Removed dependency on unzip
If you find any problems with it, drop me a line at martin@blogmechanics.net.
Subscribe to this blog's RSS feed
Use firefox to block websites / urls
I used to have a problem, and it was driving me to distraction, literally. A large part of my work consists of surfing the internet for work related information. But while working you often have to wait for something, a piece of software, a scanner warming up. A quick click on “Google News” became a little too frequent. Ever found yourself on a news website without remembering typing the address?
I cannot just unplug my computer — work without a working Internet connection would be quite impossible. Time to kick the habbit and here I found a friend in the BlockSite addon for Firefox. All the Google News links are now grayed out and useless; and the same for most of the newspapers & tech sites I tended to visit.
Sure I can bypass this, but having to do this is a good reminder that I probably shouldn’t be visiting the site. And to keep myself honest I have installed BlockSite on each of the computers I use throughout the day, remotely or local.
Subscribe to this blog's RSS feed
Google App Engine
While having some sushi for lunch yesterday I was browsing the web and found out the first news about the new Google App Engine. Since they only give away 10,000 keys during the beta period I was lucky enough to snatch up one right after I finished my lunch.
It sounds like a great way explore the Google platform (ever wondered how GMail works?). I have worked my way through the examples and I will dream up a couple of things to build in the next few days.
Positive Points
- Free for up to 500MB of storage, 10Gb bandwith (per day), that is some serious bandwidth. My hosting provider charges me much more for much less. I wonder how quick they will amend the terms and condition to exclude hosting your own plain site (its easy if you don’t script too much) on their servers.
- This scales — I want to build another GMail then the Google data centers take care of that headache — at a cost of course
Negative Points
- At the moment the only language supported is Python. This is great if like me you don’t mind learning another language and build sites from scratch. It will be not so easy if you would like to port your existing PHP/Java site to the Google cloud.
- If you become too popular you are stuck. If you run the next StumbleUpon or Flickr then this environment will help you scale quickly without much effort. But at that point you can no longer move anywhere else as your application will only run on a Google system. You will need to pay them probably serious $$$ for the privilege. You might just want to consider selling to Google at this point, but they set the terms as you have nowhere else to go.
- And of course — do you trust Google with all your sensitive customer data? That is up to each individual company. For those companies who like the idea of scalable web server and storage idea without much hassle Google might just be willing to sell them a couple of pizza box servers to keep things in-house.
The Google App Engine cloud will probably take off regardless. What is needed now is some good & basic open source packages that allow you to quickly build a site and host it on a Google server. The architecture takes care of the scaling and will probably be priced reasonably for small and medium sized sites. So its great for having your own blog (think Blogger Advanced — with plug-ins) or web store.
Hosting providers might want to keep a an eye on things — and maybe build their own implementation of the Google API to “assist” moving the next internet star onto their servers.
Subscribe to this blog's RSS feed
Backing up your Wordpress Database

What this article is about
- Daily backups of your Wordpress database
- Daily e-mail with a compressed copy of the database
Last week I managed to setup a nightly automatic backup of my Wordpress files. That still left securing the database as an unfinished task. And of course it will be handy to have a good backup when I prepare to upgrade to Wordpress 2.5
So today I wrote a little script that backups the database on my hosting provider nightly. This is no great difficulty. It just expands the example from the Wordpress codex a little. Here is what you can do to setup your own database feel-all-good backup scheme:
Step 1 - The Script
After logging in through SSH to your hosting provider, create a place to store the backup files. This should not be in your webserver directory (otherwise a smart person might just get lucky and find the location of your files).
mkdir ~/wordpress_backup
The script itself is called “backup_db.sh” and placed in this directory.
The username and password information comes straight from your wp-config.php file.
#!/bin/bash
# Setup
USER=username_for_wordpress_db
PASSWORD=password_for_wordpress_db
DATABASE=your_wordpress_database
HOST=localhost
DIRECTORY=~/wordpress_backup
# Your e-mail address for reporting errors
SYSOP=youremail@gmail.com
MailError()
{
MSG="`hostname` reports wordpress database backup failed!"
SUBJ="Database Backup Failed"
echo $MSG | mail $SYSOP -s"$SUBJ"
}
# Keep up to three copies
if [ -f $DIRECTORY/db.2.gz ]; then
mv $DIRECTORY/db.2.gz $DIRECTORY/db.3.gz
fi
if [ -f $DIRECTORY/db.1.gz ]; then
mv $DIRECTORY/db.1.gz $DIRECTORY/db.2.gz
fi
if [ -f $DIRECTORY/db.today.gz ]; then
mv $DIRECTORY/db.today.gz db.1.gz
fi
# Make the backup
mysqldump $DATABASE --add-drop-table -h $HOST --user=$USER --password=$PASSWORD | gzip > $DIRECTORY/db.today.gz
if [ $? -gt 0 ]; then
MailError
exit 1
fi
# Optional: mail the backup file to ourselves
perl $DIRECTORY/mail.pl
As the file contains password information make sure to make it less accessible:
chmod 0700 backup_db.sh
To see if this works simply run the script (sh backup_db.sh). Make sure to unpack the created zip file to verify that the database was properly dumped.
Step 2 - Running the backup automatically
This step depends on your hosting provider. My own provider (Hostmonster) does not provide the “crontab” facility I has used earlier on my own computer for nightly backups.
CPanel - Cron Jobs - Advanced Unix
In the cpanel interface they do provide a “Cron Jobs” option. So here I simply setup a similar entry that runs every morning at 2am.
If neither of the above options are possible the WP-Cron plugin might also be an option you can consider.
Step 3 - Emailing the database backup
The simplest solution for securely storing the database is to e-mail the backup file to myself.
My hosting provider does not provide the most common options for sending mime attachments (such as by using mutt) from the command line.
They do however provide Perl, and with a little searching and hacking the following Perl script nicely handles the mailing of my backup file every night.
Save the script as mail.pl in the ~/wordpress_backup directory. It will be called automatically from the above “backup_db.sh” script.
#!/usr/bin/perl
# Akadia AG, Arvenweg 4, CH-3604 Thun send_attachment.pl
# ----------------------------------------------------------------------
# File: send_attachment.pl
# Autor: Martin Zahn / 05.01.2003
# Purpose: Email attachments in Perl
# Location: $ORACLE_HOME\\Database
# Certified: Perl 5.6.1, MIME-Lite-2.117 on Cygwin / Windows 2000
# ----------------------------------------------------------------------
use MIME::Lite;
use Net::SMTP;
### Adjust sender, recipient
my $from_address = 'me@myblog.net';
my $to_address = 'me@gmail.com';
### Adjust subject and body message
my $subject = 'Daily backup of Wordpress Blog';
my $message_body = "Here's the attachment file(s) you wanted";
### Adjust the filenames
my $my_file_zip = 'db.today.gz';
my $your_file_zip = 'db.today.gz';
### Create the multipart container
$msg = MIME::Lite->new (
From => $from_address,
To => $to_address,
Subject => $subject,
Type =>'multipart/mixed'
) or die "Error creating multipart container: $!\\n";
### Add the text message part
$msg->attach (
Type => 'TEXT',
Data => $message_body
) or die "Error adding the text message part: $!\\n";
### Add the ZIP file
$msg->attach (
Type => 'application/zip',
Path => $my_file_zip,
Filename => $your_file_zip,
Disposition => 'attachment'
) or die "Error adding $file_zip: $!\\n";
### Send the Message
$msg->send;
Subscribe to this blog's RSS feed
Wordpress 2.5
I just downloaded WordPress 2.5 and installed it on a spare server. Too early days to overwrite this blog, but its time for a cup of coffee and some hacking.
First impression, besides feeling a little lost in the new admin menu ? I was curious how many filters the WP 2.5 code has compared to WP 2.3.3. So I did a little search of the source code for the “apply_filters” function call.
grep -ir apply_filters * | wc -l
The results? For WP 2.33 the answers is a total of 413 calls to “apply_filters’ . For WP 2.5 the results is 555. So that is 34% more calls ; that should make Wordpress that much more flexible (and that much slower ;-))
Subscribe to this blog's RSS feed
Tuning Wordpress for Speed

Six string bass of unknown origin by greefus groinks
After writing an earlier article about WP-Super Cache I became curious how much difference the various tweaks make in performance. So I setup a little Ubuntu test machine. After downloading Wordpress 2.3.3 I set it up with some basic posts and the default theme.
The default theme is very simple and when compared to most blogs contains only the bare essentials.
The test environment
- An aging, but working AMD Sempron(TM) 2200+ @ 1500Mhz with 1Gb of memory.
- Ubuntu 6.1 server
- Apache2
- PHP5
- Wordpress 2.3.3
- Mysql 5.0.24 (on the same server)
To test the server responses, another Ubuntu desktop was used with httperf to test the server responsiveness. For each test, the server has to return 1000 copies of the Wordpress frontpage as fast as possible. The results are measured in pages per second.
Test #0 : Static Page -> 568 pages/sec
To benchmark the basic apache2 configuration I saved the Wordpress front page as a static file and tried to see how quickly the server could return this.
Test #1 : Vanilla installation -> 3.05 pages/sec
This was the basic installation of Wordpress with no optimizations made at all.
Test #2 : eaccellarator -> 6.5 pages/sec
The first optimization was to compile eaccellarator into PHP5. This module helps out by storing the compiled PHP scripts in a cache saving PHP from having to re-compile all scripts on each refresh.
This doubled the performance — but the server still needs to query the MySQL server for each page.
Test #3 : WP-Cache-2 -> 26 pages/sec
One of Wordpress most popular extensions — WP-Cache improves performance by storing earlier generated pages on disk. Therefore there is no need to re-query the MySQL server anymore. However PHP is still loaded, and Wordpress still goes through quite a bit of initialization before showing the static pages.
Test #4 : WP-SuperCache -> 426 pages/sec
This plug in takes WP-Cache-2 to the next level. It creates a set of rewrite rules for Apache allowing it to directly fetch each page from disk. This saves loading PHP and initializing Wordpress. These savings make your Wordpress blog a whopping 16 times faster than when using just WP-Cache2.
Results
| Static Page | Vanilla | Eacellerator | WP-Cache2 | WP-Super Cache |
| 567 | 3.2 | 6.2 | 26.6 | 407 |
| 571 | 2.9 | 6.5 | 24 | 427 |
| 571 | 3 | 6.7 | 26.4 | 436 |
| 565 | 3.1 | 6.6 | 27 | 434 |
| 568.5 | 3.05 | 6.5 | 26 | 426 |
Conclusion
It definitely pays off handsomely to invest some time in optimizing Wordpress. Most hosting providers will provide a PHP accelerator such as eaccellerator standard, but beyond that you need to tweak things by yourself.
The benefit of using a cache is very much in the freedom it gives you to customize your blog. You no longer have to worry about the overhead each module adds to generating a page. Most of your visitors will not log in and so there is no need for the performance hit of building a customized page for them on each request.
References
Subscribe to this blog's RSS feed
Backup your Wordpress installation with rsync
for wordpress by gillesklein
What this article is about
- Daily Incremental backups of your Wordpress blog files
- Daily report by e-mail on the status of the backup
What it does not cover
- This script does not make a backup of your Wordpress MYSQL server. In the near future I will write another script that does this automatically every night as well.
This blog is slowly starting to feel a little like home and after much polishing the number of hours invested in it is increasing. I have uploaded pictures, plug ins and upgraded my installation.
This is always where my paranoia sets making me wonder ‘what if’.. what if is of course any kind of disaster that would wipe out my work. Mad hackers, my hosting provider going belly up, or some country taking exception to my writing or most likely: a hard disk crash at my provider.
So today is backup day. And as every day should be backup day I am going to automate the whole thing.
I have an Ubuntu Linux workstation at home to which I would like to sync a copy of my Wordpress blog and Rsync is the tool I am going to use. It is a great piece of backup software designed to transfer only the changes made, not your whole site. So if you modified only one file, it will only resend that one file. And if you only changed a small thing in that one file, it will only send the actual changes.
For this to work you will need to have the following:
- SSH access to your hosting provider and of course they should run some kind of Unix/Linux
- A Linux computer to backup to. MacOX should work as well, but lacking a Mac I cannot vouch for this.
- rsync , under Ubuntu
apt-get install rsyncshould do the trick. - mailutils, under Ubuntu
apt-get install mailutils, optional but its nice to receive an e-mailed report of your backup. (Probably not required if you have configured sendmail/postfix etc)
Part 1 - Setting up shared keys
I am going to take a little detour here. Because I would like rsync to run at night it is best to make sure that it can login automatically at your hosting provider. The most secure way of doing this is by setting up shared encrypted keys on your computer and you hosting provider.
If you skip this part you can still run the script below — you just have to enter your password every time it runs.
If you have previously created an SSH keyset, you can skip Step #1. If you are not sure check if the following file exists under your home directory (~/.ssh/id_dsa).
Step #1
Open a terminal and enter the following: ssh-keygen -t dsa
Just press enter several times there is no need for a pass phrase.
martin@edinburgh:~$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/nis/martin/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/nis/martin/.ssh/id_dsa.
Your public key has been saved in /home/nis/martin/.ssh/id_dsa.pub.
The key fingerprint is:
4e:9f:46:f9:d5:dc:53:40:c8:6a:25:3e:70:27:3e:03 martin@edinburgh
Step #2 - Copy the public key to your web host
Here it will ask you for your username & password.
scp ~/.ssh/id_dsa.pub youraccount@yourdomain:./id_dsa.pub
Step #3 - Login to the host server using SSH
Here it will ask you for your username & password.
ssh -v youraccount@yourdomain
Step #4 - Add the new public key to the keyring
mkdir .ssh
chmod 0700 .ssh
cd .ssh
touch authorized_keys2
chmod 600 authorized_keys2
cat ../id_dsa.pub >> authorized_keys2
rm ../id_dsa.pub
Step #5 - Log out & try out
If everything went smoothly you can now login to your hosting account without having to provide a password. Your computer and your hosting provider can now do this by exchanging cryptographic keys instead.
exit
ssh -v youraccount@yourdomain
Part 2 - Setting up the backup script
In this example I going to make a backup directory under my users home directory on my local Ubuntu machine. Of course this backup directory can reside anywhere else on your computer.
Step #1 - The script
mkdir ~/backup
mkdir ~/backup/wordpress
chmod 0700 ~/backup
chmod 0700 ~/backup/wordpress
Now use your favorite editor to create & modify the following script:
gedit ~/backup/run_wordpress_backup.sh
#!/bin/bash
# Your login details for your hosting account
USERNAME="yourusername"
DOMAIN="yourdomain.com"
# Your e-mail address for reporting errors
SYSOP=youremail@gmail.com
# The directory on your hosting account that contains wordpress, note the ""
REMOTEHOME="~/public_html/html"
# Directory on you local machine that stores the backup
# Note: no "" around the following
BACKUPTO=~/backup/wordpress
MailSuccess()
{
MSG="`hostname` reports wordpress backup complete!"
SUBJ="Backup Complete"
echo $MSG | mail $SYSOP -s"$SUBJ"
}
MailError()
{
MSG="`hostname` reports wordpress backup failed!"
SUBJ="Backup Failed"
echo $MSG | mail $SYSOP -s"$SUBJ"
}
# The actual sync command
rsync -e 'ssh -p 22' -v -r $USERNAME@$DOMAIN:$REMOTEHOME/* $BACKUPTO
if [ $? -gt 0 ]; then
MailError
exit 1
fi
MailSuccess
exit 0
Step #2 - Make the script executable
chmod +x ~/backup/run_wordpress_backup.sh
Step #3 - Test the script
~/backup/run_wordpress_backup.sh
On success the script will send you a brief e-mail.
If things don’t work out here you can add “-v -v” to the rsync command line to obtain more debugging information.
Part 3 - Finishing it up - and running this at night
If your home PC doesn’t sleep at night (and mine is always busy) you can set it up to run the backup automatically every night. For this you need to add a little crontab entry to your Ubuntu installation.
crontab -e
This will open an editor, in which you can add the following line:
01 04 * * * /home/yourhomedirectoy/backup/run_wordpress_backup.sh
Note that I didn’t use the “~/run_wordpress_backup.sh” notation here — its better to be specific when setting up a crontab entry.
Every night at 4:01am your computer will run the backup script and fresh in your Inbox every morning should be an e-mail telling you that things went swimmingly. If its missing your backup scheme just fell apart.
And of course don’t forget to regularly backup the backup directory to a saver medium!
Subscribe to this blog's RSS feed
Keywordlink Plugin

Neuschwanstein Castle by roblisameehan
In one of my many lives I am developing a travel website. While writing the content I quickly got tired of all the manual cross-linking. Each time I mention London in my articles I would like to add a link to the London introduction page.
It is fairly trivial to do this automatically — and it has been on my TODO list for quite a while. So when I came across someone else looking for a similar solution I cleaned up my code and put a little plug-in together that does just this.
You can find the Keyword Link plug-in here.
Have fun !
Subscribe to this blog's RSS feed
Embed images into your Wordpress Plugin
On the Wordpress forum there was some commotion regarding the GoogleSiteMap Generator Plugins use of base64 encoded content. This set off some stealth virus alerts - as a typical trick is to hide malicious code in these unreadable strings.
#region Embedded resources
if(isset($_GET["res"]) && !empty($_GET["res"])) {
$resources = array(
//PayPal
"{8C0BAD8C-77FA-4842-956E-CDEF7635F2C7}"
=>"R0lGODlhEAAQAMQQANbe5sjT3gAzZpGmvOTp7v///629zYSctK28zb"
.vI1ZKnvfH094SbtHaQrHaRrJ+xxf///wAAAAAAAAAAAAAAAAAAAAAAA"
. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAHoAxAALAAAAAA" .
. "QABAAQAVZICSOZDkGQqGuBTqUSMqqiTACwqIKgGkKwCDwVRIodkDVwjYSMFS"
. "NoCNQIgSugZ6vBMBetSYCj0UwCA6lgyy4YoqWASRAZSYNZNaA+VxM7B5bEA9C"
. boGGIyEAOw==" ); }
No virus here - Arne Brachhold, the plug-ins author, uses the base64 function to serve up images directly from the plug-ins source code. This is a neat little trick that I will gladly copy into future projects.
Why not just include a separate GIF/JPG file ? You can of course, however there is no standard way of determining your plug-ins home directory or url. So instead of creating a custom solution that works most of the time this is a nice trick that works all of the time.
The second trick is about how to serve the image on request and neatly catching a web browser just checking if its cache is still up-to-date.
if(array_key_exists($_GET["res"],$resources))
{
$key = $_GET["res"];
$content = base64_decode($resources[$key]);
$lastMod = filemtime(__FILE__);
$client = (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])?
$_SERVER['HTTP_IF_MODIFIED_SINCE']:false);
// Checking if the client is validating his cache and if it is current.
if (isset($client) && (strtotime($client) == $lastMod))
{
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lastMod).' GMT', true, 304);
exit;
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $lastMod).' GMT', true, 200);
header('Content-Length: '.strlen($content));
header('Content-Type: image/gif');
echo $content;
exit;
}
}
The above code is outside of any function directly in the plug-in source so it is executed as Wordpress loads each plug-in into memory and before it starts calling any of the filter & action hooks.
http://blogmechanics.net/?res={8C0BAD8C-77FA-4842-956E-CDEF7635F2C7}
It inspects if the “res” parameter is passed to your blog in the url. If so it loads the images and finds the one that matches and serves it up and exits immediately.
The only drawback of catching a URL this early is that the images are always available. Also outside of the administration panel. Just click the link above, it works and will display the Paypal logo.
Subscribe to this blog's RSS feed
