Tuesday, February 17, 2009

PHP Input Cleaning

I've been buried in my be-all, end-all, does-everything CMS / e-commerce site.
I thought I'd come up for err (or air) and here's what happened.

Below is an object which does lazy input cleaning of GET and POST data.

You use it by creating a new object [surprise].

You access cleaned data as attributes of an object instance.

All the cleaned data is cached in a class variable, so you can either pass around
a global or create a bunch of instances and everything will work - within the same
instance of the PHP program, of course. Once the Object
is required, it acts kind of like a Singleton Pattern.

You can restrict the query sources to GET, POST or REQUEST and control how it
reacts to undefined query parameters.

The documentation is in a comment at the top in Textile.

In some ways, I think this is kind of neat, but on the other hand it's
really depressing how much effort goes into something with such a simple
objective. Seems like there should be an easier way.

Cheers,


<?php
/*
#doc-start
h1. RequestCleaner

Created by on 2009-02-14.
Copyright (c) 2009 Clove Technologies, Inc. All rights reserved.

h3. Usage

Create a new request cleaner:

$rc = new RequestCleaner(sources, use_modes, error_mode) - where:

* sources is a comma separated string OR an array with one or more of: GET, POST, REQUEST
* use_modes is the bitwise OR of
** RequestCleaner::USE_HTMLENTITIES - process each parameter with _htmlentities()_
** RequestCleaner::USE_HTMLSPECIALCHARS - process each parameter with _htmlspecialchars()_
** RequestCleaner::USE_NL2BR - process each parameter with _nl2br()_
* error_mode - determines how the beast responds to errors - such as non-existing query parameters.
Use one of:
** RequestCleaner::RETURN_NULL - returns NULL
** RequestCleaner::RETURN_FALSE - returns FALSE - can be distinguished from NULL by '===' and '!=='
** RequestCleaner::THROW_EXCEPTION - throws an exception

For example:

$rc = new RequestCleaner('POST', RequestCleaner::USE_HTMLENTITIES | RequestCleaner::USE_NL2BR,
RequestCleaner::THROW_EXCEPTION);


To get a 'cleaned' query parameter, use '$rc->parm', where _parm_ is the parameter name.
For example, if 'foo' is a POST parameter, then '$rc->foo' will return the value of 'foo'
from after running the 'cleaning' routines on it.

h3. Fine points

All Cleaned data is cached in a RequestCleaner Class Variable, as are the sources, use and error
modes. This means that a top level PHP program can set up the method of cleaning and
allowed sources and all included code which uses _any_ instance of a RequestCleaner
will use the same methods and cache.

Consequently, you can either create a RequestCleaner instance at top level OR in any included or
required file which needs to access query parameters. It doesn't matter.

Attempts to access undefined attributes generate an error - as specified by _error_mode_.

Query parameters which return arrays - as in <input type=... name="foo[]" ...> -
are turned into arrays of cleaned strings which can be processed using normal loops
and array_...() functions

#end-doc
*/

/**
* RequestCleaner(sources = NULL) - where sources defines a comma separated list of Super Globals
* for attribute values. Legal names are: POST, GET, and REQUEST
*/
class RequestCleaner
{
const ERROR_MODE_MASK = 3;
const RETURN_NULL = 1;
const RETURN_FALSE = 2;
const THROW_EXCEPTION = 3;
const NORMAL = RequestCleaner::RETURN_NULL;

const CLEANER_MODE_MASK = 0x07; // IMPORTANT: Change This as you ADD USE_modes
const USE_HTMLENTITIES = 1;
const USE_HTMLSPECIALCHARS = 2;
const USE_NL2BR = 4;
private static $use_modes = array(
RequestCleaner::USE_HTMLENTITIES => 'htmlentities()',
RequestCleaner::USE_HTMLSPECIALCHARS => 'htmlspecialchars()',
RequestCleaner::USE_NL2BR => 'nl2br()',
);
private static $error_modes = array(
RequestCleaner::RETURN_NULL => 'return NULL',
RequestCleaner::RETURN_FALSE => 'return FALSE',
RequestCleaner::THROW_EXCEPTION => 'throw Exception'
);
private static $sources = NULL;
private static $source_names = array();
private static $error_mode = NULL;
private static $use_mode = NULL;
private static $cache = array();
function __construct($sources = array('GET', 'POST'), $use_mode = RequestCleaner::USE_HTMLENTITIES,
$error_mode = RequestCleaner::RETURN_NULL)
{
if (!RequestCleaner::$sources) {
if ($sources) {
RequestCleaner::$sources = array();
if (is_string($sources)) {
$sources = preg_split("/,\s*/", trim($sources));
}
foreach ($sources as $src) {
RequestCleaner::$source_names[] = $src;
switch ($src) {
case 'POST':
RequestCleaner::$sources[] = $_POST;
break;
case 'GET':
RequestCleaner::$sources[] = $_GET;
break;
case 'REQUEST':
RequestCleaner::$sources[] = $_REQUEST;
break;
default:
throw new Exception("RequestCleaner::__construct($sources): Illegal Source: $tmp");
}
}
} else {
RequestCleaner::$sources = array($_POST, $_GET);
}
if (RequestCleaner::CLEANER_MODE_MASK & $use_mode) {
RequestCleaner::$use_mode = RequestCleaner::CLEANER_MODE_MASK & $use_mode;
}
if (RequestCleaner::ERROR_MODE_MASK & $error_mode) {
RequestCleaner::$error_mode = RequestCleaner::ERROR_MODE_MASK & $error_mode;
}
}
}

private function stringCleaner($x)
{
if (RequestCleaner::$use_mode & RequestCleaner::USE_HTMLSPECIALCHARS) {
$x = htmlspecialchars($x);
}
if (RequestCleaner::$use_mode & RequestCleaner::USE_HTMLENTITIES) {
$x = htmlentities($x);
}
if (RequestCleaner::$use_mode & RequestCleaner::USE_NL2BR) {
$x = nl2br($x);
}
return $x;
} // end of arrayHelper()

private function useModesToString()
{
$ar = array();
foreach (array(RequestCleaner::USE_HTMLENTITIES, RequestCleaner::USE_NL2BR,
RequestCleaner::USE_HTMLSPECIALCHARS) as $mode) {
if (RequestCleaner::$use_mode & $mode) {
$ar[] = RequestCleaner::$use_modes[$mode];
}
}
return implode(',', $ar);
} // end of useModeToString()

public function __toString()
{
return "RequestCleaner: examining " . implode(', ', RequestCleaner::$source_names)
. " Using " . $this->useModesToString()
. " / Exit Mode: " . RequestCleaner::$error_modes[RequestCleaner::$error_mode];
} // end of __toString()

public function __get($name)
{
if (array_key_exists($name, RequestCleaner::$cache)) {
return RequestCleaner::$cache[$name];
}
foreach (RequestCleaner::$sources as $source) {
if (array_key_exists($name, $source)) {
$val = $source[$name];
if (is_string($val)) {
return (RequestCleaner::$cache[$name] = RequestCleaner::stringCleaner($val));
} elseif (is_array($val)) {
return (RequestCleaner::$cache[$name] = array_map(array('RequestCleaner', 'stringCleaner'), $val));
}
}
}
switch (RequestCleaner::$error_mode) {
case RequestCleaner::NORMAL: return NULL;
case RequestCleaner::RETURN_FALSE: return FALSE;
case RequestCleaner::THROW_EXCEPTION:
throw new Exception("RequestCleaner::__get($name): Value Not Defined");
default:
throw new Exception("RequestCleaner::__get($name): ERROR: Value Not Defined / Illegal Error Mode");
}
return NULL;
} // end of __get()

public function __set($name, $value)
{
switch (RequestCleaner::$error_mode) {
case RequestCleaner::NORMAL: return NULL;
case RequestCleaner::RETURN_FALSE: return FALSE;
case RequestCleaner::THROW_EXCEPTION:
throw new Exception("RequestCleaner::__set($name, $value): Setting Attributes Not Allowed");
default:
throw new Exception("RequestCleaner::__set($name, $value): Setting Attributes Not Allowed / Illegal Error Mode");
}
} // end of __set()

public function __unset($name)
{
switch (RequestCleaner::$error_mode) {
case RequestCleaner::NORMAL: return NULL;
case RequestCleaner::RETURN_FALSE: return FALSE;
case RequestCleaner::THROW_EXCEPTION:
throw new Exception("RequestCleaner::__unset($name): Unsetting Attributes Not Allowed");
default:
throw new Exception("RequestCleaner::__unset($name): Unsetting Attributes Not Allowed / Illegal Error Mode");
}
} // end of __set()

public function __isset($name)
{
if (array_key_exists($name, RequestCleaner::$cache)) {
return TRUE;
}
foreach (RequestCleaner::$sources as $source) {
if (array_key_exists($name, $source)) {
return TRUE;
}
}
return FALSE;
} // end of __isset()
}

// end class definitions

?>


Why did I post this dramatic exposition of Programming Prowess?

No particular reason, just felt like it.

Sunday, August 31, 2008

Why I hate Idea Men

Ever shoot a rifle and miss the target? Well, if you haven't here's how you miss: you're aim is off by just a little bit.

The same thing happens when you're building software - or anything, for that matter.

I've spent about 40 years building systems of various kinds - mostly software implementations to 'solve' some problem. The process is pretty straightforward and goes like this:

1. Try to figure out what you're going to do.
2. Pick the most important parts and the most important actions and interactions between the parts.
3. Pretend that is all there is in the world and build some software which mimics everything you've thought of. By the way, these parts, actions and interactions are the 'model'.
4. Test it until it works well enough to do the job.
5. Knowing what you now know, go back to step 1 and do it all over again.
6. Repeat step 5.
7. Repeat step 6.

You get the idea.

Nobody is ever right the first, second, third, or even the 'last' time.

Models aren't reality - we just work on them until they are 'close enough'.

What's this got to do with Idea Men?

Idea Men do parts 1 and 2, then they get somebody else to do step 3.

Then they blame the guys who built the thing in step 3 because they don't want to do step 4.

Finally, they won't do step 5 because they're 'right' and the guys who built it are all incompetent and that's the reason it doesn't work like they said it would.

Then the Idea Men get promotions and raises.

Crap

Tuesday, July 1, 2008

Singleton Patterns in PHP 5

The Singleton Pattern is one of the few things I really like from Design Patterns. While the original Gang of Four book has some very good stuff in it, later works seem like Software Industry Marketing Fluff [SIMF] - but I've already bitched about that.

The Singleton is GREAT because it can replace Global Variables - if not everywhere, at least in a lot of important cases.

In case you don't know what a Singleton is, it's an Object which has only one instance. Ideally, you would like to write something like
$foo = new Thing();
and get a reference to the one instance of Thing.

The "normal" way to implement the Singleton Pattern is to hack up the class definition in an unnatural way:
  • Disable the normal constructor by making it private
  • Define a class variable to hold the One Instance
  • Create a different public function which is used to instantiate the first instance and return it on all subsequent 'instantiations'
This is because none of the Object Oriented Languages directly support Singleton - except Ruby which has a Singleton base class so you can create them by normal inheritance.

I was so taken with Ruby's Singleton base class, I decided to write one in PHP 5.

Drum Roll........

Didn't work. Failed Miserably.

It turns out that in PHP 5.2 static class variables [that is, Class Variables] are always in the base class. I won't go into that here. Instead, take a look at this test I wrote.

Anyway, just because we can't build a base class for Singleton Objects, doesn't mean we can't clean up their creation. Here is an example of a pseudo-Singleton which allows me to write
$foo = new Thing();

and have a $foo object which acts just like a Singleton even though it has many instances.

The reason this works is that we don't need a single instance of the Object. What we need is a reference which returns the common data, where the methods act on the common data, where modification of the common data is seen by all existing references.

The Pseudo-Singleton looks, acts, and smells like a Singleton, except it is more convenient and natural to use.

The only thing better would be a 'singleton' keyword prefix to use in 'class' definitions.

Saturday, June 21, 2008

Reality and Stuff Like That

Believe it or not, I spend far too much time thinking about what is real and what isn't.

It seems a lot of people seem to think that there are lots of realities and lots of equally valid versions of Truth. This seems like fuzzy thinking to me. So fuzzy that it just doesn't make any sense. [where are you going to put all these versions of Truth - if there isn't a universal Truth which contains them all?]

Anyway, here's what I've come up with: (nothing original here - much stolen from Lao Tzu's work)

The first thing to be clear about is 'how do we think'. 'Cause if we understand that, then we can understand what we think is 'real'.

As nearly as I can tell, we start out by classifying stuff as 'this' and 'everything else'. Some people call this 'dualistic thinking', but my opinion is that it's simply a way to simplify the cacophony of sensory input we are inundated with. It also lets us find 'patterns' so we can form 'habits' to simplify plodding though daily life.

Anyway, when you add some properties to these 'classifications', you get a 'model'. It's a model because the 'thing' has behaviors associated with it. Like a window lets in light and a tea pot holds tea.

The BIG CATCH is when we confuse the 'model's we construct with the real world we live in. The 'model' world is really an illusion we've created - but which we treat as real.

What is 'reality'? That's tough because we're so used to classifying, finding patterns, and creating models that we aren't equipped to perceive - let alone process - what's actually out there.

Anyway - that's what I think is going on. It also answers the quest of why we argue so much:
we're all living in different illusions - not different realities - and our illusions are only loosely based on 'reality'.
There are a lot of conclusions you can draw from this - but this is plenty for now.

Wednesday, April 23, 2008

ORM's or not?

In my quest for a CMS I can not only stand but want to embrace, I've spent the last couple of weeks messing with Drupal.

Drupal is impressive - at the very least in scope and participation. I like quite a bit of it. In contrast with Rails, Drupal releases seem to be Designed rather than Grown - which is a very strong plus. [I'm not sure I can stand it, but that's another story.]

But I'm not writing to Praise Drupal, but to make an observation about Object Relational data Mappers.

Drupal through 6 doesn't have an ORM. They have two 'database adapters' and opt to use SQL. Most of the SQL used for CRUD operations is standard, so that works just fine. I'm told there is discussion in the development forums about stuffing a layer of abstraction in the database code - which I read as 'create an ORM.'

Looking over the landscape littered with the corpses of ORMs in almost every conceivable (computer) language, should give pause - at least it does to me.

Why do we ORM?

Well, we have to have the data tables in the Database match up with the Attributes in the Objects, don't we?

Well, No we don't.

There's no reason for the Data Tables to model our 'business process'. That's a knee jerk reaction taught as gospel in C.S. courses.

Couple of Facts:
  • Databases are really good at holding, retrieving, searching, and sorting vast quantities of data. Programming Languages aren't.
  • Programming Languages are really good manipulating, displaying, inputing, validating, mashing, spindling, and folding data. Databases aren't.
Now for a Web Site, much of the content doesn't have a long life, is retrieved by simple, well known searches, ordered by well known sorts, and is displayed in small chunks.

It seems to me that there much of the data used in a web site could be modeled exclusively in the Programming Language and then serialized in XML or JSON for storage in the database. That separates the representation of the data in the application from the representation in long term storage and obviates the need for an ORM.

I like that idea so much, I'm building one now just to see how it works in practice.

Stay Tuned

Friday, March 28, 2008

DRY versus WET

You've got to have either a Snappy Acronym or Fancy Vague Phrase (FVP) in order be credible. So when I decided to write about what I think is wrong with DRY, I came up with 'DRY versus WET' - but I didn't know what WET meant.

DRY - Don't Repeat Yourself - is one of the Mantras of the Current Age of Programming Wisdom.

In case you don't know what a mantra is, it's a sound or phrase which you repeat over and over again while meditating. Meditating is something you do with your mind which brings peace and quiet . . . by avoiding all thought.

The problem I have with DRY is that you have to Think in order to write Good Code. In other words, you need Well Examined Thought - that's where WET comes from. [So now I've got an Acronym that Actually Means Something].

For Example:

Take a look at the Rails source code to see what over-DRY-ness does. After a while you'll see that (almost) every piece of code which could be repeated is turned into a method call. Even stuff which isn't more than a fraction of a line! This is Really DRY - so It Must Be Good. Right? Wrong!

This is Spaghetti [see The New Spaghetti for more ranting . . I mean 'detail'].

Historical Note: Spaghetti code originally referred to the overuse of GOTO (or branch) statements in FORTRAN or Assembler programs, but any program which has a high ratio of Control Transfer statements to Useful Work is really Spaghetti - because it reads like all the code was written on the sides of noodles and then all mixed up.

So . . . Don't DRY up. Get WET!


Think it's worth doing a book about?

Thursday, March 13, 2008

The New Spaghetti

Back before Structured Programming - which everyone now thinks is as natural as breathing - we had a thing called 'Spaghetti Code'.

You wrote Spaghetti Style by using lots of conditional and unconditional GO TO statements to re-use every bit of code you'd written. It was the privative precursor of DRY [Don't Repeat Yourself].

In those days it kind of made sense - for a couple of reasons:

1. we didn't know any better

2. memory was tiny - we measured big machines in KiloBytes and wrote programs using 'overlays' [in case you don't know, an overlay is a chunk of executable code which 'overlays' another chunk in memory. We used to do that because (a) we didn't have enough memory to do the job and (b) there wasn't any automatic memory management]

The result of Spaghetti Style is that nobody could ever figure out how the programs worked and modifying them was next to impossible.

What brought this up?

I've been trying to 'learn Rails' - which is a pretty large Ruby application. Rails has close to 10,000 methods defined, about 1,500 classes, and God only knows what else. The Vocabulary is huge - and so it's a daunting task to say the least.

On top of the huge vocabulary, there it's DRY.

That seems to mean that every chunk of code which is used two or more times is ripped out and turned into a method. The result is that in order to do anything, somewhere near one and a half gazillion methods are called. In order to figure out how almost anything works you have to work through a call stack which is makes the old FORTRAN Spaghetti look like a 2nd grader's maze.

Why is this happening?

I'm guessing, but I think there are three factors driving this result:

1. DRY - This is a misunderstanding. DRY is a hip way of saying 'we want to maintain a single point of control so that we don't have to repeat bug fixes in the code'. DRY shouldn't be a mantra, because it's not a Principal of Good Programming. It's a method to implement an idea which is good programming.

Prior to formulating 'Single Point of Control' as DRY, programmers used some judgement in the size of the methods/functions they wrote. Typical size was 5 to 25 lines or so - enough to do useful work and small enough to be easily understood. Rubyists seem to be addicted to one-line methods which call other methods which call other methods which ... - but they don't Repeat!

2. Agile Development - This seems to go hand in hand with Test Driven Development. Both sound like good ideas, and they seem to work well for 'throw away' applications - which is what most web sites are. After crawling through the Rails Association Code, I've come to the conclusion something critical has been lost in the Agile-ness of the Development: There's no Design Phase.

Test Driven Development has proven you don't have to have an overall plan to build code which works. You can build any twisted mess and if you continuously test, it will pass the test.

But it won't make sense, won't be cohesive, will probably be inefficient, and it will be hell to modify or learn.

Everything has to be designed it is going to work well and be maintainable. That's true for Buildings, Cars, Motorcycles, Bridges, and, believe it or not, Software.

3. Ruby itself.

I love Ruby - almost - because it's a beautiful language and it makes it easy to otherwise hard things. The fact that Ruby is a scripting language means we get instantaneous feedback - and I love that too.

But both of those things - along with Ruby's openness which allows all kinds of self-modifying code [which seems to be confused with meta-programming] makes it easy to get the illusion of 'doing something' when the programmer is actually just churning different implementations with little impact on improving the goals of the application being developed.

Does that make sense? If not, read it again.

Activity != Progress

It takes discipline and experience to handle as powerful a tool as Ruby is without creating a mess.

Don't believe me?

Just take a look at the source for Mongrel and compare [or rather Contrast it] with a bunch of the Rails code. Zed Shaw writes awesome, easily understood code. Somebody in the Rails Core doesn't.