Resurrecting a Laptop for Development

I have an old single core laptop that doesn’t get a whole lot of use anymore, partially because it is dated (purchased in 2006) and partially I’ve never really adapted to using a laptop as a general purpose computer. Increasingly, however, I find myself in need of a laptop either when I want to get some work done when I’m away from home, or when I need to take my work with me. This being the case I decided to re-purpose my old laptop as a dedicated development machine.

I could have just put a fresh copy of Windows XP on it and gone from there, but given the circumstances that might not have been the best route. All I needed to run was apache, MySQL, PHP, subversion, and something to write code in. Clearly something more lightweight than Windows could accomplish this. In addition to this I wanted something that would mirror my production server, which is running ubuntu. I ended up installing lubuntu, a lightweight distribution based on ubuntu (if you plan on trying lubuntu bear in mind that it is still in beta). Other than some very minor bugs, lubuntu seems to be perfect for my needs: I could configure it to be almost identical to my production server, it is easy on resources (even on my ancient laptop), and I immediately noticed a big improvement with regard to battery life.

Tab Override Update

A while back I published a plugin that allowed you to insert tabs into textareas in wordpress just as you would in a text-editor. Until recently, however, there was a catch: I was only able to get it to work in Opera and Firefox. Today, however, I was contacted by Bill Bryant. He stepped in and took it the rest of the way; adding support for IE, Safari, and Chrome as well as improving the overall functionality.

Check out Tab Override

Circumventing DNS Caching

During my recent host switch I ran into a bit of a problem. After I had moved my database and content to the new server and changed the name servers, requests were still be directed toward my old server. The reason for this is that my ISP had not yet updated their DNS record cache thereby causing requests to be directed to the old server. It typically takes several days for a domain to fully propagate; the amount of time it takes for changes to take effect for an individual depends on how often their ISP updates the DNS records. There is, however, a simple way to avoid having to wait for DNS propagation.

(Note that it may be sufficient just to clear your local DNS cache using the command ipconfig /flushdns)

When resolving a domain a host will usually check for an IP address in its local DNS record first. If it cannot find an address it will pass the request on to the DNS server. The problem occurs when neither the local dns record nor the DNS servers’ records are up-to-date. In most cases the DNS servers’ records are out of our hands so the solution is to manually tell the local machine the IP address for a given domain. You can do this by editing the hosts file located in C:\Windows\System32\drivers\etc (the location should be the same for Windows XP/Vista/7). You should edit the file using notepad with administrative privileges. You can do so by selecting your Start Menu -> Accessories and then right clicking Notepad and selecting Run as administrator (This is how I did it using Windows 7).

You can now add the entries for your domain. Each entry should be on its own line and specify an IP address followed by a domain name:

123.45.67.89 mydomain.com
123.45.67.89 www.mydomain.com

You domain should now resolve to the correct host. Note that this does not in any way effect DNS propagation; users who’s DNS servers have not updated their records will still be directed to the old server. You should also note that this method assumes a static IP address; if at some point the IP address of your web server changes the domain will not resolve correctly and the entries will have to be updated or changed. This shouldn’t be much of a problem considering that the entries can (and probably should) be removed once your ISP has updated their DNS records.

New Host

I’m in the process of moving this site from my awful shared host to a shiny new VPS. Expect downtime, errors, unexpected behavior, and sudden explosions.

Apparatus Update Preview

I’ve been making some progress on the next version of Apparatus. Along with some bug fixes there are a few new features. One new thing is the option to attach a database to allow for more advanced functionality. For now this includes something I’m calling examples generation, which allows you to store your code and output and allow others to view it. This is done without giving them access to the Apparatus interface. Apparatus can still operate in lite mode (without a database), but some features will not be available.

Also in the works is a new template which will serve as the default Apparatus template (the 0.3 template can still be selected). Here is a small preview:

Apparatus Template

Apparatus 0.4.0 login screen viewed in Opera 10.5

Hopefully the new version should be ready for release by the end of the month. For now version 0.3 is available. If you haven’t yet, give it a try; it is not too late for any suggestions you may have to make it into version 0.4.

Hello World Nightmare

Traditionally, when someone is introduced to programming, the first block of code they write is the infamous “Hello World” program. Unless you’re dealing with some esoteric language this program usually consists of just a few or even a single line. There is one popular language out there where, in comparison, Hello World is a monster: Java. If you’re a Java coder you may not see it, especially if Java wasn’t your first language. Try to look at it from the perspective of a first timer:

public class HelloWorld {
	public static void main(String[] args)
	{
		System.out.println("Hello World");
	}
}

In addition to a huge dose of OOP some of the concepts bundled into this small block of code are: visibility and scope, arrays, return types, and data types. How do you explain static to someone who has no concept of an object? I explicitly recall, when taking my first Java course, my professor referring to static as “Voodoo Magic”. Compare this to something like C++:

int main()
{
	cout << "Hello World";
	return 0;
}

Granted the whole << thing might seem a bit strange, but overall this is much easier to explain. Don't even get me started on PHP:

echo ‘Hello World’;

Don't get me wrong. I think Java is a great language for beginners. It's balance between ease of use and structure keeps new comers from punching their monitors while at the same time adhering to a fairly strict set of rules.

RosettaCodex

As someone who is already experienced with a few programming languages, learning new languages, frameworks, and platforms is a much different process from someone who has no background in programming. Obviously having written a ton of code make learning how to write different code much easier. Much of the documentation out there however does not seem to take advantage of this fact. Documentation for someone who is completely new to programming is the same as documentation for someone with years of experience. It might be easier for the experienced programmer to understand and utilize that documentation, but it is still the same documentation.

The problem here, for an experienced programmer, is that all of this documentation exists in a bubble. It does not assume any prior experience and it does not use other languages and frameworks for reference. Clearly the reason for this is because any reference to alternative approaches would be wasted on an unexperienced coder, and might even be confusing or distracting.

My solution is to create an encyclopedia of problems with solutions in as many languages, frameworks, and platforms as possible. By now, if you’ve read the title, you know I’m calling this solution RosettaCodex. The concept is the same as the Rosetta Stone. If the same thing is written in multiple languages and you know at least one, you can figure out the meaning of the others.

RosettaCodex is a cross-language reference created specifically for those with programming experience. If you think this is a good idea feel free to contribute.

Check it out: RosettaCodex

PHP Confirmation Emails

If you are implementing your own user management system you may want to ensure that emails associated with users’ accounts are valid. The most straightforward way of doing this is to send an email to this account and verify that the user received it. Obviously we don’t want to do this manually so the solution is to write a script that automates the process.

High Level Concept
What we will need to do is:

  1. Generate a confirmation code for our users are registration time
  2. Store that code and track which users are not yet confirmed
  3. Send an email containing the confirmation code to the user
  4. Facilitate the user in using the code to activate their account

Confirmation Codes

The easiest way to generate a confirmation code is to take a piece of information about the user and hash it. What we don’t want to do however, is reveal how this hash is generated or make it easy for a user to generate this hash on their own. I find that the easiest way to approach this problem is to use the current timestamp in the hash; unless the user knew the time that their hash was generated down to the second they could not generated one on their own. Here is the code:

$hash = md5( $username . time() );

Notice that I assume you already have the username.

Storing Your Confirmation Code

In order to confirm a user, both the user and the server need to know the code. This means you’ll have to store the code once it is generated. You’ll also need to track which users are confirmed and which aren’t. Fortunately we can do both these things at once. You’ll need to either add another column to your `users` table or use another method to associate the code with the user. I’ll assume that you have a column called `status` in your `users` table.

Once you’ve generated your confirmation code store it in the database. We’ll worry about determining which users are confirmed later.

Sending the Email

Now that we have generated our code we will need to send it to the user. The easiest way for a user to confirm their account is to just click a link that has the code encoded into the url:

//the link
$link = &quot;http://yoursite.com/confirm.php?user=$username&amp;code=$hash&quot;;

Notice that I use the page confirm.php. We will write the script in the next step, you may call it something different if you like. Also notice that I include the username and hash in the url.

Now we need to create the rest of the email and send it. One thing you’ll want to do is keep things simple. Some email clients filter out any html so it is best to use plain text when possible.

$link = 'http://yoursite.com/confirm.php?code=' . $hash;
ob_start();
?&gt;
Confirmation Required:
Please copy and paste the following link into your browser to confirm your account
&lt;?php echo $link; ?&gt;
If you did not register an account just ignore this message
&lt;?php
$message = ob_get_clean();
$headers = 'From: you@yoursite.com' . &quot;\r\n&quot; .
    'Reply-To: you@yoursite.com' . &quot;\r\n&quot; .
    'X-Mailer: PHP/' . phpversion();
mail($userEmail, 'Confirmation Required', $message, $headers);

I used an output buffer to write the message, if you are not familiar with this approach you may want the read the output buffering section Here. Notice the $headers variable. It is important that you include the From header whenever sending email. Even though the headers parameter is optional, the from header is not. I highly recommend that you take a close look at the mail documentation.

Confirming Users

Now that the user has their confirmation url we need to write the confirm.php script I mentioned earlier. I will leave comments whenever a database transaction is needed:

$userCode = $_GET['code'];
$user = $_GET['username'];
/* get the code stored in the database
if the user does not exist, or has already been
confirmed display an error message */
$serverCode;
if($serverCode == $userCode)
{
	//change the value of the status field in the database to 'confirmed' or something else if you prefer
}
else
{
	//Invalid code. Display an error message
}

In short, all we need to do is compare the user’s code with the one stored in the database. If the match change the value of the user’s status field in the database to some value that will indicated the user is confirmed. Anytime you need to check if a user is confirmed just use that field.

Additional Concerns

There are some additional concerns that I did not address that you may want to.

A user may need to have their confirmation email resent. This is just a matter of pulling the confirmation code out of the database and sending it again.

Some users or bots may register accounts that they never confirm. You may want to setup a crontab or some other means of periodically clearing out these accounts (ie if an account hasn’t been confirmed after a week, delete it).

Protect yourself from SQL Injections whenever sending user data to the database!!!

Apparatus (also Happy New Year!)

For a while now I’ve been working on a web-based PHP interpreter; an interface I can use to quickly test or develop code from my browser. Ultimately this resulted in Apparatus, an in-browser PHP read-evaulate-print loop. Give it a try: http://tinsology.net/scripts/apparatus/.

Note that this is currently a beta version. Any help with identifying bugs will be greatly appreciated.

P.S. Happy New Year!

PHP Iterators

If you’ve spent any significant amount of time coding in PHP you’re most likely familiar with PHP’s foreach loop syntax. In simple terms, a foreach loop is an easy way to iterate over the elements of an array. Chances are if you’re reading this you already know that. What you may not know, however, is that it is possible to iterate objects with a foreach loop. Assuming you have some collection class (an object that stores some number of elements in an organized manner) you can iterate over its elements just like you can the elements of an array.

$myCollection = new Collection(); //arbitrary collection class
foreach($myCollection as $element)
{
	//do something with $element
}

In order to do this however, you must design your class in such a way as to let PHP know that it supports iteration. As is the case with many other languages, you do this by implementing an interface. An interface is basically a class containing only abstract methods (constants are allowed as well). A class implementing a certain interface must provide the definitions for those abstract methods. The interface we need in this case is called Iterator and has 5 methods that must be implemented:

class MyIterator implements Iterator
{
	//Returns the current element
	function current()
	{
	}
	//Returns the current key (position in the iterator)
	function key()
	{
	}
	//Moves to the next element (returns void)
	function next()
	{
	}
	//Resets the iterator
	function rewind()
	{
	}
	/*Returns true of the current position in the
	   iterator exists. False otherwise */
	function valid()
	{
	}
}

From these methods you can derive that the underlying implementation of a PHP foreach loop is something like this:

$i = new MyIterator();
//make sure the iterator is in the starting position
$i-&gt;rewind();
while($i-&gt;valid())
{
	//get the current element and key
	$value = $i-&gt;current();
	$key = $i-&gt;key();
	//iterator to the next element
	$i-&gt;next();
}
//equivalent foreach loop
foreach($i as $key =&gt; $value)
{
}

Now that we know what the methods do it is time to implement them. The class we’ll implement will be a stripped down version of a linked list that supports only an add method (plus the iterator methods):

class LinkedList implements Iterator
{
	private $head;
	private $last;
	private $count;
	private $curr; //iterator counter
	private $currNode; //iterator position
	function __construct()
	{
		$this-&gt;head = null;
		$this-&gt;last = null;
		$this-&gt;count = 0;
		$this-&gt;curr = 0;
		$this-&gt;currNode = $this-&gt;head;
	}
	function add($v)
	{
		$newNode = new Node();
		$newNode-&gt;value = $v;
		if($this-&gt;head == null)
		{
			$this-&gt;head = $newNode;
			$this-&gt;last = $this-&gt;head;
		}
		else
		{
			$this-&gt;last-&gt;next = $newNode;
			$this-&gt;last = $this-&gt;last-&gt;next;
		}
		$this-&gt;count++;
	}
	function current()
	{
		echo &quot;LinkedList::current \n&quot;;
		return $this-&gt;currNode-&gt;value;
	}
	function key()
	{
		echo &quot;LinkedList::key \n&quot;;
		return $this-&gt;curr;
	}
	function next()
	{
		echo &quot;LinkedList::next \n&quot;;
		$this-&gt;currNode = $this-&gt;currNode-&gt;next;
		$this-&gt;curr++;
	}
	function rewind()
	{
		echo &quot;LinkedList::rewind \n&quot;;
		$this-&gt;currNode = $this-&gt;head;
	}
	function valid()
	{
		echo &quot;LinkedList::valid \n&quot;;
		if($this-&gt;curr &gt;= $this-&gt;count)
			return false;
		return true;
	}
}
class Node
{
	public $value;
	public $next;
	function __construct()
	{
		$this-&gt;value = null;
		$this-&gt;next = null;
	}
}

Notice that I’ve added an echo to each iterator method in the LinkedList class; I’ll explain why later. In case you’re unaware, a linked list is just a series of ‘nodes’. Each node contains a value and a reference to the next node in the list. This pseudo code demonstrates how to traverse a linked list, outputting the values as we go:

Node current := head;
while current != null
	print current-&gt;value
	current := current-&gt;next
endwhile

Since, however, our linked list class implements Iterator we can traverse it using a foreach loop:

$list = new LinkedList();
$list-&gt;add('a');
$list-&gt;add('b');
$list-&gt;add('c');
foreach($list as $key =&gt; $value)
{
	echo $key . ' : ' . $value . &quot;\n&quot;;
}

Here is the output for the above code:

LinkedList::rewind
LinkedList::valid
LinkedList::current
LinkedList::key
0 : a
LinkedList::next
LinkedList::valid
LinkedList::current
LinkedList::key
1 : b
LinkedList::next
LinkedList::valid
LinkedList::current
LinkedList::key
2 : c
LinkedList::next
LinkedList::valid

The above shows the position and value of each element in our list, as well as the order each iterator method is called.

P.S.

This is the first part in a three part series. The next part will be published soon.