Magento PHP Extension “mcrypt” must be loaded – Mac OSX Lion

Ever try to setup Magento in a local dev. environment on your Mac? You might have encountered an error message: PHP extension “mcrypt” must be loaded

Well we better load it then! This solution here worked perfectly for me: http://michaelgracie.com/2011/07/21/plugging-mcrypt-into-php-on-mac-os-x-lion-10-7

Posted in General | Leave a comment

Show hidden files on Mac OSX

Ever needed to show those hidden files in Finder? I’ve tested this successfully in both Snow Leopard and Lion.

  1. Throw these two lines in your ~/.bash_profile (if it doesn’t exist, just create it)
  2. alias sf="defaults write com.apple.Finder AppleShowAllFiles true; killall Finder"
    alias hf="defaults write com.apple.Finder AppleShowAllFiles false; killall Finder"
    
  3. Reload your .bash_profile. From within terminal:
  4. . ~/.bash_profile
    
  5. Type sf to show all hidden files
  6. Type hf to hide all typically hidden files
Posted in General | Leave a comment

Getting Quicksilver to Launch at Startup on OSX Lion with a SSD

Quicksilver Splash

No Mac setup is complete without Quicksilver. If you’ve never heard of or used it before, I urge you to give it a try. It’s a lightning fast app launcher that’ll really increase your speed/productivity by reducing the amount of clicks/searching/typing you need to do to perform a task.

I digress; I recently installed a fresh version of OSX Lion on my machine and one of the first apps I installed was QS. However I quickly noticed that the Start at Login function wasn’t working very well –see not at all.

Symptoms:

  • QS logo appears at startup, but never completely fades out
  • The QS hotkey (CTRL+space) works and brings up the prompt but any subsequent keystroke is ignored

After a bit of searching I found the solution from Jon Stovell on the blacktree-quicksilver google group. It seems to affect OSX Lion setups and in particular machines using Solid State Drives or in my case a Solid State Hybrid Drive.

For completeness sake, here is the solution:

  1. Turn off the Start at login option in QS’s preferences.
  2. Paste the text below into a new plain text file in TextEdit.
  3. Save the file in ~/Library/LaunchAgents with a name like “QuicksilverStartAtLogin.plist”
  4. QS will now automatically start on next login
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>QuicksilverStartAtLogin</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Applications/Quicksilver.app/Contents/MacOS/Quicksilver</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

Optionally, you can replace <key>RunAtLoad</key> with <key>KeepAlive</key> if you want QS to restart automatically if it ever crashes.

Happy QS’ing

Posted in General | Leave a comment

brunno.in JS injection using WSO 2.2

A client recently gave me a call saying his website was throwing a malware warning when visited using Google Chrome.

Chrome Malware Warning

Chrome Malware Warning

A bit of research indicated that somehow the attacker gained access to the site, installed a Web Shell script in *.js.php files and injected JS code into existing JS files.

Google’s Webmaster Tools showed the injected code in the JS file:

Injected JS

Injected JS

The above code, once processed, created an iframe that lead to another site that perhaps contained malicious code:

<iframe frameborder="0" width="10" height="10" src="http://brunno.in/showthread.php?t=37220338"></iframe>

The other file: *.js.php is Gzipped and base64 encoded. When inflated and decoded it shows to be a Web Shell script or more specifically WSO 2.2. This allows the attacker to access & perform server based functions from the browser and easily insert malicious code.

You can find the inflated and decoded code here: WSO 2.2

What do do?
You can manually look through your files and remove all occurrences or if you have SSH access: remote to your server and use egrep/sed to match the recurring pattern and remove.

Posted in General | 1 Comment

Enabling IPv6 in Google Chrome

Alright, this will be a quick post but I wanted to take 5 and write this out for prosperity and maybe somebody else will have a similar issue.

I currently develop in RoR and PHP amongst other languages. For Rails I use Pow to quickly setup a development environment. For PHP I just set manually using the following instruction: How to setup your mac web development environment

The problem is when you use Pow, it kind of breaks your PHP development environments. So the quickest and easiest solution I found was to enable IPv6 in Apache so that your PHP dev. environments don’t conflict with Pow. Instructions on how to do this can be found here: Pow and Apache side by side.

All was good in the hood… until I ditched Firefox for Chrome. I used to use Firefox as my main browser, mainly due to Firebug. Recent developments such as Firefox’s rapid deployment schedule (Which I’m not a fan of, but that’s a whole other story) and high memory usage (I was hovering at 1.24gigs last I used FF with 5 tabs open) spurred me to change browsers.

In comes Google Chrome, life is good. Fast, small memory footprint, great built-in dev. tools… Life is good. But wait a minute, I can’t access my internal PHP dev. projects anymore. Turns out it has something to do with IPv6 and having the same DNS entry on your local machine and on the web… the exacts of it, I don’t know. But I’ve got a SOLUTION! If you’ve read this far, here it is:

Paste this in your Google Chrome address bar:
chrome://net-internals/#dns

Click on Enable IPv6

All done! I haven’t thoroughly tested for symptoms like other pages not loading but so far so good. If you have any information regarding this, please feel to share.

Posted in General | Leave a comment

Top 11 Ruby on Rails Learning Tools

Ruby on Rails LogoAbout a year ago I decided it was time to start learning RoR (Ruby on Rails) with the ultimate goal being that it’d replace PHP in most of my projects. While I’m still not at that point, here’s a top 11 list of Ruby and Ruby on Rails tutorials, tools and resources that really helped me out!

One thing I didn’t expect when I started with Rails is its community: for such a relatively young framework, its community of devoted followers is a reflection of the technology itself. Having said that, this is by no means an exhaustive list of the resources that are out there. This is what worked for me and hopefully helps you too.

  1. Ruby on Rails Tutorial by Michael Hartl

  2. Rails Tutorial
    Some people rather read to learn while other prefer to watch/listen to learn. I fit right in the middle. I feel each medium can sometimes better convey an idea or concept. This is where Rails Tutorial really scores for me.

    Firstly, Michael is an excellent teacher, albeit very geeky. His screencasts are very informative without being over the top, they’re divided in tidy chapters and best of all he’s just plain good at explaining things. He stops and takes the time to explain all the important and somewhat harder to grasp concepts while giving you a great idea of how a professional programmer works. Tie this in with the book format of his tutorial and you’ve got a solid toolset to help you create your first Rails app.

  3. Rails for Zombies by Gregg Pollack @ Envy Labs

  4. Rails for Zombies
    Not quite sure about Rails? Then try this out: it’s interactive, no installation required, works right out of your browser and it’s actually pretty fun. Did I mention it was free? It gives you a great but brief overview of what you can do with RoR and how you can do it.

  5. RailsCasts by Ryan Bates

  6. Railscasts
    Ryan releases a screencast every week or so focusing on RoR and RoR associated stuff such as Gems and release updates. They typically run between 8 to 15 minutes long and are really easy to follow and usually easy enough to understand by even the novice programmer.

  7. Try Ruby by Eric Allam & Nick Walsh

  8. Try Ruby
    Read, use, learn, remember. Putting in practice what you learned is a great way to not only remember but understand capabilities and limitations. Try Ruby is a great example of this. Nothing to install and free: Dead simple but beautifully so!

  9. Beginning Ruby by Peter Cooper

  10. Beginning Ruby
    Because Rails is basically an MVC(Model,View,Controller) framework for web development using Ruby it makes sense to know at least a little Ruby. Well this book by Peter Cooper is an absolute gem for learning Ruby. It’s very beginner friendly but some base knowledge of OOP(Object Oriented Programming) doesn’t go amiss. Well written, thick and chock-full of examples; I use it almost daily and not just to as an over-sized coaster for my end of day beer.

  11. Ruby on Rails Guides

  12. RailsGuides
    This list wouldn’t be complete without mention of the Ruby on Rails Guides. Constantly being updated and to the point. They’re a great reference when you’re getting started and remain useful as new versions of RoR come out and your brain starts forgetting stuff.

  13. PRY

  14. Pry
    PRY is basically a fancy Interactive Ruby Shell (IRB) or Rails console for you to play in. It allows you to do all sorts of useful stuff like navigate through your code using everyday commands like ls and cd, runtime invocation to debug your application, get documentation right in the console for that new class/method you know nothing about… The list goes on and the best way to get an idea of just how powerful this gem is: watch these two awesome screencasts: Joshua Cheek from CodeSchool and Ryan Bates from RailsCasts

  15. Ruby on Rails Documentation

  16. Ruby on Rails Documentation
    Perhaps not always the best beginner tool, but it sure shines when you’re starting to “get the hang of it”. Ruby on Rails official API is obviously a great reference when you need to get down to the nitty gritty.

  17. Cucumber – Behaviour Driven Development

  18. Cucumber
    I wont explain here why or how it works but rather why it works so well for learning. First and foremost, there’s a pretty good chance you’ll use these tools as a professional programmer. Secondly it allows you to write out in plain english(or whatever language you prefer) how you want your app to behave. From there, the tests will fail(since you haven’t actually written code) and kind of guide your development process. It’s the guidance and natural flow BDD provides that helped me learn Rails.

  19. RSpec – TDD of the BDD package

  20. RSpec
    Very similar to the above RSpec is a bit more finer grain testing then Cucumber but they work hand in hand. RSpec is a Test Driven Development tool that allows you to write tests describing how your app should react to specific conditions. Once again, it really helps drive your project and allows you to refactor later without worrying you’re breaking your application.

  21. #RubyOnRails on Freenode IRC

  22. Freenode
    Sometimes you can “Google it” all you want and still come up empty handed. Sometimes you just need somebody to listen… an outsider with a fresh outlook and bigger brain. In these cases, the #RubyOnRails channel on the Freenode IRC network is a great place to start. Crowdsourcing at its best, there’s a good chance the combined wisdom of gem cutting conductors will have an answer for you!

That’s about it! I’m sure there are probably many more great resources out there and I’d love to know about them. If you liked(or not) this post, let me know what worked for you and share the love!

Posted in General, Programming | Leave a comment

Refactoring a user input generated SQL query

I’m sure many of your are familiar with PHPMyAdmin. In short it’s a nice frontend to MySQL written in PHP that enables you to visually manipulate your MySQL databases and underlying data.

The reason I mention PHPMyAdmin is I recently needed to add a similar feature of PHPMyAdmin into one of my applications. The feature being: generate an SQL query based on users input from checkboxes.

The idea is simple: I want the user to be able to filter what type of orders will be displayed on the orders page by their payment status (Paid, Pending, Failed, Refunded)

When I’m not entirely clear on how to approach a problem programatically I tend to write it out in it’s longest version then refactor:

The very long winded and definitely not the best approach:

$switch = false;
if(!isset($payment_status['paid']) || !isset($payment_status['pending']) || !isset($payment_status['failed']) || !isset($payment_status['refunded'])) { //One of them is unset so we can act
  if(isset($payment_status['paid']) && $switch == false) {
    $switch = true;
    $sql .= " AND (orders.payment_status = 'paid'";
    if(isset($payment_status['pending'])) {
      $sql .= " OR orders.payment_status = 'pending'";
    }
    if(isset($payment_status['failed'])) {
      $sql .= " OR orders.payment_status = 'failed'";
    }
    if(isset($payment_status['refunded'])) {
      $sql .= " OR orders.payment_status = 'refunded'";
    }
    $sql .= ")";
  }
  if(isset($payment_status['pending']) && $switch == false) {
    $sql .= " AND (orders.payment_status = 'pending'";
    if(isset($payment_status['failed'])) {
      $sql .= " OR orders.payment_status = 'failed'";
    }
    if(isset($payment_status['refunded'])) {
      $sql .= " OR orders.payment_status = 'refunded'";
    }
    $sql .= ")";
  }
  if(isset($payment_status['failed']) && $switch == false) {
    $sql .= " AND (orders.payment_status = 'failed'";
    if(isset($payment_status['refunded'])) {
      $sql .= " OR orders.payment_status = 'refunded'";
    }
    $sql .= ")";
  }
  if(isset($payment_status['refunded']) && $switch == false) {
    $sql .= " AND orders.payment_status = 'refunded'";
  }
}

This solution basically enumerates each possibility and then adds the appropriate SQL query to the $sql variable that will then later be ran against the DB.

This is a poor solutions for many reasons, but chief amongst them:

  1. Very long winded and repetitive which goes against the DRY principle
  2. Each time you add a new payment status the code snippet would grow down the line and it wouldn’t be long before it would be unmaintanable

The next refactored version looks a bit better:

if(!isset($payment_status['paid']) || !isset($payment_status['pending']) || !isset($payment_status['failed']) || !isset($payment_status['refunded'])) { //One of them is unset so we can act
  $sql .= " AND (0 = 1";
  if (isset($payment_status['paid'])) {
      $sql .= " OR orders.payment_status = 'paid'";
  if (isset($payment_status['pending'])) {
      $sql .= " OR orders.payment_status = 'pending'";
  }
  if (isset($payment_status['failed'])) {
      $sql .= " OR orders.payment_status = 'failed'";
  }
  if (isset($payment_status['refunded'])) {
      $sql .= " OR orders.payment_status = 'refunded'";
  }
  $sql .= ")";
}

What we’re doing here is we’re forcing the OR by adding 0 = 1 which will always return false. This then allows us to create a statement made completely with OR instead of AND like we were using in the first example which lead us to repeat ourselves. This is based on a truth table, check it out if you want more information.

Having said that, I think we can still do better!

Last and definitely not least we have:

$sql .= " AND orders.payment_status IN('".implode("','",array_keys($payment_status))."')";

Down from 37 lines to 1. Now that’s refactoring.

Let’s break it down:

  1. We use the MySQL operator IN() to Check whether a value is within a set of values
  2. We use PHP functions implode and array_keys to join the array keys(paid, pending, failed, refunded) into a string joined by a comma therefore building our IN() values to check

Say the user checked the paid and refunded boxes we’d get a query that would look like this:

 AND orders.payment_status IN('paid','refunded')";

Conclusion

Refactoring is cool!

Posted in Programming | Tagged , , , , , , | Leave a comment

MySQL query returning truncated results could be because of group_concat

I recently encountered an issue where my MySQL query was returning truncated results… and by truncated I mean it was returning only a fraction of the rows it should have been returning and the last of those rows was actually missing data.

The query in question uses a few LEFT OUTER JOIN(s) and the GROUP_CONCAT function to eliminate duplicate results due to a many-to-one relationship as shown below:

Turns out that the results were getting truncated due to a GROUP_CONCAT memory limitation configured by: group_concat_max_len

I therefore had a few options:

  • Remove GROUP_CONCAT from the query and deal with the duplicate results programmatically
  • Split up the query in perhaps 2 or 3 individual queries
  • Overwrite the group_concat_max_len variable in PHP for the session

I chose the latter by adding the following snippet in my DB configuration file.

if (!mysqli_query($link, 'SET SESSION group_concat_max_len = 102400;')) {
	$error = 'Error setting group_concat_max_len: ' . mysqli_error($link);
	include $_SERVER['DOCUMENT_ROOT'].'/error.html.php';
	exit();
}

I ended up setting the value to 102400 bytes which was about the max size I could foresee the group_concat having to process.

You can check your MySQL value was by running the following in the terminal:
$ mysqld --verbose --help

Hope this helps someone!

Posted in Programming | Tagged , , , | Leave a comment

jQuery Checkbox select all

Ever wanted to allow a user to click the Select all checkbox and have all the checkboxes magically have checks in them?

You might want to do that if you have lots of options, especially if your checkboxes are being generated dynamically from information pulled from a database. The latter is what prompted me to add a select all button to one of my web apps. So like any developer who’s first, second or even third language isn’t Javascript, I fired up Google and searched for a solution.

The initial solution (not so good)

After copy pasting a bit of code here and there, I came up with a basic solution that uses document.getElementsByName

The Javascript looked like this:

<script type="text/javascript">
  function toggle(source,tgt) {
    checkboxes = document.getElementsByName(tgt);
    for(var i in checkboxes) checkboxes[i].checked = source.checked;
  }
</script>

The html:

<input type="checkbox" onClick="toggle(this, 'product[location_id][]')" />Select All<br/>

Now this worked fine until I tested it in IE. Dreaded IE! Turns out it doesn’t work because of an IE bug that doesn’t like document.getElementsByName

The best solution

So back to the drawing board or should I say Google. That’s when I found this gem: http://briancray.com/2009/08/06/check-all-jquery-javascript/

It uses jQuery which is a Javascript library. The brilliance is that it requires very little code upfront and it uses the fieldset html tag to wrap the checkboxes that you wish to check/uncheck with your select all checkbox. Therefore you can easily have many different checkbox groups with their own select all checkbox on the same page without any mixups.

Posted in Programming, Web | Leave a comment

Connect to MySQL using localhost instead of 127.0.0.1 on a MAC

For a long while now I’ve been connecting to MySQL on my development platform with 127.0.0.1 because for some reason localhost didn’t work.
Turns out it’s because 127.0.0.1 uses TCP/IP and localhost uses sockets.
The php.ini file points to the wrong place for the mysql.sock so all you have to do is change it, restart apache and voila!

  • Open php.ini: /private/etc/php.ini
  • Find the following line: mysql.default_socket = /var/mysql/mysql.sock
  • Replace with: mysql.default_socket = /tmp/mysql.sock
  • Restart apache: apachectl restart
  • Happy days!

Note: If you don’t have a php.ini file, you need to copy the provided default called php.ini.default

sudo cp /private/etc/php.ini.default /private/etc/php.ini

Thanks to Blog.Andrei.MD for the info.

Posted in General | Leave a comment