Preventing the copying of your site design templates

I was browsing the prestashop forum and ended up on a thread concerning an issue with people stealing a site design by downloading the template files from the theme directory. It struck me that this is probably something that those of you who use other template systems with your sites may also face, so thought I’d post the solution here too.

The problem is that although php files cannot be viewed directly on your browser, other source files can be e.g. files ending in .tpl

For example take a look at the following file that has the default permissions:

Unprotected template file

The best way to protect your site is to change the permissions on these files to 600. This will make them accessible only by your own code on the server and present anyone nosey enough to try and look at them with a 403 (forbidden) error. The same is true for php files (although these shouldn’t display the source unless your server configuration is broken).

Have a look at this file with the permissions set to 600:

Protected template file

Simple.

Customising Prestashop Module Templates

Please don’t edit those originals!

I came across this little gem a while ago on the Prestashop forum, and thought I would draw attention to it in the hopes that it will help someone, somewhere.

I’m not one to complain, but my pet hate is folks who edit the original source files on their stores, when there’s no need to. It bugged me in Zen Cart when people happily modified the “classic” and “default” template files, then wondered why it was difficult to upgrade… and lo and behold folks started doing the same thing to the Prestashop default theme too. Aaaargh!! How hard is it to make a copy, rename it and edit that version instead?

Where my purist instincts failed however, way back in the bad old days, was when it came to the .tpl files that were stored in the module directories themselves — there seems like there’s no choice but to edit them if you want to customise the output for your store — or is there!

The answer is surprisingly simple, and will make you nod your head in grateful appreciation… all you need to do is create a modules/ directory in your custom theme directory (well you aren’t going to be working in the default theme directory now are you), copy the original .tpl from the module directory into it and edit away to your heart’s content.

As an example, you can take the template file from the blockadvertising module (blockadvertising.tpl) and make a copy under /themes/mycooltheme/modules/blockadvertising. Now modify the copy of the original that looked like:


{l s='Advertising' mod='blockadvertising'}

to


{l s='A fantastic site for Prestashop goodies' mod='blockadvertising'}

Pure joy! Although the observant will notice that unless you edit the {$image} variable and place a static path to your graphic in its place, then you’ll have to change the picture in the module directory…. well you can’t have it all I guess.

Writing your own Prestashop Module – Part 4

Form Validation and Security

Introduction

While being sufficiently functional for what it does, the module we created in Part 2 does present us with some issues to consider when implementing “real world” modules to extend Prestashop. In particular the user input we captured with our form was written directly to the configuration entry without any checking to determine whether it was valid, nor did we take account of the type of data being entered.

In this tutorial we will look at the general issue of form input checking and security, both for Back Office and Front Office forms and user input as well as looking at improving our code both functionally and aesthetically.

The Configuration class revisited

In Part 3 we touched briefly on an additional parameter that may be passed to the Configuration::updateValue() class method. If you recall the function has the following form:

updateValue($key, $values, $html = false);

In Part 3 we ignored the $html parameter and allowed the function to use the default value of “false”. In doing this we actually inadvertently added the first element of security and validation to our code. When set to “false” the updateValue() method actually pre-processes the value to be written using the following code ($string is the input value passed to the function):

$string = strip_tags(nl2br2($string));

You can test this out by entering some HTML into the configuration screen for the module we created in Part 3. You should see that any html tags in your input are removed. We could modify the TutorialSecond module to allow input of html in the form, by changing line 29 in the source file to:

Configuration::updateValue($this->name.'_message', Tools::getValue('our_message', true));

This illustrates the fundamental principle that we need to employ throughout our own code to ensure that it is secure and operates predictably. Thankfully Prestashop provides us with some tools that we can use in our own code to make it more secure and robust.

Validation

Prestashop provides us with a class called Validate that we can use to determine whether any user input we accept is valid or not. The list of member functions is rather large, but it’s worth reproducing some of them here to illustrate the point — for a complete list you should consult the classes/Validate.php file in your Prestashop distribution.

isEmail($email);
isFloat($float);
isUnsignedFloat($float);
isCleanHtml($html);
isDate($date);
isBool($bool);
isPhoneNumber($phoneNumber);
isPostCode($postcode);
isInt($int);
isUnsignedInt($int);
isUnsignedId($id);
isNullOrUnsignedId($id);
isUrl($url);
isAbsoluteUrl($url);
isFileName($name);

As an example we can use the isCleanHtml() function from the list above as a test in our module to prevent XSS (cross site scripting) — that way we can allow html input reasonable safely.

Validating our form data

As before we’re going to create a new module based on the previous version. Why not try modifying the Tutorialsecond class yourself to create the Tutorialthird module? If you’d rather not, then just expand and copy the code below as appropriate!

<?php
class Tutorialthird extends Module
{
	private $_html = '';

	function __construct()
	{
		$this->name = 'tutorialthird';
		parent::__construct();

		$this->tab = 'eCartService.net Tutorials';
		$this->version = '0.1.0';
		$this->displayName = $this->l('Third Tutorial Module');
		$this->description = $this->l('Our third module - Security and Validation');
	}

	public function install()
	{
		parent::install();

		if (!$this->registerHook('leftColumn'))
			return false;
	}

	public function getContent()
	{
		if (Tools::isSubmit('submit'))
		{
			Configuration::updateValue($this->name.'_message', Tools::getValue('our_message'));
		}

		$this->_displayForm();

		return $this->_html;
	}

	private function _displayForm()
	{
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">

				<label>'.$this->l('Message to the world').'</label>
				<div class="margin-form">
					<input type="text" name="our_message" />

				</div>
				<input type="submit" name="submit" value="'.$this->l('Update').'" class="button" />

		</form>';
	}

	public function hookLeftColumn()
	{
		return '<div class="block"><h4>'. Configuration::get($this->name.'_message') . '</h4></div>';
	}

}
// End of: tutorialthird.php

The first stage in the process is to modify our getContent() function to add the validation step:

	public function getContent()
	{
		if (Tools::isSubmit('submit'))
		{
			$this->_postValidation();

			if (!sizeof($this->_postErrors))
			{
				Configuration::updateValue($this->name.'_message', Tools::getValue('our_message'), true);
				$this->_html .= '<div class="conf confirm">'.$this->l('Settings updated').'</div>';
			}
			else
			{
				foreach ($this->_postErrors AS $err)
				{
					$this->_html .= '<div class="alert error">'.$err.'</div>';
				}
			}
		}

		$this->_displayForm();

		return $this->_html;
	}

We also need to add a declaration for the $_postErrors member variable we’ve introduced at the beginning of our class definition e.g.

class Tutorialthird extends Module
{
	private $_html = '';
	private $_postErrors = array();

The logic flow when we post data to getContent() is now to call our _Validation() function to test the fields submitted and to set our $_postErrors array with any error messages. If there are errors we can display them prior to redisplaying the form. If the validation checks are passed, then we display a “success” message to give visual feedback that the configuration has been updated. A simple XSS test in the _Validation() function for our example could be:

	private function _postValidation()
	{
		if (!Validate::isCleanHtml(Tools::getValue('our_message')))
			$this->_postErrors[] = $this->l('The message you entered was not allowed, sorry');
	}

Obviously you aren’t limited to using the tests supplied by the Validate class, and you can also apply multiple tests to each field submitted — to test for length etc. The basic principle is the same in all cases, no matter how complex your validation requirements are.

Summary

In this article we’ve improved on our form handling by adding validation of user input for added security and/or reliability. We’ve also added some visual feedback when the configuration has been updated successfully. In the final part of this series we’ll add some final cosmetic touches to our form to standardise the interface and improve usability. We’ll also look at ideas for improving and extending the “template” module we’ve created.

Writing your own Prestashop Module – Part 3

Storing Module Configuration

Introduction

In the third part of this series we’ll look at how we can store configuration data for our modules in the Prestashop database, and how we can allow users to interact with this data to control the module’s behaviour. We will also briefly touch on how we can generate output from our module to provide visual feedback of the configuration changes.

Managing user settings

We’re going to call this module “TutorialSecond” so we again need to create a new module directory and class file — which will be named “tutorialsecond” and “tutorialsecond.php” respectively. The class file (tutorialsecond.php) should contain the following:

<?php
class Tutorialsecond extends Module
{
	private $_html = '';

	function __construct()
	{
		$this->name = 'tutorialsecond';
		parent::__construct();

		$this->tab = 'eCartService.net Tutorials';
		$this->version = '0.1.0';
		$this->displayName = $this->l('Second Tutorial Module');
		$this->description = $this->l('Our second module - A "Hello world" redux');
	}

	public function getContent()
	{

	}

	private function _displayForm()
	{

	}

}
// End of: tutorialsecond.php

You will notice that we have implemented two new member functions ::getContent() and ::_displayForm(). If you upload the file to your server and install this module at this stage you should see a new option on the modules list screen for ‘Second Tutorial Module’. There will now be a “>> Configure” link in the module entry, although clicking it will merely return an empty Back Office page. The presence of the ::getContent() member function is responsible for this as it provides the interface between our module and the Back Office.

In addition to these two new functions we have also added the $_html private member variable, which we will use later in this article to build the required output for display in the Back Office.

Storing and Retrieving Configuration Data

Prestashop provides a “Configuration” class which offers several member functions to manipulate configuration data, but the two key functions that will be most commonly used are:

Configuration::updateValue($key, $values, $html = false);
Configuration::get($key, $id_lang = NULL);

The Configuration::updateValue() function allows us to store a configuration option in the database (optionally in multiple languages in which case the $values parameter will be an array) and the Configuration::get() function allows us to retrieve configuration data for a selected or store default language. We will ignore the parameters that have default values for now, but will revisit the $html parameter in the Configuration::updateValue() function in the next article when we look at the subject of form validation.

Implementing the Configure Screen

In our source file we created a private member function _displayForm(). This is entirely optional as all of the interface code could be placed in the getContent() member function, however it is highly recommended that you separate this out for the sake of easier code maintenance. We’ll create a simple form within this function from with which we can capture store owner input.

	private function _displayForm()
	{
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">
				<label>'.$this->l('Message to the world').'</label>
				<div class="margin-form">

					<input type="text" name="our_message" />
				</div>
				<input type="submit" name="submit" value="'.$this->l('Update').'" class="button" />

		</form>';
	}

You can see that the ::_displayForm() function simply appends standard html form code to our $_html member variable, with the form target being $_SERVER[‘REQUEST_URI’]. Prestashop’s Back Office architecture will route this to our ::getContent class member function for us to handle when the form is posted.

We next need to add code to our ::getContent() function to actually display the form and handle the form submission.

	public function getContent()
	{
		if (Tools::isSubmit('submit'))
		{
			Configuration::updateValue($this->name.'_message', Tools::getValue('our_message'));
		}

		$this->_displayForm();

		return $this->_html;
	}

The ::getContent() function first uses another Prestashop class “Tools” to test whether we are handling the post action from the form, or whether this function is being called in another way i.e. a click on the “Configure” link in the module list — the parameter is the name we gave to our “update” button in the form.

If the function is being called directly by the Back Office (in which case Tools::isSubmit(’submit’) will return false), then we call the form rendering function we created above and return the output, captured in the $this->_html variable, to the Back Office for display.

If the function is being called as a result of our form being posted, then we can store our configuration parameter in the database with the value entered on our form. We again use the Tools class to obtain the value of the form variable using the call to Tools::getValue(’our_message’) where ‘our_message’ is the name of the input field in our form.

You can see that I have added the name of our module to the beginning of the configuration item name — this is to ensure that the configuration key is unique as the namespace for these keys is shared for the entire store.

Once we have stored our configuration data the form is again displayed, ready for more input if required.

Module Output on a Page

We now have a method of capturing input from the store owner and saving it in the database, so the next obvious step would be to do something with it e.g. display it on a page. In part 1 of the series we talked about “hooks” in relation to modules adding functionality. In order to utilise this we need to tell PrestaShop that our module would like to hook into the Front office and we do this using the following function (defined in the Module base class):

$this->registerHook($hook_name);

The $hook_name parameter refers to one of the different points that the Prestashop core allows modules to insert output and/or data processing, but for now we will use one in particular — “leftColumn’, which allows us to add content in the left column of all pages. In order to initialise the hook we need to add the following new override in our own class:

	public function install()
	{
		parent::install();

		if (!$this->registerHook('leftColumn'))
			return false;
	}

This tells Prestashop to execute our module hook when it is rendering the content for the left column of all pages. We next need to add a function to handle the hook callback. The convention is to name the function as the Hook name preceded by “hook”:

	public function hookLeftColumn()
	{
		return '<div class="block"><h4>'. Configuration::get($this->name.'_message') . '</h4></div>';
	}

In our simple example we are just wrapping our configuration parameter in some standard html markup so that it is displayed correctly on our page.

If you have already installed the module you should now uninstall then reinstall to ensure that the hook is correctly registered with the Prestashop core. Now you can enter a value in the configuration screen for the module — e.g. ‘Hello World’, and it will be output as the heading of a box in the left column of your store. The full code for the second example should now look like:

<?php
class Tutorialsecond extends Module
{
	private $_html = '';

	function __construct()
	{
		$this->name = 'tutorialsecond';
		parent::__construct();

		$this->tab = 'eCartService.net Tutorials';
		$this->version = '0.1.0';
		$this->displayName = $this->l('Second Tutorial Module');
		$this->description = $this->l('Our second module - A "Hello world" redux');
	}

	public function install()
	{
		parent::install();

		if (!$this->registerHook('leftColumn'))
			return false;
	}

	public function getContent()
	{
		if (Tools::isSubmit('submit'))
		{
			Configuration::updateValue($this->name.'_message', Tools::getValue('our_message'));
		}

		$this->_displayForm();

		return $this->_html;
	}

	private function _displayForm()
	{
		$this->_html .= '
		<form action="'.$_SERVER['REQUEST_URI'].'" method="post">

				<label>'.$this->l('Message to the world').'</label>
				<div class="margin-form">
					<input type="text" name="our_message" />

				</div>
				<input type="submit" name="submit" value="'.$this->l('Update').'" class="button" />

		</form>';
	}

	public function hookLeftColumn()
	{
		return '<div class="block"><h4>'. Configuration::get($this->name.'_message') . '</h4></div>';
	}

}
// End of: tutorialsecond.php

Summary

In this article we have extended our first module to include a basic configuration form and have used a hook function to display output from our module in the left column of our pages. In the next part of this series we will look at improving the configuration facility into something that could be used in a real module implementation. This will include validating user input to the form, pre-populating the form fields as appropriate based on the current configuration and displaying module errors and warnings in the Back Office screens.

Writing your own Prestashop Module – Part 2

Creating a basic module

Introduction

In this second part of the series we will look at creating our first basic Prestashop module that can be controlled from the Back Office.

The Module class

Similar to the ObjectModel base class, all Prestashop modules are extended from a common base class used to define their basic functionality. The “Module” class provides the interface between the administration screens and your module as well as providing internationalisation and “hook” management functionality.

Coding conventions

Before we can write our first code there is one more element that needs to be considered — that of module class, directory and file naming.

In Prestashop, modules must be located within the /modules directory below your base store installation directory. In addition the module directory and class source file must be named in lower case, with the same name as the module class we choose. Note that the module class name itself does not have to be lowercase (by convention class names use “Camel case”), but it is essential that the folder it resides in and the source file follow this convention.

An “empty” module

In this part of the tutorial we will create a module “TutorialFirst” which demonstrates the mandatory code required to create our very first module. The first step is to create our directory on the server and name it “tutorialfirst”. We then need to create the main module class file within this directory and insert the following code:

<?php
class TutorialFirst extends Module
{
function __construct()
{
$this->name = 'tutorialfirst';
parent::__construct();

$this->tab = 'eCartService.net Tutorials';
$this->version = '0.1.0';
$this->displayName = $this->l('First Tutorial Module');
$this->description = $this->l('Our very first module - it does absolutely nothing at all.');
}
}
// End of: tutorialfirst.php

We save this file as “tutorialfirst.php” in our module directory and upload to our server. Although the above code doesn’t look like very much, it is actually packed with functionality thanks to the base class it extends. Once you’ve uploaded to your development site you will be able the see the module listed under the group heading “eCartService.net Tutorials” and you can now install and uninstall it.

Let’s look at what we’re doing in this code, and why.

$this->name = 'tutorialfirst';
parent::__construct();

These first two lines in the class constructor are concerned with setting up the basic properties of the module and ensuring that we properly inherit required functionality from the base class. First we need to set up the “internal” name of the module — note that this again follows the naming convention for the module directory and main class definition file, and again is the class name in lower case. Once this is done we can safely call the parent constructor to allow it to set up the other necessary internal module properties for us.

Next we define the properties that will be used when displaying our module in the Back Office.

$this->tab = 'eCartService.net Tutorials';
$this->version = '0.1.0';
$this->displayName = $this->l('First Tutorial Module');
$this->description = $this->l('Our very first module - it does absolutely nothing at all.');

The $this->tab member variable defines how we wish our module to be classified by the Back Office in the modules list. In general we would choose one the the standard categories (e.g. ‘Advertisement’, ‘Products’, ‘Tools’, ‘Blocks’ etc.) however it is entirely up to you how you wish to use this property, and in the case of these examples I’ve chosen to group them under the heading “eCartservice.net Tutorials”.

The $this->version member variable allows us to display the current module version in the modules list, which will allow users to identify visually which version of our module they are using. This may also be useful in allowing us to identify old and outdated module versions later, using an external module distribution site.

The final two member variables are used to display information regarding our module in the modules list, and are fairly self-explanatory. Note however that these are being set using the $this->l() Module class function however, rather than just being assigned as the static strings directly.

The l() (base class) member function implements language support, and enables the store owner to provide translations. The English language version of the text we wish to display is passed to this function, and when defined in this way the store owner can use the Tools->Translations Back Office screens to translate them into the language of their choice. Wrapping any static text used in our module with this function enables the translation functionality and should be use for all static text within modules which isn’t language dependent.

Summary

Having read this article you should now be able to create a new module which can be listed and controlled from the Prestashop Back Office and optionally displaying this information in the store owner’s own language. In the next part of this tutorial we will look at extending our first module to allow configuration, and based on this configuration display output in a specified area of a page.

Writing your own PrestaShop Module – Part 1

So you want to write a module?

Introduction

There has always been a little bit of Voodoo associated Prestashop modules. This has been mainly down to a lack of documentation available, but never fear — this series of tutorials aim to introduce module writing to the PHP programming masses. This series will look at building our very own fully functional module which will provide all the standard functionality that is the basis for many of the most common modules. It will also provide a basic framework that you can use as a  template for your own code. Later articles will look at creating Payment Modules and extending the Administration interface, but initially we’ll look at the class of modules which deal mainly with inserting content into your pages, as this best demonstrates the fundamental basic concepts of developing for PrestaShop.

Before we start

These articles assume at least a basic knowledge of PHP 5.x.x and its object oriented programming concepts. It is highly recommended, due to the way Prestashop renders pages, that you build yourself a development Prestashop store if you haven’t done so already (and if you haven’t then why not?). For the purposes of these articles we will be building the examples based on the current development release (at the time of writing 1.2.0.6) but the code will be sufficiently generic that it should work with any version of Prestashop, certainly from version 1.1 onwards. You may find it useful to also familiarise yourself with the main third-party tools and libraries that Prestashop uses, and I particularly suggest familiarising yourself with the basics of the smarty template engine. Note that the Prestashop core handles the initialisation of the template class, so the specific areas to familiarise yourself with are the assigning of template variables, the creation (and display) of template files,  modifiers and template functions.

PrestaShop Architecture

Fundamental to understanding how Prestashop modules operate  is to be aware of how the shopping cart builds pages for output. The overall architecture is loosly based on the MVC principle of a “Model”, a “View” and a “Controller”.  While Prestashop doesn’t strictly stick to this philosophy, it is a useful to use it to visualise how the application works.

Models

Models in Prestashop are provided via a set of objects extended from a base class “ObjectModel”. The ObjectModel class defines the common behaviour required to encapsulate the database tables which make up the store. It provides CRUD (Create, Read, Update and Delete) functionality as well as implementing the basis for data validation and multi-lingual support. By extended this basic functionality, specific classes are created to manage the data used by the store. The models for prestashop are defined in the /classes folder and manage all of the data held within the database (e.g. Category, Product, Order, Configuration etc.). The convention is that each class is stored in a php file whose name matches the contained class name, so Order.php for example contains the Order class.

Views

The presentation of data from our shopping cart application is handled by the smarty template engine. Using a view allows us to separate out the business logic from the presentation. In a strict MVC environment there should be no processing of data by the view, only the display of data passed to it from a controller — and in the majority of cases this is true for Prestashop, although some Ajax/javascipt is employed by default to perform additional data processing. The view files for Prestashop are in general stored in the /themes folder, with the specific set of template files to be used being selectable from the Administration interface. Many modules also store their own specific template files within their own directory structure.

Controller

The controller is the main business logic for a “page” or collection of related pages to be displayed. They are responsible for interacting with the “Models” to retrieve data, apply business logic to the data and then output the results via one or more “Views”. In Prestashop these are contained in the root directory of the store installation, and correspond to the main “pages” that make up the web store.

OK, So where do modules fit in?

While the above describes the core functionality of Prestashop, and is sufficient to produce a working shopping cart, it is a little inflexible in terms of adding new functionality. If, for example, you wanted to modify the home page of your store with only the above architecture, you would have to modify the controller page directly to implement your change. Not only would this be bad in terms of code maintenance (you would have to apply changes and bug fixes manually to all of your modified controller pages when a new version is released) it also requires fairly detailed knowledge of programming to implement the changes.

In order to create a shopping cart system that is both easily extensible and maintainable by a non-technical store owner, additional functionality is inserted — “hooked” — into the above architecture by means of specially inserted “hook” points in the controller code, which can be exploited by user-installable “plugins”  (which Prestashop refer to as “modules”). In this case, these modules have the ability to output additional or modified content, add new functionality (business logic) to the controllers and gather information.

Payment modules are a specific class of module, but even they too hook into the standard controllers in order to provide alternative code execution paths. Administration panel extensions, operate in an entirely different way and the process is much more akin to adding additional controllers, so must be discussed separately. Thankfully the module architecture in Prestashop provides us with a fairly simple way of adding an administrative interface to modules, and in all but the most complex of cases this is the best method to use.

Summary

Having read this article you should now be familiar with the basic building blocks that go together to make up the Prestashop shopping cart. In the next part of this tutorial we will look at coding our first module using these concepts and begin extending Prestashop.