Blue Screens and SSDs

Over the past weekend I spent 3 days troubleshooting a constant blue screen of death problem. It was like no problem I've ever dealt with as the symptoms were very unusual. When I was using the computer, whether playing a game, browsing the internet or simply just working, it would freeze up. It wouldn't freeze in the usual sense, it would freeze up program by program (when I clicked to each one) until I couldn't do anything except move my mouse and wait for the unavoidable BSOD. It would even BSOD while my computer was idle, weird!

Like any competent PC owner, I tested all the hardware piece by piece. I started by disassembling the computer, cleaning everything, checking for damage, and reassembling; all good. I checked all drivers and updates. I tested each memory stick one by one. I monitored the temperature and voltage, and found nothing out of the ordinary. That only left the video card, power supply, hard drives (1 SSD, 2 HDD) and possibly the motherboard. I ruled out the power supply by monitoring the voltage. I ran disk cleanup, disk check and defragment on all the drives and they all passed. I never tested another video card as I believed it wasn't a video issue, since the symptoms had nothing to do with display. That left me with the MOBO, which I was really hoping wasn't the problem.

Before I went any further, I queried all my tech knowledgeable friends for a solution... they had none. They all suggested doing a system wipe, which I think is absurd until you determine whether it's a hardware or software issue. So I enabled BSOD logging which would allow me to read the dumps and discover a solution. However, another problem arose when the BSOD dumps were never written during a crash, and the administrative event logs weren't helpful either. I was at a loss at this point and really didn't want to spend money building a new system.

Since BSOD logs weren't being generated, a friend suggested waiting for a BSOD to occur and to write down the error message that appears. So I did. The following is a summary of the BSOD.

A process or thread crucial to system operation has unexpectedly exited or been terminated. Stop: 0x000000F4 (0x0000000000000003, 0xFFFFFA800C13D060, 0xFFFFFA800C13D340, 0XFFFFF800039D9350).

At a glance it doesn't come off as helpful, but that didn't stop me. I Googled around using "BSOD 0x000000F4" as my term coupled with each piece of hardware I was utilizing, until I found something. It just so happens that my Crucial M4 SSD that I installed a little over a year ago was the culprit. After 5,000 hours of on-time, the SSD will crash unexpectedly. The math since installation checks out: (12 average hours a day * 30 days a month) * 14 months = 5,040. With a little firmware update from the Crucial guys, I've been BSOD free for a couple days now.

I felt the need to blog this as I'm sure it would be helpful to others who encounter such weird issues, especially with new tech like SSDs. You've been warned!

Repository Cleanup

I'm currently in the mood to cleanup all my Github repositories, and with this will come some changes. I am posting this to give a warning to anyone who is cloning my repositories either directly or via submodule, as some of the repository names (and URLs) will change. This overhaul is meant to free up some of my time as I plan to veer away from starting any new projects (unless it's part of a client request) and merely want to support my current projects with bug fixes and new features, if any. With this change, the following changes are happening:

The following projects will have their names changed:

  • php-decoda --> Decoda
  • php-transit --> Transit
  • php-packager --> Packager
  • cakephp-utility --> Utility
  • cakephp-forum --> Forum
  • cakephp-uploader --> Uploader
  • moo-decoda --> Decoda.js

The following projects will be deprecated and no longer receive any kind of support:

  • cake-decoda
  • cake-ajax_handler
  • cake-auto_login
  • cake-cache_kill
  • cake-feeds
  • cake-spam_blocker
  • cake-redirect_route
  • cake-we_game
  • php-type_converter
  • php-statsburner

Most of the deprecated projects were moved to the Utility plugin or the Titon project and will continue to receive support there. The stand alone projects are merely deprecated.

The following projects will no longer be supported excluding critical bugs:

  • php-compression
  • php-resession
  • php-numword
  • php-gears
  • php-formation
  • php-databasic

Thanks for all your continuing support and sorry if these minor changes cause any hiccups. Please be patient and give Github and Composer some time to propagate the changes.

RFC proposal for getters and setters

If you haven't been following the PHP development lately, then you have been missing out. Recently, there was a vote on the PHP mailing lists about adding short syntax for arrays (ala Javascript), yet the devs vote against it with childish excuses. And then there was this one guy who forked the PHP project and patched it with speed improvements and features the users have been wanting (which I completely agree with). You can also view the PHP RFC Wiki on the list of *possible* features and the ones that were denied. As you can see, there is much happening in the PHP community, but nothing to show for it (yet).

However, my post today will be on the RFC suggestion for built in getters/setters. To keep it blunt, I really dislike the C# approach... it's, just not very PHP. Just seems odd to have floating curly blocks with a "get" and "set" in it, with no real defined scope block. On top of that, the "property" keyword is way too complicated for what it is trying to achieve. The one thing I do agree with though, is the readonly modifier. My suggestion is loosely based on the Traceur Compiler by Google syntax (they use get/set keywords instead of function, within the class).

class FooBar {
	public $value;
	protected readonly $_readOnly;
	protected static readonly $_static;
	public get value() {
		return $this->value;
	}
	final public set value($value) {
		$this->value = $value;
	}
	public get readOnly() {
		return $this->_readOnly;
	}
	public static get static() {
		return self::$_static;
	}
	public function noop() {
		return;
	}
}

Admittedly, my suggestion is a bit more verbose than the C# variant, and pretty similar to regular getValue() and setValue() methods, but there are a few key differences.

Method Naming

Technically, are they still considered methods? Regardless, when you are writing getters and setters, you should use the words "get" or "set" in place of "function". This dictates to the class that these methods should be used anytime a property is being read or written to. On top of this functionality, the visibility modifiers are in effect (public, protected, private). This allows you to write to protected properties using a public setter, or reading from private properties with a protected getter (while in the class scope of course). Final and static keywords work exactly the same as well. Below is a quick example.

$foo = new FooBar();
$foo->value = 'setter'; // calls set::value()
$foo->readOnly = 'readonly'; // throws an error/exception
FooBar::$static = 'static'; // throws an error/exception
echo $foo->value; // calls get::value()
echo $foo->readOnly; // calls get::readOnly()
echo FooBar::$static; // calls get::static() statically

Getters and setters are not required, but when implemented, they are automatically triggered. If a property is public, without a getter/setter, then getting/setting a value works like it normally would. The major difference with this proposal is allowing the getting/setting of non-public properties, and never having to write getValue() or setValue() (you just modify the property directly like the example above).

Read Only

One of the features within the original proposal that I did like, was the readonly keyword. This keyword can be applied to any class property to set it into a read-only state, which basically disallows the use of a set method. It also disallows setting a value to the property directly, using the old functionality. But this sounds like the final keyword right? Technically yes, the major difference is that you can overwrite a readonly value in a sub-class, and not with a final.

Abstract and Interfaces

These could also be used with abstract classes and interfaces, like so.

interface FooBar {
	public get value();
	public set value();
}
abstract class FooBar {
	protected $value;
	abstract protected get value();
	abstract protected set value();
}

Now this is just a personal preference and style, and is something I have been thinking about lately (I have ideas for other RFCs as well), so don't expect this to actually happen! I also didn't get too in depth, for example, when are magic methods called during this process? I will leave those out unless for some odd reason this makes it in (heh). Let me know what you think!

Using Closures as callbacks within loops

In jQuery (and other Javascript frameworks) it is quite common to use closures (I refer to them as callback functions) to loop over arrays or objects. Even though it's a slow process and is much more efficient to use the built-in for loop, it got me thinking. Why not try and use the new Closure class in PHP 5.3 and see how well it performs within a loop? Suffice to say, I got some really really interesting results. Before I get into the details, here is the test script I wrote (the Benchmark class is merely a class I have written in the past).

<?php $data = range(0, 1000);
$clean = array();
public function loop($array, Closure $closure) {
	if (!empty($array)) {
		foreach ($array as $key => $value) {
			$closure($key, $value);
		}
	}
}
Benchmark::start('loop');
foreach ($data as $key => $value) {
	$clean[$key] = $value;
}
loop($data, function($key, $value) {
	$clean[$key] = $value;
});
Benchmark::stop('loop');
echo Benchmark::display('loop'); ?>

I didn't get too in depth with my test cases and simply used Firefox and page refresh to get my results. I am running PHP 5.3.1 on a Windows 7 XAMPP installation with Apache and no caching. For benchmarking I was using microtime(true) and memory_get_usage().

I began testing with 4 different cases, each of which that changed the size of the $data array. I started with 1000 iterations, then 5000, then 10000 and lastly 100000. I would comment out the foreach/loop sections and run them one at a time (of course), and ran each test about 5 times to gather an average. Here are the results.

foreach:
1000	Time: 0.0010 / Memory: 137128 (Max: 689160)
5000	Time: 0.0052 / Memory: 706488 (Max: 1258528)
10000	Time: 0.0097 / Memory: 1412048 (Max: 1964120)
100000	Time: 0.0545 / Memory: 13849568 (Max: 14401656)
closure:
1000	Time: 0.0027 / Memory: 84984 (Max: 688832)
5000	Time: 0.0144 / Memory: 433672 (Max: 1258192)
10000	Time: 0.0267 / Memory: 866448 (Max: 1963744)
100000	Time: 0.1223 / Memory: 8525216 (Max: 14401256)

The first thing you will notice is the time it took to interpret the page. On average using a closure as a callback within a loop will take 2-3x longer to process. However, the interesting thing is that the memory usage is around 40% smaller (using more allocated memory) while using a closure than doing a foreach, yet the max allocated is nearly identical. I knew what the outcome would be before I even started it -- Javascript closures are the same way. Regardless it was a fun experiment and if anyone knows more about this, please shed some light on this topic for the rest of us!

But in closing I can sadly say, that no, you should not be using a closure for looping, just stick to the old fashion tried and true foreach or for loop.

Security::cipher() problems and Suhosin

This problem can now be solved by setting the encryption type in the CookieComponent to rijndael.

Over a week ago I migrated one of my sites to a MediaTemple (ve) Server. I installed nginx, PHP 5.3.2 (with Suhosin), MySQL, APC and Memcache. After a little configuration and debugging, everything was working smoothly except encrypted cookies. I was using my AutoLogin component and login never persisted, but regular cookies worked correctly. I thought it would be an easy fix but I was wrong (I will post another blog on this topic).

While trying to figure out the encryption problem, I debugged the CookieComponent. I tested each function individually around a fake array. I tested __implode(), __encrypt(), __explode() and Security::cipher(). My results were all over the place. When I tested the script locally, everything worked correctly and the ciphering process worked as it should (below). But on the live server, all the encryption strings would change each refresh and the un-cipher would never work.

Implode:
username|gearvOsh,password|dsadnas79dn7n1279dnadnadb1p2sdasd,hash|761c1168c645784b78f5f967160ab390,time|1286152916
Ciphered:
z~¡|ßÛí�"� =�'¥¾E¨ÿÏy� íåÇv¸”^ëS ¦ì•ˆxuŽ?��ãbm}ÜfÇ“„bËV´w±(ÐU�"éQ’Qñn²^6¿2r‰½ùé‹ÄáÄ,‡ ›d¤<ó`'ëÆìÏg$V")ËdÁ&µ‰
Base64 encode:
Q2FrZQ==.en6hfN/b7dMfij3Spb4ERaj/z3ng7eXHdriUXutTIKbslYh4dR6OP8bjYm193GbHk4Riy1a0d7Eowx+QVZbpUZJR8W6yXja/MnKJvfnpixsIxOHELIcgm2QHpDzzYCfrxhrsz2ckVggijwcpy2TBJrWJ
Using Cookie::__encrypt():
Q2FrZQ==.en6hfN/b7dMfij3Spb4ERaj/z3ng7eXHdriUXutTIKbslYh4dR6OP8bjYm193GbHk4Riy1a0d7Eowx+QVZbpUZJR8W6yXja/MnKJvfnpixsIxOHELIcgm2QHpDzzYCfrxhrsz2ckVggijwcpy2TBJrWJ
Base64 decode:
z~¡|ßÛí�"� =�'¥¾E¨ÿÏy� íåÇv¸”^ëS ¦ì•ˆxuŽ?Æãbm}ÜfÇ“„bËV´w±(ÐU�"éQ’Qñn²^6¿2r‰½ùé‹ÄáÄ,‡ ›d¤<ó`'ëÆìÏg$V")ËdÁ&µ‰
De-ciphered:
username|gearvOsh,password|dsadnas79dn7n1279dnadnadb1p2sdasd,hash|761c1168c645784b78f5f967160ab390,time|1286152916

As you can see from the debug (on my local machine), the beginning and resulting strings are the same. I then found out the problem was with Security::cipher() and srand(). I later found out that Suhosin was overriding the srand() and mt_srand() functions, which was causing my seed to always change. I tried disabling Suhosins overwrites, but to no avail.

// Did not work
ini_set('suhosin.mt_srand.ignore', 0);
ini_set('suhosin.srand.ignore', 0);

After some googling and a lot of frustration, I finally found a solution. Thanks to Edgar Valarezo, I was able to get my encrypted cookies working properly. However, I had to overwrite CakePHP's core Security class and will need to maintain it every time I upgrade Cake. Here is the new cipher() snippet for your convenience.

function cipher($text, $key = '') {
    $key .= Configure::read('Security.cipherSeed');
    $out = '';
    $textLength = strlen($text);
    $keyLength = strlen($key);
    $k = 0;
    for ($i = 0; $i < $textLength; $i++) {
        $seed = md5($key . $key[($k++) % $keyLength]);
        $mask = hexdec($seed[6] . $seed[9]); // :)
        $out .= chr(ord($text[$i]) ^ $mask);
    }
    return $out;
}

I see this as a temporary fix and would love any information on this topic. If you ran into this same problem, how did you correct? Is it possible to seed correctly with Suhosin? Thanks again!

Book Review: jQuery Enlightenment

Before I dive on topic, I want to give you all a heads up that I will be posting a review of the book: "AJAX and PHP: Building Modern Web Applications 2nd Edition", by Packt Publishing. So far the book is great and has some nice chapters about jQuery, JSON, PHP and even XAMPP.

Now jQuery Enlightenment (jQE) isn't much of a book as it is a helpful PDF. It's not as long as your typical book, but it gets the job done in explaining jQuery and its core components. The topics that are covered in jQE range from Selectors, Traversal, DOM and Manipulation, Forms, Events, Plugins, AJAX, the Core and much more. The current edition of the book covers jQuery 1.3.2, and since 1.4 recently came out, I'm going to note any differences or problems that can be solved using 1.4 (if there are any).

The document is only a mere 123 pages (PDF pages to be precise), which may sound like a lot, but in actuality it isn't. Each chapter of jQE comes with code snippets, which have links to JsBin.com that allow you to run and test the snippet yourself. The snippets are also color coded to represent which areas of the code you should be focusing on and understanding. These features were probably the greatest thing about jQE and what sets it apart from regular books. It allows you to interact with the code first hand and makes it easier to understand once you see it in action (and you don't have to manually write it all too!). One caveat though is that the snippets use alert() for testing purposes, as they didn't want to rely on you having Firebug installed.

The book begins by talking about the jQuery core, of course. It states that jQuery should only be used in HTML standards mode, and not in quirks mode, as it has problems with rendering. One great aspect that I liked is its explanations of do's and don'ts and how to properly use jQuery to its full advantage. An example of this is to use the built in short hand code, and when to properly bind and invoke certain event handlers.

// You can get the current jQuery version by using the jQuery property
var version = $().jquery; // or $.fn.jquery

A feature that I rarely use (but probably should) is deep chaining. What I mean about deep chaining is using the find() function, paired with end(). I personally prefer just calling the functions separately on the specific jQuery objects. Regardless, jQE also made use of detailing out when and how this should be used and in what context (especially helpful for callbacks and special functions). While re-reading over the selectors chapters, I can't help but think to my self "A lot of this would be easier in 1.4 with the new functions, has() and not().", but you can still create your own selection filters (which is awesome).

// Define custom filter by extending $.expr[':']
$.expr[':'].positionAbsolute = function(element) {
	return $(element).css('position') === 'absolute';
};
var divs = $('div:positionAbsolute');

I always forget that you can create your own selection filters (just a reminder to myself!). Back on topic, jQE gets more in depth and accompanies it with more examples, so a must read if you are interested in such techniques. I bet you didn't know that you can nest filters as well:

var divs = $('div:not(:has(.jQuery))');
var ps = $('p').filter(':not(:first):not(:last)');

Moving on, the chapters on traversal are really well done, as it talks about rarely used functions like andSelf() and contents() (to me at least). However, I really feel like the forms chapter could of been a bit more in depth. It described how to properly select radios, checkboxes, selects, etc, but I felt as if something was missing. I noticed that when talking about getting/setting values for selects, that jQE might be wrong or out of date, as I am able to set the value of a select by passing the "value" tag of the option, and not the text. Maybe this has been updated in newer versions of jQuery, or I'm just blind. Besides that little mishap, it provides some great examples on how to select certain options based on the selection filters (pretty nifty!).

$('#select option:not(':selected')');

When talking about events and binds, it was pretty straight forward. Events in itself aren't that complicated to understand, especially in jQuery. However, there was one minor feature I didn't know about, and that was passing an empty bind function will trigger the previous bind.

// Alert will automatically trigger since we are passing an empty click()
$('a').click(function(){ alert('Its black magic!') }).click();

Actually, I just got a bit ahead of myself. There are some pretty exciting things you can do with events, like event specific namespacing, and using the event object functions (preventDefault(), stopPropagation(), etc). I won't get into this subject, as you should purchase jQE and find it out for yourself! Oh, did you also know that you can disable the right click menu in your browser (not in Opera, sorry guys!), by simply using jQuery? Me neither!

$(document).bind('contextmenu', function() { 
	return false;
});

Now for the bigger topics, Plugins, Effects amd AJAX. jQE covers the basics on how to properly write and create a basic skeleton for your plugins. It goes over the correct usage and context for this, how to apply the plugin to all selected elements with the each command, how to return and chain properly and how to easily extend and creating custom settings. Now that's basically all it talks about, which I think was too short. I've seen so many different variations and usages for jQuery plugins, and so many of them wrote it differently. For example, Ive seen people define functions within the each() loop, as well as outside the loop scope. I'm assuming this sets the visibility to private so that the functions can not be called, but what if I do want to call a plugin function?

$.fn.myPlugin.someFunction = function() { 
	// Do something 
}

Is it possible for me to call this function outside of the plugin, or does a plugin only package everything and do it automatically. There was too many "What if", "How does" type questions I was thinking to myself, and jQE was unable to answer. But these type of questions are probably best asked in larger more in depth books.

I don't want to keep boring you with minor details, and I would like to leave the chapters on AJAX and Effects alone (aka the exciting ones). By doing so, I hope you go purchase this document and read it for yourself. I promise you won't be disappointed.

Besides a few minor gripes and unanswered questions, jQE delivered everything I needed to know on how to properly use jQuery. It did its best to go into detail, and to also describe how the internals are working. I personally liked the fact that the document was littered with multiple examples on how to optimize and write fast code. A quick example for your enjoyment (and you may have not known that you can pass objects as an argument!).

$('a').css({'display': 'block', 'color': 'red'}).attr({'title': 'Title Txt', 'href': 'http://www.jquery.com'});

All in all, this was a great book to start learning jQuery. However, there was one thing I completely disliked, and it was when the book prefixed variables with a $ ($var), ugh! Sorry, this is Javascript, not PHP!

In closing, be prepared for my next review on AJAX and PHP: Building Modern Web Applications 2nd Edition, as I know some of my readers will enjoy it (yes you!).

The flawless upgrade to Cake 1.3

Cake 1.3 has been around for quite some time now, but I never had the desire to upgrade with it being in such a beginning stage. Well seeing as how its now in Alpha and many users are testing it with no problems, I thought it would be a good idea. The project I was going to upgrade is quite large, heres a quick rundown of just how large:

19 controllers, 8 components, 15 locales, 64 models, 2 plugins, 6 vendors, 8 stylesheets, 14 javascripts, 7 helpers, 159 views

This isn't counting the admin panel, which is a whole separate app, and which I have not upgraded yet. Now lets get onto the upgrade, its probably the easiest thing to do. All I did was follow the migration guide. First off was checking to see if I used any deprecated methods, which was simple, all I did was search the whole app folder for words like del(. I was surprised to find I used it like 5 times, when I always preferred the full delete().

Next in the list was upgrading to the new Router conventions, which lucky for me didn't apply. I never used any non basic conventions, I mean why would you! One thing that bugged me though is the new page title implementation. It took me quite a while to go through all those controllers, and all the actions within them. Another nuisance was adding "echo" to all the flash() calls in the views, and removing the "inline" parameter from all meta() and css() calls, but wasn't too time consuming.

One of my most favorite updates was the new pagination support with passedArgs. I had to hack all my paging before, but in the new update I removed it all and it worked wonderfully! Thanks Cake team :]

All in all, the upgrade went smooth. If you follow Cake conventions all the way through, you don't need to do much alterations. I for one am looking forward to the future versions.

To bake or not to bake...

By now most of you have heard that the awesome Nate Abele (which I had the privilege of talking to at Zendcon) is leaving the CakePHP team. A lot of developers were taken back by this and are unsure if they should continue to develop with CakePHP. Now, I find this ludicrous on many levels. Sure Nate was the lead developer, but that doesn't mean he was the only one. We still have the mighty Mark Story and the returning Larry Masters.

I had the opportunity to attend Nate's "Future of CakePHP" panel at Zendcon in which he talked about many of the problems facing current frameworks. Towards the end of the panel he showed off the new Cake 3 functionality using filters and closures, which I have to say, is pretty clever and badass. Now if you haven't figured out by now, the new Lithium project is a fork of the Cake 3 branch, so basically Lithium is a new 5.3 specific framework, which I am fully looking forward to fiddling with. Others have already figured this out, and we should expect it sometime this Monday, according to Nate.

Now where does this leave the future of CakePHP? It will stay the same. I know for once thing, ill continue to develop and pump out scripts because I see no reason in stopping. Additionally, if Lithium is anywhere near the same setup, I can easily port my current component, behaviors, etc to the Lithium architecture. I don't see CakePHP dieing anytime soon, simply because Lithium is an experimental 5.3 framework, and 5.3 wont take off as fast anytime soon. However it should be fun to mess with :]

I wish Nate Abele and the CakePHP team good luck with their new endeavors, I will thorougly be looking forward to both projects.

ZendCon 09

I just bought my ticket for ZendCon, 2 hours before the discount ended, pretty stoked about that. This will be my first PHP/Developers conference and I am thoroughly looking forward to it. I never really had an interest in these before but my passion for PHP has grown tremendously this past year, so its only fitting that I go. I will be going with some friends and colleagues, so it should be a blast and not just me by my lonesome.

I am looking forward to taking the Zend certification test and the tutorial panels at the convention should teach me all I need to know before hand. On top of that, I'm quite excited to see Nate Abele talk about CakePHP (pretty awesome seeing as how everything else is Zend). If any of the small group of people reading my blog are attending, be sure to say hello and we can have lunch.

See you all at ZendCon in October.

Blizzcon 09

So I have not posted an entry for the past week, but I have a good excuse! I was attending Blizzcon and was doing coverage on Diablo 3 and Starcraft 2. If you unaware of what Blizzcon is, its a giant convention held by Blizzard Entertainment that basically showcases their games. They have large art and gameplay discussion panels, live game booths and a ton more for the 25,000+ attendees to divulge into. I however don't get to go to all of it because I am labeled as "press" (because I run sc2armory.com and d3armory.com), so most of my time is spent in the press room writing and covering panels. However, I have written 3 small articles detailing what I did for the past 3 days, but beware I ain't that great of a writer!

If you are a fan of Blizzard, or Starcraft 2, or Diablo 3, give a big shout out. And I must say, yes, these games are pure awesome.

  • Pre-Blizzcon: The Fansite Summit
  • Blizzcon Day 1 Round-Up
  • Blizzcon Day 2 Round-Up

Oh, and I will be starting my new job on Wednesday. Looking forward to it.