Writing PHP Code to Standard

So with the release of AWS SDK Version 2, I’ve been inspired a little to write better PHP Code, at least in stuff I have on my GitHub. The new SDK is written to match the PHP Framework Interop Group PSR-0, PSR-1 and PSR-2, as well as Composer/Packagist Support.

I been working a on project to make starting a new project easier, (create a repo, setup the deployments, Apache VHost etc). Primarily working off of the ATech Media Suite of products.

Starting from a base of peterjaap’s Codebase PHP Wrapper, where I was just adding missing API endpoints to the class, at which point the new AWS SDK was released and inspiration of a sort struck.

I started a new project from scratch, to implement all the API’s that Atech runs, it’s very much in progress, I’ve currently got full support for DeployHQ and PointHQ end points, (as well as having gotten a few obvious missing end points added to the API).

I’m clunking my way thru the CodeBase API, it’s taking some time as its got a truck load more end points, that DeployHQ and PointHQ put together. It has Projects, which have repos, which have tickets, just to scratch the surface.

At the moment it’s largely functional, it’s just missing some extras, the Time Tracking, File Uploads, and so on.
It’s very much a learning experience in an attempt to follow the coding standards as well as laying the code out properly.

At the moment the CodeBase class itself is pretty large, and I’m pondering about splitting it out to sub classes. Classes to represent Projects and Repos and Tickets and so on, but its the first thing I’ve tried to build in such a way, so much consideration is needed, to hopefully get it right. I keep looking at other Project like the AWS SDK and GoCardless’ PHP Class.

The only thing thats really missing, is Unit Testing, which I still need to sit down and learn properly, but I’m still trying to find a suitable entry point to teach myself, and of late been expanding my knowledge using Code Academy, more on that in another post!

So thats a short update on PHP Development in general, you can checkout the ATech API Class so far on GitHub. Feedback always welcome!

(I’m trying to write more on my blog, as well as more PHP in general, hence a in progress post instead of a “It’s completely finished give it a whirl” post)

Extra Jetpack!

So recently I’ve been mucking about with JetPack, for various bits and pieces.

Mainly the first thing done is just to make the sharing buttons appear above and below a post.

But from browsing the JetPack Support Forum over on extend I thought I’d make my changes available.

So, attached to this post, is my modified version of JetPack 1.4.2.

Which includes the following additions:

  • Ability to control button placement, above, below, or both of the post content
  • A Pinterest PinIt Button as requested on the forum, it will attempt to use the Post/Page Featured Image as the Image to Pin
  • Additional Twitter button elements/arguments, for recommended Twitter account following (via and related)
  • Ability to turn on/off the DNT Twitter button mode: see the docs, about what this is and does
  • Hope you find it useful.

    If using JetPack 1.6.1 use the Extend Version
    [download#4] Pre JetPack 1.6
    [download#3]

    Feedback and requests in the comments please 😀 or hit me up on Twitter: @BarryCarlyon

    (On a side note, I need to fix some theme glitches on here, hence a double featured image on the home page….)

    Update: Make sure your theme is using a recent version of jQuery. As otherwise the [+ Share] won’t pop up (for extra hidden sharing buttons)

    Update: Created a new Plugin, that doesn’t replace JetPack, it extends and runs as a separate plugin.
    So more Core JetPack update friendly. Upload and activate like a normal plugin.
    Includes a suggestion from @SkipTweets Option to use the WP.me link instead of the permalink for Twitter Sharing

    Update: The plugin is now available on extend!

    Update: JetPack Core has now updated to 1.6.1 which adds a Pinterest Button to Core. They also updated the entire ShareDaddy plugin. It looks like they are adding Twitter Via Support to.
    I’ve just released a Maintenance Fix as if you Update JetPack, it WhitePages, due to conflicting Pinterest Buttons.

    Update: Check out the Special Plugin Page

MineCraft Math

So, I tend to now and again do random bits and pieces to MineCraft Servers.

Of late I have been working with ZimDoorCraft, took the existing relatively static site, and flipped it over to a Mini PHP Powered Content Management System, that I wrote and roll out to smaller sites.
Couple of MySQL powered bits to make updates easier (Staff list and the like).

In time more complex and interesting things will be added (it was for a while running a Login with Mojang/MineCraft account, but that means you type your MineCraft login into the site…), how that works is a subject for another post. As is what ever I build next 😀

The MineCraft server in this case is running a derivative of Bukkit, which means it supports plugins, so we are using the JSON Api plugin, and making a call to the getWorld() data resource.
Which passes back information about the world in a nice handy format.

Heres an example

    [world] => stdClass Object
        (
            [remainingWeatherTicks] => 14670
            [hasStorm] => 
            [time] => 4964
            [environment] => normal
            [isThundering] => 
            [name] => world
            [fullTime] => 2903932964
        )

If your running Vanilla you can grab the same information just by decoding the level.dat file in the World Directory, however opening a file currently being written to, is not often a good idea, and the level.dat is written to a lot.

Like a lot of games, Minecraft uses ticks, in this case operating at 20 ticks per second, and running to 24000 ticks per Minecraft day, which means a Minecraft day is about 20mins.

Just to be interesting 0 ticks is Sunrise, rather than midnight. And midnight itself is 18000 ticks.

Also contained in the data packet is a count down to when the weather changes, in this case there are 7500 (ish) ticks to go.

Which works out as

14670 / 20 to get Real Seconds = 733.5 Seconds, and then its arbitrary to flip this to a human readable time. We have about 12 minutes, or half a MineCraft day, until the weather changes.

Reading out a more recent packet

    [world] => stdClass Object
        (
            [remainingWeatherTicks] => 7339
            [hasStorm] => 1
            [time] => 3827
            [environment] => normal
            [isThundering] => 
            [name] => world
            [fullTime] => 3902379827
        )

Looks like there is a storm on…. But its only Rain no Thunder and Lighting. With 6 mins to go.

On a side note!, watch out for FullTime, as its likely to run away, on a long running server, to something a 32 bit system might not be able to handle! Refer to my Post on Facebook and the Order ID on some thoughts about dealing with that.


Using Tick to Seconds math, means that it is also possible to display the current server time and weather on the website.

I’m using a bit of CSS, and the MineCraft time piece (craftable in game) to show the current time visually. In this case I’ve taken the 16×16 PNG’s and expanded them (by hand) to 32×32, finally converting the time from ticks to the relevant chunk of 360 degrees, offsetting as needed to account for the fact that Sunrise is 0 instead of Midnight.

I do this by adding 6000 ticks and from there treating the ticks complete as a percentage and scaling to meet 360 degrees. Some of the code involved needs a little tweaking and tidying to improve efficiency, but the angle is being calculated by a CRON Job powered script and stored with the full World JSON packet, in an extended object and cached in a file on the file system ready to be read by the web server when a request comes in. So it’s not a top priority to clean up yet.

I was finding that after taking into account the addition 6000 ticks to offset for Sunrise, the whole Sun Moon picture was upside down. So I just added 180 degrees, and corrected it when the angle was greater that 360. Since why bother rotating thru a whole 360 degrees?


$time = $world->time;// grab from data packet from JSON Api Call
$time += 6000;// add 600 for sunrise

// work out the scale factor 360 degrees / ticks in a Minecraft day
$scale = 360 / 24000;
$angle = $scale * $time;// calculate the <span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="">angle
$angle</span></span></span> = number_format($angle, 0);// clean up
// correct
$angle = $angle + 180;// the image is upside down :-(
if ($angle >= 360) {// clean up again
	$angle -= 360;
}

The rotation component was quite difficult to initially decide how to do, PHP wasn’t quite cutting it so switched to a CSS Transform.
HTML wise it consists of a pair of divs, a pair of images, and a chunk of CSS.

<div class="worldtime"><div class="inner"></div></div>


WorldTime being the one behind contains the Sun Moon Picture as a background image.


And Inner contains the Watch overlay also as a background image.

Apply the CSS transformation to rotate the Sun Moon Picture is just a little nasty, because in rotating the Sun Moon picture it also rotated the overlay (inner).
I decided to apply rotation to the overlay, in the reverse direction (so just sticking a negative sign in front).
Works quite well, but if you can think of a better way to spit out this with the rotation please comment below.

Heres my current Style Code

<style type="text/css">
	.worldtime .inner {
		width: 32px;
		height: 32px;
		background: url('large_watch.png') left top no-repeat;
	    /* CSS3 then proprietary code */
	    rotation: -336deg;
	    -webkit-transform: rotate(-336deg);
	    -moz-transform: rotate(-336deg);
	    filter: progid: DXImageTransform.Microsoft.BasicImage(-rotation=4);
	}
	.worldtime {
		float: left;
		width: 32px;
		height: 32px;
		margin: 0 10px;
		background: url('large_inner.png') left top no-repeat;
	    /* CSS3 then proprietary code */
	    rotation: 336deg;
	    -webkit-transform: rotate(336deg);
	    -moz-transform: rotate(336deg);
	    filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=4);
	}
</style>

The whole WorldTime Div is then wrapped in another Div and jQuery used to once per minute go and fetch the updated time, weather and CSS rotation.

At first I did try using the PHP function to rotate the image, but the quality drop off when rotating by an angle not divisible by 90 was shocking.
So ended up resorting to CSS, which does work a hell of a lot better.

This only covers how to do this using the JSON API, in a future post I’ll talk about decoding level.dat and other Minecraft Files.

Facebook Credits, the Order ID, and dealing with large integers in 32 bit PHP

So, currently at work I’ve been rewriting all our Payment Gateways for Your Members. Making them more better Class based an abstracting out the common functions to a base class, to save memory footprint and code etc.

And came across a problem when rewriting the Facebook Credits handler.

The order ID that gets passed around, as well as the Application ID is too long for a 32 Bit PHP installation to handle when treating it as an Integer.

So a number like “239724439419867” was ending up as “1.7592246582797E+14” when stored/processed, or converted to a string.
Now the obvious way to process this is to convert it to a string another way, which is somewhat difficult since before you even start it is in a format that you can’t handle.

The saving grace here is the fact that data is passed to you as a JSON packet (aside from the fact the Order ID is in the $_POST variable and thus a string, so I could of used it from there).

This led to me to look at the JSON packet, which starts as a string but when decoded the large integers are still a larger integer than can be processed (whether you json_decode to a Array or to an Object, the problem persists). So I thought about how to process the raw JSON packet and make sure the order ID, and other large integers are treated as strings.

If you look at a Raw JSON packet you can easily spot whats a string, integer, object or array.

Take this example Facebook Credits JSON Packet, (wrapped for readability):

{"order_id":239724439419867,"buyer":197803678,"app":148748711865470,
"receiver":197803678,"amount":5,"update_time":1320075413,
"time_placed":1320075408,"data":"","items":[{"item_id":"<item_id>","title":"Post",
"description":"A New Purchasable Post",
"image_url":"<some url>","product_url":"<some other url>",
"price":5,"data":"<data>"}],"status":"<status>"}
  • order_id is an integer as it has no ” around it
  • status is a string as its surrounded by “
  • Items is an array as its surrounded by [, in this case containing a single object, entries/items are comma separated.

So after thinking about this I decided the best way to sort this out was to convert the integers in the raw JSON packet to strings before decoding.

In pseudo code.

Lop off the { and } from the start and end
Explode around ,
array walk each item
split on :
check if there are no " in the second bit
if none wrap in "
glue back together

Something alone the lines of:

function largeint($rawjson) {
  $rawjson = substr($rawjson, 1, -1);
  $rawjson = explode(',' , $rawjson);
  array_walk($rawjson, 'strfun');
  $rawjson = implode(',', $rawjson);
  $rawjson = '{', . $rawjson . '}';
  $json = json_decode($rawjson);
  return $json;
}

function strfun(&$entry, $key) {
  $data = explode(':', $entry);
  if (FALSE === strpos($data[1], '"')) {
    $data[1] = '"' . $data[1] . '"';
    $entry = implode(':', $data);
  }
}

I’m not sure in terms of memory footprint if its cheaper to do a substr of $data[1] and check if its a ” or not.
I suppose it could test the string length of the detected integer to see if its invalid/unable to process, but then you would be performing a string function on an integer and again the problem would arise.

But as a block of code is does the job, its obviously not ideal for all situations, since in this case I want the integer as a string, I’m not using it for math, but if I did, we probably need to do some bizarre unpack-ing or something.

Any opinions or improvements give us a comment below 😀

Travels of a Commercial WordPress Plugin Developer 1

My job at the moment is updating and coding YourMembers, which is a commercial plugin for WordPress.

Recently I’ve been working on a method to Auto Upgrade the plugin, since commercial plugins cannot go on Extend, and there is no commercial equivalent. Extend being the WordPress plugin repository.

Commercial plugins get no nice little “Plugin needs updating Circle” on the plugins tab, or a nice little message on the plugins page, let alone access to the auto updater!

Which leaves us (commercial plugin devs) to write our own version checkers and hook in accordingly.

So now I have a nice little PHP class which will detect whether it can fwrite/rename and if not if it can FTP instead, much the same as the WordPress updater does.

Now this is all well and good, but I needed a method to download and unzip the new plugin file. Grabbing the file is easy, either file_get_contents (heaven forbid), or curl (yay for curl), and write the file (being a zip) to the web servers temporary directory and process from there.

Now the problem here is how to unzip. A Brief look at how WordPress does it seems to show it has three different methods of unzipping. So dump that.

Didn’t feel the need to use PHP’s ZipArchive class, since I don’t need to edit the zip, just extract its contents.

Off to php.net I go and I find some nice handy functions, and quite surprised to find that the zip_read function can handily recurs into directories within the zip file to return their paths/names. Mildly annoying at the time as I had gone and written a recur loop to go inside directories…. and got thrown a error, nice headdesk moment!

So basically the Zip functions, the basic ones of PHP, are actually quite nice, handy and useful!

Heres my code snippet:

<?php
class someclass() {
	private function unpack() {
		$from = $this->tmp_write;
		$to = $this->tmp_out;
		@mkdir($to);
		
		$zip = zip_open($from);
		if (is_resource($zip)) {
			$this->readzip($zip);
			zip_close($zip);
		} else {
			// failed to open
			$this->error = 1;
		}
	}
	
	private function readzip($zip) {
		$from = $this->tmp_write;
		$to = $this->tmp_out;
		
		echo '</pre><textarea style="width: 100%; height: 100px;">';
		
		while (FALSE !== ($file = zip_read($zip))) {
			$name = zip_entry_name($file);
			echo $name . "\n";
			if (!strpos($name, '.')) {
				// is dir
				@mkdir($to . '/' . $name);
			} else {
				// it recurs into directorys on its own!
				$item = zip_entry_open($zip, $file);
				$size = zip_entry_filesize($file);
				
				$read = zip_entry_read($file, $size);
				$fp = fopen($to . '/' . $name, 'w');
				fwrite($fp, $read);
				fclose($fp);
			}
		}
		
		echo '</textarea><pre>';
	}
}
?>

I just installed this code snippet plugin, which I might need to change its background colours…..

Any suggestions for code snippet plugins greatly appreciated!