From 9b7361e1f955d7a152aa1763111dc3bb5b54484e Mon Sep 17 00:00:00 2001
From: Tim van Dijen <tvdijen@gmail.com>
Date: Fri, 1 Jun 2018 01:39:16 +0200
Subject: [PATCH] Replace sppmod_* with namespaced version

---
 config-templates/config.php                   |  4 +-
 docs/simplesamlphp-authproc.md                |  2 +-
 docs/simplesamlphp-authsource.md              |  4 +-
 docs/simplesamlphp-customauth.md              | 12 +--
 docs/simplesamlphp-errorhandling.md           |  6 +-
 docs/simplesamlphp-modules.md                 |  4 +-
 lib/SimpleSAML/Auth/Default.php               |  4 +-
 .../Error/CriticalConfigurationError.php      |  2 +-
 lib/SimpleSAML/Logger/FileLoggingHandler.php  |  2 +-
 lib/SimpleSAML/Metadata/SAMLBuilder.php       |  2 +-
 lib/SimpleSAML/Module.php                     |  2 +-
 lib/SimpleSAML/Utilities.php                  |  2 +-
 lib/SimpleSAML/XHTML/EMail.php                |  2 +-
 lib/SimpleSAML/XHTML/IdPDisco.php             |  4 +-
 modules/adfs/lib/IdP/ADFS.php                 | 22 ++---
 modules/adfs/lib/SAML2/XML/fed/Const.php      |  6 +-
 modules/adfs/lib/SAML2/XML/fed/Endpoint.php   | 10 ++-
 .../XML/fed/SecurityTokenServiceType.php      | 26 +++---
 .../lib/SAML2/XML/fed/TokenTypesOffered.php   | 14 ++--
 modules/adfs/www/idp/prp.php                  |  5 +-
 .../lib/Auth/Process/ExpiryWarning.php        | 11 ++-
 .../authX509/lib/Auth/Source/X509userCert.php | 18 ++--
 .../lib/Auth/Process/OTP2YubiPrefix.php       | 12 +--
 .../authYubiKey/lib/Auth/Source/YubiKey.php   | 14 ++--
 modules/authYubiKey/www/yubikeylogin.php      |  6 +-
 modules/authcrypt/lib/Auth/Source/Hash.php    |  7 +-
 .../authcrypt/lib/Auth/Source/Htpasswd.php    | 26 +++---
 .../authfacebook/lib/Auth/Source/Facebook.php | 12 +--
 modules/authfacebook/lib/Facebook.php         | 16 ++--
 modules/authfacebook/www/linkback.php         | 10 +--
 .../authlinkedin/lib/Auth/Source/LinkedIn.php | 26 +++---
 modules/authlinkedin/www/linkback.php         |  6 +-
 .../authorize/lib/Auth/Process/Authorize.php  |  9 +-
 .../authtwitter/lib/Auth/Source/Twitter.php   | 17 ++--
 modules/authtwitter/www/linkback.php          |  8 +-
 .../lib/Auth/Source/LiveID.php                | 29 +++----
 modules/authwindowslive/www/linkback.php      |  6 +-
 modules/cas/lib/Auth/Source/CAS.php           | 40 ++++-----
 modules/cas/www/linkback.php                  |  8 +-
 modules/cdc/lib/Auth/Process/CDC.php          | 11 ++-
 modules/cdc/lib/Client.php                    |  9 +-
 modules/cdc/lib/Server.php                    | 10 ++-
 modules/cdc/www/resume.php                    |  2 +-
 modules/cdc/www/server.php                    |  2 +-
 modules/consent/docs/consent.md               |  2 +-
 modules/consent/lib/Auth/Process/Consent.php  | 12 +--
 modules/consent/lib/Consent/Store/Cookie.php  | 34 ++++----
 .../consent/lib/Consent/Store/Database.php    | 58 +++++++------
 modules/consent/lib/Logout.php                |  4 +-
 modules/consent/lib/Store.php                 | 26 +++---
 modules/consent/www/logout.php                |  2 +-
 modules/consentAdmin/www/consentAdmin.php     | 24 +++---
 modules/core/lib/ACL.php                      |  5 +-
 .../core/lib/Auth/Process/AttributeAdd.php    | 10 ++-
 .../core/lib/Auth/Process/AttributeAlter.php  |  4 +-
 .../core/lib/Auth/Process/AttributeCopy.php   |  8 +-
 .../core/lib/Auth/Process/AttributeLimit.php  |  4 +-
 .../core/lib/Auth/Process/AttributeMap.php    | 18 ++--
 .../core/lib/Auth/Process/AttributeRealm.php  |  6 +-
 modules/core/lib/Auth/Process/Cardinality.php | 14 ++--
 .../lib/Auth/Process/CardinalitySingle.php    | 10 ++-
 .../lib/Auth/Process/ExtendIdPSession.php     |  4 +-
 .../core/lib/Auth/Process/GenerateGroups.php  |  8 +-
 .../core/lib/Auth/Process/LanguageAdaptor.php | 12 +--
 modules/core/lib/Auth/Process/PHP.php         |  4 +-
 .../core/lib/Auth/Process/ScopeAttribute.php  |  4 +-
 .../lib/Auth/Process/ScopeFromAttribute.php   |  8 +-
 .../Auth/Process/StatisticsWithAttribute.php  | 14 ++--
 modules/core/lib/Auth/Process/TargetedID.php  | 14 ++--
 .../lib/Auth/Process/WarnShortSSOInterval.php |  6 +-
 .../core/lib/Auth/Source/AdminPassword.php    |  4 +-
 modules/core/lib/Auth/UserPassBase.php        | 18 ++--
 modules/core/lib/Auth/UserPassOrgBase.php     | 16 ++--
 modules/core/lib/Stats/Output/File.php        |  8 +-
 modules/core/lib/Stats/Output/Log.php         |  4 +-
 .../core/lib/Storage/SQLPermanentStorage.php  | 27 +++---
 modules/core/www/idp/logout-iframe-post.php   |  4 +-
 modules/core/www/loginuserpass.php            | 12 +--
 modules/core/www/loginuserpassorg.php         | 12 +--
 modules/discopower/lib/PowerIdPDisco.php      | 12 +--
 modules/discopower/www/disco.php              |  4 +-
 .../www/attributeserver.php                   |  4 +-
 .../lib/Auth/Process/RedirectTest.php         |  4 +-
 .../exampleauth/lib/Auth/Source/External.php  |  8 +-
 .../exampleauth/lib/Auth/Source/Static.php    | 10 ++-
 .../exampleauth/lib/Auth/Source/UserPass.php  | 15 ++--
 modules/exampleauth/www/resume.php            |  4 +-
 .../lib/Auth/Process/ExpiryDate.php           | 22 ++---
 .../lib/Auth/Process/AttributeAddFromLDAP.php | 16 ++--
 .../Auth/Process/AttributeAddUsersGroups.php  | 26 +++---
 modules/ldap/lib/Auth/Process/BaseFilter.php  | 18 ++--
 modules/ldap/lib/Auth/Source/LDAP.php         |  9 +-
 modules/ldap/lib/Auth/Source/LDAPMulti.php    |  7 +-
 modules/ldap/lib/ConfigHelper.php             | 21 ++---
 modules/metarefresh/bin/metarefresh.php       |  6 +-
 modules/metarefresh/hooks/hook_cron.php       |  8 +-
 modules/metarefresh/lib/ARP.php               | 15 ++--
 modules/metarefresh/lib/MetaLoader.php        | 75 +++++++++--------
 modules/metarefresh/www/fetch.php             |  2 +-
 .../multiauth/lib/Auth/Source/MultiAuth.php   | 16 ++--
 modules/multiauth/www/selectsource.php        | 50 +++++------
 modules/negotiate/docs/negotiate.md           |  4 +-
 .../negotiate/lib/Auth/Source/Negotiate.php   | 62 +++++++-------
 modules/negotiate/www/backend.php             |  4 +-
 modules/negotiate/www/retry.php               |  2 +-
 modules/oauth/hooks/hook_cron.php             |  6 +-
 modules/oauth/lib/Consumer.php                | 29 ++++---
 modules/oauth/lib/OAuthServer.php             | 18 +++-
 modules/oauth/lib/OAuthStore.php              | 62 +++++++-------
 modules/oauth/lib/Registry.php                | 11 +--
 modules/oauth/www/getUserInfo.php             |  6 +-
 modules/oauth/www/registry.edit.php           |  6 +-
 modules/oauth/www/registry.php                |  8 +-
 modules/portal/hooks/hook_htmlinject.php      |  6 +-
 modules/portal/lib/Portal.php                 |  8 +-
 .../lib/Auth/Process/Warning.php              |  4 +-
 modules/radius/lib/Auth/Source/Radius.php     | 15 ++--
 modules/riak/hooks/hook_cron.php              | 10 ++-
 modules/riak/lib/Store/Store.php              |  4 +-
 .../saml/lib/Auth/Process/AttributeNameID.php | 11 +--
 .../lib/Auth/Process/AuthnContextClassRef.php |  4 +-
 .../Process/ExpectedAuthnContextClassRef.php  |  7 +-
 .../saml/lib/Auth/Process/FilterScopes.php    |  1 +
 .../saml/lib/Auth/Process/NameIDAttribute.php |  4 +-
 .../lib/Auth/Process/PersistentNameID.php     | 18 ++--
 .../Process/PersistentNameID2TargetedID.php   |  6 +-
 .../lib/Auth/Process/SQLPersistentNameID.php  | 32 +++----
 .../saml/lib/Auth/Process/TransientNameID.php |  6 +-
 modules/saml/lib/Auth/Source/SP.php           | 84 ++++++++++---------
 modules/saml/lib/BaseNameIDGenerator.php      |  9 +-
 modules/saml/lib/Error.php                    | 17 ++--
 modules/saml/lib/Error/NoAuthnContext.php     |  7 +-
 modules/saml/lib/Error/NoAvailableIDP.php     |  7 +-
 modules/saml/lib/Error/NoPassive.php          |  7 +-
 modules/saml/lib/Error/NoSupportedIDP.php     |  7 +-
 modules/saml/lib/Error/ProxyCountExceeded.php |  7 +-
 modules/saml/lib/IdP/SAML1.php                |  8 +-
 modules/saml/lib/IdP/SAML2.php                | 49 ++++++-----
 modules/saml/lib/IdP/SQLNameID.php            |  9 +-
 modules/saml/lib/Message.php                  | 70 ++++++++--------
 modules/saml/lib/SP/LogoutStore.php           | 24 +++---
 modules/saml/www/proxy/invalid_session.php    |  6 +-
 modules/saml/www/sp/discoresp.php             |  2 +-
 modules/saml/www/sp/metadata.php              |  2 +-
 modules/saml/www/sp/saml1-acs.php             |  2 +-
 modules/saml/www/sp/saml2-acs.php             |  8 +-
 modules/saml/www/sp/saml2-logout.php          | 14 ++--
 .../lib/Auth/Process/SmartID.php              | 12 +--
 .../lib/Auth/Process/SmartName.php            |  4 +-
 modules/sqlauth/lib/Auth/Source/SQL.php       | 38 +++++----
 modules/statistics/bin/loganalyzer.php        |  2 +-
 modules/statistics/bin/logcleaner.php         |  2 +-
 modules/statistics/hooks/hook_cron.php        | 10 ++-
 modules/statistics/lib/AccessCheck.php        | 29 ++++---
 modules/statistics/lib/Aggregator.php         | 22 +++--
 modules/statistics/lib/DateHandler.php        |  6 +-
 modules/statistics/lib/DateHandlerMonth.php   |  6 +-
 modules/statistics/lib/Graph/GoogleCharts.php | 22 +++--
 modules/statistics/lib/LogCleaner.php         | 18 ++--
 modules/statistics/lib/LogParser.php          |  6 +-
 modules/statistics/lib/RatioDataset.php       |  6 +-
 modules/statistics/lib/Ruleset.php            | 12 ++-
 modules/statistics/lib/StatDataset.php        | 10 +--
 .../lib/Statistics/FieldPresentation/Base.php |  4 +-
 .../Statistics/FieldPresentation/Entity.php   |  4 +-
 .../lib/Statistics/Rulesets/BaseRule.php      | 12 ++-
 .../lib/Statistics/Rulesets/Ratio.php         | 12 ++-
 modules/statistics/www/showstats.php          |  6 +-
 modules/statistics/www/statmeta.php           |  4 +-
 .../consent/lib/Auth/Process/ConsentTest.php  | 16 ++--
 .../lib/Auth/Process/AttributeAddTest.php     |  2 +-
 .../lib/Auth/Process/AttributeAlterTest.php   |  2 +-
 .../lib/Auth/Process/AttributeCopyTest.php    |  2 +-
 .../lib/Auth/Process/AttributeLimitTest.php   |  2 +-
 .../lib/Auth/Process/AttributeMapTest.php     |  2 +-
 .../lib/Auth/Process/AttributeRealmTest.php   |  2 +-
 .../Auth/Process/CardinalitySingleTest.php    |  2 +-
 .../core/lib/Auth/Process/CardinalityTest.php |  2 +-
 .../modules/core/lib/Auth/Process/PHPTest.php |  4 +-
 .../lib/Auth/Process/ScopeAttributeTest.php   |  2 +-
 .../Auth/Process/ScopeFromAttributeTest.php   |  2 +-
 .../core/lib/Auth/Process/TargetedIDTest.php  |  2 +-
 .../core/lib/Auth/UserPassBaseTest.php        |  6 +-
 .../lib/Storage/SQLPermanentStorageTest.php   |  2 +-
 .../ldap/lib/Auth/Process/BaseFilterTest.php  |  4 +-
 .../lib/Auth/Process/NameIDAttributeTest.php  |  2 +-
 .../lib/Auth/Source/Auth_Source_SP_Test.php   |  8 +-
 tests/modules/saml/lib/IdP/SAML2Test.php      |  8 +-
 www/saml2/idp/ArtifactResolutionService.php   |  2 +-
 www/saml2/idp/SSOService.php                  |  2 +-
 www/saml2/idp/SingleLogoutService.php         |  2 +-
 www/shib13/idp/SSOService.php                 |  2 +-
 192 files changed, 1261 insertions(+), 981 deletions(-)

diff --git a/config-templates/config.php b/config-templates/config.php
index 6f0061b63..d71a53f81 100644
--- a/config-templates/config.php
+++ b/config-templates/config.php
@@ -563,7 +563,7 @@ $config = array(
      * See docs/simplesamlphp-advancedfeatures.txt for function code example.
      *
      * Example:
-     *   'session.check_function' => array('sspmod_example_Util', 'checkSession'),
+     *   'session.check_function' => array('\SimpleSAML\Module\example\Util', 'checkSession'),
      */
 
 
@@ -740,7 +740,7 @@ $config = array(
      * the default language for the user.
      *
      * Example:
-     *   'language.get_language_function' => array('sspmod_example_Template', 'getLanguage'),
+     *   'language.get_language_function' => array('\SimpleSAML\Module\example\Template', 'getLanguage'),
      */
 
     /*
diff --git a/docs/simplesamlphp-authproc.md b/docs/simplesamlphp-authproc.md
index f65111cff..be91c4207 100644
--- a/docs/simplesamlphp-authproc.md
+++ b/docs/simplesamlphp-authproc.md
@@ -61,7 +61,7 @@ The configuration of *Auth Proc Filters* is a list of filters with priority as *
 
 This configuration will execute *Auth Proc Filters* one by one, with the priority value in increasing order. When *Auth Proc Filters* is configured in multiple places, in example both globally, in the hosted IdP and remote SP metadata, then the list is interleaved sorted by priority.
 
-The most important parameter of each item on the list is the *class* of the *Auth Proc Filter*. The syntax of the class is `modulename:classname`. As an example the class definition `core:AttributeLimit` will be expanded to look for the class `sspmod_core_Auth_Process_AttributeLimit`. The location of this class file *must* then be: `modules/core/lib/Auth/Process/AttributeLimit.php`.
+The most important parameter of each item on the list is the *class* of the *Auth Proc Filter*. The syntax of the class is `modulename:classname`. As an example the class definition `core:AttributeLimit` will be expanded to look for the class `\SimpleSAML\Module\core\Auth\Process\AttributeLimit`. The location of this class file *must* then be: `modules/core/lib/Auth/Process/AttributeLimit.php`.
 
 You will see that a bunch of useful filters is included in the `core` module. In addition the `consent` module that is included in the SimpleSAMLphp distribution implements a filter. Beyond that, you are encouraged to create your own filters and share with the community. If you have created a cool *Auth Proc Filter* that does something useful, let us know, and we may share it on the [SimpleSAMLphp web site][].
 
diff --git a/docs/simplesamlphp-authsource.md b/docs/simplesamlphp-authsource.md
index b39d56c42..4ffd228ec 100644
--- a/docs/simplesamlphp-authsource.md
+++ b/docs/simplesamlphp-authsource.md
@@ -1,7 +1,7 @@
 Creating authentication sources
 ===============================
 
-All authentication sources are located in the `lib/Auth/Source/` directory in a module, and the class name is `sspmod_<module>_Auth_Source_<name>`.
+All authentication sources are located in the `lib/Auth/Source/` directory in a module, and the class name is `\SimpleSAML\Module\<module>\Auth\Source\<name>`.
 The authentication source must extend the `\SimpleSAML\Auth\Source` class or one of its subclasses.
 
 The "entry point" of an authentication source is the `authenticate()`-function.
@@ -36,7 +36,7 @@ Username/password authentication
 --------------------------------
 
 Since username/password authentication is quite a common operation, a base class has been created for this.
-This is the `sspmod_core_Auth_UserPassBase` class, which is can be found as `modules/core/lib/Auth/UserPassBase.php`.
+This is the `\SimpleSAML\Module\core\Auth\UserPassBase` class, which is can be found as `modules/core/lib/Auth/UserPassBase.php`.
 
 The only function you need to implement is the `login($username, $password)`-function.
 This function receives the username and password the user entered, and is expected to return the attributes of that user.
diff --git a/docs/simplesamlphp-customauth.md b/docs/simplesamlphp-customauth.md
index c9bc273a5..d3df73277 100644
--- a/docs/simplesamlphp-customauth.md
+++ b/docs/simplesamlphp-customauth.md
@@ -40,7 +40,7 @@ To begin with, we will create a very simple authentication source, where the use
 Create the file `modules/mymodule/lib/Auth/Source/MyAuth.php` with the following contents:
 
     <?php
-    class sspmod_mymodule_Auth_Source_MyAuth extends sspmod_core_Auth_UserPassBase {
+    class MyAuth extends \SimpleSAML\Module\core\Auth\UserPassBase {
         protected function login($username, $password) {
             if ($username !== 'theusername' || $password !== 'thepassword') {
                 throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
@@ -55,10 +55,10 @@ Create the file `modules/mymodule/lib/Auth/Source/MyAuth.php` with the following
 
 Some things to note:
 
-  - The classname is `sspmod_mymodule_Auth_Source_MyAuth`.
+  - The classname is `\SimpleSAML\Module\mymodule\Auth\Source\MyAuth`.
     This tells SimpleSAMLphp to look for the class in `modules/mymodule/lib/Auth/Source/MyAuth.php`.
 
-  - Our authentication source subclassese `sspmod_core_Auth_UserPassBase`.
+  - Our authentication source subclassese `\SimpleSAML\Module\core\Auth\UserPassBase`.
     This is a helper-class that implements much of the common code needed for username/password authentication.
 
   - The `login` function receives the username and password the user enters.
@@ -97,7 +97,7 @@ You can add it to the beginning of the list, so that the file looks something li
 The instance name is used to refer to this authentication source in other configuration files.
 
 The first element of the configuration of the authentication source must be `'mymodule:MyAuth'`.
-This tells SimpleSAMLphp to look for the `sspmod_mymodule_Auth_Source_MyAuth` class.
+This tells SimpleSAMLphp to look for the `\SimpleSAML\Module\mymodule\Auth\Source\MyAuth` class.
 
 
 Testing our authentication source
@@ -168,7 +168,7 @@ We can then use the properties in the `login` function.
 The complete class file should look like this:
 
     <?php
-    class sspmod_mymodule_Auth_Source_MyAuth extends sspmod_core_Auth_UserPassBase {
+    class MyAuth extends \SimpleSAML\Module\core\Auth\UserPassBase {
 
         private $username;
         private $password;
@@ -245,7 +245,7 @@ A SSHA password is created like this:
 The class follows:
 
     <?php
-    class sspmod_mymodule_Auth_Source_MyAuth extends sspmod_core_Auth_UserPassBase {
+    class MyAuth extends \SimpleSAML\Module\core\Auth\UserPassBase {
 
         /* The database DSN.
          * See the documentation for the various database drivers for information about the syntax:
diff --git a/docs/simplesamlphp-errorhandling.md b/docs/simplesamlphp-errorhandling.md
index 3482dddcf..1c9c8097c 100644
--- a/docs/simplesamlphp-errorhandling.md
+++ b/docs/simplesamlphp-errorhandling.md
@@ -67,11 +67,11 @@ For example, the `\SimpleSAML\Error\NoPassive` exception should be converted to
 * The second-level status code should be `urn:oasis:names:tc:SAML:2.0:status:NoPassive`.
 * The status message should contain the cause of the exception.
 
-The `sspmod_saml_Error` class represents SAML 2 errors.
+The `\SimpleSAML\Module\saml\Error` class represents SAML 2 errors.
 It represents a SAML 2 status code with three elements: the top-level status code, the second-level status code and the status message.
 The second-level status code and the status message is optional, and can be `NULL`.
 
-The `sspmod_saml_Error` class contains a helper function named `fromException`.
+The `\SimpleSAML\Module\saml\Error` class contains a helper function named `fromException`.
 The `fromException()` function is used by `www/saml2/idp/SSOService.php` to return SAML 2 errors to the SP.
 The function contains a list which maps various exceptions to specific SAML 2 errors.
 If it is unable to convert the exception, it will return a generic SAML 2 error describing the original exception in its status message.
@@ -93,7 +93,7 @@ Converting SAML 2 errors to normal exceptions
 ---------------------------------------------
 
 On the SP side, we want to convert SAML 2 errors to SimpleSAMLphp exceptions again.
-This is handled by the `toException()` method in `sspmod_saml_Error`.
+This is handled by the `toException()` method in `\SimpleSAML\Module\saml\Error`.
 The assertion consumer script of the SAML 2 authentication source (`modules/saml2/sp/acs.php`) uses this method.
 The result is that generic exceptions are thrown from that authentication source.
 
diff --git a/docs/simplesamlphp-modules.md b/docs/simplesamlphp-modules.md
index 92482287a..300cfb802 100644
--- a/docs/simplesamlphp-modules.md
+++ b/docs/simplesamlphp-modules.md
@@ -77,13 +77,13 @@ hooks
 lib
 :   This directory contains classes which belong to this module.
     All classes must be named in the following pattern:
-    `sspmod_<module name>_<class name>` When looking up the filename of
+    `\SimpleSAML\Module\<module name>\<class name>` When looking up the filename of
     a class, SimpleSAMLphp will search for `<class name>` in the `lib`
     directory. Underscores in the class name will be translated into
     slashes.
 
 :   Thus, if SimpleSAMLphp needs to load a class named
-    `sspmod_example_Auth_Source_Example`, it will load the file named
+    `\SimpleSAML\Module\example\Auth\Source\Example`, it will load the file named
     `modules/example/lib/Auth/Source/Example.php`.
 
 templates
diff --git a/lib/SimpleSAML/Auth/Default.php b/lib/SimpleSAML/Auth/Default.php
index bd698a05c..486d3eaa1 100644
--- a/lib/SimpleSAML/Auth/Default.php
+++ b/lib/SimpleSAML/Auth/Default.php
@@ -113,11 +113,11 @@ class DefaultAuth
 
     /**
      * @deprecated This method will be removed in SSP 2.0. Please use
-     * sspmod_saml_Auth_Source_SP::handleUnsolicitedAuth() instead.
+     * \SimpleSAML\Module\saml\Auth\Source\SP::handleUnsolicitedAuth() instead.
      */
     public static function handleUnsolicitedAuth($authId, array $state, $redirectTo)
     {
-        \sspmod_saml_Auth_Source_SP::handleUnsolicitedAuth($authId, $state, $redirectTo);
+        \SimpleSAML\Module\saml\Auth\Source\SP::handleUnsolicitedAuth($authId, $state, $redirectTo);
     }
 
 
diff --git a/lib/SimpleSAML/Error/CriticalConfigurationError.php b/lib/SimpleSAML/Error/CriticalConfigurationError.php
index de8bd0c3c..4e10b90a4 100644
--- a/lib/SimpleSAML/Error/CriticalConfigurationError.php
+++ b/lib/SimpleSAML/Error/CriticalConfigurationError.php
@@ -64,7 +64,7 @@ class CriticalConfigurationError extends ConfigurationError
      *
      * @return CriticalConfigurationError
      */
-    public static function fromException(Exception $exception)
+    public static function fromException(\Exception $exception)
     {
         $reason = null;
         $file = null;
diff --git a/lib/SimpleSAML/Logger/FileLoggingHandler.php b/lib/SimpleSAML/Logger/FileLoggingHandler.php
index 522c17979..beb9e27bb 100644
--- a/lib/SimpleSAML/Logger/FileLoggingHandler.php
+++ b/lib/SimpleSAML/Logger/FileLoggingHandler.php
@@ -107,7 +107,7 @@ class FileLoggingHandler implements LoggingHandlerInterface
             }
 
             $string = str_replace($formats, $replacements, $string);
-            file_put_contents($this->logFile, $string.PHP_EOL, FILE_APPEND);
+            file_put_contents($this->logFile, $string.\PHP_EOL, FILE_APPEND);
         }
     }
 }
diff --git a/lib/SimpleSAML/Metadata/SAMLBuilder.php b/lib/SimpleSAML/Metadata/SAMLBuilder.php
index 5640151e0..0c6c7869b 100644
--- a/lib/SimpleSAML/Metadata/SAMLBuilder.php
+++ b/lib/SimpleSAML/Metadata/SAMLBuilder.php
@@ -122,7 +122,7 @@ class SAMLBuilder
 
         $metadata = \SimpleSAML\Configuration::loadFromArray($metadata, $metadata['entityid']);
         $defaultEndpoint = $metadata->getDefaultEndpoint('SingleSignOnService');
-        $e = new \sspmod_adfs_SAML2_XML_fed_SecurityTokenServiceType();
+        $e = new \SimpleSAML\Module\adfs\SAML2\XML\fed\SecurityTokenServiceType();
         $e->Location = $defaultEndpoint['Location'];
 
         $this->addCertificate($e, $metadata);
diff --git a/lib/SimpleSAML/Module.php b/lib/SimpleSAML/Module.php
index 3f3a2261a..675a2d9d0 100644
--- a/lib/SimpleSAML/Module.php
+++ b/lib/SimpleSAML/Module.php
@@ -152,7 +152,7 @@ class Module
      *
      * This function takes a string on the form "<module>:<class>" and converts it to a class
      * name. It can also check that the given class is a subclass of a specific class. The
-     * resolved classname will be "sspmod_<module>_<$type>_<class>.
+     * resolved classname will be "\SimleSAML\Module\<module>\<$type>\<class>.
      *
      * It is also possible to specify a full classname instead of <module>:<class>.
      *
diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index e3ed6dedb..d253408f1 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -482,7 +482,7 @@ class Utilities
     /**
      * @deprecated This method will be removed in SSP 2.0. Please use SimpleSAML\Utils\XML::formatDOMElement() instead.
      */
-    public static function formatDOMElement(DOMElement $root, $indentBase = '')
+    public static function formatDOMElement(\DOMElement $root, $indentBase = '')
     {
         \SimpleSAML\Utils\XML::formatDOMElement($root, $indentBase);
     }
diff --git a/lib/SimpleSAML/XHTML/EMail.php b/lib/SimpleSAML/XHTML/EMail.php
index c09b17e2f..14d67c9df 100644
--- a/lib/SimpleSAML/XHTML/EMail.php
+++ b/lib/SimpleSAML/XHTML/EMail.php
@@ -44,7 +44,7 @@ class EMail
 
     /*
      * @param string $body
-     * @return void
+     * @return string
      */
     private function getHTML($body)
     {
diff --git a/lib/SimpleSAML/XHTML/IdPDisco.php b/lib/SimpleSAML/XHTML/IdPDisco.php
index 34b70132d..77159f3d7 100644
--- a/lib/SimpleSAML/XHTML/IdPDisco.php
+++ b/lib/SimpleSAML/XHTML/IdPDisco.php
@@ -143,7 +143,7 @@ class IdPDisco
         $this->log('returnIdParam initially set to ['.$this->returnIdParam.']');
 
         if (!array_key_exists('return', $_GET)) {
-            throw new Exception('Missing parameter: return');
+            throw new \Exception('Missing parameter: return');
         } else {
             $this->returnURL = \SimpleSAML\Utils\HTTP::checkURLAllowed($_GET['return']);
         }
@@ -250,7 +250,7 @@ class IdPDisco
             try {
                 $this->metadata->getMetaData($idp, $metadataSet);
                 return $idp;
-            } catch (Exception $e) {
+            } catch (\Exception $e) {
                 // continue
             }
         }
diff --git a/modules/adfs/lib/IdP/ADFS.php b/modules/adfs/lib/IdP/ADFS.php
index 15464d30f..8187aff89 100644
--- a/modules/adfs/lib/IdP/ADFS.php
+++ b/modules/adfs/lib/IdP/ADFS.php
@@ -1,9 +1,11 @@
 <?php
 
+namespace SimpleSAML\Module\adfs\IdP;
+
 use RobRichards\XMLSecLibs\XMLSecurityDSig;
 use RobRichards\XMLSecLibs\XMLSecurityKey;
 
-class sspmod_adfs_IdP_ADFS
+class ADFS
 {
     public static function receiveAuthnRequest(\SimpleSAML\IdP $idp)
     {
@@ -17,12 +19,12 @@ class sspmod_adfs_IdP_ADFS
             $spMetadata = $metadata->getMetaDataConfig($issuer, 'adfs-sp-remote');
 
             \SimpleSAML\Logger::info('ADFS - IdP.prp: Incoming Authentication request: '.$issuer.' id '.$requestid);
-        } catch (Exception $exception) {
+        } catch (\Exception $exception) {
             throw new \SimpleSAML\Error\Error('PROCESSAUTHNREQUEST', $exception);
         }
 
         $state = array(
-            'Responder' => array('sspmod_adfs_IdP_ADFS', 'sendResponse'),
+            'Responder' => array('\SimpleSAML\Module\adfs\IdP\ADFS', 'sendResponse'),
             'SPMetadata' => $spMetadata->toArray(),
             'ForceAuthn' => false,
             'isPassive' => false,
@@ -31,7 +33,7 @@ class sspmod_adfs_IdP_ADFS
         );
 
         if (isset($query['wreply']) && !empty($query['wreply'])) {
-            $state['adfs:wreply'] = SimpleSAML\Utils\HTTP::checkURLAllowed($query['wreply']);
+            $state['adfs:wreply'] = \SimpleSAML\Utils\HTTP::checkURLAllowed($query['wreply']);
         }
 
         $idp->handleAuthenticationRequest($state);		
@@ -164,7 +166,7 @@ MSG;
             }
             $nameid = $attributes[$nameidattribute][0];
         } else {
-            $nameid = SimpleSAML\Utils\Random::generateID();
+            $nameid = \SimpleSAML\Utils\Random::generateID();
         }
 
         $idp = \SimpleSAML\IdP::getByState($state);		
@@ -173,7 +175,7 @@ MSG;
 
         $idp->addAssociation(array(
             'id' => 'adfs:'.$spEntityId,
-            'Handler' => 'sspmod_adfs_IdP_ADFS',
+            'Handler' => '\SimpleSAML\Module\adfs\IdP\ADFS',
             'adfs:entityID' => $spEntityId,
         ));
 
@@ -182,7 +184,7 @@ MSG;
             $assertionLifetime = $idpMetadata->getInteger('assertion.lifetime', 300);
         }
 
-        $response = \sspmod_adfs_IdP_ADFS::generateResponse($idpEntityId, $spEntityId, $nameid, $attributes, $assertionLifetime);
+        $response = ADFS::generateResponse($idpEntityId, $spEntityId, $nameid, $attributes, $assertionLifetime);
 
         $privateKeyFile = \SimpleSAML\Utils\Config::getCertPath($idpMetadata->getString('privatekey'));
         $certificateFile = \SimpleSAML\Utils\Config::getCertPath($idpMetadata->getString('certificate'));
@@ -191,11 +193,11 @@ MSG;
         if ($algo === null) {
             $algo = $idpMetadata->getString('signature.algorithm', XMLSecurityKey::RSA_SHA256);
         }
-        $wresult = \sspmod_adfs_IdP_ADFS::signResponse($response, $privateKeyFile, $certificateFile, $algo);
+        $wresult = ADFS::signResponse($response, $privateKeyFile, $certificateFile, $algo);
 
         $wctx = $state['adfs:wctx'];
         $wreply = $state['adfs:wreply'] ? : $spMetadata->getValue('prp');
-        \sspmod_adfs_IdP_ADFS::postResponse($wreply, $wresult, $wctx);
+        ADFS::postResponse($wreply, $wresult, $wctx);
     }
 
     public static function sendLogoutResponse(\SimpleSAML\IdP $idp, array $state)
@@ -215,7 +217,7 @@ MSG;
         }
 
         $state = array(
-            'Responder' => array('sspmod_adfs_IdP_ADFS', 'sendLogoutResponse'),
+            'Responder' => array('\SimpleSAML\Module\adfs\IdP\ADFS', 'sendLogoutResponse'),
         );
         $assocId = null;
         // TODO: verify that this is really no problem for: 
diff --git a/modules/adfs/lib/SAML2/XML/fed/Const.php b/modules/adfs/lib/SAML2/XML/fed/Const.php
index d24436ca3..1fd7fb15e 100644
--- a/modules/adfs/lib/SAML2/XML/fed/Const.php
+++ b/modules/adfs/lib/SAML2/XML/fed/Const.php
@@ -1,10 +1,14 @@
 <?php
+
+namespace SimpleSAML\Module\adfs\SAML2\XML\fed;
+
 /**
  * Class representing fed Constants.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_adfs_SAML2_XML_fed_Const
+
+class FedConst
 {
     /**
      * The namespace for WS-FED protocol.
diff --git a/modules/adfs/lib/SAML2/XML/fed/Endpoint.php b/modules/adfs/lib/SAML2/XML/fed/Endpoint.php
index 24178c713..d3ac56ad3 100644
--- a/modules/adfs/lib/SAML2/XML/fed/Endpoint.php
+++ b/modules/adfs/lib/SAML2/XML/fed/Endpoint.php
@@ -1,18 +1,22 @@
 <?php
+
+namespace SimpleSAML\Module\adfs\SAML2\XML\fed;
+
 /**
  * Class representing fed Endpoint.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_adfs_SAML2_XML_fed_Endpoint
+
+class Endpoint
 {
     /**
      * Add this endpoint to an XML element.
      *
-     * @param DOMElement $parent  The element we should append this endpoint to.
+     * @param \DOMElement $parent  The element we should append this endpoint to.
      * @param string $name  The name of the element we should create.
      */
-    public static function appendXML(DOMElement $parent, $name, $address)
+    public static function appendXML(\DOMElement $parent, $name, $address)
     {
         assert(is_string($name));
         assert(is_string($address));
diff --git a/modules/adfs/lib/SAML2/XML/fed/SecurityTokenServiceType.php b/modules/adfs/lib/SAML2/XML/fed/SecurityTokenServiceType.php
index d162507e2..30f2f62d4 100644
--- a/modules/adfs/lib/SAML2/XML/fed/SecurityTokenServiceType.php
+++ b/modules/adfs/lib/SAML2/XML/fed/SecurityTokenServiceType.php
@@ -1,17 +1,21 @@
 <?php
+
+namespace SimpleSAML\Module\adfs\SAML2\XML\fed;
+
 /**
  * Class representing SecurityTokenServiceType RoleDescriptor.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_adfs_SAML2_XML_fed_SecurityTokenServiceType extends SAML2_XML_md_RoleDescriptor
+
+class SecurityTokenServiceType extends \SAML2\XML\md\RoleDescriptor
 {
     /**
      * List of supported protocols.
      *
      * @var array
      */
-    public $protocolSupportEnumeration = array(sspmod_adfs_SAML2_XML_fed_Const::NS_FED);
+    public $protocolSupportEnumeration = array(FedConst::NS_FED);
 
     /**
      * The Location of Services.
@@ -23,9 +27,9 @@ class sspmod_adfs_SAML2_XML_fed_SecurityTokenServiceType extends SAML2_XML_md_Ro
     /**
      * Initialize a SecurityTokenServiceType element.
      *
-     * @param DOMElement|null $xml  The XML element we should load.
+     * @param \DOMElement|null $xml  The XML element we should load.
      */
-    public function __construct(DOMElement $xml = null)
+    public function __construct(\DOMElement $xml = null)
     {
         parent::__construct('RoleDescriptor', $xml);
         if ($xml === null) {
@@ -36,19 +40,19 @@ class sspmod_adfs_SAML2_XML_fed_SecurityTokenServiceType extends SAML2_XML_md_Ro
     /**
      * Convert this SecurityTokenServiceType RoleDescriptor to XML.
      *
-     * @param DOMElement $parent  The element we should add this contact to.
-     * @return DOMElement  The new ContactPerson-element.
+     * @param \DOMElement $parent  The element we should add this contact to.
+     * @return \DOMElement  The new ContactPerson-element.
      */
-    public function toXML(DOMElement $parent)
+    public function toXML(\DOMElement $parent)
     {
         assert(is_string($this->Location));
 
         $e = parent::toXML($parent);
-        $e->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:fed', sspmod_adfs_SAML2_XML_fed_Const::NS_FED);
+        $e->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:fed', FedConst::NS_FED);
         $e->setAttributeNS(\SAML2\Constants::NS_XSI, 'xsi:type', 'fed:SecurityTokenServiceType');
-        sspmod_adfs_SAML2_XML_fed_TokenTypesOffered::appendXML($e);
-        sspmod_adfs_SAML2_XML_fed_Endpoint::appendXML($e, 'SecurityTokenServiceEndpoint', $this->Location);
-        sspmod_adfs_SAML2_XML_fed_Endpoint::appendXML($e, 'fed:PassiveRequestorEndpoint', $this->Location);
+        TokenTypesOffered::appendXML($e);
+        Endpoint::appendXML($e, 'SecurityTokenServiceEndpoint', $this->Location);
+        Endpoint::appendXML($e, 'fed:PassiveRequestorEndpoint', $this->Location);
 
         return $e;
     }
diff --git a/modules/adfs/lib/SAML2/XML/fed/TokenTypesOffered.php b/modules/adfs/lib/SAML2/XML/fed/TokenTypesOffered.php
index 280b80c3a..8e30f442c 100644
--- a/modules/adfs/lib/SAML2/XML/fed/TokenTypesOffered.php
+++ b/modules/adfs/lib/SAML2/XML/fed/TokenTypesOffered.php
@@ -1,22 +1,26 @@
 <?php
+
+namespace SimpleSAML\Module\adfs\SAML2\XML\fed;
+
 /**
  * Class representing fed TokenTypesOffered.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_adfs_SAML2_XML_fed_TokenTypesOffered
+
+class TokenTypesOffered
 {
     /**
      * Add tokentypesoffered to an XML element.
      *
-     * @param DOMElement $parent  The element we should append this endpoint to.
+     * @param \DOMElement $parent  The element we should append this endpoint to.
      */
-    public static function appendXML(DOMElement $parent)
+    public static function appendXML(\DOMElement $parent)
     {
-        $e = $parent->ownerDocument->createElementNS(sspmod_adfs_SAML2_XML_fed_Const::NS_FED, 'fed:TokenTypesOffered');
+        $e = $parent->ownerDocument->createElementNS(FedConst::NS_FED, 'fed:TokenTypesOffered');
         $parent->appendChild($e);
 
-        $tokentype = $parent->ownerDocument->createElementNS(sspmod_adfs_SAML2_XML_fed_Const::NS_FED, 'fed:TokenType');
+        $tokentype = $parent->ownerDocument->createElementNS(FedConst::NS_FED, 'fed:TokenType');
         $tokentype->setAttribute('Uri', 'urn:oasis:names:tc:SAML:1.0:assertion');
         $e->appendChild($tokentype);
 
diff --git a/modules/adfs/www/idp/prp.php b/modules/adfs/www/idp/prp.php
index 6000d72db..1f5d85e2b 100644
--- a/modules/adfs/www/idp/prp.php
+++ b/modules/adfs/www/idp/prp.php
@@ -1,4 +1,5 @@
 <?php
+
 /**
  * ADFS PRP IDP protocol support for SimpleSAMLphp.
  *
@@ -14,9 +15,9 @@ $idp = \SimpleSAML\IdP::getById('adfs:' . $idpEntityId);
 
 if (isset($_GET['wa'])) {
     if ($_GET['wa'] === 'wsignout1.0') {
-        sspmod_adfs_IdP_ADFS::receiveLogoutMessage($idp);
+        \SimpleSAML\Module\adfs\IdP\ADFS::receiveLogoutMessage($idp);
     } else if ($_GET['wa'] === 'wsignin1.0') {
-        sspmod_adfs_IdP_ADFS::receiveAuthnRequest($idp);
+        \SimpleSAML\Module\adfs\IdP\ADFS::receiveAuthnRequest($idp);
     }
     assert(false);
 } elseif (isset($_GET['assocId'])) {
diff --git a/modules/authX509/lib/Auth/Process/ExpiryWarning.php b/modules/authX509/lib/Auth/Process/ExpiryWarning.php
index 8e0972429..3457ff4b4 100644
--- a/modules/authX509/lib/Auth/Process/ExpiryWarning.php
+++ b/modules/authX509/lib/Auth/Process/ExpiryWarning.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authX509\Auth\Process;
+
 /**
  * Filter which shows a warning if the user's client certificate is about to expire.
  *
@@ -14,7 +16,8 @@
  * @author Joost van Dijk, SURFnet. <Joost.vanDijk@surfnet.nl>
  * @package SimpleSAMLphp
  */
-class sspmod_authX509_Auth_Process_ExpiryWarning extends \SimpleSAML\Auth\ProcessingFilter
+
+class ExpiryWarning extends \SimpleSAML\Auth\ProcessingFilter
 {
 
     private $warndaysbefore = 30;
@@ -35,14 +38,14 @@ class sspmod_authX509_Auth_Process_ExpiryWarning extends \SimpleSAML\Auth\Proces
         if (array_key_exists('warndaysbefore', $config)) {
             $this->warndaysbefore = $config['warndaysbefore'];
             if (!is_string($this->warndaysbefore)) {
-                throw new Exception('Invalid value for \'warndaysbefore\'-option to authX509::ExpiryWarning filter.');
+                throw new \Exception('Invalid value for \'warndaysbefore\'-option to authX509::ExpiryWarning filter.');
             }
         }
 
         if (array_key_exists('renewurl', $config)) {
             $this->renewurl = $config['renewurl'];
             if (!is_string($this->renewurl)) {
-                throw new Exception('Invalid value for \'renewurl\'-option to authX509::ExpiryWarning filter.');
+                throw new \Exception('Invalid value for \'renewurl\'-option to authX509::ExpiryWarning filter.');
             }
         }
     }
@@ -72,7 +75,7 @@ class sspmod_authX509_Auth_Process_ExpiryWarning extends \SimpleSAML\Auth\Proces
         $client_cert = $_SERVER['SSL_CLIENT_CERT'];
         $client_cert_data = openssl_x509_parse($client_cert);
         if ($client_cert_data == false) {
-            SimpleSAML\Logger::error('authX509: invalid cert');
+            \SimpleSAML\Logger::error('authX509: invalid cert');
             return;
         }
         $validTo = $client_cert_data['validTo_time_t'];
diff --git a/modules/authX509/lib/Auth/Source/X509userCert.php b/modules/authX509/lib/Auth/Source/X509userCert.php
index 2dc74bc77..54dc20fb4 100644
--- a/modules/authX509/lib/Auth/Source/X509userCert.php
+++ b/modules/authX509/lib/Auth/Source/X509userCert.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authX509\Auth\Source;
+
 /**
  * This class implements x509 certificate authentication with certificate validation against an LDAP directory.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
+class X509userCert extends \SimpleSAML\Auth\Source
 {
     /**
      * x509 attributes to use from the certificate for searching the user in the LDAP directory.
@@ -50,7 +52,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
 
         parent::__construct($info, $config);
 
-        $this->ldapcf = new sspmod_ldap_ConfigHelper(
+        $this->ldapcf = new \SimpleSAML\Module\ldap\ConfigHelper(
             $config,
             'Authentication source ' . var_export($this->authId, true)
         );
@@ -104,7 +106,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
         $client_cert = $_SERVER['SSL_CLIENT_CERT'];
         $client_cert_data = openssl_x509_parse($client_cert);
         if ($client_cert_data === false) {
-            SimpleSAML\Logger::error('authX509: invalid cert');
+            \SimpleSAML\Logger::error('authX509: invalid cert');
             $state['authX509.error'] = "INVALIDCERT";
             $this->authFailed($state);
 
@@ -117,7 +119,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
             // value is scalar
             if (array_key_exists($x509_attr, $client_cert_data['subject'])) {
                 $value = $client_cert_data['subject'][$x509_attr];
-                SimpleSAML\Logger::info('authX509: cert '. $x509_attr.' = '.$value);
+                \SimpleSAML\Logger::info('authX509: cert '. $x509_attr.' = '.$value);
                 $dn = $ldapcf->searchfordn($ldap_attr, $value, true);
                 if ($dn !== null) {
                     break;
@@ -126,7 +128,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
         }
 
         if ($dn === null) {
-            SimpleSAML\Logger::error('authX509: cert has no matching user in LDAP.');
+            \SimpleSAML\Logger::error('authX509: cert has no matching user in LDAP.');
             $state['authX509.error'] = "UNKNOWNCERT";
             $this->authFailed($state);
 
@@ -146,7 +148,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
 
         $ldap_certs = $ldapcf->getAttributes($dn, $this->ldapusercert);
         if ($ldap_certs === false) {
-            SimpleSAML\Logger::error('authX509: no certificate found in LDAP for dn='.$dn);
+            \SimpleSAML\Logger::error('authX509: no certificate found in LDAP for dn='.$dn);
             $state['authX509.error'] = "UNKNOWNCERT";
             $this->authFailed($state);
 
@@ -165,7 +167,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
             $pem = \SimpleSAML\Utils\Crypto::der2pem($ldap_cert);
             $ldap_cert_data = openssl_x509_parse($pem);
             if ($ldap_cert_data === false) {
-                SimpleSAML\Logger::error('authX509: cert in LDAP is invalid for dn='.$dn);
+                \SimpleSAML\Logger::error('authX509: cert in LDAP is invalid for dn='.$dn);
                 continue;
             }
 
@@ -180,7 +182,7 @@ class sspmod_authX509_Auth_Source_X509userCert extends \SimpleSAML\Auth\Source
             }
         }
 
-        SimpleSAML\Logger::error('authX509: no matching cert in LDAP for dn='.$dn);
+        \SimpleSAML\Logger::error('authX509: no matching cert in LDAP for dn='.$dn);
         $state['authX509.error'] = "UNKNOWNCERT";
         $this->authFailed($state);
 
diff --git a/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php b/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php
index a3d2ad409..0fe040ee4 100644
--- a/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php
+++ b/modules/authYubiKey/lib/Auth/Process/OTP2YubiPrefix.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authYubiKey\Auth\Process;
+
 /*
  * Copyright (C) 2009  Simon Josefsson <simon@yubico.com>.
  *
@@ -42,9 +44,9 @@
  *      );
  *
  */
-class sspmod_authYubiKey_Auth_Process_OTP2YubiPrefix extends \SimpleSAML\Auth\ProcessingFilter {
-
 
+class OTP2YubiPrefix extends \SimpleSAML\Auth\ProcessingFilter
+{
 	/**
 	 * Filter out YubiKey 'otp' attribute and replace it with
          * a 'yubiPrefix' attribute that leaves out the dynamic part.
@@ -56,7 +58,7 @@ class sspmod_authYubiKey_Auth_Process_OTP2YubiPrefix extends \SimpleSAML\Auth\Pr
 		assert(array_key_exists('Attributes', $state));
 		$attributes = $state['Attributes'];
 
-		SimpleSAML\Logger::debug('OTP2YubiPrefix: enter with attributes: ' . implode(',', array_keys($attributes)));
+		\SimpleSAML\Logger::debug('OTP2YubiPrefix: enter with attributes: ' . implode(',', array_keys($attributes)));
 
 		$otps = $attributes['otp'];
 		$otp = $otps['0'];
@@ -66,11 +68,11 @@ class sspmod_authYubiKey_Auth_Process_OTP2YubiPrefix extends \SimpleSAML\Auth\Pr
 
 		$attributes['yubiPrefix'] = array($identity);
 
-		SimpleSAML\Logger::info('OTP2YubiPrefix: otp: ' . $otp . ' identity: ' . $identity . ' (otp keys: ' . implode(',', array_keys($otps)) . ')');
+		\SimpleSAML\Logger::info('OTP2YubiPrefix: otp: ' . $otp . ' identity: ' . $identity . ' (otp keys: ' . implode(',', array_keys($otps)) . ')');
 
 		unset($attributes['otp']);
 
-		SimpleSAML\Logger::debug('OTP2YubiPrefix: leaving with attributes: ' . implode(',', array_keys($attributes)));
+		\SimpleSAML\Logger::debug('OTP2YubiPrefix: leaving with attributes: ' . implode(',', array_keys($attributes)));
 	}
 
 }
diff --git a/modules/authYubiKey/lib/Auth/Source/YubiKey.php b/modules/authYubiKey/lib/Auth/Source/YubiKey.php
index fdfddf309..fcd1726f3 100644
--- a/modules/authYubiKey/lib/Auth/Source/YubiKey.php
+++ b/modules/authYubiKey/lib/Auth/Source/YubiKey.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authYubiKey\Auth\Source;
+
 /*
  * Copyright (C) 2009  Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * Copyright (C) 2009  Simon Josefsson <simon@yubico.com>.
@@ -40,12 +42,12 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_authYubiKey_Auth_Source_YubiKey extends \SimpleSAML\Auth\Source
+class YubiKey extends \SimpleSAML\Auth\Source
 {
     /**
      * The string used to identify our states.
      */
-    const STAGEID = 'sspmod_authYubiKey_Auth_Source_YubiKey.state';
+    const STAGEID = '\SimpleSAML\Module\authYubiKey\Auth\Source\YubiKey.state';
 
     /**
      * The number of characters of the OTP that is the secure token.
@@ -56,7 +58,7 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends \SimpleSAML\Auth\Source
     /**
      * The key of the AuthId field in the state.
      */
-    const AUTHID = 'sspmod_authYubiKey_Auth_Source_YubiKey.AuthId';
+    const AUTHID = '\SimpleSAML\Module\authYubiKey\Auth\Source\YubiKey.AuthId';
 
     /**
      * The client id/key for use with the Auth_Yubico PHP module.
@@ -133,7 +135,7 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends \SimpleSAML\Auth\Source
         assert(array_key_exists(self::AUTHID, $state));
         $source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
         if ($source === null) {
-            throw new Exception('Could not find authentication source with id '.$state[self::AUTHID]);
+            throw new \Exception('Could not find authentication source with id '.$state[self::AUTHID]);
         }
 
         try {
@@ -186,11 +188,11 @@ class sspmod_authYubiKey_Auth_Source_YubiKey extends \SimpleSAML\Auth\Source
         require_once dirname(dirname(dirname(dirname(__FILE__)))).'/libextinc/Yubico.php';
 
         try {
-            $yubi = new Auth_Yubico($this->yubi_id, $this->yubi_key);
+            $yubi = new \Auth_Yubico($this->yubi_id, $this->yubi_key);
             $yubi->verify($otp);
             $uid = self::getYubiKeyPrefix($otp);
             $attributes = array('uid' => array($uid));
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             \SimpleSAML\Logger::info('YubiKey:'.$this->authId.': Validation error (otp '.$otp.'), debug output: '.$yubi->getLastResponse());
             throw new \SimpleSAML\Error\Error('WRONGUSERPASS', $e);
         }
diff --git a/modules/authYubiKey/www/yubikeylogin.php b/modules/authYubiKey/www/yubikeylogin.php
index c7c42ce95..868d1ec4b 100644
--- a/modules/authYubiKey/www/yubikeylogin.php
+++ b/modules/authYubiKey/www/yubikeylogin.php
@@ -2,7 +2,7 @@
 
 /**
  * This page shows a username/password login form, and passes information from it
- * to the sspmod_core_Auth_UserPassBase class, which is a generic class for
+ * to the \SimpleSAML\Module\core\Auth\UserPassBase class, which is a generic class for
  * username/password authentication.
  *
  * @author Olav Morken, UNINETT AS.
@@ -22,9 +22,9 @@ if (array_key_exists('otp', $_REQUEST)) {
 
 if (!empty($otp)) {
     // attempt to log in
-    $errorCode = \sspmod_authYubiKey_Auth_Source_YubiKey::handleLogin($authStateId, $otp);
+    $errorCode = \SimpleSAML\Module\authYubiKey\Auth\Source\YubiKey::handleLogin($authStateId, $otp);
 } else {
-    $errorCode = NULL;
+    $errorCode = null;
 }
 
 $globalConfig = \SimpleSAML\Configuration::getInstance();
diff --git a/modules/authcrypt/lib/Auth/Source/Hash.php b/modules/authcrypt/lib/Auth/Source/Hash.php
index 3109a9bbe..bcca962ce 100644
--- a/modules/authcrypt/lib/Auth/Source/Hash.php
+++ b/modules/authcrypt/lib/Auth/Source/Hash.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authcrypt\Auth\Source;
+
 /**
  * Authentication source for username & hashed password.
  *
@@ -9,7 +11,8 @@
  * @author Dyonisius Visser, TERENA.
  * @package SimpleSAMLphp
  */
-class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase
+
+class Hash extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
     /**
      * Our users, stored in an associative array. The key of the array is "<username>:<passwordhash>",
@@ -53,7 +56,7 @@ class sspmod_authcrypt_Auth_Source_Hash extends sspmod_core_Auth_UserPassBase
 
             try {
                 $attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes);
-            } catch (Exception $e) {
+            } catch (\Exception $e) {
                 throw new \Exception('Invalid attributes for user '.$username.
                     ' in authentication source '.$this->authId.': '.
                     $e->getMessage());
diff --git a/modules/authcrypt/lib/Auth/Source/Htpasswd.php b/modules/authcrypt/lib/Auth/Source/Htpasswd.php
index dd17bcb9f..86fcc0b15 100644
--- a/modules/authcrypt/lib/Auth/Source/Htpasswd.php
+++ b/modules/authcrypt/lib/Auth/Source/Htpasswd.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authcrypt\Auth\Source;
+
 /**
  * Authentication source for Apache 'htpasswd' files.
  *
@@ -9,7 +11,7 @@
 
 use WhiteHat101\Crypt\APR1_MD5;
 
-class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBase
+class Htpasswd extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
     /**
      * Our users, stored in an array, where each value is "<username>:<passwordhash>".
@@ -45,15 +47,15 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas
         $this->users = array();
 
         if (!$htpasswd = file_get_contents($config['htpasswd_file'])) {
-            throw new Exception('Could not read '.$config['htpasswd_file']);
+            throw new \Exception('Could not read '.$config['htpasswd_file']);
         }
 
         $this->users = explode("\n", trim($htpasswd));
 
         try {
-            $this->attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($config['static_attributes']);
-        } catch (Exception $e) {
-            throw new Exception('Invalid static_attributes in authentication source '.
+            $this->attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($config['static_attributes']);
+        } catch (\Exception $e) {
+            throw new \Exception('Invalid static_attributes in authentication source '.
                 $this->authId.': '.$e->getMessage());
         }
     }
@@ -89,9 +91,9 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas
                 $attributes = array_merge(array('uid' => array($username)), $this->attributes);
 
                 // Traditional crypt(3)
-                if (SimpleSAML\Utils\Crypto::secureCompare($crypted, crypt($password, $crypted))) {
-                    SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
-                    SimpleSAML\Logger::warning(
+                if (\SimpleSAML\Utils\Crypto::secureCompare($crypted, crypt($password, $crypted))) {
+                    \SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
+                    \SimpleSAML\Logger::warning(
                         'CRYPT authentication is insecure. Please consider using something else.'
                     );
                     return $attributes;
@@ -99,14 +101,14 @@ class sspmod_authcrypt_Auth_Source_Htpasswd extends sspmod_core_Auth_UserPassBas
 
                 // Apache's custom MD5
                 if (APR1_MD5::check($password, $crypted)) {
-                    SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
+                    \SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
                     return $attributes;
                 }
 
                 // SHA1 or plain-text
-                if (SimpleSAML\Utils\Crypto::pwValid($crypted, $password)) {
-                    SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
-                    SimpleSAML\Logger::warning(
+                if (\SimpleSAML\Utils\Crypto::pwValid($crypted, $password)) {
+                    \SimpleSAML\Logger::debug('User '.$username.' authenticated successfully');
+                    \SimpleSAML\Logger::warning(
                         'SHA1 and PLAIN TEXT authentication are insecure. Please consider using something else.'
                     );
                     return $attributes;
diff --git a/modules/authfacebook/lib/Auth/Source/Facebook.php b/modules/authfacebook/lib/Auth/Source/Facebook.php
index aeaff9cb0..78c90c5eb 100644
--- a/modules/authfacebook/lib/Auth/Source/Facebook.php
+++ b/modules/authfacebook/lib/Auth/Source/Facebook.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authfacebook\Auth\Source;
+
 /**
  * Authenticate using Facebook Platform.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_authfacebook_Auth_Source_Facebook extends \SimpleSAML\Auth\Source
+class Facebook extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The string used to identify our states.
@@ -88,7 +90,7 @@ class sspmod_authfacebook_Auth_Source_Facebook extends \SimpleSAML\Auth\Source
 		$state[self::AUTHID] = $this->authId;
 		\SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT);
 		
-		$facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state);
+		$facebook = new \SimpleSAML\Module\authfacebook\Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state);
 		$facebook->destroySession();
 
 		$linkback = \SimpleSAML\Module::getModuleURL('authfacebook/linkback.php');
@@ -102,13 +104,13 @@ class sspmod_authfacebook_Auth_Source_Facebook extends \SimpleSAML\Auth\Source
 	public function finalStep(&$state) {
 		assert(is_array($state));
 
-		$facebook = new sspmod_authfacebook_Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state);
+		$facebook = new \SimpleSAML\Module\authfacebook\Facebook(array('appId' => $this->api_key, 'secret' => $this->secret), $state);
 		$uid = $facebook->getUser();
 
 		if (isset($uid) && $uid) {
 			try {
 				$info = $facebook->api("/" . $uid . ($this->user_fields ? "?fields=" . $this->user_fields : ""));
-			} catch (FacebookApiException $e) {
+			} catch (\FacebookApiException $e) {
 				throw new \SimpleSAML\Error\AuthSource($this->authId, 'Error getting user profile.', $e);
 			}
 		}
@@ -133,7 +135,7 @@ class sspmod_authfacebook_Auth_Source_Facebook extends \SimpleSAML\Auth\Source
 		$attributes['facebook_targetedID'] = array('http://facebook.com!' . $uid);
 		$attributes['facebook_cn'] = array($info['name']);
 
-		SimpleSAML\Logger::debug('Facebook Returned Attributes: '. implode(", ", array_keys($attributes)));
+		\SimpleSAML\Logger::debug('Facebook Returned Attributes: '. implode(", ", array_keys($attributes)));
 
 		$state['Attributes'] = $attributes;
 	
diff --git a/modules/authfacebook/lib/Facebook.php b/modules/authfacebook/lib/Facebook.php
index c64eb5b73..edae09bd5 100644
--- a/modules/authfacebook/lib/Facebook.php
+++ b/modules/authfacebook/lib/Facebook.php
@@ -1,12 +1,15 @@
 <?php
 
+namespace SimpleSAML\Module\authfacebook;
+
 require_once(dirname(dirname(__FILE__)) . '/extlibinc/base_facebook.php');
 
 /**
  * Extends the BaseFacebook class with the intent of using
  * PHP sessions to store user ids and access tokens.
  */
-class sspmod_authfacebook_Facebook extends BaseFacebook
+
+class Facebook extends \BaseFacebook
 {
   const FBSS_COOKIE_NAME = 'fbss';
 
@@ -20,6 +23,9 @@ class sspmod_authfacebook_Facebook extends BaseFacebook
   // SimpleSAMLphp state array
   protected $ssp_state;
 
+  // \SimpleSAML\Auth\State
+  protected $state;
+
   /**
    * Identical to the parent constructor, except that
    * we start a PHP session to store the user ID and
@@ -71,7 +77,7 @@ class sspmod_authfacebook_Facebook extends BaseFacebook
       setcookie($cookie_name, $cookie_value, $expire, '/', '.'.$base_domain);
     } else {
       // @codeCoverageIgnoreStart
-      SimpleSAML\Logger::debug(
+      \SimpleSAML\Logger::debug(
         'Shared session ID cookie could not be set! You must ensure you '.
         'create the Facebook instance before headers have been sent. This '.
         'will cause authentication issues after the first request.'
@@ -88,7 +94,7 @@ class sspmod_authfacebook_Facebook extends BaseFacebook
    */
   protected function setPersistentData($key, $value) {
     if (!in_array($key, self::$kSupportedKeys)) {
-      SimpleSAML\Logger::debug("Unsupported key passed to setPersistentData: " . var_export($key, TRUE));
+      \SimpleSAML\Logger::debug("Unsupported key passed to setPersistentData: " . var_export($key, TRUE));
       return;
     }
 
@@ -98,7 +104,7 @@ class sspmod_authfacebook_Facebook extends BaseFacebook
 
   protected function getPersistentData($key, $default = false) {
     if (!in_array($key, self::$kSupportedKeys)) {
-      SimpleSAML\Logger::debug("Unsupported key passed to getPersistentData: " . var_export($key, TRUE));
+      \SimpleSAML\Logger::debug("Unsupported key passed to getPersistentData: " . var_export($key, TRUE));
       return $default;
     }
 
@@ -109,7 +115,7 @@ class sspmod_authfacebook_Facebook extends BaseFacebook
 
   protected function clearPersistentData($key) {
     if (!in_array($key, self::$kSupportedKeys)) {
-      SimpleSAML\Logger::debug("Unsupported key passed to clearPersistentData: " . var_export($key, TRUE));
+      \SimpleSAML\Logger::debug("Unsupported key passed to clearPersistentData: " . var_export($key, TRUE));
       return;
     }
 
diff --git a/modules/authfacebook/www/linkback.php b/modules/authfacebook/www/linkback.php
index b440bc46d..4d856e5ff 100644
--- a/modules/authfacebook/www/linkback.php
+++ b/modules/authfacebook/www/linkback.php
@@ -6,18 +6,18 @@
 
 // For backwards compatability look for AuthState first
 if (array_key_exists('AuthState', $_REQUEST) && !empty($_REQUEST['AuthState'])) {
-    $state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], sspmod_authfacebook_Auth_Source_Facebook::STAGE_INIT);
+    $state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], \SimpleSAML\Module\authfacebook\Auth\Source\Facebook::STAGE_INIT);
 } elseif (array_key_exists('state', $_REQUEST) && !empty($_REQUEST['state'])) {
-    $state = \SimpleSAML\Auth\State::loadState($_REQUEST['state'], sspmod_authfacebook_Auth_Source_Facebook::STAGE_INIT);
+    $state = \SimpleSAML\Auth\State::loadState($_REQUEST['state'], \SimpleSAML\Module\authfacebook\Auth\Source\Facebook::STAGE_INIT);
 } else {
     throw new \SimpleSAML\Error\BadRequest('Missing state parameter on facebook linkback endpoint.');
 }
 
 // Find authentication source
-if (!array_key_exists(sspmod_authfacebook_Auth_Source_Facebook::AUTHID, $state)) {
-    throw new \SimpleSAML\Error\BadRequest('No data in state for ' . sspmod_authfacebook_Auth_Source_Facebook::AUTHID);
+if (!array_key_exists(\SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID, $state)) {
+    throw new \SimpleSAML\Error\BadRequest('No data in state for ' . \SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID);
 }
-$sourceId = $state[sspmod_authfacebook_Auth_Source_Facebook::AUTHID];
+$sourceId = $state[\SimpleSAML\Module\authfacebook\Auth\Source\Facebook::AUTHID];
 
 $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
diff --git a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php
index c6bebd095..892dcb7c7 100644
--- a/modules/authlinkedin/lib/Auth/Source/LinkedIn.php
+++ b/modules/authlinkedin/lib/Auth/Source/LinkedIn.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authlinkedin\Auth\Source;
+
 require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/libextinc/OAuth.php');
 
 /**
@@ -8,9 +10,9 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib
  * @author Brook Schofield, TERENA.
  * @package SimpleSAMLphp
  */
-class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source 
-{
 
+class LinkedIn extends \SimpleSAML\Auth\Source 
+{
     /**
      * The string used to identify our states.
      */
@@ -41,12 +43,12 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source
         parent::__construct($info, $config);
 
         if (!array_key_exists('key', $config))
-            throw new Exception('LinkedIn authentication source is not properly configured: missing [key]');
+            throw new \Exception('LinkedIn authentication source is not properly configured: missing [key]');
 
         $this->key = $config['key'];
 
         if (!array_key_exists('secret', $config))
-            throw new Exception('LinkedIn authentication source is not properly configured: missing [secret]');
+            throw new \Exception('LinkedIn authentication source is not properly configured: missing [secret]');
 
         $this->secret = $config['secret'];
 
@@ -73,17 +75,17 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source
         $state[self::AUTHID] = $this->authId;
 
         $stateID = \SimpleSAML\Auth\State::getStateId($state);
-        SimpleSAML\Logger::debug('authlinkedin auth state id = ' . $stateID);
+        \SimpleSAML\Logger::debug('authlinkedin auth state id = ' . $stateID);
 
-        $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
+        $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret);
 
         // Get the request token
         $requestToken = $consumer->getRequestToken(
             'https://api.linkedin.com/uas/oauth/requestToken',
-            array('oauth_callback' => SimpleSAML\Module::getModuleUrl('authlinkedin') . '/linkback.php?stateid=' . $stateID)
+            array('oauth_callback' => \SimpleSAML\Module::getModuleUrl('authlinkedin') . '/linkback.php?stateid=' . $stateID)
         );
 
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             "Got a request token from the OAuth service provider [" .
             $requestToken->key . "] with the secret [" . $requestToken->secret . "]"
         );
@@ -102,9 +104,9 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source
     {
         $requestToken = $state['authlinkedin:requestToken'];
 
-        $consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
+        $consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret);
 
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             "oauth: Using this request token [" .
             $requestToken->key . "] with the secret [" . $requestToken->secret . "]"
         );
@@ -115,7 +117,7 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source
             array('oauth_verifier' => $state['authlinkedin:oauth_verifier'])
         );
 
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             "Got an access token from the OAuth service provider [" .
             $accessToken->key . "] with the secret [" . $accessToken->secret . "]"
         );
@@ -135,7 +137,7 @@ class sspmod_authlinkedin_Auth_Source_LinkedIn extends \SimpleSAML\Auth\Source
             $attributes['linkedin_user'] = array($userdata['id'] . '@linkedin.com');
         }
 
-        SimpleSAML\Logger::debug('LinkedIn Returned Attributes: '. implode(", ",array_keys($attributes)));
+        \SimpleSAML\Logger::debug('LinkedIn Returned Attributes: '. implode(", ",array_keys($attributes)));
 
         $state['Attributes'] = $attributes;
     }
diff --git a/modules/authlinkedin/www/linkback.php b/modules/authlinkedin/www/linkback.php
index e4694e755..58770b8b4 100644
--- a/modules/authlinkedin/www/linkback.php
+++ b/modules/authlinkedin/www/linkback.php
@@ -7,7 +7,7 @@
 if (!array_key_exists('stateid', $_REQUEST)) {
     throw new \Exception('Lost OAuth Client State');
 }
-$state = \SimpleSAML\Auth\State::loadState($_REQUEST['stateid'], sspmod_authlinkedin_Auth_Source_LinkedIn::STAGE_INIT);
+$state = \SimpleSAML\Auth\State::loadState($_REQUEST['stateid'], \SimpleSAML\Module\authlinkedin\Auth\Source\LinkedIn::STAGE_INIT);
 
 // http://developer.linkedin.com/docs/DOC-1008#2_Redirect_the_User_to_our_Authorization_Server
 if (array_key_exists('oauth_verifier', $_REQUEST)) {
@@ -17,8 +17,8 @@ if (array_key_exists('oauth_verifier', $_REQUEST)) {
 }
 
 // Find authentication source
-assert(array_key_exists(sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID, $state));
-$sourceId = $state[sspmod_authlinkedin_Auth_Source_LinkedIn::AUTHID];
+assert(array_key_exists(\SimpleSAML\Module\authlinkedin\Auth\Source\LinkedIn::AUTHID, $state));
+$sourceId = $state[\SimpleSAML\Module\authlinkedin\Auth\Source\LinkedIn::AUTHID];
 
 $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
diff --git a/modules/authorize/lib/Auth/Process/Authorize.php b/modules/authorize/lib/Auth/Process/Authorize.php
index 15127f776..8bac338e6 100644
--- a/modules/authorize/lib/Auth/Process/Authorize.php
+++ b/modules/authorize/lib/Auth/Process/Authorize.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authorize\Auth\Process;
+
 /**
  * Filter to authorize only certain users.
  * See docs directory.
@@ -7,8 +9,9 @@
  * @author Ernesto Revilla, Yaco Sistemas SL., Ryan Panning
  * @package SimpleSAMLphp
  */
-class sspmod_authorize_Auth_Process_Authorize extends \SimpleSAML\Auth\ProcessingFilter {
 
+class Authorize extends \SimpleSAML\Auth\ProcessingFilter
+{
 	/**
 	 * Flag to deny/unauthorize the user a attribute filter IS found
 	 *
@@ -61,10 +64,10 @@ class sspmod_authorize_Auth_Process_Authorize extends \SimpleSAML\Auth\Processin
 			if (is_string($values))
 				$values = array($values);
 			if (!is_array($values))
-				throw new Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, TRUE));
+				throw new \Exception('Filter Authorize: Attribute values is neither string nor array: ' . var_export($attribute, TRUE));
 			foreach ($values as $value){
 				if(!is_string($value)) {
-					throw new Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, TRUE) . ' value: ' . var_export($value, TRUE) . ' Config is: ' . var_export($config, TRUE));
+					throw new \Exception('Filter Authorize: Each value should be a string for attribute: ' . var_export($attribute, TRUE) . ' value: ' . var_export($value, TRUE) . ' Config is: ' . var_export($config, TRUE));
 				}
 			}
 			$this->valid_attribute_values[$attribute] = $values;
diff --git a/modules/authtwitter/lib/Auth/Source/Twitter.php b/modules/authtwitter/lib/Auth/Source/Twitter.php
index d58a7c530..3bf984f9c 100644
--- a/modules/authtwitter/lib/Auth/Source/Twitter.php
+++ b/modules/authtwitter/lib/Auth/Source/Twitter.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authtwitter\Auth\Source;
+
 require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/libextinc/OAuth.php');
 
 /**
@@ -8,7 +10,8 @@ require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/oauth/lib
  * @author Andreas Ă…kre Solberg, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_authtwitter_Auth_Source_Twitter extends \SimpleSAML\Auth\Source
+
+class Twitter extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The string used to identify our states.
@@ -77,11 +80,11 @@ class sspmod_authtwitter_Auth_Source_Twitter extends \SimpleSAML\Auth\Source
 		
 		$stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT);
 		
-		$consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
+		$consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret);
 		// Get the request token
-		$linkback = SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID));
+		$linkback = \SimpleSAML\Module::getModuleURL('authtwitter/linkback.php', array('AuthState' => $stateID));
 		$requestToken = $consumer->getRequestToken('https://api.twitter.com/oauth/request_token', array('oauth_callback' => $linkback));
-		SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" .
+		\SimpleSAML\Logger::debug("Got a request token from the OAuth service provider [" .
 			$requestToken->key . "] with the secret [" . $requestToken->secret . "]");
 
 		$state['authtwitter:authdata:requestToken'] = $requestToken;
@@ -113,14 +116,14 @@ class sspmod_authtwitter_Auth_Source_Twitter extends \SimpleSAML\Auth\Source
 		}
 		$parameters['oauth_verifier'] = (string)$_REQUEST['oauth_verifier'];
 		
-		$consumer = new sspmod_oauth_Consumer($this->key, $this->secret);
+		$consumer = new \SimpleSAML\Module\oauth\Consumer($this->key, $this->secret);
 		
-		SimpleSAML\Logger::debug("oauth: Using this request token [" .
+		\SimpleSAML\Logger::debug("oauth: Using this request token [" .
 			$requestToken->key . "] with the secret [" . $requestToken->secret . "]");
 
 		// Replace the request token with an access token
 		$accessToken = $consumer->getAccessToken('https://api.twitter.com/oauth/access_token', $requestToken, $parameters);
-		SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [" .
+		\SimpleSAML\Logger::debug("Got an access token from the OAuth service provider [" .
 			$accessToken->key . "] with the secret [" . $accessToken->secret . "]");
 
 		$verify_credentials_url = 'https://api.twitter.com/1.1/account/verify_credentials.json';
diff --git a/modules/authtwitter/www/linkback.php b/modules/authtwitter/www/linkback.php
index d24408ebe..fc0184059 100644
--- a/modules/authtwitter/www/linkback.php
+++ b/modules/authtwitter/www/linkback.php
@@ -7,13 +7,13 @@
 if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
     throw new \SimpleSAML\Error\BadRequest('Missing state parameter on twitter linkback endpoint.');
 }
-$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], sspmod_authtwitter_Auth_Source_Twitter::STAGE_INIT);
+$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], \SimpleSAML\Module\authtwitter\Auth\Source\Twitter::STAGE_INIT);
 
 // Find authentication source
-if (!array_key_exists(sspmod_authtwitter_Auth_Source_Twitter::AUTHID, $state)) {
-    throw new \SimpleSAML\Error\BadRequest('No data in state for ' . sspmod_authtwitter_Auth_Source_Twitter::AUTHID);
+if (!array_key_exists(\SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID, $state)) {
+    throw new \SimpleSAML\Error\BadRequest('No data in state for ' . \SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID);
 }
-$sourceId = $state[sspmod_authtwitter_Auth_Source_Twitter::AUTHID];
+$sourceId = $state[\SimpleSAML\Module\authtwitter\Auth\Source\Twitter::AUTHID];
 
 $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
diff --git a/modules/authwindowslive/lib/Auth/Source/LiveID.php b/modules/authwindowslive/lib/Auth/Source/LiveID.php
index 1e3ef2045..474d6d800 100644
--- a/modules/authwindowslive/lib/Auth/Source/LiveID.php
+++ b/modules/authwindowslive/lib/Auth/Source/LiveID.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\authwindowslive\Auth\Source;
+
 /**
  * Authenticate using LiveID.
  *
@@ -7,9 +9,8 @@
  * @author Guy Halse, TENET.
  * @package SimpleSAMLphp
  */
-class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
+class LiveID extends \SimpleSAML\Auth\Source
 {
-
     /**
      * The string used to identify our states.
      */
@@ -30,7 +31,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
      * @param array $info  Information about this authentication source.
      * @param array $config  Configuration.
      *
-     * @throws Exception In case of misconfiguration.
+     * @throws \Exception In case of misconfiguration.
      */
     public function __construct($info, $config)
     {
@@ -41,13 +42,13 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
         parent::__construct($info, $config);
 
         if (!array_key_exists('key', $config)) {
-            throw new Exception('LiveID authentication source is not properly configured: missing [key]');
+            throw new \Exception('LiveID authentication source is not properly configured: missing [key]');
         }
 
         $this->key = $config['key'];
 
         if (!array_key_exists('secret', $config)) {
-            throw new Exception('LiveID authentication source is not properly configured: missing [secret]');
+            throw new \Exception('LiveID authentication source is not properly configured: missing [secret]');
         }
 
         $this->secret = $config['secret'];
@@ -68,7 +69,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
 
         $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT);
 
-        SimpleSAML\Logger::debug('authwindowslive auth state id = ' . $stateID);
+        \SimpleSAML\Logger::debug('authwindowslive auth state id = ' . $stateID);
 
         // authenticate the user
         // documentation at:
@@ -77,7 +78,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
                 . '?client_id=' . $this->key
                 . '&response_type=code'
                 . '&response_mode=query'
-                . '&redirect_uri=' . urlencode(SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php')
+                . '&redirect_uri=' . urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php')
                 . '&state=' . urlencode($stateID)
                 . '&scope=' . urlencode('openid https://graph.microsoft.com/user.read')
         ;
@@ -89,11 +90,11 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
     /**
      * @param $state
      *
-     * @throws Exception
+     * @throws \Exception
      */
     public function finalStep(&$state)
     {
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             "authwindowslive oauth: Using this verification code [".$state['authwindowslive:verification_code']."]"
         );
 
@@ -104,7 +105,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
                 . '&client_secret=' . urlencode($this->secret)
                 . '&scope=' . urlencode('https://graph.microsoft.com/user.read')
                 . '&grant_type=authorization_code'
-                . '&redirect_uri=' . urlencode(SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php')
+                . '&redirect_uri=' . urlencode(\SimpleSAML\Module::getModuleUrl('authwindowslive') . '/linkback.php')
                 . '&code=' . urlencode($state['authwindowslive:verification_code']);
 
         $context = array(
@@ -121,13 +122,13 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
 
         // error checking of $response to make sure we can proceed
         if (!array_key_exists('access_token', $response)) {
-            throw new Exception(
+            throw new \Exception(
                 '['.$response['error'].'] '.$response['error_description'].
                 "\r\nNo access_token returned - cannot proceed\r\n" . implode(', ', $response['error_codes'])
             );
         }
 
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             "authwindowslive: Got an access token from the OAuth service provider [".$response['access_token']."]"
         );
 
@@ -139,7 +140,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
 
         // this is the simplest case
         if (!array_key_exists('@odata.context', $userdata) || array_key_exists('error', $userdata)) {
-            throw new Exception(
+            throw new \Exception(
                 'Unable to retrieve userdata from Microsoft Graph ['.$userdata['error']['code'].'] '.
                 $userdata['error']['message']
             );
@@ -155,7 +156,7 @@ class sspmod_authwindowslive_Auth_Source_LiveID extends \SimpleSAML\Auth\Source
         }
 
 
-        SimpleSAML\Logger::debug('LiveID Returned Attributes: '. implode(", ", array_keys($attributes)));
+        \SimpleSAML\Logger::debug('LiveID Returned Attributes: '. implode(", ", array_keys($attributes)));
 
         $state['Attributes'] = $attributes;
     }
diff --git a/modules/authwindowslive/www/linkback.php b/modules/authwindowslive/www/linkback.php
index 8b407d7ac..31637deb7 100644
--- a/modules/authwindowslive/www/linkback.php
+++ b/modules/authwindowslive/www/linkback.php
@@ -7,7 +7,7 @@
 if (!array_key_exists('state', $_REQUEST)) {
     throw new \Exception('Lost OAuth Client State');
 }
-$state = \SimpleSAML\Auth\State::loadState($_REQUEST['state'], sspmod_authwindowslive_Auth_Source_LiveID::STAGE_INIT);
+$state = \SimpleSAML\Auth\State::loadState($_REQUEST['state'], \SimpleSAML\Module\authwindowslive\Auth\Source\LiveID::STAGE_INIT);
 
 // http://msdn.microsoft.com/en-us/library/ff749771.aspx
 if (array_key_exists('code', $_REQUEST)) {
@@ -33,8 +33,8 @@ if (array_key_exists('code', $_REQUEST)) {
 }
 
 // find authentication source
-assert(array_key_exists(sspmod_authwindowslive_Auth_Source_LiveID::AUTHID, $state));
-$sourceId = $state[sspmod_authwindowslive_Auth_Source_LiveID::AUTHID];
+assert(array_key_exists(\SimpleSAML\Module\authwindowslive\Auth\Source\LiveID::AUTHID, $state));
+$sourceId = $state[\SimpleSAML\Module\authwindowslive\Auth\Source\LiveID::AUTHID];
 
 $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
diff --git a/modules/cas/lib/Auth/Source/CAS.php b/modules/cas/lib/Auth/Source/CAS.php
index 9195bd89a..e58f36f11 100644
--- a/modules/cas/lib/Auth/Source/CAS.php
+++ b/modules/cas/lib/Auth/Source/CAS.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\cas\Auth\Source;
+
 /**
  * Authenticate using CAS.
  *
@@ -9,17 +11,17 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
+class CAS extends \SimpleSAML\Auth\Source
 {
     /**
      * The string used to identify our states.
      */
-    const STAGE_INIT = 'sspmod_cas_Auth_Source_CAS.state';
+    const STAGE_INIT = '\SimpleSAML\Module\cas\Auth\Source\CAS.state';
 
     /**
      * The key of the AuthId field in the state.
      */
-    const AUTHID = 'sspmod_cas_Auth_Source_CAS.AuthId';
+    const AUTHID = '\SimpleSAML\Module\cas\Auth\Source\CAS.AuthId';
 
     /**
      * @var array with ldap configuration
@@ -32,12 +34,12 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
     private $_casConfig;
 
     /**
-     * @var cas chosen validation method
+     * @var string cas chosen validation method
      */
 
     private $_validationMethod;
     /**
-     * @var cas login method
+     * @var string cas login method
      */
     private $_loginMethod;
 
@@ -56,11 +58,11 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
         parent::__construct($info, $config);
 
         if (!array_key_exists('cas', $config)) {
-            throw new Exception('cas authentication source is not properly configured: missing [cas]');
+            throw new \Exception('cas authentication source is not properly configured: missing [cas]');
         }
 
         if (!array_key_exists('ldap', $config)) {
-            throw new Exception('ldap authentication source is not properly configured: missing [ldap]');
+            throw new \Exception('ldap authentication source is not properly configured: missing [ldap]');
         }
 
         $this->_casConfig = $config['cas'];
@@ -71,13 +73,13 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
         } elseif(isset($this->_casConfig['validate'])) {
             $this->_validationMethod = 'validate';
         } else {
-            throw new Exception("validate or serviceValidate not specified");
+            throw new \Exception("validate or serviceValidate not specified");
         }
 
         if (isset($this->_casConfig['login'])) {
             $this->_loginMethod =  $this->_casConfig['login'];
         } else {
-            throw new Exception("cas login URL not specified");
+            throw new \Exception("cas login URL not specified");
         }
     }
 
@@ -88,7 +90,7 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
      * @param string $ticket
      * @param string $service
      *
-     * @return list username and attributes
+     * @return array username and attributes
      */
     private function casValidate($ticket, $service)
     {
@@ -102,7 +104,7 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
         if (strcmp($res[0], "yes") == 0) {
             return array($res[1], array());
         } else {
-            throw new Exception("Failed to validate CAS service ticket: $ticket");
+            throw new \Exception("Failed to validate CAS service ticket: $ticket");
         }
     }
 
@@ -113,7 +115,7 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
      * @param string $ticket
      * @param string $service
      *
-     * @return list username and attributes
+     * @return array username and attributes
      */
     private function casServiceValidate($ticket, $service)
     {
@@ -127,12 +129,12 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
         $result = \SimpleSAML\Utils\HTTP::fetch($url);
 
         $dom = \SAML2\DOMDocumentFactory::fromString($result);
-        $xPath = new DOMXpath($dom);
+        $xPath = new \DOMXpath($dom);
         $xPath->registerNamespace("cas", 'http://www.yale.edu/tp/cas');
         $success = $xPath->query("/cas:serviceResponse/cas:authenticationSuccess/cas:user");
         if ($success->length == 0) {
             $failure = $xPath->evaluate("/cas:serviceResponse/cas:authenticationFailure");
-            throw new Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent);
+            throw new \Exception("Error when validating CAS service ticket: " . $failure->item(0)->textContent);
         } else {
             $attributes = array();
             if ($casattributes = $this->_casConfig['attributes']) { # some has attributes in the xml - attributes is a list of XPath expressions to get them
@@ -156,7 +158,7 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
      *
      * @param string $ticket
      * @param string $service
-     * @return list username and attributes
+     * @return array username and attributes
      */
     protected function casValidation($ticket, $service)
     {
@@ -169,15 +171,15 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
                 return $this->casServiceValidate($ticket, $service);
                 break;
             default:
-                throw new Exception("validate or serviceValidate not specified");
+                throw new \Exception("validate or serviceValidate not specified");
         }
     }
 
 
     /**
      * Called by linkback, to finish validate/ finish logging in.
-     * @param state $state
-     * @return list username, casattributes/ldap attributes
+     * @param array $state
+     * @return array username, casattributes/ldap attributes
      */
     public function finalStep(&$state)
     {
@@ -221,7 +223,7 @@ class sspmod_cas_Auth_Source_CAS extends \SimpleSAML\Auth\Source
 
         $stateID = \SimpleSAML\Auth\State::saveState($state, self::STAGE_INIT);
 
-        $serviceUrl = SimpleSAML\Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID));
+        $serviceUrl = \SimpleSAML\Module::getModuleURL('cas/linkback.php', array('stateID' => $stateID));
 
         \SimpleSAML\Utils\HTTP::redirectTrustedURL($this->_loginMethod, array('service' => $serviceUrl));
     }
diff --git a/modules/cas/www/linkback.php b/modules/cas/www/linkback.php
index 3b1699d9e..a429b9c8e 100644
--- a/modules/cas/www/linkback.php
+++ b/modules/cas/www/linkback.php
@@ -7,7 +7,7 @@
 if (!isset($_GET['stateID'])) {
     throw new \SimpleSAML\Error\BadRequest('Missing stateID parameter.');
 }
-$state = \SimpleSAML\Auth\State::loadState($_GET['stateID'], sspmod_cas_Auth_Source_CAS::STAGE_INIT);
+$state = \SimpleSAML\Auth\State::loadState($_GET['stateID'], \SimpleSAML\Module\cas\Auth\Source\CAS::STAGE_INIT);
 
 if (!isset($_GET['ticket'])) {
     throw new \SimpleSAML\Error\BadRequest('Missing ticket parameter.');
@@ -15,12 +15,12 @@ if (!isset($_GET['ticket'])) {
 $state['cas:ticket'] = (string)$_GET['ticket'];
 
 // Find authentication source
-assert(array_key_exists(sspmod_cas_Auth_Source_CAS::AUTHID, $state));
-$sourceId = $state[sspmod_cas_Auth_Source_CAS::AUTHID];
+assert(array_key_exists(\SimpleSAML\Module\cas\Auth\Source\CAS::AUTHID, $state));
+$sourceId = $state[\SimpleSAML\Module\cas\Auth\Source\CAS::AUTHID];
 
 $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
-    throw new Exception('Could not find authentication source with id ' . $sourceId);
+    throw new \Exception('Could not find authentication source with id ' . $sourceId);
 }
 
 $source->finalStep($state);
diff --git a/modules/cdc/lib/Auth/Process/CDC.php b/modules/cdc/lib/Auth/Process/CDC.php
index d3f1eb0e8..c616e7aea 100644
--- a/modules/cdc/lib/Auth/Process/CDC.php
+++ b/modules/cdc/lib/Auth/Process/CDC.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\module\cdc\Auth\Process;
+
 /**
  * Filter for setting the SAML 2 common domain cookie.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_cdc_Auth_Process_CDC extends \SimpleSAML\Auth\ProcessingFilter
+
+class CDC extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Our CDC domain.
@@ -18,7 +21,7 @@ class sspmod_cdc_Auth_Process_CDC extends \SimpleSAML\Auth\ProcessingFilter
     /**
      * Our CDC client.
      *
-     * @var sspmod_cdc_Client
+     * @var \SimpleSAML\Module\cdc\Client
      */
     private $client;
 
@@ -39,7 +42,7 @@ class sspmod_cdc_Auth_Process_CDC extends \SimpleSAML\Auth\ProcessingFilter
         }
         $this->domain = (string)$config['domain'];
 
-        $this->client = new sspmod_cdc_Client($this->domain);
+        $this->client = new \SimpleSAML\Module\cdc\Client($this->domain);
     }
 
 
@@ -53,7 +56,7 @@ class sspmod_cdc_Auth_Process_CDC extends \SimpleSAML\Auth\ProcessingFilter
         assert(is_array($state));
 
         if (!isset($state['Source']['entityid'])) {
-            SimpleSAML\Logger::warning('saml:CDC: Could not find IdP entityID.');
+            \SimpleSAML\Logger::warning('saml:CDC: Could not find IdP entityID.');
             return;
         }
 
diff --git a/modules/cdc/lib/Client.php b/modules/cdc/lib/Client.php
index ab59fa628..6af90fa49 100644
--- a/modules/cdc/lib/Client.php
+++ b/modules/cdc/lib/Client.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\cdc;
+
 /**
  * CDC client class.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_cdc_Client
+
+class Client
 {
     /**
      * Our CDC domain.
@@ -18,7 +21,7 @@ class sspmod_cdc_Client
     /**
      * The CDC server we send requests to.
      *
-     * @var sspmod_cdc_Server|NULL
+     * @var Server|NULL
      */
     private $server;
 
@@ -33,7 +36,7 @@ class sspmod_cdc_Client
         assert(is_string($domain));
 
         $this->domain = $domain;
-        $this->server = new sspmod_cdc_Server($domain);
+        $this->server = new Server($domain);
     }
 
 
diff --git a/modules/cdc/lib/Server.php b/modules/cdc/lib/Server.php
index 11ba1b0c4..b7afe2613 100644
--- a/modules/cdc/lib/Server.php
+++ b/modules/cdc/lib/Server.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\cdc;
+
 /**
  * CDC server class.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_cdc_Server
+class Server
 {
     /**
      * The domain.
@@ -117,7 +119,7 @@ class sspmod_cdc_Server
         }
 
         $domain = $request['domain'];
-        $server = new sspmod_cdc_Server($domain);
+        $server = new Server($domain);
 
         $server->validate('CDCRequest');
         $server->handleRequest($request);
@@ -136,7 +138,7 @@ class sspmod_cdc_Server
         }
         $op = (string)$request['op'];
 
-        SimpleSAML\Logger::info('Received CDC request with "op": ' . var_export($op, true));
+        \SimpleSAML\Logger::info('Received CDC request with "op": ' . var_export($op, true));
 
         if (!isset($request['return'])) {
             throw new \SimpleSAML\Error\BadRequest('Missing "return" in CDC request.');
@@ -371,7 +373,7 @@ class sspmod_cdc_Server
             $idp = base64_decode($idp);
             if ($idp === false) {
                 // Not properly base64 encoded
-                SimpleSAML\Logger::warning('CDC - Invalid base64-encoding of CDC entry.');
+                \SimpleSAML\Logger::warning('CDC - Invalid base64-encoding of CDC entry.');
                 return array();
             }
         }
diff --git a/modules/cdc/www/resume.php b/modules/cdc/www/resume.php
index 903e13fb4..1e6f79103 100644
--- a/modules/cdc/www/resume.php
+++ b/modules/cdc/www/resume.php
@@ -6,7 +6,7 @@ if (!array_key_exists('domain', $_REQUEST)) {
 }
 
 $domain = (string)$_REQUEST['domain'];
-$client = new sspmod_cdc_Client($domain);
+$client = new \SimpleSAML\Module\cdc\Client($domain);
 
 $response = $client->getResponse();
 if ($response === null) {
diff --git a/modules/cdc/www/server.php b/modules/cdc/www/server.php
index f84b7a906..d5cfd16ec 100644
--- a/modules/cdc/www/server.php
+++ b/modules/cdc/www/server.php
@@ -1,3 +1,3 @@
 <?php
 
-sspmod_cdc_Server::processRequest();
\ No newline at end of file
+\SimpleSAML\Module\cdc\Server::processRequest();
diff --git a/modules/consent/docs/consent.md b/modules/consent/docs/consent.md
index 33e15a38e..560c63d2a 100644
--- a/modules/consent/docs/consent.md
+++ b/modules/consent/docs/consent.md
@@ -149,7 +149,7 @@ The following options can be used when configuring the Consent module:
 `store`
 :   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 
+    \SimpleSAML\Module\<module>\Consent\Store\<class>. The consent module comes with two 
     built in storage backends: 'consent:Cookie' and 'consent:Database'. See 
     the separate section on setting up consent using different storage methods. 
     This option is optional. If the option is not set, then the user is asked to 
diff --git a/modules/consent/lib/Auth/Process/Consent.php b/modules/consent/lib/Auth/Process/Consent.php
index 639884570..e2744aab1 100644
--- a/modules/consent/lib/Auth/Process/Consent.php
+++ b/modules/consent/lib/Auth/Process/Consent.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\consent\Auth\Process;
+
 /**
  * Consent Authentication Processing filter
  *
@@ -14,7 +16,7 @@ use SimpleSAML\Module;
 use SimpleSAML\Stats;
 use SimpleSAML\Utils;
 
-class sspmod_consent_Auth_Process_Consent extends \SimpleSAML\Auth\ProcessingFilter
+class Consent extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Button to receive focus
@@ -40,7 +42,7 @@ class sspmod_consent_Auth_Process_Consent extends \SimpleSAML\Auth\ProcessingFil
     /**
      * Consent backend storage configuration
      *
-     * @var sspmod_consent_Store|null
+     * @var \SimpleSAML\Module\consent\Store|null
      */
     private $_store = null;
 
@@ -142,7 +144,7 @@ class sspmod_consent_Auth_Process_Consent extends \SimpleSAML\Auth\ProcessingFil
 
         if (array_key_exists('store', $config)) {
             try {
-                $this->_store = sspmod_consent_Store::parseStoreConfig($config['store']);
+                $this->_store = \SimpleSAML\Module\consent\Store::parseStoreConfig($config['store']);
             } catch (\Exception $e) {
                 Logger::error(
                     'Consent: Could not create consent storage: '.
@@ -314,7 +316,7 @@ class sspmod_consent_Auth_Process_Consent extends \SimpleSAML\Auth\ProcessingFil
                 $state['consent:store.userId'] = $userId;
                 $state['consent:store.destination'] = $targetedId;
                 $state['consent:store.attributeSet'] = $attributeSet;
-            } catch (Exception $e) {
+            } catch (\Exception $e) {
                 Logger::error('Consent: Error reading from storage: '.$e->getMessage());
                 Logger::stats('Ccnsent failed');
                 Stats::log('consent:failed', $statsData);
@@ -340,7 +342,7 @@ class sspmod_consent_Auth_Process_Consent extends \SimpleSAML\Auth\ProcessingFil
         }
 
         // Save state and redirect
-        $id = Auth\State::saveState($state, 'consent:request');
+        $id = \SimpleSAML\Auth\State::saveState($state, 'consent:request');
         $url = Module::getModuleURL('consent/getconsent.php');
         Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
     }
diff --git a/modules/consent/lib/Consent/Store/Cookie.php b/modules/consent/lib/Consent/Store/Cookie.php
index fc61b309b..fa24d6ebe 100644
--- a/modules/consent/lib/Consent/Store/Cookie.php
+++ b/modules/consent/lib/Consent/Store/Cookie.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\consent\Consent\Store;
+
 /**
  * Cookie storage for consent
  *
@@ -18,7 +21,8 @@
  * @author  Olav Morken <olav.morken@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
+
+class Cookie extends \SimpleSAML\Module\consent\Store
 {
     /**
      * Check for consent.
@@ -42,17 +46,17 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
 
         $data = $userId . ':' . $attributeSet . ':' . $destinationId;
 
-        SimpleSAML\Logger::debug('Consent cookie - Get [' . $data . ']');
+        \SimpleSAML\Logger::debug('Consent cookie - Get [' . $data . ']');
 
         if (!array_key_exists($cookieName, $_COOKIE)) {
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 'Consent cookie - no cookie with name \'' .
                 $cookieName . '\'.'
             );
             return false;
         }
         if (!is_string($_COOKIE[$cookieName])) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Value of consent cookie wasn\'t a string. Was: ' .
                 var_export($_COOKIE[$cookieName], true)
             );
@@ -62,13 +66,13 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
         $data = self::_sign($data);
 
         if ($_COOKIE[$cookieName] !== $data) {
-            SimpleSAML\Logger::info(
+            \SimpleSAML\Logger::info(
                 'Attribute set changed from the last time consent was given.'
             );
             return false;
         }
 
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             'Consent cookie - found cookie with correct name and value.'
         );
 
@@ -97,7 +101,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
         $name = self::_getCookieName($userId, $destinationId);
         $value = $userId . ':' . $attributeSet . ':' . $destinationId;
 
-        SimpleSAML\Logger::debug('Consent cookie - Set [' . $value . ']');
+        \SimpleSAML\Logger::debug('Consent cookie - Set [' . $value . ']');
 
         $value = self::_sign($value);
         $this->_setConsentCookie($name, $value);
@@ -131,14 +135,14 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
      *
      * @return void This method does not return.
      *
-     * @throws Exception This method always throws an exception indicating that it is not possible to delete all given
+     * @throws \Exception This method always throws an exception indicating that it is not possible to delete all given
      * consents with this handler.
      */
     public function deleteAllConsents($userId)
     {
         assert(is_string($userId));
 
-        throw new Exception(
+        throw new \Exception(
             'The cookie consent handler does not support delete of all consents...'
         );
     }
@@ -159,7 +163,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
 
         $ret = array();
 
-        $cookieNameStart = 'sspmod_consent:';
+        $cookieNameStart = '\SimpleSAML\Module\consent:';
         $cookieNameStartLen = strlen($cookieNameStart);
         foreach ($_COOKIE as $name => $value) {
             if (substr($name, 0, $cookieNameStartLen) !== $cookieNameStart) {
@@ -173,7 +177,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
 
             $tmp = explode(':', $value, 3);
             if (count($tmp) !== 3) {
-                SimpleSAML\Logger::warning(
+                \SimpleSAML\Logger::warning(
                     'Consent cookie with invalid value: ' . $value
                 );
                 continue;
@@ -205,7 +209,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
     {
         assert(is_string($data));
 
-        $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
+        $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
 
         return sha1($secretSalt . $data . $secretSalt) . ':' . $data;
     }
@@ -226,14 +230,14 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
 
         $data = explode(':', $signedData, 2);
         if (count($data) !== 2) {
-            SimpleSAML\Logger::warning('Consent cookie: Missing signature.');
+            \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.');
+            \SimpleSAML\Logger::warning('Consent cookie: Invalid signature.');
             return false;
         }
 
@@ -256,7 +260,7 @@ class sspmod_consent_Consent_Store_Cookie extends sspmod_consent_Store
         assert(is_string($userId));
         assert(is_string($destinationId));
 
-        return 'sspmod_consent:' . sha1($userId . ':' . $destinationId);
+        return '\SimpleSAML\Module\consent:' . sha1($userId . ':' . $destinationId);
     }
 
 
diff --git a/modules/consent/lib/Consent/Store/Database.php b/modules/consent/lib/Consent/Store/Database.php
index 82017a215..739edcff3 100644
--- a/modules/consent/lib/Consent/Store/Database.php
+++ b/modules/consent/lib/Consent/Store/Database.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\consent\Consent\Store;
+
 /**
  * Store consent in database.
  *
@@ -15,7 +18,8 @@
  * @author Olav Morken <olav.morken@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
+
+class Database extends \SimpleSAML\Module\consent\Store
 {
     /**
      * DSN for the database.
@@ -69,17 +73,17 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
      *
      * @param array $config Configuration for database consent store.
      *
-     * @throws Exception in case of a configuration error.
+     * @throws \Exception in case of a configuration error.
      */
     public function __construct($config)
     {
         parent::__construct($config);
 
         if (!array_key_exists('dsn', $config)) {
-            throw new Exception('consent:Database - Missing required option \'dsn\'.');
+            throw new \Exception('consent:Database - Missing required option \'dsn\'.');
         }
         if (!is_string($config['dsn'])) {
-            throw new Exception('consent:Database - \'dsn\' is supposed to be a string.');
+            throw new \Exception('consent:Database - \'dsn\' is supposed to be a string.');
         }
 
         $this->_dsn = $config['dsn'];
@@ -87,7 +91,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         if (array_key_exists('username', $config)) {
             if (!is_string($config['username'])) {
-                throw new Exception('consent:Database - \'username\' is supposed to be a string.');
+                throw new \Exception('consent:Database - \'username\' is supposed to be a string.');
             }
             $this->_username = $config['username'];
         } else {
@@ -96,7 +100,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         if (array_key_exists('password', $config)) {
             if (!is_string($config['password'])) {
-                throw new Exception('consent:Database - \'password\' is supposed to be a string.');
+                throw new \Exception('consent:Database - \'password\' is supposed to be a string.');
             }
             $this->_password = $config['password'];
         } else {
@@ -105,7 +109,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         if (array_key_exists('options', $config)) {
             if (!is_array($config['options'])) {
-                throw new Exception('consent:Database - \'options\' is supposed to be an array.');
+                throw new \Exception('consent:Database - \'options\' is supposed to be an array.');
             }
             $this->_options = $config['options'];
         } else {
@@ -113,7 +117,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
         }
         if (array_key_exists('table', $config)) {
             if (!is_string($config['table'])) {
-                throw new Exception('consent:Database - \'table\' is supposed to be a string.');
+                throw new \Exception('consent:Database - \'table\' is supposed to be a string.');
             }
             $this->_table = $config['table'];
         } else {
@@ -122,7 +126,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         if (isset($config['timeout'])) {
             if (!is_int($config['timeout'])) {
-                throw new Exception('consent:Database - \'timeout\' is supposed to be an integer.');
+                throw new \Exception('consent:Database - \'timeout\' is supposed to be an integer.');
             }
             $this->_timeout = $config['timeout'];
         }
@@ -179,10 +183,10 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         $rowCount = $st->rowCount();
         if ($rowCount === 0) {
-            SimpleSAML\Logger::debug('consent:Database - No consent found.');
+            \SimpleSAML\Logger::debug('consent:Database - No consent found.');
             return false;
         } else {
-            SimpleSAML\Logger::debug('consent:Database - Consent found.');
+            \SimpleSAML\Logger::debug('consent:Database - Consent found.');
             return true;
         }
     }
@@ -220,7 +224,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         if ($st->rowCount() > 0) {
             // Consent has already been stored in the database
-            SimpleSAML\Logger::debug('consent:Database - Updated old consent.');
+            \SimpleSAML\Logger::debug('consent:Database - Updated old consent.');
             return;
         }
 
@@ -232,7 +236,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
         );
 
         if ($st !== false) {
-            SimpleSAML\Logger::debug('consent:Database - Saved new consent.');
+            \SimpleSAML\Logger::debug('consent:Database - Saved new consent.');
         }
         return true;
     }
@@ -263,10 +267,10 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
         }
 
         if ($st->rowCount() > 0) {
-            SimpleSAML\Logger::debug('consent:Database - Deleted consent.');
+            \SimpleSAML\Logger::debug('consent:Database - Deleted consent.');
             return $st->rowCount();
         } else {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'consent:Database - Attempted to delete nonexistent consent'
             );
         }
@@ -294,10 +298,10 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
         }
 
         if ($st->rowCount() > 0) {
-            SimpleSAML\Logger::debug('consent:Database - Deleted (' . $st->rowCount() . ') consent(s).');
+            \SimpleSAML\Logger::debug('consent:Database - Deleted (' . $st->rowCount() . ') consent(s).');
             return $st->rowCount();
         } else {
-            SimpleSAML\Logger::warning('consent:Database - Attempted to delete nonexistent consent');
+            \SimpleSAML\Logger::warning('consent:Database - Attempted to delete nonexistent consent');
         }
     }
 
@@ -327,7 +331,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
             return array();
         }
 
-        while ($row = $st->fetch(PDO::FETCH_NUM)) {
+        while ($row = $st->fetch(\PDO::FETCH_NUM)) {
             $ret[] = $row;
         }
 
@@ -344,7 +348,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
      * @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.
+     * @return \PDOStatement|false  The statement, or false if execution failed.
      */
     private function _execute($statement, $parameters)
     {
@@ -358,7 +362,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         $st = $db->prepare($statement);
         if ($st === false) {
-            SimpleSAML\Logger::error(
+            \SimpleSAML\Logger::error(
                 'consent:Database - Error preparing statement \'' .
                 $statement . '\': ' . self::_formatError($db->errorInfo())
             );
@@ -366,7 +370,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
         }
 
         if ($st->execute($parameters) !== true) {
-            SimpleSAML\Logger::error(
+            \SimpleSAML\Logger::error(
                 'consent:Database - Error executing statement \'' .
                 $statement . '\': ' . self::_formatError($st->errorInfo())
             );
@@ -398,7 +402,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
             return array();
         }
 
-        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+        if ($row = $st->fetch(\PDO::FETCH_NUM)) {
             $ret['total'] = $row[0];
         }
 
@@ -413,7 +417,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
             return array();
         }
 
-        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+        if ($row = $st->fetch(\PDO::FETCH_NUM)) {
             $ret['users'] = $row[0];
         }
 
@@ -427,7 +431,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
             return array();
         }
 
-        if ($row = $st->fetch(PDO::FETCH_NUM)) {
+        if ($row = $st->fetch(\PDO::FETCH_NUM)) {
             $ret['services'] = $row[0];
         }
 
@@ -438,7 +442,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
     /**
      * Get database handle.
      *
-     * @return PDO|false Database handle, or false if we fail to connect.
+     * @return \PDO|false Database handle, or false if we fail to connect.
      */
     private function _getDB()
     {
@@ -448,7 +452,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
 
         $driver_options = array();
         if (isset($this->_timeout)) {
-            $driver_options[PDO::ATTR_TIMEOUT] = $this->_timeout;
+            $driver_options[\PDO::ATTR_TIMEOUT] = $this->_timeout;
         }
         if (isset($this->_options)) {
             $this->_options = array_merge($driver_options, $this->_options);
@@ -456,7 +460,7 @@ class sspmod_consent_Consent_Store_Database extends sspmod_consent_Store
             $this->_options = $driver_options;
         }
 
-        $this->_db = new PDO($this->_dsn, $this->_username, $this->_password, $this->_options);
+        $this->_db = new \PDO($this->_dsn, $this->_username, $this->_password, $this->_options);
 
         return $this->_db;
     }
diff --git a/modules/consent/lib/Logout.php b/modules/consent/lib/Logout.php
index dfd94afde..f82961ee3 100644
--- a/modules/consent/lib/Logout.php
+++ b/modules/consent/lib/Logout.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\consent;
+
 /**
  * Class defining the logout completed handler for the consent page.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_consent_Logout
+class Logout
 {
     public static function postLogout(\SimpleSAML\IdP $idp, array $state)
     {
diff --git a/modules/consent/lib/Store.php b/modules/consent/lib/Store.php
index b9f9ae3ce..528f2ca16 100644
--- a/modules/consent/lib/Store.php
+++ b/modules/consent/lib/Store.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\consent;
+
 /**
  * Base class for consent storage handlers.
  *
@@ -6,7 +9,8 @@
  * @author Olav Morken <olav.morken@uninett.no>
  * @author JAcob Christiansen <jach@wayf.dk>
  */
-abstract class sspmod_consent_Store
+
+abstract class Store
 {
     /**
      * Constructor for the base class.
@@ -74,11 +78,11 @@ abstract class sspmod_consent_Store
      *
      * @return mixed Should be the number of consent removed
      *
-     * @throws Exception
+     * @throws \Exception
      */
     public function deleteAllConsents($userId)
     {
-        throw new Exception('Not implemented: deleteAllConsents()');
+        throw new \Exception('Not implemented: deleteAllConsents()');
     }
 
 
@@ -87,11 +91,11 @@ abstract class sspmod_consent_Store
      *
      * @return mixed Statistics from the consent store
      *
-     * @throws Exception
+     * @throws \Exception
      */
     public function getStatistics()
     {
-        throw new Exception('Not implemented: getStatistics()');
+        throw new \Exception('Not implemented: getStatistics()');
     }
 
 
@@ -115,9 +119,9 @@ abstract class sspmod_consent_Store
      *
      * @param mixed $config The configuration.
      *
-     * @return sspmod_consent_Store An object which implements the sspmod_consent_Store class.
+     * @return \SimpleSAML\Module\consent\Store An object which implements the \SimpleSAML\Module\consent\Store class.
      *
-     * @throws Exception if the configuration is invalid.
+     * @throws \Exception if the configuration is invalid.
      */
     public static function parseStoreConfig($config)
     {
@@ -126,17 +130,17 @@ abstract class sspmod_consent_Store
         }
 
         if (!is_array($config)) {
-            throw new Exception('Invalid configuration for consent store option: '.var_export($config, true));
+            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.');
+            throw new \Exception('Consent store without name given.');
         }
 
-        $className = SimpleSAML\Module::resolveClass(
+        $className = \SimpleSAML\Module::resolveClass(
             $config[0],
             'Consent_Store',
-            'sspmod_consent_Store'
+            '\SimpleSAML\Module\consent\Store'
         );
 
         unset($config[0]);
diff --git a/modules/consent/www/logout.php b/modules/consent/www/logout.php
index 8d4c2f6d8..0065cbea1 100644
--- a/modules/consent/www/logout.php
+++ b/modules/consent/www/logout.php
@@ -10,7 +10,7 @@ if (!array_key_exists('StateId', $_GET)) {
 }
 $state = \SimpleSAML\Auth\State::loadState($_GET['StateId'], 'consent:request');
 
-$state['Responder'] = array('sspmod_consent_Logout', 'postLogout');
+$state['Responder'] = array('\SimpleSAML\Module\consent\Logout', 'postLogout');
 
 $idp = \SimpleSAML\IdP::getByState($state);
 $idp->handleLogoutRequest($state, null);
diff --git a/modules/consentAdmin/www/consentAdmin.php b/modules/consentAdmin/www/consentAdmin.php
index 4ff6031be..57b22db43 100644
--- a/modules/consentAdmin/www/consentAdmin.php
+++ b/modules/consentAdmin/www/consentAdmin.php
@@ -67,12 +67,12 @@ function driveProcessingChain(
      */
     $destination = $sp_metadata['metadata-set'].'|'.$sp_entityid;
 
-    $targeted_id = sspmod_consent_Auth_Process_Consent::getTargetedID($userid, $source, $destination);
-    $attribute_hash = sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes, $hashAttributes);
+    $targeted_id = \SimpleSAML\Module\consent\Auth\Process\Consent::getTargetedID($userid, $source, $destination);
+    $attribute_hash = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes, $hashAttributes);
 
-    SimpleSAML\Logger::info('consentAdmin: user: '.$userid);
-    SimpleSAML\Logger::info('consentAdmin: target: '.$targeted_id);
-    SimpleSAML\Logger::info('consentAdmin: attribute: '.$attribute_hash);
+    \SimpleSAML\Logger::info('consentAdmin: user: '.$userid);
+    \SimpleSAML\Logger::info('consentAdmin: target: '.$targeted_id);
+    \SimpleSAML\Logger::info('consentAdmin: attribute: '.$attribute_hash);
 
     // Return values
     return array($targeted_id, $attribute_hash, $attributes);
@@ -127,7 +127,7 @@ $userid_attributename = (isset($idp_metadata['userid.attribute']) && is_string($
 $userids = $attributes[$userid_attributename];
 
 if (empty($userids)) {
-    throw new Exception('Could not generate useridentifier for storing consent. Attribute ['.
+    throw new \Exception('Could not generate useridentifier for storing consent. Attribute ['.
         $userid_attributename.'] was not available.');
 }
 
@@ -146,7 +146,7 @@ if (!empty($_GET['action'])) {
     $action = $_GET["action"];
 }
 
-SimpleSAML\Logger::critical('consentAdmin: sp: '.$sp_entityid.' action: '.$action);
+\SimpleSAML\Logger::critical('consentAdmin: sp: '.$sp_entityid.' action: '.$action);
 
 // Remove services, whitch have consent disabled
 if (isset($idp_metadata['consent.disable'])) {
@@ -157,13 +157,13 @@ if (isset($idp_metadata['consent.disable'])) {
     }
 }
 
-SimpleSAML\Logger::info('consentAdmin: '.$idp_entityid);
+\SimpleSAML\Logger::info('consentAdmin: '.$idp_entityid);
 
 // Parse consent config
-$consent_storage = sspmod_consent_Store::parseStoreConfig($cA_config->getValue('consentadmin'));
+$consent_storage = \SimpleSAML\Module\consent\Store::parseStoreConfig($cA_config->getValue('consentadmin'));
 
 // Calc correct user ID hash
-$hashed_user_id = sspmod_consent_Auth_Process_Consent::getHashedUserID($userid, $source);
+$hashed_user_id = \SimpleSAML\Module\consent\Auth\Process\Consent::getHashedUserID($userid, $source);
 
 // If a checkbox have been clicked
 if ($action !== null && $sp_entityid !== null) {
@@ -233,10 +233,10 @@ foreach ($all_sp_metadata as $sp_entityid => $sp_values) {
     // Check if consent exists
     if (array_key_exists($targeted_id, $user_consent)) {
         $sp_status = "changed";
-        SimpleSAML\Logger::info('consentAdmin: changed');
+        \SimpleSAML\Logger::info('consentAdmin: changed');
         // Check if consent is valid. (Possible that attributes has changed)
         if ($user_consent[$targeted_id] == $attribute_hash) {
-            SimpleSAML\Logger::info('consentAdmin: ok');
+            \SimpleSAML\Logger::info('consentAdmin: ok');
             $sp_status = "ok";
         }
         // Consent does not exists
diff --git a/modules/core/lib/ACL.php b/modules/core/lib/ACL.php
index 4c020ebdf..b99483b74 100644
--- a/modules/core/lib/ACL.php
+++ b/modules/core/lib/ACL.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core;
+
 /**
  * Generic library for access control lists.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_core_ACL {
+
+class ACL {
 
 	/**
 	 * The access control list, as an array.
diff --git a/modules/core/lib/Auth/Process/AttributeAdd.php b/modules/core/lib/Auth/Process/AttributeAdd.php
index 1eaaf331a..e83a54f05 100644
--- a/modules/core/lib/Auth/Process/AttributeAdd.php
+++ b/modules/core/lib/Auth/Process/AttributeAdd.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter to add attributes.
  *
@@ -8,8 +10,9 @@
  * @author Olav Morken, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_core_Auth_Process_AttributeAdd extends \SimpleSAML\Auth\ProcessingFilter {
 
+class AttributeAdd extends \SimpleSAML\Auth\ProcessingFilter
+{
 	/**
 	 * Flag which indicates wheter this filter should append new values or replace old values.
 	 */
@@ -40,7 +43,7 @@ class sspmod_core_Auth_Process_AttributeAdd extends \SimpleSAML\Auth\ProcessingF
 				if($values === '%replace') {
 					$this->replace = TRUE;
 				} else {
-					throw new Exception('Unknown flag: ' . var_export($values, TRUE));
+					throw new \Exception('Unknown flag: ' . var_export($values, TRUE));
 				}
 				continue;
 			}
@@ -50,7 +53,7 @@ class sspmod_core_Auth_Process_AttributeAdd extends \SimpleSAML\Auth\ProcessingF
 			}
 			foreach($values as $value) {
 				if(!is_string($value)) {
-					throw new Exception('Invalid value for attribute ' . $name . ': ' .
+					throw new \Exception('Invalid value for attribute ' . $name . ': ' .
 						var_export($values, TRUE));
 				}
 			}
@@ -81,5 +84,4 @@ class sspmod_core_Auth_Process_AttributeAdd extends \SimpleSAML\Auth\ProcessingF
 			}
 		}
 	}
-
 }
diff --git a/modules/core/lib/Auth/Process/AttributeAlter.php b/modules/core/lib/Auth/Process/AttributeAlter.php
index 1f6743405..da0546e9b 100644
--- a/modules/core/lib/Auth/Process/AttributeAlter.php
+++ b/modules/core/lib/Auth/Process/AttributeAlter.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter to modify attributes using regular expressions
  *
@@ -9,7 +11,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter
+class AttributeAlter extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Should the pattern found be replaced?
diff --git a/modules/core/lib/Auth/Process/AttributeCopy.php b/modules/core/lib/Auth/Process/AttributeCopy.php
index 0f2e7b2fe..0e156d956 100644
--- a/modules/core/lib/Auth/Process/AttributeCopy.php
+++ b/modules/core/lib/Auth/Process/AttributeCopy.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Attribute filter for renaming attributes.
  *
@@ -16,7 +18,7 @@
  *
  */
 
-class sspmod_core_Auth_Process_AttributeCopy extends \SimpleSAML\Auth\ProcessingFilter
+class AttributeCopy extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * Assosiative array with the mappings of attribute names.
@@ -38,11 +40,11 @@ class sspmod_core_Auth_Process_AttributeCopy extends \SimpleSAML\Auth\Processing
 		foreach($config as $source => $destination) {
 
 			if(!is_string($source)) {
-				throw new Exception('Invalid source attribute name: ' . var_export($source, TRUE));
+				throw new \Exception('Invalid source attribute name: ' . var_export($source, TRUE));
 			}
 
 			if(!is_string($destination) && !is_array($destination)) {
-				throw new Exception('Invalid destination attribute name: ' . var_export($destination, TRUE));
+				throw new \Exception('Invalid destination attribute name: ' . var_export($destination, TRUE));
 			}
 
 			$this->map[$source] = $destination;
diff --git a/modules/core/lib/Auth/Process/AttributeLimit.php b/modules/core/lib/Auth/Process/AttributeLimit.php
index cffe4f8c0..70e991590 100644
--- a/modules/core/lib/Auth/Process/AttributeLimit.php
+++ b/modules/core/lib/Auth/Process/AttributeLimit.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * A filter for limiting which attributes are passed on.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter
+class AttributeLimit extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * List of attributes which this filter will allow through.
diff --git a/modules/core/lib/Auth/Process/AttributeMap.php b/modules/core/lib/Auth/Process/AttributeMap.php
index 29135c2ee..6eb229cd4 100644
--- a/modules/core/lib/Auth/Process/AttributeMap.php
+++ b/modules/core/lib/Auth/Process/AttributeMap.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Attribute filter for renaming attributes.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_AttributeMap extends \SimpleSAML\Auth\ProcessingFilter
+class AttributeMap extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Associative array with the mappings of attribute names.
@@ -47,11 +49,11 @@ class sspmod_core_Auth_Process_AttributeMap extends \SimpleSAML\Auth\ProcessingF
             }
 
             if (!is_string($origName)) {
-                throw new Exception('Invalid attribute name: '.var_export($origName, true));
+                throw new \Exception('Invalid attribute name: '.var_export($origName, true));
             }
 
             if (!is_string($newName) && !is_array($newName)) {
-                throw new Exception('Invalid attribute name: '.var_export($newName, true));
+                throw new \Exception('Invalid attribute name: '.var_export($newName, true));
             }
 
             $this->map[$origName] = $newName;
@@ -78,22 +80,22 @@ class sspmod_core_Auth_Process_AttributeMap extends \SimpleSAML\Auth\ProcessingF
 
         $m = explode(':', $fileName);
         if (count($m) === 2) { // we are asked for a file in a module
-            if (!SimpleSAML\Module::isModuleEnabled($m[0])) {
-                throw new Exception("Module '$m[0]' is not enabled.");
+            if (!\SimpleSAML\Module::isModuleEnabled($m[0])) {
+                throw new \Exception("Module '$m[0]' is not enabled.");
             }
-            $filePath = SimpleSAML\Module::getModuleDir($m[0]).'/attributemap/'.$m[1].'.php';
+            $filePath = \SimpleSAML\Module::getModuleDir($m[0]).'/attributemap/'.$m[1].'.php';
         } else {
             $filePath = $config->getPathValue('attributenamemapdir', 'attributemap/').$fileName.'.php';
         }
 
         if (!file_exists($filePath)) {
-            throw new Exception('Could not find attribute map file: '.$filePath);
+            throw new \Exception('Could not find attribute map file: '.$filePath);
         }
 
         $attributemap = null;
         include($filePath);
         if (!is_array($attributemap)) {
-            throw new Exception('Attribute map file "'.$filePath.'" didn\'t define an attribute map.');
+            throw new \Exception('Attribute map file "'.$filePath.'" didn\'t define an attribute map.');
         }
 
         if ($this->duplicate) {
diff --git a/modules/core/lib/Auth/Process/AttributeRealm.php b/modules/core/lib/Auth/Process/AttributeRealm.php
index bf2a8cfad..c32543d8b 100644
--- a/modules/core/lib/Auth/Process/AttributeRealm.php
+++ b/modules/core/lib/Auth/Process/AttributeRealm.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter that will take the user ID on the format 'andreas@uninett.no'
  * and create a new attribute 'realm' that includes the value after the '@' sign.
@@ -9,7 +11,7 @@
  * @deprecated Use ScopeFromAttribute instead.
  */
 
-class sspmod_core_Auth_Process_AttributeRealm extends \SimpleSAML\Auth\ProcessingFilter
+class AttributeRealm extends \SimpleSAML\Auth\ProcessingFilter
 {
     private $attributename = 'realm';
 
@@ -42,7 +44,7 @@ class sspmod_core_Auth_Process_AttributeRealm extends \SimpleSAML\Auth\Processin
         $attributes =& $request['Attributes'];
 
         if (!array_key_exists('UserID', $request)) {
-            throw new Exception('core:AttributeRealm: Missing UserID for this user. Please' .
+            throw new \Exception('core:AttributeRealm: Missing UserID for this user. Please' .
                 ' check the \'userid.attribute\' option in the metadata against the' .
                 ' attributes provided by the authentication source.');
         }
diff --git a/modules/core/lib/Auth/Process/Cardinality.php b/modules/core/lib/Auth/Process/Cardinality.php
index 2960e86fe..983431fce 100644
--- a/modules/core/lib/Auth/Process/Cardinality.php
+++ b/modules/core/lib/Auth/Process/Cardinality.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 use SimpleSAML\Utils\HTTPAdapter;
 
 /**
@@ -9,7 +11,7 @@ use SimpleSAML\Utils\HTTPAdapter;
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFilter
+class Cardinality extends \SimpleSAML\Auth\ProcessingFilter
 {
     /** @var array Associative array with the mappings of attribute names. */
     private $cardinality = array();
@@ -17,7 +19,7 @@ class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFi
     /** @var array Entities that should be ignored */
     private $ignoreEntities = array();
 
-    /** @var HTTP */
+    /** @var HTTPAdapter */
     private $http;
 
     /**
@@ -107,7 +109,7 @@ class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFi
             $entityid = $request['Source']['entityid'];
         }
         if (in_array($entityid, $this->ignoreEntities, true)) {
-            SimpleSAML\Logger::debug('Cardinality: Ignoring assertions from '.$entityid);
+            \SimpleSAML\Logger::debug('Cardinality: Ignoring assertions from '.$entityid);
             return;
         }
 
@@ -123,7 +125,7 @@ class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFi
             /* minimum cardinality */
             if (count($v) < $this->cardinality[$k]['min']) {
                 if ($this->cardinality[$k]['warn']) {
-                    SimpleSAML\Logger::warning(sprintf(
+                    \SimpleSAML\Logger::warning(sprintf(
                         'Cardinality: attribute %s from %s does not meet minimum cardinality of %d (%d)',
                         $k, $entityid, $this->cardinality[$k]['min'], count($v)
                     ));
@@ -136,7 +138,7 @@ class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFi
             /* maximum cardinality */
             if (array_key_exists('max', $this->cardinality[$k]) && count($v) > $this->cardinality[$k]['max']) {
                 if ($this->cardinality[$k]['warn']) {
-                    SimpleSAML\Logger::warning(sprintf(
+                    \SimpleSAML\Logger::warning(sprintf(
                         'Cardinality: attribute %s from %s does not meet maximum cardinality of %d (%d)',
                         $k, $entityid, $this->cardinality[$k]['max'], count($v)
                     ));
@@ -153,7 +155,7 @@ class sspmod_core_Auth_Process_Cardinality extends \SimpleSAML\Auth\ProcessingFi
                 continue;
             }
             if ($this->cardinality[$k]['warn']) {
-                SimpleSAML\Logger::warning(sprintf(
+                \SimpleSAML\Logger::warning(sprintf(
                     'Cardinality: attribute %s from %s is missing',
                     $k, $entityid
                 ));
diff --git a/modules/core/lib/Auth/Process/CardinalitySingle.php b/modules/core/lib/Auth/Process/CardinalitySingle.php
index dc8672b68..0d4b180f3 100644
--- a/modules/core/lib/Auth/Process/CardinalitySingle.php
+++ b/modules/core/lib/Auth/Process/CardinalitySingle.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 use SimpleSAML\Utils\HttpAdapter;
 
 /**
@@ -12,7 +14,7 @@ use SimpleSAML\Utils\HttpAdapter;
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
+class CardinalitySingle extends \SimpleSAML\Auth\ProcessingFilter
 {
     /** @var array Attributes that should be single-valued or we generate an error */
     private $singleValued = array();
@@ -29,7 +31,7 @@ class sspmod_core_Auth_Process_CardinalitySingle extends \SimpleSAML\Auth\Proces
     /** @var array Entities that should be ignored */
     private $ignoreEntities = array();
 
-    /** @var HTTP */
+    /** @var HTTPAdapter */
     private $http;
 
     /**
@@ -81,7 +83,7 @@ class sspmod_core_Auth_Process_CardinalitySingle extends \SimpleSAML\Auth\Proces
             array_key_exists('entityid', $request['Source']) &&
             in_array($request['Source']['entityid'], $this->ignoreEntities, true)
         ) {
-            SimpleSAML\Logger::debug('CardinalitySingle: Ignoring assertions from '.$request['Source']['entityid']);
+            \SimpleSAML\Logger::debug('CardinalitySingle: Ignoring assertions from '.$request['Source']['entityid']);
             return;
         }
 
@@ -110,7 +112,7 @@ class sspmod_core_Auth_Process_CardinalitySingle extends \SimpleSAML\Auth\Proces
         /* abort if we found a problematic attribute */
         if (array_key_exists('core:cardinality:errorAttributes', $request)) {
             $id = \SimpleSAML\Auth\State::saveState($request, 'core:cardinality');
-            $url = SimpleSAML\Module::getModuleURL('core/cardinality_error.php');
+            $url = \SimpleSAML\Module::getModuleURL('core/cardinality_error.php');
             $this->http->redirectTrustedURL($url, array('StateId' => $id));
             return;
         }
diff --git a/modules/core/lib/Auth/Process/ExtendIdPSession.php b/modules/core/lib/Auth/Process/ExtendIdPSession.php
index 6526115dc..4a4bd5ae5 100644
--- a/modules/core/lib/Auth/Process/ExtendIdPSession.php
+++ b/modules/core/lib/Auth/Process/ExtendIdPSession.php
@@ -1,10 +1,12 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Extend IdP session and cookies.
 */
 
-class sspmod_core_Auth_Process_ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter
+class ExtendIdPSession extends \SimpleSAML\Auth\ProcessingFilter
 {
 	public function process(&$state) {
 		assert(is_array($state));
diff --git a/modules/core/lib/Auth/Process/GenerateGroups.php b/modules/core/lib/Auth/Process/GenerateGroups.php
index d4ff3c338..f2bdf41b8 100644
--- a/modules/core/lib/Auth/Process/GenerateGroups.php
+++ b/modules/core/lib/Auth/Process/GenerateGroups.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter to generate a groups attribute based on many of the attributes of the user.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter
+class GenerateGroups extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * The attributes we should generate groups from.
@@ -38,7 +40,7 @@ class sspmod_core_Auth_Process_GenerateGroups extends \SimpleSAML\Auth\Processin
 			// Validate configuration
 			foreach ($config as $attributeName) {
 				if (!is_string($attributeName)) {
-					throw new Exception('Invalid attribute name for core:GenerateGroups filter: ' .
+					throw new \Exception('Invalid attribute name for core:GenerateGroups filter: ' .
 						var_export($attributeName, TRUE));
 				}
 			}
@@ -68,7 +70,7 @@ class sspmod_core_Auth_Process_GenerateGroups extends \SimpleSAML\Auth\Processin
 
 		foreach ($this->generateGroupsFrom as $name) {
 			if (!array_key_exists($name, $attributes)) {
-				SimpleSAML\Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.');
+				\SimpleSAML\Logger::debug('GenerateGroups - attribute \'' . $name . '\' not found.');
 				/* Attribute not present. */
 				continue;
 			}
diff --git a/modules/core/lib/Auth/Process/LanguageAdaptor.php b/modules/core/lib/Auth/Process/LanguageAdaptor.php
index c02228dd7..eb120e29a 100644
--- a/modules/core/lib/Auth/Process/LanguageAdaptor.php
+++ b/modules/core/lib/Auth/Process/LanguageAdaptor.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter to set and get language settings from attributes.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_LanguageAdaptor extends \SimpleSAML\Auth\ProcessingFilter
+class LanguageAdaptor extends \SimpleSAML\Auth\ProcessingFilter
 {
 	private $langattr = 'preferredLanguage';
 
@@ -45,18 +47,18 @@ class sspmod_core_Auth_Process_LanguageAdaptor extends \SimpleSAML\Auth\Processi
 		if (array_key_exists($this->langattr, $attributes))
 			$attrlang = $attributes[$this->langattr][0];
 
-		$lang = SimpleSAML\Locale\Language::getLanguageCookie();
+		$lang = \SimpleSAML\Locale\Language::getLanguageCookie();
 
 
 		if (isset($attrlang))
-			SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']');
+			\SimpleSAML\Logger::debug('LanguageAdaptor: Language in attribute was set [' . $attrlang . ']');
 		if (isset($lang))
-			SimpleSAML\Logger::debug('LanguageAdaptor: Language in session   was set [' . $lang . ']');
+			\SimpleSAML\Logger::debug('LanguageAdaptor: Language in session   was set [' . $lang . ']');
 
 
 		if (isset($attrlang) && !isset($lang)) {
 			// Language set in attribute but not in cookie - update cookie
-			SimpleSAML\Locale\Language::setLanguageCookie($attrlang);
+			\SimpleSAML\Locale\Language::setLanguageCookie($attrlang);
 		} elseif (!isset($attrlang) && isset($lang)) {
 			// Language set in cookie, but not in attribute. Update attribute
 			$request['Attributes'][$this->langattr] = array($lang);
diff --git a/modules/core/lib/Auth/Process/PHP.php b/modules/core/lib/Auth/Process/PHP.php
index 97cca71a0..386a59919 100644
--- a/modules/core/lib/Auth/Process/PHP.php
+++ b/modules/core/lib/Auth/Process/PHP.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Attribute filter for running arbitrary PHP code.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_PHP extends \SimpleSAML\Auth\ProcessingFilter
+class PHP extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * The PHP code that should be run.
diff --git a/modules/core/lib/Auth/Process/ScopeAttribute.php b/modules/core/lib/Auth/Process/ScopeAttribute.php
index 7684b18d6..ee7eb0409 100644
--- a/modules/core/lib/Auth/Process/ScopeAttribute.php
+++ b/modules/core/lib/Auth/Process/ScopeAttribute.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Add a scoped variant of an attribute.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_ScopeAttribute extends \SimpleSAML\Auth\ProcessingFilter
+class ScopeAttribute extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * The attribute we extract the scope from.
diff --git a/modules/core/lib/Auth/Process/ScopeFromAttribute.php b/modules/core/lib/Auth/Process/ScopeFromAttribute.php
index 735c30e1c..da41e9ab0 100644
--- a/modules/core/lib/Auth/Process/ScopeFromAttribute.php
+++ b/modules/core/lib/Auth/Process/ScopeFromAttribute.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Retrieve a scope from a source attribute and add it as a virtual target
  * attribute.
@@ -17,7 +19,7 @@
  * attribute.
  */
 
-class sspmod_core_Auth_Process_ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter
+class ScopeFromAttribute extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * The attribute where the scope is taken from
@@ -78,11 +80,11 @@ class sspmod_core_Auth_Process_ScopeFromAttribute extends \SimpleSAML\Auth\Proce
 			$attributes[$this->targetAttribute] = array();
 			$scope = substr($sourceAttrVal, $scopeIndex+1);
 			$attributes[$this->targetAttribute][] = $scope;
-			SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute ' .
+			\SimpleSAML\Logger::debug('ScopeFromAttribute: Inserted new attribute ' .
 			                         $this->targetAttribute . ', with scope ' .
 			                         $scope);
 		} else {
-			SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute ' .
+			\SimpleSAML\Logger::warning('ScopeFromAttribute: The configured source attribute ' .
 			                           $this->sourceAttribute .
 			                           ' does not have a scope. Did not add attribute ' .
 			                           $this->targetAttribute . '.');
diff --git a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
index d75b474fc..35848be87 100644
--- a/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
+++ b/modules/core/lib/Auth/Process/StatisticsWithAttribute.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Log a line in the STAT log with one attribute.
  *
@@ -7,13 +9,13 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_StatisticsWithAttribute extends \SimpleSAML\Auth\ProcessingFilter
+class StatisticsWithAttribute extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * The attribute to log
      * @var string|null
      */
-	private $attribute = null;
+    private $attribute = null;
 
     /**
      * @var string
@@ -41,14 +43,14 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends \SimpleSAML\Auth\
         if (array_key_exists('attributename', $config)) {
             $this->attribute = $config['attributename'];
             if (!is_string($this->attribute)) {
-                throw new Exception('Invalid attribute name given to core:StatisticsWithAttribute filter.');
+                throw new \Exception('Invalid attribute name given to core:StatisticsWithAttribute filter.');
             }
         }
 
         if (array_key_exists('type', $config)) {
             $this->typeTag = $config['type'];
             if (!is_string($this->typeTag)) {
-                throw new Exception('Invalid typeTag given to core:StatisticsWithAttribute filter.');
+                throw new \Exception('Invalid typeTag given to core:StatisticsWithAttribute filter.');
             }
         }
 
@@ -88,10 +90,10 @@ class sspmod_core_Auth_Process_StatisticsWithAttribute extends \SimpleSAML\Auth\
 
         if (!array_key_exists('PreviousSSOTimestamp', $state)) {
             // The user hasn't authenticated with this SP earlier in this session
-            SimpleSAML\Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '. $logAttribute);
+            \SimpleSAML\Logger::stats($isPassive.$this->typeTag.'-first '.$dest.' '.$source.' '. $logAttribute);
         }
 
-        SimpleSAML\Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute);
+        \SimpleSAML\Logger::stats($isPassive.$this->typeTag.' '.$dest.' '.$source.' '.$logAttribute);
 	}
 
     /**
diff --git a/modules/core/lib/Auth/Process/TargetedID.php b/modules/core/lib/Auth/Process/TargetedID.php
index 69888dc84..538d8138f 100644
--- a/modules/core/lib/Auth/Process/TargetedID.php
+++ b/modules/core/lib/Auth/Process/TargetedID.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Filter to generate the eduPersonTargetedID attribute.
  *
@@ -29,7 +31,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_TargetedID extends \SimpleSAML\Auth\ProcessingFilter
+class TargetedID extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * The attribute we should generate the targeted id from, or NULL if we should use the
@@ -60,14 +62,14 @@ class sspmod_core_Auth_Process_TargetedID extends \SimpleSAML\Auth\ProcessingFil
 		if (array_key_exists('attributename', $config)) {
 			$this->attribute = $config['attributename'];
 			if (!is_string($this->attribute)) {
-				throw new Exception('Invalid attribute name given to core:TargetedID filter.');
+				throw new \Exception('Invalid attribute name given to core:TargetedID filter.');
 			}
 		}
 
 		if (array_key_exists('nameId', $config)) {
 			$this->generateNameId = $config['nameId'];
 			if (!is_bool($this->generateNameId)) {
-				throw new Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.');
+				throw new \Exception('Invalid value of \'nameId\'-option to core:TargetedID filter.');
 			}
 		}
 	}
@@ -84,7 +86,7 @@ class sspmod_core_Auth_Process_TargetedID extends \SimpleSAML\Auth\ProcessingFil
 
 		if ($this->attribute === NULL) {
 			if (!array_key_exists('UserID', $state)) {
-				throw new Exception('core:TargetedID: Missing UserID for this user. Please' .
+				throw new \Exception('core:TargetedID: Missing UserID for this user. Please' .
 					' check the \'userid.attribute\' option in the metadata against the' .
 					' attributes provided by the authentication source.');
 			}
@@ -92,7 +94,7 @@ class sspmod_core_Auth_Process_TargetedID extends \SimpleSAML\Auth\ProcessingFil
 			$userID = $state['UserID'];
 		} else {
 			if (!array_key_exists($this->attribute, $state['Attributes'])) {
-				throw new Exception('core:TargetedID: Missing attribute \'' . $this->attribute .
+				throw new \Exception('core:TargetedID: Missing attribute \'' . $this->attribute .
 					'\', which is needed to generate the targeted ID.');
 			}
 
@@ -100,7 +102,7 @@ class sspmod_core_Auth_Process_TargetedID extends \SimpleSAML\Auth\ProcessingFil
 		}
 
 
-		$secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
+		$secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
 
 		if (array_key_exists('Source', $state)) {
 			$srcID = self::getEntityId($state['Source']);
diff --git a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
index 74c7b5dd0..b51180f5c 100644
--- a/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
+++ b/modules/core/lib/Auth/Process/WarnShortSSOInterval.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Process;
+
 /**
  * Give a warning to the user if we receive multiple requests in a short time.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Process_WarnShortSSOInterval extends \SimpleSAML\Auth\ProcessingFilter
+class WarnShortSSOInterval extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * Process a authentication response.
@@ -40,7 +42,7 @@ class sspmod_core_Auth_Process_WarnShortSSOInterval extends \SimpleSAML\Auth\Pro
 			$entityId = 'UNKNOWN';
 		}
 
-		SimpleSAML\Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta .
+		\SimpleSAML\Logger::warning('WarnShortSSOInterval: Only ' . $timeDelta .
 			' seconds since last SSO for this user from the SP ' .
 			var_export($entityId, TRUE));
 
diff --git a/modules/core/lib/Auth/Source/AdminPassword.php b/modules/core/lib/Auth/Source/AdminPassword.php
index 1e37d2539..13afe27f0 100644
--- a/modules/core/lib/Auth/Source/AdminPassword.php
+++ b/modules/core/lib/Auth/Source/AdminPassword.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth\Source;
+
 /**
  * Authentication source which verifies the password against
  * the 'auth.adminpassword' configuration option.
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Auth_Source_AdminPassword extends sspmod_core_Auth_UserPassBase
+class AdminPassword extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
 	/**
 	 * Constructor for this authentication source.
diff --git a/modules/core/lib/Auth/UserPassBase.php b/modules/core/lib/Auth/UserPassBase.php
index ec63c8ffa..324a5fc2c 100644
--- a/modules/core/lib/Auth/UserPassBase.php
+++ b/modules/core/lib/Auth/UserPassBase.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth;
+
 /**
  * Helper class for username/password authentication.
  *
@@ -10,18 +12,18 @@
  * @package SimpleSAMLphp
  */
 
-abstract class sspmod_core_Auth_UserPassBase extends \SimpleSAML\Auth\Source
+abstract class UserPassBase extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The string used to identify our states.
 	 */
-	const STAGEID = 'sspmod_core_Auth_UserPassBase.state';
+	const STAGEID = '\SimpleSAML\Module\core\Auth\UserPassBase.state';
 
 
 	/**
 	 * The key of the AuthId field in the state.
 	 */
-	const AUTHID = 'sspmod_core_Auth_UserPassBase.AuthId';
+	const AUTHID = '\SimpleSAML\Module\core\Auth\UserPassBase.AuthId';
 
 
 	/**
@@ -209,7 +211,7 @@ abstract class sspmod_core_Auth_UserPassBase extends \SimpleSAML\Auth\Source
 		 * Redirect to the login form. We include the identifier of the saved
 		 * state array as a parameter to the login form.
 		 */
-		$url = SimpleSAML\Module::getModuleURL('core/loginuserpass.php');
+		$url = \SimpleSAML\Module::getModuleURL('core/loginuserpass.php');
 		$params = array('AuthState' => $id);
 		\SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
 
@@ -257,7 +259,7 @@ abstract class sspmod_core_Auth_UserPassBase extends \SimpleSAML\Auth\Source
 		assert(array_key_exists(self::AUTHID, $state));
 		$source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
 		if ($source === NULL) {
-			throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
+			throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
 		}
 
 		/*
@@ -268,12 +270,12 @@ abstract class sspmod_core_Auth_UserPassBase extends \SimpleSAML\Auth\Source
 		/* Attempt to log in. */
 		try {
 			$attributes = $source->login($username, $password);
-		} catch (Exception $e) {
-			SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.');
+		} catch (\Exception $e) {
+			\SimpleSAML\Logger::stats('Unsuccessful login attempt from '.$_SERVER['REMOTE_ADDR'].'.');
 			throw $e;
 		}
 
-		SimpleSAML\Logger::stats('User \''.$username.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']);
+		\SimpleSAML\Logger::stats('User \''.$username.'\' successfully authenticated from '.$_SERVER['REMOTE_ADDR']);
 
 		/* Save the attributes we received from the login-function in the $state-array. */
 		assert(is_array($attributes));
diff --git a/modules/core/lib/Auth/UserPassOrgBase.php b/modules/core/lib/Auth/UserPassOrgBase.php
index e3207ee37..c87df897c 100644
--- a/modules/core/lib/Auth/UserPassOrgBase.php
+++ b/modules/core/lib/Auth/UserPassOrgBase.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Auth;
+
 /**
  * Helper class for username/password/organization authentication.
  *
@@ -12,24 +14,24 @@
  * @package SimpleSAMLphp
  */
 
-abstract class sspmod_core_Auth_UserPassOrgBase extends \SimpleSAML\Auth\Source
+abstract class UserPassOrgBase extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The string used to identify our states.
 	 */
-	const STAGEID = 'sspmod_core_Auth_UserPassOrgBase.state';
+	const STAGEID = '\SimpleSAML\Module\core\Auth\UserPassOrgBase.state';
 
 
 	/**
 	 * The key of the AuthId field in the state.
 	 */
-	const AUTHID = 'sspmod_core_Auth_UserPassOrgBase.AuthId';
+	const AUTHID = '\SimpleSAML\Module\core\Auth\UserPassOrgBase.AuthId';
 
 
 	/**
 	 * The key of the OrgId field in the state, identifies which org was selected.
 	 */
-	const ORGID = 'sspmod_core_Auth_UserPassOrgBase.SelectedOrg';
+	const ORGID = '\SimpleSAML\Module\core\Auth\UserPassOrgBase.SelectedOrg';
 
 
 	/**
@@ -154,7 +156,7 @@ abstract class sspmod_core_Auth_UserPassOrgBase extends \SimpleSAML\Auth\Source
 
 		$id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID);
 
-		$url = SimpleSAML\Module::getModuleURL('core/loginuserpassorg.php');
+		$url = \SimpleSAML\Module::getModuleURL('core/loginuserpassorg.php');
 		$params = array('AuthState' => $id);
 		\SimpleSAML\Utils\HTTP::redirectTrustedURL($url, $params);
 	}
@@ -215,7 +217,7 @@ abstract class sspmod_core_Auth_UserPassOrgBase extends \SimpleSAML\Auth\Source
 		assert(array_key_exists(self::AUTHID, $state));
 		$source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
 		if ($source === NULL) {
-			throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
+			throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
 		}
 
 		$orgMethod = $source->getUsernameOrgMethod();
@@ -263,7 +265,7 @@ abstract class sspmod_core_Auth_UserPassOrgBase extends \SimpleSAML\Auth\Source
 		assert(array_key_exists(self::AUTHID, $state));
 		$source = \SimpleSAML\Auth\Source::getById($state[self::AUTHID]);
 		if ($source === NULL) {
-			throw new Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
+			throw new \Exception('Could not find authentication source with id ' . $state[self::AUTHID]);
 		}
 
 		$orgMethod = $source->getUsernameOrgMethod();
diff --git a/modules/core/lib/Stats/Output/File.php b/modules/core/lib/Stats/Output/File.php
index d2cd70520..fe0dc3fdd 100644
--- a/modules/core/lib/Stats/Output/File.php
+++ b/modules/core/lib/Stats/Output/File.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core\Stats\Output;
+
 /**
  * Statistics logger that writes to a set of log files
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Stats_Output_File extends \SimpleSAML\Stats\Output
+class File extends \SimpleSAML\Stats\Output
 {
 	/**
 	 * The log directory.
@@ -37,10 +39,10 @@ class sspmod_core_Stats_Output_File extends \SimpleSAML\Stats\Output
 
 		$this->logDir = $config->getPathValue('directory');
 		if ($this->logDir === NULL) {
-			throw new Exception('Missing "directory" option for core:File');
+			throw new \Exception('Missing "directory" option for core:File');
 		}
 		if (!is_dir($this->logDir)) {
-			throw new Exception('Could not find log directory: ' . var_export($this->logDir, TRUE));
+			throw new \Exception('Could not find log directory: ' . var_export($this->logDir, TRUE));
 		}
 
 	}
diff --git a/modules/core/lib/Stats/Output/Log.php b/modules/core/lib/Stats/Output/Log.php
index 05575058a..b4872bd5b 100644
--- a/modules/core/lib/Stats/Output/Log.php
+++ b/modules/core/lib/Stats/Output/Log.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\core\Stats\Output;
+
 /**
  * Statistics logger that writes to the default logging handler.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_core_Stats_Output_Log extends \SimpleSAML\Stats\Output
+class Log extends \SimpleSAML\Stats\Output
 {
 	/**
 	 * The logging function we should call.
diff --git a/modules/core/lib/Storage/SQLPermanentStorage.php b/modules/core/lib/Storage/SQLPermanentStorage.php
index 0c22f75d8..8db457f66 100644
--- a/modules/core/lib/Storage/SQLPermanentStorage.php
+++ b/modules/core/lib/Storage/SQLPermanentStorage.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\core\Storage;
+
 /**
  * SQLPermanentStorage
  * 
@@ -9,7 +11,8 @@
  * @author Andreas Ă…kre Solberg <andreas@uninett.no>, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_core_Storage_SQLPermanentStorage
+
+class SQLPermanentStorage
 {
     private $db;
 
@@ -22,9 +25,9 @@ class sspmod_core_Storage_SQLPermanentStorage
         $datadir = $config->getPathValue('datadir', 'data/');
 
         if (!is_dir($datadir)) {
-            throw new Exception('Data directory ['.$datadir.'] does not exist');
+            throw new \Exception('Data directory ['.$datadir.'] does not exist');
         } else if (!is_writable($datadir)) {
-            throw new Exception('Data directory ['.$datadir.'] is not writable');
+            throw new \Exception('Data directory ['.$datadir.'] is not writable');
         }
 
         $sqllitedir = $datadir.'sqllite/';
@@ -50,7 +53,7 @@ class sspmod_core_Storage_SQLPermanentStorage
                 ');
             } 
         } else {
-            throw new Exception('Error creating SQL lite database ['.$dbfile.'].');
+            throw new \Exception('Error creating SQL lite database ['.$dbfile.'].');
         }
     }
 
@@ -75,7 +78,7 @@ class sspmod_core_Storage_SQLPermanentStorage
             ':updated' => time(), ':expire' => $expire,
             ':value' => serialize($value));
         $prepared->execute($data);
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         return $results;
     }
 
@@ -89,7 +92,7 @@ class sspmod_core_Storage_SQLPermanentStorage
             ':type' => $type, ':updated' => time(),
             ':expire' => $expire, ':value' => serialize($value));
         $prepared->execute($data);
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         return $results;
     }
 
@@ -100,7 +103,7 @@ class sspmod_core_Storage_SQLPermanentStorage
 
         $prepared = $this->db->prepare($query);
         $prepared->execute();
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         if (count($results) !== 1) {
             return null;
         }
@@ -128,7 +131,7 @@ class sspmod_core_Storage_SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = array(':type' => $type, ':key1' => $key1, ':key2' => $key2);
         $prepared->execute($data);
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         return (count($results) == 1);
     }
 
@@ -139,7 +142,7 @@ class sspmod_core_Storage_SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $prepared->execute();
 
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         if (count($results) == 0) {
             return null;
         }
@@ -153,7 +156,7 @@ class sspmod_core_Storage_SQLPermanentStorage
     public function getKeys($type = null, $key1 = null, $key2 = null, $whichKey = 'type')
     {
         if (!in_array($whichKey, array('key1', 'key2', 'type'), true)) {
-            throw new Exception('Invalid key type');
+            throw new \Exception('Invalid key type');
         }
 
         $conditions = self::getCondition($type, $key1, $key2);
@@ -161,7 +164,7 @@ class sspmod_core_Storage_SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = array('whichKey' => $whichKey);
         $prepared->execute($data);
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
 
         if (count($results) == 0) {
             return null;
@@ -180,7 +183,7 @@ class sspmod_core_Storage_SQLPermanentStorage
         $prepared = $this->db->prepare($query);
         $data = array(':type' => $type, ':key1' => $key1, ':key2' => $key2);
         $prepared->execute($data);
-        $results = $prepared->fetchAll(PDO::FETCH_ASSOC);
+        $results = $prepared->fetchAll(\PDO::FETCH_ASSOC);
         return (count($results) == 1);
     }
 
diff --git a/modules/core/www/idp/logout-iframe-post.php b/modules/core/www/idp/logout-iframe-post.php
index b1e937c00..603cb1fb5 100644
--- a/modules/core/www/idp/logout-iframe-post.php
+++ b/modules/core/www/idp/logout-iframe-post.php
@@ -26,7 +26,7 @@ $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
 $idpMetadata = $idp->getConfig();
 $spMetadata = $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
 
-$lr = sspmod_saml_Message::buildLogoutRequest($idpMetadata, $spMetadata);
+$lr = \SimpleSAML\Module\saml\Message::buildLogoutRequest($idpMetadata, $spMetadata);
 $lr->setSessionIndex($association['saml:SessionIndex']);
 $lr->setNameId($association['saml:NameID']);
 
@@ -41,7 +41,7 @@ if ($encryptNameId === null) {
     $encryptNameId = $idpMetadata->getBoolean('nameid.encryption', false);
 }
 if ($encryptNameId) {
-    $lr->encryptNameId(sspmod_saml_Message::getEncryptionKey($spMetadata));
+    $lr->encryptNameId(\SimpleSAML\Module\saml\Message::getEncryptionKey($spMetadata));
 }
 
 \SimpleSAML\Stats::log('saml:idp:LogoutRequest:sent', array(
diff --git a/modules/core/www/loginuserpass.php b/modules/core/www/loginuserpass.php
index 51cd91b63..bbace6815 100644
--- a/modules/core/www/loginuserpass.php
+++ b/modules/core/www/loginuserpass.php
@@ -2,7 +2,7 @@
 
 /**
  * This page shows a username/password login form, and passes information from it
- * to the sspmod_core_Auth_UserPassBase class, which is a generic class for
+ * to the \SimpleSAML\Module\core\Auth\UserPassBase class, which is a generic class for
  * username/password authentication.
  *
  * @author Olav Morken, UNINETT AS.
@@ -14,11 +14,11 @@ if (!array_key_exists('AuthState', $_REQUEST)) {
 	throw new \SimpleSAML\Error\BadRequest('Missing AuthState parameter.');
 }
 $authStateId = $_REQUEST['AuthState'];
-$state = \SimpleSAML\Auth\State::loadState($authStateId, sspmod_core_Auth_UserPassBase::STAGEID);
+$state = \SimpleSAML\Auth\State::loadState($authStateId, \SimpleSAML\Module\core\Auth\UserPassBase::STAGEID);
 
-$source = \SimpleSAML\Auth\Source::getById($state[sspmod_core_Auth_UserPassBase::AUTHID]);
+$source = \SimpleSAML\Auth\Source::getById($state[\SimpleSAML\Module\core\Auth\UserPassBase::AUTHID]);
 if ($source === NULL) {
-	throw new Exception('Could not find authentication source with id ' . $state[sspmod_core_Auth_UserPassBase::AUTHID]);
+	throw new \Exception('Could not find authentication source with id ' . $state[\SimpleSAML\Module\core\Auth\UserPassBase::AUTHID]);
 }
 
 
@@ -59,12 +59,12 @@ if (!empty($_REQUEST['username']) || !empty($password)) {
     if ($source->isRememberMeEnabled()) {
         if (array_key_exists('remember_me', $_REQUEST) && $_REQUEST['remember_me'] === 'Yes') {
             $state['RememberMe'] = TRUE;
-            $authStateId = \SimpleSAML\Auth\State::saveState($state, sspmod_core_Auth_UserPassBase::STAGEID);
+            $authStateId = \SimpleSAML\Auth\State::saveState($state, \SimpleSAML\Module\core\Auth\UserPassBase::STAGEID);
         }
     }
 
 	try {
-		sspmod_core_Auth_UserPassBase::handleLogin($authStateId, $username, $password);
+		\SimpleSAML\Module\core\Auth\UserPassBase::handleLogin($authStateId, $username, $password);
 	} catch (\SimpleSAML\Error\Error $e) {
 		/* Login failed. Extract error code and parameters, to display the error. */
 		$errorCode = $e->getErrorCode();
diff --git a/modules/core/www/loginuserpassorg.php b/modules/core/www/loginuserpassorg.php
index 037ce592c..ea7050c37 100644
--- a/modules/core/www/loginuserpassorg.php
+++ b/modules/core/www/loginuserpassorg.php
@@ -2,7 +2,7 @@
 
 /**
  * This page shows a username/password/organization login form, and passes information from
- * itto the sspmod_core_Auth_UserPassBase class, which is a generic class for
+ * into the \SimpleSAML\Module\core\Auth\UserPassBase class, which is a generic class for
  * username/password/organization authentication.
  *
  * @author Olav Morken, UNINETT AS.
@@ -14,14 +14,14 @@ if (!array_key_exists('AuthState', $_REQUEST)) {
 	throw new \SimpleSAML\Error\BadRequest('Missing AuthState parameter.');
 }
 $authStateId = $_REQUEST['AuthState'];
-$state = \SimpleSAML\Auth\State::loadState($authStateId, sspmod_core_Auth_UserPassOrgBase::STAGEID);
+$state = \SimpleSAML\Auth\State::loadState($authStateId, \SimpleSAML\Module\core\Auth\UserPassOrgBase::STAGEID);
 
-$source = \SimpleSAML\Auth\Source::getById($state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
+$source = \SimpleSAML\Auth\Source::getById($state[\SimpleSAML\Module\core\Auth\UserPassOrgBase::AUTHID]);
 if ($source === NULL) {
-	throw new Exception('Could not find authentication source with id ' . $state[sspmod_core_Auth_UserPassOrgBase::AUTHID]);
+	throw new \Exception('Could not find authentication source with id ' . $state[\SimpleSAML\Module\core\Auth\UserPassOrgBase::AUTHID]);
 }
 
-$organizations = \sspmod_core_Auth_UserPassOrgBase::listOrganizations($authStateId);
+$organizations = \SimpleSAML\Module\core\Auth\UserPassOrgBase::listOrganizations($authStateId);
 
 if (array_key_exists('username', $_REQUEST)) {
 	$username = $_REQUEST['username'];
@@ -61,7 +61,7 @@ if ($organizations === NULL || !empty($organization)) {
 		}
 
 		try {
-			\sspmod_core_Auth_UserPassOrgBase::handleLogin($authStateId, $username, $password, $organization);
+			\SimpleSAML\Module\core\Auth\UserPassOrgBase::handleLogin($authStateId, $username, $password, $organization);
 		} catch (\SimpleSAML\Error\Error $e) {
 			// Login failed. Extract error code and parameters, to display the error
 			$errorCode = $e->getErrorCode();
diff --git a/modules/discopower/lib/PowerIdPDisco.php b/modules/discopower/lib/PowerIdPDisco.php
index 31452d482..d1d143eae 100644
--- a/modules/discopower/lib/PowerIdPDisco.php
+++ b/modules/discopower/lib/PowerIdPDisco.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\discopower;
+
 /**
  * This class implements a generic IdP discovery service, for use in various IdP discovery service pages. This should
  * reduce code duplication.
@@ -10,7 +12,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_discopower_PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
+class PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
 {
     /**
      * The configuration for this instance.
@@ -70,7 +72,7 @@ class sspmod_discopower_PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
      */
     protected function log($message)
     {
-        SimpleSAML\Logger::info('PowerIdPDisco.'.$this->instance.': '.$message);
+        \SimpleSAML\Logger::info('PowerIdPDisco.'.$this->instance.': '.$message);
     }
 
 
@@ -133,7 +135,7 @@ class sspmod_discopower_PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
         }
 
         foreach ($slist as $tab => $tbslist) {
-            uasort($slist[$tab], array('sspmod_discopower_PowerIdPDisco', 'mcmp'));
+            uasort($slist[$tab], array('\SimpleSAML\Module\discopower\PowerIdPDisco', 'mcmp'));
         }
 
         return $slist;
@@ -188,7 +190,7 @@ class sspmod_discopower_PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
 
         try {
             $spmd = $this->metadata->getMetaData($this->spEntityId, 'saml20-sp-remote');
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             return $list;
         }
 
@@ -244,7 +246,7 @@ class sspmod_discopower_PowerIdPDisco extends \SimpleSAML\XHTML\IdPDisco
         $idpList = $this->getIdPList();
         $idpList = $this->idplistStructured($this->filterList($idpList));
         $preferredIdP = $this->getRecommendedIdP();
-        $faventry = NULL;
+        $faventry = null;
         foreach ($idpList AS $tab => $slist) {
             if (!empty($preferredIdP) && array_key_exists($preferredIdP, $slist)) {
                 $faventry = $slist[$preferredIdP];
diff --git a/modules/discopower/www/disco.php b/modules/discopower/www/disco.php
index a4e98408d..29d4343f6 100644
--- a/modules/discopower/www/disco.php
+++ b/modules/discopower/www/disco.php
@@ -1,7 +1,7 @@
 <?php
 
 try {
-    $discoHandler = new sspmod_discopower_PowerIdPDisco(array('saml20-idp-remote', 'shib13-idp-remote'), 'poweridpdisco');
+    $discoHandler = new \SimpleSAML\Module\discopower\PowerIdPDisco(array('saml20-idp-remote', 'shib13-idp-remote'), 'poweridpdisco');
 } catch (\Exception $exception) {
     // An error here should be caused by invalid query parameters
     throw new \SimpleSAML\Error\Error('DISCOPARAMS', $exception);
@@ -9,7 +9,7 @@ try {
 
 try {
     $discoHandler->handleRequest();
-} catch(\Exception $exception) {
+} catch (\Exception $exception) {
     // An error here should be caused by metadata
     throw new \SimpleSAML\Error\Error('METADATA', $exception);
 }
diff --git a/modules/exampleattributeserver/www/attributeserver.php b/modules/exampleattributeserver/www/attributeserver.php
index 75c6944d8..9978b0bbc 100644
--- a/modules/exampleattributeserver/www/attributeserver.php
+++ b/modules/exampleattributeserver/www/attributeserver.php
@@ -79,7 +79,7 @@ $sc->SubjectConfirmationData->Recipient = $endpoint;
 $sc->SubjectConfirmationData->InResponseTo = $query->getId();
 $assertion->setSubjectConfirmation(array($sc));
 
-sspmod_saml_Message::addSign($idpMetadata, $spMetadata, $assertion);
+\SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $assertion);
 
 $response = new \SAML2\Response();
 $response->setRelayState($query->getRelayState());
@@ -87,7 +87,7 @@ $response->setDestination($endpoint);
 $response->setIssuer($idpEntityId);
 $response->setInResponseTo($query->getId());
 $response->setAssertions(array($assertion));
-sspmod_saml_Message::addSign($idpMetadata, $spMetadata, $response);
+\SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $response);
 
 $binding = new \SAML2\HTTPPost();
 $binding->send($response);
diff --git a/modules/exampleauth/lib/Auth/Process/RedirectTest.php b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
index fb81a8971..149976959 100644
--- a/modules/exampleauth/lib/Auth/Process/RedirectTest.php
+++ b/modules/exampleauth/lib/Auth/Process/RedirectTest.php
@@ -1,11 +1,13 @@
 <?php
 
+namespace SimpleSAML\Module\exampleautth\Auth\Process;
+
 /**
  * A simple processing filter for testing that redirection works as it should.
  *
  */
 
-class sspmod_exampleauth_Auth_Process_RedirectTest extends \SimpleSAML\Auth\ProcessingFilter
+class RedirectTest extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * Initialize processing of the redirect test.
diff --git a/modules/exampleauth/lib/Auth/Source/External.php b/modules/exampleauth/lib/Auth/Source/External.php
index 2ab694298..453d0da3a 100644
--- a/modules/exampleauth/lib/Auth/Source/External.php
+++ b/modules/exampleauth/lib/Auth/Source/External.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\exampleauth\Auth\Source;
+
 /**
  * Example external authentication source.
  *
@@ -21,12 +23,12 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_exampleauth_Auth_Source_External extends \SimpleSAML\Auth\Source
+class External extends \SimpleSAML\Auth\Source
 {
         /**
          * The key of the AuthId field in the state.
          */
-        const AUTHID = 'sspmod_exampleauth_Auth_Source_External.AuthId';
+        const AUTHID = 'SimpleSAML\Module\exampleautth\Auth\Sourc\External.AuthId';
 
 	/**
 	 * Constructor for this authentication source.
@@ -153,7 +155,7 @@ class sspmod_exampleauth_Auth_Source_External extends \SimpleSAML\Auth\Source
 		 * is also part of this module, but in a real example, this would likely be
 		 * the absolute URL of the login page for the site.
 		 */
-		$authPage = SimpleSAML\Module::getModuleURL('exampleauth/authpage.php');
+		$authPage = \SimpleSAML\Module::getModuleURL('exampleauth/authpage.php');
 
 		/*
 		 * The redirect to the authentication page.
diff --git a/modules/exampleauth/lib/Auth/Source/Static.php b/modules/exampleauth/lib/Auth/Source/Static.php
index 33d63eb1a..ca17a378c 100644
--- a/modules/exampleauth/lib/Auth/Source/Static.php
+++ b/modules/exampleauth/lib/Auth/Source/Static.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\exampleauth\Auth\Source;
+
 /**
  * Example authentication source.
  *
@@ -10,7 +12,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_exampleauth_Auth_Source_Static extends \SimpleSAML\Auth\Source
+class StaticSource extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The attributes we return.
@@ -34,9 +36,9 @@ class sspmod_exampleauth_Auth_Source_Static extends \SimpleSAML\Auth\Source
 
 		// Parse attributes
 		try {
-			$this->attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($config);
-		} catch(Exception $e) {
-			throw new Exception('Invalid attributes for authentication source ' .
+			$this->attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($config);
+		} catch (\Exception $e) {
+			throw new \Exception('Invalid attributes for authentication source ' .
 				$this->authId . ': ' . $e->getMessage());
 		}
 
diff --git a/modules/exampleauth/lib/Auth/Source/UserPass.php b/modules/exampleauth/lib/Auth/Source/UserPass.php
index 8be6d76d7..8a5ef6215 100644
--- a/modules/exampleauth/lib/Auth/Source/UserPass.php
+++ b/modules/exampleauth/lib/Auth/Source/UserPass.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\exampleauth\Auth\Source;
+
 /**
  * Example authentication source - username & password.
  *
@@ -10,7 +12,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassBase
+class UserPass extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
 	/**
 	 * Our users, stored in an associative array. The key of the array is "<username>:<password>",
@@ -37,22 +39,22 @@ class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassB
 		// Validate and parse our configuration
 		foreach ($config as $userpass => $attributes) {
 			if (!is_string($userpass)) {
-				throw new Exception('Invalid <username>:<password> for authentication source ' .
+				throw new \Exception('Invalid <username>:<password> for authentication source ' .
 					$this->authId . ': ' . $userpass);
 			}
 
 			$userpass = explode(':', $userpass, 2);
 			if (count($userpass) !== 2) {
-				throw new Exception('Invalid <username>:<password> for authentication source ' .
+				throw new \Exception('Invalid <username>:<password> for authentication source ' .
 					$this->authId . ': ' . $userpass[0]);
 			}
 			$username = $userpass[0];
 			$password = $userpass[1];
 
 			try {
-				$attributes = SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes);
-			} catch(Exception $e) {
-				throw new Exception('Invalid attributes for user ' . $username .
+				$attributes = \SimpleSAML\Utils\Attributes::normalizeAttributesArray($attributes);
+			} catch(\Exception $e) {
+				throw new \Exception('Invalid attributes for user ' . $username .
 					' in authentication source ' . $this->authId . ': ' .
 					$e->getMessage());
 			}
@@ -86,5 +88,4 @@ class sspmod_exampleauth_Auth_Source_UserPass extends sspmod_core_Auth_UserPassB
 
 		return $this->users[$userpass];
 	}
-
 }
diff --git a/modules/exampleauth/www/resume.php b/modules/exampleauth/www/resume.php
index e7ff5f8a6..192c13a20 100644
--- a/modules/exampleauth/www/resume.php
+++ b/modules/exampleauth/www/resume.php
@@ -9,4 +9,6 @@
  * @package SimpleSAMLphp
  */
 
-sspmod_exampleauth_Auth_Source_External::resume();
+namespace SimpleSAML\Module\exampleauth\Auth\Source;
+
+External::resume();
diff --git a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
index 858047bbc..b6e0b3fcb 100644
--- a/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
+++ b/modules/expirycheck/lib/Auth/Process/ExpiryDate.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\expirycheck\Auth\Process;
+
 /**
  * Filter which show "about to expire" warning or deny access if netid is expired.
  *
@@ -20,8 +22,8 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_expirycheck_Auth_Process_ExpiryDate extends \SimpleSAML\Auth\ProcessingFilter {
-
+class ExpiryDate extends \SimpleSAML\Auth\ProcessingFilter
+{
 	private $warndaysbefore = 0;
 	private $netid_attr = NULL;
 	private $expirydate_attr = NULL;
@@ -42,28 +44,28 @@ class sspmod_expirycheck_Auth_Process_ExpiryDate extends \SimpleSAML\Auth\Proces
 		if (array_key_exists('warndaysbefore', $config)) {
 			$this->warndaysbefore = $config['warndaysbefore'];
 			if (!is_string($this->warndaysbefore)) {
-				throw new Exception('Invalid value for number of days given to expirycheck::ExpiryDate filter.');
+				throw new \Exception('Invalid value for number of days given to expirycheck::ExpiryDate filter.');
 			}
 		}
 
 		if (array_key_exists('netid_attr', $config)) {
 			$this->netid_attr = $config['netid_attr'];
 			if (!is_string($this->netid_attr)) {
-				throw new Exception('Invalid attribute name given as eduPersonPrincipalName to expirycheck::ExpiryDate filter.');
+				throw new \Exception('Invalid attribute name given as eduPersonPrincipalName to expirycheck::ExpiryDate filter.');
 			}
 		}
 
 		if (array_key_exists('expirydate_attr', $config)) {
 			$this->expirydate_attr = $config['expirydate_attr'];
 			if (!is_string($this->expirydate_attr)) {
-				throw new Exception('Invalid attribute name given as schacExpiryDate to expirycheck::ExpiryDate filter.');
+				throw new \Exception('Invalid attribute name given as schacExpiryDate to expirycheck::ExpiryDate filter.');
 			}
 		}
 
 		if (array_key_exists('date_format', $config)) {
 			$this->date_format = $config['date_format'];
 			if (!is_string($this->date_format)) {
-				throw new Exception('Invalid date format given to expirycheck::ExpiryDate filter.');
+				throw new \Exception('Invalid date format given to expirycheck::ExpiryDate filter.');
 			}
 		}
 	}
@@ -126,26 +128,26 @@ class sspmod_expirycheck_Auth_Process_ExpiryDate extends \SimpleSAML\Auth\Proces
 				return;
 			}
 
-			SimpleSAML\Logger::warning('expirycheck: NetID ' . $netId .
+			\SimpleSAML\Logger::warning('expirycheck: NetID ' . $netId .
 			                           ' is about to expire!');
 
 			// Save state and redirect
 			$state['expireOnDate'] = date($this->date_format, $expireOnDate);
 			$state['netId'] = $netId;
 			$id = \SimpleSAML\Auth\State::saveState($state, 'expirywarning:about2expire');
-			$url = SimpleSAML\Module::getModuleURL('expirycheck/about2expire.php');
+			$url = \SimpleSAML\Module::getModuleURL('expirycheck/about2expire.php');
 			\SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 		}
 
 		if (!self::checkDate($expireOnDate)) {
-			SimpleSAML\Logger::error('expirycheck: NetID ' . $netId .
+			\SimpleSAML\Logger::error('expirycheck: NetID ' . $netId .
 				' has expired [' . date($this->date_format, $expireOnDate) . ']. Access denied!');
 
 			/* Save state and redirect. */
 			$state['expireOnDate'] = date($this->date_format, $expireOnDate);
 			$state['netId'] = $netId;
 			$id = \SimpleSAML\Auth\State::saveState($state, 'expirywarning:expired');
-			$url = SimpleSAML\Module::getModuleURL('expirycheck/expired.php');
+			$url = \SimpleSAML\Module::getModuleURL('expirycheck/expired.php');
 			\SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('StateId' => $id));
 
 		}
diff --git a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php
index eeb39071a..3aced4638 100644
--- a/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php
+++ b/modules/ldap/lib/Auth/Process/AttributeAddFromLDAP.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap\Auth\Process;
+
 /**
  * Filter to add attributes to the identity by executing a query against an LDAP directory
  *
@@ -32,9 +34,9 @@
  * @author Remy Blom <remy.blom@hku.nl>
  * @package SimpleSAMLphp
  */
-class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Process_BaseFilter
-{
 
+class AttributeAddFromLDAP extends BaseFilter
+{
     /**
      * LDAP attributes to add to the request attributes
      *
@@ -160,13 +162,13 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro
         $filter = str_replace($arrSearch, $arrReplace, $this->search_filter);
 
         if (strpos($filter, '%') !== false) {
-            SimpleSAML\Logger::info('AttributeAddFromLDAP: There are non-existing attributes in the search filter. ('.
+            \SimpleSAML\Logger::info('AttributeAddFromLDAP: There are non-existing attributes in the search filter. ('.
                                     $this->search_filter.')');
             return;
         }
 
         if (!in_array($this->attr_policy, array('merge', 'replace', 'add'), true)) {
-            SimpleSAML\Logger::warning("AttributeAddFromLDAP: 'attribute.policy' must be one of 'merge',".
+            \SimpleSAML\Logger::warning("AttributeAddFromLDAP: 'attribute.policy' must be one of 'merge',".
                                        "'replace' or 'add'.");
             return;
         }
@@ -174,9 +176,9 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro
         // getLdap
         try {
             $ldap = $this->getLdap();
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             // Added this warning in case $this->getLdap() fails
-            SimpleSAML\Logger::warning("AttributeAddFromLDAP: exception = " . $e);
+            \SimpleSAML\Logger::warning("AttributeAddFromLDAP: exception = " . $e);
             return;
         }
         // search for matching entries
@@ -188,7 +190,7 @@ class sspmod_ldap_Auth_Process_AttributeAddFromLDAP extends sspmod_ldap_Auth_Pro
                 true,
                 false
             );
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             return; // silent fail, error is still logged by LDAP search
         }
 
diff --git a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php
index 14ff9041d..c9b0a17dc 100644
--- a/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php
+++ b/modules/ldap/lib/Auth/Process/AttributeAddUsersGroups.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap\Auth\Process;
+
 /**
  * Does a reverse membership lookup on the logged in user,
  * looking for groups it is a member of and adds them to
@@ -9,7 +11,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_Process_BaseFilter
+class AttributeAddUsersGroups extends BaseFilter
 {
     /**
      * This is run when the filter is processed by SimpleSAML.
@@ -26,7 +28,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
         assert(array_key_exists('Attributes', $request));
 
         // Log the process
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Attempting to get the users groups...'
         );
 
@@ -56,7 +58,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
         $group_attribute = array_unique($group_attribute);
 
         // All done
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Added users groups to the group attribute [' .
             $map['groups'] . ']: ' . implode('; ', $groups)
         );
@@ -77,7 +79,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
     protected function getGroups($attributes)
     {
         // Log the request
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Checking for groups based on the best method for the LDAP product.'
         );
 
@@ -95,7 +97,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
                 $map =& $this->attribute_map;
 
                 // Log the general search
-                SimpleSAML\Logger::debug(
+                \SimpleSAML\Logger::debug(
                     $this->title . 'Searching LDAP using the default search method.'
                 );
 
@@ -119,7 +121,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
         }
 
         // All done
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'User found to be a member of the groups:' . implode('; ', $groups)
         );
         return $groups;
@@ -138,7 +140,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
     protected function getGroupsOpenLdap($attributes)
     {
         // Log the OpenLDAP specific search
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Searching LDAP using OpenLDAP specific method.'
         );
 
@@ -147,7 +149,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
 
         // Print group search string and search for all group names
         $openldap_base = $this->config->getString('ldap.basedn','ou=groups,dc=example,dc=com');
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . "Searching for groups in ldap.basedn ".$openldap_base." with filter (".$map['memberof']."=".$attributes[$map['username']][0].") and attributes ".$map['member']
         );
 
@@ -180,7 +182,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
     protected function getGroupsActiveDirectory($attributes)
     {
         // Log the AD specific search
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Searching LDAP using ActiveDirectory specific method.'
         );
 
@@ -229,7 +231,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
         $map =& $this->attribute_map;
 
         // Log the search
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Checking DNs for groups.' .
             ' DNs: '. implode('; ', $memberof) .
             ' Attributes: ' . $map['memberof'] . ', ' . $map['type'] .
@@ -302,7 +304,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
         $map =& $this->attribute_map;
 
         // Log the search
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title . 'Searching ActiveDirectory group membership.' .
             ' DN: ' . $dn .
             ' DN Attribute: ' . $map['dn'] .
@@ -353,7 +355,7 @@ class sspmod_ldap_Auth_Process_AttributeAddUsersGroups extends sspmod_ldap_Auth_
             }
 
             // Could not find DN, log and continue
-            SimpleSAML\Logger::notice(
+            \SimpleSAML\Logger::notice(
                 $this->title . 'The DN attribute [' .
                 implode(', ', array($map['dn'], strtolower($map['dn']), 'dn')) .
                 '] could not be found in the entry. ' . $this->var_export($entry)
diff --git a/modules/ldap/lib/Auth/Process/BaseFilter.php b/modules/ldap/lib/Auth/Process/BaseFilter.php
index c4fb9120e..60e9b70d9 100644
--- a/modules/ldap/lib/Auth/Process/BaseFilter.php
+++ b/modules/ldap/lib/Auth/Process/BaseFilter.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap\Auth\Process;
+
 /**
  * This base LDAP filter class can be extended to enable real
  * filter classes direct access to the authsource ldap config
@@ -13,7 +15,7 @@
  * @package SimpleSAMLphp
  */
 
-abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\ProcessingFilter
+abstract class BaseFilter extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * List of attribute "alias's" linked to the real attribute
@@ -102,7 +104,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         $this->title = 'ldap:'.end($classname).' : ';
 
         // Log the construction
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title.'Creating and configuring the filter.'
         );
 
@@ -110,7 +112,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         if (isset($config['authsource']) && $config['authsource']) {
 
             // Log the authsource request
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 $this->title.'Attempting to get configuration values from authsource ['.
                 $config['authsource'].']'
             );
@@ -194,7 +196,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
             $config = array_merge($authconfig, $config);
 
             // Authsource complete
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 $this->title.'Retrieved authsource ['.$config['authsource'].
                 '] configuration values: '.$this->var_export($authconfig)
             );
@@ -215,7 +217,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         $this->product = strtoupper($this->product);
 
         // Log the member values retrieved above
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title.'Configuration values retrieved;'.
             ' BaseDN: '.$this->var_export($this->base_dn).
             ' Product: '.$this->var_export($this->product)
@@ -233,7 +235,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         );
 
         // Log the attribute map
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title.'Attribute map created: '.$this->var_export($this->attribute_map)
         );
 
@@ -244,7 +246,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         );
 
         // Log the type map
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title.'Type map created: '.$this->var_export($this->type_map)
         );
     }
@@ -274,7 +276,7 @@ abstract class sspmod_ldap_Auth_Process_BaseFilter extends \SimpleSAML\Auth\Proc
         $password   = $this->config->getString('ldap.password', null);
 
         // Log the LDAP connection
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             $this->title.'Connecting to LDAP server;'.
             ' Hostname: '.$hostname.
             ' Port: '.$port.
diff --git a/modules/ldap/lib/Auth/Source/LDAP.php b/modules/ldap/lib/Auth/Source/LDAP.php
index 2e2144b8f..38101cce7 100644
--- a/modules/ldap/lib/Auth/Source/LDAP.php
+++ b/modules/ldap/lib/Auth/Source/LDAP.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap\Auth\Source;
+
 /**
  * LDAP authentication source.
  *
@@ -10,9 +12,9 @@
  *
  * @package SimpleSAMLphp
  */
-class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase
-{
 
+class LDAP extends \SimpleSAML\Module\core\Auth\UserPassBase
+{
     /**
      * A LDAP configuration object.
      */
@@ -33,7 +35,7 @@ class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase
         // Call the parent constructor first, as required by the interface
         parent::__construct($info, $config);
 
-        $this->ldapConfig = new sspmod_ldap_ConfigHelper($config,
+        $this->ldapConfig = new \SimpleSAML\Module\ldap\ConfigHelper($config,
             'Authentication source ' . var_export($this->authId, true));
     }
 
@@ -53,5 +55,4 @@ class sspmod_ldap_Auth_Source_LDAP extends sspmod_core_Auth_UserPassBase
 
         return $this->ldapConfig->login($username, $password, $sasl_args);
     }
-
 }
diff --git a/modules/ldap/lib/Auth/Source/LDAPMulti.php b/modules/ldap/lib/Auth/Source/LDAPMulti.php
index eaf8716b5..ff6e3e42b 100644
--- a/modules/ldap/lib/Auth/Source/LDAPMulti.php
+++ b/modules/ldap/lib/Auth/Source/LDAPMulti.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap\Auth\Source;
+
 /**
  * LDAP authentication source.
  *
@@ -10,7 +12,8 @@
  *
  * @package SimpleSAMLphp
  */
-class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase
+
+class LDAPMulti extends \SimpleSAML\Module\core\Auth\UserPassOrgBase
 {
     /**
      * An array with descriptions for organizations.
@@ -73,7 +76,7 @@ class sspmod_ldap_Auth_Source_LDAPMulti extends sspmod_core_Auth_UserPassOrgBase
                 $this->orgs[$orgId] = $orgId;
             }
 
-            $orgCfg = new sspmod_ldap_ConfigHelper($orgCfg,
+            $orgCfg = new \SimpleSAML\Module\ldap\ConfigHelper($orgCfg,
                 'Authentication source ' . var_export($this->authId, true) .
                 ', organization ' . var_export($orgId, true));
             $this->ldapOrgs[$orgId] = $orgCfg;
diff --git a/modules/ldap/lib/ConfigHelper.php b/modules/ldap/lib/ConfigHelper.php
index cc5e1e876..3b03a0826 100644
--- a/modules/ldap/lib/ConfigHelper.php
+++ b/modules/ldap/lib/ConfigHelper.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\ldap;
+
 /**
  * LDAP authentication source configuration parser.
  *
@@ -9,7 +11,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_ldap_ConfigHelper
+class ConfigHelper
 {
     /**
      * String with the location of this configuration.
@@ -17,19 +19,16 @@ class sspmod_ldap_ConfigHelper
      */
     private $location;
 
-
     /**
      * The hostname of the LDAP server.
      */
     private $hostname;
 
-
     /**
      * Whether we should use TLS/SSL when contacting the LDAP server.
      */
     private $enableTLS;
 
-
     /**
      * Whether debug output is enabled.
      *
@@ -37,7 +36,6 @@ class sspmod_ldap_ConfigHelper
      */
     private $debug;
 
-
     /**
      * The timeout for accessing the LDAP server.
      *
@@ -185,7 +183,7 @@ class sspmod_ldap_ConfigHelper
         assert(is_string($password));
 
         if (empty($password)) {
-            SimpleSAML\Logger::info($this->location.': Login with empty password disallowed.');
+            \SimpleSAML\Logger::info($this->location.': Login with empty password disallowed.');
             throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
         }
 
@@ -197,14 +195,14 @@ class sspmod_ldap_ConfigHelper
         } else {
             if ($this->searchUsername !== null) {
                 if (!$ldap->bind($this->searchUsername, $this->searchPassword)) {
-                    throw new Exception('Error authenticating using search username & password.');
+                    throw new \Exception('Error authenticating using search username & password.');
                 }
             }
 
             $dn = $ldap->searchfordn($this->searchBase, $this->searchAttributes, $username, true, $this->searchFilter, $this->searchScope);
             if ($dn === null) {
                 /* User not found with search. */
-                SimpleSAML\Logger::info($this->location.': Unable to find users DN. username=\''.$username.'\'');
+                \SimpleSAML\Logger::info($this->location.': Unable to find users DN. username=\''.$username.'\'');
                 throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
             }
         }
@@ -223,7 +221,7 @@ class sspmod_ldap_ConfigHelper
         if ($this->privRead) {
             /* Yes, rebind with privs */
             if (!$ldap->bind($this->privUsername, $this->privPassword)) {
-                throw new Exception('Error authenticating using privileged DN & password.');
+                throw new \Exception('Error authenticating using privileged DN & password.');
             }
         }
 
@@ -268,7 +266,7 @@ class sspmod_ldap_ConfigHelper
 
         if ($this->searchUsername !== null) {
             if (!$ldap->bind($this->searchUsername, $this->searchPassword)) {
-                throw new Exception('Error authenticating using search username & password.');
+                throw new \Exception('Error authenticating using search username & password.');
             }
         }
 
@@ -293,10 +291,9 @@ class sspmod_ldap_ConfigHelper
         if ($this->privRead) {
             /* Yes, rebind with privs */
             if (!$ldap->bind($this->privUsername, $this->privPassword)) {
-                throw new Exception('Error authenticating using privileged DN & password.');
+                throw new \Exception('Error authenticating using privileged DN & password.');
             }
         }
         return $ldap->getAttributes($dn, $attributes);
     }
-
 }
diff --git a/modules/metarefresh/bin/metarefresh.php b/modules/metarefresh/bin/metarefresh.php
index 43ecebd4f..aa18eb65d 100755
--- a/modules/metarefresh/bin/metarefresh.php
+++ b/modules/metarefresh/bin/metarefresh.php
@@ -13,7 +13,7 @@ $baseDir = dirname(dirname(dirname(dirname(__FILE__))));
 // Add library autoloader.
 require_once($baseDir . '/lib/_autoload.php');
 
-if(!SimpleSAML\Module::isModuleEnabled('metarefresh')) {
+if(!\SimpleSAML\Module::isModuleEnabled('metarefresh')) {
 	echo("You need to enable the metarefresh module before this script can be used.\n");
 	echo("You can enable it by running the following command:\n");
 	echo('  echo >"' . $baseDir . '/modules/metarefresh/enable' . "\"\n");
@@ -21,7 +21,7 @@ if(!SimpleSAML\Module::isModuleEnabled('metarefresh')) {
 }
 
 /* Initialize the configuration. */
-$configdir = SimpleSAML\Utils\Config::getConfigDir();
+$configdir = \SimpleSAML\Utils\Config::getConfigDir();
 \SimpleSAML\Configuration::setConfigDir($configdir);
 
 /* $outputDir contains the directory we will store the generated metadata in. */
@@ -128,7 +128,7 @@ if(count($files) === 0) {
 
 
 /* The metadata global variable will be filled with the metadata we extract. */
-$metaloader = new sspmod_metarefresh_MetaLoader();
+$metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader();
 
 foreach($files as $f) {
 	$source = array('src' => $f);
diff --git a/modules/metarefresh/hooks/hook_cron.php b/modules/metarefresh/hooks/hook_cron.php
index c4761f928..8b627292d 100644
--- a/modules/metarefresh/hooks/hook_cron.php
+++ b/modules/metarefresh/hooks/hook_cron.php
@@ -23,7 +23,7 @@ function metarefresh_hook_cron(&$croninfo) {
 			$cronTags = $set->getArray('cron');
 			if (!in_array($croninfo['tag'], $cronTags, true)) continue;
 
-			SimpleSAML\Logger::info('cron [metarefresh]: Executing set [' . $setkey . ']');
+			\SimpleSAML\Logger::info('cron [metarefresh]: Executing set [' . $setkey . ']');
 
 			$expireAfter = $set->getInteger('expireAfter', NULL);
 			if ($expireAfter !== NULL) {
@@ -41,7 +41,7 @@ function metarefresh_hook_cron(&$croninfo) {
 				'directory' => $outputDir,
 			));
 
-			$metaloader = new sspmod_metarefresh_MetaLoader($expire, $stateFile, $oldMetadataSrc);
+			$metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire, $stateFile, $oldMetadataSrc);
 
 			# Get global blacklist, whitelist and caching info
 			$blacklist = $mconfig->getArray('blacklist', array());
@@ -86,7 +86,7 @@ function metarefresh_hook_cron(&$croninfo) {
 					$source['conditionalGET'] = $conditionalGET;
 				}
 
-				SimpleSAML\Logger::debug('cron [metarefresh]: In set [' . $setkey . '] loading source ['  . $source['src'] . ']');
+				\SimpleSAML\Logger::debug('cron [metarefresh]: In set [' . $setkey . '] loading source ['  . $source['src'] . ']');
 				$metaloader->loadSource($source);
 			}
 
@@ -108,7 +108,7 @@ function metarefresh_hook_cron(&$croninfo) {
 			}
 		}
 
-	} catch (Exception $e) {
+	} catch (\Exception $e) {
 		$croninfo['summary'][] = 'Error during metarefresh: ' . $e->getMessage();
 	}
 }
diff --git a/modules/metarefresh/lib/ARP.php b/modules/metarefresh/lib/ARP.php
index c0e3378ac..43ccaa81b 100644
--- a/modules/metarefresh/lib/ARP.php
+++ b/modules/metarefresh/lib/ARP.php
@@ -1,10 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\metarefresh;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
 
-class sspmod_metarefresh_ARP
+class ARP
 {
     /**
      * @var array
@@ -26,10 +29,10 @@ class sspmod_metarefresh_ARP
      */
     private $suffix;
 
-	/**
-	 * Constructor
-	 *
-	 * @param array $metadata
+    /**
+     * Constructor
+     *
+     * @param array $metadata
      * @param string $attributemap
      * @param string $prefix
      * @param string $suffix
@@ -56,7 +59,7 @@ class sspmod_metarefresh_ARP
         include($config->getPathValue('attributemap', 'attributemap/') . $attributemap . '.php');
         // Note that $attributemap was a string before the call to include() and is now an array!
         $this->attributes = $attributemap;
-	}
+    }
 
     /**
      * @param string $name
diff --git a/modules/metarefresh/lib/MetaLoader.php b/modules/metarefresh/lib/MetaLoader.php
index 3b88b2bcd..87afecf20 100644
--- a/modules/metarefresh/lib/MetaLoader.php
+++ b/modules/metarefresh/lib/MetaLoader.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\metarefresh;
+
 /**
  * @package SimpleSAMLphp
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  */
-class sspmod_metarefresh_MetaLoader
+
+class MetaLoader
 {
     private $expire;
     private $metadata;
@@ -41,7 +45,6 @@ class sspmod_metarefresh_MetaLoader
         }
 
         $this->state = array();
-
     }
 
 
@@ -85,24 +88,24 @@ class sspmod_metarefresh_MetaLoader
             // GET!
             try {
                 list($data, $responseHeaders) = \SimpleSAML\Utils\HTTP::fetch($source['src'], $context, true);
-            } catch(Exception $e) {
-                SimpleSAML\Logger::warning('metarefresh: ' . $e->getMessage());
+            } catch(\Exception $e) {
+                \SimpleSAML\Logger::warning('metarefresh: ' . $e->getMessage());
             }
 
             // We have response headers, so the request succeeded
             if (!isset($responseHeaders)) {
                 // No response headers, this means the request failed in some way, so re-use old data
-                SimpleSAML\Logger::debug('No response from ' . $source['src'] . ' - attempting to re-use cached metadata');
+                \SimpleSAML\Logger::debug('No response from ' . $source['src'] . ' - attempting to re-use cached metadata');
                 $this->addCachedMetadata($source);
                 return;
             } elseif (preg_match('@^HTTP/1\.[01]\s304\s@', $responseHeaders[0])) {
                 // 304 response
-                SimpleSAML\Logger::debug('Received HTTP 304 (Not Modified) - attempting to re-use cached metadata');
+                \SimpleSAML\Logger::debug('Received HTTP 304 (Not Modified) - attempting to re-use cached metadata');
                 $this->addCachedMetadata($source);
                 return;
             } elseif (!preg_match('@^HTTP/1\.[01]\s200\s@', $responseHeaders[0])) {
                 // Other error
-                SimpleSAML\Logger::debug('Error from ' . $source['src'] . ' - attempting to re-use cached metadata');
+                \SimpleSAML\Logger::debug('Error from ' . $source['src'] . ' - attempting to re-use cached metadata');
                 $this->addCachedMetadata($source);
                 return;
             }
@@ -115,14 +118,14 @@ class sspmod_metarefresh_MetaLoader
         // Everything OK. Proceed.
         if (isset($source['conditionalGET']) && $source['conditionalGET']) {
             // Stale or no metadata, so a fresh copy
-            SimpleSAML\Logger::debug('Downloaded fresh copy');
+            \SimpleSAML\Logger::debug('Downloaded fresh copy');
         }
 
         try {
             $entities = $this->loadXML($data, $source);
-        } catch(Exception $e) {
-            SimpleSAML\Logger::debug('XML parser error when parsing ' . $source['src'] . ' - attempting to re-use cached metadata');
-            SimpleSAML\Logger::debug('XML parser returned: ' . $e->getMessage());
+        } catch(\Exception $e) {
+            \SimpleSAML\Logger::debug('XML parser error when parsing ' . $source['src'] . ' - attempting to re-use cached metadata');
+            \SimpleSAML\Logger::debug('XML parser returned: ' . $e->getMessage());
             $this->addCachedMetadata($source);
             return;
         }
@@ -131,21 +134,21 @@ class sspmod_metarefresh_MetaLoader
 
             if (isset($source['blacklist'])) {
                 if (!empty($source['blacklist']) && in_array($entity->getEntityID(), $source['blacklist'], true)) {
-                    SimpleSAML\Logger::info('Skipping "' .  $entity->getEntityID() . '" - blacklisted.' . "\n");
+                    \SimpleSAML\Logger::info('Skipping "' .  $entity->getEntityID() . '" - blacklisted.' . "\n");
                     continue;
                 }
             }
 
             if (isset($source['whitelist'])) {
                 if (!empty($source['whitelist']) && !in_array($entity->getEntityID(), $source['whitelist'], true)) {
-                    SimpleSAML\Logger::info('Skipping "' .  $entity->getEntityID() . '" - not in the whitelist.' . "\n");
+                    \SimpleSAML\Logger::info('Skipping "' .  $entity->getEntityID() . '" - not in the whitelist.' . "\n");
                     continue;
                 }
             }
 
             if (array_key_exists('certificates', $source) && $source['certificates'] !== null) {
                 if (!$entity->validateSignature($source['certificates'])) {
-                    SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using certificate.' . "\n");
+                    \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using certificate.' . "\n");
                     continue;
                 }
             }
@@ -153,11 +156,11 @@ class sspmod_metarefresh_MetaLoader
             if (array_key_exists('validateFingerprint', $source) && $source['validateFingerprint'] !== null) {
                 if (!array_key_exists('certificates', $source) || $source['certificates'] == null) {
                     if (!$entity->validateFingerprint($source['validateFingerprint'])) {
-                        SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using fingerprint.' . "\n");
+                        \SimpleSAML\Logger::info('Skipping "' . $entity->getEntityId() . '" - could not verify signature using fingerprint.' . "\n");
                         continue;
                     }
                 } else {
-                    SimpleSAML\Logger::info('Skipping validation with fingerprint since option certificate is set.' . "\n");
+                    \SimpleSAML\Logger::info('Skipping validation with fingerprint since option certificate is set.' . "\n");
                 }
             }
 
@@ -266,11 +269,11 @@ class sspmod_metarefresh_MetaLoader
     {
         try {
             $doc = \SAML2\DOMDocumentFactory::fromString($data);
-        } catch (Exception $e) {
-            throw new Exception('Failed to read XML from ' . $source['src']);
+        } catch (\Exception $e) {
+            throw new \Exception('Failed to read XML from ' . $source['src']);
         }
         if ($doc->documentElement === null) {
-            throw new Exception('Opened file is not an XML document: ' . $source['src']);
+            throw new \Exception('Opened file is not an XML document: ' . $source['src']);
         }
         return \SimpleSAML\Metadata\SAMLParser::parseDescriptorsElement($doc->documentElement);
     }
@@ -282,8 +285,8 @@ class sspmod_metarefresh_MetaLoader
     public function writeState()
     {
         if ($this->changed) {
-            SimpleSAML\Logger::debug('Writing: ' . $this->stateFile);
-            SimpleSAML\Utils\System::writeFile(
+            \SimpleSAML\Logger::debug('Writing: ' . $this->stateFile);
+            \SimpleSAML\Utils\System::writeFile(
                 $this->stateFile,
                 "<?php\n/* This file was generated by the metarefresh module at ".$this->getTime() . ".\n".
                 " Do not update it manually as it will get overwritten. */\n".
@@ -323,9 +326,9 @@ class sspmod_metarefresh_MetaLoader
      * This function adds metadata from the specified file to the list of metadata.
      * This function will return without making any changes if $metadata is NULL.
      *
-     * @param $filename The filename the metadata comes from.
-     * @param $metadata The metadata.
-     * @param $type The metadata type.
+     * @param string $filename The filename the metadata comes from.
+     * @param array  $metadata The metadata.
+     * @param string $type The metadata type.
      */
     private function addMetadata($filename, $metadata, $type, $template = null)
     {
@@ -379,7 +382,7 @@ class sspmod_metarefresh_MetaLoader
         }
 
         // $metadata, $attributemap, $prefix, $suffix
-        $arp = new sspmod_metarefresh_ARP($md,
+        $arp = new \SimpleSAML\Module\metarefresh\ARP($md,
             $config->getValue('attributemap', ''),
             $config->getValue('prefix', ''),
             $config->getValue('suffix', '')
@@ -388,7 +391,7 @@ class sspmod_metarefresh_MetaLoader
 
         $arpxml = $arp->getXML();
 
-        SimpleSAML\Logger::info('Writing ARP file: ' . $arpfile . "\n");
+        \SimpleSAML\Logger::info('Writing ARP file: ' . $arpfile . "\n");
         file_put_contents($arpfile, $arpxml);
     }
 
@@ -403,10 +406,10 @@ class sspmod_metarefresh_MetaLoader
         }
 
         if (!file_exists($outputDir)) {
-            SimpleSAML\Logger::info('Creating directory: ' . $outputDir . "\n");
+            \SimpleSAML\Logger::info('Creating directory: ' . $outputDir . "\n");
             $res = @mkdir($outputDir, 0777, true);
             if ($res === false) {
-                throw new Exception('Error creating directory: ' . $outputDir);
+                throw new \Exception('Error creating directory: ' . $outputDir);
             }
         }
 
@@ -415,7 +418,7 @@ class sspmod_metarefresh_MetaLoader
 
             if (array_key_exists($type, $this->metadata)) {
                 $elements = $this->metadata[$type];
-                SimpleSAML\Logger::debug('Writing: ' . $filename);
+                \SimpleSAML\Logger::debug('Writing: ' . $filename);
 
                 $content  = '<?php' . "\n" . '/* This file was generated by the metarefresh module at '. $this->getTime() . "\n";
                 $content .= ' Do not update it manually as it will get overwritten' . "\n" . '*/' . "\n";
@@ -428,12 +431,12 @@ class sspmod_metarefresh_MetaLoader
 
                 $content .= "\n" . '?>';
 
-                SimpleSAML\Utils\System::writeFile($filename, $content, 0644);
+                \SimpleSAML\Utils\System::writeFile($filename, $content, 0644);
             } elseif (is_file($filename)) {
                 if (unlink($filename)) {
-                    SimpleSAML\Logger::debug('Deleting stale metadata file: ' . $filename);
+                    \SimpleSAML\Logger::debug('Deleting stale metadata file: ' . $filename);
                 } else {
-                    SimpleSAML\Logger::warning('Could not delete stale metadata file: ' . $filename);
+                    \SimpleSAML\Logger::warning('Could not delete stale metadata file: ' . $filename);
                 }
             }
         }
@@ -456,7 +459,7 @@ class sspmod_metarefresh_MetaLoader
             foreach ($elements as $m) {
                 $entityId = $m['metadata']['entityid'];
 
-                SimpleSAML\Logger::debug(
+                \SimpleSAML\Logger::debug(
                     'metarefresh: Add metadata entry ' .
                     var_export($entityId, true) . ' in set ' . var_export($set, true) . '.'
                 );
@@ -469,7 +472,7 @@ class sspmod_metarefresh_MetaLoader
         foreach ($metaHandler->getMetadataSets() as $set) {
             foreach ($metaHandler->getMetadataSet($set) as $entityId => $metadata) {
                 if (!array_key_exists('expire', $metadata)) {
-                    SimpleSAML\Logger::warning(
+                    \SimpleSAML\Logger::warning(
                         'metarefresh: Metadata entry without expire timestamp: ' . var_export($entityId, true) .
                         ' in set ' . var_export($set, true) . '.'
                     );
@@ -478,8 +481,8 @@ class sspmod_metarefresh_MetaLoader
                 if ($metadata['expire'] > $ct) {
                     continue;
                 }
-                SimpleSAML\Logger::debug('metarefresh: ' . $entityId . ' expired ' . date('l jS \of F Y h:i:s A', $metadata['expire']));
-                SimpleSAML\Logger::debug(
+                \SimpleSAML\Logger::debug('metarefresh: ' . $entityId . ' expired ' . date('l jS \of F Y h:i:s A', $metadata['expire']));
+                \SimpleSAML\Logger::debug(
                     'metarefresh: Delete expired metadata entry ' .
                     var_export($entityId, true) . ' in set ' . var_export($set, true) . '. (' . ($ct - $metadata['expire']) . ' sec)'
                 );
diff --git a/modules/metarefresh/www/fetch.php b/modules/metarefresh/www/fetch.php
index 94ea86546..8c3120b2d 100644
--- a/modules/metarefresh/www/fetch.php
+++ b/modules/metarefresh/www/fetch.php
@@ -22,7 +22,7 @@ foreach ($sets AS $setkey => $set) {
 			$expire = NULL;
 		}
 
-		$metaloader = new sspmod_metarefresh_MetaLoader($expire);
+		$metaloader = new \SimpleSAML\Module\metarefresh\MetaLoader($expire);
 
 		# Get global black/whitelists
 		$blacklist = $mconfig->getArray('blacklist', array());
diff --git a/modules/multiauth/lib/Auth/Source/MultiAuth.php b/modules/multiauth/lib/Auth/Source/MultiAuth.php
index 1a46678d3..b9b16b6d3 100644
--- a/modules/multiauth/lib/Auth/Source/MultiAuth.php
+++ b/modules/multiauth/lib/Auth/Source/MultiAuth.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\multiauth\Auth\Source;
+
 /**
  * Authentication source which let the user chooses among a list of
  * other authentication sources
@@ -8,22 +10,22 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_multiauth_Auth_Source_MultiAuth extends \SimpleSAML\Auth\Source
+class MultiAuth extends \SimpleSAML\Auth\Source
 {
 	/**
 	 * The key of the AuthId field in the state.
 	 */
-	const AUTHID = 'sspmod_multiauth_Auth_Source_MultiAuth.AuthId';
+	const AUTHID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.AuthId';
 
 	/**
 	 * The string used to identify our states.
 	 */
-	const STAGEID = 'sspmod_multiauth_Auth_Source_MultiAuth.StageId';
+	const STAGEID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.StageId';
 
 	/**
 	 * The key where the sources is saved in the state.
 	 */
-	const SOURCESID = 'sspmod_multiauth_Auth_Source_MultiAuth.SourceId';
+	const SOURCESID = '\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth.SourceId';
 
 	/**
 	 * The key where the selected source is saved in the session.
@@ -49,7 +51,7 @@ class sspmod_multiauth_Auth_Source_MultiAuth extends \SimpleSAML\Auth\Source
 		parent::__construct($info, $config);
 
 		if (!array_key_exists('sources', $config)) {
-			throw new Exception('The required "sources" config option was not found');
+			throw new \Exception('The required "sources" config option was not found');
 		}
 
 		$globalConfiguration = \SimpleSAML\Configuration::getInstance();
@@ -112,7 +114,7 @@ class sspmod_multiauth_Auth_Source_MultiAuth extends \SimpleSAML\Auth\Source
 
 		/* Redirect to the select source page. We include the identifier of the
 		saved state array as a parameter to the login form */
-		$url = SimpleSAML\Module::getModuleURL('multiauth/selectsource.php');
+		$url = \SimpleSAML\Module::getModuleURL('multiauth/selectsource.php');
 		$params = array('AuthState' => $id);
 
 		// Allowes the user to specify the auth souce to be used
@@ -150,7 +152,7 @@ class sspmod_multiauth_Auth_Source_MultiAuth extends \SimpleSAML\Auth\Source
 			$state[self::SOURCESID]
         );
 		if ($as === NULL || !in_array($authId, $valid_sources, true)) {
-			throw new Exception('Invalid authentication source: ' . $authId);
+			throw new \Exception('Invalid authentication source: ' . $authId);
 		}
 
 		/* Save the selected authentication source for the logout process. */
diff --git a/modules/multiauth/www/selectsource.php b/modules/multiauth/www/selectsource.php
index d04e556ea..8becbeb20 100644
--- a/modules/multiauth/www/selectsource.php
+++ b/modules/multiauth/www/selectsource.php
@@ -3,7 +3,7 @@
 /**
  * This page shows a list of authentication sources. When the user selects
  * one of them if pass this information to the
- * sspmod_multiauth_Auth_Source_MultiAuth class and call the
+ * \SimpleSAML\Module\multiauth\Auth\Source\MultiAuth class and call the
  * delegateAuthentication method on it.
  *
  * @author Lorenzo Gil, Yaco Sistemas S.L.
@@ -12,49 +12,49 @@
 
 // Retrieve the authentication state
 if (!array_key_exists('AuthState', $_REQUEST)) {
-	throw new \SimpleSAML\Error\BadRequest('Missing AuthState parameter.');
+    throw new \SimpleSAML\Error\BadRequest('Missing AuthState parameter.');
 }
 $authStateId = $_REQUEST['AuthState'];
-$state = \SimpleSAML\Auth\State::loadState($authStateId, sspmod_multiauth_Auth_Source_MultiAuth::STAGEID);
+$state = \SimpleSAML\Auth\State::loadState($authStateId, \SimpleSAML\Module\multiauth\Auth\Source\MultiAuth::STAGEID);
 
 if (array_key_exists("\SimpleSAML\Auth\Source.id", $state)) {
-	$authId = $state["\SimpleSAML\Auth\Source.id"];
-	$as = \SimpleSAML\Auth\Source::getById($authId);
+    $authId = $state["\SimpleSAML\Auth\Source.id"];
+    $as = \SimpleSAML\Auth\Source::getById($authId);
 } else {
-	$as = NULL;
+    $as = null;
 }
 
-$source = NULL;
+$source = null;
 if (array_key_exists('source', $_REQUEST)) {
-	$source = $_REQUEST['source'];
+    $source = $_REQUEST['source'];
 } else {
-	foreach ($_REQUEST as $k => $v) {
-		$k = explode('-', $k, 2);
-		if (count($k) === 2 && $k[0] === 'src') {
-			$source = base64_decode($k[1]);
-		}
-	}
+    foreach ($_REQUEST as $k => $v) {
+        $k = explode('-', $k, 2);
+        if (count($k) === 2 && $k[0] === 'src') {
+            $source = base64_decode($k[1]);
+        }
+    }
 }
-if ($source !== NULL) {
-	if ($as !== NULL) {
-		$as->setPreviousSource($source);
-	}
-	\sspmod_multiauth_Auth_Source_MultiAuth::delegateAuthentication($source, $state);
+if ($source !== null) {
+    if ($as !== null) {
+        $as->setPreviousSource($source);
+    }
+    \SimpleSAML\Module\multiauth\Auth\Source\MultiAuth::delegateAuthentication($source, $state);
 }
 
 if (array_key_exists('multiauth:preselect', $state)) {
-	$source = $state['multiauth:preselect'];
-	\sspmod_multiauth_Auth_Source_MultiAuth::delegateAuthentication($source, $state);
+    $source = $state['multiauth:preselect'];
+    \SimpleSAML\Module\multiauth\Auth\Source\MultiAuth::delegateAuthentication($source, $state);
 }
 
 $globalConfig = \SimpleSAML\Configuration::getInstance();
 $t = new \SimpleSAML\XHTML\Template($globalConfig, 'multiauth:selectsource.php');
 $t->data['authstate'] = $authStateId;
-$t->data['sources'] = $state[\sspmod_multiauth_Auth_Source_MultiAuth::SOURCESID];
-if ($as !== NULL) {
-	$t->data['preferred'] = $as->getPreviousSource();
+$t->data['sources'] = $state[\SimpleSAML\Module\multiauth\Auth\Source\MultiAuth::SOURCESID];
+if ($as !== null) {
+    $t->data['preferred'] = $as->getPreviousSource();
 } else {
-	$t->data['preferred'] = NULL;
+    $t->data['preferred'] = null;
 }
 $t->show();
 exit();
diff --git a/modules/negotiate/docs/negotiate.md b/modules/negotiate/docs/negotiate.md
index 968d56eaf..3a3dd76f0 100644
--- a/modules/negotiate/docs/negotiate.md
+++ b/modules/negotiate/docs/negotiate.md
@@ -211,7 +211,7 @@ if (array_key_exists('negotiate:authId', $state)) {
         } elseif ($session_disabled) {
             $retryState = \SimpleSAML\Auth\State::cloneState($state);
             unset($retryState[\SimpleSAML\Auth\State::ID]);
-            $nego_retry = \SimpleSAML\Auth\State::saveState($retryState, 'sspmod_negotiate_Auth_Source_Negotiate.StageId');
+            $nego_retry = \SimpleSAML\Auth\State::saveState($retryState, '\SimpleSAML\Module\negotiate\Auth\Source\Negotiate.StageId');
             $nego_session = true;
         }
     }
@@ -247,7 +247,7 @@ security check in SSP's state handling library. If you omit this and
 pass on the original state you will see a warning in the log like
 this:
 
-    Sep 27 13:47:36 simplesamlphp WARNING [b99e6131ee] Wrong stage in state. Was 'foo', should be 'sspmod_negotiate_Auth_Source_Negotiate.StageId'.
+    Sep 27 13:47:36 simplesamlphp WARNING [b99e6131ee] Wrong stage in state. Was 'foo', should be '\SimpleSAML\Module\negotiate\Auth\Source\Negotiate.StageId'.
 
 It will work as loadState will take controll and call
 Negotiate->authenticate() but remaining code in retry.php will be
diff --git a/modules/negotiate/lib/Auth/Source/Negotiate.php b/modules/negotiate/lib/Auth/Source/Negotiate.php
index d144e2855..ed9b8c5e8 100644
--- a/modules/negotiate/lib/Auth/Source/Negotiate.php
+++ b/modules/negotiate/lib/Auth/Source/Negotiate.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\negotiate\Auth\Source;
+
 /**
  * The Negotiate module. Allows for password-less, secure login by Kerberos and Negotiate.
  *
@@ -7,10 +9,10 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
+class Negotiate extends \SimpleSAML\Auth\Source
 {
     // Constants used in the module
-    const STAGEID = 'sspmod_negotiate_Auth_Source_Negotiate.StageId';
+    const STAGEID = '\SimpleSAML\Module\negotiate\Auth\Source\Negotiate.StageId';
 
     protected $ldap = null;
     protected $backend = '';
@@ -43,7 +45,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
         assert(is_array($config));
 
         if (!extension_loaded('krb5')) {
-            throw new Exception('KRB5 Extension not installed');
+            throw new \Exception('KRB5 Extension not installed');
         }
 
         // call the parent constructor first, as required by the interface
@@ -103,7 +105,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
             (!empty($_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT']) &&
                 $_COOKIE['NEGOTIATE_AUTOLOGIN_DISABLE_PERMANENT'] == 'True')
         ) {
-            SimpleSAML\Logger::debug('Negotiate - session disabled. falling back');
+            \SimpleSAML\Logger::debug('Negotiate - session disabled. falling back');
             $this->fallBack($state);
             // never executed
             assert(false);
@@ -115,9 +117,9 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
             assert(false);
         }
 
-        SimpleSAML\Logger::debug('Negotiate - authenticate(): looking for Negotiate');
+        \SimpleSAML\Logger::debug('Negotiate - authenticate(): looking for Negotiate');
         if (!empty($_SERVER['HTTP_AUTHORIZATION'])) {
-            SimpleSAML\Logger::debug('Negotiate - authenticate(): Negotiate found');
+            \SimpleSAML\Logger::debug('Negotiate - authenticate(): Negotiate found');
             $this->ldap = new \SimpleSAML\Auth\LDAP(
                 $this->hostname,
                 $this->enableTLS,
@@ -129,26 +131,26 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
 
             list($mech,) = explode(' ', $_SERVER['HTTP_AUTHORIZATION'], 2);
             if (strtolower($mech) == 'basic') {
-                SimpleSAML\Logger::debug('Negotiate - authenticate(): Basic found. Skipping.');
+                \SimpleSAML\Logger::debug('Negotiate - authenticate(): Basic found. Skipping.');
             } else {
                 if (strtolower($mech) != 'negotiate') {
-                    SimpleSAML\Logger::debug('Negotiate - authenticate(): No "Negotiate" found. Skipping.');
+                    \SimpleSAML\Logger::debug('Negotiate - authenticate(): No "Negotiate" found. Skipping.');
                 }
             }
 
-            $auth = new KRB5NegotiateAuth($this->keytab);
+            $auth = new \KRB5NegotiateAuth($this->keytab);
             // attempt Kerberos authentication
             try {
                 $reply = $auth->doAuthentication();
-            } catch (Exception $e) {
-                SimpleSAML\Logger::error('Negotiate - authenticate(): doAuthentication() exception: '.$e->getMessage());
+            } catch (\Exception $e) {
+                \SimpleSAML\Logger::error('Negotiate - authenticate(): doAuthentication() exception: '.$e->getMessage());
                 $reply = null;
             }
 
             if ($reply) {
                 // success! krb TGS received
                 $user = $auth->getAuthenticatedUser();
-                SimpleSAML\Logger::info('Negotiate - authenticate(): '.$user.' authenticated.');
+                \SimpleSAML\Logger::info('Negotiate - authenticate(): '.$user.' authenticated.');
                 $lookup = $this->lookupUserData($user);
                 if ($lookup !== null) {
                     $state['Attributes'] = $lookup;
@@ -156,20 +158,20 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
                     $state['LogoutState'] = array(
                         'negotiate:backend' => null,
                     );
-                    SimpleSAML\Logger::info('Negotiate - authenticate(): '.$user.' authorized.');
+                    \SimpleSAML\Logger::info('Negotiate - authenticate(): '.$user.' authorized.');
                     \SimpleSAML\Auth\Source::completeAuth($state);
                     // Never reached.
                     assert(false);
                 }
             } else {
                 // Some error in the received ticket. Expired?
-                SimpleSAML\Logger::info('Negotiate - authenticate(): Kerberos authN failed. Skipping.');
+                \SimpleSAML\Logger::info('Negotiate - authenticate(): Kerberos authN failed. Skipping.');
             }
         } else {
             // No auth token. Send it.
-            SimpleSAML\Logger::debug('Negotiate - authenticate(): Sending Negotiate.');
+            \SimpleSAML\Logger::debug('Negotiate - authenticate(): Sending Negotiate.');
             // Save the $state array, so that we can restore if after a redirect
-            SimpleSAML\Logger::debug('Negotiate - fallback: '.$state['LogoutState']['negotiate:backend']);
+            \SimpleSAML\Logger::debug('Negotiate - fallback: '.$state['LogoutState']['negotiate:backend']);
             $id = \SimpleSAML\Auth\State::saveState($state, self::STAGEID);
             $params = array('AuthState' => $id);
 
@@ -177,7 +179,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
             exit;
         }
 
-        SimpleSAML\Logger::info('Negotiate - authenticate(): Client failed Negotiate. Falling back');
+        \SimpleSAML\Logger::info('Negotiate - authenticate(): Client failed Negotiate. Falling back');
         $this->fallBack($state);
         /* The previous function never returns, so this code is never
            executed */
@@ -189,13 +191,13 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
     {
         if (array_key_exists('negotiate:disable', $spMetadata)) {
             if ($spMetadata['negotiate:disable'] == true) {
-                SimpleSAML\Logger::debug('Negotiate - SP disabled. falling back');
+                \SimpleSAML\Logger::debug('Negotiate - SP disabled. falling back');
                 return true;
             } else {
-                SimpleSAML\Logger::debug('Negotiate - SP disable flag found but set to FALSE');
+                \SimpleSAML\Logger::debug('Negotiate - SP disable flag found but set to FALSE');
             }
         } else {
-            SimpleSAML\Logger::debug('Negotiate - SP disable flag not found');
+            \SimpleSAML\Logger::debug('Negotiate - SP disable flag not found');
         }
         return false;
     }
@@ -217,13 +219,13 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
         }
         $ip = $_SERVER['REMOTE_ADDR'];
         foreach ($this->subnet as $cidr) {
-            $ret = SimpleSAML\Utils\Net::ipCIDRcheck($cidr);
+            $ret = \SimpleSAML\Utils\Net::ipCIDRcheck($cidr);
             if ($ret) {
-                SimpleSAML\Logger::debug('Negotiate: Client "'.$ip.'" matched subnet.');
+                \SimpleSAML\Logger::debug('Negotiate: Client "'.$ip.'" matched subnet.');
                 return true;
             }
         }
-        SimpleSAML\Logger::debug('Negotiate: Client "'.$ip.'" did not match subnet.');
+        \SimpleSAML\Logger::debug('Negotiate: Client "'.$ip.'" did not match subnet.');
         return false;
     }
 
@@ -236,7 +238,7 @@ class sspmod_negotiate_Auth_Source_Negotiate extends \SimpleSAML\Auth\Source
      */
     protected function sendNegotiate($params)
     {
-        $url = htmlspecialchars(SimpleSAML\Module::getModuleURL('negotiate/backend.php', $params));
+        $url = htmlspecialchars(\SimpleSAML\Module::getModuleURL('negotiate/backend.php', $params));
         $json_url = json_encode($url);
 
         header('HTTP/1.1 401 Unauthorized');
@@ -262,7 +264,7 @@ EOF;
      *
      * @throws \SimpleSAML\Error\Error If couldn't determine the auth source.
      * @throws \SimpleSAML\Error\Exception
-     * @throws Exception
+     * @throws \Exception
      */
     public static function fallBack(&$state)
     {
@@ -282,7 +284,7 @@ EOF;
             \SimpleSAML\Auth\State::throwException($state, $e);
         }
         // fallBack never returns after loginCompleted()
-        SimpleSAML\Logger::debug('Negotiate: backend returned');
+        \SimpleSAML\Logger::debug('Negotiate: backend returned');
         self::loginCompleted($state);
     }
 
@@ -309,7 +311,7 @@ EOF;
             $dn = $this->ldap->searchfordn($this->base, $this->attr, $uid);
             return $this->ldap->getAttributes($dn, $this->attributes);
         } catch (\SimpleSAML\Error\Exception $e) {
-            SimpleSAML\Logger::debug('Negotiate - ldap lookup failed: '.$e);
+            \SimpleSAML\Logger::debug('Negotiate - ldap lookup failed: '.$e);
             return null;
         }
     }
@@ -325,13 +327,13 @@ EOF;
             // no admin user
             return;
         }
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             'Negotiate - authenticate(): Binding as system user '.var_export($this->admin_user, true)
         );
 
         if (!$this->ldap->bind($this->admin_user, $this->admin_pw)) {
             $msg = 'Unable to authenticate system user (LDAP_INVALID_CREDENTIALS) '.var_export($this->admin_user, true);
-            SimpleSAML\Logger::error('Negotiate - authenticate(): '.$msg);
+            \SimpleSAML\Logger::error('Negotiate - authenticate(): '.$msg);
             throw new \SimpleSAML\Error\AuthSource('negotiate', $msg);
         }
     }
@@ -350,7 +352,7 @@ EOF;
         assert(is_array($state));
         // get the source that was used to authenticate
         $authId = $state['negotiate:backend'];
-        SimpleSAML\Logger::debug('Negotiate - logout has the following authId: "'.$authId.'"');
+        \SimpleSAML\Logger::debug('Negotiate - logout has the following authId: "'.$authId.'"');
 
         if ($authId === null) {
             $session = \SimpleSAML\Session::getSessionFromRequest();
diff --git a/modules/negotiate/www/backend.php b/modules/negotiate/www/backend.php
index 7c97aa4b9..07550c9e0 100644
--- a/modules/negotiate/www/backend.php
+++ b/modules/negotiate/www/backend.php
@@ -8,9 +8,9 @@
  * @package SimpleSAMLphp
  */
 
-$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], sspmod_negotiate_Auth_Source_Negotiate::STAGEID);
+$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], \SimpleSAML\Module\negotiate\Auth\Source\Negotiate::STAGEID);
 \SimpleSAML\Logger::debug('backend - fallback: '.$state['LogoutState']['negotiate:backend']);
 
-sspmod_negotiate_Auth_Source_Negotiate::fallBack($state);
+\SimpleSAML\Module\negotiate\Auth\Source\Negotiate::fallBack($state);
 
 exit;
diff --git a/modules/negotiate/www/retry.php b/modules/negotiate/www/retry.php
index 046963c59..8378714f7 100644
--- a/modules/negotiate/www/retry.php
+++ b/modules/negotiate/www/retry.php
@@ -8,7 +8,7 @@
  *
  */
 
-$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], sspmod_negotiate_Auth_Source_Negotiate::STAGEID);
+$state = \SimpleSAML\Auth\State::loadState($_REQUEST['AuthState'], \SimpleSAML\Module\negotiate\Auth\Source\Negotiate::STAGEID);
 
 $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
 $idpid = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted', 'metaindex');
diff --git a/modules/oauth/hooks/hook_cron.php b/modules/oauth/hooks/hook_cron.php
index cb626e387..8a0c9daa4 100644
--- a/modules/oauth/hooks/hook_cron.php
+++ b/modules/oauth/hooks/hook_cron.php
@@ -15,15 +15,15 @@ function oauth_hook_cron(&$croninfo) {
 	if ($oauthconfig->getValue('cron_tag', NULL) !== $croninfo['tag']) return;
 	
 	try {
-		$store = new sspmod_core_Storage_SQLPermanentStorage('oauth');
+		$store = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('oauth');
 		$cleaned = $store->removeExpired();
 		
 #		if ($cleaned > 0) 
 			$croninfo['summary'][] = 'OAuth clean up. Removed ' . $cleaned . ' expired entries from OAuth storage.';
 		
-	} catch (Exception $e) {
+	} catch (\Exception $e) {
 		$message = 'OAuth clean up cron script failed: ' . $e->getMessage();
-		SimpleSAML\Logger::warning($message);
+		\SimpleSAML\Logger::warning($message);
 		$croninfo['summary'][] = $message;
 	}
 }
diff --git a/modules/oauth/lib/Consumer.php b/modules/oauth/lib/Consumer.php
index 27550ccde..d71053771 100644
--- a/modules/oauth/lib/Consumer.php
+++ b/modules/oauth/lib/Consumer.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\oauth;
+
 require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
 
 /**
@@ -8,15 +10,16 @@ require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
  * @author Andreas Ă…kre Solberg, <andreas.solberg@uninett.no>, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_oauth_Consumer
+
+class Consumer
 {
     private $consumer;
     private $signer;
 
     public function __construct($key, $secret)
     {
-        $this->consumer = new OAuthConsumer($key, $secret, null);
-        $this->signer = new OAuthSignatureMethod_HMAC_SHA1();
+        $this->consumer = new \OAuthConsumer($key, $secret, null);
+        $this->signer = new \OAuthSignatureMethod_HMAC_SHA1();
     }
 
     // Used only to load the libextinc library early
@@ -68,7 +71,7 @@ class sspmod_oauth_Consumer
                 $error .= $oautherror;
             }
 
-            throw new Exception($error . ':' . $url);
+            throw new \Exception($error . ':' . $url);
         } 
         // Fall back to return response, if could not reckognize HTTP header. Should not happen.
         return $response;
@@ -76,7 +79,7 @@ class sspmod_oauth_Consumer
 
     public function getRequestToken($url, $parameters = null)
     {
-        $req_req = OAuthRequest::from_consumer_and_token($this->consumer, null, "GET", $url, $parameters);
+        $req_req = \OAuthRequest::from_consumer_and_token($this->consumer, null, "GET", $url, $parameters);
         $req_req->sign_request($this->signer, $this->consumer, null);
 
         $response_req = self::getHTTP(
@@ -87,13 +90,13 @@ class sspmod_oauth_Consumer
         parse_str($response_req, $responseParsed);
 
         if (array_key_exists('error', $responseParsed)) {
-            throw new Exception('Error getting request token: ' . $responseParsed['error']);
+            throw new \Exception('Error getting request token: ' . $responseParsed['error']);
         }
 
         $requestToken = $responseParsed['oauth_token'];
         $requestTokenSecret = $responseParsed['oauth_token_secret'];
 
-        return new OAuthToken($requestToken, $requestTokenSecret);
+        return new \OAuthToken($requestToken, $requestTokenSecret);
     }
 
     public function getAuthorizeRequest($url, $requestToken, $redirect = true, $callback = null)
@@ -112,27 +115,27 @@ class sspmod_oauth_Consumer
 
     public function getAccessToken($url, $requestToken, $parameters = null)
     {
-        $acc_req = OAuthRequest::from_consumer_and_token($this->consumer, $requestToken, "GET", $url, $parameters);
+        $acc_req = \OAuthRequest::from_consumer_and_token($this->consumer, $requestToken, "GET", $url, $parameters);
         $acc_req->sign_request($this->signer, $this->consumer, $requestToken);
 
         try {
             $response_acc = \SimpleSAML\Utils\HTTP::fetch($acc_req->to_url());
         } catch (\SimpleSAML\Error\Exception $e) {
-            throw new Exception('Error contacting request_token endpoint on the OAuth Provider');
+            throw new \Exception('Error contacting request_token endpoint on the OAuth Provider');
         }
 
-        SimpleSAML\Logger::debug('oauth: Reponse to get access token: '. $response_acc);
+        \SimpleSAML\Logger::debug('oauth: Reponse to get access token: '. $response_acc);
 
         parse_str($response_acc, $accessResponseParsed);
 
         if (array_key_exists('error', $accessResponseParsed)) {
-            throw new Exception('Error getting request token: ' . $accessResponseParsed['error']);
+            throw new \Exception('Error getting request token: ' . $accessResponseParsed['error']);
         }
 
         $accessToken = $accessResponseParsed['oauth_token'];
         $accessTokenSecret = $accessResponseParsed['oauth_token_secret'];
 
-        return new OAuthToken($accessToken, $accessTokenSecret);
+        return new \OAuthToken($accessToken, $accessTokenSecret);
     }
 
     public function postRequest($url, $accessToken, $parameters)
@@ -164,7 +167,7 @@ class sspmod_oauth_Consumer
 
     public function getUserInfo($url, $accessToken, $opts = null)
     {
-        $data_req = OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "GET", $url, null);
+        $data_req = \OAuthRequest::from_consumer_and_token($this->consumer, $accessToken, "GET", $url, null);
         $data_req->sign_request($this->signer, $this->consumer, $accessToken);
 
         if (is_array($opts)) {
diff --git a/modules/oauth/lib/OAuthServer.php b/modules/oauth/lib/OAuthServer.php
index 03d04fe30..30087c6da 100644
--- a/modules/oauth/lib/OAuthServer.php
+++ b/modules/oauth/lib/OAuthServer.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\oauth;
+
 require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
 
 /**
@@ -8,9 +10,17 @@ require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
  * @author Andreas Ă…kre Solberg, <andreas.solberg@uninett.no>, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_oauth_OAuthServer extends OAuthServer {
-	public function get_signature_methods() {
-		return $this->signature_methods;
-	}
+
+class OAuthServer extends OAuthServer
+{
+    public function __construct($store)
+    {
+        parent::__construct($store);
+    }
+
+    public function get_signature_methods()
+    {
+        return $this->signature_methods;
+    }
 }
 
diff --git a/modules/oauth/lib/OAuthStore.php b/modules/oauth/lib/OAuthStore.php
index 7ef2141f3..db18ee589 100644
--- a/modules/oauth/lib/OAuthStore.php
+++ b/modules/oauth/lib/OAuthStore.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\oauth;
+
 require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
 
 /**
@@ -11,7 +14,8 @@ require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
  * @author Mark Dobrinic, <mdobrinic@cozmanova.com>, Cozmanova bv
  * @package SimpleSAMLphp
  */
-class sspmod_oauth_OAuthStore extends OAuthDataStore
+
+class OAuthStore extends \OAuthDataStore
 {
     private $store;
     private $config;
@@ -29,18 +33,18 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
 
     public function __construct()
     {
-        $this->store = new sspmod_core_Storage_SQLPermanentStorage('oauth');
+        $this->store = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('oauth');
         $this->config = \SimpleSAML\Configuration::getOptionalConfig('module_oauth.php');
     }
 
 
     /**
      * Attach the data to the token, and establish the Callback URL and verifier
-     * @param $requestTokenKey RequestToken that was authorized
-     * @param $data Data that is authorized and to be attached to the requestToken
+     * @param string $requestTokenKey RequestToken that was authorized
+     * @param string $data Data that is authorized and to be attached to the requestToken
      * @return array(string:url, string:verifier) ; empty verifier for 1.0-response
      */
-	public function authorize($requestTokenKey, $data)
+    public function authorize($requestTokenKey, $data)
     {
         $url = null;
 
@@ -61,7 +65,7 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
             $url = $oConsumer->callback_url;
         }
 
-        $verifier = SimpleSAML\Utils\Random::generateID();
+        $verifier = \SimpleSAML\Utils\Random::generateID();
         $url = \SimpleSAML\Utils\HTTP::addURLParameters($url, array("oauth_verifier"=>$verifier));
 
         $this->store->set('authorized', $requestTokenKey, $verifier, $data, $this->config->getValue('requestTokenDuration', 60*30));
@@ -73,26 +77,26 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
      * Perform lookup whether a given token exists in the list of authorized tokens; if a verifier is
      * passed as well, the verifier *must* match the verifier that was registered with the token<br/>
      * Note that an accessToken should never be stored with a verifier
-     * @param $requestToken
-     * @param $verifier
-     * @return unknown_type
+     * @param string $requestToken
+     * @param string $verifier
+     * @return bool
      */
     public function isAuthorized($requestToken, $verifier = '')
     {
-        SimpleSAML\Logger::info('OAuth isAuthorized(' . $requestToken . ')');
+        \SimpleSAML\Logger::info('OAuth isAuthorized(' . $requestToken . ')');
         return $this->store->exists('authorized', $requestToken, $verifier);
     }
 
     public function getAuthorizedData($token, $verifier = '')
     {
-        SimpleSAML\Logger::info('OAuth getAuthorizedData(' . $token . ')');
+        \SimpleSAML\Logger::info('OAuth getAuthorizedData(' . $token . ')');
         $data = $this->store->get('authorized', $token, $verifier);
         return $data['value'];
     }
 
     public function moveAuthorizedData($requestToken, $verifier, $accessTokenKey)
     {
-        SimpleSAML\Logger::info('OAuth moveAuthorizedData(' . $requestToken . ', ' . $accessTokenKey . ')');
+        \SimpleSAML\Logger::info('OAuth moveAuthorizedData(' . $requestToken . ', ' . $accessTokenKey . ')');
 
         // Retrieve authorizedData from authorized.requestToken (with provider verifier)
         $authorizedData = $this->getAuthorizedData($requestToken, $verifier);
@@ -107,7 +111,7 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
 
     public function lookup_consumer($consumer_key)
     {
-        SimpleSAML\Logger::info('OAuth lookup_consumer(' . $consumer_key . ')');
+        \SimpleSAML\Logger::info('OAuth lookup_consumer(' . $consumer_key . ')');
         if (!$this->store->exists('consumers', $consumer_key, '')) {
             return null;
         }
@@ -119,25 +123,25 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
         }
 
         if ($consumer['value']['RSAcertificate']) {
-            return new OAuthConsumer($consumer['value']['key'], $consumer['value']['RSAcertificate'], $callback);
+            return new \OAuthConsumer($consumer['value']['key'], $consumer['value']['RSAcertificate'], $callback);
         } else {
-            return new OAuthConsumer($consumer['value']['key'], $consumer['value']['secret'], $callback);
+            return new \OAuthConsumer($consumer['value']['key'], $consumer['value']['secret'], $callback);
         }
     }
 
-    function lookup_token($consumer, $tokenType = 'default', $token)
+    public function lookup_token($consumer, $tokenType = 'default', $token)
     {
-        SimpleSAML\Logger::info('OAuth lookup_token(' . $consumer->key . ', ' . $tokenType. ',' . $token . ')');
+        \SimpleSAML\Logger::info('OAuth lookup_token(' . $consumer->key . ', ' . $tokenType. ',' . $token . ')');
         $data = $this->store->get($tokenType, $token, $consumer->key);
         if ($data == null) {
-            throw new Exception('Could not find token');
+            throw new \Exception('Could not find token');
         }
         return $data['value'];
     }
 
-    function lookup_nonce($consumer, $token, $nonce, $timestamp)
+    public function lookup_nonce($consumer, $token, $nonce, $timestamp)
     {
-        SimpleSAML\Logger::info('OAuth lookup_nonce(' . $consumer . ', ' . $token. ',' . $nonce . ')');
+        \SimpleSAML\Logger::info('OAuth lookup_nonce(' . $consumer . ', ' . $token. ',' . $nonce . ')');
         if ($this->store->exists('nonce', $nonce, $consumer->key)) {
             return true;
         }
@@ -145,13 +149,13 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
         return false;
     }
 
-    function new_request_token($consumer, $callback = null, $version = null)
+    public function new_request_token($consumer, $callback = null, $version = null)
     {
-        SimpleSAML\Logger::info('OAuth new_request_token(' . $consumer . ')');
+        \SimpleSAML\Logger::info('OAuth new_request_token(' . $consumer . ')');
 
         $lifetime = $this->config->getValue('requestTokenDuration', 60*30); 
 
-        $token = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
+        $token = new \OAuthToken(\SimpleSAML\Utils\Random::generateID(), \SimpleSAML\Utils\Random::generateID());
         $token->callback = $callback;	// OAuth1.0-RevA
         $this->store->set('request', $token->key, $consumer->key, $token, $lifetime);
 
@@ -169,22 +173,22 @@ class sspmod_oauth_OAuthStore extends OAuthDataStore
         return $token;
     }
 
-    function new_access_token($requestToken, $consumer, $verifier = null)
+    public function new_access_token($requestToken, $consumer, $verifier = null)
     {
-        SimpleSAML\Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')');
-        $accesstoken = new OAuthToken(SimpleSAML\Utils\Random::generateID(), SimpleSAML\Utils\Random::generateID());
+        \SimpleSAML\Logger::info('OAuth new_access_token(' . $requestToken . ',' . $consumer . ')');
+        $accesstoken = new \OAuthToken(\SimpleSAML\Utils\Random::generateID(), \SimpleSAML\Utils\Random::generateID());
         $this->store->set('access', $accesstoken->key, $consumer->key, $accesstoken, $this->config->getValue('accessTokenDuration', 60*60*24) );
         return $accesstoken;
     }
 
     /**
      * Return OAuthConsumer-instance that a given requestToken was issued to
-     * @param $requestTokenKey
-     * @return unknown_type
+     * @param string $requestTokenKey
+     * @return mixed
      */
     public function lookup_consumer_by_requestToken($requestTokenKey)
     {
-        SimpleSAML\Logger::info('OAuth lookup_consumer_by_requestToken(' . $requestTokenKey . ')');
+        \SimpleSAML\Logger::info('OAuth lookup_consumer_by_requestToken(' . $requestTokenKey . ')');
         if (!$this->store->exists('requesttorequest', $requestTokenKey, '')) {
             return null;
         }
diff --git a/modules/oauth/lib/Registry.php b/modules/oauth/lib/Registry.php
index b2bc33bb9..98ccf022e 100644
--- a/modules/oauth/lib/Registry.php
+++ b/modules/oauth/lib/Registry.php
@@ -1,14 +1,16 @@
 <?php
 
+namespace SimpleSAML\Module\oauth;
+
 /**
  * Editor for OAuth Client Registry
  *
  * @author Andreas Ă…kre Solberg <andreas@uninett.no>, UNINETT AS.
  * @package SimpleSAMLphp
  */
-class sspmod_oauth_Registry {
-
 
+class Registry
+{
 	protected function getStandardField($request, &$entry, $key) {
 		if (array_key_exists('field_' . $key, $request)) {
 			$entry[$key] = $request['field_' . $key];
@@ -36,9 +38,9 @@ class sspmod_oauth_Registry {
 
 	protected function requireStandardField($request, $key) {
 		if (!array_key_exists('field_' . $key, $request))
-			throw new Exception('Required field [' . $key . '] was missing.');
+			throw new \Exception('Required field [' . $key . '] was missing.');
 		if (empty($request['field_' . $key]))
-			throw new Exception('Required field [' . $key . '] was empty.');
+			throw new \Exception('Required field [' . $key . '] was empty.');
 	}
 
 	public function checkForm($request) {
@@ -127,7 +129,6 @@ class sspmod_oauth_Registry {
 			'<input type="submit" name="submit" value="Save" style="margin-top: 5px" />' .
 		'</form>';
 	}
-	
 }
 
 
diff --git a/modules/oauth/www/getUserInfo.php b/modules/oauth/www/getUserInfo.php
index 0389436eb..001e3b33f 100644
--- a/modules/oauth/www/getUserInfo.php
+++ b/modules/oauth/www/getUserInfo.php
@@ -5,11 +5,11 @@ require_once(dirname(dirname(__FILE__)) . '/libextinc/OAuth.php');
 $oauthconfig = \SimpleSAML\Configuration::getConfig('module_oauth.php');
 
 if (!$oauthconfig->getBoolean('getUserInfo.enable', FALSE)) {
-	throw new Exception('Get user info endpoint is disabled. This endpoint can be enabled in the module_oauth.php configuration file.');
+	throw new \Exception('Get user info endpoint is disabled. This endpoint can be enabled in the module_oauth.php configuration file.');
 }
 
-$store = new sspmod_oauth_OAuthStore();
-$server = new sspmod_oauth_OAuthServer($store);
+$store = new \SimpleSAML\Module\oauth\OAuthStore();
+$server = new \SimpleSAML\Module\oauth\OAuthServer($store);
 
 $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
 $plaintext_method = new OAuthSignatureMethod_PLAINTEXT();
diff --git a/modules/oauth/www/registry.edit.php b/modules/oauth/www/registry.edit.php
index 3331667cb..a1f1a4609 100644
--- a/modules/oauth/www/registry.edit.php
+++ b/modules/oauth/www/registry.edit.php
@@ -5,7 +5,7 @@ $config = \SimpleSAML\Configuration::getInstance();
 $session = \SimpleSAML\Session::getSessionFromRequest();
 $oauthconfig = \SimpleSAML\Configuration::getOptionalConfig('module_oauth.php');
 
-$store = new \sspmod_core_Storage_SQLPermanentStorage('oauth');
+$store = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('oauth');
 
 $authsource = "admin";	// force admin to authenticate as registry maintainer
 $useridattr = $oauthconfig->getValue('useridattr', 'user');
@@ -14,7 +14,7 @@ if ($session->isValid($authsource)) {
 	$attributes = $session->getAuthData($authsource, 'Attributes');
 	// Check if userid exists
 	if (!isset($attributes[$useridattr])) 
-		throw new Exception('User ID is missing');
+		throw new \Exception('User ID is missing');
 	$userid = $attributes[$useridattr][0];
 } else {
 	$as = \SimpleSAML\Auth\Source::getById($authsource);
@@ -41,7 +41,7 @@ if (array_key_exists('editkey', $_REQUEST)) {
 	);
 }
 
-$editor = new sspmod_oauth_Registry();
+$editor = new \SimpleSAML\Module\oauth\Registry();
 
 if (isset($_POST['submit'])) {
 	$editor->checkForm($_POST);
diff --git a/modules/oauth/www/registry.php b/modules/oauth/www/registry.php
index 54ff396e1..a229c3782 100644
--- a/modules/oauth/www/registry.php
+++ b/modules/oauth/www/registry.php
@@ -5,7 +5,7 @@ $config = \SimpleSAML\Configuration::getInstance();
 $session = \SimpleSAML\Session::getSessionFromRequest();
 $oauthconfig = \SimpleSAML\Configuration::getOptionalConfig('module_oauth.php');
 
-$store = new \sspmod_core_Storage_SQLPermanentStorage('oauth');
+$store = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('oauth');
 
 $authsource = "admin";	// force admin to authenticate as registry maintainer
 $useridattr = $oauthconfig->getValue('useridattr', 'user');
@@ -14,7 +14,7 @@ if ($session->isValid($authsource)) {
 	$attributes = $session->getAuthData($authsource, 'Attributes');
 	// Check if userid exists
 	if (!isset($attributes[$useridattr])) 
-		throw new Exception('User ID is missing');
+		throw new \Exception('User ID is missing');
 	$userid = $attributes[$useridattr][0];
 } else {
 	$as = \SimpleSAML\Auth\Source::getById($authsource);
@@ -23,9 +23,9 @@ if ($session->isValid($authsource)) {
 
 function requireOwnership($entry, $userid) {
 	if (!isset($entry['owner']))
-		throw new Exception('OAuth Consumer has no owner. Which means no one is granted access, not even you.');
+		throw new \Exception('OAuth Consumer has no owner. Which means no one is granted access, not even you.');
 	if ($entry['owner'] !== $userid) 
-		throw new Exception('OAuth Consumer has an owner that is not equal to your userid, hence you are not granted access.');
+		throw new \Exception('OAuth Consumer has an owner that is not equal to your userid, hence you are not granted access.');
 }
 
 
diff --git a/modules/portal/hooks/hook_htmlinject.php b/modules/portal/hooks/hook_htmlinject.php
index 88a7d63e4..c4c060cbd 100644
--- a/modules/portal/hooks/hook_htmlinject.php
+++ b/modules/portal/hooks/hook_htmlinject.php
@@ -12,7 +12,7 @@ function portal_hook_htmlinject(&$hookinfo) {
 	assert(array_key_exists('page', $hookinfo));
 
 	$links = array('links' => array());
-	SimpleSAML\Module::callHooks('frontpage', $links);
+	\SimpleSAML\Module::callHooks('frontpage', $links);
 
 	$portalConfig = \SimpleSAML\Configuration::getOptionalConfig('module_portal.php');
 	
@@ -24,8 +24,8 @@ function portal_hook_htmlinject(&$hookinfo) {
 	$pagesets = $portalConfig->getValue('pagesets', array(
 		array('frontpage_welcome', 'frontpage_config', 'frontpage_auth', 'frontpage_federation'),
 	));
-	SimpleSAML\Module::callHooks('portalextras', $pagesets);
-	$portal = new sspmod_portal_Portal($allLinks, $pagesets);
+	\SimpleSAML\Module::callHooks('portalextras', $pagesets);
+	$portal = new \SimpleSAML\Module\portal\Portal($allLinks, $pagesets);
 	
 	if (!$portal->isPortalized($hookinfo['page'])) return;
 
diff --git a/modules/portal/lib/Portal.php b/modules/portal/lib/Portal.php
index f12e4062b..fd4e909cb 100644
--- a/modules/portal/lib/Portal.php
+++ b/modules/portal/lib/Portal.php
@@ -1,6 +1,8 @@
 <?php
 
-class sspmod_portal_Portal
+namespace SimpleSAML\Module\portal;
+
+class Portal
 {
 	private $pages;
 	private $config;
@@ -37,14 +39,14 @@ class sspmod_portal_Portal
 	public function getLoginInfo($translator, $thispage)
     {
 		$info = array('info' => '', 'translator' => $translator, 'thispage' => $thispage);
-		SimpleSAML\Module::callHooks('portalLoginInfo', $info);
+		\SimpleSAML\Module::callHooks('portalLoginInfo', $info);
 		return $info['info'];
 	}
 	
 	public function getMenu($thispage)
     {
 		$config = \SimpleSAML\Configuration::getInstance();
-		$t = new SimpleSAML\Locale\Translate($config);
+		$t = new \SimpleSAML\Locale\Translate($config);
 		$tabset = $this->getTabset($thispage);
 		$logininfo = $this->getLoginInfo($t, $thispage);
 		$text = '';
diff --git a/modules/preprodwarning/lib/Auth/Process/Warning.php b/modules/preprodwarning/lib/Auth/Process/Warning.php
index ffeb13320..5ea5b400d 100644
--- a/modules/preprodwarning/lib/Auth/Process/Warning.php
+++ b/modules/preprodwarning/lib/Auth/Process/Warning.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\preprodwarning\Auth\Process;
+
 /**
  * Give a warning that the user is accessing a test system, not a production system.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_preprodwarning_Auth_Process_Warning extends \SimpleSAML\Auth\ProcessingFilter
+class Warning extends \SimpleSAML\Auth\ProcessingFilter
 {
 	/**
 	 * Process a authentication response.
diff --git a/modules/radius/lib/Auth/Source/Radius.php b/modules/radius/lib/Auth/Source/Radius.php
index 514d60784..d590b71f7 100644
--- a/modules/radius/lib/Auth/Source/Radius.php
+++ b/modules/radius/lib/Auth/Source/Radius.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\radius\Auth\Source;
+
 /**
  * RADIUS authentication source.
  *
@@ -7,7 +9,8 @@
  *
  * @package SimpleSAMLphp
  */
-class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase
+
+class Radius extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
     /**
      * The list of radius servers to use.
@@ -130,18 +133,18 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase
             if (!radius_add_server($radius,
                 $server['hostname'], $server['port'], $server['secret'], 
                 $this->timeout, $this->retries)) {
-                SimpleSAML\Logger::info("Could not add radius server: " .
+                \SimpleSAML\Logger::info("Could not add radius server: " .
                     radius_strerror($radius));
                 continue;
             }
             $success = true;
         }
         if (!$success) {
-            throw new Exception('Error adding radius servers, no servers available');
+            throw new \Exception('Error adding radius servers, no servers available');
         }
 
         if (!radius_create_request($radius, RADIUS_ACCESS_REQUEST)) {
-            throw new Exception('Error creating radius request: ' .
+            throw new \Exception('Error creating radius request: ' .
                 radius_strerror($radius));
         }
 
@@ -190,7 +193,7 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase
         while ($resa = radius_get_attr($radius)) {
 
             if (!is_array($resa)) {
-                throw new Exception('Error getting radius attributes: ' .
+                throw new \Exception('Error getting radius attributes: ' .
                     radius_strerror($radius));
             }
 
@@ -206,7 +209,7 @@ class sspmod_radius_Auth_Source_Radius extends sspmod_core_Auth_UserPassBase
 
             $resv = radius_get_vendor_attr($resa['data']);
             if (!is_array($resv)) {
-                throw new Exception('Error getting vendor specific attribute: ' .
+                throw new \Exception('Error getting vendor specific attribute: ' .
                     radius_strerror($radius));
             }
 
diff --git a/modules/riak/hooks/hook_cron.php b/modules/riak/hooks/hook_cron.php
index 6e1ab68fc..cce9cec0e 100644
--- a/modules/riak/hooks/hook_cron.php
+++ b/modules/riak/hooks/hook_cron.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\riak;
+
 /*
  * Copyright (c) 2012 The University of Queensland
  *
@@ -36,18 +38,18 @@ function riak_hook_cron(&$croninfo) {
 	if ($croninfo['tag'] !== 'hourly') return;
 
 	try {
-		$store = new sspmod_riak_Store_Store();
+		$store = new \SimpleSAML\Module\riak\Store\Store();
 		$result = $store->bucket->indexSearch('expires', 'int',
 		    1, time() - 30);
 		foreach ($result as $link) {
 			$link->getBinary()->delete();
 		}
 
-		SimpleSAML\Logger::info(sprintf("deleted %s riak key%s",
+		\SimpleSAML\Logger::info(sprintf("deleted %s riak key%s",
 		    sizeof($result), sizeof($result) == 1 ? '' : 's'));
-	} catch (Exception $e) {
+	} catch (\Exception $e) {
 		$message = 'riak threw exception: ' . $e->getMessage();
-		SimpleSAML\Logger::warning($message);
+		\SimpleSAML\Logger::warning($message);
 		$croninfo['summary'][] = $message;
 	}
 }
diff --git a/modules/riak/lib/Store/Store.php b/modules/riak/lib/Store/Store.php
index 86d41e0c9..89b62d60c 100644
--- a/modules/riak/lib/Store/Store.php
+++ b/modules/riak/lib/Store/Store.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\riak\Store;
+
 /*
  * Copyright (c) 2012 The University of Queensland
  *
@@ -22,7 +24,7 @@
  * and Information Technology.
  */
 
-class sspmod_riak_Store_Store extends SimpleSAML\Store
+class Store extends \SimpleSAML\Store
 {
     public $client;
     public $bucket;
diff --git a/modules/saml/lib/Auth/Process/AttributeNameID.php b/modules/saml/lib/Auth/Process/AttributeNameID.php
index 1bddd2f2c..fbb5669a8 100644
--- a/modules/saml/lib/Auth/Process/AttributeNameID.php
+++ b/modules/saml/lib/Auth/Process/AttributeNameID.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
 
 /**
  * Authentication processing filter to create a NameID from an attribute.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGenerator
+
+class AttributeNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
 {
     /**
      * The attribute we should use as the NameID.
@@ -51,14 +53,14 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen
     {
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating attribute NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating attribute NameID.'
             );
@@ -68,7 +70,7 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen
         $value = $value[0];
 
         if (empty($value)) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -77,5 +79,4 @@ class sspmod_saml_Auth_Process_AttributeNameID extends sspmod_saml_BaseNameIDGen
 
         return $value;
     }
-
 }
diff --git a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
index afb701cb4..106d7b51f 100644
--- a/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
+++ b/modules/saml/lib/Auth/Process/AuthnContextClassRef.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
 
 /**
  * Filter for setting the AuthnContextClassRef in the response.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Auth_Process_AuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
+
+class AuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * The URI we should set as the AuthnContextClassRef in the login response.
diff --git a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
index 1569c6d3d..d7ae42fbc 100644
--- a/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
+++ b/modules/saml/lib/Auth/Process/ExpectedAuthnContextClassRef.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
+
 /**
  * Attribute filter to validate AuthnContextClassRef values.
  *
@@ -16,9 +18,8 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
+class ExpectedAuthnContextClassRef extends \SimpleSAML\Auth\ProcessingFilter
 {
-
     /**
      * Array of accepted AuthnContextClassRef
      * @var array
@@ -47,7 +48,7 @@ class sspmod_saml_Auth_Process_ExpectedAuthnContextClassRef extends \SimpleSAML\
 
         assert(is_array($config));
         if (empty($config['accepted'])) {
-            SimpleSAML\Logger::error(
+            \SimpleSAML\Logger::error(
                 'ExpectedAuthnContextClassRef: Configuration error. There is no accepted AuthnContextClassRef.'
             );
             throw new \SimpleSAML\Error\Exception(
diff --git a/modules/saml/lib/Auth/Process/FilterScopes.php b/modules/saml/lib/Auth/Process/FilterScopes.php
index 7b972e625..6b9eda30f 100644
--- a/modules/saml/lib/Auth/Process/FilterScopes.php
+++ b/modules/saml/lib/Auth/Process/FilterScopes.php
@@ -11,6 +11,7 @@ use SimpleSAML\Logger;
  * @author Jaime Pérez Crespo, UNINETT AS <jaime.perez@uninett.no>
  * @package SimpleSAMLphp
  */
+
 class FilterScopes extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
diff --git a/modules/saml/lib/Auth/Process/NameIDAttribute.php b/modules/saml/lib/Auth/Process/NameIDAttribute.php
index f141bd792..29387ba0a 100644
--- a/modules/saml/lib/Auth/Process/NameIDAttribute.php
+++ b/modules/saml/lib/Auth/Process/NameIDAttribute.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
 
 /**
  * Authentication processing filter to create an attribute from a NameID.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Auth_Process_NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter
+
+class NameIDAttribute extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * The attribute we should save the NameID in.
diff --git a/modules/saml/lib/Auth/Process/PersistentNameID.php b/modules/saml/lib/Auth/Process/PersistentNameID.php
index e67148830..a70c74932 100644
--- a/modules/saml/lib/Auth/Process/PersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/PersistentNameID.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
+
 /**
  * Authentication processing filter to generate a persistent NameID.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGenerator
+
+class PersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
 {
     /**
      * Which attribute contains the unique identifier of the user.
@@ -45,28 +48,27 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe
      */
     protected function getValue(array &$state)
     {
-
         if (!isset($state['Destination']['entityid'])) {
-            SimpleSAML\Logger::warning('No SP entity ID - not generating persistent NameID.');
+            \SimpleSAML\Logger::warning('No SP entity ID - not generating persistent NameID.');
             return null;
         }
         $spEntityId = $state['Destination']['entityid'];
 
         if (!isset($state['Source']['entityid'])) {
-            SimpleSAML\Logger::warning('No IdP entity ID - not generating persistent NameID.');
+            \SimpleSAML\Logger::warning('No IdP entity ID - not generating persistent NameID.');
             return null;
         }
         $idpEntityId = $state['Source']['entityid'];
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -76,14 +78,14 @@ class sspmod_saml_Auth_Process_PersistentNameID extends sspmod_saml_BaseNameIDGe
         $uid = $uid[0];
 
         if (empty($uid)) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
 
-        $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
+        $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
 
         $uidData = 'uidhashbase'.$secretSalt;
         $uidData .= strlen($idpEntityId).':'.$idpEntityId;
diff --git a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
index 84a717fdc..021630afa 100644
--- a/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
+++ b/modules/saml/lib/Auth/Process/PersistentNameID2TargetedID.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
+
 /**
  * Authentication processing filter to create the eduPersonTargetedID attribute from the persistent NameID.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends \SimpleSAML\Auth\ProcessingFilter
+class PersistentNameID2TargetedID extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * The attribute we should save the NameID in.
@@ -59,7 +61,7 @@ class sspmod_saml_Auth_Process_PersistentNameID2TargetedID extends \SimpleSAML\A
         assert(is_array($state));
 
         if (!isset($state['saml:NameID'][\SAML2\Constants::NAMEID_PERSISTENT])) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Unable to generate eduPersonTargetedID because no persistent NameID was available.'
             );
             return;
diff --git a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
index 91cb165de..c1b3bf51a 100644
--- a/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
+++ b/modules/saml/lib/Auth/Process/SQLPersistentNameID.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
+
 /**
  * Authentication processing filter to generate a persistent NameID.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameIDGenerator
+class SQLPersistentNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
 {
     /**
      * Which attribute contains the unique identifier of the user.
@@ -77,13 +79,13 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
      * @param array $state The state array.
      * @return string|null The NameID value.
      *
-     * @throws sspmod_saml_Error if the NameID creation policy is invalid.
+     * @throws \SimpleSAML\Module\saml\Error if the NameID creation policy is invalid.
      */
     protected function getValue(array &$state)
     {
 
         if (!isset($state['saml:NameIDFormat']) && !$this->allowUnspecified) {
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 'SQLPersistentNameID: Request did not specify persistent NameID format, '.
                 'not generating persistent NameID.'
             );
@@ -98,7 +100,7 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
         if (count($validNameIdFormats) && !in_array($this->format, $validNameIdFormats, true) &&
             !$this->allowDifferent
         ) {
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 'SQLPersistentNameID: SP expects different NameID format ('.
                 implode(', ', $validNameIdFormats).'),  not generating persistent NameID.'
             );
@@ -106,26 +108,26 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
         }
 
         if (!isset($state['Destination']['entityid'])) {
-            SimpleSAML\Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
+            \SimpleSAML\Logger::warning('SQLPersistentNameID: No SP entity ID - not generating persistent NameID.');
             return null;
         }
         $spEntityId = $state['Destination']['entityid'];
 
         if (!isset($state['Source']['entityid'])) {
-            SimpleSAML\Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
+            \SimpleSAML\Logger::warning('SQLPersistentNameID: No IdP entity ID - not generating persistent NameID.');
             return null;
         }
         $idpEntityId = $state['Source']['entityid'];
 
         if (!isset($state['Attributes'][$this->attribute]) || count($state['Attributes'][$this->attribute]) === 0) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'SQLPersistentNameID: Missing attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
         if (count($state['Attributes'][$this->attribute]) > 1) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'SQLPersistentNameID: More than one value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
@@ -135,16 +137,16 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
         $uid = $uid[0];
 
         if (empty($uid)) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'Empty value in attribute '.var_export($this->attribute, true).
                 ' on user - not generating persistent NameID.'
             );
             return null;
         }
 
-        $value = sspmod_saml_IdP_SQLNameID::get($idpEntityId, $spEntityId, $uid);
+        $value = \SimpleSAML\Module\saml\IdP\SQLNameID::get($idpEntityId, $spEntityId, $uid);
         if ($value !== null) {
-            SimpleSAML\Logger::debug(
+            \SimpleSAML\Logger::debug(
                 'SQLPersistentNameID: Found persistent NameID '.var_export($value, true).' for user '.
                 var_export($uid, true).'.'
             );
@@ -152,21 +154,21 @@ class sspmod_saml_Auth_Process_SQLPersistentNameID extends sspmod_saml_BaseNameI
         }
 
         if ((!isset($state['saml:AllowCreate']) || !$state['saml:AllowCreate']) && !$this->alwaysCreate) {
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 'SQLPersistentNameID: Did not find persistent NameID for user, and not allowed to create new NameID.'
             );
-            throw new sspmod_saml_Error(
+            throw new \SimpleSAML\Module\saml\Error(
                 \SAML2\Constants::STATUS_RESPONDER,
                 'urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy'
             );
         }
 
         $value = bin2hex(openssl_random_pseudo_bytes(20));
-        SimpleSAML\Logger::debug(
+        \SimpleSAML\Logger::debug(
             'SQLPersistentNameID: Created persistent NameID '.var_export($value, true).' for user '.
             var_export($uid, true).'.'
         );
-        sspmod_saml_IdP_SQLNameID::add($idpEntityId, $spEntityId, $uid, $value);
+        \SimpleSAML\Module\saml\IdP\SQLNameID::add($idpEntityId, $spEntityId, $uid, $value);
 
         return $value;
     }
diff --git a/modules/saml/lib/Auth/Process/TransientNameID.php b/modules/saml/lib/Auth/Process/TransientNameID.php
index e42e077a7..b4a24de5e 100644
--- a/modules/saml/lib/Auth/Process/TransientNameID.php
+++ b/modules/saml/lib/Auth/Process/TransientNameID.php
@@ -1,12 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Process;
+
 /**
  * Authentication processing filter to generate a transient NameID.
  *
  * @package SimpleSAMLphp
  */
 
-class sspmod_saml_Auth_Process_TransientNameID extends sspmod_saml_BaseNameIDGenerator
+class TransientNameID extends \SimpleSAML\Module\saml\BaseNameIDGenerator
 {
     /**
      * Initialize this filter, parse configuration
@@ -31,6 +33,6 @@ class sspmod_saml_Auth_Process_TransientNameID extends sspmod_saml_BaseNameIDGen
      */
     protected function getValue(array &$state)
     {
-        return SimpleSAML\Utils\Random::generateID();
+        return \SimpleSAML\Utils\Random::generateID();
     }
 }
diff --git a/modules/saml/lib/Auth/Source/SP.php b/modules/saml/lib/Auth/Source/SP.php
index a6840d35d..8eb262208 100644
--- a/modules/saml/lib/Auth/Source/SP.php
+++ b/modules/saml/lib/Auth/Source/SP.php
@@ -1,9 +1,11 @@
 <?php
 
+namespace SimpleSAML\Module\saml\Auth\Source;
+
 use SimpleSAML\Auth\Source;
 use SimpleSAML\Auth\State;
 
-class sspmod_saml_Auth_Source_SP extends Source
+class SP extends Source
 {
     /**
      * The entity ID of this SP.
@@ -61,8 +63,8 @@ class sspmod_saml_Auth_Source_SP extends Source
         $this->idp = $this->metadata->getString('idp', null);
         $this->discoURL = $this->metadata->getString('discoURL', null);
 
-        if (empty($this->discoURL) && SimpleSAML\Module::isModuleEnabled('discojuice')) {
-            $this->discoURL = SimpleSAML\Module::getModuleURL('discojuice/central.php');
+        if (empty($this->discoURL) && \SimpleSAML\Module::isModuleEnabled('discojuice')) {
+            $this->discoURL = \SimpleSAML\Module::getModuleURL('discojuice/central.php');
         }
     }
 
@@ -73,7 +75,7 @@ class sspmod_saml_Auth_Source_SP extends Source
      */
     public function getMetadataURL()
     {
-        return SimpleSAML\Module::getModuleURL('saml/sp/metadata.php/' . urlencode($this->authId));
+        return \SimpleSAML\Module::getModuleURL('saml/sp/metadata.php/' . urlencode($this->authId));
     }
 
     /**
@@ -117,17 +119,17 @@ class sspmod_saml_Auth_Source_SP extends Source
         // First, look in saml20-idp-remote.
         try {
             return $metadataHandler->getMetaDataConfig($entityId, 'saml20-idp-remote');
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             /* Metadata wasn't found. */
-            SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage());
+            \SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage());
         }
 
         /* Not found in saml20-idp-remote, look in shib13-idp-remote. */
         try {
             return $metadataHandler->getMetaDataConfig($entityId, 'shib13-idp-remote');
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             /* Metadata wasn't found. */
-            SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage());
+            \SimpleSAML\Logger::debug('getIdpMetadata: ' . $e->getMessage());
         }
 
         /* Not found. */
@@ -159,14 +161,14 @@ class sspmod_saml_Auth_Source_SP extends Source
         }
 
         if ($useArtifact) {
-            $shire = SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId . '/artifact');
+            $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId . '/artifact');
         } else {
-            $shire = SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId);
+            $shire = \SimpleSAML\Module::getModuleURL('saml/sp/saml1-acs.php/' . $this->authId);
         }
 
         $url = $ar->createRedirect($idpEntityId, $shire);
 
-        SimpleSAML\Logger::debug('Starting SAML 1 SSO to ' . var_export($idpEntityId, true) .
+        \SimpleSAML\Logger::debug('Starting SAML 1 SSO to ' . var_export($idpEntityId, true) .
             ' from ' . var_export($this->entityId, true) . '.');
         \SimpleSAML\Utils\HTTP::redirectTrustedURL($url);
     }
@@ -186,22 +188,22 @@ class sspmod_saml_Auth_Source_SP extends Source
             );
         }
 
-        $ar = sspmod_saml_Message::buildAuthnRequest($this->metadata, $idpMetadata);
+        $ar = \SimpleSAML\Module\saml\Message::buildAuthnRequest($this->metadata, $idpMetadata);
 
-        $ar->setAssertionConsumerServiceURL(SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->authId));
+        $ar->setAssertionConsumerServiceURL(\SimpleSAML\Module::getModuleURL('saml/sp/saml2-acs.php/' . $this->authId));
 
         if (isset($state['\SimpleSAML\Auth\Source.ReturnURL'])) {
             $ar->setRelayState($state['\SimpleSAML\Auth\Source.ReturnURL']);
         }
 
         if (isset($state['saml:AuthnContextClassRef'])) {
-            $accr = SimpleSAML\Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']);
-            $comp = SAML2\Constants::COMPARISON_EXACT;
+            $accr = \SimpleSAML\Utils\Arrays::arrayize($state['saml:AuthnContextClassRef']);
+            $comp = \SAML2\Constants::COMPARISON_EXACT;
             if (isset($state['saml:AuthnContextComparison']) && in_array($state['AuthnContextComparison'], array(
-                        SAML2\Constants::COMPARISON_EXACT,
-                        SAML2\Constants::COMPARISON_MINIMUM,
-                        SAML2\Constants::COMPARISON_MAXIMUM,
-                        SAML2\Constants::COMPARISON_BETTER,
+                        \SAML2\Constants::COMPARISON_EXACT,
+                        \SAML2\Constants::COMPARISON_MINIMUM,
+                        \SAML2\Constants::COMPARISON_MAXIMUM,
+                        \SAML2\Constants::COMPARISON_BETTER,
             ), true)) {
                 $comp = $state['saml:AuthnContextComparison'];
             }
@@ -276,7 +278,7 @@ class sspmod_saml_Auth_Source_SP extends Source
         $id = State::saveState($state, 'saml:sp:sso', true);
         $ar->setId($id);
 
-        SimpleSAML\Logger::debug('Sending SAML 2 AuthnRequest to ' .
+        \SimpleSAML\Logger::debug('Sending SAML 2 AuthnRequest to ' .
             var_export($idpMetadata->getString('entityid'), true));
 
         /* Select appropriate SSO endpoint */
@@ -352,10 +354,10 @@ class sspmod_saml_Auth_Source_SP extends Source
         $discoURL = $this->discoURL;
         if ($discoURL === null) {
             /* Fallback to internal discovery service. */
-            $discoURL = SimpleSAML\Module::getModuleURL('saml/disco.php');
+            $discoURL = \SimpleSAML\Module::getModuleURL('saml/disco.php');
         }
 
-        $returnTo = SimpleSAML\Module::getModuleURL('saml/sp/discoresp.php', array('AuthID' => $id));
+        $returnTo = \SimpleSAML\Module::getModuleURL('saml/sp/discoresp.php', array('AuthID' => $id));
 
         $params = array(
             'entityID' => $this->entityId,
@@ -402,7 +404,7 @@ class sspmod_saml_Auth_Source_SP extends Source
 
             if (empty($intersection)) {
                 // all requested IdPs are unknown
-                throw new SimpleSAML\Module\saml\Error\NoSupportedIDP(
+                throw new \SimpleSAML\Module\saml\Error\NoSupportedIDP(
                     \SAML2\Constants::STATUS_REQUESTER,
                     'None of the IdPs requested are supported by this proxy.'
                 );
@@ -410,7 +412,7 @@ class sspmod_saml_Auth_Source_SP extends Source
 
             if (!is_null($idp) && !in_array($idp, $intersection, true)) {
                 // the IdP is enforced but not in the IDPList
-                throw new SimpleSAML\Module\saml\Error\NoAvailableIDP(
+                throw new \SimpleSAML\Module\saml\Error\NoAvailableIDP(
                     \SAML2\Constants::STATUS_REQUESTER,
                     'None of the IdPs requested are available to this proxy.'
                 );
@@ -467,7 +469,7 @@ class sspmod_saml_Auth_Source_SP extends Source
 
             if (empty($intersection)) {
                 // all requested IdPs are unknown
-                throw new SimpleSAML\Module\saml\Error\NoSupportedIDP(
+                throw new \SimpleSAML\Module\saml\Error\NoSupportedIDP(
                     \SAML2\Constants::STATUS_REQUESTER,
                     'None of the IdPs requested are supported by this proxy.'
                 );
@@ -480,7 +482,7 @@ class sspmod_saml_Auth_Source_SP extends Source
              */
             if (!is_null($this->idp) && !in_array($this->idp, $intersection, true)) {
                 // an IdP is enforced but not requested
-                throw new SimpleSAML\Module\saml\Error\NoAvailableIDP(
+                throw new \SimpleSAML\Module\saml\Error\NoAvailableIDP(
                     \SAML2\Constants::STATUS_REQUESTER,
                     'None of the IdPs requested are available to this proxy.'
                 );
@@ -491,7 +493,7 @@ class sspmod_saml_Auth_Source_SP extends Source
              * starting the authentication process again with a different IdP, or
              * cancel the current SSO attempt.
              */
-            SimpleSAML\Logger::warning(
+            \SimpleSAML\Logger::warning(
                 "Reauthentication after logout is needed. The IdP '${state['saml:sp:IdP']}' is not in the IDPList ".
                 "provided by the Service Provider '${state['core:SP']}'."
             );
@@ -531,7 +533,7 @@ class sspmod_saml_Auth_Source_SP extends Source
 
         if (isset($state['isPassive']) && (bool)$state['isPassive']) {
             // passive request, we cannot authenticate the user
-            throw new SimpleSAML\Module\saml\Error\NoPassive(
+            throw new \SimpleSAML\Module\saml\Error\NoPassive(
                     \SAML2\Constants::STATUS_REQUESTER,
                     'Reauthentication required'
             );
@@ -539,8 +541,8 @@ class sspmod_saml_Auth_Source_SP extends Source
 
         // save the state WITHOUT a restart URL, so that we don't try an IdP-initiated login if something goes wrong
         $id = State::saveState($state, 'saml:proxy:invalid_idp', true);
-        $url = SimpleSAML\Module::getModuleURL('saml/proxy/invalid_session.php');
-        SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('AuthState' => $id));
+        $url = \SimpleSAML\Module::getModuleURL('saml/proxy/invalid_session.php');
+        \SimpleSAML\Utils\HTTP::redirectTrustedURL($url, array('AuthState' => $id));
         assert(false);
     }
 
@@ -553,12 +555,12 @@ class sspmod_saml_Auth_Source_SP extends Source
      */
     public static function reauthLogout(array $state)
     {
-        SimpleSAML\Logger::debug('Proxy: logging the user out before re-authentication.');
+        \SimpleSAML\Logger::debug('Proxy: logging the user out before re-authentication.');
 
         if (isset($state['Responder'])) {
             $state['saml:proxy:reauthLogout:PrevResponder'] = $state['Responder'];
         }
-        $state['Responder'] = array('sspmod_saml_Auth_Source_SP', 'reauthPostLogout');
+        $state['Responder'] = array('\SimpleSAML\Module\saml\Auth\Source\SP', 'reauthPostLogout');
 
         $idp = \SimpleSAML\IdP::getByState($state);
         $idp->handleLogoutRequest($state, null);
@@ -596,15 +598,15 @@ class sspmod_saml_Auth_Source_SP extends Source
     {
         assert(isset($state['saml:sp:AuthId']));
 
-        SimpleSAML\Logger::debug('Proxy: logout completed.');
+        \SimpleSAML\Logger::debug('Proxy: logout completed.');
 
         if (isset($state['saml:proxy:reauthLogout:PrevResponder'])) {
             $state['Responder'] = $state['saml:proxy:reauthLogout:PrevResponder'];
         }
 
-        $sp = Source::getById($state['saml:sp:AuthId'], 'sspmod_saml_Auth_Source_SP');
-        /** @var sspmod_saml_Auth_Source_SP $authSource */
-        SimpleSAML\Logger::debug('Proxy: logging in again.');
+        $sp = Source::getById($state['saml:sp:AuthId'], '\SimpleSAML\Module\saml\Auth\Source\SP');
+        /** @var \SimpleSAML\Module\saml\Auth\Source\SP $authSource */
+        \SimpleSAML\Logger::debug('Proxy: logging in again.');
         $sp->authenticate($state);
         assert(false);
     }
@@ -633,11 +635,11 @@ class sspmod_saml_Auth_Source_SP extends Source
             \SAML2\Constants::BINDING_HTTP_REDIRECT,
             \SAML2\Constants::BINDING_HTTP_POST), false);
         if ($endpoint === false) {
-            SimpleSAML\Logger::info('No logout endpoint for IdP ' . var_export($idp, true) . '.');
+            \SimpleSAML\Logger::info('No logout endpoint for IdP ' . var_export($idp, true) . '.');
             return;
         }
 
-        $lr = sspmod_saml_Message::buildLogoutRequest($this->metadata, $idpMetadata);
+        $lr = \SimpleSAML\Module\saml\Message::buildLogoutRequest($this->metadata, $idpMetadata);
         $lr->setNameId($nameId);
         $lr->setSessionIndex($sessionIndex);
         $lr->setRelayState($id);
@@ -648,7 +650,7 @@ class sspmod_saml_Auth_Source_SP extends Source
             $encryptNameId = $this->metadata->getBoolean('nameid.encryption', false);
         }
         if ($encryptNameId) {
-            $lr->encryptNameId(sspmod_saml_Message::getEncryptionKey($idpMetadata));
+            $lr->encryptNameId(\SimpleSAML\Module\saml\Message::getEncryptionKey($idpMetadata));
         }
 
         $b = \SAML2\Binding::getBinding($endpoint['Binding']);
@@ -706,7 +708,7 @@ class sspmod_saml_Auth_Source_SP extends Source
         $authProcState = array(
             'saml:sp:IdP' => $idp,
             'saml:sp:State' => $state,
-            'ReturnCall' => array('sspmod_saml_Auth_Source_SP', 'onProcessingCompleted'),
+            'ReturnCall' => array('\SimpleSAML\Module\saml\Auth\Source\SP', 'onProcessingCompleted'),
 
             'Attributes' => $attributes,
             'Destination' => $spMetadataArray,
@@ -781,7 +783,7 @@ class sspmod_saml_Auth_Source_SP extends Source
         $sourceId = $state['saml:sp:AuthId'];
         $source = Source::getById($sourceId);
         if ($source === null) {
-            throw new Exception('Could not find authentication source with id ' . $sourceId);
+            throw new \Exception('Could not find authentication source with id ' . $sourceId);
         }
 
         /* Register a callback that we can call if we receive a logout request from the IdP. */
diff --git a/modules/saml/lib/BaseNameIDGenerator.php b/modules/saml/lib/BaseNameIDGenerator.php
index d4981fcc3..12115dc37 100644
--- a/modules/saml/lib/BaseNameIDGenerator.php
+++ b/modules/saml/lib/BaseNameIDGenerator.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml;
+
 /**
  * Base filter for generating NameID values.
  *
  * @package SimpleSAMLphp
  */
-abstract class sspmod_saml_BaseNameIDGenerator extends \SimpleSAML\Auth\ProcessingFilter
+
+abstract class BaseNameIDGenerator extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * What NameQualifier should be used.
@@ -96,7 +99,7 @@ abstract class sspmod_saml_BaseNameIDGenerator extends \SimpleSAML\Auth\Processi
             if (isset($state['IdPMetadata']['entityid'])) {
                 $nameId->NameQualifier = $state['IdPMetadata']['entityid'];
             } else {
-                SimpleSAML\Logger::warning('No IdP entity ID, unable to set NameQualifier.');
+                \SimpleSAML\Logger::warning('No IdP entity ID, unable to set NameQualifier.');
             }
         } elseif (is_string($this->nameQualifier)) {
             $nameId->NameQualifier = $this->nameQualifier;
@@ -106,7 +109,7 @@ abstract class sspmod_saml_BaseNameIDGenerator extends \SimpleSAML\Auth\Processi
             if (isset($state['SPMetadata']['entityid'])) {
                 $nameId->SPNameQualifier = $state['SPMetadata']['entityid'];
             } else {
-                SimpleSAML\Logger::warning('No SP entity ID, unable to set SPNameQualifier.');
+                \SimpleSAML\Logger::warning('No SP entity ID, unable to set SPNameQualifier.');
             }
         } elseif (is_string($this->spNameQualifier)) {
             $nameId->SPNameQualifier = $this->spNameQualifier;
diff --git a/modules/saml/lib/Error.php b/modules/saml/lib/Error.php
index e0061a4ad..605624190 100644
--- a/modules/saml/lib/Error.php
+++ b/modules/saml/lib/Error.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml;
+
 /**
  * Class for representing a SAML 2 error.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Error extends \SimpleSAML\Error\Exception
+
+class Error extends \SimpleSAML\Error\Exception
 {
     /**
      * The top-level status code.
@@ -35,9 +38,9 @@ class sspmod_saml_Error extends \SimpleSAML\Error\Exception
      * @param string $status  The top-level status code.
      * @param string|null $subStatus  The second-level status code. Can be NULL, in which case there is no second-level status code.
      * @param string|null $statusMessage  The status message. Can be NULL, in which case there is no status message.
-     * @param Exception|null $cause  The cause of this exception. Can be NULL.
+     * @param \Exception|null $cause  The cause of this exception. Can be NULL.
      */
-    public function __construct($status, $subStatus = null, $statusMessage = null, Exception $cause = null)
+    public function __construct($status, $subStatus = null, $statusMessage = null, \Exception $cause = null)
     {
         assert(is_string($status));
         assert($subStatus === null || is_string($subStatus));
@@ -98,11 +101,11 @@ class sspmod_saml_Error extends \SimpleSAML\Error\Exception
      * status codes from an arbitrary exception.
      *
      * @param \SimpleSAML\Error\Exception $exception  The original exception.
-     * @return sspmod_saml_Error  The new exception.
+     * @return \SimpleSAML\Module\saml\Error  The new exception.
      */
     public static function fromException(\SimpleSAML\Error\Exception $exception)
     {
-        if ($exception instanceof sspmod_saml_Error) {
+        if ($exception instanceof \SimpleSAML\Module\saml\Error) {
             // Return the original exception unchanged
             return $exception;
 
@@ -142,7 +145,7 @@ class sspmod_saml_Error extends \SimpleSAML\Error\Exception
      * If it is unable to create a more specific exception, it will return the current
      * object.
      *
-     * @see sspmod_saml_Error::fromException()
+     * @see \SimpleSAML\Module\saml\Error::fromException()
      *
      * @return \SimpleSAML\Error\Exception  An exception representing this error.
      */
@@ -154,7 +157,7 @@ class sspmod_saml_Error extends \SimpleSAML\Error\Exception
             case \SAML2\Constants::STATUS_RESPONDER:
                 switch ($this->subStatus) {
                     case \SAML2\Constants::STATUS_NO_PASSIVE:
-                        $e = new SimpleSAML\Module\saml\Error\NoPassive(
+                        $e = new \SimpleSAML\Module\saml\Error\NoPassive(
                             \SAML2\Constants::STATUS_RESPONDER,
                             $this->statusMessage
                         );
diff --git a/modules/saml/lib/Error/NoAuthnContext.php b/modules/saml/lib/Error/NoAuthnContext.php
index 27f5ecf55..54a147463 100644
--- a/modules/saml/lib/Error/NoAuthnContext.php
+++ b/modules/saml/lib/Error/NoAuthnContext.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\saml\Error;
+
 /**
  * A SAML error indicating that none of the requested Authentication Contexts can be used.
  *
@@ -6,11 +9,9 @@
  * @package SimpleSAMLphp
  */
 
-namespace SimpleSAML\Module\saml\Error;
-
 use SAML2\Constants;
 
-class NoAuthnContext extends \sspmod_saml_Error
+class NoAuthnContext extends \SimpleSAML\Module\saml\Error
 {
     /**
      * NoAuthnContext error constructor.
diff --git a/modules/saml/lib/Error/NoAvailableIDP.php b/modules/saml/lib/Error/NoAvailableIDP.php
index 9245ef993..92f78d00b 100644
--- a/modules/saml/lib/Error/NoAvailableIDP.php
+++ b/modules/saml/lib/Error/NoAvailableIDP.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\saml\Error;
+
 /**
  * A SAML error indicating that none of the requested IdPs can be used.
  *
@@ -6,11 +9,9 @@
  * @package SimpleSAMLphp
  */
 
-namespace SimpleSAML\Module\saml\Error;
-
 use SAML2\Constants;
 
-class NoAvailableIDP extends \sspmod_saml_Error
+class NoAvailableIDP extends \SimpleSAML\Module\saml\Error
 {
     /**
      * NoAvailableIDP error constructor.
diff --git a/modules/saml/lib/Error/NoPassive.php b/modules/saml/lib/Error/NoPassive.php
index 2fa30be6b..8602bce1f 100644
--- a/modules/saml/lib/Error/NoPassive.php
+++ b/modules/saml/lib/Error/NoPassive.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\saml\Error;
+
 /**
  * A SAML error indicating that passive authentication cannot be used.
  *
@@ -6,11 +9,9 @@
  * @package SimpleSAMLphp
  */
 
-namespace SimpleSAML\Module\saml\Error;
-
 use SAML2\Constants;
 
-class NoPassive extends \sspmod_saml_Error
+class NoPassive extends \SimpleSAML\Module\saml\Error
 {
     /**
      * NoPassive error constructor.
diff --git a/modules/saml/lib/Error/NoSupportedIDP.php b/modules/saml/lib/Error/NoSupportedIDP.php
index 0e1e6d7f7..5eedd1d27 100644
--- a/modules/saml/lib/Error/NoSupportedIDP.php
+++ b/modules/saml/lib/Error/NoSupportedIDP.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\saml\Error;
+
 /**
  * A SAML error indicating that none of the IdPs requested are supported.
  *
@@ -6,11 +9,9 @@
  * @package SimpleSAMLphp
  */
 
-namespace SimpleSAML\Module\saml\Error;
-
 use SAML2\Constants;
 
-class NoSupportedIDP extends \sspmod_saml_Error
+class NoSupportedIDP extends \SimpleSAML\Module\saml\Error
 {
     /**
      * NoSupportedIDP error constructor.
diff --git a/modules/saml/lib/Error/ProxyCountExceeded.php b/modules/saml/lib/Error/ProxyCountExceeded.php
index 7ded7b61b..f85216d82 100644
--- a/modules/saml/lib/Error/ProxyCountExceeded.php
+++ b/modules/saml/lib/Error/ProxyCountExceeded.php
@@ -1,4 +1,7 @@
 <?php
+
+namespace SimpleSAML\Module\saml\Error;
+
 /**
  * A SAML error indicating that the maximum amount of proxies traversed has been reached.
  *
@@ -6,11 +9,9 @@
  * @package SimpleSAMLphp
  */
 
-namespace SimpleSAML\Module\saml\Error;
-
 use SAML2\Constants;
 
-class ProxyCountExceeded extends \sspmod_saml_Error
+class ProxyCountExceeded extends \SimpleSAML\Module\saml\Error
 {
     /**
      * ProxyCountExceeded error constructor.
diff --git a/modules/saml/lib/IdP/SAML1.php b/modules/saml/lib/IdP/SAML1.php
index f306a951f..8e5226c47 100644
--- a/modules/saml/lib/IdP/SAML1.php
+++ b/modules/saml/lib/IdP/SAML1.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\saml\IdP;
+
 use SimpleSAML\Bindings\Shib13\HTTPPost;
 use SimpleSAML\Utils\HTTP;
 
@@ -9,7 +11,7 @@ use SimpleSAML\Utils\HTTP;
  * @package SimpleSAMLphp
  */
 
-class sspmod_saml_IdP_SAML1
+class SAML1
 {
     /**
      * Send a response to the SP.
@@ -28,7 +30,7 @@ class sspmod_saml_IdP_SAML1
         $spMetadata = \SimpleSAML\Configuration::loadFromArray($spMetadata,
             '$metadata[' . var_export($spEntityId, true) . ']');
 
-        SimpleSAML\Logger::info('Sending SAML 1.1 Response to ' . var_export($spEntityId, true));
+        \SimpleSAML\Logger::info('Sending SAML 1.1 Response to ' . var_export($spEntityId, true));
 
         $attributes = $state['Attributes'];
         $shire = $state['saml:shire'];
@@ -125,7 +127,7 @@ class sspmod_saml_IdP_SAML1
             array('cookieTime' => time()));
 
         $state = array(
-            'Responder' => array('sspmod_saml_IdP_SAML1', 'sendResponse'),
+            'Responder' => array('\SimpleSAML\Module\saml\IdP\SAML1', 'sendResponse'),
             'SPMetadata' => $spMetadata->toArray(),
             \SimpleSAML\Auth\State::RESTART => $sessionLostURL,
             'saml:shire' => $shire,
diff --git a/modules/saml/lib/IdP/SAML2.php b/modules/saml/lib/IdP/SAML2.php
index b5df095ed..3e72e1402 100644
--- a/modules/saml/lib/IdP/SAML2.php
+++ b/modules/saml/lib/IdP/SAML2.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\saml\IdP;
+
 use RobRichards\XMLSecLibs\XMLSecurityKey;
 use SimpleSAML\Configuration;
 use SimpleSAML\Logger;
@@ -10,7 +12,8 @@ use SAML2\SOAP;
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_IdP_SAML2
+
+class SAML2
 {
     /**
      * Send a response to the SP.
@@ -52,7 +55,7 @@ class sspmod_saml_IdP_SAML2
         // create the session association (for logout)
         $association = array(
             'id'                => 'saml:'.$spEntityId,
-            'Handler'           => 'sspmod_saml_IdP_SAML2',
+            'Handler'           => '\SimpleSAML\Modulesaml\IdP\SAML2',
             'Expires'           => $assertion->getSessionNotOnOrAfter(),
             'saml:entityID'     => $spEntityId,
             'saml:NameID'       => $state['saml:idp:NameID'],
@@ -117,7 +120,7 @@ class sspmod_saml_IdP_SAML2
 
         $idpMetadata = $idp->getConfig();
 
-        $error = \sspmod_saml_Error::fromException($exception);
+        $error = \SimpleSAML\Module\saml\Error::fromException($exception);
 
         Logger::warning("Returning error to SP with entity ID '".var_export($spEntityId, true)."'.");
         $exception->log(Logger::WARNING);
@@ -333,7 +336,7 @@ class sspmod_saml_IdP_SAML2
             }
             $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
 
-            sspmod_saml_Message::validateMessage($spMetadata, $idpMetadata, $request);
+            \SimpleSAML\Module\saml\Message::validateMessage($spMetadata, $idpMetadata, $request);
 
             $relayState = $request->getRelayState();
 
@@ -411,8 +414,8 @@ class sspmod_saml_IdP_SAML2
         );
 
         $state = array(
-            'Responder'                                   => array('sspmod_saml_IdP_SAML2', 'sendResponse'),
-            \SimpleSAML\Auth\State::EXCEPTION_HANDLER_FUNC => array('sspmod_saml_IdP_SAML2', 'handleAuthError'),
+            'Responder'                                   => array('\SimpleSAML\Module\saml\IdP\SAML2', 'sendResponse'),
+            \SimpleSAML\Auth\State::EXCEPTION_HANDLER_FUNC => array('\SimpleSAML\Module\saml\IdP\SAML2', 'handleAuthError'),
             \SimpleSAML\Auth\State::RESTART                => $sessionLostURL,
 
             'SPMetadata'                  => $spMetadata->toArray(),
@@ -507,7 +510,7 @@ class sspmod_saml_IdP_SAML2
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
 
-        $lr = sspmod_saml_Message::buildLogoutResponse($idpMetadata, $spMetadata);
+        $lr = \SimpleSAML\Module\saml\Message::buildLogoutResponse($idpMetadata, $spMetadata);
         $lr->setInResponseTo($state['saml:RequestId']);
         $lr->setRelayState($state['saml:RelayState']);
 
@@ -568,7 +571,7 @@ class sspmod_saml_IdP_SAML2
         $idpMetadata = $idp->getConfig();
         $spMetadata = $metadata->getMetaDataConfig($spEntityId, 'saml20-sp-remote');
 
-        sspmod_saml_Message::validateMessage($spMetadata, $idpMetadata, $message);
+        \SimpleSAML\Module\saml\Message::validateMessage($spMetadata, $idpMetadata, $message);
 
         if ($message instanceof \SAML2\LogoutResponse) {
             Logger::info('Received SAML 2.0 LogoutResponse from: '.var_export($spEntityId, true));
@@ -584,7 +587,7 @@ class sspmod_saml_IdP_SAML2
             $relayState = $message->getRelayState();
 
             if (!$message->isSuccess()) {
-                $logoutError = sspmod_saml_Message::getResponseError($message);
+                $logoutError = \SimpleSAML\Module\saml\Message::getResponseError($message);
                 Logger::warning('Unsuccessful logout. Status was: '.$logoutError);
             } else {
                 $logoutError = null;
@@ -604,7 +607,7 @@ class sspmod_saml_IdP_SAML2
             Logger::stats('saml20-idp-SLO spinit '.$spStatsId.' '.$idpMetadata->getString('entityid'));
 
             $state = array(
-                'Responder'       => array('sspmod_saml_IdP_SAML2', 'sendLogoutResponse'),
+                'Responder'       => array('\SimpleSAML\Module\saml\IdP\SAML2', 'sendLogoutResponse'),
                 'saml:SPEntityId' => $spEntityId,
                 'saml:RelayState' => $message->getRelayState(),
                 'saml:RequestId'  => $message->getId(),
@@ -648,7 +651,7 @@ class sspmod_saml_IdP_SAML2
             if ($relayState !== null) {
                 $params['RelayState'] = $relayState;
             }
-            return SimpleSAML\Module::getModuleURL('core/idp/logout-iframe-post.php', $params);
+            return \SimpleSAML\Module::getModuleURL('core/idp/logout-iframe-post.php', $params);
         }
 
         $lr = self::buildLogoutRequest($idpMetadata, $spMetadata, $association, $relayState);
@@ -672,7 +675,7 @@ class sspmod_saml_IdP_SAML2
         $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
         try {
             return $metadata->getMetaDataConfig($association['saml:entityID'], 'saml20-sp-remote');
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             return Configuration::loadFromArray(array(), 'Unknown SAML 2 entity.');
         }
     }
@@ -705,7 +708,7 @@ class sspmod_saml_IdP_SAML2
                 $idpEntityId = $idpMetadata->getString('entityid');
                 $spEntityId = $spMetadata->getString('entityid');
 
-                $secretSalt = SimpleSAML\Utils\Config::getSecretSalt();
+                $secretSalt = \SimpleSAML\Utils\Config::getSecretSalt();
 
                 $uidData = 'uidhashbase'.$secretSalt;
                 $uidData .= strlen($idpEntityId).':'.$idpEntityId;
@@ -781,7 +784,7 @@ class sspmod_saml_IdP_SAML2
                 }
 
                 $attrval = $value;
-                if ($value instanceof DOMNodeList) {
+                if ($value instanceof \DOMNodeList) {
                     $attrval = new \SAML2\XML\saml\AttributeValue($value->item(0)->parentNode);
                 }
 
@@ -797,7 +800,7 @@ class sspmod_saml_IdP_SAML2
                             $doc = \SAML2\DOMDocumentFactory::fromString('<root>'.$value.'</root>');
                             $value = $doc->firstChild->childNodes;
                         }
-                        assert($value instanceof DOMNodeList || $value instanceof \SAML2\XML\saml\NameID);
+                        assert($value instanceof \DOMNodeList || $value instanceof \SAML2\XML\saml\NameID);
                         break;
                     default:
                         throw new \SimpleSAML\Error\Exception('Invalid encoding for attribute '.
@@ -878,7 +881,7 @@ class sspmod_saml_IdP_SAML2
 
         $a = new \SAML2\Assertion();
         if ($signAssertion) {
-            sspmod_saml_Message::addSign($idpMetadata, $spMetadata, $a);
+            \SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $a);
         }
 
         $a->setIssuer($idpMetadata->getString('entityid'));
@@ -907,7 +910,7 @@ class sspmod_saml_IdP_SAML2
         $sessionLifetime = $config->getInteger('session.duration', 8 * 60 * 60);
         $a->setSessionNotOnOrAfter($sessionStart + $sessionLifetime);
 
-        $a->setSessionIndex(SimpleSAML\Utils\Random::generateID());
+        $a->setSessionIndex(\SimpleSAML\Utils\Random::generateID());
 
         $sc = new \SAML2\XML\saml\SubjectConfirmation();
         $sc->SubjectConfirmationData = new \SAML2\XML\saml\SubjectConfirmationData();
@@ -1000,7 +1003,7 @@ class sspmod_saml_IdP_SAML2
 
             if ($nameIdFormat === \SAML2\Constants::NAMEID_TRANSIENT) {
                 // generate a random id
-                $nameIdValue = SimpleSAML\Utils\Random::generateID();
+                $nameIdValue = \SimpleSAML\Utils\Random::generateID();
             } else {
                 /* this code will end up generating either a fixed assigned id (via nameid.attribute)
                    or random id if not assigned/configured */
@@ -1008,7 +1011,7 @@ class sspmod_saml_IdP_SAML2
                 if ($nameIdValue === null) {
                     Logger::warning('Falling back to transient NameID.');
                     $nameIdFormat = \SAML2\Constants::NAMEID_TRANSIENT;
-                    $nameIdValue = SimpleSAML\Utils\Random::generateID();
+                    $nameIdValue = \SimpleSAML\Utils\Random::generateID();
                 }
             }
 
@@ -1027,7 +1030,7 @@ class sspmod_saml_IdP_SAML2
             $encryptNameId = $idpMetadata->getBoolean('nameid.encryption', false);
         }
         if ($encryptNameId) {
-            $a->encryptNameId(sspmod_saml_Message::getEncryptionKey($spMetadata));
+            $a->encryptNameId(\SimpleSAML\Module\saml\Message::getEncryptionKey($spMetadata));
         }
 
         return $a;
@@ -1115,7 +1118,7 @@ class sspmod_saml_IdP_SAML2
         array $association,
         $relayState
     ) {
-        $lr = sspmod_saml_Message::buildLogoutRequest($idpMetadata, $spMetadata);
+        $lr = \SimpleSAML\Module\saml\Message::buildLogoutRequest($idpMetadata, $spMetadata);
         $lr->setRelayState($relayState);
         $lr->setSessionIndex($association['saml:SessionIndex']);
         $lr->setNameId($association['saml:NameID']);
@@ -1131,7 +1134,7 @@ class sspmod_saml_IdP_SAML2
             $encryptNameId = $idpMetadata->getBoolean('nameid.encryption', false);
         }
         if ($encryptNameId) {
-            $lr->encryptNameId(sspmod_saml_Message::getEncryptionKey($spMetadata));
+            $lr->encryptNameId(\SimpleSAML\Module\saml\Message::getEncryptionKey($spMetadata));
         }
 
         return $lr;
@@ -1163,7 +1166,7 @@ class sspmod_saml_IdP_SAML2
         $r->setDestination($consumerURL);
 
         if ($signResponse) {
-            sspmod_saml_Message::addSign($idpMetadata, $spMetadata, $r);
+            \SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $r);
         }
 
         return $r;
diff --git a/modules/saml/lib/IdP/SQLNameID.php b/modules/saml/lib/IdP/SQLNameID.php
index e8d47b9b4..3a6093927 100644
--- a/modules/saml/lib/IdP/SQLNameID.php
+++ b/modules/saml/lib/IdP/SQLNameID.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\IdP;
+
 /**
  * Helper class for working with persistent NameIDs stored in SQL datastore.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_IdP_SQLNameID
+
+class SQLNameID
 {
     /**
      * Create NameID table in SQL, if it is missing.
@@ -111,7 +114,7 @@ class sspmod_saml_IdP_SQLNameID
         $query = $store->pdo->prepare($query);
         $query->execute($params);
 
-        $row = $query->fetch(PDO::FETCH_ASSOC);
+        $row = $query->fetch(\PDO::FETCH_ASSOC);
         if ($row === false) {
             // No NameID found
             return null;
@@ -172,7 +175,7 @@ class sspmod_saml_IdP_SQLNameID
         $query->execute($params);
 
         $res = array();
-        while (($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
+        while (($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) {
             $res[$row['_user']] = $row['_value'];
         }
 
diff --git a/modules/saml/lib/Message.php b/modules/saml/lib/Message.php
index 8c96f474d..8cc89f647 100644
--- a/modules/saml/lib/Message.php
+++ b/modules/saml/lib/Message.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\saml;
+
 use RobRichards\XMLSecLibs\XMLSecurityKey;
 
 /**
@@ -7,7 +9,7 @@ use RobRichards\XMLSecLibs\XMLSecurityKey;
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_Message
+class Message
 {
     /**
      * Add signature key and sender certificate to an element (Message or Assertion).
@@ -24,11 +26,11 @@ class sspmod_saml_Message
         $dstPrivateKey = $dstMetadata->getString('signature.privatekey', null);
 
         if ($dstPrivateKey !== null) {
-            $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true, 'signature.');
-            $certArray = SimpleSAML\Utils\Crypto::loadPublicKey($dstMetadata, false, 'signature.');
+            $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true, 'signature.');
+            $certArray = \SimpleSAML\Utils\Crypto::loadPublicKey($dstMetadata, false, 'signature.');
         } else {
-            $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($srcMetadata, true);
-            $certArray = SimpleSAML\Utils\Crypto::loadPublicKey($srcMetadata, false);
+            $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($srcMetadata, true);
+            $certArray = \SimpleSAML\Utils\Crypto::loadPublicKey($srcMetadata, false);
         }
 
         $algo = $dstMetadata->getString('signature.algorithm', null);
@@ -159,11 +161,11 @@ class sspmod_saml_Message
                             "-----END CERTIFICATE-----\n";
                         break;
                     default:
-                        SimpleSAML\Logger::debug('Skipping unknown key type: '.$key['type']);
+                        \SimpleSAML\Logger::debug('Skipping unknown key type: '.$key['type']);
                 }
             }
         } elseif ($srcMetadata->hasValue('certFingerprint')) {
-            SimpleSAML\Logger::notice(
+            \SimpleSAML\Logger::notice(
                 "Validating certificates by fingerprint is deprecated. Please use ".
                 "certData or certificate options in your remote metadata configuration."
             );
@@ -178,10 +180,10 @@ class sspmod_saml_Message
             // we don't have the full certificate stored. Try to find it in the message or the assertion instead
             if (count($certificates) === 0) {
                 /* We need the full certificate in order to match it against the fingerprint. */
-                SimpleSAML\Logger::debug('No certificate in message when validating against fingerprint.');
+                \SimpleSAML\Logger::debug('No certificate in message when validating against fingerprint.');
                 return false;
             } else {
-                SimpleSAML\Logger::debug('Found '.count($certificates).' certificates in '.get_class($element));
+                \SimpleSAML\Logger::debug('Found '.count($certificates).' certificates in '.get_class($element));
             }
 
             $pemCert = self::findCertificate($certFingerprint, $certificates);
@@ -193,7 +195,7 @@ class sspmod_saml_Message
             );
         }
 
-        SimpleSAML\Logger::debug('Has '.count($pemKeys).' candidate keys for validation.');
+        \SimpleSAML\Logger::debug('Has '.count($pemKeys).' candidate keys for validation.');
 
         $lastException = null;
         foreach ($pemKeys as $i => $pem) {
@@ -204,12 +206,12 @@ class sspmod_saml_Message
                 // make sure that we have a valid signature on either the response or the assertion
                 $res = $element->validate($key);
                 if ($res) {
-                    SimpleSAML\Logger::debug('Validation with key #'.$i.' succeeded.');
+                    \SimpleSAML\Logger::debug('Validation with key #'.$i.' succeeded.');
                     return true;
                 }
-                SimpleSAML\Logger::debug('Validation with key #'.$i.' failed without exception.');
-            } catch (Exception $e) {
-                SimpleSAML\Logger::debug('Validation with key #'.$i.' failed with exception: '.$e->getMessage());
+                \SimpleSAML\Logger::debug('Validation with key #'.$i.' failed without exception.');
+            } catch (\Exception $e) {
+                \SimpleSAML\Logger::debug('Validation with key #'.$i.' failed with exception: '.$e->getMessage());
                 $lastException = $e;
             }
         }
@@ -291,7 +293,7 @@ class sspmod_saml_Message
         $keys = array();
 
         // load the new private key if it exists
-        $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, false, 'new_');
+        $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, false, 'new_');
         if ($keyArray !== null) {
             assert(isset($keyArray['PEM']));
 
@@ -304,7 +306,7 @@ class sspmod_saml_Message
         }
 
         // find the existing private key
-        $keyArray = SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true);
+        $keyArray = \SimpleSAML\Utils\Crypto::loadPrivateKey($dstMetadata, true);
         assert(isset($keyArray['PEM']));
 
         $key = new XMLSecurityKey(XMLSecurityKey::RSA_1_5, array('type' => 'private'));
@@ -367,7 +369,7 @@ class sspmod_saml_Message
             }
             if ($encryptAssertion) {
                 /* The assertion was unencrypted, but we have encryption enabled. */
-                throw new Exception('Received unencrypted assertion, but encryption was enabled.');
+                throw new \Exception('Received unencrypted assertion, but encryption was enabled.');
             }
 
             return $assertion;
@@ -375,7 +377,7 @@ class sspmod_saml_Message
 
         try {
             $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata);
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             throw new \SimpleSAML\Error\Exception('Error decrypting assertion: '.$e->getMessage());
         }
 
@@ -385,10 +387,10 @@ class sspmod_saml_Message
         foreach ($keys as $i => $key) {
             try {
                 $ret = $assertion->getAssertion($key, $blacklist);
-                SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
+                \SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
                 return $ret;
-            } catch (Exception $e) {
-                SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
+            } catch (\Exception $e) {
+                \SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
                 $lastException = $e;
             }
         }
@@ -418,7 +420,7 @@ class sspmod_saml_Message
 
         try {
             $keys = self::getDecryptionKeys($srcMetadata, $dstMetadata);
-        } catch (Exception $e) {
+        } catch (\Exception $e) {
             throw new \SimpleSAML\Error\Exception('Error decrypting attributes: '.$e->getMessage());
         }
 
@@ -428,11 +430,11 @@ class sspmod_saml_Message
         foreach ($keys as $i => $key) {
             try {
                 $assertion->decryptAttributes($key, $blacklist);
-                SimpleSAML\Logger::debug('Attribute decryption with key #'.$i.' succeeded.');
+                \SimpleSAML\Logger::debug('Attribute decryption with key #'.$i.' succeeded.');
                 $error = false;
                 break;
-            } catch (Exception $e) {
-                SimpleSAML\Logger::debug('Attribute decryption failed with exception: '.$e->getMessage());
+            } catch (\Exception $e) {
+                \SimpleSAML\Logger::debug('Attribute decryption failed with exception: '.$e->getMessage());
             }
         }
         if ($error) {
@@ -442,16 +444,16 @@ class sspmod_saml_Message
 
 
     /**
-     * Retrieve the status code of a response as a sspmod_saml_Error.
+     * Retrieve the status code of a response as a \SimpleSAML\Module\saml\Error.
      *
      * @param \SAML2\StatusResponse $response The response.
      *
-     * @return sspmod_saml_Error The error.
+     * @return \SimpleSAML\Module\saml\Error The error.
      */
     public static function getResponseError(\SAML2\StatusResponse $response)
     {
         $status = $response->getStatus();
-        return new sspmod_saml_Error($status['Code'], $status['SubCode'], $status['Message']);
+        return new \SimpleSAML\Module\saml\Error($status['Code'], $status['SubCode'], $status['Message']);
     }
 
 
@@ -568,7 +570,7 @@ class sspmod_saml_Message
     /**
      * Process a response message.
      *
-     * If the response is an error response, we will throw a sspmod_saml_Error exception with the error.
+     * If the response is an error response, we will throw a \SimpleSAML\Module\saml\Error exception with the error.
      *
      * @param \SimpleSAML\Configuration $spMetadata The metadata of the service provider.
      * @param \SimpleSAML\Configuration $idpMetadata The metadata of the identity provider.
@@ -592,7 +594,7 @@ class sspmod_saml_Message
         $currentURL = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery();
         $msgDestination = $response->getDestination();
         if ($msgDestination !== null && $msgDestination !== $currentURL) {
-            throw new Exception('Destination in response doesn\'t match the current URL. Destination is "'.
+            throw new \Exception('Destination in response doesn\'t match the current URL. Destination is "'.
                 $msgDestination.'", current URL is "'.$currentURL.'".');
         }
 
@@ -825,7 +827,7 @@ class sspmod_saml_Message
         if ($assertion->isNameIdEncrypted()) {
             try {
                 $keys = self::getDecryptionKeys($idpMetadata, $spMetadata);
-            } catch (Exception $e) {
+            } catch (\Exception $e) {
                 throw new \SimpleSAML\Error\Exception('Error decrypting NameID: '.$e->getMessage());
             }
 
@@ -835,11 +837,11 @@ class sspmod_saml_Message
             foreach ($keys as $i => $key) {
                 try {
                     $assertion->decryptNameId($key, $blacklist);
-                    SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
+                    \SimpleSAML\Logger::debug('Decryption with key #'.$i.' succeeded.');
                     $lastException = null;
                     break;
-                } catch (Exception $e) {
-                    SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
+                } catch (\Exception $e) {
+                    \SimpleSAML\Logger::debug('Decryption with key #'.$i.' failed with exception: '.$e->getMessage());
                     $lastException = $e;
                 }
             }
diff --git a/modules/saml/lib/SP/LogoutStore.php b/modules/saml/lib/SP/LogoutStore.php
index 18f01d8f8..8d329a8cc 100644
--- a/modules/saml/lib/SP/LogoutStore.php
+++ b/modules/saml/lib/SP/LogoutStore.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\saml\SP;
+
 /**
  * A directory over logout information.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_saml_SP_LogoutStore
+
+class LogoutStore
 {
     /**
      * Create logout table in SQL, if it is missing.
@@ -22,8 +25,8 @@ class sspmod_saml_SP_LogoutStore
             $query = 'ALTER TABLE ' . $store->prefix . '_saml_LogoutStore MODIFY _authSource VARCHAR(255) NOT NULL';
             try {
                 $store->pdo->exec($query);
-            } catch (Exception $e) {
-                SimpleSAML\Logger::warning($store->pdo->errorInfo());
+            } catch (\Exception $e) {
+                \SimpleSAML\Logger::warning($store->pdo->errorInfo());
                 return;
             }
             $store->setTableVersion('saml_LogoutStore', 2);
@@ -57,7 +60,7 @@ class sspmod_saml_SP_LogoutStore
      */
     private static function cleanLogoutStore(\SimpleSAML\Store\SQL $store)
     {
-        SimpleSAML\Logger::debug('saml.LogoutStore: Cleaning logout store.');
+        \SimpleSAML\Logger::debug('saml.LogoutStore: Cleaning logout store.');
 
         $query = 'DELETE FROM ' . $store->prefix . '_saml_LogoutStore WHERE _expire < :now';
         $params = array('now' => gmdate('Y-m-d H:i:s'));
@@ -128,7 +131,7 @@ class sspmod_saml_SP_LogoutStore
         $query->execute($params);
 
         $res = array();
-        while ( ($row = $query->fetch(PDO::FETCH_ASSOC)) !== false) {
+        while ( ($row = $query->fetch(\PDO::FETCH_ASSOC)) !== false) {
             $res[$row['_sessionindex']] = $row['_sessionid'];
         }
 
@@ -189,7 +192,7 @@ class sspmod_saml_SP_LogoutStore
              * it supports SLO, but we don't want an LogoutRequest with a specific
              * SessionIndex to match this session. We therefore generate our own session index.
              */
-            $sessionIndex = SimpleSAML\Utils\Random::generateID();
+            $sessionIndex = \SimpleSAML\Utils\Random::generateID();
         }
 
         $store = \SimpleSAML\Store::getInstance();
@@ -275,7 +278,7 @@ class sspmod_saml_SP_LogoutStore
         $numLoggedOut = 0;
         foreach ($sessionIndexes as $sessionIndex) {
             if (!isset($sessions[$sessionIndex])) {
-                SimpleSAML\Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
+                \SimpleSAML\Logger::info('saml.LogoutStore: Logout requested for unknown SessionIndex.');
                 continue;
             }
 
@@ -283,21 +286,20 @@ class sspmod_saml_SP_LogoutStore
 
             $session = \SimpleSAML\Session::getSession($sessionId);
             if ($session === null) {
-                SimpleSAML\Logger::info('saml.LogoutStore: Skipping logout of missing session.');
+                \SimpleSAML\Logger::info('saml.LogoutStore: Skipping logout of missing session.');
                 continue;
             }
 
             if (!$session->isValid($authId)) {
-                SimpleSAML\Logger::info('saml.LogoutStore: Skipping logout of session because it isn\'t authenticated.');
+                \SimpleSAML\Logger::info('saml.LogoutStore: Skipping logout of session because it isn\'t authenticated.');
                 continue;
             }
 
-            SimpleSAML\Logger::info('saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackID() . '].');
+            \SimpleSAML\Logger::info('saml.LogoutStore: Logging out of session with trackId [' . $session->getTrackID() . '].');
             $session->doLogout($authId);
             $numLoggedOut += 1;
         }
 
         return $numLoggedOut;
     }
-
 }
diff --git a/modules/saml/www/proxy/invalid_session.php b/modules/saml/www/proxy/invalid_session.php
index f24f493db..0be45e11d 100644
--- a/modules/saml/www/proxy/invalid_session.php
+++ b/modules/saml/www/proxy/invalid_session.php
@@ -23,7 +23,7 @@ try {
 
     // success! Try to continue with reauthentication, since we no longer have a valid session here
     $idp = \SimpleSAML\IdP::getById($state['core:IdP']);
-    \sspmod_saml_Auth_Source_SP::reauthPostLogout($idp, $state);
+    \SimpleSAML\Module\saml\Auth\Source\SP::reauthPostLogout($idp, $state);
 }
 
 if (isset($_POST['cancel'])) {
@@ -39,8 +39,8 @@ if (isset($_POST['cancel'])) {
 
 if (isset($_POST['continue'])) {
     // log the user out before being able to login again
-    $as = \SimpleSAML\Auth\Source::getById($state['saml:sp:AuthId'], 'sspmod_saml_Auth_Source_SP');
-    /** @var \sspmod_saml_Auth_Source_SP $as */
+    $as = \SimpleSAML\Auth\Source::getById($state['saml:sp:AuthId'], '\SimpleSAML\Module\saml\Auth\Source\SP');
+    /** @var \SimpleSAML\Module\saml\Auth\Source\SP $as */
     $as->reauthLogout($state);
 }
 
diff --git a/modules/saml/www/sp/discoresp.php b/modules/saml/www/sp/discoresp.php
index 7c7bb68a5..60c15045a 100644
--- a/modules/saml/www/sp/discoresp.php
+++ b/modules/saml/www/sp/discoresp.php
@@ -21,7 +21,7 @@ $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
     throw new Exception('Could not find authentication source with id ' . $sourceId);
 }
-if (!($source instanceof sspmod_saml_Auth_Source_SP)) {
+if (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) {
     throw new \SimpleSAML\Error\Exception('Source type changed?');
 }
 
diff --git a/modules/saml/www/sp/metadata.php b/modules/saml/www/sp/metadata.php
index eb78a0dfc..395bc3552 100644
--- a/modules/saml/www/sp/metadata.php
+++ b/modules/saml/www/sp/metadata.php
@@ -14,7 +14,7 @@ if ($source === null) {
     throw new \SimpleSAML\Error\AuthSource($sourceId, 'Could not find authentication source.');
 }
 
-if (!($source instanceof \sspmod_saml_Auth_Source_SP)) {
+if (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) {
     throw new \SimpleSAML\Error\AuthSource($sourceId,
         'The authentication source is not a SAML Service Provider.');
 }
diff --git a/modules/saml/www/sp/saml1-acs.php b/modules/saml/www/sp/saml1-acs.php
index 7d7dbc0c5..0e607eb53 100644
--- a/modules/saml/www/sp/saml1-acs.php
+++ b/modules/saml/www/sp/saml1-acs.php
@@ -21,7 +21,7 @@ if ($end === false) {
 }
 $sourceId = substr($sourceId, 1, $end - 1);
 
-$source = \SimpleSAML\Auth\Source::getById($sourceId, 'sspmod_saml_Auth_Source_SP');
+$source = \SimpleSAML\Auth\Source::getById($sourceId, '\SimpleSAML\Module\saml\Auth\Source\SP');
 
 SimpleSAML\Logger::debug('Received SAML1 response');
 
diff --git a/modules/saml/www/sp/saml2-acs.php b/modules/saml/www/sp/saml2-acs.php
index 2bb3b9fe3..d89712980 100644
--- a/modules/saml/www/sp/saml2-acs.php
+++ b/modules/saml/www/sp/saml2-acs.php
@@ -9,7 +9,7 @@ if (!array_key_exists('PATH_INFO', $_SERVER)) {
 }
 
 $sourceId = substr($_SERVER['PATH_INFO'], 1);
-$source = \SimpleSAML\Auth\Source::getById($sourceId, 'sspmod_saml_Auth_Source_SP');
+$source = \SimpleSAML\Auth\Source::getById($sourceId, '\SimpleSAML\Module\saml\Auth\Source\SP');
 $spMetadata = $source->getMetadata();
 
 try {
@@ -126,8 +126,8 @@ if (empty($idpMetadata)) {
 }
 
 try {
-    $assertions = sspmod_saml_Message::processResponse($spMetadata, $idpMetadata, $response);
-} catch (sspmod_saml_Error $e) {
+    $assertions = \SimpleSAML\Module\saml\Message::processResponse($spMetadata, $idpMetadata, $response);
+} catch (\SimpleSAML\Module\saml\Error $e) {
     // the status of the response wasn't "success"
     $e = $e->toException();
     \SimpleSAML\Auth\State::throwException($state, $e);
@@ -197,7 +197,7 @@ if ($expire !== null) {
 
 if (!empty($nameId)) {
     // register this session in the logout store
-    sspmod_saml_SP_LogoutStore::addSession($sourceId, $nameId, $sessionIndex, $logoutExpire);
+    \SimpleSAML\Module\saml\SP\LogoutStore::addSession($sourceId, $nameId, $sessionIndex, $logoutExpire);
 
     // we need to save the NameID and SessionIndex for logout
     $logoutState = array(
diff --git a/modules/saml/www/sp/saml2-logout.php b/modules/saml/www/sp/saml2-logout.php
index 5b1da5e55..1ab456692 100644
--- a/modules/saml/www/sp/saml2-logout.php
+++ b/modules/saml/www/sp/saml2-logout.php
@@ -16,7 +16,7 @@ $source = \SimpleSAML\Auth\Source::getById($sourceId);
 if ($source === null) {
     throw new \Exception('Could not find authentication source with id ' . $sourceId);
 }
-if (!($source instanceof sspmod_saml_Auth_Source_SP)) {
+if (!($source instanceof \SimpleSAML\Module\saml\Auth\Source\SP)) {
     throw new \SimpleSAML\Error\Exception('Source type changed?');
 }
 
@@ -45,7 +45,7 @@ $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
 $idpMetadata = $source->getIdPMetadata($idpEntityId);
 $spMetadata = $source->getMetadata();
 
-sspmod_saml_Message::validateMessage($idpMetadata, $spMetadata, $message);
+\SimpleSAML\Module\saml\Message::validateMessage($idpMetadata, $spMetadata, $message);
 
 $destination = $message->getDestination();
 if ($destination !== null && $destination !== \SimpleSAML\Utils\HTTP::getSelfURLNoQuery()) {
@@ -61,7 +61,7 @@ if ($message instanceof \SAML2\LogoutResponse) {
     }
 
     if (!$message->isSuccess()) {
-        \SimpleSAML\Logger::warning('Unsuccessful logout. Status was: ' . sspmod_saml_Message::getResponseError($message));
+        \SimpleSAML\Logger::warning('Unsuccessful logout. Status was: ' . \SimpleSAML\Module\saml\Message::getResponseError($message));
     }
 
     $state = \SimpleSAML\Auth\State::loadState($relayState, 'saml:slosent');
@@ -75,12 +75,12 @@ if ($message instanceof \SAML2\LogoutResponse) {
 
     if ($message->isNameIdEncrypted()) {
         try {
-            $keys = sspmod_saml_Message::getDecryptionKeys($idpMetadata, $spMetadata);
+            $keys = \SimpleSAML\Module\saml\Message::getDecryptionKeys($idpMetadata, $spMetadata);
         } catch (\Exception $e) {
             throw new \SimpleSAML\Error\Exception('Error decrypting NameID: ' . $e->getMessage());
         }
 
-        $blacklist = sspmod_saml_Message::getBlacklistedAlgorithms($idpMetadata, $spMetadata);
+        $blacklist = \SimpleSAML\Module\saml\Message::getBlacklistedAlgorithms($idpMetadata, $spMetadata);
 
         $lastException = null;
         foreach ($keys as $i => $key) {
@@ -102,7 +102,7 @@ if ($message instanceof \SAML2\LogoutResponse) {
     $nameId = $message->getNameId();
     $sessionIndexes = $message->getSessionIndexes();
 
-    $numLoggedOut = sspmod_saml_SP_LogoutStore::logoutSessions($sourceId, $nameId, $sessionIndexes);
+    $numLoggedOut = \SimpleSAML\Module\saml\SP\LogoutStore::logoutSessions($sourceId, $nameId, $sessionIndexes);
     if ($numLoggedOut === false) {
         /* This type of logout was unsupported. Use the old method. */
         $source->handleLogout($idpEntityId);
@@ -110,7 +110,7 @@ if ($message instanceof \SAML2\LogoutResponse) {
     }
 
     /* Create and send response. */
-    $lr = sspmod_saml_Message::buildLogoutResponse($spMetadata, $idpMetadata);
+    $lr = \SimpleSAML\Module\saml\Message::buildLogoutResponse($spMetadata, $idpMetadata);
     $lr->setRelayState($message->getRelayState());
     $lr->setInResponseTo($message->getId());
 
diff --git a/modules/smartattributes/lib/Auth/Process/SmartID.php b/modules/smartattributes/lib/Auth/Process/SmartID.php
index cf0b7036c..2dbde82f9 100644
--- a/modules/smartattributes/lib/Auth/Process/SmartID.php
+++ b/modules/smartattributes/lib/Auth/Process/SmartID.php
@@ -1,6 +1,8 @@
 <?php
 
-class sspmod_smartattributes_Auth_Process_SmartID extends \SimpleSAML\Auth\ProcessingFilter
+namespace SimpleSAML\Module\smartattributes\Auth\Process;
+
+class SmartID extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Which attributes to use as identifiers?
@@ -52,28 +54,28 @@ class sspmod_smartattributes_Auth_Process_SmartID extends \SimpleSAML\Auth\Proce
         if (array_key_exists('candidates', $config)) {
             $this->_candidates = $config['candidates'];
             if (!is_array($this->_candidates)) {
-                throw new Exception('SmartID authproc configuration error: \'candidates\' should be an array.');
+                throw new \Exception('SmartID authproc configuration error: \'candidates\' should be an array.');
             }
         }
 
         if (array_key_exists('id_attribute', $config)) {
             $this->_id_attribute = $config['id_attribute'];
             if (!is_string($this->_id_attribute)) {
-                throw new Exception('SmartID authproc configuration error: \'id_attribute\' should be a string.');
+                throw new \Exception('SmartID authproc configuration error: \'id_attribute\' should be a string.');
             }
         }
 
         if (array_key_exists('add_authority', $config)) {
             $this->_add_authority = $config['add_authority'];
             if (!is_bool($this->_add_authority)) {
-                throw new Exception('SmartID authproc configuration error: \'add_authority\' should be a boolean.');
+                throw new \Exception('SmartID authproc configuration error: \'add_authority\' should be a boolean.');
             }
         }
 
         if (array_key_exists('add_candidate', $config)) {
             $this->_add_candidate = $config['add_candidate'];
             if (!is_bool($this->_add_candidate)) {
-                throw new Exception('SmartID authproc configuration error: \'add_candidate\' should be a boolean.');
+                throw new \Exception('SmartID authproc configuration error: \'add_candidate\' should be a boolean.');
             }
         }
     }
diff --git a/modules/smartattributes/lib/Auth/Process/SmartName.php b/modules/smartattributes/lib/Auth/Process/SmartName.php
index b41e6aabc..6d86a2297 100644
--- a/modules/smartattributes/lib/Auth/Process/SmartName.php
+++ b/modules/smartattributes/lib/Auth/Process/SmartName.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\smartattributes\Auth\Process;
+
 /**
  * Filter to set name in a smart way, based on available name attributes.
  *
@@ -7,7 +9,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_smartattributes_Auth_Process_SmartName extends \SimpleSAML\Auth\ProcessingFilter
+class SmartName extends \SimpleSAML\Auth\ProcessingFilter
 {
     /**
      * Attributes which should be added/appended.
diff --git a/modules/sqlauth/lib/Auth/Source/SQL.php b/modules/sqlauth/lib/Auth/Source/SQL.php
index 526f7aa15..713c69c32 100644
--- a/modules/sqlauth/lib/Auth/Source/SQL.php
+++ b/modules/sqlauth/lib/Auth/Source/SQL.php
@@ -1,5 +1,7 @@
 <?php
 
+namespace SimpleSAML\Module\sqlauth\Auth\Source;
+
 /**
  * Simple SQL authentication source
  *
@@ -9,7 +11,7 @@
  * @package SimpleSAMLphp
  */
 
-class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase
+class SQL extends \SimpleSAML\Module\core\Auth\UserPassBase
 {
     /**
      * The DSN we should connect to.
@@ -55,12 +57,12 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase
         // Make sure that all required parameters are present.
         foreach (array('dsn', 'username', 'password', 'query') as $param) {
             if (!array_key_exists($param, $config)) {
-                throw new Exception('Missing required attribute \'' . $param .
+                throw new \Exception('Missing required attribute \'' . $param .
                     '\' for authentication source ' . $this->authId);
             }
 
             if (!is_string($config[$param])) {
-                throw new Exception('Expected parameter \'' . $param .
+                throw new \Exception('Expected parameter \'' . $param .
                     '\' for authentication source ' . $this->authId .
                     ' to be a string. Instead it was: ' .
                     var_export($config[$param], true));
@@ -80,18 +82,18 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase
     /**
      * Create a database connection.
      *
-     * @return PDO  The database connection.
+     * @return \PDO  The database connection.
      */
     private function connect()
     {
         try {
-            $db = new PDO($this->dsn, $this->username, $this->password, $this->options);
-        } catch (PDOException $e) {
-            throw new Exception('sqlauth:' . $this->authId . ': - Failed to connect to \'' .
+            $db = new \PDO($this->dsn, $this->username, $this->password, $this->options);
+        } catch (\PDOException $e) {
+            throw new \Exception('sqlauth:' . $this->authId . ': - Failed to connect to \'' .
                 $this->dsn . '\': '. $e->getMessage());
         }
 
-        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
+        $db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
 
         $driver = explode(':', $this->dsn, 2);
         $driver = strtolower($driver[0]);
@@ -134,31 +136,31 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase
 
         try {
             $sth = $db->prepare($this->query);
-        } catch (PDOException $e) {
-            throw new Exception('sqlauth:' . $this->authId .
+        } catch (\PDOException $e) {
+            throw new \Exception('sqlauth:' . $this->authId .
                 ': - Failed to prepare query: ' . $e->getMessage());
         }
 
         try {
             $sth->execute(array('username' => $username, 'password' => $password));
-        } catch (PDOException $e) {
-            throw new Exception('sqlauth:' . $this->authId .
+        } catch (\PDOException $e) {
+            throw new \Exception('sqlauth:' . $this->authId .
                 ': - Failed to execute query: ' . $e->getMessage());
         }
 
         try {
-            $data = $sth->fetchAll(PDO::FETCH_ASSOC);
-        } catch (PDOException $e) {
-            throw new Exception('sqlauth:' . $this->authId .
+            $data = $sth->fetchAll(\PDO::FETCH_ASSOC);
+        } catch (\PDOException $e) {
+            throw new \Exception('sqlauth:' . $this->authId .
                 ': - Failed to fetch result set: ' . $e->getMessage());
         }
 
-        SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Got ' . count($data) .
+        \SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Got ' . count($data) .
             ' rows from database');
 
         if (count($data) === 0) {
             /* No rows returned - invalid username/password. */
-            SimpleSAML\Logger::error('sqlauth:' . $this->authId .
+            \SimpleSAML\Logger::error('sqlauth:' . $this->authId .
                 ': No rows in result set. Probably wrong username/password.');
             throw new \SimpleSAML\Error\Error('WRONGUSERPASS');
         }
@@ -190,7 +192,7 @@ class sspmod_sqlauth_Auth_Source_SQL extends sspmod_core_Auth_UserPassBase
             }
         }
 
-        SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Attributes: ' .
+        \SimpleSAML\Logger::info('sqlauth:' . $this->authId . ': Attributes: ' .
             implode(',', array_keys($attributes)));
 
         return $attributes;
diff --git a/modules/statistics/bin/loganalyzer.php b/modules/statistics/bin/loganalyzer.php
index d55ded29d..0186477c6 100755
--- a/modules/statistics/bin/loganalyzer.php
+++ b/modules/statistics/bin/loganalyzer.php
@@ -50,7 +50,7 @@ foreach($argv as $a) {
     }
 }
 
-$aggregator = new sspmod_statistics_Aggregator(true);
+$aggregator = new \SimpleSAML\Module\statistics\Aggregator(true);
 $aggregator->dumpConfig();
 $aggregator->debugInfo();
 $results = $aggregator->aggregate($debug);
diff --git a/modules/statistics/bin/logcleaner.php b/modules/statistics/bin/logcleaner.php
index c7112267a..5a84c2a5e 100755
--- a/modules/statistics/bin/logcleaner.php
+++ b/modules/statistics/bin/logcleaner.php
@@ -58,7 +58,7 @@ foreach ($argv as $a) {
     }
 }
 
-$cleaner = new sspmod_statistics_LogCleaner($infile);
+$cleaner = new \SimpleSAML\Module\statistics\LogCleaner($infile);
 $cleaner->dumpConfig();
 $todelete = $cleaner->clean($debug);
 
diff --git a/modules/statistics/hooks/hook_cron.php b/modules/statistics/hooks/hook_cron.php
index b918991ce..7df92b8dd 100644
--- a/modules/statistics/hooks/hook_cron.php
+++ b/modules/statistics/hooks/hook_cron.php
@@ -1,9 +1,11 @@
 <?php
+
 /**
  * Hook to run a cron job.
  *
  * @param array &$croninfo  Output
  */
+
 function statistics_hook_cron(&$croninfo)
 {
     assert(is_array($croninfo));
@@ -25,16 +27,16 @@ function statistics_hook_cron(&$croninfo)
     }
 	
     try {
-        $aggregator = new sspmod_statistics_Aggregator();
+        $aggregator = new \SimpleSAML\Module\statistics\Aggregator();
         $results = $aggregator->aggregate();
         if (empty($results)) {
-            SimpleSAML\Logger::notice('Output from statistics aggregator was empty.');
+            \SimpleSAML\Logger::notice('Output from statistics aggregator was empty.');
         } else {
             $aggregator->store($results);
         }
-    } catch (Exception $e) {
+    } catch (\Exception $e) {
         $message = 'Loganalyzer threw exception: ' . $e->getMessage();
-        SimpleSAML\Logger::warning($message);
+        \SimpleSAML\Logger::warning($message);
         $croninfo['summary'][] = $message;
     }
 }
diff --git a/modules/statistics/lib/AccessCheck.php b/modules/statistics/lib/AccessCheck.php
index 7fd210330..5b7967f1c 100644
--- a/modules/statistics/lib/AccessCheck.php
+++ b/modules/statistics/lib/AccessCheck.php
@@ -1,11 +1,14 @@
 <?php
 
+namespace SimpleSAML\Module\statistics;
+
 /**
  * Class implementing the access checker function for the statistics module.
  *
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_AccessCheck
+
+class AccessCheck
 {
     /**
      * Check that the user has access to the statistics.
@@ -28,15 +31,15 @@ class sspmod_statistics_AccessCheck
             return;
         }
 
-        if (SimpleSAML\Utils\Auth::isAdmin()) {
+        if (\SimpleSAML\Utils\Auth::isAdmin()) {
             // User logged in as admin. OK.
-            SimpleSAML\Logger::debug('Statistics auth - logged in as admin, access granted');
+            \SimpleSAML\Logger::debug('Statistics auth - logged in as admin, access granted');
             return;
         }
 
         if (!isset($authsource)) {
             // If authsource is not defined, init admin login.
-            SimpleSAML\Utils\Auth::requireAdmin();
+            \SimpleSAML\Utils\Auth::requireAdmin();
         }
 
         // We are using an authsource for login.
@@ -45,7 +48,7 @@ class sspmod_statistics_AccessCheck
         $as->requireAuth();
 
         // User logged in with auth source.
-        SimpleSAML\Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']');
+        \SimpleSAML\Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']');
 
         // Retrieving attributes
         $attributes = $as->getAttributes();
@@ -53,28 +56,28 @@ class sspmod_statistics_AccessCheck
         if (!empty($allowedusers)) {
             // Check if userid exists
             if (!isset($attributes[$useridattr][0])) {
-                throw new Exception('User ID is missing');
+                throw new \Exception('User ID is missing');
             }
 
             // Check if userid is allowed access..
             if (in_array($attributes[$useridattr][0], $allowedusers, true)) {
-                SimpleSAML\Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']');
+                \SimpleSAML\Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']');
                 return;
             }
-            SimpleSAML\Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']');
+            \SimpleSAML\Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']');
         } else {
-            SimpleSAML\Logger::debug('Statistics auth - no allowedUsers list.');
+            \SimpleSAML\Logger::debug('Statistics auth - no allowedUsers list.');
         }
 
         if (!is_null($acl)) {
-            $acl = new sspmod_core_ACL($acl);
+            $acl = new \SimpleSAML\Module\core\ACL($acl);
             if ($acl->allows($attributes)) {
-                SimpleSAML\Logger::debug('Statistics auth - allowed access by ACL.');
+                \SimpleSAML\Logger::debug('Statistics auth - allowed access by ACL.');
                 return;
             }
-            SimpleSAML\Logger::debug('Statistics auth - denied access by ACL.');
+            \SimpleSAML\Logger::debug('Statistics auth - denied access by ACL.');
         } else {
-            SimpleSAML\Logger::debug('Statistics auth - no ACL configured.');
+            \SimpleSAML\Logger::debug('Statistics auth - no ACL configured.');
         }
         throw new \SimpleSAML\Error\Exception('Access denied to the current user.');
     }
diff --git a/modules/statistics/lib/Aggregator.php b/modules/statistics/lib/Aggregator.php
index 3de80a133..eae6ab5c5 100644
--- a/modules/statistics/lib/Aggregator.php
+++ b/modules/statistics/lib/Aggregator.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_Aggregator
+
+class Aggregator
 {
     private $statconfig;
     private $statdir;
@@ -74,25 +78,25 @@ class sspmod_statistics_Aggregator
         $this->loadMetadata();
 
         if (!is_dir($this->statdir)) {
-            throw new Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
+            throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
         }
 
         if (!file_exists($this->inputfile)) {
-            throw new Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
+            throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
         }
 
         $file = fopen($this->inputfile, 'r');
 
         if ($file === false) {
-            throw new Exception('Statistics module: unable to open file [' . $this->inputfile . ']');
+            throw new \Exception('Statistics module: unable to open file [' . $this->inputfile . ']');
         }
 
-        $logparser = new sspmod_statistics_LogParser(
+        $logparser = new LogParser(
             $this->statconfig->getValue('datestart', 0), $this->statconfig->getValue('datelength', 15), $this->statconfig->getValue('offsetspan', 44)
         );
         $datehandler = array(
-            'default' => new sspmod_statistics_DateHandler($this->offset),
-            'month' => new  sspmod_statistics_DateHandlerMonth($this->offset),
+            'default' => new DateHandler($this->offset),
+            'month' => new  DateHandlerMonth($this->offset),
         );
 
         $notBefore = 0;
@@ -239,8 +243,8 @@ class sspmod_statistics_Aggregator
     public function store($results)
     {
         $datehandler = array(
-            'default' => new sspmod_statistics_DateHandler($this->offset),
-            'month' => new  sspmod_statistics_DateHandlerMonth($this->offset),
+            'default' => new DateHandler($this->offset),
+            'month' => new DateHandlerMonth($this->offset),
         );
 
         // Iterate the first level of results, which is per rule, as defined in the config.
diff --git a/modules/statistics/lib/DateHandler.php b/modules/statistics/lib/DateHandler.php
index 13ed07c7f..b35d07ab3 100644
--- a/modules/statistics/lib/DateHandler.php
+++ b/modules/statistics/lib/DateHandler.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_DateHandler
+
+class DateHandler
 {
     protected $offset;
 
diff --git a/modules/statistics/lib/DateHandlerMonth.php b/modules/statistics/lib/DateHandlerMonth.php
index cdbe93c35..979e1838b 100644
--- a/modules/statistics/lib/DateHandlerMonth.php
+++ b/modules/statistics/lib/DateHandlerMonth.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_DateHandlerMonth extends sspmod_statistics_DateHandler
+
+class DateHandlerMonth extends DateHandler
 {
     /**
      * Constructor
diff --git a/modules/statistics/lib/Graph/GoogleCharts.php b/modules/statistics/lib/Graph/GoogleCharts.php
index 613dddfc5..db3df1446 100644
--- a/modules/statistics/lib/Graph/GoogleCharts.php
+++ b/modules/statistics/lib/Graph/GoogleCharts.php
@@ -1,12 +1,16 @@
 <?php
+
+namespace SimpleSAML\Module\statistics\Graph;
+
 /*
- * sspmod_statistics_Graph_GoogleCharts will help you to create a Google Chart
+ * \SimpleSAML\Module\statistics\Graph\GoogleCharts will help you to create a Google Chart
  * using the Google Charts API. 
  *
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_Graph_GoogleCharts
+
+class GoogleCharts
 {
     /**
      * @var integer
@@ -71,17 +75,17 @@ class sspmod_statistics_Graph_GoogleCharts
      * More documentation on Google Charts here: 
      *   http://code.google.com/apis/chart/
      *
-     * @param $axis        Axis
-     * @param $axpis       Axis positions
-     * @param $datasets    Datasets values
-     * @param $max         Max value. Will be the topmost value on the Y-axis.
+     * @param string $axis        Axis
+     * @param string $axpis       Axis positions
+     * @param array $datasets    Datasets values
+     * @param integer $max         Max value. Will be the topmost value on the Y-axis.
      */
     public function show($axis, $axispos, $datasets, $maxes)
     {
         $labeld = '&chxt=x,y' . '&chxr=0,0,1|1,0,' . $maxes[0];
         if (count($datasets) > 1) {
             if (count($datasets) !== count($maxes)) {
-                throw new Exception('Incorrect number of max calculations for graph plotting.');
+                throw new \Exception('Incorrect number of max calculations for graph plotting.');
             }
             $labeld = '&chxt=x,y,r' . '&chxr=0,0,1|1,0,' . $maxes[0] . '|2,0,' . $maxes[1];
         }
@@ -135,11 +139,11 @@ class sspmod_statistics_Graph_GoogleCharts
      * <code>
      * 	    $foo = array(0, 2, 2.3, 2.6, 6, 10, 15, 98, 198, 256, 487, 563, 763, 801, 899, 999, 987, 198234.485, 283746);
      *	    foreach ($foo AS $f) {
-     *	        echo '<p>' . $f . ' => ' . sspmod_statistics_Graph_GoogleCharts::roof($f);
+     *	        echo '<p>' . $f . ' => ' . \SimpleSAML\Module\statistics\Graph\GoogleCharts::roof($f);
      *	    }
      * </code>
      * 
-     * @param $max    Input value.
+     * @param integer $max    Input value.
      */
     public static function roof($max)
     {
diff --git a/modules/statistics/lib/LogCleaner.php b/modules/statistics/lib/LogCleaner.php
index 9d55de9f9..77ceeaaa4 100644
--- a/modules/statistics/lib/LogCleaner.php
+++ b/modules/statistics/lib/LogCleaner.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_LogCleaner
+
+class LogCleaner
 {
     private $statconfig;
     private $statdir;
@@ -46,16 +50,16 @@ class sspmod_statistics_LogCleaner
     public function clean($debug = false)
     {
         if (!is_dir($this->statdir)) {
-            throw new Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
+            throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
         }
 
         if (!file_exists($this->inputfile)) {
-            throw new Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
+            throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
         }
 
         $file = fopen($this->inputfile, 'r');
 
-        $logparser = new sspmod_statistics_LogParser(
+        $logparser = new LogParser(
             $this->statconfig->getValue('datestart', 0), $this->statconfig->getValue('datelength', 15), $this->statconfig->getValue('offsetspan', 44)
         );
 
@@ -128,11 +132,11 @@ class sspmod_statistics_LogCleaner
         echo "Preparing to delete [" .count($todelete) . "] trackids\n";
 
         if (!is_dir($this->statdir)) {
-            throw new Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
+            throw new \Exception('Statistics module: output dir do not exists [' . $this->statdir . ']');
         }
 
         if (!file_exists($this->inputfile)) {
-            throw new Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
+            throw new \Exception('Statistics module: input file do not exists [' . $this->inputfile . ']');
         }
 
         $file = fopen($this->inputfile, 'r');
@@ -144,7 +148,7 @@ class sspmod_statistics_LogCleaner
         }
         $outfile = fopen($outputfile, 'x'); /* Create the output file. */
 
-        $logparser = new sspmod_statistics_LogParser(
+        $logparser = new LogParser(
             $this->statconfig->getValue('datestart', 0), $this->statconfig->getValue('datelength', 15), $this->statconfig->getValue('offsetspan', 44)
         );
 
diff --git a/modules/statistics/lib/LogParser.php b/modules/statistics/lib/LogParser.php
index 516c56c93..e4cf72a15 100644
--- a/modules/statistics/lib/LogParser.php
+++ b/modules/statistics/lib/LogParser.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_LogParser
+
+class LogParser
 {
     /**
      * @var integer
diff --git a/modules/statistics/lib/RatioDataset.php b/modules/statistics/lib/RatioDataset.php
index a88573c65..da9f5d055 100644
--- a/modules/statistics/lib/RatioDataset.php
+++ b/modules/statistics/lib/RatioDataset.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_RatioDataset extends sspmod_statistics_StatDataset
+
+class RatioDataset extends StatDataset
 {
     public function aggregateSummary()
     {
diff --git a/modules/statistics/lib/Ruleset.php b/modules/statistics/lib/Ruleset.php
index 0c65b1399..679dd368e 100644
--- a/modules/statistics/lib/Ruleset.php
+++ b/modules/statistics/lib/Ruleset.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_Ruleset
+
+class Ruleset
 {
     private $statconfig;
     private $availrulenames;
@@ -29,7 +33,7 @@ class sspmod_statistics_Ruleset
          * Walk through file lists, and get available [rule][fileslot]...
          */
         if (!is_dir($statdir)) {
-            throw new Exception('Statisics output directory [' . $statdir . '] does not exists.');
+            throw new \Exception('Statisics output directory [' . $statdir . '] does not exists.');
         }
         $filelist = scandir($statdir);
         $this->available = array();
@@ -42,7 +46,7 @@ class sspmod_statistics_Ruleset
             }
         }
         if (empty($this->available)) {
-            throw new Exception('No aggregated statistics files found in [' . $statdir . ']');
+            throw new \Exception('No aggregated statistics files found in [' . $statdir . ']');
         }
 
         /*
@@ -86,7 +90,7 @@ class sspmod_statistics_Ruleset
         $statrulesConfig = $this->statconfig->getConfigItem('statrules');
         $statruleConfig = $statrulesConfig->getConfigItem($rule);
 
-        $presenterClass = SimpleSAML\Module::resolveClass($statruleConfig->getValue('presenter', 'statistics:BaseRule'), 'Statistics_Rulesets');
+        $presenterClass = \SimpleSAML\Module::resolveClass($statruleConfig->getValue('presenter', 'statistics:BaseRule'), 'Statistics_Rulesets');
         $statrule = new $presenterClass($this->statconfig, $statruleConfig, $rule, $this->available);
         return $statrule;
     }
diff --git a/modules/statistics/lib/StatDataset.php b/modules/statistics/lib/StatDataset.php
index 993cf3eff..7d890848c 100644
--- a/modules/statistics/lib/StatDataset.php
+++ b/modules/statistics/lib/StatDataset.php
@@ -1,12 +1,13 @@
 <?php
 
+namespace SimpleSAML\Module\statistics;
 
 /**
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
 
-class sspmod_statistics_StatDataset
+class StatDataset
 {
     protected $statconfig;
     protected $ruleconfig;
@@ -45,9 +46,9 @@ class sspmod_statistics_StatDataset
         $this->delimiter = '_';
         $this->max = 0;
 
-        $this->datehandlerTick = new \sspmod_statistics_DateHandler($this->statconfig->getValue('offset', 0));
+        $this->datehandlerTick = new DateHandler($this->statconfig->getValue('offset', 0));
         if ($this->timeresconfig->getValue('customDateHandler', 'default') === 'month') {
-            $this->datehandlerFile = new \sspmod_statistics_DateHandlerMonth(0);
+            $this->datehandlerFile = new DateHandlerMonth(0);
         } else {
             $this->datehandlerFile = $this->datehandlerTick;
         }
@@ -90,7 +91,7 @@ class sspmod_statistics_StatDataset
             }
             $maxvalue = max($res[$this->delimiter], $maxvalue);
         }
-        $this->max = sspmod_statistics_Graph_GoogleCharts::roof($maxvalue);
+        $this->max = Graph\GoogleCharts::roof($maxvalue);
     }
 
     public function getDebugData()
@@ -304,6 +305,5 @@ class sspmod_statistics_StatDataset
         }
         $this->results = $combined;
     }
-
 }
 
diff --git a/modules/statistics/lib/Statistics/FieldPresentation/Base.php b/modules/statistics/lib/Statistics/FieldPresentation/Base.php
index 1402ee315..591892b79 100644
--- a/modules/statistics/lib/Statistics/FieldPresentation/Base.php
+++ b/modules/statistics/lib/Statistics/FieldPresentation/Base.php
@@ -1,6 +1,8 @@
 <?php
 
-class sspmod_statistics_Statistics_FieldPresentation_Base
+namespace SimpleSAML\Module\statistics\Statistics\FieldPresentation;
+
+class Base
 {
     protected $fields;
     protected $template;
diff --git a/modules/statistics/lib/Statistics/FieldPresentation/Entity.php b/modules/statistics/lib/Statistics/FieldPresentation/Entity.php
index d41df2696..0994be59a 100644
--- a/modules/statistics/lib/Statistics/FieldPresentation/Entity.php
+++ b/modules/statistics/lib/Statistics/FieldPresentation/Entity.php
@@ -1,6 +1,8 @@
 <?php
 
-class sspmod_statistics_Statistics_FieldPresentation_Entity extends sspmod_statistics_Statistics_FieldPresentation_Base
+namespace SimpleSAML\Module\statistics\Statistics\FieldPresentation;
+
+class Entity extends Base
 {
     public function getPresentation()
     {
diff --git a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
index 09388e52f..6841861ba 100644
--- a/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
+++ b/modules/statistics/lib/Statistics/Rulesets/BaseRule.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics\Statistics\Rulesets;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_Statistics_Rulesets_BaseRule
+
+class BaseRule
 {
     protected $statconfig;
     protected $ruleconfig;
@@ -49,9 +53,9 @@ class sspmod_statistics_Statistics_Rulesets_BaseRule
         $timeresConfig = $timeresConfigs[$timeres];
 
         if (isset($timeresConfig['customDateHandler']) && $timeresConfig['customDateHandler'] == 'month') {
-            $datehandler = new sspmod_statistics_DateHandlerMonth(0);
+            $datehandler = new \SimpleSAML\Module\statistics\DateHandlerMonth(0);
         } else {
-            $datehandler = new sspmod_statistics_DateHandler($this->statconfig->getValue('offset', 0));
+            $datehandler = new \SimpleSAML\Module\statistics\DateHandler($this->statconfig->getValue('offset', 0));
         }
 
         /*
@@ -112,7 +116,7 @@ class sspmod_statistics_Statistics_Rulesets_BaseRule
     {
         $timeres = $this->resolveTimeRes($preferTimeRes);
         $fileslot = $this->resolveFileSlot($timeres, $preferTime);
-        $dataset = new sspmod_statistics_StatDataset($this->statconfig, $this->ruleconfig, $this->ruleid, $timeres, $fileslot);
+        $dataset = new \SimpleSAML\Module\statistics\StatDataset($this->statconfig, $this->ruleconfig, $this->ruleid, $timeres, $fileslot);
         return $dataset;
     }
 }
diff --git a/modules/statistics/lib/Statistics/Rulesets/Ratio.php b/modules/statistics/lib/Statistics/Rulesets/Ratio.php
index 923e518db..89d9f1c78 100644
--- a/modules/statistics/lib/Statistics/Rulesets/Ratio.php
+++ b/modules/statistics/lib/Statistics/Rulesets/Ratio.php
@@ -1,9 +1,13 @@
 <?php
+
+namespace SimpleSAML\Module\statistics\Statistics\Rulesets;
+
 /*
  * @author Andreas Ă…kre Solberg <andreas.solberg@uninett.no>
  * @package SimpleSAMLphp
  */
-class sspmod_statistics_Statistics_Rulesets_Ratio extends sspmod_statistics_Statistics_Rulesets_BaseRule
+
+class Ratio extends BaseRule
 {
     protected $refrule1;
     protected $refrule2;
@@ -25,8 +29,8 @@ class sspmod_statistics_Statistics_Rulesets_Ratio extends sspmod_statistics_Stat
         $statruleConfig1 = $statrulesConfig->getConfigItem($refNames[0]);
         $statruleConfig2 = $statrulesConfig->getConfigItem($refNames[1]);
 
-        $this->refrule1 = new sspmod_statistics_Statistics_Rulesets_BaseRule($this->statconfig, $statruleConfig1, $refNames[0], $available);
-        $this->refrule2 = new sspmod_statistics_Statistics_Rulesets_BaseRule($this->statconfig, $statruleConfig2, $refNames[1], $available);
+        $this->refrule1 = new BaseRule($this->statconfig, $statruleConfig1, $refNames[0], $available);
+        $this->refrule2 = new BaseRule($this->statconfig, $statruleConfig2, $refNames[1], $available);
     }
 
     public function availableTimeRes()
@@ -61,7 +65,7 @@ class sspmod_statistics_Statistics_Rulesets_Ratio extends sspmod_statistics_Stat
 
         $refNames = $this->ruleconfig->getArray('ref');
 
-        $dataset = new sspmod_statistics_RatioDataset($this->statconfig, $this->ruleconfig, $refNames, $timeres, $fileslot);
+        $dataset = new \SimpleSAML\Module\statistics\RatioDataset($this->statconfig, $this->ruleconfig, $refNames, $timeres, $fileslot);
         return $dataset;
     }
 }
diff --git a/modules/statistics/www/showstats.php b/modules/statistics/www/showstats.php
index a7eeeeca0..b2dd8a26f 100644
--- a/modules/statistics/www/showstats.php
+++ b/modules/statistics/www/showstats.php
@@ -4,7 +4,7 @@ $config = \SimpleSAML\Configuration::getInstance();
 $statconfig = \SimpleSAML\Configuration::getConfig('module_statistics.php');
 $session = \SimpleSAML\Session::getSessionFromRequest();
 
-\sspmod_statistics_AccessCheck::checkAccess($statconfig);
+\SimpleSAML\Module\statistics\AccessCheck::checkAccess($statconfig);
 
 /*
  * Check input parameters
@@ -38,7 +38,7 @@ if ($preferRule2 === '_') {
 /*
  * Create statistics data.
  */
-$ruleset = new \sspmod_statistics_Ruleset($statconfig);
+$ruleset = new \SimpleSAML\Module\statistics\Ruleset($statconfig);
 $statrule = $ruleset->getRule($preferRule);
 $rule = $statrule->getRuleID();
 
@@ -109,7 +109,7 @@ if (isset($preferRule2)) {
 
 $dimx = $statconfig->getValue('dimension.x', 800);
 $dimy = $statconfig->getValue('dimension.y', 350);
-$grapher = new \sspmod_statistics_Graph_GoogleCharts($dimx, $dimy);
+$grapher = new \SimpleSAML\Module\statistics\Graph\GoogleCharts($dimx, $dimy);
 
 $t->data['imgurl'] = $grapher->show($axis['axis'], $axis['axispos'], $datasets, $maxes);
 if (isset($piedata)) {
diff --git a/modules/statistics/www/statmeta.php b/modules/statistics/www/statmeta.php
index 65910d820..442723d0b 100644
--- a/modules/statistics/www/statmeta.php
+++ b/modules/statistics/www/statmeta.php
@@ -3,9 +3,9 @@
 $config = \SimpleSAML\Configuration::getInstance();
 $statconfig = \SimpleSAML\Configuration::getConfig('module_statistics.php');
 
-\sspmod_statistics_AccessCheck::checkAccess($statconfig);
+\SimpleSAML\Module\statistics\AccessCheck::checkAccess($statconfig);
 
-$aggr = new sspmod_statistics_Aggregator();
+$aggr = new \SimpleSAML\Module\statistics\Aggregator();
 $aggr->loadMetadata();
 $metadata = $aggr->getMetadata();
 
diff --git a/tests/modules/consent/lib/Auth/Process/ConsentTest.php b/tests/modules/consent/lib/Auth/Process/ConsentTest.php
index e24b12c3f..1e06862d3 100644
--- a/tests/modules/consent/lib/Auth/Process/ConsentTest.php
+++ b/tests/modules/consent/lib/Auth/Process/ConsentTest.php
@@ -27,7 +27,7 @@ class ConsentTest extends TestCase
      */
     private function processFilter(array $config, array $request)
     {
-        $filter = new \sspmod_consent_Auth_Process_Consent($config, null);
+        $filter = new \SimpleSAML\Module\consent\Auth\Process\Consent($config, null);
         $filter->process($request);
         return $request;
     }
@@ -127,13 +127,13 @@ class ConsentTest extends TestCase
             'attribute1' => array('val1', 'val2'),
             'attribute2' => array('val1', 'val2')
         );
-        $attributeHash1 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes1, true);
+        $attributeHash1 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes1, true);
 
         $attributes2 = array(
             'attribute1' => array('val1', 'val2'),
             'attribute2' => array('val2', 'val1')
         );
-        $attributeHash2 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes2, true);
+        $attributeHash2 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes2, true);
 
         $this->assertEquals($attributeHash1, $attributeHash2, "Hash is not the same when the order of values changes");
     }
@@ -144,13 +144,13 @@ class ConsentTest extends TestCase
             'attribute2' => array('val1', 'val2'),
             'attribute1' => array('val1', 'val2')
         );
-        $attributeHash1 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes1, true);
+        $attributeHash1 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes1, true);
 
         $attributes2 = array(
             'attribute1' => array('val1', 'val2'),
             'attribute2' => array('val1', 'val2')
         );
-        $attributeHash2 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes2, true);
+        $attributeHash2 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes2, true);
 
         $this->assertEquals(
             $attributeHash1,
@@ -165,13 +165,13 @@ class ConsentTest extends TestCase
             'attribute2' => array('val1', 'val2'),
             'attribute1' => array('val1', 'val2')
         );
-        $attributeHash1 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes1);
+        $attributeHash1 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes1);
 
         $attributes2 = array(
             'attribute1' => array('val1', 'val2'),
             'attribute2' => array('val1', 'val2')
         );
-        $attributeHash2 = \sspmod_consent_Auth_Process_Consent::getAttributeHash($attributes2);
+        $attributeHash2 = \SimpleSAML\Module\consent\Auth\Process\Consent::getAttributeHash($attributes2);
 
         $this->assertEquals(
             $attributeHash1,
@@ -182,7 +182,7 @@ class ConsentTest extends TestCase
 
     public function testConstructorSetsInstancePrivateVars()
     {
-        $reflection = new \ReflectionClass('\sspmod_consent_Auth_Process_Consent');
+        $reflection = new \ReflectionClass('\SimpleSAML\Module\consent\Auth\Process\Consent');
 
         foreach (array(
             '_includeValues', '_checked', '_focus', '_hiddenAttributes', '_noconsentattributes', '_showNoConsentAboutService'
diff --git a/tests/modules/core/lib/Auth/Process/AttributeAddTest.php b/tests/modules/core/lib/Auth/Process/AttributeAddTest.php
index e6f763b3f..deabdd3d2 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeAddTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeAddTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_AttributeAdd extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeAdd($config, null);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeAdd($config, null);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/AttributeAlterTest.php b/tests/modules/core/lib/Auth/Process/AttributeAlterTest.php
index c13bcbd10..d59522cba 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeAlterTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeAlterTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_AttributeAlter extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeAlter($config, null);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeAlter($config, null);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/AttributeCopyTest.php b/tests/modules/core/lib/Auth/Process/AttributeCopyTest.php
index d960c379f..52f03613c 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeCopyTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeCopyTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_AttributeCopy extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeCopy($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeCopy($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/AttributeLimitTest.php b/tests/modules/core/lib/Auth/Process/AttributeLimitTest.php
index 535932ba1..fc55240f9 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeLimitTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeLimitTest.php
@@ -16,7 +16,7 @@ class Test_Core_Auth_Process_AttributeLimitTest extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeLimit($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeLimit($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/AttributeMapTest.php b/tests/modules/core/lib/Auth/Process/AttributeMapTest.php
index f454aa480..5c50f59bd 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeMapTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeMapTest.php
@@ -16,7 +16,7 @@ class Test_Core_Auth_Process_AttributeMap extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeMap($config, null);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeMap($config, null);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/AttributeRealmTest.php b/tests/modules/core/lib/Auth/Process/AttributeRealmTest.php
index 915475d17..75ea9441a 100644
--- a/tests/modules/core/lib/Auth/Process/AttributeRealmTest.php
+++ b/tests/modules/core/lib/Auth/Process/AttributeRealmTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_AttributeRealm extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_AttributeRealm($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\AttributeRealm($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/CardinalitySingleTest.php b/tests/modules/core/lib/Auth/Process/CardinalitySingleTest.php
index 2affbaf5c..0c04b777b 100644
--- a/tests/modules/core/lib/Auth/Process/CardinalitySingleTest.php
+++ b/tests/modules/core/lib/Auth/Process/CardinalitySingleTest.php
@@ -22,7 +22,7 @@ class Test_Core_Auth_Process_CardinalitySingleTest extends \PHPUnit_Framework_Te
     {
         $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
         $_SERVER['REQUEST_METHOD'] = 'GET';
-        $filter = new sspmod_core_Auth_Process_CardinalitySingle($config, null, $this->http);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\CardinalitySingle($config, null, $this->http);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/CardinalityTest.php b/tests/modules/core/lib/Auth/Process/CardinalityTest.php
index 30e28f953..8d9475444 100644
--- a/tests/modules/core/lib/Auth/Process/CardinalityTest.php
+++ b/tests/modules/core/lib/Auth/Process/CardinalityTest.php
@@ -23,7 +23,7 @@ class Test_Core_Auth_Process_CardinalityTest extends \PHPUnit_Framework_TestCase
     {
         $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.1';
         $_SERVER['REQUEST_METHOD'] = 'GET';
-        $filter = new sspmod_core_Auth_Process_Cardinality($config, null, $this->http);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\Cardinality($config, null, $this->http);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/PHPTest.php b/tests/modules/core/lib/Auth/Process/PHPTest.php
index 54f2bb290..c73313973 100644
--- a/tests/modules/core/lib/Auth/Process/PHPTest.php
+++ b/tests/modules/core/lib/Auth/Process/PHPTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_PHP extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_PHP($config, null);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\PHP($config, null);
         @$filter->process($request);
         return $request;
     }
@@ -33,7 +33,7 @@ class Test_Core_Auth_Process_PHP extends TestCase
             "\SimpleSAML\Error\Exception",
             "core:PHP: missing mandatory configuration option 'code'."
         );
-        new sspmod_core_Auth_Process_PHP($config, null);
+        new \SimpleSAML\Module\core\Auth\Process\PHP($config, null);
     }
 
 
diff --git a/tests/modules/core/lib/Auth/Process/ScopeAttributeTest.php b/tests/modules/core/lib/Auth/Process/ScopeAttributeTest.php
index 866fc1a64..843492678 100644
--- a/tests/modules/core/lib/Auth/Process/ScopeAttributeTest.php
+++ b/tests/modules/core/lib/Auth/Process/ScopeAttributeTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_ScopeAttribute extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_ScopeAttribute($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\ScopeAttribute($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/ScopeFromAttributeTest.php b/tests/modules/core/lib/Auth/Process/ScopeFromAttributeTest.php
index f22251508..1d24c38e9 100644
--- a/tests/modules/core/lib/Auth/Process/ScopeFromAttributeTest.php
+++ b/tests/modules/core/lib/Auth/Process/ScopeFromAttributeTest.php
@@ -17,7 +17,7 @@ class Test_Core_Auth_Process_ScopeFromAttribute extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_ScopeFromAttribute($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\ScopeFromAttribute($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/Process/TargetedIDTest.php b/tests/modules/core/lib/Auth/Process/TargetedIDTest.php
index 7cfc1abe3..e828db779 100644
--- a/tests/modules/core/lib/Auth/Process/TargetedIDTest.php
+++ b/tests/modules/core/lib/Auth/Process/TargetedIDTest.php
@@ -16,7 +16,7 @@ class Test_Core_Auth_Process_TargetedID extends TestCase
      */
     private static function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_core_Auth_Process_TargetedID($config, NULL);
+        $filter = new \SimpleSAML\Module\core\Auth\Process\TargetedID($config, NULL);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/core/lib/Auth/UserPassBaseTest.php b/tests/modules/core/lib/Auth/UserPassBaseTest.php
index ff248bdc5..d70616800 100644
--- a/tests/modules/core/lib/Auth/UserPassBaseTest.php
+++ b/tests/modules/core/lib/Auth/UserPassBaseTest.php
@@ -1,6 +1,6 @@
 <?php
 
-class sspmod_core_Auth_UserPassBaseTest extends \PHPUnit_Framework_TestCase
+class UserPassBaseTest extends \PHPUnit_Framework_TestCase
 {
     public function testAuthenticateECPCallsLoginAndSetsAttributes()
     {
@@ -10,7 +10,7 @@ class sspmod_core_Auth_UserPassBaseTest extends \PHPUnit_Framework_TestCase
         $username = $state['core:auth:username'] = 'username';
         $password = $state['core:auth:password'] = 'password';
 
-        $stub = $this->getMockBuilder('sspmod_core_Auth_UserPassBase')
+        $stub = $this->getMockBuilder('\SimpleSAML\Module\core\Auth\UserPassBase')
             ->disableOriginalConstructor()
             ->setMethods(array('login'))
             ->getMockForAbstractClass();
@@ -35,7 +35,7 @@ class sspmod_core_Auth_UserPassBaseTest extends \PHPUnit_Framework_TestCase
         $state['core:auth:username'] = 'username';
         $password = $state['core:auth:password'] = 'password';
 
-        $stub = $this->getMockBuilder('sspmod_core_Auth_UserPassBase')
+        $stub = $this->getMockBuilder('\SimpleSAML\Module\core\Auth\UserPassBase')
             ->disableOriginalConstructor()
             ->setMethods(array('login'))
             ->getMockForAbstractClass();
diff --git a/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php b/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php
index 0b8c19d52..49b17fd61 100644
--- a/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php
+++ b/tests/modules/core/lib/Storage/SQLPermanentStorageTest.php
@@ -15,7 +15,7 @@ class Test_Core_Storage_SQLPermanentStorage extends TestCase
         $config = \SimpleSAML\Configuration::loadFromArray([
             'datadir' => sys_get_temp_dir(),
         ]);
-        self::$sql = new sspmod_core_Storage_SQLPermanentStorage('test', $config);
+        self::$sql = new \SimpleSAML\Module\core\Storage\SQLPermanentStorage('test', $config);
     }
 
     public static function tearDownAfterClass()
diff --git a/tests/modules/ldap/lib/Auth/Process/BaseFilterTest.php b/tests/modules/ldap/lib/Auth/Process/BaseFilterTest.php
index 08dd8ea52..11f6efed6 100644
--- a/tests/modules/ldap/lib/Auth/Process/BaseFilterTest.php
+++ b/tests/modules/ldap/lib/Auth/Process/BaseFilterTest.php
@@ -2,11 +2,11 @@
 
 use PHPUnit\Framework\TestCase;
 
-class sspmod_ldap_Auth_Process_BaseFilter_Test extends TestCase
+class BaseFilter_Test extends TestCase
 {
     public function testVarExportHidesLdapPassword()
     {
-        $stub = $this->getMockBuilder('sspmod_ldap_Auth_Process_BaseFilter')
+        $stub = $this->getMockBuilder('\SimpleSAML\Module\ldap\Auth\Process\BaseFilter')
             ->disableOriginalConstructor()
             ->getMockForAbstractClass();
         $class = new \ReflectionClass($stub);
diff --git a/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php b/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php
index 56f02d540..84799db9e 100644
--- a/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php
+++ b/tests/modules/saml/lib/Auth/Process/NameIDAttributeTest.php
@@ -20,7 +20,7 @@ class NameIDAttributeTest extends TestCase
      */
     private function processFilter(array $config, array $request)
     {
-        $filter = new sspmod_saml_Auth_Process_NameIDAttribute($config, null);
+        $filter = new \SimpleSAML\Module\saml\Auth\Process\NameIDAttribute($config, null);
         $filter->process($request);
         return $request;
     }
diff --git a/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php b/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php
index d18974b23..502babca7 100644
--- a/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php
+++ b/tests/modules/saml/lib/Auth/Source/Auth_Source_SP_Test.php
@@ -28,11 +28,11 @@ class ExitTestException extends \Exception
 
 
 /**
- * Wrap the SSP sspmod_saml_Auth_Source_SP class
+ * Wrap the SSP \SimpleSAML\Module\saml\Auth\Source\SP class
  * - Use introspection to make startSSO2Test available
  * - Override sendSAML2AuthnRequest() to catch the AuthnRequest being sent
  */
-class SP_Tester extends \sspmod_saml_Auth_Source_SP
+class SP_Tester extends \SimpleSAML\Module\saml\Auth\Source\SP
 {
 
     public function __construct($info, $config)
@@ -66,7 +66,7 @@ class SP_Tester extends \sspmod_saml_Auth_Source_SP
 
 
 /**
- * Set of test cases for sspmod_saml_Auth_Source_SP.
+ * Set of test cases for \SimpleSAML\Module\saml\Auth\Source\SP.
  */
 class SP_Test extends TestCase
 {
@@ -130,7 +130,7 @@ class SP_Test extends TestCase
 
 
     /**
-     * Create a SAML AuthnRequest using sspmod_saml_Auth_Source_SP
+     * Create a SAML AuthnRequest using \SimpleSAML\Module\saml\Auth\Source\SP
      *
      * @param array $state The state array to use in the test. This is an array of the parameters described in section
      * 2 of https://simplesamlphp.org/docs/development/saml:sp
diff --git a/tests/modules/saml/lib/IdP/SAML2Test.php b/tests/modules/saml/lib/IdP/SAML2Test.php
index e587f59e0..76efcedb2 100644
--- a/tests/modules/saml/lib/IdP/SAML2Test.php
+++ b/tests/modules/saml/lib/IdP/SAML2Test.php
@@ -1,6 +1,6 @@
 <?php
 
-class sspmod_saml_IdP_SAML2Test extends \PHPUnit_Framework_TestCase
+class SAML2Test extends \PHPUnit_Framework_TestCase
 {
     public function testProcessSOAPAuthnRequest()
     {
@@ -8,7 +8,7 @@ class sspmod_saml_IdP_SAML2Test extends \PHPUnit_Framework_TestCase
         $password = $_SERVER['PHP_AUTH_PW'] = 'password';
         $state = array();
 
-        sspmod_saml_IdP_SAML2::processSOAPAuthnRequest($state);
+        \SimpleSAML\Module\saml\IdP\SAML2::processSOAPAuthnRequest($state);
 
         $this->assertEquals($username, $state['core:auth:username']);
         $this->assertEquals($password, $state['core:auth:password']);
@@ -22,7 +22,7 @@ class sspmod_saml_IdP_SAML2Test extends \PHPUnit_Framework_TestCase
         unset($_SERVER['PHP_AUTH_USER']);
         $state = array();
 
-        sspmod_saml_IdP_SAML2::processSOAPAuthnRequest($state);
+        \SimpleSAML\Module\saml\IdP\SAML2::processSOAPAuthnRequest($state);
     }
 
     public function testProcessSOAPAuthnRequestMissingPassword()
@@ -33,6 +33,6 @@ class sspmod_saml_IdP_SAML2Test extends \PHPUnit_Framework_TestCase
         unset($_SERVER['PHP_AUTH_PW']);
         $state = array();
 
-        sspmod_saml_IdP_SAML2::processSOAPAuthnRequest($state);
+        \SimpleSAML\Module\saml\IdP\SAML2::processSOAPAuthnRequest($state);
     }
 }
diff --git a/www/saml2/idp/ArtifactResolutionService.php b/www/saml2/idp/ArtifactResolutionService.php
index 59e3a0f77..26a4b48ff 100644
--- a/www/saml2/idp/ArtifactResolutionService.php
+++ b/www/saml2/idp/ArtifactResolutionService.php
@@ -64,5 +64,5 @@ $artifactResponse = new \SAML2\ArtifactResponse();
 $artifactResponse->setIssuer($idpEntityId);
 $artifactResponse->setInResponseTo($request->getId());
 $artifactResponse->setAny($responseXML);
-sspmod_saml_Message::addSign($idpMetadata, $spMetadata, $artifactResponse);
+\SimpleSAML\Module\saml\Message::addSign($idpMetadata, $spMetadata, $artifactResponse);
 $binding->send($artifactResponse);
diff --git a/www/saml2/idp/SSOService.php b/www/saml2/idp/SSOService.php
index 4b4090fc3..5a400b854 100644
--- a/www/saml2/idp/SSOService.php
+++ b/www/saml2/idp/SSOService.php
@@ -18,7 +18,7 @@ $idpEntityId = $metadata->getMetaDataCurrentEntityID('saml20-idp-hosted');
 $idp = \SimpleSAML\IdP::getById('saml2:' . $idpEntityId);
 
 try {
-    \sspmod_saml_IdP_SAML2::receiveAuthnRequest($idp);
+    \SimpleSAML\Module\saml\IdP\SAML2::receiveAuthnRequest($idp);
 } catch (\Exception $e) {
     if ($e->getMessage() === "Unable to find the current binding.") {
         throw new \SimpleSAML\Error\Error('SSOPARAMS', $e, 400);
diff --git a/www/saml2/idp/SingleLogoutService.php b/www/saml2/idp/SingleLogoutService.php
index 0cf9b37ba..402e8d5e2 100644
--- a/www/saml2/idp/SingleLogoutService.php
+++ b/www/saml2/idp/SingleLogoutService.php
@@ -20,7 +20,7 @@ if (isset($_REQUEST['ReturnTo'])) {
     $idp->doLogoutRedirect(\SimpleSAML\Utils\HTTP::checkURLAllowed((string) $_REQUEST['ReturnTo']));
 } else {
     try {
-        sspmod_saml_IdP_SAML2::receiveLogoutMessage($idp);
+        \SimpleSAML\Module\saml\IdP\SAML2::receiveLogoutMessage($idp);
     } catch (\Exception $e) { // TODO: look for a specific exception
         /*
          * This is dirty. Instead of checking the message of the exception, \SAML2\Binding::getCurrentBinding() should
diff --git a/www/shib13/idp/SSOService.php b/www/shib13/idp/SSOService.php
index d5b7f075d..2237091b8 100644
--- a/www/shib13/idp/SSOService.php
+++ b/www/shib13/idp/SSOService.php
@@ -16,6 +16,6 @@ require_once '../../_include.php';
 $metadata = \SimpleSAML\Metadata\MetaDataStorageHandler::getMetadataHandler();
 $idpEntityId = $metadata->getMetaDataCurrentEntityID('shib13-idp-hosted');
 $idp = \SimpleSAML\IdP::getById('saml1:' . $idpEntityId);
-\sspmod_saml_IdP_SAML1::receiveAuthnRequest($idp);
+\SimpleSAML\Module\saml\IdP\SAML1::receiveAuthnRequest($idp);
 
 assert(false);
-- 
GitLab