Blog

Blesta 3.0: Data Validation

August 29, 2011 | Posted by Cody


Blesta 3 offers a huge collection of programming tools for developers. From encryption to session handling, and everything in between. Today we’ll focus on the ins and outs of input validation using the Input component packaged with minPHP.

Input validation in version 3 is clear, concise, and modular. Rules reside within the business logic (the model). The benefit of this design is three fold:

  1. No (or at least reduced) redundancy
  2. Increased readability/writability
  3. Reduced testing/less bugs

Some may argue the benefits of input validation from the first source (i.e. the controller). The folly of this design is its complexity and redundancy. Suppose a client can sign up through an order form, through a signup form, or be created by a staff member. Now you have three locations to test, update, and debug each time a business rule changes (for example, phone number is now required). Now suppose you need clients to be created through an API. Adding a fourth set of rules is just plain silly. A client is a client, regardless of where they originate, so why not consolidate all of this?

“Well, Cody,” you might say, “a phone number is only required when a client places an order so we need separate rules.” Hogwash! Add a parameter to your Clients::add() method to identify a signup via order to set the phone number rule as required.

Let’s look at a few examples.

<?php 
// /app/models/clients.php
class Clients extends AppModel {
    public function __construct() {
        Loader::loadComponents($this, array("Input"));
    }
 
    public function add(array $input) {
        // Input is coming straight from POST
        $rules = array(
            'first_name' =--> array(
                'empty' => array(
                    'rule' => "isEmpty",
                    'negate' => true,
                    'message' => $this->_("Clients.!error.first_name.empty"),
                    'post_format' => "trim"
                )
            ),
            'last_name' => array(
                'empty' => array(
                    'rule' => "isEmpty",
                    'negate' => true,
                    'message' => $this->_("Clients.!error.last_name.empty"),
                    'post_format' => "trim"
                )
            ),
            'email' => array(
                'format' => array(
                    'rule' => "isEmail",
                    'message' => $this->_("Client.!error.email.format"),
                    'post_format' => "trim"
                )
            )
        );
 
        $this->Input->setRules($rules);
        if ($this->Input->validates($input)) {
            // Insert into the database, email, or do anything else needed when a client is added
        }
    }
}
?>

Let’s break this down.

  1. Line 5 loads the Input component (in reality this is already done in AppModel, but you ought to know how it happens)
  2. Lines 10 – 34 define our rules. For those who’ve worked with cakePHP this will look somewhat familiar.
  3. Lines 11, 19, and 27 are the indexes of the input data from our input array parameter. Evaluating arrays would look something like ‘addresses[]’, or ‘addresses[][city]‘, etc.
  4. Lines 12, 20, and 28 begin individual rule sets. The labels here are superfluous (we could use numerically indexed elements instead), but these help us understand what’s expected of the rule. Any number of rule sets can be added.
  5. Each rule contains two necessary components:
    1. The ‘rule’ index, and
    2. The ‘message’ index
  6. The first defines how the input is evaluated. If the rule returns true the validation passes, if false, the validation fails. The message is what’s set for the error upon failure. In this example, and throughout Blesta, messages are language definitions which are translated before being set ($this->() maps to [Language::()]3).
  7. Lines 14 and 22 tell the “isEmpty” rule to negate the response. Obviously we don’t want to require first and last names to be empty. Instead we want to ensure non-emptiness.
  8. Lines 16, 24, and 31 perform a formatting action on data after the rule is evaluated. Conversely, there’s a ‘pre_format’ action that formats the data before the rule is evaluated. Both ‘pre_action’ and ‘post_action’ work just like ‘rule’.
  9. Line 36 prepares the rules for evaluation
  10. Line 37 runs the validation, setting any errors that are encountered into the Input object, accessed via Input::errors(). AppModel defines a public method called “errors” to grant access to these errors from our controllers. As you’ve probably deduced, Input::validates() returns boolean true if validation was a success and false otherwise.

In the above example, all of the rules are defined within the Input component, but rules can consist of PHP functions (as seen on line 16), callbacks, or even boolean values. In addition, a rule can also define parameters. In any case, however, the first parameter to the rule is always the input value.

Below we look at an example of a rule set where the phone number is conditionally dependent on a method parameter, with a more complex rule.

<?php
    if ($order_signup) {
        $rules['phone'] = array(
            'format' => array(
                'rule' => array(array($this, "isPhone"), $input['country']),
                'if_set' => true,
                'message' => $this->_("Client.!error.phone.format"),
                'final' => true
            )
        );
    }
?>

Notice we now have a couple new actions. The ‘if_set’ action allows the rule to be executed if and only if the field is set. The ‘final’ action tells us that if this rule does not pass evaluation then there’s no point in evaluating any other rules. Similarly, there’s another action called ‘last’ that will cease evaluating rules within a particular rule set (that is, for a single field).

Our rule is to execute a public class method and pass an additional parameter which will help us determine the correct format for the phone number based on the country. The signature of Clients::isPhone would look something like this:

public function isPhone($number, $country)

As you’ve seen, the Input component allows us to reuse code (one of the main goals behind object oriented programming), reduce redundancy, and create readable rules quickly and easily.

Blesta 3.0: XSS? No problem.

August 22, 2011 | Posted by Cody


Browsers have come a long way in preventing malicious scripts from compromising a user’s system, but XSS (Cross Site Scripting) still poses a security threat for developers. In version 3, we make use of a couple libraries packaged with the minPHP framework and recommend you do the same with your plugins, modules, or gateways. They are the Html and Formhelpers.

In the previous article I showed how to eliminate SQL inection, but what do you do when a user submits some XSS code through a web form? Obviously parameter binding won’t help you there, so what do you do? Nothing. Well, at least for now, and here’s why:

  1. Sanitizing input for XSS is expensive (both computationally, and economically). Web technologies change very frequently. What if W3C decides to add an “ontrippleclick” event?
  2. Not all form data will end up in an HTML document. Some data is destined for emails or 3rd party APIs.
  3. Sanitizing may make the data less or unsearchable by the database engine.

So when do we deal with this potentially hazardous data? Why, when we render it of course. And here’s how that’s done:

<div>Name: <?php $this->Html->_($name);?></div>

In the above example, Html::_() both sanitizes and prints the data, but we can force it to return the sanitized output by setting the 2nd parameter to false. Neat-o. When used in a form, the Form helper will take care of drawing the form field and sanitizing the data.

<div>Name: <?php echo $this->Form->fieldText($name);?></div>

One thing to note is that we’re not destroying the XSS, we’re simply treating it as plain-text within an HTML document. While this takes care of most scenarios, there are some instances the Html helper can’t help you with. One such case is in dealing with the href attribute of an anchor tag. As a programmer you simply need to be aware of such pitfalls and address them accordingly.

Blesta 3.0: Eliminating SQL Injection

August 15, 2011 | Posted by Cody


SQL injection is a serious concern for developers, and there are a number of ways of dealing with it; however the best, and most proven method, is through parameter binding. What parameter binding does is substitute variable data within a query with parameters, which are then replaced by the database driver during query execution. Since the database driver is intimately aware of which parts of the query are parameters it can parse the query and then execute it with the bound parameters safely set.

The framework that Blesta 3 is built on, minPHP, handles parameter binding through use of the PDO extension. But because writing queries is tedious and prone to typos, minPHP offers a database access object to interface with PDO in the Record class. A query that would otherwise looks like this…

$this->query("SELECT `users`.`first_name`, `users`.`last_name` FROM `users` WHERE `id`=?", 3);

becomes…

$this->Record->select(array("users.first_name","users.last_name"))->from("users")->where("id", "=", 3);

No need to worry about syntax, semantics, escaping data, or back-ticks. That’s all handled by the computer, which loves performing tedious operations over and over.

We’ll look at how to overcome cross site scripting (XSS) vulnerabilities next week.

Blesta 3.0: Manual Invoices (video)

July 13, 2011 | Posted by Paul


We’ve got a video for you today, the first in what will likely be a larger series. This video focuses on the aspect of manual invoice creation. (Not to be confused with automatic, recurring service invoice creation, which Blesta handles well too)

There are a few notable new features in v3 from previous versions.

  1. Draft Invoices, with automatic saving
  2. Voided Invoices (replaces deleting invoices)
  3. Quantities, including fractional quantities
  4. Sub-total, tax, and total preview
  5. Line item drag-n-drop sorting
  6. Additional optional invoice delivery methods, like Interfax and PostalMethods
  7. Standalone recurring invoices (Do not require a package or service)
  8. Dynamic custom invoice numbering system (prefix/suffix, etc)
  9. Invoice delivery logging, date/time and method of each delivery

Please note that features are subject to change. Blesta v3 is currently in active development.

Turn your sound on, and let us know what you think.

Tags:

Blesta 3.0: June Status Update

June 16, 2011 | Posted by Paul


Blesta treats mountains like so much dirt! –I have a framed copy of a magazine ad in my office that has a similar slogan. First 2 people to send me a picture of that ad get a free owned license of Blesta! sales -at- blesta.com UPDATE! Both licenses have now been claimed. Thanks to all who participated!

When can I rock out with v3?

Let’s give it some context. v3 is a complete, ground-up rewrite. All of the back-end, and all of the front-end. It’s completely object-oriented. It’s powerful, and intuitive, and customizable, and developer friendly. It has a ton of new and improved features, many of which we couldn’t even consider adding to the old codebase, due to inherent limitations.

It’s coming together really, really well. I’m excited, it looks amazing. It’s the best thing we’ve ever done. But, we still have some work to do, we’re not quite there yet. We have internal goals and deadlines, and we have a pretty good idea when v3 will be ready.. but the last thing we want to do is take shortcuts and fall short of the standard we’ve set to make a deadline. So, we’re keeping those internals confidential for the time being, they are afterall subject to change, if it favors a better product.

But, I promise to keep you in the loop as much as I can. As we get closer and closer we’ll start streaming out information more quickly. I really cannot wait to get v3 in your hands.

Alright, now it’s time for some dessert.

This is a (scaled down, I know) screenshot of the Client Overview page. While this is an entirely new and improved design, it still feels like Blesta, and most actions are performed here just like 2.x. As soon as you get your hands on v3, you’ll feel right at home. Completely rewritten, yes. New and improved features, yes.. but it’s still Blesta, it feels like Blesta.

You may have noticed that the colors have changed slightly. The default color scheme is going to be this shade of blue, the official Blesta blue. Bolder.

One thing I don’t believe I’ve mentioned is how dynamic the new interface is. Staff can customize their experience with drag-n-drop elements that we call widgets. Changes are persistent, so when you come back those windows will be just where you left them. We realize different staff members have different responsibilities, so it only makes sense that the interface should adjust.

That reminds me.. we’ve talked a little bit about color themes. Here’s a few that will likely be shipping with Blesta. Them aren’t images either, these colors are made up purely of glorious hex codes which means a limit of 16 million colors. I call it gradient magic. Whoa I feel like I just lined up some ipods.

I’ll have more for you soon. Thanks for reading, the future looks great!

Tags: