Blog Archive

Showing posts with label Tutorial. Show all posts
Showing posts with label Tutorial. Show all posts

Wednesday, 19 February 2014

Creating an authentication system for Fuel CMS using the Ion Auth library and Codeigniter hooks

Fuel CMS has an excellent system for publishing pages to a website. But what if you wanted some of those pages to be "members only", protected on the front end by an authentication layer? There is no in-built method to do this, but there are plenty of ways in the underlying Codeigniter framework to enable it.

In this tutorial we will install and use the excellent Ion Auth library written for Codeigniter by Ben Edmunds to create just such an authentication layer for Fuel CMS pages.

The Ion Auth library is available as a zip from GitHub, and is already packaged in the Codeigniter directory hierarchy, so just unpack it into your Fuel CMS directory, in the /application/ folder, and run the SQL provided. We will be making use of it just as if it were running in a plain vanilla CI site.

Preparing Fuel CMS for front end authentication

From Fuel’s CMS perspective, we are going to alter the default layout (“main”) for “pages”, but we want to set Fuel’s page mode to “auto” for our purposes, so change $config['fuel_mode'] (in /application/config/MY_fuel.php) if it is set to anything else.

A bit of background on the way Fuel CMS stores "pages" might be useful to understand the concept of "layouts".

"Pages" are stored in 2 database tables in Fuel:
  1. Fuel_pages is a relatively small table which stores the id, location (uri), published status, cache mode and related author and timestamp data. This is the “parent” table.
  2. Fuel_page_variables (the “child” table) stores the actual content of the page, related by a foreign key to Fuel_pages. What makes the Pages module in Fuel so flexible is that the "layout" fields are stored as name and value pairs, which means they are easily extendable. More fields = more rows in this table.
So the HTML input fields that are evident in the Pages module of the Fuel admin system are actually configured by "layouts", which are really just PHP arrays. These array templates are then stored, in name value pairs in the Fuel _pages_variables table. Importantly, each pair is also classified by a "type", so an input field might be text, multi, date, file and so on (more info here). This means if you want to add to the fields/inputs for a page layout, you don't need to alter the SQL structure of the storage table, you just add to the PHP arrays! This is a HUGE timesaver!

If you need to have different content layouts in your site (eg your "Home" page has need of video urls, or your"About" page differs from other pages as it has formatted staff biographies) then one way to tackle these content differences is by making use of one or more layouts. The choice of layout is actually there in the page (Fuel_pages) definition. Try swapping between "main" and "alias" layouts in the pages module and see how the field layout alters completely!

To change or create new layouts, we need to edit MY_fuel_layouts.php (found in the /application/config folder). Note that if you add another layout to the MY_fuel_layouts file, then you should also provide a new layout view file in /application/views/_layouts of the same name as the config index..

However, we are going to keep things relatively simple here and just alter the "main" layout. We want simple “boolean” authentication across all the pages we create, and for the sake of this tutorial we will stick with one layout that incorporates this. So find the array definition $config['layouts']['main'] and add to the end of the "fields" sub-array this:

'auth' => array(
'type' => 'enum',
'options' => array('0' => 'No', '1' => 'Yes'))


Here we are adding a field called "auth" to the main layout. It's an enum type, so Fuel's Form Builder Class will render a radio button array (as there are only 2 values) and the values will be 0 and 1, with labels "No" and "Yes" respectively.
admin_auth_field

Save MY_fuel_layouts.php and call up the pages module in the Fuel admin to see the result. Note that because we added the value  after the Body fieldset definition, the new field "auth" will appear last under the "Body" tab in the "Layout Variables" section of the page. Select “Yes” for the new field. Now when you save the page, the selected value (1) will be stored in the Fuel_page_variables table. Try running the following SQL in your database client to verify the saved value (your page_id value may differ):

select * from fuel_page_variables where page_id = 2 and name = 'auth';

The result may look something like:

page_variable_auth_sql


Note that if you re-save that page, but with “No” selected, you will observe from running the SQL query again that the “No” value (0) is actually saved as an empty value.

Ok, so we can now flag which pages are to be protected. But how to actually check the value in the page against Ion Auth?

Using Codeigniter’s hooks

There are a few ways to implement Ion Auth in Codeigniter – we could use the controller system to create an authentication controller, and extend from that when we need to employ login credential checks. But for this tutorial we will use Codeigniter’s Hooks.

As the name implies, Hooks are means of intercepting processes in Codeigniter at crucial points. With our authentication system, we want to check at the Controller level, or very near it. One hook “post_controller_constructor” suits our requirements. It will be almost as good as writing the Ion Auth authentication into each and every controller’s constructor method. Note that doing this may introduce performance penalties as it will be run on every controller call in the application, so it is important to tread lightly using this technique!

To create a Hook, we need to add an entry to /application/config/hooks.php:

include(FUEL_PATH . 'config/fuel_hooks.php');
 
/* Our hook code for Ion Auth */
$hook['post_controller_constructor'][] = array(
    'class' => 'Auth_hooks',
    'function' => 'cms_auth',
    'filename' => 'Auth_hooks.php',
    'filepath' => 'hooks',
    'params' => array(),
    'module' => 'app',
);

Note that we add this hook definition after the include for Fuel’s own hooks, and that we employ the “multiple calls to the same hook” extra array index (this is because Fuel is already using this Hook point, so we are adding to it with the extra array dimension).

So we need to have a class called Auth_hooks.php in /application/hooks, with a method “cms_auth()”. We don’t have to use a class, but we will!

class Auth_hooks {

    function cms_auth() {
        $CI = &get_instance();
        $redirect_to = 'auth/login';
        $pagevars = $CI->fuel->pagevars->retrieve(uri_path());
        if(isset($pagevars)) {
            if(isset($pagevars['auth'])) {
                $CI->load->library('ion_auth');
                if(!$CI->ion_auth->logged_in() && $pagevars['auth'] == 1) {
                        redirect($redirect_to);
                }
            }
        }
    }
}


This is a very simple means of protecting CMS content using hooks. If the page is set to require authentication ($pagevars['auth'] == 1) and Ion_Auth detects no login credentials, then we redirect the user to the auth/login controller (which should have been added when the Ion Auth zip was unpacked). Note that we use the Pagevars class to find any variables for the given url. One other important note: turn off caching for authenticated pages - otherwise you may inadvertently store login information.

There are a number of improvements we could make to this basic authentication handling. For example, we could make it more fine grained and authenticate against Ion Auth’s groups (ie a user must be logged in and a member of group or groups x,y,z…). We could make the redirect a bit more helpful, such that after logging in the user is redirected to the original page he or she was rejected from.

All of this is possible and may be the subject of a further post!

Wednesday, 1 May 2013

Putting the Form Builder class to work in FUEL CMS

Building forms in HTML is rarely a pleasure, so any functionality that aids that chore is a boon. Codeigniter has some form helper functions that are handy, and separately, the Validation class to prepare form data for processing. FUEL CMS builds on these to create the seriously useful Form Builder class.

In this tutorial I will show how useful it can be by building a form with CAPTCHA capabilities, and error responses.  I will be using v1.0 of FUEL CMS. I will use the CAPTCHA library found here CodeIgniter-Captcha

The form

 The source fields for the Form Builder class can be stored as an array, so why not create a config file for forms? In the application/config folder, create a file imaginatively called "forms.php". This can store one or more forms, and in this example it will have a "contact us" type form like so:


/* 
* CONTACT FORM
 */
$config['contact']['form'] = array(
  'required_text' => '* required fields',
  'css_class' => 'regular',
  'form_attrs' => array('method' => 'post'),
  'submit_value' => 'Send'
);

/* Setup fields */
$config['contact']['fields'] = array(
  'name' => array('type' => 'text', 'label' => 'Your name', 'required' => TRUE),
  'email' => array('type' => 'text', 'label' => 'Your email', 'required' => TRUE),
  'telephone' => array('label' => 'Your telephone'),
  'enquiry' => array('type' => 'textarea', 'label' => 'Your enquiry', 'required' => TRUE) 
);


The configuration for Form Builder is in 2 parts - the form itself, and then the fields. The keys for the fields are self explanatory, the form configuration keys are more complex - some are attributes, others are HTML snippets.

How do we put these to work in Form Builder? We will need to load the config file in our controller, and supply the "form" array as the configuration parameters to the class. So in a controller we can do:

class Contact extends CI_Controller {
    
  public $form_data;

  public function __construct() 
  {
    parent::__construct();
    // load contact config
   $this->load->config('forms');
   $this->form_data = $this->config->item('contact');
  }
...


For convenience I am putting the loaded "contact" array into a public variable. Later in the controller, Form Builder can be configured like so:

$this->load->library('form_builder', $this->form_data['form']);
$this->load->library('captcha');
$this->load->library('form_validation');


This configuration can occur in a method of your choosing - since this will be for an index page, my code was in the index() method. Note also I am loading the CAPTCHA library referred to above, and the form validation library.

As per the typical Codeigniter form validation, this same controller method should use some validation rules:

/* validators */
$this->form_validation->set_rules('name', 'Name', 'trim|required|max_length[128]|xss_clean');   
$this->form_validation->set_rules('email', 'Email', 'trim|required|max_length[256]|valid_email|xss_clean');
$this->form_validation->set_rules('telephone', 'Telephone', 'trim|max_length[24]|xss_clean');   
$this->form_validation->set_rules('enquiry', 'Enquiry', 'trim|min_length[8]|max_length[1024]|xss_clean');

// captcha rule - use codeigniter validation callback feature! NB we set function beginning with
// underscore so it won't get actioned by URL request - hence double underscore in callback 
// (callback convention + controller method convention)!
$this->form_validation->set_rules('captcha', 'CAPTCHA', 'required|callback__captcha_check');
$this->form_validation->set_message('_captcha_check', 'Text did not match the characters in the image');


The validations for the fields loaded by the forms.php config file are unremarkable, but something special is happening regarding the CAPTCHA input field - another method is being called (_captcha_check) within the rules argument. The method call is prefixed with "callback_" which is Codeigniter's way of implementing a function call for callbacks. So there will need to be another method in the controller like:

// CAPTCHA callback function - used by validation 
function _captcha_check($str)
{
  if($this->captcha->check($str))
     return TRUE;     
  else 
    return FALSE;   
}


The method follows the Codeigniter convention of beginning with an underscore so that it is not available as a URI request. The callback gets the string from the supplied input and uses the Captcha library to test if it matches the session string. A boolean return completes the validation.

So far, nothing has happened about the tiresome form construction! Here's how it will happen: we only need show the form either on initial load, or if the form has been submitted and failed validation, so inside of the validation test for "no validation"

if($this->form_validation->run() == FALSE) {

  // create CAPTCHA img and field
  if($this->captcha->create()){
    $captcha = $this->captcha->html_data;
  } else {
    $captcha = 'Captcha : ' . $this->captcha->debug;
  }
  // append captcha html to text field of same name
  $captcha_html = "<p title='Input the characters in this image in the field below'>";
  $captcha_html .= img($captcha) ."</p>";
  $this->form_data['fields']['captcha']['before_html'] = $captcha_html;
    
  // See if submit has occurred (and failed) & populate fields
  // with submitted data, and append error too.
  if($this->input->post('Send'))
  {
    foreach($this->form_data['fields'] as $key => $val)
    {
      $this->form_data['fields'][$key]['value'] = $this->input->post($key);
      $this->form_data['fields'][$key]['after_html'] = form_error($key);
    }
  }
  $data['form'] = $this->form_builder->render_divs($this->form_data['fields']);
}



This is where Form Builder really comes into its own. Remember that earlier we created a class property array $this->form_data? The last line in the code snippet above builds the entire form from the config file array "fields" using this property. Using the class method render_divs(), it constructs the form using div tags to separate the label / input rows! That's it! Providing your CSS is up to snuff, the form should look fine already.

But what else is going on here? Two things: a CAPTCHA image is created using the library we referenced earlier, and inserted into an HTML sandwich, which is pre-pended to the CAPTCHA field. What CAPTCHA field?? We've been sneaky here and made a form field ("captcha") on the fly - and then been doubly sneaky by bolting it on with Form Builder's 'before_html' key so that the image appears above the text input field that will be validated by the rules we set earlier.

But wait, there's more! We then loop over the fields from the config array 'fields' index, and append any form errors using the key 'after_html', whilst also adding the submitted value back into the correct input's 'value' attribute. Double whammy!

And that is all contained in $data['form'], which is going to be part of the array we send to the view in Codeigniter fashion like so:

// use Fuel_page to render so it will grab all opt-in variables and do any necessary parsing  
$this->fuel->pages->render($view, $data);   


This view rendering is part of FUEL CMS' Pages class, but it's the same principle as if we used the Codeigniter load->view('view', $data) arrangement.

Thus all we need do in the view itself is echo out the form with:

<?php echo $form; ?>


So we should have:
  1. A nicely constructed form
  2. A captcha image and input field within it
  3. A form that validates itself, and reports errors and displays the submitted values


Wash, rinse, repeat.

Thursday, 7 February 2013

The ins and outs of inline editing in FUEL CMS

FUEL CMS automatically allows inline editing of CMS content from the front end of a site. If you are logged in as an administrator,a tool bar will appear on the front end allowing you to edit content such as page titles, meta descriptions and body content there and then, thus making a trip to the admin redundant. Content is made editable via modal dialogue forms. The editable fields are defined in application/config/MY_fuel_layouts.php and the array key defining a layout should match a view file in views/_layouts.

Controllers and CMS content


It is of course possible to create controllers and views that also mix in CMS content - just fetch the CMS fields for a given url and combine the controller content (whatever that might be - from a model, or variables) and make sure the view can show both.

For example a (v1.0) controller like the following:

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

class Rendercms extends CI_Controller {
  
    public function __construct() {
        parent::__construct();
    }
  
    public function index()
    {
        $params;
        $view = 'rendercms/index';
        $vars = array();
        $cms_vars = array();      
        $vars['some_controller_content'] = "Me? I'm controller content!";
        $cms_vars = $this->fuel->pagevars->retrieve($this->uri->uri_string());
        $all_vars = array_merge($cms_vars, $vars);
      
        if($this->input->get('cms') == 'true') {
            $params = array('render_mode' => 'cms');      
        }

        $this->fuel->pages->render($view, $all_vars, $params);  
    }

}

 
combined with a view file (views/rendercms/index.php) such as:

<?php echo fuel_var('body', 'No CMS content here, sorry'); ?>
<hr>
<?php echo $some_controller_content; ?>
<hr>
<?php echo $some_variables_content; ?> 

<hr> 
<p>And I'm humble view HTML</p>
 
can demonstrate the features of FUEL CMS's abilities. The view file will show any CMS content at the url /rendercms (or simply default to 'No CMS content here...'), it can also show the 'some_controller_content' created by the controller, and, as a bonus, it picks up a variable defined in views/_variables/rendercms.php:

<?php

$vars['some_variables_content'] = "I'm only variable content";

?>


So far so good! However, notice the FUEL toolbar on this page (you need to be logged in to the admin, remember, to see this). It's there, but there is nothing it can do to edit the CMS content! Those features, the "toggle editable areas" and "toggle page's publish status" and the rest, are unavailable.

Depending on your needs, this may be only a mild inconvenience. But is there a way round it - a way to get everything!?

The answer is yes, but with some drawbacks.

Everything


In the controller above, you will notice I added a conditional to check for a parameter "cms=true".

Add that parameter to the url (/rendercms?cms=true) and refresh the page (NB make sure in config.php you have allowed GET: $config['allow_get_array']  = TRUE;).

Now only the CMS content is visible, in whatever layout file the CMS has defined (probably 'main' if nothing else). The variables and controller content and even the view file itself are now ignored because the render_mode => 'cms' specification (the default value is 'views'). The 'main' layout file alone is being used, and that, of course, lacks your custom controller content!

So, if there was a layout file that could echo the controller, variable AND CMS content, we'd win!

Make a file ("rendercms.php") in the views/_layouts folder that includes all these variable placeholders eg:

<html>
<head><title><?php echo fuel_var('page_title'); ?></title></head>
<body style="font-family: Georgia;">
<h1>This is a layout file</h1>
<?php echo fuel_var('body', 'No CMS content here, sorry'); ?>
<hr>
<?php echo $some_controller_content; ?>
<hr>
<?php echo $some_variables_content; ?>
</body>
</html>


Now go back to your CMS page in the admin, for "rendercms". In the layout field (you may need to refresh the admin page to reload the options) you should see "rendercms" as a layout. Select it, and save the page. Now when you return and refresh /rendercms?cms=true you should see CMS fields that are editable from the toolbar, controller content and variables content combined.

The additional drawback to this solution, however, is that to make the 'layout variables' fields appear in the admin, you will also need to add an array for "rendercms" in MY_fuel_layouts.php. eg:

$config['layouts']['rendercms'] = $config['layouts']['main'];

Here for example, we copy all the fields for the 'main' layout to the new 'rendercms' layout.

So to make a consistent inline editing experience for the user, where you have CMS & controller content combined, you need to

  1. make a layout file and 
  2. a layout configuration array to support it, in addition to 
  3. the controller, 
  4. view 
  5. (and optionally) the variables file.

It's conceivable though, that you could make just one layout file, and make it contain all the possible controller content it might need to accommodate, eg by adjusting its own layout according to which (controller) url it is responding too. Conceivable, but possibly monstrous! The viability of that solution would depend on the scale, complexity and number of your controllers.

If however inline editing isn't such a priority, the original method outlined above is pretty simple to effect. If you want, that functionality can be moved to MY_Controller, and controllers that combine CMS and their own content can be extended from that.

Saturday, 4 August 2012

Caching assets in FUEL CMS

FUEL CMS has several enhancements in terms of classes over plain vanilla Codeigniter. One which I have recently been making more use of is the Asset class.

I’ve been using Andy Clarke’s 320 & Up and in the early version of this, there were a number of CSS and JS files, some conditional for IE.

The Asset class in FUEL CMS allows some neat optimisations regarding CSS & JS that are worth stressing. Typically you can use the css() method to do something simple like:

<?php echo css('base'); ?>

and this will create a <link> tag with an href to the (now cached) base.css file. However, if you have a conditional file for IE you can set the method like this:

<?php echo css('legacy-ie', NULL, 
  array('output' => TRUE, 'attrs' => 'media="screen"', 'ie_conditional' => 'lte IE 6')); ?>

and this will surround the tag with IE conditional comments, and add attributes as specified in the 'attrs' array key.

But there’s more! By combining several css file names as arguments to the css() method, the files can be combined by the Asset class, and with the ‘output’ key set to ‘gzip’, the resulting cache file will be gzipped too. Eg:

<?php echo css('base, home', NULL, array('output' => 'gzip')); ?>   

your server environment permitting of course!

Most of the functionality for the css() method is also available to the js() method too. Eg to combine Imgsizer & Selectivizr scripts and gzip them with IE conditional tags around them:

<?php 
echo js('imgsizer, selectivizr', NULL,
  array('output' => 'gzip', 'ie_conditional' => '(lt IE 9) & (!IEMobile) '));
 ?>

results in the following being rendered in a cached file:

<!--[if (lt IE 9) & (!IEMobile) ]>
<script src="/assets/cache/d370bce01d8e837e3253b2d90ac8c4fb_1325372400.php"
 type="text/javascript" charset="utf-8"></script>
<![endif]—>

If you want to, the ‘output’ array key value can simply be set to TRUE and this will not only gzip but will also clear out whitespace in the source files too. Consult the Asset class guide for more information.

Monday, 25 June 2012

Add a JQuery plugin to FUEL CMS module admin page

When creating a new FUEL CMS module, you get a fully fledged administration CRUD when the module is added to MY_fuel_modules.php. As good as that is, there’s often a need to extend its javascript capabilities in certain situations.

FUEL CMS makes use of a javascript framework named JQX. Its employment in the FUEL admin allows additional code and plugins to be added.

Firstly, let’s demonstrate how JQuery can be hooked into the existing HTML & PHP of the admin. We would want to assign a CSS id or classname to a given field or fields as a selector for JQuery. If the application of a plugin is to a single field, then FUEL CMS assigns an HTML id attribute to the fields within the create / edit page of the module anyway, so that’s catered for. If you wish to assign a custom class name then this can be done within the model of the module, using FUEL’s form_fields() method:

$fields['yourfield']['class'] = 'your-class-name';

So, class or id, we are ready to add functionality via JQX.

First off, we need to create a javascript controller file, using the same name of the module. For example, if the module in hand were named “news” we would create a file called ‘NewsController.js’ and add it to the /fuel/modules/fuel/assets/js/fuel/controller folder. This naming convention allows FUEL to use the script without any further intervention! So when you browse to (for example) /your-site/fuel/news/edit/1 any code within the NewsController.js will be executed. However, the code in that file should be an extension of the existing JQX controller class! So the javascript within should look something like:

   1:  fuel.controller.NewsController = jqx.createController(fuel.controller.BaseFuelController, {
   2:      
   3:      init: function(initObj){
   4:          this._super(initObj);
   5:      },
   6:      
   7:      add_edit: function(){
   8:          this._super();
   9:      }    
  10:  });

This example does nothing but create a new class. To make use of it at all though, we need to add the following to MY_fuel_modules in /config:
$config['modules']['news'] = array(
'js_controller' => 'fuel.controller.NewsController'
);

You may have many other module configurations in this array, but 'js_controller' is required to load the js file in the module. With that done, how do we apply a plugin to a field in the create / edit form?

Again, by convention, the JQX framework looks for plugins on a specific path, in v0.93 of FUEL CMS it is in /fuel/modules/fuel/assets/js/fuel/jquery/plugins. Add the plugin to that folder, and then add the following to the beginning of the js controller script, before the class initialisation (NB the .js file extension is not required):

jqx.load('plugin', 'charCount');

This plugin (charCount.js) happens to be a character countdown script which I want to apply to a textarea field called “summary” within the news module. To instance it we need to add a line to the add_edit function, and create a function that will call the plugin and apply it to the field in question. So our controller code becomes:

   1:  jqx.load('plugin', 'charCount');
   2:             
   3:  fuel.controller.NewsController = jqx.createController(fuel.controller.BaseFuelController, {
   4:      
   5:      init: function(initObj){
   6:          this._super(initObj);
   7:      },
   8:      
   9:      add_edit: function(){
  10:          this._super();
  11:          this.charCounter();
  12:      },
  13:      charCounter: function() {
  14:          // applies char countdown to summary field
  15:          $('#summary').charCount({
  16:              allowed: 120,        
  17:              warning: 20,
  18:              counterText: 'Chars left: '    
  19:          });
  20:      }    
  21:  });

The add_edit() now invokes the charCounter() function on line 11. In turn, this then applies (via JQuery) the character counting plugin code to an element with id “summary”, although as noted above, we could have used a class name instead of an id as a selector. If you are adding more plugins to the module, just use jqx.load() and do something similar with the add_edit function to invoke the plugin.

Powerful stuff, JQX!

I've added a similar walkthrough of adding JQuery functionality to admin modules here.

Friday, 22 June 2012

Tweeting from a FUEL CMS module

Recently a client asked if it were possible to tweet automatically from a news module, such that in publishing a news item, a tweet could optionally be sent too. This article will deal with the basics of creating a tweet relationship within a FUEL CMS news module.

What I envisaged was a checkbox in the module’s create/edit page that indicated the tweet option, and then some post processing to send it. OAUTH would be catered for preferably, and would be invisible to the administrator (eg permission to use the Twitter account would be a condition of being able to use the module in the first place). The link to the tweeted article could be auto generated and shortened using the an API, so again, no user intervention would be required.

The first task was to find a Twitter library, and after prodding several that either didn’t work as expected, or I didn’t understand in time, I used the one supplied by Simon Emms. This offered exactly what I wanted for the module, and was already developed for Codeigniter! Follow Simon’s instructions on how to make use of the library, and you will also need (obviously) a Twitter account to use, and the keys required to use the application including those to auto authenticate the account (ie the consumer key, consumer secret, access key and access secret).

Next,I needed a library to auto shorten the links to the news article. I considered two – one for Google and one for Bitly. Since the Bitly one was also from Simon Emms, that seemed appropriate, but either would have done.

To work

In addition to the checkbox option I had imagined, it seemed a good idea to store whether a tweet had occurred, so my news module MySQL table looked something like

   1:  CREATE TABLE `news` (
   2:    `id` int(11) NOT NULL auto_increment,
   3:    `date_added` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
   4:    `keywords` varchar(255) default NULL,
   5:    `description` varchar(320) default NULL,
   6:    `title` varchar(255) NOT NULL,
   7:    `publish_date` date NOT NULL,
   8:    `summary` varchar(2048) default NULL,
   9:    `content` text,
  10:    `url` varchar(255) default NULL,
  11:    `tweet` enum('yes','no') NOT NULL default 'no',
  12:    `tweeted` int(11) NOT NULL default 0,
  13:    `active` enum('yes','no') default 'no',
  14:    `last_updated` timestamp NULL default NULL,
  15:    PRIMARY KEY  (`id`),
  16:    UNIQUE KEY `id_UNIQUE` (`id`)
  17:  )

The column “tweeted” would store the number of times the article had been posted to twitter (probably only ever once, but you never know), and the “tweet” column would act as a switch to trigger a tweet.


I also made the “tweeted” field readonly, as there is no point rendering it as an editable field, so the news model’s form_fields() method was


   1:  function form_fields($values = array())
   2:  {
   3:    $fields = parent::form_fields($values);
   4:    $fields['tweeted'] = array('readonly' => TRUE, 'comment' => 'Times tweeted (read only)', 
   5:      'order' => 8, 'default' => 0);
   6:    return $fields;
   10:   }



To process the tweet I chose the on_after_save() hook that derives from the  MY_Model class of FUEL CMS. It was as simple as:


   1:  function on_after_save($values)
   2:  {
   3:    if($values['tweet'] == 'yes' && $values['active'] == 'yes')
   4:    {
   5:      $this->load->library('cache'); // required by Twitter lib below
   6:      $this->load->library('twitter');
   7:      if($this->twitter->is_logged_in()) {
   8:          $this->load->library('bitly');
   9:          $tweet = $values['summary'];
  10:          $shortUrl = '';
  11:          $shortUrl = $this->bitly->shorten(site_url('news/item/'. $values['id']));
  12:          $this->twitter->post_tweet($tweet. ' ' . $shortUrl);
  13:          $this->session->set_flashdata('success_other', 'This item has been tweeted successfully too!');
  14:          $this->_updateTweeted($values['id']);
  15:      }    
  16:    else
  17:          $this->session->set_flashdata('success_other', 'Not logged in to Twitter account!');        
  18:    }
  19:    // reset tweet status
  20:    $this->db->set('tweet', 'no');
  21:    $this->db->where('id', $values['id']);
  22:    $this->db->update('news');
  23:  }



The data posted by the module’s form is sent in the $values array. I test for the “tweet” field being positive, and also that the posted item is “active” (eg in published status). The magic with twitter authentication then happens, and if all is well, the Bitly url shortening proceeds, and then the post to Twitter. The _updateTweeted() method is not shown, but this just increments the tweeted field.


I’m using the news module’s “summary” field as the source for the tweet, (and in fact I added a character count to that textarea to warn the user when their limit was up, but I’m not detailing that here).


The success or otherwise of this process is represented in the flashdata messages. I had to edit a core FUEL CMS file (fuel/modules/fuel/views/_blocks/notifications.php) to represent these messages in the admin views, as setting flashdata messages in the on_after_save() method will otherwise see them overwritten by the standard system messaging (hence I use ‘success_other’ key to put them out of harm’s way!). Since tweeting is really only secondary in importance to the form as a whole being saved correctly, the “fail” message will appear after the “Data has been saved” message, rather than in an alert of it’s own.

Wednesday, 30 May 2012

Authenticating pages in FUEL CMS

FUEL CMS uses an ingenious table model to store page variables for its CMS (fuel_page_variables). Such is its design that it is possible to create new variables, or fields, for the Pages module just by adding keys to the array in application/config/MY_fuel_layouts.php. The values stored in the database are under “name” and “value” columns.

It occurred to me that it would be possible to add a boolean field to the array that indicated whether the page required authentication to be viewed. So an admin could check any page in the Pages section as “private” – ie requiring a login.

So adding the key ‘is_private’ (line 8) to MY_fuel_layout.php:

   1:  $config['layout_fields']['main'] =  array(
   2:  'copy' => array('copy' => lang('layout_field_main_copy')),
   3:  'page_title' => array('label' => lang('layout_field_page_title')),
   4:  'meta_description' => array('label' => lang('layout_field_meta_description')),
   5:  'meta_keywords' => array('label' => lang('layout_field_meta_keywords')),
   6:  'body' => array('label' => lang('layout_field_body'), 'type' => 'textarea', 
       'description' => lang('layout_field_body_description')),
   7:  'body_class' => array('label' => lang('layout_field_body_class')),
   8:  'is_private' => array('type' => 'enum', 'options' => array('yes' => 'yes', 'no' => 'no'), 
       'default' => 'no', 'description' => 'Page requires authentication')
   9:  );




creates radio buttons in the “layout variables” section of the Pages edit/create form labelled yes, no. There could be a group requirement and all sorts of sophistication here, but ‘yes’ and ‘no’ will do for now.


How to intercept this variable, and where?

As per Codeigniter, we can use hooks.  In application/config/hooks.php we can add an array to the ‘post_controller’ hook.

   1:  $hook['post_controller'][] = array(
   2:   'class'    => 'MY_auth',
   3:   'function' => 'page_auth',
   4:   'filename' => 'MY_auth.php',
   5:   'filepath' => 'libraries',
   6:   'params'   => array()
   7:   );



Here we identify a class (in application/libraries it so happens) called MY_auth, and a method in it called page_auth(). This will be called after every controller. Note that the array is multi dimensional – the class here can be tacked on to existing hooks by declaring the arrays for a given hook in this manner, see the CI user guide.

In MY_auth we put:

   1:  <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
   2:  class MY_auth {
   3:    var $CI;
   4:    function __construct()
   5:    {
   6:      $this->CI = & get_instance();
   7:      $this->CI->load->library('ion_auth');
   8:    }
   9:      
  10:    function page_auth()
  11:    {
  12:      $this->CI->load->module_library(FUEL_FOLDER, 'fuel_pagevars');
  13:      $vars = $this->CI->fuel_pagevars->retrieve(uri_path(), 'db');
  14:      if(isset($vars['is_private']))
  15:        if($vars['is_private'] == 'yes')
  16:          if(!$this->CI->ion_auth->logged_in())
  17:             redirect('auth/login', 'refresh');
  18:    }
  19:  }



Page_auth() grabs the page variables associated with the current url (specified by uri_path()) from the Fuel_pagevars library in the Fuel modules folder. If one of these is “is_private” and it’s set to ‘yes’, then we whammy the visitor to the auth controller (in this case, courtesy of ion_auth).

Friday, 4 May 2012

Add site-wide authentication to FUEL CMS

FUEL CMS has a simple method of forcing a site-wide password within fuel.php, where you are able to set a "dev_password". However, if you want to add a 3rd party site wide authentication system, you can do so much like you can with a regular Codeigniter install, by editing MY_Controller.

For this example, I'll use Ben Edmunds' ion_auth. It’s very easy to add – unzip the files into the application folder, and setup the SQL in your database.

Open up application/core/MY_Controller.php. In FUEL v0.93, this has no class definition yet, so add the basic class and ion auth requirements:
 
   1:  class MY_Controller extends CI_Controller 
   2:  {
   3:      function __construct()
   4:      {
   5:          parent::__construct();
   6:          $this->load->library('ion_auth');
   7:          $this->load->helper('url');
   8:          if(!$this->ion_auth->logged_in())
   9:          {
  10:                  //redirect them to the login page
  11:                  redirect('auth/login', 'refresh');
  12:          }
  13:      }
  14:  }



Once saved, that should trigger a redirect to ion auth’s login page with any controller inheriting from MY_Controller. If you need to remove that functionality, return MY_Controller.php back to its original state!

Now you need to edit every controller that extended CI_Controller, and change that class name to “MY_Controller” (which itself extends CI_Controller).

That accounts for custom controllers, but not for some core FUEL CMS controllers. The class name swap will also need to occur in page_router.php, Fuel_base_controller.php and Blog_base_controller.php to if you are using that module. I’m prepared to be wrong, but I think that covers all the important controllers, at least for triggering ion auth login.

Thursday, 3 May 2012

Attaching documents to pages in FUEL CMS

The FUEL CMS user guide has a good example tutorial of creating a one to many relationship between simple modules. Recently I tried to do something similar, but using the FUEL admin model for pages, such that you could attach multiple objects (documents in this example) to a page in the admin, using a combo select widget, and display them on the site.

Since this wasn’t as straightforward as I’d hoped, I thought I’d jot down the procedure. I’ve tried to avoid adding all the features you’d need to do this as a real-world project, and have instead concentrated on the essentials. This tutorial relates to v0.93 of FUEL CMS.

Step one

The obvious starting place is to create a couple of database tables: “documents” and “documents_to_pages”.

CREATE TABLE `documents` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `summary` varchar(255) DEFAULT '',
  `file` varchar(255) NOT NULL DEFAULT '',
  `publish_date` datetime,
  `author` varchar(255) NULL default '',
  `tags` varchar(1024) NULL default '',
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `active` enum('yes','no') DEFAULT 'no',
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `documents_to_pages` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `page_id` int(11) NOT NULL,
  `document_id` int(11) NOT NULL, 
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

These are just examples, you may want more or less fields, or a different charset. The "documents" table will hold the file details, including a publishing date and file name, and the “documents_to_pages” is a plain vanilla look-up table to relate the key (id) of the document against the key (also named id) of the fuel_pages table (this is FUEL’s core page table - many of the layout fields are stored in “fuel_page_variables”).

Once these are added to your FUEL database schema, we can go on with the models for the 2 tables, and set about the model for pages.

Step two

Here’s the document model in full:

   1:  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:   
   3:  require_once(FUEL_PATH.'models/base_module_model.php');
   4:   
   5:  class Documents_model extends Base_module_model {
   6:       
   7:      public $record_class = 'Document';
   8:       
   9:      function __construct()
  10:      {
  11:          parent::__construct('documents');
  12:      }
  13:    
  14:      function form_fields($values = array())
  15:      {
  16:          $fields = parent::form_fields($values);
  17:          $upload_path = assets_server_path('_uploads/documents/');   
  18:          $fields['file_upload'] = array('type' => 'file',
  19:                          'upload_path' => $upload_path, 'overwrite' => FALSE);
  20:          return $fields;
  21:      }
  22:       
  23:      function on_after_delete($where)
  24:      {
  25:          $CI =& get_instance();
  26:          $CI->load->model('documents_to_pages_model');
  27:          if (is_array($where) && isset($where['id']))
  28:          {
  29:              $where = array('document_id' => $where['id']);
  30:              $CI->documents_to_pages_model->delete($where);
  31:          }
  32:       }
  33:  }
  34:   
  35:  class Document_model extends Base_module_record {
  36:   
  37:  }

Mostly this is standard FUEL CMS fare. In the form_fields() method we set an upload path where the file will be stored – you may want this to be different. We also configure the “dummy”upload field (dummy in the sense it doesn’t exist in the database, but by convention, it will store the file name in the field "file").

Using the on_after_delete() hook, we can erase any look-up records related to the deleted document. Not necessary but tidy!

Step three

The "documents_to_pages_model" can look like this:

   1:  <?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
   2:   
   3:  class Documents_to_pages_model extends MY_Model {
   4:   
   5:      public $record_class = 'Document_to_page';
   6:   
   7:      function __construct()
   8:      {
   9:          parent::__construct('documents_to_pages');
  10:      }
  11:   
  12:      function _common_query()
  13:      {
  14:          $this->db->select('documents_to_pages.*, documents.title');
  15:          $this->db->join('documents', 'documents_to_pages.document_id = documents.id', 'left');
  16:          $this->db->join('fuel_pages', 'documents_to_pages.page_id = fuel_pages.id', 'left');        
  17:      }
  18:   
  19:   function getItemsByPage($page_id) 
  20:  {
  21:        $this->db->select("documents.id, documents.title, documents.file, documents.summary, 
             DATE_FORMAT(documents.publish_date,'%Y-%m-%d'), 
             UPPER(REVERSE(SUBSTRING_INDEX(REVERSE(documents.file),'.',1))) AS file_type", FALSE);
  22:        $this->db->join("documents", "documents_to_pages.document_id = documents.id", "left");
  23:        $this->db->join("fuel_pages", "documents_to_pages.page_id =  fuel_pages.id", "left");
  24:        $this->db->where("documents.active", "yes");
  25:        $this->db->where("documents.publish_date <=", "CURRENT_TIMESTAMP", FALSE);
  26:        $this->db->where("documents_to_pages.page_id", $page_id);
  27:        $result = $this->db->get("documents_to_pages");
  28:        return $result;
  29:        }
  30:  }
  31:   
  32:  class Document_to_page_model extends Data_record {
  33:  }

Nothing much unusual here. The getItemsByPage() method will be used to display a list of records on a given page. The active record methods (select, join, where) ensure the records are active and published.

Step four

Next we need to modify the pages_model.php file found in the Fuel directory (/fuel/modules/fuel/models/). We have to add the combo select field which will allow files to be selected and “attached” to the page. To do this, we edit the form_fields() method:

   1:  function form_fields($values = array())
   2:  {
   3:      $related = array('documents' => 'documents_to_pages_model');
   4:      $fields = parent::form_fields();
   5:      $fields['date_added']['type'] = 'hidden';
   6:          
   7:  // ******************* NEW RELATED DOCUMENT FIELD BEGIN 
   8:  // NB pages controller needs updating as of v0.93 to ensure $values is passed to form fields
   9:  // eg $fields = $this->model->form_fields($saved);
  10:      $CI =& get_instance();
  11:      $CI->load->model('documents_model');
  12:      $CI->load->model('documents_to_pages_model');
  13:      $document_options = $CI->documents_model->options_list('id', 
           'title', array('active' => 'yes'), 'title');
  14:      $document_values = (!empty($values['id'])) ? 
           array_keys($CI->documents_to_pages_model->find_all_array_assoc('document_id', 
           array('page_id' => $values['id']))) : array();
  15:      $fields['documents'] = array('label' => 'Documents', 'type' => 'array',  
           'class' => 'add_edit documents', 'options' => $document_options,  
           'value' => $document_values, 'mode' => 'multi');
  16:  // ******************* NEW RELATED DOCUMENT FIELD END
  17:      
  18:      $yes = lang('form_enum_option_yes');
  19:      $no = lang('form_enum_option_no');
  20:      $fields['cache']['options'] = array('yes' => $yes, 'no' => $no);
  21:      return $fields;
  22:  }

The comments indicate the new field "documents" we are inserting into this method, but line 3 also indicates the relationship with the documents_to_pages_model. The values of this new field will be whatever is retrieved with the find_all_array_assoc() method of the MY_Model class we extended with the Documents_to_pages_model defined earlier. Note that there is a comment about the pages controller on line 8. It's commonly the case that the form_fields() argument $values contains the saved form data, but as of v0.93 of FUEL, this isn’t so of the pages model. So we must add the argument $values = array() as per line 1, and then the pages_controller also needs to be edited to send that argument in the first place, and that’s simple enough to do. Open up /fuel/modules/fuel/controllers/pages.php and find this line (line 117 of the current code):

$fields = $this->model->form_fields();

and change it to:

$fields = $this->model->form_fields($saved);

Easy!

We have not finished with the pages_model however. We add this hook:

   1:  function on_after_save($values)
   2:  {
   3:      $data = (!empty($this->normalized_save_data['documents'])) ? 
           $this->normalized_save_data['documents'] : array();
   4:      $this->save_related('documents_to_pages_model', 
           array('page_id' => $values['id']), array('document_id' => $data));        
   5:  }

This inserts the document id's and page id into the look-up table. And then we should delete related look-up records when a page is deleted, so we add a line to the on_after_delete() hook:

   1:  function on_after_delete($where)
   2:  {
   3:      $this->delete_related(array(FUEL_FOLDER => 'pagevariables_model'), 'page_id', $where);
   4:      $this->delete_related(documents_to_pages_model, 'page_id', $where);
   5:  }

Line 4 is the addition.

Step five


The admin will not display the new document model yet, not until this line is added to MY_fuel_modules.php (located in application/config):

$config['modules']['documents'] = array(); 

It should now be possible to add some test documents to the documents module in FUEL's admin. Once you have done that, take a look at the pages module too, and create or edit a page - you should see the combo select widget with the files you added to the documents module on the left. Use the combo and add one or more documents to the right hand side, and hit save. You should now see the saved files remain on the right hand selection area.

That’s about all on this topic! Bear in mind that the lookup table could be made more generic, such that documents could be associated with any module (not just pages), or even to be a store for the relationship of any module to any other module. I’ll also leave aside how to display the related documents, but that’s relatively straightforward.

Thanks to David McReynolds, lead developer of the FUEL CMS project, for helping me out with some of the issues I encountered. The forums for FUEL are massively helpful, and I recommend visiting there for help and advice.

Wednesday, 2 May 2012

Make CMS content appear in a controller view with FUEL CMS

Fuel CMS is a CMS based on the Codeigniter MVC framework. One of the first things I tried when setting it up was to create a controller and view that would display custom content, but would also show any CMS page data. That way, a client can add their copy to a view that would otherwise just loop over module data. They might, for example, have a document library view page (where data is sourced from a documents table) but want to add their own CMS advice to the page too.

It is possible to do this, but it needs a few steps that are not explicit from tutorials I have read.

This tutorial is based on v0.93 of the Fuel CMS and it may become redundant in later versions. Update v1.0 now makes the rendering method a bit simpler - see the end of this post.

Step one

Having installed Fuel CMS (see the user guide) you will need to fire up your editor of choice and create a controller. For this tutorial we’ll make a home controller, which of course will reside in /application/controllers/home.php.

   1:  <?php 
   2:  if (!defined('BASEPATH')) exit('No direct script access allowed');
   3:  class Home extends CI_Controller
   4:  { 
   5:      function __construct()
   6:      {
   7:          parent::__construct();
   8:      }
   9:      function home() 
  10:      {        
  11:          parent::Controller();    
  12:      }
  13:      function index()
  14:      {
  15:          $data = array();
  16:          $data['my_custom_content'] = 'Lorem ipsum dolor sit amet.';
  17:          $data['view'] = 'home/home'; 
  18:          $page_init = array('location' => 'home');        
  19:          $this->load->module_library(FUEL_FOLDER, 'fuel_page', $page_init);
  20:          $this->fuel_page->add_variables($data);
  21:          $this->fuel_page->render();    
  22:      }
  23:  }
  24:  ?>


Anyone familiar with Codeigniter will recognise what’s going on in this code. And there are few surprises from the Fuel CMS point of view either. We assign a string to the key value "my_custom_content", but this could be content from a model class or whatever you like. This is the content we want to see in the view, in addition to the CMS page data.

Note the definition of the $data[‘view’] and $page_init.

Step two

The view file can be as simple as this:

   1:  <?php fuel_set_var('layout', '')?>
   2:  <h1><?php echo fuel_var('page_title', 'Home page'); ?></h1>
   3:  <?php echo fuel_var('body', 'No CMS content'); ?> 
   4:  <h2>Controller content</h2>
   5:  <?php echo $my_custom_content; ?>


Here in line 1 we are erasing the layout  fuel_render() would ordinarily apply. Without this Fuel would grab the layout file located in application/views/_layouts/main.php. Why remove that functionality? Partly to demonstrate it’s possible, and partly because home page layouts are usually one-off designs not shared with the rest of a site.

In lines 2 and 3 we add the usual Fuel methods for adding CMS content with fuel_var(). Note that fuel_var() allows a second argument - this is the default value to show if the first argument is empty. After these, we add the content supplied by the controller. As usual with Codeigniter’s MVC framework, we access the key of the array passed in the controller ($my_custom_content), in this instance to the add_variables() method.

Step three

Add a CMS page with a location of “home” in the Fuel admin. Add some body content and a title to satisfy the variables we put in the view file (“page_title” & “body”).

Step four

You would be disappointed if you tried to access the url /home in your install at this point! We have one last configuration to make to get the home page to look as intended.

Open up the file MY_fuel.php in the application/config folder. Edit the “fuel_mode” value, and set it to "auto" if it is set to anything else:

   1:  $config['fuel_mode'] = 'auto';

This makes Fuel search the CMS for content matching the url as well as fetching a view.

Step five

There is a further change to make to ensure the view can respect the "published" status of CMS content (that is to say, when the page is un-published, the CMS content will not show). To effect this we need to edit the pagevariables_model.php file in the Fuel module itself (/fuel/modules/fuel/models/pagevariables_model.php). The _common_query()  method does not anticipate being called outside of the admin environment, so we need to ensure it will only show published pages when instanced outside of the admin. Replace the entire method with the following:

   1:      function _common_query()
   2:      {
   3:          $this->db->join($this->_tables['pages'], 
$this->_tables['pages'].'.id = '.$this->_tables['pagevars'].'.page_id', 'left');
   4:          // respect published status outside of admin
   5:          if (!defined('FUEL_ADMIN'))
   6:          {
   7:              $this->db->where(array($this->_tables['pages'].'.published' => 'yes'));
   8:          }
   9:      }

This fix might well be included in a future update of Fuel.

Step six

If you want to add a further nicety, you can edit the routes.php (also in the config folder) and change the line

   1:  $route['default_controller'] = 'fuel/page_router';

to

   1:  $route['default_controller'] = 'home';

Doing this will allow the home controller to serve / and /home.

Update (Sept 2012)

In v1.0 of Fuel CMS the render method has changed somewhat, making the process easier. There is now a pages object.

All that is now required is to set the url part to retrieve CMS content, and the view path like so:

$vars = $this->fuel->pagevars->retrieve($this->uri->uri_string());
$this->fuel->pages->render('home/index', $vars); 
My top artists