An introduction to OOP

Note: This article has been marked for a quality review and will soon be updated.

Object-orientated programming is a concept that is more likely to pop up when programming desktop applications rather than those for the web. But once you start using OOP you will wonder why you ever used procedural programming (that's simply using a program that calls a load of functions/procedures), well maybe not completely - OOP has its place on the web, and in this tutorial we will explore a practical usage of the common programming-paradigm. So what is it? Put simply OOP is when programmers create objects in which they can store data, and ask those objects to do certain things. So for an example, we might have a person object for which we can set things like eye colour and height - these values would be stored in variables. We might also have some instructions that we can give to our person object* like "star jump!", our person would then do a star jump, in our case it might be more like writing something to the screen like "I just did a star jump!".

So how do we know what variables and instructions we have for any give object? Put simply, with our class. A class is a file which contains all the information about any objects that will be created. The most common analogy for a class is a blue-print - it's a good one, because our class contains all the information we need to know about anything we make using it. Just as a blueprint for a house tells us the dimensions of the thing, it also shows us how the doors open and where the water comes in. When we actually make our house in the real world we build it, in the world of computers we instantiate it. When we've finished building in the real world we say we have a house, in programming we call it an instance of the house class.

Deep breaths people! Let's move onto the why we might want to program like this.

OOP really re-enforces a number of good programming techniques, and the 4 principles of the paradigm are as follows: A PIE. No, not the tasty treat, but another acronym! Now if your background isn't in programming the next 4 words might fly over your head - but for the moment I need you to grab a net and get ready to catch them. A PIE stands for Abstraction, Polymorphism, Inheritance, and Encapsulation. Now if you've done any programming on the web or otherwise it's likely you've done at least 2 of the above things. So let's go through them one at a time.

Abstraction

This refers to the technique of taking a problem and focusing on the 'abstract' rather than the individual. Take a look at this function:

function addMyNumbers($a, $b){
    return $a + $b;
}

Above is a very basic example of abstraction at work. Instead of writing 4 + 7 directly into our code, we have written a function that adapts to return a value based on what we pass to it. Therefore we have abstracted that concept. In OOP we use abstraction to make classes. For instance, in our person class we might have an instance method of runOneMileThatWay() - a method that does exactly what the name suggests. But the problem with such a method is that it is very specific. If we wanted our person object to run 5 miles instead of 1 (they are very fit by the way), we would either have to write a new method, or call the same method 5 times. The solution to this is to copy our add method above, and pass a value which tells our instance to run $x amount of times. This makes our program more efficient and easier to maintain.

Polymorphism

If any of these words is going to trip you up, this is gonna be the one. Bear with me here. Polymorphism is the term used to describe the idea that variables, objects, and functions can have more than one form. We don't need to go too deep into why this is important, but let's take a look at an example where polymorphism comes into play.

$x = (int) 4;
$y = (float) 5.76532;

echo $x + $y;

Perfectly legal right? We've declared 2 variables - one integer, and one floating point number, and then added them together. Run this code and you get a number just below 10. But technically this shouldn't work. Integers and floats are stored using different methods, but thanks to polymorphism PHP knew to simply add the two together as we humans would, instead of complaining about the distinction between integers and floats. And that's all you really need to know about polymorphism for now.

Inheritance

Nice and simple - your mum has blue eyes, so you have blue eyes right? Well human genetics is a little more complex than what we're going to be doing, but you get the idea - you inherit (or get) your traits from your parents and general ancestry. In OOP our objects can also inherit things like methods from their super classes. In certain languages you must always tell the world (or rather compiler) what class you are inheriting from. For example in Objective-C - the language used on iOS, the most common class to inherit from is called NSObject. As I said before you can inherit methods which ensures you don't repeat yourself, and can easily maintain your code. NSObject contains really useful methods such as 'description' which can do all kinds of things.

In our example we might have methods such as 'wake up' and 'sleep', but these behaviours are not limited to humans, all living things do this (I should think), so maybe we could create a class called 'Animal'. In the animal class we could have methods such as wakeUp and fallAsleep, and then we could sub class it and make our person class inherit from it. Lets see the PHP way of doing just that.

Class Animal {
	private $awake = false;

	public function wakeUp(){
		$this->awake = true;
	}
	
	public function fallAsleep(){
		$this->awake = false;
	}
}

Class Person Extends Animal {
	public $name;
	
	public function starJump(){
		echo $this->name . ' did a star jump!';
	}
}

$me = new Person();

$me->wakeUp();
$me->name = 'Tom';
$me->starJump();

Don't worry about the syntax too much if you're not familiar with it; but here we can see that we have 2 classes. Our first is 'Animal' which has the methods we said we'd create, and the second is 'Person' which allows us to do a star jump - I've never seen a monkey do one of those, so I think we're safe to keep that within our own species for now. We then create a new object based on the person class, and immediately call the 'wakeUp' function - but this doesn't exist in our Person class, so what's going on?! Well because we used the keyword 'Extends' - (syntax varies from language to language) our $me object has access to all the methods implemented in our Animal class. And that's inheritance.

Encapsulation

Last but not least is this badboy. The term is means when we take the data (instance variables/ivars) and instructions (methods), and put it all within a class. When we do this we make our objects self-sufficient. Think about it like so. Without encapsulation our person class might have to be operated on by another function outside of our class to, say for instance, make a curry. So it might send a bunch of messages (that's just calling the methods of a class), to our object, and fiddle around with our public instance variables. That way of doing things will get the job done. But, and it's a big but, it ain't good practise!

If you were working on a project where your people objects had to be able to make a curry (maybe it's a restaurant game), and you wrote your curry method outside of your person class it would work. But then what happens if you start a new project, and the people objects in that scenario need the curry shizzle?! Bad things start to happen, that what happens. So let it be known, objects should know what they are doing without needing help (anything beyond variable data), from the rest of your program. Maybe you decide not all people should need to know how to make a curry (plain craziness quite frankly), it would be a better idea to sub-class the Person object to something like a 'Chef' class - using your handy friend inheritance .

And with that we have finished with the main concepts of OOP. As you can see above, most of the A PIE concepts work together to create a beautiful paradigm (to a programmer at least), and one that will ensure you consistently write good quality code. Although this has been written from the perspective of web development, should you ever wish to move into complied programming languages such as Objective-C for iOS, you will find that they are heavily class based, so you've learnt something that should serve you well in the future - well done you!

* I am by no means suggesting that you objectify men or women.

Protect your assets with expiring URLs

Note: This article has been marked for a quality review and will soon be updated.

A problem that many web developers face is how to protect their assets. Specifically ones that users are supposed to pay for - say a video training site for instance, you don't want every Tom, Dick and Harry being able to guess the URL, or worse crack open the source code to find an unprotected URL. IF this happens companies can lose a lot of money, so it's kind of an important subject. The more astute of you out there (or those that read the title), might have already guessed that today we will be building a system that will allow us to force expiring URLs. Head over to the example to see what we'll be creating here.

To do this we won't be naming our files anything too funky, nor will we leave polite messages in our source; instead we will create a media-serving script that will make sure the request isn't coming from an unscrupulous source. For that we will need to get time on our side, and generate unique hash-keys that will allow us to verify the request. On a side note you could have a system which connected to a database to see if a hash existed, and if it wasn't expired, but for this tutorial, we will stick with using good ol' time. We'll only request our protected files from our script, and send 2 parameters to make sure we get what we want, they will be our file path, and our token in hash form. We will also use some nifty htaccess trickery to ensure users don't just copy and past the file path from our URL to their browser window - because that would just invalidate what we are about to do. Let's get started!

To begin we will create our media serving script, so go ahead and create a new file called asset.php - this script will decide if the request is genuine and if so will serve up our media. Here is the code for that file:

$t = $_GET['t'];
$url = $_GET['url'];

if(!empty($t) && !empty($url)){
	if($t==md5(date('his').'my_amazing_salt')){
		$image = imagecreatefromjpeg($url);
		header('Content-Type: image/jpeg');
		imagejpeg($image);	
	}else {
		echo 'Invalid URL!';
	}
}else {
	echo 'Invalid URL!';
}

Now the code above works under the pretence that we are only serving jpegs - if you wanted to only serve something like pngs for instance, you would just need to alter the content type, and fiddle with the loading of the actual file. So what does it actually do? Well at the top we make sure the variables passed to the script in the URL aren't empty, and then go on to validate them. The token system we're using here is one that generates a hash-key based on the current time, along with our own 'my_amazing_salt' string (just to make things even more secure) - which is then encrypted using the handy md5() function. We then load in the image, set the header (so it displays as an image and not a bunch of random characters), and serve up our media. If any of the checks fail along the way we just output a little message to our users.

If you want to have links that expire after an minute for example, you would simply alter the parameter passed to the date() function to something like "hi" for hour and minutes - check out the date function for more info.

Great, we've done the hard part, now we just need to replace any image URLs on our site with ones that point to our script that we just made. We can generate the URLs like so:

$url = 'asset.php?url=food.jpg&t='.md5(date('his').'my_amazing_salt'); 

And just alter the 'url' parameter where appropriate. I would recommend picking a totally random salt to add to the end of your encryption just so others won't have a clue what it is.

Ok, so now we have a working system whereby we can request our media from one file, and if that URL is visited by the user after the page load, they will be shown the door. But we still have one problem. Users will still be able to access our files using the path we pass to our script - they could just copy and paste it into their browser, and hey presto they've gotten what they wanted. So how do we fix this? Well the best way is using some htaccess magic to prevent direct loading of our media files.

Whack the following line of code into your htaccess file (if it doesn't exist, create one in your media directory):

RewriteEngine On
RewriteRule ^(.*).jpg$ asset.php?src=$1 [L]

That rule above simply sends all requests for images with the extension 'jpg' to the script we just created; and as we know, because the redirect will go to a URL without a token, it will invariably be rejected. At this point you might want to alter the code above to reflect whatever kind of media you are trying to protect.

And that's how to protect your assets! This method is useful when you want to conserve bandwidth and stop users from simply grabbing a load of subscription/payment-based files from your server.

Update

Is would seem the kids these days are into also protecting these moving-picture thingy-ma-jigs, so I thought I'd update this post to encompass protecting videos. Depending on what video format you wish to use, some of the code below will need changing, but I'll highlight that when we get there.

The code is nearly identical to what we used for images, with a couple of alterations, so here's the code you put in your .htaccess file:

RewriteEngine On

RewriteRule ^(.*).m4v$ asset.php?src=$1 [L]

Notice the ".m4v" extension - this is something you'll have to alter if you're using another format.

Then our PHP file changes to:

$t = $_GET['t'];
$url = $_GET['url'];

if(!empty($t) && !empty($url)){
	if($t==md5(date('his').'my_amazing_salt')){
		$filename = $_GET['url'];
		$fsize = filesize($filename);
		header('Content-Disposition: filename='.$url);
		header('Content-Type: video/quicktime');
		header('Content-Length: '.(string)$fsize);
		readfile($filename);
	}else {
		echo 'Invalid URL';
	}
}else {
	echo 'Invalid URL';
}
	

Again, notice the file extension here and alter accordingly. To include the video on your page you can do all manner of things, for instance you might want to use a flash player or the swanky <video> tag. In the video example I've used an iFrame.

And that's how to protect videos!

Search a UITableView

Note: This article has been marked for a quality review and will soon be updated.

As with most things there are a bunch of tutorials on the internet about how to search a UITableView, but when I was attempting to implement my search I hit a brick wall with it and ended back where I started - Apple's developer docs - the code from which will be used in this here tutorial. I trawled through many tutorials and cannibalised a load of code, but finally I tamed the beast and got myself a lovely search bar. So this post is as much a form of catharsis for me, as it is a tutorial for you 🙂 Let's get started.

To begin we need to think about what we need for this - we want a search bar, we need a search button, we may even need some scope titles to allow us to filter our results. Something which might not be too obvious to begin with is the fact that we also need to think about the UITableView in which to load our results. When we've finished loading this UITableView, it will display it to the user to scroll through. In terms of variables we also need to consider the fact that we will need a duplicate of our main data - be it an array or dictionary, so that we can store our search results. Lastly we need to store the search term and selected scope so that if our users switch to another view we can retain that information. All of this code is available from Apple, but I'll show you it here in a real world implementation - they use their own "Product" class, but I'll show you how to accomplish search with an NSDictionary and NSArray. Now at this point you may be wondering what you've let yourself in for, after all I've just gone through a rather long list of UI elements that are required to search our table, but luckily for us Apple provides a UISearchDisplayController class, which handles the UI, and expects only the back-end implementation to be written by us. So I'm going to create a new view-based project and get started.

My data structure will be as follows: I will have an NSArray populated with NSDictionary objects holding all my data, I will then populate my table-view with that data, and implement the search functionality based on that structure. If you want to use some other type of object, just replace all mention of NSArray etc. You should also note that Apple's implementation places code inside a view controller based on the UITableView class, not the UIView class - this will affect what variables we need, and what we need to hook up in IB. In this tutorial we will put a UITableView within a UIView.

Go ahead and add a UITableView, and then add a "Search Bar and Search Display Controller" to your UITableView, and link up the dataSource and delegate parts, making sure to implement their relevant protocols - you know how to set up a UITableView right? That handy object, as you might be able to tell, handles our search bar, and the controller for our search. We don't need to link to these expressly in our code by creating variables and properties, but we will need to implement a couple of protocols - namely the UISearchDisplayDelegate, UISearchBarDelegate ones. The search controller that we added in IB automatically sets it's delegate, so there's no need to hook that up manually. So now let's set up our variables. I'm putting these in my .h file:

NSArray*listItems;
NSMutableArray *filteredListItems;
NSString *savedSearchTerm;
NSInteger savedScopeButtonIndex;
BOOL SearchWasActive;
IBOutlet UITableView tableView; // Be sure to hook this up in IB

The role of some of these variables will soon become clear. Don't forget to link the tableView variable up in IB before continuing. Then to finish up in the .h file we need to add our properties like so:

@property (nonatomic, retain) NSArray *listItems;
@property (nonatomic, retain) NSMutableArray *filteredListItems;

@property (nonatomic, copy) NSString *savedSearchTerm;
@property (nonatomic) NSInteger savedScopeButtonIndex;
@property (nonatomic) BOOL searchWasActive;

Notice the mutability of our filtered content array - this is very important as we will be changing the content of this data store each time the user performs a search. If you want to use a dictionary at this point, you know what to do. And with that we can wave goodbye to our header, and welcome our implementation. Once you've synthesised your variables, we need to look at the methods required by the protocols we promised to implement.

The first two we will write are fairly simple, they will be called when a search is performed:

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
    [self filterContentForSearchText:searchString scope:
			[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];

    return YES;
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
			[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
    return YES;
}

Those two bad-boys each call another function, and then exit while returning "YES". When a user types something in the search field the first function is called, it then passes what it knows to the function filterContentForSearchText:scope:. The second is called whenever the user selects a different scope, and does the same as the first. Great stuff, we only have 1 more function to implement our search and a few lines to put elsewhere a little later on. And this is the part that caught me out to begin with. For some reason Apple neglected to provided simple code concerned with searching something like an array, and instead they provide a separate class - maybe that's more common where they come from, but round these parts I'm rather partial to the ol' NSArray and NSDictionary. So I changed certain parts of the following code to allow the use of said objects in our table. Just so you know my dictionaries that are stored in my listItems array have the keys "title" and "type". This is what I got:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{	
	[filteredListItems removeAllObjects]; // Clear the filtered array.

	for (NSDictionary *item in listItems)
	{
		if ([scope isEqualToString:@"All"] || [[item objectForKey:@"type"]  isEqualToString:scope]  || scope == nil)
		{
			NSComparisonResult result = [[item objectForKey:@"title"] compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
            if (result == NSOrderedSame)
			{
				[filteredListItems addObject:item];
            }
		}
	}
}

This function first clears the filtered array, and then uses fast enumeration to search through our main array for matches. If you don't know what fast enumeration is, in short it is a more efficient way of iterating of collections of data. Inside our loop we compare the scope to "All", and if we have a match we use some nifty functions to see if our search term matches what we have in our array. Notice the if statement also features two other parts - the second compares our "type" key - so maybe dinner or snack, to the scope buttons, and the last checks to see if the scope is nil - meaning we haven't set any buttons for our scope. So if we select the "Snack" scope button it will only compare items with a type set to "Snack".

This next bit of code is for your viewDidLoad method.

// create a filtered list that will contain products for the search results table.
//filteredListItems = [NSMutableArray arrayWithCapacity:[listItems count]];
filteredListItems = [[NSMutableArray alloc] initWithCapacity:[listItems count]];

// restore search settings if they were saved in didReceiveMemoryWarning.
if (self.savedSearchTerm){
    [self.searchDisplayController setActive:self.searchWasActive];
    [self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
    [self.searchDisplayController.searchBar setText:savedSearchTerm];
                
    self.savedSearchTerm = nil;
}

[self.tableView reloadData];

Here we simply restore any data that we have retained if our user dismissed the current view, and then reload our table to reflect any changes. Now we need to update our viewDidDisappear to make sure we actually save the data we are using in the above function, so go ahead and add the following lines to your viewDidDisappear method:

self.searchWasActive = [self.searchDisplayController isActive];
self.savedSearchTerm = [self.searchDisplayController.searchBar text];
self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];

And add this to your viewDidUnload method:

 self.filteredListItems = nil;

Now we need to think about our already-implemented UITableView methods - no you're not going mad, I've not written them here, but we need to change them up a bit. At the moment they all return data based on our main list called "listItems", this is okay if we need to display our table to users, but when in search mode, our functions will be returning the unfiltered data - let's get a fixin'.

The easy way to do this is to set up an if statement to detect if we are in search mode, and then return different data based on that information, that if statement looks like:

if (tableView == self.searchDisplayController.searchResultsTableView){
    // Search mode
}else {
    // Normal mode
}

So go ahead and add this to all your protocol methods; as an example your method for returning the number of rows in a section would look like:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.searchDisplayController.searchResultsTableView){
        return [self.filteredListItems count];
    }
    else{
        return [self.listItems count];
    }
}

Now we are ready to run it! Go ahead and hit run, and type something in the search bar, you should see a filtered list appear as you type. Now you may be getting a warning or two if you used the variable name "tableView", about the method parameters hiding your instance variables, in this case it's not a big deal, but it might be a good idea to change the name to something a little more descriptive in the future.

So what if we want to implement some scope buttons? Well now we've done all the work behind the scenes, we can jump into IB, and add some titles. So go to IB and select your search-bar. In the attributes inspector you should see a box that says "Scope titles", just above that is a check box that says "Shows Scope Bar" - check that, and use the +/- controls to add titles. Then if you want your scope bar to be visible all the time leave the check box checked, but if you want it to only appear when the search becomes active, uncheck the box. Now when you run the program you should see that a scope bar has appeared!

And with that, we have successfully added search to our app. If you have any issues with this code do let me know, and if you want the completed project use the link below.

Completed XCode 4 Project

Generate a calendar with PHP

Note: This article has been marked for a quality review and will soon be updated.

Calendars are useful for a wide variety of things, least of all planning and recording events that are going to happen in the future, and while it may not be obvious at first, there a are a number of challenges in creating a dynamic calendar with PHP. In this tutorial I will show you the basics of what you need to get started. See an example of what we will be creating here.

Let's first think about what we are creating. We want a standard calendar that will display dates month by month, and in this tutorial we will make it dynamic as to display the current month, and highlight the current day. But unfortunately this isn't as simple as printing out 31 days and labelling them up. Because calendars show dates preceding and succeeding the month, we need to display our data based on the day of the week that the month starts on, this is something we need to think about when designing the code. Not all months have 31 days in them either, so we need to build a system which adapts to each month.

Let's take a look at the PHP. First we will gather all the information we need about the month - we will be using the current month, but you could change the values of the following variables based on your needs.

$today = date("d"); // Current day
$month = date("m"); // Current month
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month

$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
		
$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
$laststart = $start - 1; // Days of previous month in calendar

Okay, so the code above utilises some inbuilt functions and stores al the data we need. Firstly we get today's date using PHP's date() function, having this will allow us to highlight the current day. We then collect the current month, year, and the number of days in the current month. All pretty standard so far. Then we go on to get the number of days in the month preceding the current month, as well as both the start and end date of the current month. We can use those variables to figure out an offset so that we can display the day on which the current month started correctly.

To that we will add the logic that will actually display the calendar:

$today = date("d"); // Current day
$month = date("m"); // Current month
$year = date("Y"); // Current year
$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month

$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month

$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
$laststart = $start - 1; // Days of previous month in calander

$counter = 1;
$nextMonthCounter = 1;

if($start > 5){	$rows = 6; }else {$rows = 5; }
for($i = 1; $i <= $rows; $i++){
	echo '<tr class="week">';
	for($x = 1; $x <= 7; $x++){				
		
		if(($counter - $start) < 0){
			$date = (($lastmonth - $laststart) + $counter);
			$class = 'class="blur"';
		}else if(($counter - $start) >= $days){
			$date = ($nextMonthCounter);
			$nextMonthCounter++;
			
			$class = 'class="blur"';
		
		}else {
			$date = ($counter - $start + 1);
			if($today == $counter - $start + 1){
				$class = 'class="today"';
			}
		}
				
			
		echo '<td '.$class.'><a class="date">'. $date . '</a></td>';
		
		$counter++;
		$class = '';
	}
	echo '</tr>';
}

Let's go over what that does. To begin with we figure out how many rows we are going to need by checking to see if the start day is greater than a Friday; if it is, we have 6 rows, otherwise we have 5. We then have a nested loop - one for the weeks, and one for the days in the weeks. Looking at the code we can see that the first loop runs as many times as there are rows, while the inner loop always loops 7 times. Then we have a fancy if statement to give us our date. In plain English, this is what it does: if the number of days already processed, take the starting day of the current month is less than 0, output a day from the last month - this makes sure we fill in the gaps, so if the current month started on a Tuesday, this code would get executed on the first iteration to display last month's Monday. If not, is the day in question part of next month? If so output the day with it's own date - nice an simple because all months start from 1.

And then we come to the last part of the if statement, which will be executed if the day in question is part of the current month. If it is today's date we give it a class of "today". Then we output the variables, increment our counter variable to keep track of the current day, and reset our $class variable.

So to put it all together within a table we would have:

<section id="content" class="planner">	
<h2><?php echo date("F Y") ?></h2>

<table class="month">
	<tr class="days">
		<td>Mon</td>
		<td>Tues</td>
		<td>Wed</td>
		<td>Thurs</td>
		<td>Fri</td>
		<td>Sat</td>
		<td>Sun</td>
	</tr>
<?php 
		
	$today = date("d"); // Current day
	$month = date("m"); // Current month
	$year = date("Y"); // Current year
	$days = cal_days_in_month(CAL_GREGORIAN,$month,$year); // Days in current month
	
	$lastmonth = date("t", mktime(0,0,0,$month-1,1,$year)); // Days in previous month
	
	$start = date("N", mktime(0,0,0,$month,1,$year)); // Starting day of current month
	$finish = date("N", mktime(0,0,0,$month,$days,$year)); // Finishing day of  current month
	$laststart = $start - 1; // Days of previous month in calander
	
	$counter = 1;
	$nextMonthCounter = 1;
	
	if($start > 5){	$rows = 6; }else {$rows = 5; }

	for($i = 1; $i <= $rows; $i++){
		echo '<tr class="week">';
		for($x = 1; $x <= 7; $x++){				
			
			if(($counter - $start) < 0){
				$date = (($lastmonth - $laststart) + $counter);
				$class = 'class="blur"';
			}else if(($counter - $start) >= $days){
				$date = ($nextMonthCounter);
				$nextMonthCounter++;
				
				$class = 'class="blur"';
					
			}else {
				$date = ($counter - $start + 1);
				if($today == $counter - $start + 1){
					$class = 'class="today"';
				}
			}
				
			
			echo '<td '.$class.'><a class="date">'. $date . '</a></td>';
		
			$counter++;
			$class = '';
		}
		echo '</tr>';
	}
	
?>
</table>
</section>	

If you wanted to add things like 'st' to each date, or even the day to each date you could use a case statement to switch on the $x variable - 1 being Monday, 2 being Tuesday, and so on. And that's that! Don't forget to style the classes that I added such as "blur" to those days that don't fall in the current month, as well as "today" to, well I'm sure you can figure that one out 😉 And as always check out the demo here.

CSS From Scratch

Continuing the series of learning web development from scratch is my introduction to CSS. In the video I go over how to add style to the killer robots site and introduce simple CSS to enable you to make your sites look awesome!

As always leave a comment below if you need anything clarifying, and you can download the source code or view the demo using the links below.

View Demo
Download files
Previous: HTML From Scratch

HTML From Scratch

I am often asked where to find quality tutorials on beginning learning HTML and all that jazz, so I thought I'd make a video! This is the first in a series I call "From Scratch" that aims to teach total newbies how to make web-pages, I hope the video explains it all well enough and you get something from it. As always comment below if you need any help.

You can view the demo of what we create, and also download the finished product below.

View demo
Download files
Next: CSS From Scratch

WordPress: Load more posts on page scroll

Note: This article has been marked for a quality review and will soon be updated.

Although I don't visit archive pages very often, when I do I like it when I don't have to trawl through pages and pages of 10 posts using tiny navigation buttons at the bottom of the page. A great way to prevent this annoyance for your users is to use AJAX to dynamically append posts to the end of your archive list. To do this in WordPress we need to abstract the process of getting the list of posts and then use some Javascript (in out case jQuery aided) magic to load in our content. So lets get started.

First off we need to create a function that we can call to spit out a list of posts. Usually on an archive page we would use the normal WordPress loop to accomplish this, but in our case we need to abstract the loop into a separate function so that we can access it from any file - more specifically our Javascript file. We also need to be able to pass an offset value to this function to make sure we don't load the same posts every time it is called. This function is going to differ slightly depending on your markup for your archive page, but this is how it would look for Tom's Big Box:

function getArchives($count,$offset){
	query_posts('posts_per_page='.$count.'&offset='.$offset);
	
	$posts = array();

	if(have_posts()) : while(have_posts()) : the_post(); 	
		$img = post_image($post->ID);
		$commentsNo = get_comments_number();
		if($commentsNo==0){
			$comments = 'No Responses';
		}else if($commentsNo==1){
			$comments = '1 Response';
		}else {
			$comments = $commentsNo . ' Responses';
		}
		
		$item = '<li id="'. get_the_ID() .'">
			<figure class="vignette left">
				<img src="'. get_bloginfo('template_url') .'/scripts/timthumb.php?src='. $img->src .'&w=180&h=120" alt="'. $img->alt .'" />
			</figure>
			<h3><a href="'. get_permalink() .'">'. get_the_title() .'
			<p class="article-meta left">'. get_the_time('jS M Y',$post->ID) .' ~ '. $comments .'

<p class="extract"> '. get_the_excerpt() .' </p> </li>'; array_push($posts,$item); endwhile; endif; return $posts; }*/

Stick this in your functions.php file, and we can walk through what this code is doing. Firstly the two parameters that we it accepts are $count - which tells our functions how many posts we want, and $offset - to ensure that we don't load the same posts every time our function is called. We then send these parameters to WordPress's query_posts() function which will give us a list of posts. We then set up the $posts array to sold our data and begin iterating through the posts. I created a separate image variable to hold information about each post's image because I don't use WordPress's inbuilt image resizing, this is something which may not apply to you. After that an if statement creates a nice string based on the number of comments per post - this is because the inbuilt functions return only the number of comments or directly outputs to the document - something we don;t want. Then we load our content into the $item variable using whatever markup we need, and finally use array_push() to add our $item variable to the $posts variable, before returning the final $posts variable in its entirety.

Phew! Well that's most of the server-side stuff done, but before we can say goodbye to PHP, we need to do one more thing. We need to create a file to which we will pass our parameters, and that will execute the function we just created, and return the code we need. Don't worry, this is far simpler than the function above, let's take a look at the code:

require( '../../../../wp-load.php' );
$posts = getArchives(20,$_GET['offset'],false); 
foreach($posts as $p){
	echo str_replace("'","'",$p);
}

So, ignoring the first line for a moment, this file simply passes the $_GET['offset'] variable to our newly created function, and then iterates over the output, making sure to replace any single quotation marks to stop it from breaking. "But hang on Tom, what does that first line do?!" I hear you cry, well the first line makes sure we can access the function we just created, and for that matter all the inbuilt WordPress functions, so it is vital that you keep it. You will also need to change the path in the require() statement to ensure it matches the root directory of your WordPress install. Pop the above code in a file called get-posts.php and stick it in your theme's directory. And with that, we can say hasta la vista to PHP, and buongiorno to jQuery (that's right, I'm cultured).

Now, having made sure jQuery is included on your page, paste in the following code:

var halfWay = ($(document).height()/2);
var offset = 20;
var inAction = false;
var reachedEnd = false;

$(document).scroll(function(){
   if($(document).scrollTop() > halfWay && inAction == false){
       inAction = true;
		
       $('.article-list').append($('
').load('http://example.com/wp-content/themes/myTheme/get-posts.php?offset='+offset, function(){ offset = offset + 20; halfWay = halfWay + 1775; inAction = false; })); } });

Lets go through what this does. We have a function that fires whenever the page scrolls, and within that we compare the current scroll amount to half the overall document height, if it is greater (meaning that the user has scrolled more than half way down the page), and the variable inAction (I'll get to that in a moment) is true, it executes the following code. If the conditions are satisfied we then use AJAX to load in some more posts. Now it may appear a rather convoluted way to be doing so, but in my experience this way of handling an AJAX request of this type is the best. So for this method we send a request to our file that we just created in our theme's directory, and pass it the variable offset, when the content is loaded we run the embedded function which increments our offset variable by 20, adds a suitable amount to our halfWay variable. We then reset the inAction variable. This variable is used to prevent a massive build up of requests because of page scrolling, we use it because every time the page scrolls even a pixel, the function is called, so we don't want it to be called 3 times before we have a chance to offset the next post, otherwise we will end up with a huge amount of duplicate posts being loaded in. The conditions in the if statement will stop being satisfied after the last posts are loaded in because our inAction will stay in it's true state forever after one request for no posts means the success() function isn't executed.

And that's it! It might be a good idea to have a loading graphic at the bottom of you page when doing this to give some user feedback, and I would suggest also adding pagination just incase your server stops responding and leaves your users hanging. But aside from that, I think I covered the basics of how to implement the AJAx loading in of content. Oh and by the way, you will now also be able to generate archives anywhere on your site using the function getArchives(), meaning you will write less code in the long run - two birds with one stone!

Elegant URL Rewriting

To me .htaccess files are black magic - one letter wrong and you get internal server errors bouncing around everywhere, so when it came to URL re-writing (more specifically removal of file extensions) I was a little tired of getting "Error 500" messages. But I finally managed to manipulate the dark magic that lyes deep within the realms of the kingdom of .htaccess file, and created a system whereby I made my server pass all URL arguments to a single file to play with. Here's what I did.

Firstly you're going to need to edit your .htaccess file, for my purposes I send all the info to my index.php file like so:

RewriteEngine On

<IfModule mod_rewrite.c>
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

The code above simply ignores the path that was requested, and loads your index.php file. From there we can do implement some logic to decide what it is our users are after. To be able to understand the request we need to find out what the URL is, and to do that we will use some PHP to grab the URL, and then put the contents into an array like so:

$request = explode('/', $_SERVER['REQUEST_URI']); 
$args = array();
	
//Remove empty indexes
foreach($request as $r){
	if(!empty($r)){
		array_push($args, $r);
        }
}		

The above code simply creates an array where each index contains parts of the URL separated by a slash ('/'). We then look for any empty parts of the array to make sure we don't run in to difficulty later on. Now we need to think about when users visit the root directory of our site, when they do our array will be empty, so we need to cater for that by assigning our default page to our array with the following code:

//Allow no parameters
if(empty($args) || $args[0] == 'index.php'){ $args[0] = 'home'; }

Now for the next part we also need to consider page titles to use in out <title> sections, to do that we will look at making the slug more human-readable. We will implement that alongside the code that will deal with actually getting the physical files, and what we will do if a certain file doesn't exist.

if(file_exists($args[0] . '.php')){
	$page = str_replace("-"," ",ucfirst($args[count($args)-1]));
	include($args[0] . '.php');
}else {
	$page = '404';
	include('404.php'); //Keeps URL intact
}

So above we check to see if the file exists, and if it does we set the $page variable to a proper title - this isn't entirely necessary, but I found it useful later on. After that we simply include the file that was requested. But if the file doesn't exists, we include our 404 page to make sure our site doesn't simply throw an error.

Now in my case the included files would then query a database for content, but if you'd like you can do that directly in this file - instead of the include() statement, you could set up a database query there to ask for the page "with title" and go from there.

And with that you should have some fine looking URLs!

Build an uploader for S3

S3 is Amazon's "Simple Storage Service" for hosting content on the web. It allows developers to offload static content to their powerful content delivery network at low cost, to improve site performance. I've used S3 on a number of projects to host content, but one thing that only recently cropped up wad the notion of allowing users to upload their own content to the service from within any given site. To accomplish this I had to use a little bit of everything, including PHP and jQuery. But don't worry, if you don't want to use jQuery, this technique should still apply to other implementations.

As I said we will be using jQuery for this, and more specifically, the fantastic plugin Uplodify - a set of files that will enable simple uploading, and that will handle all the heavy lifting of file manipulation. So go ahead and download/unzip Uplodify, and then stick it on your server. I then used the following standard HTML to display the upload button.

<div id="upload_box">
	<div id="file_upload" name="theFile"></div>
</div>

Having done that, make sure to include jQuery, swifobject.js, and jquery.uplodify.[VERSION].js, and then add the following JS.

<script type="text/javascript">
    $(document).ready(function() {
      $('#file_upload').uploadify({
        'uploader'  : 'uploadify.swf',
        'script'    : 'uploadify.php',
        'folder'    : 'uploads',
        'multi'	: true,
        'fileExt'   : '*.jpg;*.gif;*.png',
        'auto'      : true,
        'buttonImg' : 'button.jpg',
        'width'	: '86',
        'height'	: '28',
        'onSWFReady': function(){ $("#file_upload").show(); },
      });
      
    });
</script>

And that's the basic configuration needed to get Uploadify working. Now we need to enlist the help of a PHP class to enable us to interface with S3. That class allows you to do some pretty advanced stuff, and is a great solution all round for working with S3. In our case you just need to download that that and pop it in the same directory as the file uplodify.php.

And now we are finally ready to add the functionality that we've all been waiting for. Open uplodify.php and change:

move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);

to:

$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile =  str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];

 $fileTypes  = str_replace('*.','',$_REQUEST['fileext']);
 $fileTypes  = str_replace(';','|',$fileTypes);
 $typesArray = split('\|',$fileTypes);
 $fileParts  = pathinfo($_FILES['Filedata']['name']);

 if (in_array($fileParts['extension'],$typesArray)) {
	
	if (!class_exists('S3'))require_once('S3.php');
	
	//AWS access info
	if (!defined('awsAccessKey')) define('awsAccessKey', '[ACCESS KEY]');
	if (!defined('awsSecretKey')) define('awsSecretKey', '[SECRET KEY]');
	
	//instantiate the class
	$s3 = new S3(awsAccessKey, awsSecretKey);

	//move the file
	$s3->putObject($_FILES['Filedata']['tmp_name'], "[BUCKET NAME]", $_FILES['Filedata']['name'], S3::ACL_PUBLIC_READ);


	echo "http://s3.amazonaws.com/[BUCKET NAME]/".$fileName;
 } else {
 	echo 'Invalid file type.';
 }

So what we've done there is replaced the part of the code that previously moved the uploaded file (with the imaginatively named move_uploaded_file() function), with some code to invoke a move to your S3 bucket. As you can see in the code above, the functions require some information that you will need to provide yourself such as your secret key - this can be found by logging in here.

And that's that! As I said above the class can be used for more advanced manipulation of your S3 buckets and account, so do go and explore some of the things you can do with that, and have fun uploading!

Use PayPal for pay-per-post on WordPress.

Note: This article has been marked for a quality review and will soon be updated.

As you may know I like WordPress - it's a great platform for building websites on. As you may not know is, I like PayPal - it's an easy to way to safely make quick payments online. Now you may be asking what the hell I'm on about, have I been paid by WP and PayPal to go on about their services? Nope. Today I want to share with you an easy way to integrate these two fantastic services, to allow users of your site to pay each time they want to post on your site. For this we will be using the PayPal API, and a rather special page indeed which will allow your users to post from outside of the admin panel. If you didn't know, there is already a tutorial on doing so entitled - Publishing to WordPress from outside the admin panel, so go ahead and check that out, and then come back over here.

So first let's think about the theory behind this. We want users to go to our post-page, and then be asked to buy a token to post 1 article; we then want to send the user to PayPal, for them to pay us, and then be sent back to our site, where the same post-page now shows them everything they need to post an article. Sound good? Almost there, we need to make sure we prepare for something - say for instance the user has user paid, and there is a power-cut at their house, in that case they will have just lost the money they paid us, and will be rather angry that there is no way to get it back; so essentially we are covering for the user closing their browser without posting, having paid us. And for that we are going to enlist the help of the cookie monster! Nah, just kidding, we'll stick to just one cookie for now - which will be placed on the user's machine to tell our site that they have paid, and when they have posted we can alter the cookie to reflect that. So let's go ahead and start with our posting page, place this code above your form.

<?php
if($_POST['payment_status']=="Completed"){
  $paid = true;
}else if($_COOKIE['activeToken']=="true") {
  $paid = true;
}else {
  $paid = false;
}

if(!$paid){ ?>

// User hasn't paid

<?php }else {  ?>

So what do we have here? Well at the top we can see we are checking to see if a posted variable is equal to "Completed" - this is something that PayPal gives us when the user has completed their transaction. We then set the $paid variable equal to true. Next we check a cookie to see if it's value is "true", and once again if this is true, we set $paid equal to true. And finally if neither of the above conditions validates we simply set the variable equal to false. Next we have an if statement which runs if $paid is equal to false - using the handy ! just before the variable. Now, after the else { statement is where you will want to put your form for posting an article, but not before you enter our crazy AJAX/Cookie-goodness code which follows.

<script type="text/javascript">
  $(document).ready(function(){
    var dataString = "cval=true";
    $.ajax({
      type: "POST",
      url: "<?php bloginfo('template_url') ?>/scripts/cookie.php",
      data: dataString,
    });
  });
</script>

// Your HTML goes here

<?php } ?>

Woah what the frick is that?! I hear you shouting. Right well let's go from the top. First off we can see that we are using JavaScript, and also jQuery - so make sure it's included, and we are also waiting for the DOM to have fully loaded everything before beginning our code. Then inside of this code we are setting up a variable named dataString and setting it's value to "cval=true" - more on this soon. Then we create an AJAX call using jQuery which will POST to a URL which is in our theme folder in the scripts sub-folder, to a file named "cookie.php" the data in the variable dataString. Make sense? Hopefully it does. Now you might be thinking, but wait a moment, I don't have a file called cookie.php, and even more annoying is that I don't even have a folder called scripts in my theme directory. Well don't worry - go ahead and create a new file called cookie.php in your theme directory, and if you tend to store scripts in another directory like me, go ahead and move it into that directory - just be sure to update the URL there - and if you didn't know that handy bit of code that reads <?php bloginfo('template_url') ?> just spits out the URL of your theme's directory. Now, copy and paste the following code into your new file.

<?php
$expire = 60 * 60 * 24 * 60 + time();
setcookie('activeToken', $_POST['cval'], $expire,'/');
?>

So what does that code do? Well the first line sets up a variable named $expire which holds the value of the date two months from today using some basic maths. Then we use the PHP function setcookie() to create a cookie in the format setcookie(name,value>,expiry date,directory) - now you might be wondering what that final "directory" bit is about - put simply that is the location where your cookie can be read from - if you leave out this parameter you won't be able to access your cookie, except from the cookie.php page you created it on - not ideal.

Now we have a good thing going now, but we need to think about when the user has submitted the form, and posted an article - we need to alter the cookie to tell our site that the user has used up the token he bought - simply by using the same JavaScript code that we used above, but changing "cval=true" to "cval=false". Now if you submit your main form using AJAX you can simply add this function in the success: parameter, otherwise you might want to do any number of other things - using jQuery's submit() function like so.

$("#myform").submit(function(){
  var dataString = "cval=false";
  $.ajax({
    type: "POST",
    url: "<?php bloginfo('template_url') ?>/scripts/cookie.php",
    data: dataString,
  });
});

Or you could stick the code on the page to which new post data is posted (new-post.php). Either way, you just have to ensure, that when the submit button is clicked - the cookie is set to false.

Now we've done nearly everything without having touched PayPal - the subject of the next section of the article; but before we begin I want to eradicate any preconceptions you may have about working with PayPal. Many people think it will be rather difficult to use PayPal in the way I am going to describe - that because you are dealing with people's money there is a greater margin for error. But this isn't the case - because at the end of the day, PayPal is the one going all the ground-work, and if it doesn't like what you are doing - it's going to tell you, so don't worry - and just go crazy! So go ahead and replace that comment we created earlier "//User hasn't paid" with the following code - kindly provided by PayPal.

<form action="https://www.paypal.com/cgi-bin/webscr?return=<?php the_permalink(); ?>&cpp_header_image=http://example.com/myHeaderImage.jpg&cbt=Return and post an article&rm=2" method="post">
<!-- Identify your business so that you can collect the payments. -->
<input type="hidden" name="business" value="name@example.com">
<!-- Specify a Buy Now button. -->
<input type="hidden" name="cmd" value="_xclick">
<!-- Specify details about the item that buyers will purchase. -->
<input type="hidden" name="item_name" value="Job Post Token">
<input type="hidden" name="amount" value="1000"> <input type="hidden" name="currency_code" value="USD">
<!-- Display the payment button. -->
<button value="Buy Posting Token"><span>Buy Posting Token</span></button>
<img alt="" border="0" width="1" height="1" src="https://www.paypal.com/en_US/i/scr/pixel.gif" >
</form>

So above, we have a form with a heck of a lot of information in it, but if we break it down, it's actually rather simple. Firstly we set up the form and tell it to post to PayPal's website - we also specify a number of variables to post along with it - the values of which are highlighted in bold. Firstly we have return - where the user will be returned to, once payment has been completed, for this we use the page's URL, helpfully provided to us by WordPress. Then we send it something called cpp_header_image - a 90x750px image which will be used in the header - using an image of your own will make the user feel more comfortable, and looks more professional. Then a variable called - cbt - which is the text used on the button which will send users back to the return URL specified above. The last variable is to do with PayPal posting values back to our page - including that of the handy payment_status - so don't change that.

The next value highlighted in bold is an email address - this is where you should enter the email address of the PayPal account holder to which all transactions will be credited. Next is the value "1000" - which is the amount you wish to charge your users to post - in this case $1000 - may be a little pricy - you decide. The currency is also set below and is currently set to US Dollars. PayPal provides a full list of variables for you to use, which is worth checking out for further customisation.

And that, ladies and gentlemen, is that! So now hopefully you can see just how easy it is to integrate PayPal with WordPress. As always if you have any questions/problems with the tutorial, leave a comment and let me know what you think.

Edit
For those of you who wish to make visitors to your site pay per viewing of each post you would need the following code structure alongside the code above.

<?php
if($_POST['payment_status']=="Completed"){
  $paid = true;
}else if($_COOKIE['activeToken']=="true") {
  $paid = true;
}else {
  $paid = false;
}

if($paid){ ?>

// User had paid, therefore enter the WordPress loop for the post

if(have_posts()) : while(have_posts()) : the_post();

//etc

<?php }else { ?>

//User hasn't paid, so display the payment options

<?php } ?>

Check out the codex for more information on the loop.