Skip to content


Adding an entry to /etc/hosts on OS X

Web Developers, Administrators of Mac Networks, and anyone who likes to noodle with OS X will probably eventually need to add hosts file entries. I use them when I’m testing a moved and/or changed version of a website at new hosting before I move the DNS.

I used to add hosts file entries manually then wonder why they didn’t seem to work. I tried rebooting, logging out, etc with varying success, until I learned this trick. On the Mac you must flush the DNS cache for the changes to take effect. Mac OS X used to have a friendly utility called NetInfo Manager, but that seems to have been removed in Leopard, so we’re using terminal commands.

Open a terminal sesion and type:
sudo nano /etc/hosts

Hit the down arrow until you get to the end of the file, and add your hosts file entry, for example:
192.168.2.33 myintranetserver.mydomain.com
… I put in an extra line break at the end. I don’t think it’s really necessary but it’s a habit from having to use Windows, which would ignore the last line in a hosts file.

then flush the cache:
sudo dscacheutil -flushcache

…the name should now resolve! Test it:
ping myintranetserver.mydomain.com

Other Info

One thing that Windows, for all its annoyances, did get right is that changes to the hosts file (in ‘c:\Windows\system32\drivers\etc’) are reflected immediately. I’d like to see Apple do something about this in OS X, perhaps just flushing the cache automatically when /etc/hosts changes.

Another handy use for /etc/hosts is to set up mapping of virtual server addresses. For example, I use MAMP on my development Mac, and create new virtual hosts entries in Apache for each site I’m working on. Then for each I just add a new entry in the hosts file, e.g.:
127.0.0.1 devclientsite7.leftcolumn.net
… then I just use devclientsite7.leftcolumn.net:8080 in Safari or Firefox to access the development site. It means my development sites don’t have to be in subdirectories, instead I just make sure the sites use a config file to figure out what their address is, and I make sure that config file is updated when the site is moved to a live system.

On OS X Tiger (10.4) and probably earlier, there was some strange behaviour with hosts file entries. You could add an entry and it would take effect, but if you had no network available, the name would not resolve and could not be used, even if it resolved to 127.0.0.1! So you have the bizarre situation of putting in addresses for virtual hosts as described in the previous paragraph, all of which resolve to 127.0.0.1, but still not being able to use them for testing and development when not connected to the Internet. If anyone can enlighten me as to how this was anything other than a bug in OS X I’d be interested…

You can also use hosts file entries to block ads (by resolving common ad server addresses to e.g.: 127.0.0.1). You can download huge lists of ad servers for this purpose. This is a good idea when you’re stuck using Internet Explorer on Windows, especially on dial-up.

Posted in mac osx. Tagged with , , , .

MacBook Pro won’t wake up from sleep

One day my new MacBook Pro 17″ wouldn’t wake up. When I opened the lid machine was running but the Desktop wouldn’t load (just a default blue Desktop background colour) and there was no response from the Mouse or Keyboard. I eventually had to hard reset the Mac.

This annoying issue can apparently be caused a few different ways, but if your Mac is new and has all System Updates applied, chances are that the issue is caused when you close the lid and then move the mac before the contents of RAM are written out. There’s a feature called Safe Sleep, enabled by default, which can preserve and restore the state of a sleeping Mac even when the battery is removed. This sounds great, but the Safe Sleep procedure can take up to 30 seconds, which is too long for me.

How to fix this annoying problem? Here’s how I switched it off:

sudo pmset -a hibernatemode 0
sudo rm /var/vm/sleepimage

…you need to supply the super user password. After making the change, reboot the Mac. The Mac should now Sleep within a couple of seconds. The second line removes the file that Sleep Safe uses to store the contents of RAM. Since you’ve switched off Safe Sleep, the space can be recovered.

Personally I don’t see the need for Safe Sleep on a Mac with a non-removable battery, but be aware that if the machine is asleep and runs out of battery power you wil lose your logged in session! I haven’t tried it, and most OS X apps will deal pretty well with this anyway, but it’s not wise to let this happen…

More details:

Apple pmset Manual
Macworld article on setting sleep modes

Posted in mac osx. Tagged with , , .

Zend Framework: How to add FCKeditor to a Zend_Form

There are around 1,083,367 JavaScript-based Rich-Text Editors out there, and I’m sure most are pretty good. But I’ve had good results with FCKeditor so I use it on all my projects. Here’s a step-by-step guide to adding the FCKeditor to your Zend Form Elements.

1 – The basics

Download FCKeditor and Upload it to your Web Server. It needs to be somewhere accessible to the world, for example: /js/fckeditor/, which on your server may be a path like /var/www/html/your_site/js/fckeditor/.


2 – .htaccess

The .htaccess that sets up your index.php as the bootstrap needs to exclude the files that FCKeditor uses. If your bootstrap code in .htaccess looks like this:

RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css)$ index.php

you’ll need to change it. I typically only rewrite to /index.php if the requested file really doesn’t exist. So .htaccess should be something like this:

RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1


3 – Zend_Form Elements

In the Form code, you need to make sure that you know the id of the Element (In this case the id is ‘body’), and that you are filtering out all tags and attributes that you don’t want to explicitly allow. Create an allowed_tags list like the one below and ensure that the FormElement has a StripTags filter applied to it:

$allowed_tags = array(
	'a' =>	array('href', 'title'),
	'strong',
	'img'	=>	array('src', 'alt'),
	'ul',
	'ol',
	'li',
	'em',
	'u',
	'strike');

$body = new Zend_Form_Element_Textarea('body');
$body->setLabel('Body')
	->setAttrib('rows', 12)
	->setAttrib('cols', 40)
	->setRequired(true)
	->addFilter('StringTrim')
	->addFilter('StripTags', $allowed_tags);


4 – View Script

Let’s Assume that you use Layouts, and that you only want to use the FCKeditor on a couple of pages on your site. You don’t want to include the FCKeditor code on every page because it just adds to the page size, so we do something like this in the View Script (Note: Wordpress is messing with the quote marks in this block, ensure you have single quotes after src= and before the last semicolon. The other quotes should be double quotes.):

$this->custom_head .= '<script src="/js/fckeditor/fckeditor.js" type="text/javascript"></script>';
$this->custom_head = "<script language='javascript' type='text/javascript' src='/js/customs.js'></script>";
$this->custom_body = ' onload="setupFCK()"';


5 – Layout Script

The Layout Script needs to know about this new variable, so the Layout Script needs to know to refer to $this->custom_head if it is set. Drop the code below inside the <head> section of your layout script:

<?php

if ($this->custom_head) {
	echo $this->custom_head;
}
?>

…and change the html body element to look like this:

<body<?php if ($this->custom_body) {
	echo $this->custom_body;
}?>>

6 – Loading the FCKEditor when the page loads

Create /js/custom.js and put this in it:

function setUpFCK() {
	if(document.getElementById('body')) {
        var oFCKeditor = new FCKeditor('body') ;
        oFCKeditor.BasePath = "/js/fckeditor/" ;
        oFCKeditor.Height = 400;
        oFCKeditor.ReplaceTextarea() ;
    }

}

7 – FCKeditor changes

I like to implement FCKeditor as a single row of buttons for basic editing, just to keep it from looking too big and clunky. I use a set of icons like this:

FCKConfig.ToolbarSets["Default"] = [
	['Bold','Italic','Underline','StrikeThrough','OrderedList','UnorderedList','Blockquote','Link','Unlink','Image', 'SpecialChar','SpellCheck']
] ;

And I don’t want to enable any kind of file uploads, so I make sure these configs are all set to false (edited to show the relevant bits):

FCKConfig.LinkBrowser = false ;
...
FCKConfig.ImageBrowser = false ;
...
FCKConfig.FlashBrowser = false ;
...
FCKConfig.LinkUpload = false ;
...
FCKConfig.ImageUpload = false ;
...
FCKConfig.FlashUpload = false ;


8 – Anything else?

Not really! There are no Controller changes, which is good because this stuff all belongs in Views anyway. The Models know about the allowed tags, which is good because that’s the kind of work that Models should do. So to me this solution fits the MVC pattern and is not too hack-like. Feedback welcome…

Update: 25/3/09

Fixed various problems with the instructions and it should now all work properly.

Update: 20/3/09

I’ve been doing a bit of reading about Ruby on Rails with the intention of moving to it as my primary development platform. I haven’t quite got my head around the integration of front-end stuff like FCKeditor yet but Rails really does look like it simplifies the creation and maintenance of forms, which is, after all, about 70% of the work in websites. Need an example? Well Rails has a sensible defaults approach to forms where they can be created automatically based on the model. So compare that to Zend Framework, where I create a separate class for the Form that must match the structure of the model (and be updated when the model changes)! For a big site, that is significant: only one class per table/model!

Posted in zend framework. Tagged with , , , .

Zend Framework one-line platform config: Configure, Don’t Integrate

Separating config from code in Zend Framework is not as simple as it is in say, Ruby on Rails. And when your source code is version-controlled you want to minimise the manual configuration required. So here’s a nice way to keep it simple. The idea is to keep configuration data for your test and production environments in a single config file that does not change, then switch environments in a dedicated separate one-line config file.

Here’s a sample platforms.ini:

[test]
developer_mode = true
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.dbname = testdb
db.params.username = lkdf034k3k3b
db.params.password = SJGS43we3sdd

[production]
developer_mode = false
db.adapter = PDO_MYSQL
db.params.host = localhost
db.params.dbname = productiondb
db.params.username = ksjdhfkjjdhf
db.params.password = jfdhkjsdhdjk

.. .And here’s active_platform.ini. This is where we define which of test or production is currently active:

[platform]
setting = test

…And here’s how index.php refers to active_platform.ini to first determine which platform it’s on, and second load the appropriate config from platforms.ini:

// which platform mode are we on? i.e.: test or production
$active_platform = new Zend_Config_Ini('application/configs/active_platform.ini','active_platform');

// get the platform config
$config = new Zend_Config_Ini('application/configs/platforms.ini', $active_platform->setting);
Zend_Registry::set('config', $config);

// set up the db
$db = Zend_Db::factory($platform_config->db);
Zend_Db_Table::setDefaultAdapter($db);

When you want to deploy to production, you change the setting in active_platform.ini to ‘production.’ Simple as that.. this may be obvious but I’ve found it to speed up deployment and make it less error-prone.

Posted in zend framework. Tagged with , , .

40 Useful Mac OS X Shell Scripts and Terminal Commands

Here are a bunch of Mac OS X terminal commands sorted into general categories. I have intentionally omitted long bash scripts and AppleScripts and focussed instead on small useful commands that can be plugged into bigger scripts or used on their own… enjoy!

System

Restart Mac OS X:

shutdown - r now

Shutdown Mac OS X:

shutdown now

Power Management / Energy Saving

Get overview of current Power Management Settings:

pmset -g

Put display to sleep after 15 minutes of inactivity:

sudo pmset displaysleep 15

Put Computer to sleep after 30 minutes of inactivity:

sudo pmset sleep 30

…Also see my post about hibernate mode and Safe Sleep on the Mac

OS X Look and Feel

Permanently disable Dock icon bouncing

Disable Dashboard (don’t forget to drag the Dashboard Dock icon off the Dock too):

defaults write com.apple.dashboard mcx-disabled -boolean YES
killall Dock

Enable Dashboard:

defaults write com.apple.dashboard mcx-disabled -boolean NO
killall Dock

Force the Finder to show hidden files (very useful for Web Developers who need to edit .htaccess files, for example):

defaults write com.apple.finder AppleShowAllFiles TRUE

Force the Finder to hide hidden files (ie: back to the default setting):

defaults write com.apple.finder AppleShowAllFiles FALSE

Networking

Ping a host to see whether it’s available:

ping -o leftcolumn.net

Troubleshoot routing problems to a host using traceroute:

traceroute leftcolumn.net

Check whether a host is running an HTTP server (ie: check that a Web Site is available):

curl -I www.leftcolumn.net | head -n 1

Automatically enable Internet Sharing at startup

Manage Windows networks (a drop-in for the NET command on Windows). Too many options to list here, so run this for details:

man net

Use dig to discover Domain information:

dig www.leftcolumn.net A
dig www.leftcolumn.net MX

Who is logged in to your Mac?

w

Show routing table:

netstat -r

Show active network connections:

netstat -an

Show network statistics:

netstat -s

Troubleshooting

List all open files (this will take a few seconds to complete on most Macs):

lsof

Restart Bonjour – handy when a Mac ‘disappears’ from the Network:

sudo launchctl unload /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist
sudo launchctl load /System/Library/LaunchDaemons/com.apple.mDNSResponder.plist

Eject a CD… it’s never happened to me but you can eject a stuck cd with the following. Note that it won’t always be ‘disk1′:

diskutil eject disk1

Text Manipulation commands

Sometimes you need to take some text from the clipboard or a file, transform it somehow and then use it. Here are a bunch of commands that do text manipulation. I’ve assumed you want to transform text from the clipboard and back again, see the notes at the end of the article for info on how to write to and from files instead.

Count number of lines in the text in the Clipboard:

pbpaste | wc -l

Count number of words in the text in the Clipboard:

pbpaste | wc -w

Sort lines of text in the Clipboard and copy them back to the Clipboard:

pbpaste | sort | pbcopy

Reverse each line of text in the Clipboard (ie: make each line appear backwards) and copy them back to the Clipboard:

pbpaste | rev | pbcopy

Strip duplicate lines from lines of text in the Clipboard and copy only one instance of each duplicate line back to the Clipboard (output is sorted):

pbpaste | sort | uniq | pbcopy

Find duplicate lines from lines of text in the Clipboard and copy only one instance of each duplicate line (stripping non-duplicates) back to the Clipboard (output is sorted):

pbpaste | sort | uniq -d | pbcopy

Strip duplicate lines from lines of text in the Clipboard and copy only one instance of each line (stripping duplicates entirely) back to the Clipboard (output is sorted):

pbpaste | sort | uniq -u | pbcopy

Tidy up HTML in the Clipboard and copy it back to the Clipboard:

pbpaste | tidy | pbcopy

Display the first 5 lines from the Clipboard:

pbpaste | head -n 5

Display the last 5 lines from the Clipboard:

pbpaste | tail -n 5

Convert tabs to spaces for the lines in the Clipboard:

pbpaste | expand | pbcopy

Other useful commands

Password protect your web site! Create a CRYPTed user/password for using in a .htpasswd file. Save the outputted results of A below to a file called .htpasswd in the directory you want to secure. Then save the contents of B to a file called .htaccess in the same folder.

A:

htpasswd -nb username password

B:

AuthType Basic
AuthName "restricted area"
AuthUserFile /path/to/your/site/.htpasswd
require valid-user

Display a history of commands used in the terminal by the current user:

history

Convert a file to HTML. Support formats are Text, .RTF, .DOC.

textutil -convert html file.extension

Nano is a very easy-to-use text editor for quick changes to text files. It is less powerful than VIM but has the advantage of clearly showing you the common editing commands:

nano [file_to_edit]

…In nano, use ctrl+o to Save and ctrl+x to quit.

iTunes

Change iTunes link behaviour to point at local iTunes Library instead of iTunes Store:

defaults write com.apple.iTunes invertStoreLinks -bool YES

Change iTunes link behaviour to point at iTunes Store instead of local iTunes Library (ie: back to the default):

defaults write com.apple.iTunes invertStoreLinks -bool NO

Other Mac OS X Terminal Resources

Mac OS X Hacking Tools (old but detailed list for the obsessive only).

Cameron Hayne’s Bash Scripts

Mac OS X Hints

Apple Forums

Note: For commands where I’ve used pbcopy to get the contents of the Clipboard as input, you can use the contents of a file as input instead. Swap pbpaste for:

cat [/path/to/filename]

And to put the results into a file on your desktop, just swap | pbcopy for:

> ~/Desktop/filename.txt

… hope you find them useful!

Posted in mac osx. Tagged with , , , , .

MD5 Tool added to site

Here’s a new MD5 Tool for creating salted hashes of passwords. Just added this because I find it useful and it’s good to share!

Posted in site admin. Tagged with , .