Launch Google Chrome Incognito from the terminal or a shortcut in OSX

Problem: Ok not really a problem, but I want to be able to launch Google Chrome straight to Incognito mode from a shortcut. This is useful when logging into multiple bank accounts, Google Apps accounts, or testing session based websites. etc etc etc.

Fix: Thankfully the Google Chrome.app can be launched with the –incognito switch to do just that. The terminal command to do this, assuming the browser is sitting in /Applications/ is this:

open -a /Applications/Google Chrome.app --args --incognito

Note: –args has to be passed to satisfy the ‘open’ command’s arguments first.

Launching it from a shortcut: If you want to create a shortcut to do this, open AppleScript Editor and enter the following:

tell application "Terminal"
	activate
	do script "open -a /Applications/Google\ Chrome.app --args --incognito;"
	delay 1
	quit
end tell

Note: The space in the Google Chrome.app name must be double-escaped with two backslashes like that to work. Also, without the delay I found that the script exits too quickly or something like that, and it doesn’t work.

Save the above script as an Application, and call it something like ‘Incognito’. Running this app will launch Terminal, Chrome Incognito, then exit Terminal. Bingo!

Giving your Incognito app an Icon: I’ve added the app to my Dock, and given it a special icon (see below for a downloadable PNG icon). To do this:

  • Open the image you want to use as the icon – it should be a 512×512 24bit PNG if possible – and copy the image to the clipboard. If you are using Preview to view the image, do cmd+a to select all, then cmd+c to copy it… this works for most other graphics packages also.
  • Locate the app you created above in Finder, then press cmd+i to bring up the info window (alternatively right-click the app then select ‘get info’).
  • In the resulting pop-up, click on the icon at the top to highlight it like so (notice the blue halo around it):
    Original Script Icon
  • Then use cmd+v to paste the new icon from the clopboard into the icon area and it should look like this:
    New Incognito icon
  • Close the info window, and it’s done. You should now have a nice looking shortcut that opens Chrome Incognito with one or two clicks!

Feel free to use this icon. It’s just the standard one with some ‘colour replace’ work to make it blue. You could paste some tacky sun glasses over it if you wished 🙂

Convert eregi_replace to preg_replace in old class.phpmailer.php scripts

Problem: I have lots of legacy php code on old sites that uses eregi_replace to format up an HTML email body. As eregi_replace is now depreciated it can be replaced with preg_replace. This is tricky sometimes because the formatting is quite different.

Fix: Here’s a common line from class.phpmailer.php scripts:

$emailBody = eregi_replace("[]",'',$emailBody);

To convert that you’ll need to do this:

$emailBody = preg_replace("/\\/", '', $emailBody);

Wondering why there are so MANY escaping backslashes there? I asked that question and got this answer:

“..the backslash needs to be escaped once for the php string’s benefit, then again for the interpretation of the regular expression engine, as escaped characters like d indicate a digit in regular expressions. So a pattern of \d would match a digit, but \\d would match a backslash then a d character. PHP strings are lenient on backslashing when it isn’t necessary, so:
– setting a string to “d” will give it a value of d (the same as setting it to “\d”).
– but setting it to “”” will give a value of “.
– and setting it to “” will return a syntax error.

– PHP double quoted strings will consume the (first) backslash for \ n t r and “.
– PHP single quoted strings will only consume the first backslash for \ and ‘ “

There.. clear as mud!

WordPress replaces double and triple hyphens (– or —)

Problem: The other day I was trying to type two hypens (–) in a post, and when I saved/published the post, WordPress reformatted the hypens to display as an ‘en dash‘ (–).

More Info: After some searching about, and some helpful info provided in the WordPress Codex, I found out about a WP function called ‘wptexturize’ which is applied each time a post is rendered. The function – which can be found in ‘wp-includes/formatting.php’ – replaces quite a few things, like ™ to ™ etc.

Fix: You could stop this happening a number of ways i.e. editing the function to stop it doing the replace altogether, or install a plugin that does it (maybe this one, haven’t tried it!). I decided to use WordPress’s remove_filter function to stop the reformatting taking place.

To do this, open the ‘functions.php’ file within your theme. If one does not exist, create it.

Add the following code to the bottom of the file, taking care not to end up with too many or too few <?php tags:

<?php
remove_filter('the_content', 'wptexturize');
remove_filter('the_title', 'wptexturize');
?>

Then save the file (or ‘update’ if you’re doing this via the theme editor in WP admin) and view your post. That should do it! (proof is here, you can only see those double and triple hyphens in this blog post title because I’ve just added the code above to this sites functions.php also!)

Add ‘Drafts’ sorting to Shopp Products list

Problem: There is no ‘drafts’ view filter in the Shopp (>1.1.9) Product Manager, i.e you can’t quickly list all the products that have ‘draft’ status in one go.

Fix: I made this mod to answer a question in the Shopp Helpdesk forum, it’s not very tested, but seems to work perfectly!

Open ‘wp-content/plugins/shopp/core/flow/Warehouse.php’ and replace this:

198
$subfilters = array('f' => 'featured','p' => 'published','s' => 'onsale','i' => 'inventory');

With this:

198
$subfilters = array('f' => 'featured','p' => 'published','d' => 'draft','s' => 'onsale','i' => 'inventory');

Then in the same file replace this:

199
200
201
202
203
204
205
$subs = array(
'all' => array('label' => __('All','Shopp'),'columns' => "count(distinct pd.id) AS total",'where'=>'true'),
'published' => array('label' => __('Published','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pd.status='publish'",'request' => 'p'),
'onsale' => array('label' => __('On Sale','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pt.sale='on'",'request' => 's'),
'featured' => array('label' => __('Featured','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pd.featured='on'",'request' => 'f'),
'inventory' => array('label' => __('Inventory','Shopp'),'total' => 0,'columns' => "count(distinct pt.id) AS total",'where'=>"pt.inventory='on' AND pt.type!='N/A'",'grouping'=>'pt.id','request' => 'i')
);

With this:

199
200
201
202
203
204
205
206
$subs = array(
'all' => array('label' => __('All','Shopp'),'columns' => "count(distinct pd.id) AS total",'where'=>'true'),
'published' => array('label' => __('Published','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pd.status='publish'",'request' => 'p'),
'draft' => array('label' => __('Draft','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pd.status='draft'",'request' => 'd'),
'onsale' => array('label' => __('On Sale','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pt.sale='on'",'request' => 's'),
'featured' => array('label' => __('Featured','Shopp'),'total' => 0,'columns' => "count(distinct pd.id) AS total",'where'=>"pd.featured='on'",'request' => 'f'),
'inventory' => array('label' => __('Inventory','Shopp'),'total' => 0,'columns' => "count(distinct pt.id) AS total",'where'=>"pt.inventory='on' AND pt.type!='N/A'",'grouping'=>'pt.id','request' => 'i')
);

Hopefully this will be included in a future version of Shopp.

Swap days and months in PHP – quick and dirty MM/DD/YY to DD/MM/YY

Problem

I have a ton of date strings in the stupid US style dd/mm/yy format. i.e. 12/24/09 being 24th September 2009. I need to convert them to the UK style dd/mm/yy.

Solution 1

As a string in PHP is really just an array of characters, the simplest fix was to address the individual number characters by their positions within the sting, and rearrange them into the format I wanted:

$d = "12/24/09";
$d = $d[3].$d[4]."/".$d[0].$d[1]."/".$d[6].$d[7];
echo $d; // displays "24/12/19".

Solution 2

I posted my solution on twitter (@hutchings) and asked for comments and @londonhackspace organiser Jonty came back with the following elegant (and much cleverer) suggestion:

$d = "12/24/09";
$d = preg_replace('|(d+)/(d+)/(d+)|', '$2/$1/$3', $d);
echo $d; // displays "24/12/19".

So provided you know that your original string is in US format, both these solutions can be used. In my testing I found solution 1 executed more quickly, but isn’t as pleasing to look at 🙂 Cheers Jonty.

Cannot set alpha on dynamic text in Flash / ActionScript 2

Problem

I’m doing some freelance Flash development, and it’s been a while. I have just created a dynamic text field that I wanted to fill via actionscript, then fade in via an alpha tween. This wasn’t working, even if I set _alpha = 0 on the movieclip containing the text field.

Solution

You can only set _alpha on a Dynamic Text field if the font has been embeded (with the embed button).

Works now! wohoo! Simple stuff that I’ve known in the past, but forgot.

Set space between list item and bullet (HTML, CSS)…

Problem

I’ve just had to convert a Photoshop visual to a WordPress template. The designer wanted a bulleted list where the bullets themselves were very close to the list items, and were small dashes. Cross browser support for list item and bullet styling is ropey at best, and to make things perfect I’d have to resort to browser specific styles.

Solution

The solution I think I’ll be using for the rest of my ‘web’ career will be this. JUST FORGET THE BULLET ITEM, and use positioned background images instead.

In the stylesheet, add styles for both the ‘ul’ tag, and the ‘li’ tag like so (explanations inline):

ul {
margin-left:0px; /* Set the indenting back to far left. */
padding-left:0px; /* Set the indenting back to far left. */
}
 
ul li {
list-style-type:none; /* Switch the list bullet off altogether. */
background-image:url(dashbullet.gif); /* The replacement bullet image */
background-position:0px 4px; /* Place bullet 0px from left and 4px from top */
background-repeat:no-repeat; /* Stops bullet tiling, important */
padding-left:7px; /* separation from li txt and bullet */
}

Then just create the list as you usually would, with ‘ul’ and ‘li’ tags. Here’s what it looks like in use:

Bullet fix in CSS

Here’s a bit more detail so you can get your head around the spacing. It’s incredibly simple, but still, nice to have a diagram or two sometimes:

Detail showing some dimensions and spacing
Detail showing some dimensions and spacing

This style works perfectly (by my testing, but I’m not perfect) on:

  • Internet Explorer 6, 7 & 8+
  • Firefox 2.*+
  • Opera 9+ (not tested 8, but bet it works!
  • Google Chrome (all versions)
  • Safari (Mac and PC versions)
Any problems, please post a question or comment below.

Quick ‘Lorem Ipsum’ plugin / extension for IE

Problem: While doing web development, I frequently need to insert lorem ipsum into a text field or textarea. To do this – bearing in mind that I don’t really like or use bookmarks, too messy – I tend to google “lorem ipsum”, hit lipsum.com, select/copy the block of text, and then return to my form field and paste it.

I wanted a quicker solution, and as I find myself using IE more and more to develop in now (thanks to the excellent ‘Developer Tools’ extension – never thought I’d say that!) my lorem ipsum fix would have to be in the form of an IE toolbar button or menu item.

Fix: It turns out that adding a simple javascript based text field filler option to a context menu is really easy, so that’s what I did. Here are the steps:

Firstly: Create the javascript to access the currently focused field, and insert the lorem ipsum text. Create a new html file in a location of your choice –  I used C:Program FilesInternet ExplorerPlugins – and copy the following code into it:

<script language="JavaScript">
var parentwin = external.menuArguments;
var doc = parentwin.document;
var rng = doc.selection.createRange();
rng.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
</script>

Save the file as loremipsum.htm.

Secondly: Create the registry entry for the menu item:

  1. Open/run ‘regedit’ (Start > run… > “regedit” > ‘Ok’)
  2. Use the tree to navigate to:
    HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMenuExt
    using the tree view on the left of the Registry Editor.
  3. Create a new key (Right click, “New” > “Key”) and call it “Lorem Ipsum” or anything you like.
  4. Inside the new key, open the ‘default’ string value that’s already there (double click on it), and enter the path to the script you created just now. i.e. C:Program FilesInternet ExplorerPluginsloremipsum.htm
  5. Now create a new DWORD value (Right click, “New” > “DWORD Value”) and rename it “Contexts”. Set the value to 0x04 (hex) or 4 (decimal). Here’s an explanation of the different values.
The new Key and values in RegEdit
The new Key and values in RegEdit

 

That’s it! Now open IE, find a textarea or text field, right click, and you should see something like this:

Note the new highlighted option in the context menu
Note the new highlighted option in the context menu

Moving VirtueMart: Link path problem in admin console

Problem: Just now, I needed to move a website running Joomla 1.5 and VirtueMart 1.1.2 from the development server, to the live web space. After I had moved the data, and the files, and updated the path in Joomla’s ‘configuration.php’ file, it seemed to work ok, but all the links in the VirtueMart Admin area still pointed to my development server.

Fix: After doing a ‘find in files’ for my development server’s name, I found two more paths that need changing in VirtueMart’s own configuration file. This is the file:

/administrator/components/com_virtuemart/virtuemart.cfg.php

The following two paths need editing to point to the new server location (URL):

35
36
define( 'URL', 'http://my.devserver.com/joomla/' );
define( 'SECUREURL', 'https://secure.devserver.com/joomla/' );

A simple fix, but probably worth posting.

Select template by Section in Joomla 1.5

Problem: In Joomla 1.5, at present, there is no way to set the template applied to an article or category  based on the section that article is in. Templates can be set by menu item, but not by the overall section they reside in. This means that if multiple templates are being used, each time a new article is added, changes have to be made to the template setup too – very tedious. All I wanted was to be able to create an article or category, add it to a certain section, and know that it would be rendered/displayed using a particular template:

Fix: This took some searching and tweaking. I found a post in the Joomla developers forum about someone trying to do something similar, but their example code was broken. It was enough to get me started though.

What you need to do is: find and open application.php in the includes directory on the root of your Joomla 1.5 installation. Then find line 309 or thereabouts and look for this code:

309
310
311
// Allows for overriding the active template from the request
$template = JRequest::getCmd('template', $template);
$template = JFilterInput::clean($template, 'cmd'); // need to filter the default value as well

Insert AFTER the comment on line 309, but BEFORE line 310, add this code:

// Templates by Section hack - Begin
 
$eItemView = JRequest::getVar('view');
$eItemId = JRequest::getVar('id');
 
$sectionId = NULL;
 
$eItemId = (strpos($eItemId,":"))? substr($eItemId,0,strpos($eItemId,":")) : $eItemId;
 
switch ($eItemView) {
case "article":
$edb =& JFactory::getDBO();
$eQuery = 'SELECT sectionid FROM #__content WHERE id LIKE '.$eItemId.'';
$edb->setQuery($eQuery, 0, 1);
$sectionId = $edb->loadResult();
break;
case "category":
$edb =& JFactory::getDBO();
$eQuery = 'SELECT section FROM #__categories WHERE id LIKE '.$eItemId.'';
$edb->setQuery($eQuery, 0, 1);
$sectionId = $edb->loadResult();
break;
case "section":
$sectionId = $eItemId;
break;
}
 
// Edit the section id below, you can find it in the sections admin area.
if ($sectionId == "1") {
$template = "rhuk_milkyway_red"; // Use the full template name.
}
// Add more if clauses if there are other templates.
 
// Templates by Section hack - End

Hopefully you can see what this does. It looks for the section id to use in 3 ways, depending on whether joomla is currently displaying a section root page, a category root page, or an article. It then looks to see whether that section id has had a specific template specified for it by name.

This hack works well for me, I only need to add the different template data once in application.php for a given site. Ideally someone needs to make an admin mod for this, so that sections and categories can be assigned different templates in the backend. Maybe one day I’ll make one, but not unless there’s demand 🙂

Any questions, corrections or thoughts, please comment below (no need to create an account or anything!)