diff --git a/modules/consent/docs/consent.txt b/modules/consent/docs/consent.txt
index 1dbbcc82bcb4a2021619895cfbb5723139d07588..092843e3ff46123d45e792e6483a8a442fbea6de 100644
--- a/modules/consent/docs/consent.txt
+++ b/modules/consent/docs/consent.txt
@@ -1,50 +1,75 @@
-Installing and configuring the consent module
-=============================================
+Consent module
+==============
 
-The consent module is implemented as an Authentication Processing Filter. That means it can be configured in the global config.php file or the SP remote or IdP hosted metadata.
+<!-- {{TOC}} -->
 
-It is recommended to run the consent module at the IdP, and configure the filter to run after all attribute mangling filters is completed, to show the user the exact same attributes that are sent to the SP.
+
+The consent module is implemented as an Authentication Processing Filter. That 
+means it can be configured in the global config.php file or the SP remote or 
+IdP hosted metadata.
+
+It is recommended to run the consent module at the IdP, and configure the 
+filter to run after all attribute mangling filters is completed, to show the 
+user the exact same attributes that are sent to the SP.
 
   * [Read more about processing filters in simpleSAMLphp](simplesamlphp-authproc)
 
 
-Configure the user ID
----------------------
+How to setup the consent module
+-------------------------------
 
-In order to generate the privacy preserving hashes in the consent module, you need to name one attribute that always is available and that is unique to all users. An example of such an attribute is eduPersonPrincipalName.
+In order to generate the privacy preserving hashes in the consent module, you 
+need to name one attribute that always is available and that is unique to all 
+users. An example of such an attribute is eduPersonPrincipalName.
 
 In your `saml20-idp-hosted.php` add the name of the user ID attribute:
 
 	'userid.attribute' => 'uid', 
 
-If the attribute defined above is not available for a user, an error message will be shown, and the user will not be allowed through the filter. So make sure that you select an attribute that is available to all users.
+If the attribute defined above is not available for a user, an error message 
+will be shown, and the user will not be allowed through the filter. So make 
+sure that you select an attribute that is available to all users.
+
+Next you need to enable the consent module, touch an `enable` file, in the
+consent module:
+	
+    touch modules/consent/enable
 
+The simplest wayf to setup the consent module is to not use any storage at 
+all. This means that the user will always be asked to give consent each time 
+the user logs in.
 
-The first step: consent module with cookie as storage
------------------------------------------------------
+Example:
+
+    90 => array(
+        'class:Consent',
+    ),
 
-We reccomend to try to enable the consent module with cookie as a storage, before setting up a database.
+Using storage
+-------------
 
-To enable the consent module, touch an `enable` file, in the consent module:
+The consent module is shipped with two storage options, Cookie and Database.
 
-	touch modules/consent/enable
 
-Then edit `config.php` and look for the `authproc.idp` configuration. Uncomment the followig filter configuration:
+### Using cookies as storage ###
+
+In order to use a storage backend, you need to set the `store` option. To use
+cookies as storage you need to set the `store` option to `consent:Cookie`.
+
+Example: 
 
 	90 => array(
 		'class' 	=> 'consent:Consent', 
 		'store' 	=> 'consent:Cookie', 
-		'focus' 	=> 'yes', 
-		'checked' 	=> TRUE
 	),
 
-Then login through an SP and make sure that you are asked for consent.
 
+### Using a database as storage ###
 
-Setting up a database
----------------------
+In order to use tha database backend storage, you first need to setup the
+database. 
 
-Here is the initialization SQL script for PostgreSQL:
+Here is the initialization SQL script:
 
 	CREATE TABLE consent (
 		consent_date TIMESTAMP NOT NULL,
@@ -55,70 +80,106 @@ Here is the initialization SQL script for PostgreSQL:
 		UNIQUE (hashed_user_id, service_id)
 	);
 
+The `consent:Database` backend storage has the following options
+
+`class`
+:   Must be set to `consent:Database`.
+
+`dsn`
+:   Data Source Name must comply to the syntax for the PHP PDO layer.
+
+`username`
+:   Username for the database user to be used for the connectio.
+
+`password`
+:   Password for the database user used for the connection.
+
+`table`
+:   Name of the table used for storing the consents. This option is optional
+and defaults to `consent`.
+
+Example config using PostgreSQL database:
+
+	90 => array(
+		'class'	=> 'consent:Consent', 
+		'store'	=> array(
+			'consent:Database', 
+			'dsn' => 'pgsql:host=sql.example.org;dbname=consent',
+			'username' => 'simplesaml',
+			'password' => 'sdfsdf',
+		),
+	),
+
+Example config using MySQL database:
 
-Configuring the processing filter
----------------------------------
+	90 => array(
+		'class'	=> 'consent:Consent', 
+		'store'	=> array(
+			'consent:Database', 
+            'dsn' => 'mysql:host=db.example.org;dbname=simplesaml',
+			'username' => 'simplesaml',
+			'password' => 'sdfsdf',
+		),
+	),
+
+
+Options
+-------
 
-### Options ###
 The following options can be used when configuring the Consent module
 
 `ìncludeValues`
 :   Boolean value that indicate whether the values of the attributes should be 
-used in calculating the unique hashes that identifies the consent. If 
-includeValues is set and the value of an attribute changes, then the consent
-becomes invalid. This option is optional and defaults to FALSE. 
+    used in calculating the unique hashes that identifies the consent. If 
+    includeValues is set and the value of an attribute changes, then the 
+    consent becomes invalid. This option is optional and defaults to FALSE. 
 
 `checked`
 :   Boolean value that indicate whether the "Remember" consent checkbox is
-checkd by default. This option is optional and defaults to FALSE. 
+    checkd by default. This option is optional and defaults to FALSE. 
 
 `focus`
 :   Indicates whether the "Yes" or "No" button is in fucus by default. This
-option is optional and can take the value 'yes' or 'no' as strings. If omitted
-neither will recive focus.
+    option is optional and can take the value 'yes' or 'no' as strings. If 
+    omitted neither will recive focus.
 
 `store`
-:   Configuration of the Consent store. See seperate section on setting up
-consent using different storage methods.
+:   Configuration of the Consent storage backend. The store option is given in 
+    the format <module>:<class> and refers to the class 
+    sspmod_<module>_Consent_Store_<class>. The consent module comes with two 
+    build in storages backends 'consnet:Cookie' and 'consent:Database'. See 
+    seperate section on setting up consent using different storage methods. 
+    This option is optional. If option is not set, then the user is asked to 
+    consent, but the consent is not saved.
 
 `hiddenAttributes`
 :   Whether the value of the attributes should be hidden. Set to an array of
-the attributes that should have it value hidden. Default behaviour is that all
-attribute values are shown
+    the attributes that should have it value hidden. Default behaviour is that 
+    all attribute values are shown
+
+
+External options
+----------------
 
-### Options set elswhere ###
-The following options can be set in otherplaces
+The following options can/ be set in other places in simpleSAMLphp
 
 `privacypolicy`
 :   This is an absolute URL for where an user can find a privacy policy for SP. 
-If set, this will be shown on the consent page. %SPENTITYID% in the URL
-will be replaced with the entityID of the service provider.
+    If set, this will be shown on the consent page. %SPENTITYID% in the URL 
+    will be replaced with the entityID of the service provider.
 
-:   This option can be set in [SP-remote metadata](./simplesamlphp-reference-sp-remote) 
-and in [IdP-hosted metadata](./simplesamlphp-reference-idp-hosted). 
-The entry in the SP-remote metadata overrides the option in the IdP-hosted 
-metadata.
+    This option can be set in 
+    [SP-remote metadata](./simplesamlphp-reference-sp-remote) and in 
+    [IdP-hosted metadata](./simplesamlphp-reference-idp-hosted). The entry in 
+    the SP-remote metadata overrides the option in the IdP-hosted metadata.
 
 `consent.disable`
 :   Disable consent for a set of services. See section `Disabling consent`
 
 `userid.attribute`
 :   Unique identifier that is released for all users. See section `Configure
-the user ID`.
+    the user ID`.
 
-Example config using PostgreSQL database:
-
-	90 => array(
-		'class' 	=> 'consent:Consent', 
-		'store' 	=> array(
-			'consent:Database', 
-			'dsn' => 'pgsql:host=sql.uninett.no;dbname=andreas_consent',
-			'username' => 'simplesaml',
-			'password' => 'sdfsdf',
-		),
-		'focus' 	=> 'yes', 
-		'checked' 	=> TRUE
-	),
 
 Disabling consent
 -----------------
@@ -135,6 +196,7 @@ Example:
         'sp2.example.com',
         ...
     ),
+
    
 Attribute presentation
 ----------------------
@@ -162,6 +224,7 @@ If you want the attributes to be listed in more than one level, you can make
 the function add a child_ prefix to the root node attribute name in a recursive 
 attribute tree.
 
+
 ### Examples ###
 
 These values will be listed as an bullet list
diff --git a/modules/consent/lib/Auth/Process/Consent.php b/modules/consent/lib/Auth/Process/Consent.php
index 68cf164c24c1d3475bd0766a31b3082e478a41ab..a7c06e568b76acdff231fc9cfb9cc41bec599f0c 100644
--- a/modules/consent/lib/Auth/Process/Consent.php
+++ b/modules/consent/lib/Auth/Process/Consent.php
@@ -1,147 +1,146 @@
 <?php
 /**
- * Filter for requiring the user to give consent before the attributes are released to the SP.
+ * Consent Authentication Processing filter
  *
- * The initial focus of the consent form can be set by setting the 'focus'-attribute to either
- * 'yes' or 'no'.
- *
- * Different storage backends can be configured by setting the 'store'-attribute. The'store'-attribute
- * is on the form <module>:<class>, and refers to the class sspmod_<module>_Consent_Store_<class>. For
- * examples, see the built-in modules 'consent:Cookie' and 'consent:Database', which can be found
- * under modules/consent/lib/Consent/Store.
- *
- * Example - minimal:
- * <code>
- * 'authproc' => array(
- *   'consent:Consent',
- *   ),
- * </code>
- *
- * Example - save in cookie:
- * <code>
- * 'authproc' => array(
- *   array(
- *     'consent:Consent',
- *     'store' => 'consent:Cookie',
- *   ),
- * </code>
- *
- * Example - save in MySQL database:
- * <code>
- * 'authproc' => array(
- *   array(
- *     'consent:Consent',
- *     'store' => array(
- *       'consent:Database',
- *       'dsn' => 'mysql:host=db.example.org;dbname=simplesaml',
- *       'username' => 'simplesaml',
- *       'password' => 'secretpassword',
- *       ),
- *     ),
- *   ),
- * </code>
- *
- * Example - initial focus on yes-button:
- * <code>
- * 'authproc' => array(
- *   array('consent:Consent', 'focus' => 'yes'),
- *   ),
- * </code>
+ * Filter for requesting the user to give consent before attributes are
+ * released to the SP.
  *
  * @package simpleSAMLphp
  * @version $Id$
  */
-class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilter {
-
+class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilter
+{
     /**
-     * Where the focus should be in the form. Can be 'yesbutton', 'nobutton', or NULL.
+     * Button to recive focus
+     *
+     * @var string|null
      */
-    private $focus;
+    private $_focus = null;
 
     /**
-     * Whether or not to include attribute values when generates hash
+     * Include attribute values
+     *
+     * @var bool
      */
-    private $includeValues;
+    private $_includeValues = false;
 
-    private $checked;
+    /**
+     * Check remember consent
+     *
+     * @var bool
+     */
+    private $_checked = false;
 
     /**
-     * Consent store, if enabled.
+     * Consent backend storage configuration
+     *
+     * @var array
      */
-    private $store;
+    private $_store = null;
 
     /**
-     * List of attributes where the value should be hidden by default.
+     * Attributes where the value should be hidden
      *
      * @var array
      */
-    private $hiddenAttributes;
+    private $_hiddenAttributes = array();
 
-    private $_noconsentattributes;
+    /**
+     * Attributes which should not require consent
+     *
+     * @var aray
+     */
+    private $_noconsentattributes = array();
 
     /**
-     * Initialize consent filter.
+     * Initialize consent filter
      *
-     * This is the constructor for the consent filter. It validates and parses the configuration.
+     * Validates and parses the configuration
      *
-     * @param array $config  Configuration information about this filter.
-     * @param mixed $reserved  For future use.
+     * @param array $config   Configuration information
+     * @param mixed $reserved For future use
      */
-    public function __construct($config, $reserved) {
-        parent::__construct($config, $reserved);
+    public function __construct($config, $reserved)
+    {
         assert('is_array($config)');
+        parent::__construct($config, $reserved);
 
-        $this->includeValues = FALSE;
         if (array_key_exists('includeValues', $config)) {
-            $this->includeValues = $config['includeValues'];
+            if (!is_bool($config['includeValues'])) {
+                throw new SimpleSAML_Error_Exception(
+                    'Consent: includeValues must be boolean. ' .
+                    var_export($config['includeValues']) . ' given.'
+                );
+            }
+            $this->_includeValues = $config['includeValues'];
         }
 
-        $this->checked = FALSE;
         if (array_key_exists('checked', $config)) {
-            $this->checked = $config['checked'];
+            if (!is_bool($config['checked'])) {
+                throw new SimpleSAML_Error_Exception(
+                    'Consent: checked must be boolean. ' .
+                    var_export($config['checked']) . ' given.'
+                );
+            }
+            $this->_checked = $config['checked'];
         }
 
         if (array_key_exists('focus', $config)) {
-            $this->focus = $config['focus'];
-            if (!in_array($this->focus, array('yes', 'no'), TRUE)) {
-                throw new Exception('Invalid value for \'focus\'-parameter to' .
-                    ' consent:Consent authentication filter: ' . var_export($this->focus, TRUE));
+            if (!in_array($config['focus'], array('yes', 'no'), true)) {
+                throw new SimpleSAML_Error_Exception(
+                    'Consent: focus must be a string with values `yes` or `no`. ' .
+                    var_export($config['focus']) . ' given.'
+                );
             }
-        } else {
-            $this->focus = NULL;
+            $this->_focus = $config['focus'];
         }
 
-        $this->store = NULL;
-        if (array_key_exists('store', $config)) {
-            try {
-                $this->store = sspmod_consent_Store::parseStoreConfig($config['store']);
-            } catch(Exception $e) {
-                SimpleSAML_Logger::error('Consent - constructor() : Could not create consent storage: ' . $e->getMessage());
-            }
-        } 
-
         if (array_key_exists('hiddenAttributes', $config)) {
-            $this->hiddenAttributes = $config['hiddenAttributes'];
-        } else {
-            $this->hiddenAttributes = array();
+            if (!is_array($config['hiddenAttributes'])) {
+                throw new SimpleSAML_Error_Exception(
+                    'Consent: hiddenAttributes must be an array. ' .
+                    var_export($config['hiddenAttributes']) . ' given.'
+                );
+            }
+            $this->_hiddenAttributes = $config['hiddenAttributes'];
         }
 
         if (array_key_exists('noconsentattributes', $config)) {
+            if (!is_array($config['noconsentattributes'])) {
+                throw new SimpleSAML_Error_Exception(
+                    'Consent: noconsentattributes must be an array. ' .
+                    var_export($config['noconsentattributes']) . ' given.'
+                );
+            }
             $this->_noconsentattributes = $config['noconsentattributes'];
-        } else {
-            $this->_noconsentattributes = array();
         }
+        
+        if (array_key_exists('store', $config)) {
+            try {
+                $this->_store = sspmod_consent_Store::parseStoreConfig($config['store']);
+            } catch(Exception $e) {
+                SimpleSAML_Logger::error(
+                    'Consent: Could not create consent storage: ' .
+                    $e->getMessage()
+                );
+            }
+        } 
     }
 
     /**
-     * Process a authentication response.
+     * Process a authentication response
+     *
+     * This function saves the state, and redirects the user to the page where
+     * the user can authorize the release of the attributes.
+     * If storage is used and the consent has already been given the user is 
+     * passed on.
      *
-     * This function saves the state, and redirects the user to the page where the user
-     * can authorize the release of the attributes.
+     * @param array &$state The state of the response.
      *
-     * @param array $state  The state of the response.
+     * @return void
      */
-    public function process(&$state) {
+    public function process(&$state)
+    {
         assert('is_array($state)');
         assert('array_key_exists("UserID", $state)');
         assert('array_key_exists("Destination", $state)');
@@ -150,107 +149,135 @@ class sspmod_consent_Auth_Process_Consent extends SimpleSAML_Auth_ProcessingFilt
         assert('array_key_exists("entityid", $state["Source"])');
         assert('array_key_exists("metadata-set", $state["Source"])');
 
-        $session = SimpleSAML_Session::getInstance(); 
+        $session  = SimpleSAML_Session::getInstance(); 
         $metadata = SimpleSAML_Metadata_MetaDataStorageHandler::getMetadataHandler();
 
-        /* If the consent module is active on a bridge $state['saml:sp:IdP'] will contain
-         * an entry id for the remote IdP. If not, then the
-         * consent module is active on a local IdP and nothing needs to be done.
+        /**
+         * If the consent module is active on a bridge $state['saml:sp:IdP']
+         * will contain an entry id for the remote IdP. If not, then the
+         * consent module is active on a local IdP and nothing needs to be
+         * done.
          */
-        if(isset($state['saml:sp:IdP'])) {
-            $idpmeta = $metadata->getMetaData($state['saml:sp:IdP'], 'saml20-idp-remote');
+        if (isset($state['saml:sp:IdP'])) {
+            $idpmeta         = $metadata->getMetaData($state['saml:sp:IdP'], 'saml20-idp-remote');
             $state['Source'] = $idpmeta;
-        } elseif($session->getIdP() !== NULL) {
-            /* For backwards compatibility. TODO: Remove in version 1.8. */
-            $idpmeta = $metadata->getMetaData($session->getIdP(), 'saml20-idp-remote');
+        } elseif ($session->getIdP() !== null) {
+            // For backwards compatibility. TODO: Remove in version 1.8
+            $idpmeta         = $metadata->getMetaData($session->getIdP(), 'saml20-idp-remote');
             $state['Source'] = $idpmeta;
         }
 
-        if ($this->store !== NULL) {
+        if ($this->_store !== null) {
             // Do not use consent if disabled on source entity 
-            if(isset($state['Source']['consent.disable']) && in_array($state['Destination']['entityid'], $state['Source']['consent.disable'])) {
-                SimpleSAML_Logger::debug('Consent - Consent disabled for entity ' . $state['Destination']['entityid']);
+            if ( isset($state['Source']['consent.disable']) && in_array($state['Destination']['entityid'], $state['Source']['consent.disable'])) {
+                SimpleSAML_Logger::debug(
+                    'Consent: Consent disabled for entity ' .
+                    $state['Destination']['entityid']
+                );
                 return;
             }
 
-            $source = $state['Source']['metadata-set'] . '|' . $state['Source']['entityid'];
+            $source      = $state['Source']['metadata-set'] . '|' . $state['Source']['entityid'];
             $destination = $state['Destination']['metadata-set'] . '|' . $state['Destination']['entityid'];
-            $attributes = $state['Attributes'];
+            $attributes  = $state['Attributes'];
 
             // Remove attributes that do not require consent
-            foreach($attributes AS $attrkey => $attrval) {
-                if(in_array($attrkey, $this->_noconsentattributes)) {
+            foreach ($attributes AS $attrkey => $attrval) {
+                if (in_array($attrkey, $this->_noconsentattributes)) {
                     unset($attributes[$attrkey]);
                 }
             }
 
-            SimpleSAML_Logger::debug('Consent - userid : ' . $state['UserID']);
-            SimpleSAML_Logger::debug('Consent - source : ' . $source);
-            SimpleSAML_Logger::debug('Consent - destination : ' . $destination);
-
-            $userId = self::getHashedUserID($state['UserID'], $source);
-            $targetedId = self::getTargetedID($state['UserID'], $source, $destination);
-            $attributeSet = self::getAttributeHash($attributes, $this->includeValues);
-
-            SimpleSAML_Logger::debug('Consent - hasConsent() : [' . $userId . '|' . $targetedId . '|' .  $attributeSet . ']');
-            if ($this->store->hasConsent($userId, $targetedId, $attributeSet)) {
-
-                SimpleSAML_Logger::stats('consent found');
-
-                /* Consent already given. */
+            SimpleSAML_Logger::debug('Consent: userid: ' . $state['UserID']);
+            SimpleSAML_Logger::debug('Consent: source: ' . $source);
+            SimpleSAML_Logger::debug('Consent: destination: ' . $destination);
+
+            $userId       = self::getHashedUserID($state['UserID'], $source);
+            $targetedId   = self::getTargetedID($state['UserID'], $source, $destination);
+            $attributeSet = self::getAttributeHash($attributes, $this->_includeValues);
+
+            SimpleSAML_Logger::debug(
+                'Consent: hasConsent() [' . $userId . '|' . $targetedId . '|' .
+                $attributeSet . ']'
+            );
+            
+            if ($this->_store->hasConsent($userId, $targetedId, $attributeSet)) {
+                // Consent already given
+                SimpleSAML_Logger::stats('Consent: Consent found');
                 return;
             }
-            SimpleSAML_Logger::stats('consent notfound');
 
-            $state['consent:store'] = $this->store;
-            $state['consent:store.userId'] = $userId;
-            $state['consent:store.destination'] = $targetedId;
-            $state['consent:store.attributeSet'] = $attributeSet;
+            SimpleSAML_Logger::stats('Consent: Consent notfound');
 
+            $state['consent:store']              = $this->_store;
+            $state['consent:store.userId']       = $userId;
+            $state['consent:store.destination']  = $targetedId;
+            $state['consent:store.attributeSet'] = $attributeSet;
         } else {
-            SimpleSAML_Logger::stats('consent nostorage');
+            SimpleSAML_Logger::stats('Consent: No storage');
         }
 
-        $state['consent:focus'] = $this->focus;
-        $state['consent:checked'] = $this->checked;
-        $state['consent:hiddenAttributes'] = $this->hiddenAttributes;
+        $state['consent:focus']               = $this->_focus;
+        $state['consent:checked']             = $this->_checked;
+        $state['consent:hiddenAttributes']    = $this->_hiddenAttributes;
         $state['consent:noconsentattributes'] = $this->_noconsentattributes;
 
-        /* User interaction nessesary. Throw exception on isPassive request */	
-        if (isset($state['isPassive']) && $state['isPassive'] == TRUE) {
-            throw new SimpleSAML_Error_NoPassive('Unable to give consent on passive request.');
+        // User interaction nessesary. Throw exception on isPassive request	
+        if (isset($state['isPassive']) && $state['isPassive'] == true) {
+            throw new SimpleSAML_Error_NoPassive(
+                'Unable to give consent on passive request.'
+            );
         }
 
-        /* Save state and redirect. */
-        $id = SimpleSAML_Auth_State::saveState($state, 'consent:request');
+        // Save state and redirect
+        $id  = SimpleSAML_Auth_State::saveState($state, 'consent:request');
         $url = SimpleSAML_Module::getModuleURL('consent/getconsent.php');
         SimpleSAML_Utilities::redirect($url, array('StateId' => $id));
     }
 
-
     /**
-     * Generate a globally unique identifier of the user. Will also be anonymous (hashed).
+     * Generate a unique identifier of the user
+     * 
+     * @param string $userid The user id
+     * @param string $source The source id
      *
-     * @return hash( eduPersonPrincipalName + salt + IdP-identifier ) 
+     * @return string SHA1 of the user id, source id and salt 
      */
-    public static function getHashedUserID($userid, $source) {		
-        return hash('sha1', $userid . '|'  . SimpleSAML_Utilities::getSecretSalt() . '|' . $source );
+    public static function getHashedUserID($userid, $source)
+    {
+        return hash('sha1', $userid . '|' . SimpleSAML_Utilities::getSecretSalt() . '|' . $source);
     }
 
     /**
-     * Get a targeted ID. An identifier that is unique per SP entity ID.
+     * Generate a unique targeted identifier
+     *
+     * @param string $userid      The user id
+     * @param string $source      The source id
+     * @param string $destination The destination id
+     *
+     * @return string SHA1 of the user id, source id, destination id and salt 
      */
-    public static function getTargetedID($userid, $source, $destination) {
+    public static function getTargetedID($userid, $source, $destination)
+    {
         return hash('sha1', $userid . '|' . SimpleSAML_Utilities::getSecretSalt() . '|' . $source . '|' . $destination);
     }
 
     /**
-     * Get a hash value that changes when attributes are added or attribute values changed.
-     * @param boolean $includeValues Whether or not to include the attribute value in the generation of the hash.
+     * Generate unique identitier for attributes
+     *
+     * Create a hash value for the attributes that changes when attributes are
+     * added or removed. If the attribute values are included in the hash, the 
+     * hash will change if the values change.
+     *
+     * @param string $attributes    The attributes
+     * @param bool   $includeValues Whether or not to include the attribute
+     *                              value in the generation of the hash.
+     *
+     * @return string SHA1 of the user id, source id, destination id and salt 
      */
-    public static function getAttributeHash($attributes, $includeValues = FALSE) {
-
-        $hashBase = NULL;	
+    public static function getAttributeHash($attributes, $includeValues = false)
+    {
+        $hashBase = null;	
         if ($includeValues) {
             ksort($attributes);
             $hashBase = serialize($attributes);
diff --git a/modules/consent/lib/Consent/Store/Cookie.php b/modules/consent/lib/Consent/Store/Cookie.php
index 3fbfe5fd554d34804d781d7f8f1cb1bdbf848bdb..d0e638e945e6745103dca8dea17d629415d8c957 100644
--- a/modules/consent/lib/Consent/Store/Cookie.php
+++ b/modules/consent/lib/Consent/Store/Cookie.php
@@ -1,12 +1,12 @@
 <?php
-
 /**
- * Store consent in cookies.
+ * Cookie storage for consent
  *
- * This class implements a consent store which stores the consent information in
- * cookies on the users computer.
+ * This class implements a consent store which stores the consent information
+ * in cookies on the users computer.
  *
  * Example - Consent module with cookie store:
+ * 
  * <code>
  * 'authproc' => array(
  *   array(
@@ -16,251 +16,276 @@
  *   ),
  * </code>
  *
- *
+ * @author  Olav Morken <olav.morken@uninett.no>
  * @package simpleSAMLphp
  * @version $Id$
  */
-class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store {
-
-
-	/**
-	 * Check for consent.
-	 *
-	 * This function checks whether a given user has authorized the release of the attributes
-	 * identified by $attributeSet from $source to $destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 * @return bool  TRUE if the user has given consent earlier, FALSE if not (or on error).
-	 */
-	public function hasConsent($userId, $destinationId, $attributeSet) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-		assert('is_string($attributeSet)');
-
-		$cookieName = self::getCookieName($userId, $destinationId);
-		
-		$data = $userId . ':' . $attributeSet . ':' . $destinationId;
-		
-		SimpleSAML_Logger::debug('Consent cookie - Get [' . $data . ']');
-
-		if (!array_key_exists($cookieName, $_COOKIE)) {
-			SimpleSAML_Logger::debug('Consent cookie - no cookie with name \'' . $cookieName . '\'.');
-			return FALSE;
-		}
-		if (!is_string($_COOKIE[$cookieName])) {
-			SimpleSAML_Logger::warning('Value of consent cookie wasn\'t a string. Was: ' . var_export($_COOKIE[$cookieName], TRUE));
-			return FALSE;
-		}
-
-
-		
-		$data = self::sign($data);
-
-		if ($_COOKIE[$cookieName] !== $data) {
-			SimpleSAML_Logger::info('Attribute set changed from the last time consent was given.');
-			return FALSE;
-		}
-
-		SimpleSAML_Logger::debug('Consent cookie - found cookie with correct name and value.');
-
-		return TRUE;
-	}
-
-
-	/**
-	 * Save consent.
-	 *
-	 * Called when the user asks for the consent to be saved. If consent information
-	 * for the given user and destination already exists, it should be overwritten.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 */
-	public function saveConsent($userId, $destinationId, $attributeSet) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-		assert('is_string($attributeSet)');
-
-		$name = self::getCookieName($userId, $destinationId);
-		$value = $userId . ':' . $attributeSet . ':' . $destinationId;
-		
-		SimpleSAML_Logger::debug('Consent cookie - Set [' . $value . ']');
-		
-		$value = self::sign($value);
-		$this->setConsentCookie($name, $value);
-	}
-
-
-	/**
-	 * Delete consent.
-	 *
-	 * Called when a user revokes consent for a given destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 */
-	public function deleteConsent($userId, $destinationId) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-
-		$name = self::getCookieName($userId, $destinationId);
-		$this->setConsentCookie($name, NULL);
-
-	}
-	
-	/**
-	 * Delete consent.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 */
-	public function deleteAllConsents($userId) {
-		assert('is_string($userId)');
-
-		throw new Exception('The cookie consent handler does not support to delete all consents...');
-	}
-
-
-	/**
-	 * Retrieve consents.
-	 *
-	 * This function should return a list of consents the user has saved.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @return array  Array of all destination ids the user has given consent for.
-	 */
-	public function getConsents($userId) {
-		assert('is_string($userId)');
-
-		$ret = array();
-
-		$cookieNameStart = 'sspmod_consent:';
-		$cookieNameStartLen = strlen($cookieNameStart);
-		foreach ($_COOKIE as $name => $value) {
-
-			if (substr($name, 0, $cookieNameStartLen) !== $cookieNameStart) {
-				continue;
-			}
-
-			$value = self::verify($value);
-			if ($value === FALSE) {
-				continue;
-			}
-
-			$tmp = explode(':', $value, 3);
-			if (count($tmp) !== 3) {
-				SimpleSAML_Logger::warning('Consent cookie with invalid value: ' . $value);
-				continue;
-			}
-
-			if ($userId !== $tmp[0]) {
-				/* Wrong user. */
-				continue;
-			}
-
-			$destination = $tmp[2];
-
-
-			$ret[] = $destination;
-		}
-
-		return $ret;
-	}
-
-
-	/**
-	 * Calculate a signature of some data.
-	 *
-	 * This function calculates a signature of the data.
-	 *
-	 * @param string $data  The data which should be signed.
-	 * @return string  The signed data.
-	 */
-	private static function sign($data) {
-		assert('is_string($data)');
-
-		$secretSalt = SimpleSAML_Utilities::getSecretSalt();
-
-		return sha1($secretSalt . $data . $secretSalt) . ':' . $data;
-	}
-
-
-	/**
-	 * Verify signed data.
-	 *
-	 * This function verifies signed data.
-	 *
-	 * @param string $signedData  The data which is signed.
-	 * @return string|FALSE  The data, or FALSE if the signature is invalid.
-	 */
-	private static function verify($signedData) {
-		assert('is_string($signedData)');
-
-		$data = explode(':', $signedData, 2);
-		if (count($data) !== 2) {
-			SimpleSAML_Logger::warning('Consent cookie: Missing signature.');
-			return FALSE;
-		}
-		$data = $data[1];
-
-		$newSignedData = self::sign($data);
-		if ($newSignedData !== $signedData) {
-			SimpleSAML_Logger::warning('Consent cookie: Invalid signature.');
-			return FALSE;
-		}
-
-		return $data;
-	}
-
-
-	/**
-	 * Get cookie name.
-	 *
-	 * This function gets the cookie name for the given user & destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 */
-	private static function getCookieName($userId, $destinationId) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-
-		return 'sspmod_consent:' . sha1($userId . ':' . $destinationId);
-	}
-
-
-	/**
-	 * Helper function for setting a cookie.
-	 *
-	 * @param string $name  Name of the cookie.
-	 * @param string|NULL $value  Value of the cookie. Set this to NULL to delete the cookie.
-	 */
-	private function setConsentCookie($name, $value) {
-		assert('is_string($name)');
-		assert('is_string($value)');
-
-		if ($value === NULL) {
-			$expire = 1; /* Delete by setting expiry in the past. */
-			$value = '';
-		} else {
-			$expire = time() + 90 * 24*60*60;
-		}
-
-		if (SimpleSAML_Utilities::isHTTPS()) {
-			/* Enable secure cookie for https-requests. */
-			$secure = TRUE;
-		} else {
-			$secure = FALSE;
-		}
-
-		$globalConfig = SimpleSAML_Configuration::getInstance();
-		$path = '/' . $globalConfig->getBaseURL();
-
-		setcookie($name, $value, $expire, $path, NULL, $secure);
-	}
+class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
+{
+    /**
+     * Check for consent.
+     *
+     * This function checks whether a given user has authorized the release of
+     * the attributes identified by $attributeSet from $source to $destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return bool True if the user has given consent earlier, false if not
+     *              (or on error).
+     */
+    public function hasConsent($userId, $destinationId, $attributeSet)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+        assert('is_string($attributeSet)');
+
+        $cookieName = self::_getCookieName($userId, $destinationId);
+
+        $data = $userId . ':' . $attributeSet . ':' . $destinationId;
+
+        SimpleSAML_Logger::debug('Consent cookie - Get [' . $data . ']');
+
+        if (!array_key_exists($cookieName, $_COOKIE)) {
+            SimpleSAML_Logger::debug(
+                'Consent cookie - no cookie with name \'' .
+                $cookieName . '\'.'
+            );
+            return false;
+        }
+        if (!is_string($_COOKIE[$cookieName])) {
+            SimpleSAML_Logger::warning(
+                'Value of consent cookie wasn\'t a string. Was: ' .
+                var_export($_COOKIE[$cookieName], true)
+            );
+            return false;
+        }
+
+        $data = self::_sign($data);
+
+        if ($_COOKIE[$cookieName] !== $data) {
+            SimpleSAML_Logger::info(
+                'Attribute set changed from the last time consent was given.'
+            );
+            return false;
+        }
+
+        SimpleSAML_Logger::debug(
+            'Consent cookie - found cookie with correct name and value.'
+        );
+
+        return true;
+    }
+
+    /**
+     * Save consent.
+     *
+     * Called when the user asks for the consent to be saved. If consent information
+     * for the given user and destination already exists, it should be overwritten.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return void
+     */
+    public function saveConsent($userId, $destinationId, $attributeSet)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+        assert('is_string($attributeSet)');
+
+        $name = self::_getCookieName($userId, $destinationId);
+        $value = $userId . ':' . $attributeSet . ':' . $destinationId;
+
+        SimpleSAML_Logger::debug('Consent cookie - Set [' . $value . ']');
+
+        $value = self::_sign($value);
+        $this->_setConsentCookie($name, $value);
+    }
+
+    /**
+     * Delete consent.
+     *
+     * Called when a user revokes consent for a given destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     *
+     * @return void
+     */
+    public function deleteConsent($userId, $destinationId)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+
+        $name = self::_getCookieName($userId, $destinationId);
+        $this->_setConsentCookie($name, null);
+    }
+
+    /**
+     * Delete consent.
+     *
+     * @param string $userId The hash identifying the user at an IdP.
+     *
+     * @return void
+     */
+    public function deleteAllConsents($userId)
+    {
+        assert('is_string($userId)');
+
+        throw new Exception(
+            'The cookie consent handler does not support delete of all consents...'
+        );
+    }
+
+    /**
+     * Retrieve consents.
+     *
+     * This function should return a list of consents the user has saved.
+     *
+     * @param string $userId The hash identifying the user at an IdP.
+     * 
+     * @return array Array of all destination ids the user has given consent for.
+     */
+    public function getConsents($userId)
+    {
+        assert('is_string($userId)');
+
+        $ret = array();
+
+        $cookieNameStart = 'sspmod_consent:';
+        $cookieNameStartLen = strlen($cookieNameStart);
+        foreach ($_COOKIE as $name => $value) {
+            if (substr($name, 0, $cookieNameStartLen) !== $cookieNameStart) {
+                continue;
+            }
+
+            $value = self::_verify($value);
+            if ($value === false) {
+                continue;
+            }
+
+            $tmp = explode(':', $value, 3);
+            if (count($tmp) !== 3) {
+                SimpleSAML_Logger::warning(
+                    'Consent cookie with invalid value: ' . $value
+                );
+                continue;
+            }
+
+            if ($userId !== $tmp[0]) {
+                // Wrong user
+                continue;
+            }
+
+            $destination = $tmp[2];
+            $ret[] = $destination;
+        }
+
+        return $ret;
+    }
+
+    /**
+     * Calculate a signature of some data.
+     *
+     * This function calculates a signature of the data.
+     *
+     * @param string $data The data which should be signed.
+     * 
+     * @return string The signed data.
+     */
+    private static function _sign($data)
+    {
+        assert('is_string($data)');
+
+        $secretSalt = SimpleSAML_Utilities::getSecretSalt();
+
+        return sha1($secretSalt . $data . $secretSalt) . ':' . $data;
+    }
+
+    /**
+     * Verify signed data.
+     *
+     * This function verifies signed data.
+     *
+     * @param string $signedData The data which is signed.
+     * 
+     * @return string|false The data, or false if the signature is invalid.
+     */
+    private static function _verify($signedData)
+    {
+        assert('is_string($signedData)');
+
+        $data = explode(':', $signedData, 2);
+        if (count($data) !== 2) {
+            SimpleSAML_Logger::warning('Consent cookie: Missing signature.');
+            return false;
+        }
+        $data = $data[1];
+
+        $newSignedData = self::_sign($data);
+        if ($newSignedData !== $signedData) {
+            SimpleSAML_Logger::warning('Consent cookie: Invalid signature.');
+            return false;
+        }
+
+        return $data;
+    }
+
+    /**
+     * Get cookie name.
+     *
+     * This function gets the cookie name for the given user & destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     *
+     * @return string The cookie name
+     */
+    private static function _getCookieName($userId, $destinationId)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+
+        return 'sspmod_consent:' . sha1($userId . ':' . $destinationId);
+    }
+
+    /**
+     * Helper function for setting a cookie.
+     *
+     * @param string      $name  Name of the cookie.
+     * @param string|null $value Value of the cookie. Set this to null to
+     *                           delete the cookie.
+     *
+     * @return void
+     */
+    private function _setConsentCookie($name, $value)
+    {
+        assert('is_string($name)');
+        assert('is_string($value)');
+
+        if ($value === null) {
+            $expire = 1; /* Delete by setting expiry in the past. */
+            $value = '';
+        } else {
+            $expire = time() + 90 * 24*60*60;
+        }
+
+        if (SimpleSAML_Utilities::isHTTPS()) {
+            /* Enable secure cookie for https-requests. */
+            $secure = true;
+        } else {
+            $secure = false;
+        }
+
+        $globalConfig = SimpleSAML_Configuration::getInstance();
+        $path = '/' . $globalConfig->getBaseURL();
+
+        setcookie($name, $value, $expire, $path, null, $secure);
+    }
 
 }
 
-?>
\ No newline at end of file
+?>
diff --git a/modules/consent/lib/Consent/Store/Database.php b/modules/consent/lib/Consent/Store/Database.php
index 5d7480fff5b293a82377f215f59bd66f0d5cf7c3..5ec4a46586951263ff34131d658c8dbfa8b95390 100644
--- a/modules/consent/lib/Consent/Store/Database.php
+++ b/modules/consent/lib/Consent/Store/Database.php
@@ -1,425 +1,478 @@
 <?php
-
 /**
  * Store consent in database.
  *
- * This class implements a consent store which stores the consent information in
- * a database. It is tested, and should work against both MySQL and PostgreSQL.
+ * This class implements a consent store which stores the consent information
+ * in a database. It is tested, and should work against both MySQL and
+ * PostgreSQL.
  *
  * It has the following options:
- * - dsn: The DSN which should be used to connect to the database server. Check the various
- *        database drivers in http://php.net/manual/en/pdo.drivers.php for a description of
- *        the various DSN formats.
- * - username: The username which should be used when connecting to the database server.
- * - password: The password which should be used when connecting to the database server.
- * - table: The name of the table. Optional, defaults to 'consent'.
- *
- * Example - consent module with MySQL database:
- * <code>
- * 'authproc' => array(
- *   array(
- *     'consent:Consent',
- *     'store' => array(
- *       'consent:Database',
- *       'dsn' => 'mysql:host=db.example.org;dbname=simplesaml',
- *       'username' => 'simplesaml',
- *       'password' => 'secretpassword',
- *       ),
- *     ),
- *   ),
- * </code>
- *
- * Example - consent module with PostgreSQL database:
- * <code>
- * 'authproc' => array(
- *   array(
- *     'consent:Consent',
- *     'store' => array(
- *       'consent:Database',
- *       'dsn' => 'pgsql:host=db.example.org;port=5432;dbname=simplesaml',
- *       'username' => 'simplesaml',
- *       'password' => 'secretpassword',
- *       ),
- *     ),
- *   ),
- * </code>
- *
- *
- * Table declaration:
- * CREATE TABLE consent (
- *   consent_date TIMESTAMP NOT NULL,
- *   usage_date TIMESTAMP NOT NULL,
- *   hashed_user_id VARCHAR(80) NOT NULL,
- *   service_id VARCHAR(255) NOT NULL,
- *   attribute VARCHAR(80) NOT NULL,
- *   UNIQUE (hashed_user_id, service_id)
- * );
+ * - dsn: The DSN which should be used to connect to the database server. See 
+ *        PHP Manual for supported drivers and DSN formats.
+ * - username: The username used for database connection.
+ * - password: The password used for database connection.
+ * - table: The name of the table used. Optional, defaults to 'consent'.
  *
+ * @author  Olav Morken <olav.morken@uninett.no>
  * @package simpleSAMLphp
  * @version $Id$
  */
-class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store {
-
-
-	/**
-	 * DSN for the database.
-	 */
-	private $dsn;
-
-
-	/**
-	 * Username for the database.
-	 */
-	private $username;
-
-
-	/**
-	 * Password for the database;
-	 */
-	private $password;
-
-
-	/**
-	 * Table with consent.
-	 */
-	private $table;
-
-
-	/**
-	 * Database handle.
-	 *
-	 * This variable can't be serialized.
-	 */
-	private $db;
-
-
-	/**
-	 * Parse configuration.
-	 *
-	 * This constructor parses the configuration.
-	 *
-	 * @param array $config  Configuration for database consent store.
-	 */
-	public function __construct($config) {
-		parent::__construct($config);
-
-		foreach (array('dsn', 'username', 'password') as $id) {
-			if (!array_key_exists($id, $config)) {
-				throw new Exception('consent:Database - Missing required option \'' . $id . '\'.');
-			}
-			if (!is_string($config[$id])) {
-				throw new Exception('consent:Database - \'' . $id . '\' is supposed to be a string.');
-			}
-		}
-
-		$this->dsn = $config['dsn'];
-		$this->username = $config['username'];
-		$this->password = $config['password'];
-
-		if (array_key_exists('table', $config)) {
-			if (!is_string($config['table'])) {
-				throw new Exception('consent:Database - \'table\' is supposed to be a string.');
-			}
-			$this->table = $config['table'];
-		} else {
-			$this->table = 'consent';
-		}
-		
-		$db = $this->getDB();
-	}
-
-
-	/**
-	 * Called before serialization.
-	 *
-	 * @return array  The variables which should be serialized.
-	 */
-	public function __sleep() {
-
-		return array(
-			'dsn',
-			'username',
-			'password',
-			'table',
-			);
-	}
-
-
-	/**
-	 * Check for consent.
-	 *
-	 * This function checks whether a given user has authorized the release of the attributes
-	 * identified by $attributeSet from $source to $destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 * @return bool  TRUE if the user has given consent earlier, FALSE if not (or on error).
-	 */
-	public function hasConsent($userId, $destinationId, $attributeSet) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-		assert('is_string($attributeSet)');
-
-		$st = $this->execute('UPDATE ' . $this->table . ' SET usage_date = NOW() WHERE hashed_user_id = ? AND service_id = ? AND attribute = ?',
-			array($userId, $destinationId, $attributeSet));
-		if ($st === FALSE) {
-			return FALSE;
-		}
-
-		$rowCount = $st->rowCount();
-		if ($rowCount === 0) {
-			SimpleSAML_Logger::debug('consent:Database - No consent found.');
-			return FALSE;
-		} else {
-			SimpleSAML_Logger::debug('consent:Database - Consent found.');
-			return TRUE;
-		}
-
-	}
-
-
-	/**
-	 * Save consent.
-	 *
-	 * Called when the user asks for the consent to be saved. If consent information
-	 * for the given user and destination already exists, it should be overwritten.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 */
-	public function saveConsent($userId, $destinationId, $attributeSet) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-		assert('is_string($attributeSet)');
-
-		/* Check for old consent (with different attribute set). */
-		$st = $this->execute('UPDATE ' . $this->table . ' SET consent_date = NOW(), usage_date = NOW(), attribute = ? WHERE hashed_user_id = ? AND service_id = ?',
-			array($attributeSet, $userId, $destinationId));
-		if ($st === FALSE) {
-			return;
-		}
-		if ($st->rowCount() > 0) {
-			/* We had already stored consent for the given destination in the database. */
-			SimpleSAML_Logger::debug('consent:Database - Updated old consent.');
-			return;
-		}
-
-		/* Add new consent. We don't check for error since there is nothing we can do if one occurs. */
-		$st = $this->execute('INSERT INTO ' . $this->table . ' (consent_date, usage_date, hashed_user_id, service_id, attribute) VALUES(NOW(),NOW(),?,?,?)',
-			array($userId, $destinationId, $attributeSet));
-		if ($st !== FALSE) {
-			SimpleSAML_Logger::debug('consent:Database - Saved new consent.');
-		}
-		return TRUE;
-	}
-
-
-	/**
-	 * Delete consent.
-	 *
-	 * Called when a user revokes consent for a given destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifies the destination.
-	 */
-	public function deleteConsent($userId, $destinationId) {
-		assert('is_string($userId)');
-		assert('is_string($destinationId)');
-
-		$st = $this->execute('DELETE FROM ' . $this->table . ' WHERE hashed_user_id = ? and service_id = ?',
-			array($userId, $destinationId));
-		if ($st === FALSE) {
-			return;
-		}
-
-		if ($st->rowCount() > 0) {
-			SimpleSAML_Logger::debug('consent:Database - Deleted consent.');
-			return $st->rowCount();
-		} else {
-			SimpleSAML_Logger::warning('consent:Database - Attempted to delete nonexistent consent');
-		}
-	}
-
-	/**
-	 * Delete all consents.
- 	 * 
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 */
-	public function deleteAllConsents($userId) {
-		assert('is_string($userId)');
-
-		$st = $this->execute('DELETE FROM ' . $this->table . ' WHERE hashed_user_id = ?', array($userId));
-		if ($st === FALSE) return;
-
-		if ($st->rowCount() > 0) {
-			SimpleSAML_Logger::debug('consent:Database - Deleted (' . $st->rowCount() . ') consent(s).');
-			return $st->rowCount();
-		} else {
-			SimpleSAML_Logger::warning('consent:Database - Attempted to delete nonexistent consent');
-		}
-	}
-
-
-	/**
-	 * Retrieve consents.
-	 *
-	 * This function should return a list of consents the user has saved.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @return array  Array of all destination ids the user has given consent for.
-	 */
-	public function getConsents($userId) {
-		assert('is_string($userId)');
-
-		$ret = array();
-
-		$st = $this->execute('SELECT service_id, attribute, consent_date, usage_date FROM ' . $this->table . ' WHERE hashed_user_id = ?',
-			array($userId));
-		if ($st === FALSE) {
-			return array();
-		}
-
-		while ($row = $st->fetch(PDO::FETCH_NUM)) {
-			$ret[] = $row;
-		}
-
-		return $ret;
-	}
-
-
-	/**
-	 * Prepare and execute statement.
-	 *
-	 * This function prepares and executes a statement. On error, FALSE will be returned.
-	 *
-	 * @param string $statement  The statement which should be executed.
-	 * @param array $parameters  Parameters for the statement.
-	 * @return PDOStatement|FALSE  The statement, or FALSE if execution failed.
-	 */
-	private function execute($statement, $parameters) {
-		assert('is_string($statement)');
-		assert('is_array($parameters)');
-
-		$db = $this->getDB();
-		if ($db === FALSE) {
-			return FALSE;
-		}
-
-		$st = $db->prepare($statement);
-		if ($st === FALSE) {
-			if ($st === FALSE) {
-				SimpleSAML_Logger::error('consent:Database - Error preparing statement \'' .
-					$statement . '\': ' . self::formatError($db->errorInfo()));
-				return FALSE;
-			}
-		}
-
-		if ($st->execute($parameters) !== TRUE) {
-			SimpleSAML_Logger::error('consent:Database - Error executing statement \'' .
-				$statement . '\': ' . self::formatError($st->errorInfo()));
-			return FALSE;
-		}
-
-		return $st;
-	}
-
-
-	/**
-	 * get statistics
-	 *
-	 */
-	public function getStatistics() {
-		$ret = array();
-
-		$st = $this->execute('select count(*) as no from consent', array());
-		if ($st === FALSE) return array(); 
-		if($row = $st->fetch(PDO::FETCH_NUM)) $ret['total'] = $row[0];
-
-		$st = $this->execute('select count(*) as no from (select distinct hashed_user_id from consent ) as foo', array());
-		if ($st === FALSE) return array(); 
-		if($row = $st->fetch(PDO::FETCH_NUM)) $ret['users'] = $row[0];
-
-		$st = $this->execute('select count(*) as no from (select distinct service_id from consent ) as foo', array());
-		if ($st === FALSE) return array();
-		if($row = $st->fetch(PDO::FETCH_NUM)) $ret['services'] = $row[0];
-
-		return $ret;
-	}
-	
-	
-	
-	
-	/**
-	 * Create consent table.
-	 *
-	 * This function creates the table with consent data.
-	 *
-	 * @return TRUE if successful, FALSE if not.
-	 */
-	private function createTable() {
-
-		$db = $this->getDB();
-		if ($db === FALSE) {
-			return FALSE;
-		}
-
-		$res = $this->db->exec(
-			'CREATE TABLE ' . $this->table . ' (' .
-			'consent_date TIMESTAMP NOT NULL,' .
-			'usage_date TIMESTAMP NOT NULL,' .
-			'hashed_user_id VARCHAR(80) NOT NULL,' .
-			'service_id VARCHAR(255) NOT NULL,' .
-			'attribute VARCHAR(80) NOT NULL,' .
-			'UNIQUE (hashed_user_id, service_id)' .
-			')');
-		if ($res === FALSE) {
-			SimpleSAML_Logger::error('consent:Database - Failed to create table \'' . $this->table . '\'.');
-			return FALSE;
-		}
-
-		return TRUE;
-	}
-
-
-	/**
-	 * Get database handle.
-	 *
-	 * @return PDO|FALSE  Database handle, or FALSE if we fail to connect.
-	 */
-	private function getDB() {
-		if ($this->db !== NULL) {
-			return $this->db;
-		}
-
-		//try {
-		$this->db = new PDO($this->dsn, $this->username, $this->password);
-		// 		} catch (PDOException $e) {
-		// 			SimpleSAML_Logger::error('consent:Database - Failed to connect to \'' .
-		// 				$this->dsn . '\': '. $e->getMessage());
-		// 			$this->db = FALSE;
-		// 		}
-
-		return $this->db;
-	}
-
-
-	/**
-	 * Format PDO error.
-	 *
-	 * This function formats a PDO error, as returned from errorInfo.
-	 *
-	 * @param array $error  The error information.
-	 * @return string  Error text.
-	 */
-	private static function formatError($error) {
-		assert('is_array($error)');
-		assert('count($error) >= 3');
-
-		return $error[0] . ' - ' . $error[2] . ' (' . $error[1] . ')';
-	}
-
+class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
+{
+    /**
+     * DSN for the database.
+     */
+    private $_dsn;
+
+    /**
+     * Username for the database.
+     */
+    private $_username;
+
+    /**
+     * Password for the database;
+     */
+    private $_password;
+
+    /**
+     * Table with consent.
+     */
+    private $_table;
+
+    /**
+     * Database handle.
+     *
+     * This variable can't be serialized.
+     */
+    private $_db;
+
+    /**
+     * Parse configuration.
+     *
+     * This constructor parses the configuration.
+     *
+     * @param array $config Configuration for database consent store.
+     */
+    public function __construct($config)
+    {
+        parent::__construct($config);
+
+        foreach (array('dsn', 'username', 'password') as $id) {
+            if (!array_key_exists($id, $config)) {
+                throw new Exception(
+                    'consent:Database - Missing required option \'' . $id . '\'.'
+                );
+            }
+
+            if (!is_string($config[$id])) {
+                throw new Exception(
+                    'consent:Database - \'' . $id . '\' is supposed to be a string.'
+                );
+            }
+        }
+
+        $this->_dsn = $config['dsn'];
+        $this->_username = $config['username'];
+        $this->_password = $config['password'];
+
+        if (array_key_exists('table', $config)) {
+            if (!is_string($config['table'])) {
+                throw new Exception(
+                    'consent:Database - \'table\' is supposed to be a string.'
+                );
+            }
+            $this->_table = $config['table'];
+        } else {
+            $this->_table = 'consent';
+        }
+
+        // @TODO Should be removed
+        $db = $this->_getDB();
+    }
+
+    /**
+     * Called before serialization.
+     *
+     * @return array The variables which should be serialized.
+     */
+    public function __sleep()
+    {
+        return array(
+            '_dsn',
+            '_username',
+            '_password',
+            '_table',
+        );
+    }
+
+    /**
+     * Check for consent.
+     *
+     * This function checks whether a given user has authorized the release of
+     * the attributes identified by $attributeSet from $source to $destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return bool True if the user has given consent earlier, false if not
+     *              (or on error).
+     */
+    public function hasConsent($userId, $destinationId, $attributeSet)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+        assert('is_string($attributeSet)');
+
+        $st = $this->_execute(
+            'UPDATE ' . $this->_table . ' ' .
+            'SET usage_date = NOW() ' .
+            'WHERE hashed_user_id = ? AND service_id = ? AND attribute = ?',
+            array($userId, $destinationId, $attributeSet)
+        );
+
+        if ($st === false) {
+            return false;
+        }
+
+        $rowCount = $st->rowCount();
+        if ($rowCount === 0) {
+            SimpleSAML_Logger::debug('consent:Database - No consent found.');
+            return false;
+        } else {
+            SimpleSAML_Logger::debug('consent:Database - Consent found.');
+            return true;
+        }
+
+    }
+
+    /**
+     * Save consent.
+     *
+     * Called when the user asks for the consent to be saved. If consent information
+     * for the given user and destination already exists, it should be overwritten.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return void|true True if consent is deleted 
+     */
+    public function saveConsent($userId, $destinationId, $attributeSet)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+        assert('is_string($attributeSet)');
+
+        /* Check for old consent (with different attribute set). */
+        $st = $this->_execute(
+            'UPDATE ' . $this->_table . ' ' .
+            'SET consent_date = NOW(), usage_date = NOW(), attribute = ? ' .
+            'WHERE hashed_user_id = ? AND service_id = ?',
+            array($attributeSet, $userId, $destinationId)
+        );
+
+        if ($st === false) {
+            return;
+        }
+
+        if ($st->rowCount() > 0) {
+            // Consent has already been stored in the database
+            SimpleSAML_Logger::debug('consent:Database - Updated old consent.');
+            return;
+        }
+
+        // Add new consent
+        $st = $this->_execute(
+            'INSERT INTO ' . $this->_table . ' (' .
+            'consent_date, usage_date, hashed_user_id, service_id, attribute' .
+            ') ' .
+            'VALUES (NOW(), NOW(), ?, ?, ?)',
+            array($userId, $destinationId, $attributeSet)
+        );
+
+        if ($st !== false) {
+            SimpleSAML_Logger::debug('consent:Database - Saved new consent.');
+        }
+        return true;
+    }
+
+    /**
+     * Delete consent.
+     *
+     * Called when a user revokes consent for a given destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifies the destination.
+     *
+     * @return int Number of consents deleted
+     */
+    public function deleteConsent($userId, $destinationId)
+    {
+        assert('is_string($userId)');
+        assert('is_string($destinationId)');
+
+        $st = $this->_execute(
+            'DELETE FROM ' . $this->_table . ' ' .
+            'WHERE hashed_user_id = ? AND service_id = ?;',
+            array($userId, $destinationId)
+        );
+
+        if ($st === false) {
+            return;
+        }
+
+        if ($st->rowCount() > 0) {
+            SimpleSAML_Logger::debug('consent:Database - Deleted consent.');
+            return $st->rowCount();
+        } else {
+            SimpleSAML_Logger::warning(
+                'consent:Database - Attempted to delete nonexistent consent'
+            );
+        }
+    }
+
+    /**
+     * Delete all consents.
+     * 
+     * @param string $userId The hash identifying the user at an IdP.
+     *
+     * @return int Number of consents deleted
+     */
+    public function deleteAllConsents($userId)
+    {
+        assert('is_string($userId)');
+
+        $st = $this->_execute(
+            'DELETE FROM ' . $this->_table . ' WHERE hashed_user_id = ?',
+            array($userId)
+        );
+
+        if ($st === false) {
+            return;
+        }
+
+        if ($st->rowCount() > 0) {
+            SimpleSAML_Logger::debug(
+                'consent:Database - Deleted (' . $st->rowCount() . ') consent(s).'
+            );
+            return $st->rowCount();
+        } else {
+            SimpleSAML_Logger::warning(
+                'consent:Database - Attempted to delete nonexistent consent'
+            );
+        }
+    }
+
+    /**
+     * Retrieve consents.
+     *
+     * This function should return a list of consents the user has saved.
+     *
+     * @param string $userId The hash identifying the user at an IdP.
+     *
+     * @return array Array of all destination ids the user has given consent for.
+     */
+    public function getConsents($userId)
+    {
+        assert('is_string($userId)');
+
+        $ret = array();
+
+        $st = $this->_execute(
+            'SELECT service_id, attribute, consent_date, usage_date ' .
+            'FROM ' . $this->_table . ' ' .
+            'WHERE hashed_user_id = ?',
+            array($userId)
+        );
+
+        if ($st === false) {
+            return array();
+        }
+
+        while ($row = $st->fetch(PDO::FETCH_NUM)) {
+            $ret[] = $row;
+        }
+
+        return $ret;
+    }
+
+    /**
+     * Prepare and execute statement.
+     *
+     * This function prepares and executes a statement. On error, false will be
+     * returned.
+     *
+     * @param string $statement  The statement which should be executed.
+     * @param array  $parameters Parameters for the statement.
+     *
+     * @return PDOStatement|false  The statement, or false if execution failed.
+     */
+    private function _execute($statement, $parameters)
+    {
+        assert('is_string($statement)');
+        assert('is_array($parameters)');
+
+        $db = $this->_getDB();
+        if ($db === false) {
+            return false;
+        }
+
+        $st = $db->prepare($statement);
+        if ($st === false) {
+            if ($st === false) {
+                SimpleSAML_Logger::error(
+                    'consent:Database - Error preparing statement \'' .
+                    $statement . '\': ' . self::_formatError($db->errorInfo())
+                );
+                return false;
+            }
+        }
+
+        if ($st->execute($parameters) !== true) {
+            SimpleSAML_Logger::error(
+                'consent:Database - Error executing statement \'' .
+                $statement . '\': ' . self::_formatError($st->errorInfo())
+            );
+            return false;
+        }
+
+        return $st;
+    }
+
+    /**
+     * Get statistics from the database
+     *
+     * The returned array contains 3 entries
+     * - total: The total number of consents
+     * - users: Total number of uses that have given consent
+     * ' services: Total number of services that has been given consent to
+     *
+     * @return array Array containing the statistics
+     * @TODO Change fixed table name to condig option
+     */
+    public function getStatistics()
+    {
+        $ret = array();
+
+        // Get total number of consents
+        $st = $this->_execute('SELECT COUNT(*) AS no FROM consent', array());
+        
+        if ($st === false) {
+            return array(); 
+        }
+
+        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+            $ret['total'] = $row[0];
+        }
+
+        // Get total number of users that has given consent
+        $st = $this->_execute(
+            'SELECT COUNT(*) AS no ' .
+            'FROM (SELECT DISTINCT hashed_user_id FROM consent ) AS foo',
+            array()
+        );
+        
+        if ($st === false) {
+            return array(); 
+        }
+
+        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+            $ret['users'] = $row[0];
+        }
+
+        // Get total number of services that has been given consent to
+        $st = $this->_execute(
+            'SELECT COUNT(*) AS no ' .
+            'FROM (SELECT DISTINCT service_id FROM consent) AS foo',
+            array()
+        );
+        
+        if ($st === false) {
+            return array();
+        }
+
+        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+            $ret['services'] = $row[0];
+        }
+
+        return $ret;
+    }
+
+    /**
+     * Create consent table.
+     *
+     * This function creates the table with consent data.
+     *
+     * @return True if successful, false if not.
+     *
+     * @TODO Remove this function since it is not used
+     */
+    private function _createTable()
+    {
+        $db = $this->_getDB();
+        if ($db === false) {
+            return false;
+        }
+
+        $res = $this->db->exec(
+            'CREATE TABLE ' . $this->_table . ' (' .
+            'consent_date TIMESTAMP NOT null,' .
+            'usage_date TIMESTAMP NOT null,' .
+            'hashed_user_id VARCHAR(80) NOT null,' .
+            'service_id VARCHAR(255) NOT null,' .
+            'attribute VARCHAR(80) NOT null,' .
+            'UNIQUE (hashed_user_id, service_id)' .
+            ')'
+        );
+        if ($res === false) {
+            SimpleSAML_Logger::error(
+                'consent:Database - Failed to create table \'' .
+                $this->_table . '\'.'
+            );
+            return false;
+        }
+
+        return true;
+    }
+
+    /**
+     * Get database handle.
+     *
+     * @return PDO|false Database handle, or false if we fail to connect.
+     */
+    private function _getDB()
+    {
+        if ($this->_db !== null) {
+            return $this->_db;
+        }
+
+        // @TODO Cleanup this section
+        //try {
+        $this->_db = new PDO($this->_dsn, $this->_username, $this->_password);
+        // 		} catch (PDOException $e) {
+        // 			SimpleSAML_Logger::error('consent:Database - Failed to connect to \'' .
+        // 				$this->_dsn . '\': '. $e->getMessage());
+        // 			$this->db = false;
+        // 		}
+
+        return $this->_db;
+    }
+
+    /**
+     * Format PDO error.
+     *
+     * This function formats a PDO error, as returned from errorInfo.
+     *
+     * @param array $error The error information.
+     * 
+     * @return string Error text.
+     */
+    private static function _formatError($error)
+    {
+        assert('is_array($error)');
+        assert('count($error) >= 3');
+
+        return $error[0] . ' - ' . $error[2] . ' (' . $error[1] . ')';
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/modules/consent/lib/Store.php b/modules/consent/lib/Store.php
index a6ba0a7957fb96de4889303b287e5e83cdd729ec..3a1db83f1603185226795cd83cada0661e46d1ae 100644
--- a/modules/consent/lib/Store.php
+++ b/modules/consent/lib/Store.php
@@ -1,123 +1,138 @@
 <?php
-
 /**
  * Base class for consent storage handlers.
  *
  * @package simpleSAMLphp
+ * @author Olav Morken <olav.morken@uninett.no>
+ * @author JAcob Christiansen <jach@wayf.dk>
  * @version $Id$
  */
-abstract class sspmod_consent_Store {
-
-
-	/**
-	 * Constructor for the base class.
-	 *
-	 * This constructor should always be called first in any class which implements
-	 * this class.
-	 *
-	 * @param array &$config  The configuration for this storage handler..
-	 */
-	protected function __construct(&$config) {
-		assert('is_array($config)');
-	}
-
-
-	/**
-	 * Check for consent.
-	 *
-	 * This function checks whether a given user has authorized the release of the attributes
-	 * identified by $attributeSet from $source to $destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifyes the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 * @return bool  TRUE if the user has given consent earlier, FALSE if not (or on error).
-	 */
-	abstract public function hasConsent($userId, $destinationId, $attributeSet);
-
-
-	/**
-	 * Save consent.
-	 *
-	 * Called when the user asks for the consent to be saved. If consent information
-	 * for the given user and destination already exists, it should be overwritten.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifyes the destination.
-	 * @param string $attributeSet  A hash which identifies the attributes.
-	 */
-	abstract public function saveConsent($userId, $destinationId, $attributeSet);
-
-
-	/**
-	 * Delete consent.
-	 *
-	 * Called when a user revokes consent for a given destination.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @param string $destinationId  A string which identifyes the destination.
-	 */
-	abstract public function deleteConsent($userId, $destinationId);
-
-
-	/**
-	 * Delete all consents.
-	 *
-	 * Called when a user revokes all consents
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 */
-	public function deleteAllConsents($userId) {
-		throw new Exception('Not implemented: deleteAllConsents()');
-	}
-	
-	
-	public function getStatistics() {
-		throw new Exception('Not implemented: getStatistics()');
-	}
-
-	/**
-	 * Retrieve consents.
-	 *
-	 * This function should return a list of consents the user has saved.
-	 *
-	 * @param string $userId  The hash identifying the user at an IdP.
-	 * @return array  Array of all destination ids the user has given consent for.
-	 */
-	abstract public function getConsents($userId);
-
-
-	/**
-	 * Parse consent storage configuration.
-	 *
-	 * This function parses the configuration for a consent storage method. An exception
-	 * will be thrown if configuration parsing fails.
-	 *
-	 * @param mixed $config  The configuration.
-	 * @return sspmod_consent_Store  An object which implements of the sspmod_consent_Store class.
-	 */
-	public static function parseStoreConfig($config) {
-
-		if (is_string($config)) {
-			$config = array($config);
-		}
-
-		if (!is_array($config)) {
-			throw new Exception('Invalid configuration for consent store option: ' .
-				var_export($config, TRUE));
-		}
-
-		if (!array_key_exists(0, $config)) {
-			throw new Exception('Consent store without name given.');
-		}
-
-		$className = SimpleSAML_Module::resolveClass($config[0], 'Consent_Store',
-			'sspmod_consent_Store');
-
-		unset($config[0]);
-		return new $className($config);
-	}
-
+abstract class sspmod_consent_Store
+{
+    /**
+     * Constructor for the base class.
+     *
+     * This constructor should always be called first in any class which implements
+     * this class.
+     *
+     * @param array &$config The configuration for this storage handler.
+     */
+    protected function __construct(&$config)
+    {
+        assert('is_array($config)');
+    }
+
+    /**
+     * Check for consent.
+     *
+     * This function checks whether a given user has authorized the release of
+     * the attributes identified by $attributeSet from $source to $destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifyes the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return bool True if the user has given consent earlier, false if not
+     *              (or on error).
+     */
+    abstract public function hasConsent($userId, $destinationId, $attributeSet);
+
+    /**
+     * Save consent.
+     *
+     * Called when the user asks for the consent to be saved. If consent information
+     * for the given user and destination already exists, it should be overwritten.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifyes the destination.
+     * @param string $attributeSet  A hash which identifies the attributes.
+     *
+     * @return bool True if consent is succesfully saved otherwise false 
+     */
+    abstract public function saveConsent($userId, $destinationId, $attributeSet);
+
+    /**
+     * Delete consent.
+     *
+     * Called when a user revokes consent for a given destination.
+     *
+     * @param string $userId        The hash identifying the user at an IdP.
+     * @param string $destinationId A string which identifyes the destination.
+     *
+     * @return mixed Should be the number of consent deleted 
+     */
+    abstract public function deleteConsent($userId, $destinationId);
+
+    /**
+     * Delete all consents.
+     *
+     * Called when a user revokes all consents
+     *
+     * @param string $userId The hash identifying the user at an IdP.
+     *
+     * @return mixed Should be the number of consent removed
+     */
+    public function deleteAllConsents($userId)
+    {
+        throw new Exception('Not implemented: deleteAllConsents()');
+    }
+
+    /**
+     * Get statistics for all consent given in the consent store
+     *
+     * @return mixed Statistics from the consent store
+     */
+    public function getStatistics()
+    {
+        throw new Exception('Not implemented: getStatistics()');
+    }
+
+    /**
+     * Retrieve consents.
+     *
+     * This function should return a list of consents the user has saved.
+     *
+     * @param string $userId The hash identifying the user at an IdP.
+     *
+     * @return array Array of all destination ids the user has given consent for.
+     */
+    abstract public function getConsents($userId);
+
+    /**
+     * Parse consent storage configuration.
+     *
+     * This function parses the configuration for a consent storage method.
+     * An exception will be thrown if configuration parsing fails.
+     *
+     * @param mixed $config The configuration.
+     *
+     * @return sspmod_consent_Store An object which implements the
+     *                              sspmod_consent_Store class.
+     */
+    public static function parseStoreConfig($config)
+    {
+        if (is_string($config)) {
+            $config = array($config);
+        }
+
+        if (!is_array($config)) {
+            throw new Exception(
+                'Invalid configuration for consent store option: ' . 
+                var_export($config, true)
+            );
+        }
+
+        if (!array_key_exists(0, $config)) {
+            throw new Exception('Consent store without name given.');
+        }
+
+        $className = SimpleSAML_Module::resolveClass(
+            $config[0],
+            'Consent_Store',
+            'sspmod_consent_Store'
+        );
+
+        unset($config[0]);
+        return new $className($config);
+    }
 }
-
-?>
\ No newline at end of file
diff --git a/modules/consent/templates/consentform.php b/modules/consent/templates/consentform.php
index bbe3d790f6543484eba7c95e2ab745e89c63a32b..d08b20367b8881e1e3c0f4654fda9a8511daff03 100644
--- a/modules/consent/templates/consentform.php
+++ b/modules/consent/templates/consentform.php
@@ -1,5 +1,4 @@
 <?php
-
 /**
  * Template form for giving consent.
  *
@@ -24,33 +23,31 @@ assert('is_string($this->data["noTarget"])');
 assert('is_array($this->data["noData"])');
 assert('is_array($this->data["attributes"])');
 assert('is_array($this->data["hiddenAttributes"])');
-assert('$this->data["sppp"] === FALSE || is_string($this->data["sppp"])');
-
-
-/* Parse parameters. */
+assert('$this->data["sppp"] === false || is_string($this->data["sppp"])');
 
+// Parse parameters
 if (array_key_exists('name', $this->data['srcMetadata'])) {
-	$srcName = $this->data['srcMetadata']['name'];
+    $srcName = $this->data['srcMetadata']['name'];
 } elseif (array_key_exists('OrganizationDisplayName', $this->data['srcMetadata'])) {
-	$srcName = $this->data['srcMetadata']['OrganizationDisplayName'];
+    $srcName = $this->data['srcMetadata']['OrganizationDisplayName'];
 } else {
-	$srcName = $this->data['srcMetadata']['entityid'];
+    $srcName = $this->data['srcMetadata']['entityid'];
 }
 
 if (is_array($srcName)) {
-	$srcName = $this->t($srcName);
+    $srcName = $this->t($srcName);
 }
 
 if (array_key_exists('name', $this->data['dstMetadata'])) {
-	$dstName = $this->data['dstMetadata']['name'];
+    $dstName = $this->data['dstMetadata']['name'];
 } elseif (array_key_exists('OrganizationDisplayName', $this->data['dstMetadata'])) {
-	$dstName = $this->data['dstMetadata']['OrganizationDisplayName'];
+    $dstName = $this->data['dstMetadata']['OrganizationDisplayName'];
 } else {
-	$dstName = $this->data['dstMetadata']['entityid'];
+    $dstName = $this->data['dstMetadata']['entityid'];
 }
 
 if (is_array($dstName)) {
-	$dstName = $this->t($dstName);
+    $dstName = $this->t($dstName);
 }
 
 $srcName = htmlspecialchars($srcName);
@@ -59,146 +56,173 @@ $dstName = htmlspecialchars($dstName);
 $attributes = $this->data['attributes'];
 
 $this->data['header'] = $this->t('{consent:consent:consent_header}');
-$this->data['head']  = '<link rel="stylesheet" type="text/css" href="/' . $this->data['baseurlpath'] . 'module.php/consent/style.css" />' . "\n";
-
+$this->data['head']  = '<link rel="stylesheet" type="text/css" href="/' .
+    $this->data['baseurlpath'] . 'module.php/consent/style.css" />' . "\n";
 
 $this->includeAtTemplateBase('includes/header.php');
 ?>
 
-
 <p>
 <?php
-	echo $this->t('{consent:consent:consent_accept}', array( 'SPNAME' => $dstName, 'IDPNAME' => $srcName ));
-	if (array_key_exists('descr_purpose', $this->data['dstMetadata'])) {
-		echo '</p><p>' . $this->t('{consent:consent:consent_purpose}', array(
-			'SPNAME' => $dstName,
-			'SPDESC' => $this->getTranslation(SimpleSAML_Utilities::arrayize($this->data['dstMetadata']['descr_purpose'], 'en')),
-		));
-	}
+echo $this->t(
+    '{consent:consent:consent_accept}',
+    array( 'SPNAME' => $dstName, 'IDPNAME' => $srcName)
+);
+
+if (array_key_exists('descr_purpose', $this->data['dstMetadata'])) {
+    echo '</p><p>' . $this->t(
+        '{consent:consent:consent_purpose}', 
+        array(
+            'SPNAME' => $dstName,
+            'SPDESC' => $this->getTranslation(
+                SimpleSAML_Utilities::arrayize(
+                    $this->data['dstMetadata']['descr_purpose'],
+                    'en'
+                )
+            ),
+        )
+    );
+}
 ?>
 </p>
 
-
 <form style="display: inline; margin: 0px; padding: 0px" action="<?php echo htmlspecialchars($this->data['yesTarget']); ?>">
 <p style="margin: 1em">
 
 <?php
-	if ($this->data['usestorage']) {
-		$checked = ($this->data['checked'] ? 'checked="checked"' : '');
-		echo('<input type="checkbox" name="saveconsent" ' . $checked . ' value="1" /> ' . $this->t('{consent:consent:remember}') . '');
-	}
-	
-	// Embed hidden fields...
-	foreach ($this->data['yesData'] as $name => $value) {
-		echo('<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />');
-	}
-?>
+if ($this->data['usestorage']) {
+    $checked = ($this->data['checked'] ? 'checked="checked"' : '');
+    echo '<input type="checkbox" name="saveconsent" ' . $checked .
+        ' value="1" /> ' . $this->t('{consent:consent:remember}');
+}
 
-</p>
-		<input type="submit" name="yes" id="yesbutton" value="<?php echo htmlspecialchars($this->t('{consent:consent:yes}')) ?>" />
+// Embed hidden fields...
+foreach ($this->data['yesData'] as $name => $value) {
+    echo '<input type="hidden" name="' . htmlspecialchars($name) .
+        '" value="' . htmlspecialchars($value) . '" />';
+}
+?>
+    </p>
+    <input type="submit" name="yes" id="yesbutton" value="<?php echo htmlspecialchars($this->t('{consent:consent:yes}')) ?>" />
 </form>
 
 <form style="display: inline; margin-left: .5em;" action="<?php echo htmlspecialchars($this->data['noTarget']); ?>" method="get">
 
 <?php
 foreach ($this->data['noData'] as $name => $value) {
-        echo('<input type="hidden" name="' . htmlspecialchars($name) . '" value="' . htmlspecialchars($value) . '" />');
+    echo('<input type="hidden" name="' . htmlspecialchars($name) .
+        '" value="' . htmlspecialchars($value) . '" />');
 }
 ?>
-
-	<input type="submit" style="display: inline" name="no" id="nobutton" value="<?php echo htmlspecialchars($this->t('{consent:consent:no}')) ?>" />
-
+    <input type="submit" style="display: inline" name="no" id="nobutton" value="<?php echo htmlspecialchars($this->t('{consent:consent:no}')) ?>" />
 </form>
 
 <?php
-if ($this->data['sppp'] !== FALSE) {
-	echo "<p>" . htmlspecialchars($this->t('{consent:consent:consent_privacypolicy}')) . " ";
-	echo "<a target='_blank' href='" . htmlspecialchars($this->data['sppp']) . "'>" . $dstName . "</a>";
-	echo "</p>";
+if ($this->data['sppp'] !== false) {
+    echo "<p>" . htmlspecialchars($this->t('{consent:consent:consent_privacypolicy}')) . " ";
+    echo "<a target='_blank' href='" . htmlspecialchars($this->data['sppp']) . "'>" . $dstName . "</a>";
+    echo "</p>";
 }
-?>
 
-<?php
+/**
+ * Recursiv attribute array listing function
+ *
+ * @param SimpleSAML_XHTML_Template $t          Template object
+ * @param array                     $attributes Attributes to be presented
+ * @param string                    $nameParent Name of parent element
+ *
+ * @return string HTML representation of the attributes 
+ */
+function present_attributes($t, $attributes, $nameParent)
+{
+    $alternate = array('odd', 'even');
+    $i = 0;
+    $summary = 'summary="' . $t->t('{consent:consent:table_summary}') . '"';
+
+    if (strlen($nameParent) > 0) {
+        $parentStr = strtolower($nameParent) . '_';
+        $str = '<table class="attributes" ' . $summary . '>';
+    } else {
+        $parentStr = '';
+        $str = '<table id="table_with_attributes"  class="attributes" '. $summary .'>';
+        $str .= "\n" . '<caption>' . $t->t('{consent:consent:table_caption}') .
+            '</caption>';
+    }
+
+    foreach ($attributes as $name => $value) {
+        $nameraw = $name;
+        $name = $t->getAttributeTranslation($parentStr . $nameraw);
+
+        if (preg_match('/^child_/', $nameraw)) {
+            // Insert child table
+            $parentName = preg_replace('/^child_/', '', $nameraw);
+            foreach ($value AS $child) {
+                $str .= "\n" . '<tr class="odd"><td style="padding: 2em">' .
+                    present_attributes($t, $child, $parentName) . '</td></tr>';
+            }
+        } else {
+            // Insert values directly
+
+            $str .= "\n" . '<tr class="' . $alternate[($i++ % 2)] .
+                '"><td><span class="attrname">' . htmlspecialchars($name) . '</span>';
+
+            $isHidden = in_array($nameraw, $t->data['hiddenAttributes'], true);
+            if ($isHidden) {
+                $hiddenId = SimpleSAML_Utilities::generateID();
+
+                $str .= '<div class="attrvalue" style="display: none;" id="hidden_' . $hiddenId . '">';
+            } else {
+                $str .= '<div class="attrvalue">';
+            }
+
+            if (sizeof($value) > 1) {
+                // We hawe several values
+                $str .= '<ul>';
+                foreach ($value AS $listitem) {
+                    if ($nameraw === 'jpegPhoto') {
+                        $str .= '<li><img src="data:image/jpeg;base64,' .
+                            htmlspecialchars($listitem) .
+                            '" alt="User photo" /></li>';
+                    } else {
+                        $str .= '<li>' . htmlspecialchars($listitem) . '</li>';
+                    }
+                }
+                $str .= '</ul>';
+            } elseif (isset($value[0])) {
+                // We hawe only one value
+                if ($nameraw === 'jpegPhoto') {
+                    $str .= '<img src="data:image/jpeg;base64,' .
+                        htmlspecialchars($value[0]) .
+                        '" alt="User photo" />';
+                } else {
+                    $str .= htmlspecialchars($value[0]);
+                }
+            }	// end of if multivalue
+            $str .= '</div>';
+
+            if ($isHidden) {
+                $str .= '<div class="attrvalue consent_showattribute" id="visible_' . $hiddenId . '">';
+                $str .= '... ';
+                $str .= '<a class="consent_showattributelink" href="javascript:SimpleSAML_show(\'hidden_' . $hiddenId . '\'); SimpleSAML_hide(\'visible_' . $hiddenId . '\');">';
+                $str .= $t->t('{consent:consent:show_attribute}');
+                $str .= '</a>';
+                $str .= '</div>';
+            }
+
+            $str .= '</td></tr>';
+        }	// end else: not child table
+    }	// end foreach
+    $str .= isset($attributes)? '</table>':'';
+    return $str;
+}
 
+echo '<h3 id="attributeheader">' .
+    $this->t(
+        '{consent:consent:consent_attributes_header}',
+        array( 'SPNAME' => $dstName, 'IDPNAME' => $srcName)
+    ) .
+    '</h3>';
 
-// Recursiv attribute array listing function
-function present_attributes($t, $attributes, $nameParent) {
-	$alternate = array('odd', 'even'); $i = 0;
-	$summary = 'summary="' . $t->t('{consent:consent:table_summary}') . '"';
-	
-	if(strlen($nameParent) > 0){
-		$parentStr = strtolower($nameParent) . '_';
-		$str = '<table class="attributes" ' . $summary . '>';
-	}else{
-		$parentStr = '';
-		$str = '<table id="table_with_attributes"  class="attributes" '. $summary .'>';
-		$str .= "\n" . '<caption>' . $t->t('{consent:consent:table_caption}') . '</caption>';
-	}
-	
-	foreach ($attributes as $name => $value) {
-		$nameraw = $name;
-		$name = $t->getAttributeTranslation($parentStr . $nameraw);
-		
-		if (preg_match('/^child_/', $nameraw)) {
-			// Insert child table
-			$parentName = preg_replace('/^child_/', '', $nameraw);
-			foreach($value AS $child) {
-				$str .= "\n" . '<tr class="odd"><td style="padding: 2em">' . present_attributes($t, $child, $parentName) . '</td></tr>';
-			}
-		} else {
-			// Insert values directly
-
-			$str .= "\n" . '<tr class="' . $alternate[($i++ % 2)] . '"><td><span class="attrname">' . htmlspecialchars($name) . '</span>';
-
-			$isHidden = in_array($nameraw, $t->data['hiddenAttributes'], TRUE);
-			if ($isHidden) {
-				$hiddenId = SimpleSAML_Utilities::generateID();
-
-				$str .= '<div class="attrvalue" style="display: none;" id="hidden_' . $hiddenId . '">';
-			} else {
-				$str .= '<div class="attrvalue">';
-			}
-
-			if (sizeof($value) > 1) {
-				// We hawe several values
-				$str .= '<ul>';
-				foreach ($value AS $listitem) {
-					if ($nameraw === 'jpegPhoto') {
-						$str .= '<li><img src="data:image/jpeg;base64,' . htmlspecialchars($listitem) . '" alt="User photo" /></li>';
-					} else {
-						$str .= '<li>' . htmlspecialchars($listitem) . '</li>';
-					}
-				}
-				$str .= '</ul>';
-			} elseif(isset($value[0])) {
-				// We hawe only one value
-				if ($nameraw === 'jpegPhoto') {
-					$str .= '<img src="data:image/jpeg;base64,' . htmlspecialchars($value[0]) . '" alt="User photo" />';
-				} else {
-					$str .= htmlspecialchars($value[0]);
-				}
-			}	// end of if multivalue
-			$str .= '</div>';
-
-			if ($isHidden) {
-				$str .= '<div class="attrvalue consent_showattribute" id="visible_' . $hiddenId . '">';
-				$str .= '... ';
-				$str .= '<a class="consent_showattributelink" href="javascript:SimpleSAML_show(\'hidden_' . $hiddenId . '\'); SimpleSAML_hide(\'visible_' . $hiddenId . '\');">';
-				$str .= $t->t('{consent:consent:show_attribute}');
-				$str .= '</a>';
-				$str .= '</div>';
-			}
-
-			$str .= '</td></tr>';
-		}	// end else: not child table
-	}	// end foreach
-	$str .= isset($attributes)? '</table>':'';
-	return $str;
-}
-?>
-	<h3 id="attributeheader"><?php echo $this->t('{consent:consent:consent_attributes_header}',array( 'SPNAME' => $dstName, 'IDPNAME' => $srcName )); ?></h3>
-	<?php echo(present_attributes($this, $attributes, '')); ?>
+echo(present_attributes($this, $attributes, '')); 
 
-<?php
 $this->includeAtTemplateBase('includes/footer.php');
-?>
diff --git a/modules/consent/templates/noconsent.php b/modules/consent/templates/noconsent.php
index f96b44542cf1ecb96b186c6c5775a5fefa3b1e0d..5d52fb3cde50dc41f20f9be817a173c2e780e442 100644
--- a/modules/consent/templates/noconsent.php
+++ b/modules/consent/templates/noconsent.php
@@ -1,23 +1,20 @@
 <?php
-	$this->data['header'] = $this->t('{consent:consent:noconsent_title}');;
-	$this->includeAtTemplateBase('includes/header.php');
-?>
+$this->data['header'] = $this->t('{consent:consent:noconsent_title}');;
+$this->includeAtTemplateBase('includes/header.php');
 
+echo '<h2>' . $this->data['header'] . '</h2>';
+echo '<p>' . $this->t('{consent:consent:noconsent_text}') . '</p>';
 
-	<h2><?php echo($this->data['header']); ?></h2>
-	<p><?php echo($this->t('{consent:consent:noconsent_text}')); ?></p>
+if ($this->data['resumeFrom']) {
+    echo('<p><a href="' . htmlspecialchars($this->data['resumeFrom']) . '">');
+    echo($this->t('{consent:consent:noconsent_return}'));
+    echo('</a></p>');
+}
 
-<?php
-	if($this->data['resumeFrom']) {
-		echo('<p><a href="' . htmlspecialchars($this->data['resumeFrom']) . '">');
-		echo($this->t('{consent:consent:noconsent_return}'));
-		echo('</a></p>');
-	}
-		if($this->data['aboutService']) {
-		echo('<p><a href="' . htmlspecialchars($this->data['aboutService']) . '">');
-		echo($this->t('{consent:consent:noconsent_goto_about}'));
-		echo('</a></p>');
-	}
-?>
+if ($this->data['aboutService']) {
+    echo('<p><a href="' . htmlspecialchars($this->data['aboutService']) . '">');
+    echo($this->t('{consent:consent:noconsent_goto_about}'));
+    echo('</a></p>');
+}
 
-<?php $this->includeAtTemplateBase('includes/footer.php'); ?>
+$this->includeAtTemplateBase('includes/footer.php');
diff --git a/modules/consent/www/getconsent.php b/modules/consent/www/getconsent.php
index 8363917ae67bd06c4dc93457cb4c3da0c1857099..949630dfe5d60d28e32a46322c620b02689a077f 100644
--- a/modules/consent/www/getconsent.php
+++ b/modules/consent/www/getconsent.php
@@ -8,7 +8,6 @@
  * @package simpleSAMLphp
  * @version $Id$
  */
-
 /**
  * Explicit instruct consent page to send no-cache header to browsers to make 
  * sure the users attribute information are not store on client disk.
@@ -26,7 +25,9 @@ $globalConfig = SimpleSAML_Configuration::getInstance();
 SimpleSAML_Logger::info('Consent - getconsent: Accessing consent interface');
 
 if (!array_key_exists('StateId', $_REQUEST)) {
-    throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
+    throw new SimpleSAML_Error_BadRequest(
+        'Missing required StateId query parameter.'
+    );
 }
 
 $id = $_REQUEST['StateId'];
@@ -43,15 +44,18 @@ if (array_key_exists('yes', $_REQUEST)) {
 
     if (   array_key_exists('consent:store', $state) 
         && array_key_exists('saveconsent', $_REQUEST)
-        && $_REQUEST['saveconsent'] === '1')
-    {
+        && $_REQUEST['saveconsent'] === '1'
+    ) {
         /* Save consent. */
         $store = $state['consent:store'];
         $userId = $state['consent:store.userId'];
         $targetedId = $state['consent:store.destination'];
         $attributeSet = $state['consent:store.attributeSet'];
 
-        SimpleSAML_Logger::debug('Consent - saveConsent() : [' . $userId . '|' . $targetedId . '|' .  $attributeSet . ']');	
+        SimpleSAML_Logger::debug(
+            'Consent - saveConsent() : [' . $userId . '|' .
+            $targetedId . '|' .  $attributeSet . ']'
+        );	
         $store->saveConsent($userId, $targetedId, $attributeSet);
     }
 
@@ -63,8 +67,8 @@ $attributes = $state['Attributes'];
 $noconsentattributes = $state['consent:noconsentattributes'];
 
 // Remove attributes that do not require consent
-foreach($attributes AS $attrkey => $attrval) {
-    if(in_array($attrkey, $noconsentattributes)) {
+foreach ($attributes AS $attrkey => $attrval) {
+    if (in_array($attrkey, $noconsentattributes)) {
         unset($attributes[$attrkey]);
     }
 }
@@ -92,30 +96,34 @@ if (array_key_exists('privacypolicy', $state['Destination'])) {
 } elseif (array_key_exists('privacypolicy', $state['Source'])) {
     $privacypolicy = $state['Source']['privacypolicy'];
 } else {
-    $privacypolicy = FALSE;
+    $privacypolicy = false;
 }
-if($privacypolicy !== FALSE) {
-    $privacypolicy = str_replace('%SPENTITYID%', urlencode($spentityid), $privacypolicy);
+if ($privacypolicy !== false) {
+    $privacypolicy = str_replace(
+        '%SPENTITYID%',
+        urlencode($spentityid), 
+        $privacypolicy
+    );
 }
 $t->data['sppp'] = $privacypolicy;
 
 // Set focus element
 switch ($state['consent:focus']) {
-    case 'yes':
-        $t->data['autofocus'] = 'yesbutton';
-        break;
-    case 'no':
-        $t->data['autofocus'] = 'nobutton';
-        break;
-    case NULL:
-    default:
-        break;
+case 'yes':
+    $t->data['autofocus'] = 'yesbutton';
+    break;
+case 'no':
+    $t->data['autofocus'] = 'nobutton';
+    break;
+case null:
+default:
+    break;
 }
 
 if (array_key_exists('consent:store', $state)) {
-    $t->data['usestorage'] = TRUE;
+    $t->data['usestorage'] = true;
 } else {
-    $t->data['usestorage'] = FALSE;
+    $t->data['usestorage'] = false;
 }
 
 if (array_key_exists('consent:hiddenAttributes', $state)) {
@@ -125,4 +133,3 @@ if (array_key_exists('consent:hiddenAttributes', $state)) {
 }
 
 $t->show();
-exit;
diff --git a/modules/consent/www/noconsent.php b/modules/consent/www/noconsent.php
index de677f8068d1563e76c8b479564d21c12d6c0eda..b1982338817cfcd06b8b0da4cdc0f477555cbc61 100644
--- a/modules/consent/www/noconsent.php
+++ b/modules/consent/www/noconsent.php
@@ -1,24 +1,27 @@
 <?php
-
 /**
  * This is the page the user lands on when choosing "no" in the consent form.
  *
  * @package simpleSAMLphp
  * @version $Id$
  */
-
 if (!array_key_exists('StateId', $_REQUEST)) {
-	throw new SimpleSAML_Error_BadRequest('Missing required StateId query parameter.');
+    throw new SimpleSAML_Error_BadRequest(
+        'Missing required StateId query parameter.'
+    );
 }
 
 $id = $_REQUEST['StateId'];
 $state = SimpleSAML_Auth_State::loadState($id, 'consent:request');
 
-$resumeFrom = SimpleSAML_Module::getModuleURL('consent/getconsent.php', array('StateId' => $id));
+$resumeFrom = SimpleSAML_Module::getModuleURL(
+    'consent/getconsent.php',
+    array('StateId' => $id)
+);
 
-$aboutService = NULL;
-if(isset($state['Destination']['url.about']) ){
-	$aboutService = $state['Destination']['url.about'];
+$aboutService = null;
+if (isset($state['Destination']['url.about'])) {
+    $aboutService = $state['Destination']['url.about'];
 }
 
 $globalConfig = SimpleSAML_Configuration::getInstance();
@@ -28,5 +31,3 @@ $t->data['dstMetadata'] = $state['Destination'];
 $t->data['resumeFrom'] = $resumeFrom;
 $t->data['aboutService'] = $aboutService;
 $t->show();
-
-?>
\ No newline at end of file
diff --git a/modules/consent/www/style.css b/modules/consent/www/style.css
index 56586fb0c47b1296336e68a0d6062c1434b81c48..573ca554bd5adf62e97c31f1a5bd6b0914688ab0 100644
--- a/modules/consent/www/style.css
+++ b/modules/consent/www/style.css
@@ -1,35 +1,35 @@
 fieldset {
-	padding: 0px;
+    padding: 0px;
 }
 
 fieldset legend {
-	background: #eee;
+    background: #eee;
 }
 
 h3#attributeheader {
-	margin: 1.5em 0em 0.5em 0em;
+    margin: 1.5em 0em 0.5em 0em;
 }
 
 table#table_with_attributes .attrname {
-	text-align: right;
-	font-weight: bold;
+    text-align: right;
+    font-weight: bold;
 }
 
 table#table_with_attributes .attrvalue {
-	padding-left: 1em;
-	margin: 0.5em 0em;
+    padding-left: 1em;
+    margin: 0.5em 0em;
 }
 
 table#table_with_attributes tr:last-child td {
-	border-bottom: none;
+    border-bottom: none;
 }
 
 table#table_with_attributes img {
-	border: 1px solid #777;
-	margin: 4px;
+    border: 1px solid #777;
+    margin: 4px;
 }
 
 table#table_with_attributes ul {
-	margin: 0px;
-	padding-left: 1em;
+    margin: 0px;
+    padding-left: 1em;
 }