Posts Tagged ‘php’

Remove Boonex Footer From Dolphin CMS

Posted in Code, Programming on March 11th, 2010 by Eric Lamb – 1 Comment

After the server lockout and subsequent move last week I had to setup all my old sites on the new server. Aside from the loss of a few posts my blog (which I could restore from Google cache) and a few comments (which I couldn’t restore unfortunately) everything was pretty smooth. That was until I had to move over one of my clients sites that was using Dolphin CMS.

Remove Boonex Footer From Dolphin CMS

Remove Boonex Footer From Dolphin CMS

The issue was that the client’s site was now being tagged with a Powered By Boonex footer; not cool because the client had purchased a license and shouldn’t have the callout to Boonex. It looked like the site couldn’t reach the licensing server so it was acting like the site wasn’t a valid and licensed version.

I had set up the new server in a pretty locked down way, using a pretty paranoid strategy with firewalls and port changes and all that fun stuff. Unfortunately for my client, this included mod_security which Dolphin requires special configuration for:

If some security module is installed on the server (such as mod_security for Apache), it should be able to be disabled or set up for specific folders.

Not wanting to allow such a blatant security hole into my server following the above just wasn’t acceptable. Instead I decided to just remove the call to the licensing server in the code; it’s just php so I didn’t think it would be too difficult. It wasn’t but it was a little confusing though so here’s the code and process in case anyone else has the need.

BECAUSE I DON’T WANT TO GET SUED: only use this if you’ve already purchased a license. Blah, blah, blah. Oh, and this has only been tested in Dolphin 6.1.

  1. First, open up “/inc/design.inc.php”
  2. look for a HUGE base64 encoded line (one really long and one underneath is short). You’re going to need to remove both lines.
    It should be around line 500 and indented a few pages in. If you can’t find it search for “base64_decode” and it’ll come up.
  3. Replace the both lines with the below:
$s813518='Y3JlYXRlX2Z1bmN0aW9u';$s534634='base64_decode';$s434741='YmFzZTY0X2RlY29kZQ==';$s865127='ZWNobw==';$s734874='Z2xvYmFsICRfcGFnZTsNCg0KJHM0MzUyMzYgPSBiYXNlNjRfZGVjb2RlKCAnWW1GelpUWTBYMlJsWTI5a1pRPT0nICk7DQokczU4OTM1NSA9ICdYMTlpYjI5dVpYaGZabTl2ZEdWeWMxOWYnOw0KJHM3NDM3NjUgPSAnWjJ4dlltRnNJQ1J6YVhSbE93MEtaMnh2WW1Gc0l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0NjU5MCApIHsNCiAgICAkczY1Mzk4NyA9ICRzMDIzOTUwKCAkczQzNTIzNiggJHM1ODkzNTUgKSwgZXZhbCggJHM0MzUyMzYoJHM3NDM3NjUpICksICRzNjUzOTg3ICk7DQogICAgJHM2NTM5ODcgPSAkczkzNzUwNCggJHM0MzQ2NDMsICRzNTQ1NjI0LCAkczY1Mzk4NyApOw0KICAgIGVjaG8gJHM2NTM5ODc7DQp9IGVsc2UNCiAgICBlY2hvICRzOTg3NTYwWyRzMzg1OTQzXSAuICcgJyAuICRzNDM1MjM2KCAkczY3NzQzNCApOw==';
 
$s545674=$s534634( $s813518 );$s548866=$s534634( $s434741 );$s947586=$s534634( $s865127 );$$s947586=$s545674( '$s653987', $s548866( $s734874 )

Boonex uses base64 to encode and obfuscate the licensing code so it can’t be modified without a bare minimum of trouble. Not that they had much of an option; php is notoriously hard to encode with any elegance or reliability. Anyway, they chose base64.

All that was needed was to base64_decode the code, and then base64_decode that code (yup, they did it twice). After that I made the changes to remove the HTML that displays the Boonex footer, base64_encoded that, then did it again to create the above.

So, once again, only use the above code if you’ve already purchased a license. Yes, it should work if you didn’t but I don’t want to get sued so it has to be said.

Bookmark and Share

Easily Add Gravatar to Your PHP Apps

Posted in Code, Programming on February 17th, 2010 by Eric Lamb – Be the first to comment

Among the few hassles to being a citizen of the Internets, along with multiple login credentials, comment trolls and pedophiles (obviously), is the hassle of multiple profile pics. Yes, it’s an extremely small problem but it is a problem solved by Gravatar.

Easily Add Gravatar to Your PHP Apps

Easily Add Gravatar to Your PHP Apps

Gravatar, which stands for Globally Recognized Avatar (seriously), is a service provided by Automattic (yes, the same Automattic that provides WordPress) that allows users to upload a single image which developers can then use on their websites. The outcome is that users have a single icon (or avatar) representing them, that they don’t have to repeatedly upload. Another, less publicized benefit, is that us developers don’t have to write all the photo uploading and resizing functionality. Again.

The Basics

From an implementation standpoint Gravatars couldn’t be simpler. At the base level it’s just a call to a URL that includes an md5() hash of a users email. For example my gravatar URL is the below:

http://www.gravatar.com/avatar/8a55f4e419d6d5314e420ba26bf7455e?s=75&d=wavatar&r=X

Looking at the URL (which hopefully, you’re comfortable looking at) it’s broken up like so:

Base URL: http://www.gravatar.com/avatar/

My Identifier (eric@ericlamb.net in md5()): 8a55f4e419d6d5314e420ba26bf7455e

Query String Parameters: s=75&d=wavatar&r=X

As far as the query string goes, none of the below are required but using them allows to customize the output. You have the following options:

Image Size: s (between 1 and 512)

Default: d (wavatar, identicon, monsterids or custom URL)

Rating: r (think movie ratings with G – X)

Considering all of the above, and how simple it is, I’m kind of amazed that there’s still an issue with wide adoption (though this could be due to Gravatar scaling the service for the obscene amount of traffic this would create) .

The Codes

Obviously, writing a little snippet to create the Gravatar URLs in PHP would be trivial to most programmers:

<?php
$url = 'http://www.gravatar.com/avatar/';
$email = 'eric@ericlamb.net';
$default = 'monsterid';
$size = 75;
 
$grav_url = $url.'?gravatar_id='.md5( strtolower($email) ).
'&default='.urlencode($default).'&size='.$size; 
?>
<img src="<?php echo $grav_url;?>" />

Simple but the code above could be a lot more useful. As expected though, a few php classes have been written that’ll handle all the particulars for you. One, available on phpclasses.org, I looked at, and even used within a project, but it didn’t have native support for “defaults” so I decided against using it as an example here (still a cool script if the next one doesn’t float your boat).

The other script is available through TalkPHP, so it’s not really clear who the actual author is (sorry for not giving credit whoever you are). The code is clean, clear and dead easy to implement though.

<?php
include_once('./TalkPHP_Gravatar.php');
$pAvatar = new TalkPHP_Gravatar();
$pAvatar->setEmail('adam@talkphp.com')->setSize(80)->setRatingAsPG()->setDefaultImageAsIdentIcon();
?>
<img src="<?php echo $pAvatar->getAvatar(); ?>" />

Very, very simple. I have to say I’m a fan of Gravatar. I wish more sites implemented Gravatars, instead of having me constantly uploading a different image, but now you can do your part. Get cracking.

Bookmark and Share

Parse Apache Log Files With PHP

Posted in IT, Programming on January 9th, 2010 by Eric Lamb – 1 Comment

Parsing the log files generated by Apache is one of those random tasks with a random occurrence in my world. This is a task that, until recently, hadn’t come up enough to warrant any sort of a ready solution (and it was just fun enough to be ok to write a custom solution). So every time this came up I would always fire up Google and go on a scavenger hunt for a starter script written in php.

Parse Apache Log Files With PHP

Parse Apache Log Files With PHP

This always felt like a good idea at the time the need came up. These days, for some ungodly reason, parsing Apache logs seems to come up a little too frequently to keep this up. In the spirit of making my life a hell of a lot easier for tomorrow I’ve taken a shot at writing an Apache log parser written in PHP.

One thing I decided to implement is a filtering system so you can filter out based on a provided regex. Might not be too useful to everyone but it should be trivial to remove the functionality.

Anyway, I hope someone finds this useful (even to learn from and, of course, use)

Here’s the main class:

<?php
/**
 * Apache Log Parser
 * Parses an Apache log file and runs the strings through filters to find what you're looking for.
 * @author Eric Lamb
 *
 */
class apache_log_parser
{
	/**
	 * The path to the log file
	 * @var string
	 */
	private $file = FALSE;
 
	/**
	 * What filters to apply. Should be in the format of array('KEY_TO_SEARCH' => array('regex' => 'YOUR_REGEX'))
	 * @var array
	 */
	public $filters = FALSE;
 
	/**
	 * Duh.
	 * @param string $file
	 * @return void
	 */
	public function __construct($file)
	{
		if(!is_readable($file))
		{
			return 	FALSE;
		}
 
		$this->file = $file;
	}
 
	/**
	 * Executes the supplied filter to the string
	 * @param $filer
	 * @param $status
	 * @return string
	 */
	private function applyFilters($str)
	{
		if(!$this->filters || !is_array($this->filters))
		{
			return $str;
		}
 
		foreach($this->filters AS $area => $filter)
		{
			if(preg_match($filter['regex'], $str[$area], $matches, PREG_OFFSET_CAPTURE))
			{
				return $str;
			}
		}
	}
 
	/**
	 * Returns an array of all the filtered lines 
	 * @param $limit
	 * @return array
	 */
	public function getData($limit = FALSE)
	{
		$handle = fopen($this->file, 'rb');
		if ($handle) {
			$count = 1;
			$lines = array();
		    while (!feof($handle)) {
		        $buffer = fgets($handle);
		        $data = $this->applyFilters($this->format_line($buffer));
		        if($data)
		        {
		        	$lines[] = $data;
		        }
 
		        if($limit && $count == $limit)
		        {
		        	break;
		        }
		        $count++;
		    }
		    fclose($handle);
		    return $lines;
		}		
	}
 
	/**
	 * Regex to parse the log file line
	 * @param string $line
	 * @return array
	 */
	function format_log_line($line)
	{
		preg_match("/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/", $line, $matches); // pattern to format the line
		return $matches;
	}
 
	/**
	 * Takes the format_log_line array and makes it usable to us stupid humans
	 * @param $line
	 * @return array
	 */
	function format_line($line)
	{
		$logs = $this->format_log_line($line); // format the line
 
		if (isset($logs[0])) // check that it formated OK
		{
			$formated_log = array(); // make an array to store the lin info in
			$formated_log['ip'] = $logs[1];
			$formated_log['identity'] = $logs[2];
			$formated_log['user'] = $logs[2];
			$formated_log['date'] = $logs[4];
			$formated_log['time'] = $logs[5];
			$formated_log['timezone'] = $logs[6];
			$formated_log['method'] = $logs[7];
			$formated_log['path'] = $logs[8];
			$formated_log['protocal'] = $logs[9];
			$formated_log['status'] = $logs[10];
			$formated_log['bytes'] = $logs[11];
			$formated_log['referer'] = $logs[12];
			$formated_log['agent'] = $logs[13];
			return $formated_log; // return the array of info
		}
		else
		{
			$this->badRows++; // if the row is not in the right format add it to the bad rows
			return false;
		}
	}
}
?>

And here’s an example of how to use it:

<?php
$data = new apache_log_parser($d->path.'/'.$entry); // Create an apache log parser
$data->filters = array(
	'path' => array('regex' => '/^.*\.(FLV|flv)$/') //pull only flv files
);
 
$data = $data->getData();
?>

A couple things to note about this script though:

1. The regex and parsing was pretty stolen from the Apache Log Parser on PHPClasses.org.
2. Without filters the script is pretty memory intensive. My needs don’t require anything client facing but heed my adivice; Don’t use this on a public web server.

Bookmark and Share

Get Rid of HTML Templates With HAML

Posted in Code, Programming on January 4th, 2010 by Eric Lamb – 4 Comments

I was working with a new client the last couple weeks where I met a python developer who introduced me to something I hadn’t head of before: HAML. HAML stands for XHTML Abstraction Markup Language and is a markup “language” modeled after, what appears to me to be, YAML. (The syntax and structure is very similar to YAML but I couldn’t find any reference to this being intentional so I could be wrong.)

Get Rid of Templates With HAML

Get Rid of Templates With HAML

Anywho, it looks like HAML was originally created for Ruby on Rails but has been adopted by a few other programming languages and environments like PHP. According to the official site:

Haml is a markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ASP, and ERB, the templating language used in most Ruby on Rails applications. However, Haml avoids the need for explicitly coding HTML into the template, because it itself is a description of the HTML, with some code to generate dynamic content.

So in a nutshell HAML allows for the replacement of the normal, everyday, HTML markup with something a little more “elegant”. The HAML Wikipedia page has a really good example of the differences between HTML and HAML (which I’ve stolen and placed below):

HAML

!!!
%html{ :xmlns => "http://www.w3.org/1999/xhtml", :lang => "en", "xml:lang" => "en"}
  %head
    %title BoBlog
    %meta{"http-equiv" => "Content-Type", :content => "text/html; charset=utf-8"}
    = stylesheet_link_tag 'main'
  %body
    #header
      %h1 BoBlog
      %h2 Bob's Blog
    #content
      - @entries.each do |entry|
        .entry
          %h3.title= entry.title
          %p.date= entry.posted.strftime("%A, %B %d, %Y")
          %p.body= entry.body
    #footer
      %p
        All content copyright © Bob

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
  <head>
    <title>BoBlog</title>
    <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
    <link href="/stylesheets/main.css" media="screen" rel="Stylesheet" type="text/css" />
  </head>
  <body>
    <div id='header'>
      <h1>BoBlog</h1>
      <h2>Bob's Blog</h2>
    </div>
    <div id='content'>
      <div class='entry'>
        <h3 class='title'>Halloween</h3>
        <p class='date'>Tuesday, October 31, 2006</p>
        <p class='body'>
          Happy Halloween, glorious readers! I'm going to a party this evening... I'm very excited.
        </p>
      </div>
      <div class='entry'>
        <h3 class='title'>New Rails Templating Engine</h3>
        <p class='date'>Friday, August 11, 2006</p>
        <p class='body'>
          There's a very cool new Templating Engine out for Ruby on Rails. It's called Haml.
        </p>
      </div>
    </div>
    <div id='footer'>
      <p>
        All content copyright © Bob
      </p>
    </div>
  </body>
</html>

After comparing the two examples above it should be pretty obvious how HAML is structured compared to good old HTML. There’s nothing too crazy going on in the syntax but that doesn’t matter nearly as much as there’s another syntax to learn. Still, if you can get past that HAML is pretty intriguing and worth it to look at.

Now, if you’re a PHP developer you may be saying, “That’s great and all but what the fuck do I care about a Ruby on Rails tool?”. Well, that’s one of the cool parts; there’s a PHP implementation of HAML a PHP class called phpHaml. phpHaml is a PHP class to compile HAML code into static HTML templates, which is useful if you want to jump right in and build a template system.

At it’s most basic a phpHaml script looks like the below:

<?php
require_once './includes/haml/HamlParser.class.php';
$parser = new HamlParser('./tpl', './tmp/haml');
echo $parser->setFile('example2.haml');
?>

Simple. Simple. Simple. Obviously, there are other, more advanced options for working with phpHaml but 3 lines is really all it takes for the learning portion.

My interest in HAML is a little greater than my time allows so I haven’t been able to play too deeply with phpHaml. From my limited time with it though I do feel that the the compiler works as expected on the limited HTML I threw at it and it’s probably worth a deeper look. Oh, yeah, as an added bonus phpHaml also includes a SASS parser (but that’s a whole other post) to play with.

Bookmark and Share

Code Like It’s 1999 With Dolphin CMS

Posted in Brain Dump, Programming, Rant on December 2nd, 2009 by Eric Lamb – 1 Comment

It’s interesting how life can throw you a little too much coincidence. For example, I was having a nice conversation (with a pretty smart dude) where it was mentioned how much more painful development on large projects used to be back in the confused days of early PHP. Then life decided to highlight this little message with a project using Dolphin 6.1 from Boonex.

Coding Like It's 1999 :: Dolphin CMS

Your Soul is the Fish

The work came from a client that had a straight-forward install of Dolphin. She wanted to customize it a bit to make it a little more user friendly; nothing too difficult. Before the project came to me the client had gone the usual route of hiring someone on the cheap who ended up not being up to the task and was, subsequently, left high and dry. This left me with a project that had some of the work started, but not finished, which added to the pain a little but Dolphin sure has it’s own ways of ruining a mood.

In case anyone else has the misfortune of having to work on a Dolphin CMS project I thought I’d highlight just what you’re in for.

The Good

To be fair, for as bad of a nightmare Dolphin CMS is as a project (compared to coding standards in today’s landscape), it does have one or two(ish) redeeming qualities.

For one thing Dolphin CMS has a pretty logical directory structure. Looking for the language file? Why it’s in the “lang” directory of course. Looking for a class? Just check out the “inc/classes” directory. Admittedly, this is a small thing if you’re using a modern IDE but I still appreciate it (so many programs I’ve ran into lately don’t even include this level of logic).

Dolphin CMS also has what can only be called an advanced admin panel. This thing allows you to customize all sorts of areas including the content of pages as well as the layout of the pages. I had a lot of fun playing with that thing. This is double edged though because it serves no practical purpose if you want something unique and cool. For newbies though I think this is a nice feature to learn about the possibilities for a website.

The Bad

Right off, Dolphin CMS is PHP 4 compatible. This is just silly; it’s fucking 2009 already and Dolphin CMS using PHP 4 as a baseline is probably more to blame for the rest of this list than anything else. If you’re going to use old technology why not use old coding standards? In that situation I imagine complacency and laziness would come naturally.

Then there’s the use of short tags in Dolphin CMS. I admit to having a problem myself with maintaining this standard (it’s still natural for me in a template file) but it’s irritating if you have short tags disabled in your ini file.

Another offense: inline HTML and PHP together ALL OVER THE PLACE. You can’t hardly open any file, seriously, any file, without wanting to tear your eyes out of your skull from the cluster fuck in front of you. Add to that the confusion in that the system has a template system (see below) Dolphin CMS just doesn’t use it for the parts you’d actually want to change. Gave me a headache when I would think about it.

As mentioned above there is a template system (of sorts) but it doesn’t actually templatize anything. I guess it’s more of a layout system but considering the majority of templates only had header, footer and content references it’s a poorly utilized one. To make it even worse though Dolphin CMS uses a hard-coded, numerically indexed, naming convention. Want to know what template file you’re file is using? Just open up that file and look for a variable called “$_page['name_index']” and use the value as a reference. Seriously, why would you use a number instead of something meaningful like the name of the file (or similar)?

Back Pedaling

I just got done working with Dolphin CMS so, yes, I’m a little raw. Wah; I know. Still, the fact remains that Dolphin CMS is one of the biggest pains in the ass to work with that I’ve run into in quite some time. It’s not too complicated to work on, it’s structure should be familiar to anyone who’s worked with PHP ten years ago, which is it’s biggest issue. You have to dumb yourself down to work with. And for the love of god don’t try and abstract anything.

The most heinous thing though is that Boonex actually charges for this filth. Real money too. Crap can be excused if it’s free but there’s nothing worse than paying for a box full of horse shit.

Bookmark and Share

Simple Project Profiling With PHPLoc

Posted in Brain Dump, Programming on November 24th, 2009 by Eric Lamb – 1 Comment

One of the most natural things to do while being an obsessive programmer is focusing on the minutia. Not only do our projects have to perform and function to our standards but they also have to be structured “just so” with just the right comment style and just the right indentation to space ratio (4 of course!). Point being that, for me, it’s ridiculously easy to spend time and energy focusing on, what amounts to in the end, as trivial. I was reminded of this while playing around with the latest release of PHPLoc (1.40).

Photo: Grahambones

Photo: Grahambones

PHPLoc is a project by Sebastian Berman that measures the size of a PHP project. In a nutshell PHPLoc is a project analyzer that shows details like amount of classes, files, directories and total Lines Of Code (PHPLoc get it?) to name a few features. It’s ran from the command line and I had no issue getting it to work on Windows (huge plus for quality IMHO).

According to the Git repository:

phploc is a tool for quickly measuring the size of a PHP project.

The goal of phploc is not not to replace more sophisticated tools such as phpcs, pdepend, or phpmd, but rather to provide an alternative to them when you just need to get a quick understanding of a project’s size.

PHPLoc works as a PEAR module (requires PEAR installer version 1.8.1 at least) and as such is really easy to install. There’s some great instructions on the Git site that I had zero issues with (outside of having to update PEAR) so I won’t go into detail here.

Here’s an example of the output when ran against a Zend Framework 1.9 distribution:

C:\php>phploc --count-tests C:\ProjectFiles\ZF
phploc 1.4.0 by Sebastian Bergmann.
 
Directories:                                        393
Files:                                             1856
 
Lines of Code (LOC):                             372292
  Cyclomatic Complexity / Lines of Code:           0.11
Comment Lines of Code (CLOC):                    173793
Non-Comment Lines of Code (NCLOC):               198499
 
Namespaces:                                           0
Interfaces:                                          94
Classes:                                           1758
  Abstract:                                         155 (8.82%)
  Concrete:                                        1603 (91.18%)
  Lines of Code / Number of Classes:                167
Methods:                                          12377
  Scope:
    Non-Static:                                   11517 (93.05%)
    Static:                                         860 (6.95%)
  Visibility:
    Public:                                        9886 (79.87%)
    Non-Public:                                    2491 (20.13%)
  Lines of Code / Number of Methods:                 23
  Cyclomatic Complexity / Number of Methods:       2.78
 
Anonymous Functions:                                  0
Functions:                                            0
 
Constants:                                         3361
  Global constants:                                   1
  Class constants:                                 3360
 
Tests:
  Classes:                                            2
  Methods:                                            0

As you can see, PHPLoc gives some really nice insight into a project. I have to admit I’m more interested in the OCD satisfaction than the practical reasons but it’s still cool. Definitely check it out if you’re looking to get some interesting though completely trivial information about your project.

Bookmark and Share

Thoughts on the Akelos PHP Framework

Posted in Programming on November 9th, 2009 by Eric Lamb – Be the first to comment

I recently took  on a project that was a failure for the original developers. It was the usual story of outsourcing a project and just getting hosed on cost and timeline (my bread and butter). I was asked to take a look and see if I could finish off the project ASAP. Looking under the hood I found that the site was using a framework I hadn’t heard of called Akelos.

Akelos

Akelos

Akelos touts itself as a port of Ruby on Rails (RoR) to PHP but, frankly, I think that’s mostly marketing. Hell, even in the footer disclaimer on the Akelos site they minimize the R0R relationship. Not that that’s a bad thing per se (I wouldn’t want to be associated with RoR at the moment either).

Expecting a clusterfuck of code I was actually a little surprised to find the use of a framework. Granted, the previous developers weren’t using the framework very well, or in any optimal way, but it was still nice to see. Of course that meant I had to learn Another Fucking Framework but what the hell; I like to learn.

According to the site:

The Akelos PHP Framework is a web application development platform based on the MVC (Model View Controller) design pattern. Based on good practices, it allows you to:

  • Write views using Ajax easily
  • Control requests and responses through a controller
  • Manage internationalized applications
  • Communicate models and the database using simple conventions.

Your Akelos based applications can run on most shared hosting service providers since Akelos only requires that PHP be available at the server. This means that the Akelos PHP Framework is the ideal candidate for distributing standalone web applications as it does not require any non-standard PHP configuration to run.

It seems to work similarly to most MVC frameworks, like the Zend Framework, in file structure and hierarchy which definitely eased some of the pain. Unfortunately, I can’t really speak to the Ajax ease of use because, well, like I said above the previous developers were not so much on the… ummm, good side of the coin.

There is a video which is definitely worth checking out; it’ll walk you through the basics of how to use Akelos to generate your project. While there’s a bunch of options for generating your project it does come off a little schizophrenic in that it uses both command line and a web interface depending on what you’re trying to do.

One thing I was impressed with was the localization functionality. Basically, it works like most do, using translate files (read; arrays), which by itself isn’t that impressive, but I really appreciate the way the system uses the browser locale value if one isn’t selected. Nice.

One thing that really didn’t impress me was the absolute NEED for a database connection; NO MATTER WHAT. That’s just confining and comes across to me as lazy and wasteful. Seriously, why would this be a good idea? Does no one care about performance anymore?

It’s unfortunate that Zend Framework and Symfony are the juggernauts they are; I know I wouldn’t want to go against them. It’s got to be tough building a competitive framework with those two being as rad as they are.

All and all Akelos isn’t a bad framework and it does have potential. The Ajax readiness is intriguing and the file structure and hierarchy is intuitive (if you’ve used any other MVC framework )so it was easy to figure things out. There’s also the plugin architecture; I do enjoy me a good plugin architecture.

But I don’t think the relationship to Ruby on Rails is as good a thing as the developers of Akelos think it is. To be honest, I found the similarities between the two jarring due to how uneven the implementation was. Plus, similarities to RoR might have been a good marketing hook 2 years ago, these days it’s just another bullet point. Add to that my personal bias that PHP should function like… you know… PHP.

Point being, I like RoR and if I want to code like RoR I’ll use RoR, not PHP, thankyouverymuch. Add to that my dislike for code generation (and Akelos has a lot of code generation) and I just don’t care anymore.

So for me, Akelos is a fail. Not because Akelos sucks and not because Akelos isn’t good (though it does suck a little and it’s not all that good). More because of design decisions that can’t be helped that disagree with how I like to work.

Zf = 1
Akelos = 0

http://framework.zend.com/
Bookmark and Share

Make Zend_Form Bend To Your Will

Posted in Code, Programming on September 23rd, 2009 by Eric Lamb – 4 Comments

The first thing you need when working with any new web language or framework is figure out how to work with forms. Forms are one of the constants when working online and it’s the rare occasion when you can bypass dealing with them. They are also one of the more rote and boring portions of a web app to build; they’re, pretty much, always the same requiring the same fields on the same pages with the same validation rules and the same database schema.

Make Zend_Form Bend To Your Will

Make Zend_Form Bend To Your Will

If you’re smart dealing with forms effectively becomes a priority. My previously held favorite method was using HTML_QuickForm for handling forms. If you’ve never used; IT IS AWESOME.

Here’s an example login form script:

<?php
/**
 * Include HTML_QuickForm library
 */
require 'HTML/QuickForm.php';
 
/**
 * Include HTML_QuickForm Smarty Renderer
 */
require('HTML/QuickForm/Renderer/ArraySmarty.php');
 
$renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
$form = new HTML_QuickForm('login');
 
$form->addElement('text','Email','Email:' ,'class="textfield" size="30" maxlength="128"');
$form->addRule('Email','Please Enter Your Email','required', null, 'client');
$form->addRule('Email','Please enter a valid email address','email', true, 'client');
 
$form->addElement('password','Password','Password:','class="textfield" size="30" maxlength="128"');
$form->addRule('Password','Please Enter Your Password','required', null, 'client');
$form->addElement('checkbox','remember',null,'Remember Me?');
$form->addElement('submit','save','Submit','class="csubmit"');
 
if ($form->validate()) {
    //do the processing stuff here...
 
}
 
$form->accept($renderer);
$smarty->assign('LoginForm', $renderer->toArray());
?>

Very straightforward I think; instantiate the object, declare the elements, attach the rules and send to smarty (view) object.

The corresponding Smarty template is just as straightforward:

{$LoginForm.javascript}
<form {$LoginForm.attributes}>
{$LoginForm.hidden}
 
{if $LoginForm.Email.error}<span class="errorMessage">{$LoginForm.Email.error}</span><br />{/if}
<div id="email">
	Email: {$LoginForm.Email.html}
</div>
 
<div id="password">
	Password: {$LoginForm.Password.html}
</div>
 
<div id="remember">
	{$LoginForm.remember.html}
</div>
 
 
<div id="submit">
	{$LoginForm.submit.html}
</div>
</form>

That’s my preferred method when layout of the form is important and/or outside the box; it’s totally possible to use HTML_QuickForm without the Smarty integration but I like the control. It allows me to build forms as complicated in layout as the I Am Legend community was (my baseline for form complexity):

Register for I Am Legend Community

Register for I Am Legend Community

Since I’m now using the Zend Framework, and it’s form component is Zend_Form, I can honestly say after the flexibility of HTML_QuickForm and Smarty Zend_Form is, at first, not so awesome. A lot of the resources and tutorials/articles for Zend_Form tout it’s use of the decorator design pattern and all the examples I found looked the same. Not. Good.

Almost none of the references I looked at mentioned anything about removing decorators and rendering just the raw form elements like I needed. It is possible though; you just have to attache a couple extra methods to remove the decorators as laid out below. Make note of the calls to “removeDecorator” and “setAttrib”. Those are the key pieces.

As a counter point here’s the above script using Zend_Form:

<?php
//APPLICATION_PATH/forms/Login.php
<?php
 
class Form_Login extends Zend_Form
{
	public function __construct($options = null)
	{
		parent::__construct($options);
 
		$email = new Zend_Form_Element_Text('email');
		$email->setLabel('Email')
				->setRequired(true)
				->addFilter('StripTags')
				->addFilter('StringTrim')
				->addValidator('NotEmpty', TRUE)
				->addValidator(new Zend_Validate_Db_RecordExists('users', 'email'))
				->removeDecorator('label')
				->removeDecorator('htmlTag')
				->removeDecorator('description')
				->setAttrib('class', 'transperentInput');
 
		$password = new Zend_Form_Element_Password('password');
		$password->setLabel('Password')
				->setRequired(true)
				->addFilter('StripTags')
				->addFilter('StringTrim')
				->addValidator('NotEmpty')
				->removeDecorator('label')
				->removeDecorator('htmlTag')
				->removeDecorator('description')
				->setAttrib('class', 'transperentInput');
 
		$submit = new Zend_Form_Element_Submit('submit');		
		$this->addElements(array($email, $password, $submit));
    }
}
?>

Since Zend_Form is a part of the Zend Framework MVC the above is just the form class and the below is the actual processing portion:

<?php
//APPLICATION_PATH/controllers/Login.php
class LoginController extends Zend_Controller_Action
{
	public function indexAction()
	{
		$form = new Form_Login;
		if ($this->getRequest()->isPost()) {
 
			$formData = $this->getRequest()->getPost();
			if ($form->isValid($formData)) {
                            //do the processing stuff here...
 
			}
 
		}
 
		$this->view->form = $form;
	}
}
?>

Sigh…
And then in the view script:

<form action="<?php echo $this->escape($this->form->getAction()); ?>" 
method="<?php echo $this->escape($this->form->getMethod()) ?>" 
id="sumbitForm">
<div id="email">
	Email: <?=$this->form->email; ?>
</div>
 
<div id="password">
	Password: <?=$this->form->password; ?>
</div>
 
<div id="remember">
	<?=$this->form->remember; ?>
</div>
 
 
<div id="submit">
	<?=$this->form->submit; ?>
</div>
</form>

There you go: Zend_Form is your bitch.

Bookmark and Share

pChart – a PHP class to build charts

Posted in Code, Programming on September 11th, 2009 by Eric Lamb – 2 Comments

In my never ending quest to find a replacement for JpGraph  I’ve covered charts built using JavaScript with the Google Visualization API and charts done with SWFs using Open Flash Charts (OFS). If you’re building web apps it’s easy to just stop there and consider yourself covered. I certainly thought so; until my conscience spoke up that is.

pChart

pChart

The thought them comes creaping into my head, “Um… What about the JavaScript? How do you think those pretty charts and graphs will degrade?”.

Shit.

Not to take anything away from either of those programs; they’re very fun to work with and, relatively, easy to use. It’s just that they’re both rendered using JavaScript which is well and good provided your user has JavaScript enabled (and Flash too for OFS). It’d be a nice addition to provide an alternative when using either one of the previous programs.

This is where pChart comes in:

pChart is a PHP class oriented framework designed to create aliased charts. Most of todays chart libraries have a cost, our project is intended to be free. Data can be retrieved from SQL queries, CSV files, or manually provided. This project is still under development and new features or fix are made every week.

Focus has been put on rendering quality introducing an aliasing algorithm to draw eye candy graphics. Rendering speed has been dramatically enhanced since the first version, we’ll still continue optimising the code!

Implementation is pretty easy too:

// Standard inclusions
include("pChart/pData.class");
include("pChart/pChart.class");
 
// Dataset definition
$DataSet = new pData;
$DataSet-&gt;AddPoint(array(1,4,3,2,3,3,2,1,0,7,4,3,2,3,3,5,1,0,7));
$DataSet-&gt;AddSerie();
$DataSet-&gt;SetSerieName("Sample data","Serie1");
 
// Initialise the graph
$Test = new pChart(700,230);
$Test-&gt;setFontProperties("Fonts/tahoma.ttf",10);
$Test-&gt;setGraphArea(40,30,680,200);
$Test-&gt;drawGraphArea(252,252,252);
$Test-&gt;drawScale($DataSet-&gt;GetData(),$DataSet-&gt;GetDataDescription(),SCALE_NORMAL,150,150,150,TRUE,0,2);
$Test-&gt;drawGrid(4,TRUE,230,230,230,255);
 
// Draw the line graph
$Test-&gt;drawLineGraph($DataSet-&gt;GetData(),$DataSet-&gt;GetDataDescription());
$Test-&gt;drawPlotGraph($DataSet-&gt;GetData(),$DataSet-&gt;GetDataDescription(),3,2,255,255,255);
 
// Finish the graph
$Test-&gt;setFontProperties("Fonts/tahoma.ttf",8);
$Test-&gt;drawLegend(45,35,$DataSet-&gt;GetDataDescription(),255,255,255);
$Test-&gt;setFontProperties("Fonts/tahoma.ttf",10);
$Test-&gt;drawTitle(60,22,"My pretty graph",50,50,50,585);
$Test-&gt;Render("Naked.png");
?&gt;

The above code produces something similar to:

pChart Linechart Example

pChart Linechart Example

One really cool addition the developers added was a little cmd script, buildAll.cmd, to automate the build of all the Example scripts on Windows machines. Just double click that and you’ll have all the graph images generated automatically.

It is recommended by the developers that caching is implemented but I haven’t really found the need for it yet.

A good idea, and one I’m going to be implementing, is to use charts and graphs created with OFC and create static image graphs for the noscript tags using pChart. Definitely a lot of work but it’ll add a bit of shiny to my programs. Yours too I think.

Bookmark and Share

Keeping an Eye on Your Development

Posted in Code, Programming on September 7th, 2009 by Eric Lamb – Be the first to comment

Oh, var_dump()… Poor, pathetic, little vardump()… There was a time when you were my favorite little go-to for debugging. Once upon a time, you were the end all be all of problem solving tools; this would be during my idiot phase of life. Not anymore though; thanks to some god (or whatever) someone smarter than me (and apparently with more time on their hands) went and invented the Debug Toolbar.

Keeping an Eye on Your Development

Keeping an Eye on Your Development

In case you didn’t know, a Debug Toolbar (I don’t know if that’s the universal name for it but it makes sense to me) is a nifty little widget that allows for easy access to all sorts of info on your web program. Since I work primarily in php that’s what I’m going focus on; I’m sure they’re available in other languages. Like most things; Google is your friend on this.

Usually, a Debug Toolbar contains information on included files, any sessions and cookies available, the database calls with timers and a breakdown of memory usage and performance.

Debug Toolbars usually work by encapsulating different code blocks or functions around “timer” functions to record the time it took for a block to run. All the Debug Toolbars I’ve used also included a memory component; really helps to see where the spikes are. There’s also the database integration; it’s just good sense to know where the bottlenecks are in a project.

As I said in the intro var_dump() is a handy little tool for debugging issues in php scripts. It works pretty well for small scripts but, the thing is, on larger projects it just becomes unpractical. Not only is it limited to arrays and objects but you have to manually place the call in the code and depending on the issue, you can get a HUGE amount of data back in a horrible tangle of strings. Makes XML look good.

Instead, using a Debug Toolbar, you get a nicely formatted unobtrusive way to keep an eye on how your code is performing while creating it. Needless to say, these are handy little tools.

PHP_Debug

A little disclosure: My first experience with a debug toolbar was with a really early, think pre alpha, version of PHP_Debug. PHP_Debug, at that time, worked by displaying the debug information at the bottom of a page in a table. This was definitely a step up from using var_dump(), to be sure, but it was still a little painful to decipher. Clients would complain.

Then PHP_Debug pretty much innovated the Microsoft way and copied a feature from another application; Symfony. (I kid, I kid.)

Seriously though, PHP_Debug does claim inspiration from the Symfony which I think is pretty classy of them; it seems too many times credit goes unsaid.

Keep in mind, this was the first time I saw anything like a debug toolbar. I don’t want to break down to hyperbole but to say the sky parted and angels sang would be a fucking understatement.

PHP_Debug Toolbar

PHP_Debug Toolbar

PHP_Debug is perfect for those stand alone projects that are started from scratch. It’s not impossible to integrate PHP_Debug into an existing program, I’ve done it a few times, but unless you’ve abstracted out a good deal of the logic it’s going to be a little painful. Put aside a few hours if you’re going to attempt it.

The script displays the output in 2 different ways; through a floating div at the top of a page or as an HTML table displayed at the bottom of the page. Installation is pretty easy and straightforward, either as a PEAR module or as a stand alone script.

ZFDebug

ZFDebug is a plugin for the Zend Framework that acts pretty much like PHP_Debug except with a simple and easy integration into the Zend Framework and it’s quite a bit slicker. Smooth animations, version details, sticky states and full of detail. If you use the Zend Framework I can’t recommend it highly enough.

ZFDebug

ZFDebug

There are some installation instructions which at the time of this writing are just broken though. Follow the linked instructions but use the below code in place of the code provided in the instructions:

protected function _initZFDebug()
{
    $autoloader = Zend_Loader_Autoloader::getInstance();
    $autoloader->registerNamespace('ZFDebug');
 
    $options = array(
        'plugins' => array('Variables', 
                           'File' => array('base_path' => '/path/to/project/'),
                           'Memory', 
                           'Time', 
                           'Registry', 
                           'Exception')
    );
 
    # Instantiate the database adapter and setup the plugin.
    # Alternatively just add the plugin like above and rely on the autodiscovery feature.
    if ($this->hasPluginResource('db')) {
        $this->bootstrap('db');
        $db = $this->getPluginResource('db')->getDbAdapter();
        $options['plugins']['Database']['adapter'] = $db;
    }
 
    # Setup the cache plugin
    if ($this->hasPluginResource('cache')) {
        $this->bootstrap('cache');
        $cache = $this->getPluginResource('cache')->getDbAdapter();
        $options['plugins']['Cache']['backend'] = $cache->getBackend();
    }
 
    $debug = new ZFDebug_Controller_Plugin_Debug($options);
 
    $this->bootstrap('frontController');
    $frontController = $this->getResource('frontController');
    $frontController->registerPlugin($debug);
}

Using ZFDebug is as simple as that. Once installed you’ll have a div laying at the bottom of the page with all the details you could want. Plus, it comes preinstalled with the hooks for database and cache profiling. It’s still possible to manually insert timing blocks but the hard part is already done for you.

Symfony

If you’re using Symfony you’re in luck (and none of this is probably news to you); Symfony comes with a Debug Toolbar (the original maybe?) preinstalled and read to use. All you have to do is either hit up frontend_dev.php in a browser or change:

$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'prod', false);

to

$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'dev', false);

in your bootstrap file.

Symfony Debug Toolbar

Symfony Debug Toolbar

It’s not as robust as PHP_Debug or ZFDebug out of the box (oddly, there’s no included file reference) but it does allow for customization so it has the potential to be very informative and useful.

One last thing about Web Debug Toolbars; they aren’t a replacement for good practices. You can’t rely on them too much and sometimes your instinct will contradict the output of the toolbar. In my experience you should trust that instinct. A Web Debug Toolbar should only be used to provide insight not replace common sense.

One thing to keep in mind is to not focus too much on the

Bookmark and Share