From 9b2c0a7a450fff3b634f8119c8003ae1d20b97d0 Mon Sep 17 00:00:00 2001
From: Fabian Becker <fabian.becker@uni-tuebingen.de>
Date: Thu, 18 Jul 2013 11:33:23 +0200
Subject: [PATCH] Refactor class Piwik_Commin to \Piwik\Core\Common

Notice that auto refactoring has created a nested namespace. Not sure this is what we want - so we might have to edit those nested namespaces afterwards (I think they don't look so good)
---
 core/API/DataTableGenericFilter.php           |    1 +
 core/API/DataTableManipulator/LabelFilter.php |    1 +
 core/API/DocumentationGenerator.php           |    1 +
 core/API/Proxy.php                            |    1 +
 core/API/Request.php                          |    1 +
 core/API/ResponseBuilder.php                  |    1 +
 core/Access.php                               |    1 +
 core/ArchiveProcessor/Rules.php               |    1 +
 core/AssetManager.php                         |    1 +
 core/CacheFile.php                            |    1 +
 core/Common.php                               | 2949 +++++++++--------
 core/Controller.php                           |    1 +
 core/Cookie.php                               |    1 +
 core/DataAccess/ArchiveSelector.php           |    1 +
 core/DataAccess/ArchiveTableCreator.php       |    1 +
 core/DataAccess/ArchiveWriter.php             |    1 +
 core/DataAccess/LogAggregator.php             |    1 +
 core/DataTable/Renderer/Csv.php               |    1 +
 core/DataTable/Renderer/Json.php              |    1 +
 core/DataTable/Renderer/Rss.php               |    1 +
 core/Db/Schema/Myisam.php                     |    1 +
 core/FrontController.php                      |    1 +
 core/Http.php                                 |    1 +
 core/IP.php                                   |    1 +
 core/Log.php                                  |    3 +-
 core/Log/Exception.php                        |    1 +
 core/Log/Message.php                          |    1 +
 core/Menu/Abstract.php                        |    1 +
 core/Nonce.php                                |    1 +
 core/Option.php                               |    1 +
 core/Period/Range.php                         |    1 +
 core/Piwik.php                                |    2 +-
 core/Plugin.php                               |    1 +
 core/Plugin/MetadataLoader.php                |    1 +
 core/PluginsArchiver.php                      |    1 +
 core/PluginsManager.php                       |    1 +
 core/ProxyHeaders.php                         |    1 +
 core/ReportRenderer/Pdf.php                   |    1 +
 core/Segment.php                              |    1 +
 core/Session.php                              |    1 +
 core/Session/Namespace.php                    |    1 +
 core/Tracker.php                              |    1 +
 core/Tracker/Action.php                       |    1 +
 core/Tracker/Db.php                           |    1 +
 core/Tracker/GoalManager.php                  |    1 +
 core/Tracker/Referer.php                      |    1 +
 core/Tracker/Request.php                      |    1 +
 core/Tracker/Visit.php                        |    1 +
 core/Tracker/VisitExcluded.php                |    1 +
 core/Translate.php                            |    1 +
 core/TranslationWriter.php                    |    1 +
 core/Twig.php                                 |    1 +
 core/UpdateCheck.php                          |    1 +
 core/Updater.php                              |    1 +
 core/Updates/0.2.10.php                       |    1 +
 core/Updates/0.2.12.php                       |    1 +
 core/Updates/0.2.13.php                       |    1 +
 core/Updates/0.2.24.php                       |    1 +
 core/Updates/0.2.27.php                       |    1 +
 core/Updates/0.2.32.php                       |    1 +
 core/Updates/0.2.33.php                       |    1 +
 core/Updates/0.2.35.php                       |    1 +
 core/Updates/0.2.37.php                       |    1 +
 core/Updates/0.4.1.php                        |    1 +
 core/Updates/0.4.2.php                        |    1 +
 core/Updates/0.4.php                          |    1 +
 core/Updates/0.5.4.php                        |    1 +
 core/Updates/0.5.5.php                        |    1 +
 core/Updates/0.5.php                          |    1 +
 core/Updates/0.6-rc1.php                      |    1 +
 core/Updates/0.6.3.php                        |    1 +
 core/Updates/0.7.php                          |    1 +
 core/Updates/0.9.1.php                        |    1 +
 core/Updates/1.10.2-b1.php                    |    1 +
 core/Updates/1.10.2-b2.php                    |    1 +
 core/Updates/1.12-b1.php                      |    1 +
 core/Updates/1.12-b16.php                     |    1 +
 core/Updates/1.2-rc1.php                      |    1 +
 core/Updates/1.2.3.php                        |    1 +
 core/Updates/1.2.5-rc1.php                    |    1 +
 core/Updates/1.2.5-rc7.php                    |    1 +
 core/Updates/1.4-rc1.php                      |    1 +
 core/Updates/1.4-rc2.php                      |    1 +
 core/Updates/1.5-b1.php                       |    1 +
 core/Updates/1.5-b2.php                       |    1 +
 core/Updates/1.5-b3.php                       |    1 +
 core/Updates/1.5-b4.php                       |    1 +
 core/Updates/1.5-b5.php                       |    1 +
 core/Updates/1.6-b1.php                       |    1 +
 core/Updates/1.7-b1.php                       |    1 +
 core/Updates/1.7.2-rc5.php                    |    1 +
 core/Updates/1.7.2-rc7.php                    |    1 +
 core/Updates/1.8.3-b1.php                     |    1 +
 core/Updates/1.8.4-b1.php                     |    1 +
 core/Updates/1.9-b16.php                      |    1 +
 core/Updates/1.9-b19.php                      |    1 +
 core/Updates/1.9-b9.php                       |    1 +
 core/Updates/1.9.1-b2.php                     |    1 +
 core/Updates/1.9.3-b8.php                     |    1 +
 core/Url.php                                  |    1 +
 core/View.php                                 |    1 +
 core/ViewDataTable.php                        |    1 +
 core/ViewDataTable/GenerateGraphData.php      |    1 +
 .../GenerateGraphData/ChartEvolution.php      |    1 +
 core/ViewDataTable/GenerateGraphHTML.php      |    1 +
 .../GenerateGraphHTML/ChartEvolution.php      |    1 +
 core/ViewDataTable/HtmlTable.php              |    1 +
 core/ViewDataTable/HtmlTable/Goals.php        |    1 +
 core/ViewDataTable/Sparkline.php              |    1 +
 core/Visualization/Chart.php                  |    1 +
 core/Visualization/Cloud.php                  |    1 +
 libs/upgradephp/upgrade.php                   |    1 +
 misc/cron/archive.php                         |    1 +
 misc/others/geoipUpdateRows.php               |    1 +
 misc/others/iframeWidget_localhost.php        |    2 +
 ...kies_GenerateHundredsWebsitesAndVisits.php |    1 +
 .../test_generateLotsVisitsWebsites.php       |    1 +
 plugins/API/API.php                           |    5 +-
 plugins/API/Controller.php                    |    1 +
 plugins/API/ProcessedReport.php               |    1 +
 plugins/API/RowEvolution.php                  |    1 +
 plugins/Actions/API.php                       |    1 +
 plugins/Actions/Actions.php                   |    1 +
 plugins/Annotations/Controller.php            |    1 +
 plugins/AnonymizeIP/AnonymizeIP.php           |    1 +
 plugins/CoreAdminHome/API.php                 |    1 +
 plugins/CoreAdminHome/Controller.php          |    1 +
 plugins/CoreHome/Controller.php               |    1 +
 .../DataTableRowAction/MultiRowEvolution.php  |    1 +
 .../DataTableRowAction/RowEvolution.php       |    1 +
 plugins/CorePluginsAdmin/Controller.php       |    1 +
 plugins/CoreUpdater/Controller.php            |    1 +
 plugins/CoreUpdater/CoreUpdater.php           |    1 +
 plugins/CustomVariables/Archiver.php          |    2 +-
 plugins/DBStats/API.php                       |    1 +
 plugins/DBStats/MySQLMetadataProvider.php     |    1 +
 plugins/Dashboard/Controller.php              |    1 +
 plugins/Dashboard/Dashboard.php               |    1 +
 plugins/DevicesDetection/Controller.php       |    1 +
 plugins/DevicesDetection/DevicesDetection.php |    1 +
 plugins/ExamplePlugin/Controller.php          |    1 +
 plugins/ExampleUI/Controller.php              |    1 +
 plugins/Feedback/Controller.php               |    1 +
 plugins/Goals/API.php                         |    1 +
 plugins/Goals/Controller.php                  |    1 +
 plugins/Goals/Goals.php                       |    1 +
 plugins/ImageGraph/API.php                    |    1 +
 plugins/ImageGraph/Controller.php             |    1 +
 plugins/ImageGraph/ImageGraph.php             |    2 +-
 plugins/Installation/Controller.php           |    1 +
 plugins/Installation/FormDatabaseSetup.php    |    1 +
 plugins/Installation/Installation.php         |    1 +
 plugins/LanguagesManager/API.php              |    1 +
 plugins/LanguagesManager/Controller.php       |    1 +
 plugins/LanguagesManager/LanguagesManager.php |    1 +
 plugins/Live/API.php                          |    1 +
 plugins/Live/Controller.php                   |    1 +
 plugins/Live/Visitor.php                      |    1 +
 plugins/Login/Auth.php                        |    1 +
 plugins/Login/Controller.php                  |    1 +
 plugins/MobileMessaging/API.php               |    1 +
 plugins/MobileMessaging/Controller.php        |    1 +
 .../MobileMessaging/ReportRenderer/Sms.php    |    1 +
 plugins/MultiSites/API.php                    |    1 +
 plugins/MultiSites/Controller.php             |    1 +
 plugins/Overlay/Controller.php                |    1 +
 plugins/PDFReports/API.php                    |    1 +
 plugins/PDFReports/Controller.php             |    1 +
 plugins/PDFReports/PDFReports.php             |    1 +
 plugins/PrivacyManager/Controller.php         |    1 +
 plugins/PrivacyManager/LogDataPurger.php      |    1 +
 plugins/PrivacyManager/PrivacyManager.php     |    1 +
 plugins/Provider/Provider.php                 |    1 +
 plugins/Provider/functions.php                |    1 +
 plugins/Proxy/Controller.php                  |    1 +
 plugins/Referers/API.php                      |    1 +
 plugins/Referers/Archiver.php                 |    2 +-
 plugins/Referers/Controller.php               |    1 +
 plugins/Referers/functions.php                |    1 +
 plugins/SEO/Controller.php                    |    1 +
 plugins/SEO/MajesticClient.php                |    1 +
 plugins/SegmentEditor/API.php                 |    1 +
 plugins/SegmentEditor/Controller.php          |    1 +
 plugins/SegmentEditor/SegmentEditor.php       |    1 +
 plugins/SitesManager/API.php                  |    1 +
 plugins/SitesManager/Controller.php           |    1 +
 plugins/Transitions/API.php                   |    1 +
 plugins/UserCountry/Controller.php            |    1 +
 plugins/UserCountry/GeoIPAutoUpdater.php      |    1 +
 plugins/UserCountry/LocationProvider.php      |    1 +
 .../UserCountry/LocationProvider/Default.php  |    1 +
 plugins/UserCountry/UserCountry.php           |    1 +
 plugins/UserCountryMap/Controller.php         |    1 +
 plugins/UserSettings/Archiver.php             |    2 +
 plugins/UsersManager/API.php                  |    1 +
 plugins/UsersManager/Controller.php           |    1 +
 plugins/VisitFrequency/Controller.php         |    1 +
 plugins/VisitTime/VisitTime.php               |    1 +
 plugins/VisitorGenerator/Controller.php       |    1 +
 plugins/VisitsSummary/Controller.php          |    1 +
 plugins/Widgetize/Controller.php              |    1 +
 tests/PHPUnit/BaseFixture.php                 |    1 +
 tests/PHPUnit/BenchmarkTestCase.php           |    1 +
 tests/PHPUnit/Benchmarks/Fixtures/SqlDump.php |    1 +
 tests/PHPUnit/Core/ArchiveProcessingTest.php  |    1 +
 tests/PHPUnit/Core/CommonTest.php             |    2 +
 tests/PHPUnit/Core/IPTest.php                 |    1 +
 tests/PHPUnit/Core/OptionTest.php             |    2 +
 tests/PHPUnit/Core/ReleaseCheckListTest.php   |    1 +
 tests/PHPUnit/Core/SegmentTest.php            |    2 +
 tests/PHPUnit/Core/ServeStaticFileTest.php    |    1 +
 tests/PHPUnit/Core/TranslationWriterTest.php  |    2 +
 .../ManySitesImportedLogsWithXssAttempts.php  |    2 +
 ...everalDaysDateRange_ArchivingTestsTest.php |    1 +
 ...mVariables_SegmentMatchVisitorTypeTest.php |    1 +
 .../Integration/UrlNormalizationTest.php      |    2 +
 tests/PHPUnit/IntegrationTestCase.php         |    1 +
 .../PHPUnit/Plugins/LanguagesManagerTest.php  |    2 +
 tests/PHPUnit/Plugins/PrivacyManagerTest.php  |    1 +
 tests/resources/staticFileServer.php          |    1 +
 220 files changed, 1711 insertions(+), 1476 deletions(-)

diff --git a/core/API/DataTableGenericFilter.php b/core/API/DataTableGenericFilter.php
index 02e2b31a24..39dbba045c 100644
--- a/core/API/DataTableGenericFilter.php
+++ b/core/API/DataTableGenericFilter.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/API/DataTableManipulator/LabelFilter.php b/core/API/DataTableManipulator/LabelFilter.php
index 6830511895..1d6ca323d9 100644
--- a/core/API/DataTableManipulator/LabelFilter.php
+++ b/core/API/DataTableManipulator/LabelFilter.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class is responsible for handling the label parameter that can be
diff --git a/core/API/DocumentationGenerator.php b/core/API/DocumentationGenerator.php
index f4a8cd387f..e36023af01 100644
--- a/core/API/DocumentationGenerator.php
+++ b/core/API/DocumentationGenerator.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/API/Proxy.php b/core/API/Proxy.php
index 8bb16832ac..16a0f6dd32 100644
--- a/core/API/Proxy.php
+++ b/core/API/Proxy.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * To differentiate between "no value" and default value of null
diff --git a/core/API/Request.php b/core/API/Request.php
index 56d12ecba7..19bf6634ca 100644
--- a/core/API/Request.php
+++ b/core/API/Request.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * An API request is the object used to make a call to the API and get the result.
diff --git a/core/API/ResponseBuilder.php b/core/API/ResponseBuilder.php
index bdac6a6488..d4082226d1 100644
--- a/core/API/ResponseBuilder.php
+++ b/core/API/ResponseBuilder.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/Access.php b/core/Access.php
index cab3a766e9..52ef921eba 100644
--- a/core/Access.php
+++ b/core/Access.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class to handle User Access:
diff --git a/core/ArchiveProcessor/Rules.php b/core/ArchiveProcessor/Rules.php
index 0d27b89059..e1a1b2004b 100644
--- a/core/ArchiveProcessor/Rules.php
+++ b/core/ArchiveProcessor/Rules.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class contains Archiving rules/logic which are used in several places
diff --git a/core/AssetManager.php b/core/AssetManager.php
index 87dee1a8d2..6a62cb176f 100644
--- a/core/AssetManager.php
+++ b/core/AssetManager.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see libs/jsmin/jsmin.php
diff --git a/core/CacheFile.php b/core/CacheFile.php
index faa2b59405..a7697084cd 100644
--- a/core/CacheFile.php
+++ b/core/CacheFile.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Code originally inspired from OpenX
diff --git a/core/Common.php b/core/Common.php
index d9c9371c69..36c3c97db4 100644
--- a/core/Common.php
+++ b/core/Common.php
@@ -1,1597 +1,1608 @@
 <?php
-/**
- * Piwik - Open source web analytics
- *
- * @link http://piwik.org
- * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
- *
- * @category Piwik
- * @package Piwik
- */
-use Piwik\Core\Config;
-
-/**
- * Static class providing functions used by both the CORE of Piwik and the visitor Tracking engine.
- *
- * This is the only external class loaded by the /piwik.php file.
- * This class should contain only the functions that are used in
- * both the CORE and the piwik.php statistics logging engine.
- *
- * @package Piwik
- */
-class Piwik_Common
-{
-    const CLASSES_PREFIX = 'Piwik_';
-    
-    /**
-     * Const used to map the referer type to an integer in the log_visit table
-     */
-    const REFERER_TYPE_DIRECT_ENTRY = 1;
-    const REFERER_TYPE_SEARCH_ENGINE = 2;
-    const REFERER_TYPE_WEBSITE = 3;
-    const REFERER_TYPE_CAMPAIGN = 6;
-
-    /**
-     * Flag used with htmlspecialchar
-     * See php.net/htmlspecialchars
-     */
-    const HTML_ENCODING_QUOTE_STYLE = ENT_QUOTES;
-
-    /*
-     * Database
-     */
-
-    /**
-     * Hashes a string into an integer which should be very low collision risks
-     * @param string $string  String to hash
-     * @return int  Resulting int hash
-     */
-    public static function hashStringToInt($string)
-    {
-        $stringHash = substr(md5($string), 0, 8);
-        return base_convert($stringHash, 16, 10);
-    }
-
-    public static $cachedTablePrefix = null;
+namespace Piwik\Core {
+    use Exception;
+    use Piwik_IP;
+    use Piwik_PluginsManager;
+    use Piwik_Tracker;
+    use Piwik_Tracker_Cache;
+    use Piwik_UserCountry_LocationProvider_Default;
 
     /**
-     * Returns the table name prefixed by the table prefix.
-     * Works in both Tracker and UI mode.
+     * Static class providing functions used by both the CORE of Piwik and the visitor Tracking engine.
      *
-     * @param string $table  The table name to prefix, ie "log_visit"
-     * @return string  The table name prefixed, ie "piwik-production_log_visit"
-     */
-    public static function prefixTable($table)
-    {
-        $prefix = Config::getInstance()->database['tables_prefix'];
-        return $prefix . $table;
-    }
-
-    /**
-     * Returns an array containing the prefixed table names of every passed argument.
-     *
-     * @param string ... The table names to prefix, ie "log_visit"
-     * @return array The prefixed names in an array.
-     */
-    public static function prefixTables()
-    {
-        $result = array();
-        foreach (func_get_args() as $table) {
-            $result[] = self::prefixTable($table);
-        }
-        return $result;
-    }
-
-    /**
-     * Returns the table name, after removing the table prefix
+     * This is the only external class loaded by the /piwik.php file.
+     * This class should contain only the functions that are used in
+     * both the CORE and the piwik.php statistics logging engine.
      *
-     * @param string $table
-     * @return string
+     * @package Piwik
      */
-    public static function unprefixTable($table)
+    class Piwik_Common
     {
-        static $prefixTable = null;
-        if (is_null($prefixTable)) {
-            $prefixTable = Config::getInstance()->database['tables_prefix'];
-        }
-        if (empty($prefixTable)
-            || strpos($table, $prefixTable) !== 0
-        ) {
-            return $table;
-        }
-        $count = 1;
-        return str_replace($prefixTable, '', $table, $count);
-    }
-
-    /*
-     * Tracker
-     */
-    public static function isGoalPluginEnabled()
-    {
-        return Piwik_PluginsManager::getInstance()->isPluginActivated('Goals');
-    }
-
-    /*
-     * URLs
-     */
-
-    /**
-     * Returns the path and query part from a URL.
-     * Eg. http://piwik.org/test/index.php?module=CoreHome will return /test/index.php?module=CoreHome
-     *
-     * @param string $url  either http://piwik.org/test or /
-     * @return string
-     */
-    public static function getPathAndQueryFromUrl($url)
-    {
-        $parsedUrl = parse_url($url);
-        $result = '';
-        if (isset($parsedUrl['path'])) {
-            $result .= substr($parsedUrl['path'], 1);
-        }
-        if (isset($parsedUrl['query'])) {
-            $result .= '?' . $parsedUrl['query'];
-        }
-        return $result;
-    }
-
-    /**
-     * Returns the value of a GET parameter $parameter in an URL query $urlQuery
-     *
-     * @param string $urlQuery  result of parse_url()['query'] and htmlentitied (& is &amp;) eg. module=test&amp;action=toto or ?page=test
-     * @param string $parameter
-     * @return string|bool  Parameter value if found (can be the empty string!), null if not found
-     */
-    public static function getParameterFromQueryString($urlQuery, $parameter)
-    {
-        $nameToValue = self::getArrayFromQueryString($urlQuery);
-        if (isset($nameToValue[$parameter])) {
-            return $nameToValue[$parameter];
-        }
-        return null;
-    }
-
-    /**
-     * Returns an URL query string in an array format
-     *
-     * @param string $urlQuery
-     * @return array  array( param1=> value1, param2=>value2)
-     */
-    public static function getArrayFromQueryString($urlQuery)
-    {
-        if (strlen($urlQuery) == 0) {
-            return array();
-        }
-        if ($urlQuery[0] == '?') {
-            $urlQuery = substr($urlQuery, 1);
+        const CLASSES_PREFIX = 'Piwik_';
+
+        /**
+         * Const used to map the referer type to an integer in the log_visit table
+         */
+        const REFERER_TYPE_DIRECT_ENTRY = 1;
+        const REFERER_TYPE_SEARCH_ENGINE = 2;
+        const REFERER_TYPE_WEBSITE = 3;
+        const REFERER_TYPE_CAMPAIGN = 6;
+
+        /**
+         * Flag used with htmlspecialchar
+         * See php.net/htmlspecialchars
+         */
+        const HTML_ENCODING_QUOTE_STYLE = ENT_QUOTES;
+
+        /*
+         * Database
+         */
+
+        /**
+         * Hashes a string into an integer which should be very low collision risks
+         * @param string $string  String to hash
+         * @return int  Resulting int hash
+         */
+        public static function hashStringToInt($string)
+        {
+            $stringHash = substr(md5($string), 0, 8);
+            return base_convert($stringHash, 16, 10);
+        }
+
+        public static $cachedTablePrefix = null;
+
+        /**
+         * Returns the table name prefixed by the table prefix.
+         * Works in both Tracker and UI mode.
+         *
+         * @param string $table  The table name to prefix, ie "log_visit"
+         * @return string  The table name prefixed, ie "piwik-production_log_visit"
+         */
+        public static function prefixTable($table)
+        {
+            $prefix = Config::getInstance()->database['tables_prefix'];
+            return $prefix . $table;
+        }
+
+        /**
+         * Returns an array containing the prefixed table names of every passed argument.
+         *
+         * @param string ... The table names to prefix, ie "log_visit"
+         * @return array The prefixed names in an array.
+         */
+        public static function prefixTables()
+        {
+            $result = array();
+            foreach (func_get_args() as $table) {
+                $result[] = \Piwik\Core\self::prefixTable($table);
+            }
+            return $result;
         }
-        $separator = '&';
-
-        $urlQuery = $separator . $urlQuery;
-        //		$urlQuery = str_replace(array('%20'), ' ', $urlQuery);
-        $refererQuery = trim($urlQuery);
-
-        $values = explode($separator, $refererQuery);
-
-        $nameToValue = array();
 
-        foreach ($values as $value) {
-            $pos = strpos($value, '=');
-            if ($pos !== false) {
-                $name = substr($value, 0, $pos);
-                $value = substr($value, $pos + 1);
-                if ($value === false) {
-                    $value = '';
-                }
-            } else {
-                $name = $value;
-                $value = false;
+        /**
+         * Returns the table name, after removing the table prefix
+         *
+         * @param string $table
+         * @return string
+         */
+        public static function unprefixTable($table)
+        {
+            static $prefixTable = null;
+            if (is_null($prefixTable)) {
+                $prefixTable = Config::getInstance()->database['tables_prefix'];
             }
-            if (!empty($name)) {
-                $name = Piwik_Common::sanitizeInputValue($name);
+            if (empty($prefixTable)
+                || strpos($table, $prefixTable) !== 0
+            ) {
+                return $table;
             }
-            if (!empty($value)) {
-                $value = Piwik_Common::sanitizeInputValue($value);
+            $count = 1;
+            return str_replace($prefixTable, '', $table, $count);
+        }
+
+        /*
+         * Tracker
+         */
+        public static function isGoalPluginEnabled()
+        {
+            return Piwik_PluginsManager::getInstance()->isPluginActivated('Goals');
+        }
+
+        /*
+         * URLs
+         */
+
+        /**
+         * Returns the path and query part from a URL.
+         * Eg. http://piwik.org/test/index.php?module=CoreHome will return /test/index.php?module=CoreHome
+         *
+         * @param string $url  either http://piwik.org/test or /
+         * @return string
+         */
+        public static function getPathAndQueryFromUrl($url)
+        {
+            $parsedUrl = parse_url($url);
+            $result = '';
+            if (isset($parsedUrl['path'])) {
+                $result .= substr($parsedUrl['path'], 1);
             }
-
-            // if array without indexes
-            $count = 0;
-            $tmp = preg_replace('/(\[|%5b)(]|%5d)$/i', '', $name, -1, $count);
-            if (!empty($tmp) && $count) {
-                $name = $tmp;
-                if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) {
-                    $nameToValue[$name] = array();
-                }
-                array_push($nameToValue[$name], $value);
-            } else if (!empty($name)) {
-                $nameToValue[$name] = $value;
+            if (isset($parsedUrl['query'])) {
+                $result .= '?' . $parsedUrl['query'];
             }
+            return $result;
         }
-        return $nameToValue;
-    }
-
-    /**
-     * Builds a URL from the result of parse_url function
-     * Copied from the PHP comments at http://php.net/parse_url
-     * @param array $parsed
-     * @return bool|string
-     */
-    public static function getParseUrlReverse($parsed)
-    {
-        if (!is_array($parsed)) {
-            return false;
-        }
-
-        $uri = !empty($parsed['scheme']) ? $parsed['scheme'] . ':' . (!strcasecmp($parsed['scheme'], 'mailto') ? '' : '//') : '';
-        $uri .= !empty($parsed['user']) ? $parsed['user'] . (!empty($parsed['pass']) ? ':' . $parsed['pass'] : '') . '@' : '';
-        $uri .= !empty($parsed['host']) ? $parsed['host'] : '';
-        $uri .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';
-
-        if (!empty($parsed['path'])) {
-            $uri .= (!strncmp($parsed['path'], '/', 1))
-                ? $parsed['path']
-                : ((!empty($uri) ? '/' : '') . $parsed['path']);
-        }
-
-        $uri .= !empty($parsed['query']) ? '?' . $parsed['query'] : '';
-        $uri .= !empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
-        return $uri;
-    }
-
-    /**
-     * Returns true if the string passed may be a URL.
-     * We don't need a precise test here because the value comes from the website
-     * tracked source code and the URLs may look very strange.
-     *
-     * @param string $url
-     * @return bool
-     */
-    public static function isLookLikeUrl($url)
-    {
-        return preg_match('~^(ftp|news|http|https)?://(.*)$~D', $url, $matches) !== 0
-            && strlen($matches[2]) > 0;
-    }
-
-    /*
-     * File operations
-     */
-
-    /**
-     * ending WITHOUT slash
-     *
-     * @return string
-     */
-    public static function getPathToPiwikRoot()
-    {
-        return realpath(dirname(__FILE__) . "/..");
-    }
-
-    /**
-     * Create directory if permitted
-     *
-     * @param string $path
-     * @param bool $denyAccess
-     */
-    public static function mkdir($path, $denyAccess = true)
-    {
-        if (!is_dir($path)) {
-            // the mode in mkdir is modified by the current umask
-            @mkdir($path, $mode = 0755, $recursive = true);
-        }
-
-        // try to overcome restrictive umask (mis-)configuration
-        if (!is_writable($path)) {
-            @chmod($path, 0755);
-            if (!is_writable($path)) {
-                @chmod($path, 0775);
 
-                // enough! we're not going to make the directory world-writeable
+        /**
+         * Returns the value of a GET parameter $parameter in an URL query $urlQuery
+         *
+         * @param string $urlQuery  result of parse_url()['query'] and htmlentitied (& is &amp;) eg. module=test&amp;action=toto or ?page=test
+         * @param string $parameter
+         * @return string|bool  Parameter value if found (can be the empty string!), null if not found
+         */
+        public static function getParameterFromQueryString($urlQuery, $parameter)
+        {
+            $nameToValue = \Piwik\Core\self::getArrayFromQueryString($urlQuery);
+            if (isset($nameToValue[$parameter])) {
+                return $nameToValue[$parameter];
             }
-        }
-
-        if ($denyAccess) {
-            self::createHtAccess($path, $overwrite = false);
-        }
-    }
-
-    /**
-     * Create .htaccess file in specified directory
-     *
-     * Apache-specific; for IIS @see web.config
-     *
-     * @param string $path     without trailing slash
-     * @param bool $overwrite whether to overwrite an existing file or not
-     * @param string $content
-     */
-    public static function createHtAccess($path, $overwrite = true, $content = "<Files \"*\">\n<IfModule mod_access.c>\nDeny from all\n</IfModule>\n<IfModule !mod_access_compat>\n<IfModule mod_authz_host.c>\nDeny from all\n</IfModule>\n</IfModule>\n<IfModule mod_access_compat>\nDeny from all\n</IfModule>\n</Files>\n")
-    {
-        if (self::isApache()) {
-            $file = $path . '/.htaccess';
-            if ($overwrite || !file_exists($file)) {
-                @file_put_contents($file, $content);
+            return null;
+        }
+
+        /**
+         * Returns an URL query string in an array format
+         *
+         * @param string $urlQuery
+         * @return array  array( param1=> value1, param2=>value2)
+         */
+        public static function getArrayFromQueryString($urlQuery)
+        {
+            if (strlen($urlQuery) == 0) {
+                return array();
             }
-        }
-    }
-
-    /**
-     * Get canonicalized absolute path
-     * See http://php.net/realpath
-     *
-     * @param string $path
-     * @return string  canonicalized absolute path
-     */
-    public static function realpath($path)
-    {
-        if (file_exists($path)) {
-            return realpath($path);
-        }
-        return $path;
-    }
-
-    /**
-     * Returns true if the string is a valid filename
-     * File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
-     * File names beginning with anything but a-Z or 0-9 will be rejected (including .htaccess for example).
-     * File names containing anything other than above mentioned will also be rejected (file names with spaces won't be accepted).
-     *
-     * @param string $filename
-     * @return bool
-     *
-     */
-    public static function isValidFilename($filename)
-    {
-        return (0 !== preg_match('/(^[a-zA-Z0-9]+([a-zA-Z_0-9.-]*))$/D', $filename));
-    }
-
-    /*
-     * String operations
-     */
-
-    /**
-     * byte-oriented substr() - ASCII
-     *
-     * @param string $string
-     * @param int $start
-     * @param int     ...      optional length
-     * @return string
-     */
-    public static function substr($string, $start)
-    {
-        // in case mbstring overloads substr function
-        $substr = function_exists('mb_orig_substr') ? 'mb_orig_substr' : 'substr';
-
-        $length = func_num_args() > 2
-            ? func_get_arg(2)
-            : self::strlen($string);
-
-        return $substr($string, $start, $length);
-    }
-
-    /**
-     * byte-oriented strlen() - ASCII
-     *
-     * @param string $string
-     * @return int
-     */
-    public static function strlen($string)
-    {
-        // in case mbstring overloads strlen function
-        $strlen = function_exists('mb_orig_strlen') ? 'mb_orig_strlen' : 'strlen';
-        return $strlen($string);
-    }
-
-    /**
-     * multi-byte substr() - UTF-8
-     *
-     * @param string $string
-     * @param int $start
-     * @param int     ...      optional length
-     * @return string
-     */
-    public static function mb_substr($string, $start)
-    {
-        $length = func_num_args() > 2
-            ? func_get_arg(2)
-            : self::mb_strlen($string);
-
-        if (function_exists('mb_substr')) {
-            return mb_substr($string, $start, $length, 'UTF-8');
-        }
-
-        return substr($string, $start, $length);
-    }
-
-    /**
-     * multi-byte strlen() - UTF-8
-     *
-     * @param string $string
-     * @return int
-     */
-    public static function mb_strlen($string)
-    {
-        if (function_exists('mb_strlen')) {
-            return mb_strlen($string, 'UTF-8');
-        }
-
-        return strlen($string);
-    }
+            if ($urlQuery[0] == '?') {
+                $urlQuery = substr($urlQuery, 1);
+            }
+            $separator = '&';
 
-    /**
-     * multi-byte strtolower() - UTF-8
-     *
-     * @param string $string
-     * @return string
-     */
-    public static function mb_strtolower($string)
-    {
-        if (function_exists('mb_strtolower')) {
-            return mb_strtolower($string, 'UTF-8');
-        }
+            $urlQuery = $separator . $urlQuery;
+            //		$urlQuery = str_replace(array('%20'), ' ', $urlQuery);
+            $refererQuery = trim($urlQuery);
 
-        return strtolower($string);
-    }
+            $values = explode($separator, $refererQuery);
 
-    /*
-     * Escaping input
-     */
+            $nameToValue = array();
 
-    /**
-     * Returns the variable after cleaning operations.
-     * NB: The variable still has to be escaped before going into a SQL Query!
-     *
-     * If an array is passed the cleaning is done recursively on all the sub-arrays.
-     * The array's keys are filtered as well!
-     *
-     * How this method works:
-     * - The variable returned has been htmlspecialchars to avoid the XSS security problem.
-     * - The single quotes are not protected so "Piwik's amazing" will still be "Piwik's amazing".
-     *
-     * - Transformations are:
-     *         - '&' (ampersand) becomes '&amp;'
-     *         - '"'(double quote) becomes '&quot;'
-     *         - '<' (less than) becomes '&lt;'
-     *         - '>' (greater than) becomes '&gt;'
-     * - It handles the magic_quotes setting.
-     * - A non string value is returned without modification
-     *
-     * @param mixed $value The variable to be cleaned
-     * @param bool $alreadyStripslashed
-     * @throws Exception
-     * @return mixed  The variable after cleaning
-     */
-    public static function sanitizeInputValues($value, $alreadyStripslashed = false)
-    {
-        if (is_numeric($value)) {
-            return $value;
-        } elseif (is_string($value)) {
-            $value = self::sanitizeInputValue($value);
-
-            if (!$alreadyStripslashed) // a JSON array was already stripslashed, don't do it again for each value
-            {
-                $value = self::undoMagicQuotes($value);
-            }
-        } elseif (is_array($value)) {
-            foreach (array_keys($value) as $key) {
-                $newKey = $key;
-                $newKey = self::sanitizeInputValues($newKey, $alreadyStripslashed);
-                if ($key != $newKey) {
-                    $value[$newKey] = $value[$key];
-                    unset($value[$key]);
+            foreach ($values as $value) {
+                $pos = strpos($value, '=');
+                if ($pos !== false) {
+                    $name = substr($value, 0, $pos);
+                    $value = substr($value, $pos + 1);
+                    if ($value === false) {
+                        $value = '';
+                    }
+                } else {
+                    $name = $value;
+                    $value = false;
+                }
+                if (!empty($name)) {
+                    $name = \Piwik\Core\Piwik_Common::sanitizeInputValue($name);
+                }
+                if (!empty($value)) {
+                    $value = \Piwik\Core\Piwik_Common::sanitizeInputValue($value);
                 }
 
-                $value[$newKey] = self::sanitizeInputValues($value[$newKey], $alreadyStripslashed);
+                // if array without indexes
+                $count = 0;
+                $tmp = preg_replace('/(\[|%5b)(]|%5d)$/i', '', $name, -1, $count);
+                if (!empty($tmp) && $count) {
+                    $name = $tmp;
+                    if (isset($nameToValue[$name]) == false || is_array($nameToValue[$name]) == false) {
+                        $nameToValue[$name] = array();
+                    }
+                    array_push($nameToValue[$name], $value);
+                } else if (!empty($name)) {
+                    $nameToValue[$name] = $value;
+                }
             }
-        } elseif (!is_null($value)
-            && !is_bool($value)
-        ) {
-            throw new Exception("The value to escape has not a supported type. Value = " . var_export($value, true));
-        }
-        return $value;
-    }
-
-    /**
-     * Sanitize a single input value
-     *
-     * @param string $value
-     * @return string  sanitized input
-     */
-    public static function sanitizeInputValue($value)
-    {
-        // $_GET and $_REQUEST already urldecode()'d
-        // decode
-        // note: before php 5.2.7, htmlspecialchars() double encodes &#x hex items
-        $value = html_entity_decode($value, Piwik_Common::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
-
-        // filter
-        $value = str_replace(array("\n", "\r", "\0"), '', $value);
-
-        // escape
-        $tmp = @htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
-
-        // note: php 5.2.5 and above, htmlspecialchars is destructive if input is not UTF-8
-        if ($value != '' && $tmp == '') {
-            // convert and escape
-            $value = utf8_encode($value);
-            $tmp = htmlspecialchars($value, self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
-        }
-        return $tmp;
-    }
-
-    /**
-     * Unsanitize a single input value
-     *
-     * @param string $value
-     * @return string  unsanitized input
-     */
-    public static function unsanitizeInputValue($value)
-    {
-        return htmlspecialchars_decode($value, self::HTML_ENCODING_QUOTE_STYLE);
-    }
-
-    /**
-     * Unsanitize one or more values.
-     *
-     * @param string|array $value
-     * @return string|array  unsanitized input
-     */
-    public static function unsanitizeInputValues($value)
-    {
-        if (is_array($value)) {
-            $result = array();
-            foreach ($value as $key => $arrayValue) {
-                $result[$key] = self::unsanitizeInputValues($arrayValue);
+            return $nameToValue;
+        }
+
+        /**
+         * Builds a URL from the result of parse_url function
+         * Copied from the PHP comments at http://php.net/parse_url
+         * @param array $parsed
+         * @return bool|string
+         */
+        public static function getParseUrlReverse($parsed)
+        {
+            if (!is_array($parsed)) {
+                return false;
             }
-            return $result;
-        } else {
-            return self::unsanitizeInputValue($value);
-        }
-    }
 
-    /**
-     * Undo the damage caused by magic_quotes; deprecated in php 5.3 but not removed until php 5.4
-     *
-     * @param string
-     * @return string  modified or not
-     */
-    public static function undoMagicQuotes($value)
-    {
-        return version_compare(PHP_VERSION, '5.4', '<')
-            && get_magic_quotes_gpc()
-            ? stripslashes($value)
-            : $value;
-    }
+            $uri = !empty($parsed['scheme']) ? $parsed['scheme'] . ':' . (!strcasecmp($parsed['scheme'], 'mailto') ? '' : '//') : '';
+            $uri .= !empty($parsed['user']) ? $parsed['user'] . (!empty($parsed['pass']) ? ':' . $parsed['pass'] : '') . '@' : '';
+            $uri .= !empty($parsed['host']) ? $parsed['host'] : '';
+            $uri .= !empty($parsed['port']) ? ':' . $parsed['port'] : '';
 
-    /**
-     * Returns a sanitized variable value from the $_GET and $_POST superglobal.
-     * If the variable doesn't have a value or an empty value, returns the defaultValue if specified.
-     * If the variable doesn't have neither a value nor a default value provided, an exception is raised.
-     *
-     * @see sanitizeInputValues() for the applied sanitization
-     *
-     * @param string $varName            name of the variable
-     * @param string $varDefault         default value. If '', and if the type doesn't match, exit() !
-     * @param string $varType            Expected type, the value must be one of the following: array, int, integer, string, json
-     * @param array $requestArrayToUse
-     *
-     * @throws Exception  if the variable type is not known
-     *                    or if the variable we want to read doesn't have neither a value nor a default value specified
-     *
-     * @return mixed The variable after cleaning
-     */
-    public static function getRequestVar($varName, $varDefault = null, $varType = null, $requestArrayToUse = null)
-    {
-        if (is_null($requestArrayToUse)) {
-            $requestArrayToUse = $_GET + $_POST;
-        }
-        $varDefault = self::sanitizeInputValues($varDefault);
-        if ($varType === 'int') {
-            // settype accepts only integer
-            // 'int' is simply a shortcut for 'integer'
-            $varType = 'integer';
-        }
-
-        // there is no value $varName in the REQUEST so we try to use the default value
-        if (empty($varName)
-            || !isset($requestArrayToUse[$varName])
-            || (!is_array($requestArrayToUse[$varName])
-                && strlen($requestArrayToUse[$varName]) === 0
-            )
-        ) {
-            if (is_null($varDefault)) {
-                throw new Exception("The parameter '$varName' isn't set in the Request, and a default value wasn't provided.");
-            } else {
-                if (!is_null($varType)
-                    && in_array($varType, array('string', 'integer', 'array'))
-                ) {
-                    settype($varDefault, $varType);
-                }
-                return $varDefault;
+            if (!empty($parsed['path'])) {
+                $uri .= (!strncmp($parsed['path'], '/', 1))
+                    ? $parsed['path']
+                    : ((!empty($uri) ? '/' : '') . $parsed['path']);
             }
-        }
 
-        // Normal case, there is a value available in REQUEST for the requested varName:
-
-        // we deal w/ json differently
-        if ($varType == 'json') {
-            $value = self::undoMagicQuotes($requestArrayToUse[$varName]);
-            $value = Piwik_Common::json_decode($value, $assoc = true);
-            return self::sanitizeInputValues($value, $alreadyStripslashed = true);
+            $uri .= !empty($parsed['query']) ? '?' . $parsed['query'] : '';
+            $uri .= !empty($parsed['fragment']) ? '#' . $parsed['fragment'] : '';
+            return $uri;
+        }
+
+        /**
+         * Returns true if the string passed may be a URL.
+         * We don't need a precise test here because the value comes from the website
+         * tracked source code and the URLs may look very strange.
+         *
+         * @param string $url
+         * @return bool
+         */
+        public static function isLookLikeUrl($url)
+        {
+            return preg_match('~^(ftp|news|http|https)?://(.*)$~D', $url, $matches) !== 0
+            && strlen($matches[2]) > 0;
         }
 
-        $value = self::sanitizeInputValues($requestArrayToUse[$varName]);
-        if (!is_null($varType)) {
-            $ok = false;
-
-            if ($varType === 'string') {
-                if (is_string($value)) $ok = true;
-            } elseif ($varType === 'integer') {
-                if ($value == (string)(int)$value) $ok = true;
-            } elseif ($varType === 'float') {
-                if ($value == (string)(float)$value) $ok = true;
-            } elseif ($varType === 'array') {
-                if (is_array($value)) $ok = true;
-            } else {
-                throw new Exception("\$varType specified is not known. It should be one of the following: array, int, integer, float, string");
-            }
-
-            // The type is not correct
-            if ($ok === false) {
-                if ($varDefault === null) {
-                    throw new Exception("The parameter '$varName' doesn't have a correct type, and a default value wasn't provided.");
-                } // we return the default value with the good type set
-                else {
-                    settype($varDefault, $varType);
-                    return $varDefault;
-                }
+        /*
+         * File operations
+         */
+
+        /**
+         * ending WITHOUT slash
+         *
+         * @return string
+         */
+        public static function getPathToPiwikRoot()
+        {
+            return realpath(dirname(__FILE__) . "/..");
+        }
+
+        /**
+         * Create directory if permitted
+         *
+         * @param string $path
+         * @param bool $denyAccess
+         */
+        public static function mkdir($path, $denyAccess = true)
+        {
+            if (!is_dir($path)) {
+                // the mode in mkdir is modified by the current umask
+                @mkdir($path, $mode = 0755, $recursive = true);
             }
-            settype($value, $varType);
-        }
-        return $value;
-    }
-
-    /*
-     * Generating unique strings
-     */
 
-    /**
-     * Returns a 32 characters long uniq ID
-     *
-     * @return string 32 chars
-     */
-    public static function generateUniqId()
-    {
-        return md5(uniqid(rand(), true));
-    }
-
-    /**
-     * Get salt from [superuser] section
-     *
-     * @return string
-     */
-    public static function getSalt()
-    {
-        static $salt = null;
-        if (is_null($salt)) {
-            $salt = @Config::getInstance()->superuser['salt'];
-        }
-        return $salt;
-    }
-
-    /**
-     * Configureable hash() algorithm (defaults to md5)
-     *
-     * @param string $str String to be hashed
-     * @param bool $raw_output
-     * @return string Hash string
-     */
-    public static function hash($str, $raw_output = false)
-    {
-        static $hashAlgorithm = null;
-        if (is_null($hashAlgorithm)) {
-            $hashAlgorithm = @Config::getInstance()->General['hash_algorithm'];
-        }
-
-        if ($hashAlgorithm) {
-            $hash = @hash($hashAlgorithm, $str, $raw_output);
-            if ($hash !== false)
-                return $hash;
-        }
-
-        return md5($str, $raw_output);
-    }
-
-    /**
-     * Generate random string
-     *
-     * @param int $length string length
-     * @param string $alphabet characters allowed in random string
-     * @return string  random string with given length
-     */
-    public static function getRandomString($length = 16, $alphabet = "abcdefghijklmnoprstuvwxyz0123456789")
-    {
-        $chars = $alphabet;
-        $str = '';
-
-        list($usec, $sec) = explode(" ", microtime());
-        $seed = ((float)$sec + (float)$usec) * 100000;
-        mt_srand($seed);
-
-        for ($i = 0; $i < $length; $i++) {
-            $rand_key = mt_rand(0, strlen($chars) - 1);
-            $str .= substr($chars, $rand_key, 1);
-        }
-        return str_shuffle($str);
-    }
-
-    /*
-     * Conversions
-     */
-
-    /**
-     * Convert hexadecimal representation into binary data.
-     * !! Will emit warning if input string is not hex!!
-     *
-     * @see http://php.net/bin2hex
-     *
-     * @param string $str  Hexadecimal representation
-     * @return string
-     */
-    public static function hex2bin($str)
-    {
-        return pack("H*", $str);
-    }
-
-    /**
-     * This function will convert the input string to the binary representation of the ID
-     * but it will throw an Exception if the specified input ID is not correct
-     *
-     * This is used when building segments containing visitorId which could be an invalid string
-     * therefore throwing Unexpected PHP error [pack(): Type H: illegal hex digit i] severity [E_WARNING]
-     *
-     * It would be simply to silent fail the pack() call above but in all other cases, we don't expect an error,
-     * so better be safe and get the php error when something unexpected is happening
-     * @param string $id
-     * @throws Exception
-     * @return string  binary string
-     */
-    public static function convertVisitorIdToBin($id)
-    {
-        if (strlen($id) !== Piwik_Tracker::LENGTH_HEX_ID_STRING
-            || @bin2hex(self::hex2bin($id)) != $id
-        ) {
-            throw new Exception("visitorId is expected to be a " . Piwik_Tracker::LENGTH_HEX_ID_STRING . " hex char string");
-        }
-        return self::hex2bin($id);
-    }
-
-    /**
-     * Convert IP address (in network address format) to presentation format.
-     * This is a backward compatibility function for code that only expects
-     * IPv4 addresses (i.e., doesn't support IPv6).
-     *
-     * @see Piwik_IP::N2P()
-     *
-     * This function does not support the long (or its string representation)
-     * returned by the built-in ip2long() function, from Piwik 1.3 and earlier.
-     *
-     * @deprecated 1.4
-     *
-     * @param string $ip  IP address in network address format
-     * @return string
-     */
-    public static function long2ip($ip)
-    {
-        return Piwik_IP::long2ip($ip);
-    }
-
-    /**
-     * Should we use the replacement json_encode/json_decode functions?
-     *
-     * @return bool  True if broken; false otherwise
-     */
-    private static function useJsonLibrary()
-    {
-        static $useLib;
-
-        if (!isset($useLib)) {
-            /*
-             * 5.1.x - doesn't have json extension; we use lib/upgradephp instead
-             * 5.2 to 5.2.4 - broken in various ways, including:
-             *
-             * @see https://bugs.php.net/bug.php?id=38680 'json_decode cannot decode basic types'
-             * @see https://bugs.php.net/bug.php?id=41403 'json_decode cannot decode floats'
-             * @see https://bugs.php.net/bug.php?id=42785 'json_encode outputs numbers according to locale'
-             */
-            $useLib = false;
-            if (version_compare(PHP_VERSION, '5.2.1') < 0) {
-                $useLib = true;
-            } else if (version_compare(PHP_VERSION, '5.2.5') < 0) {
-                $info = localeconv();
-                $useLib = $info['decimal_point'] != '.';
-            }
-        }
-
-        return $useLib;
-    }
-
-    /**
-     * JSON encode wrapper
-     * - missing or broken in some php 5.x versions
-     *
-     * @param mixed $value
-     * @return string
-     */
-    public static function json_encode($value)
-    {
-        if (self::useJsonLibrary()) {
-            return _json_encode($value);
-        }
-
-        return @json_encode($value);
-    }
-
-    /**
-     * JSON decode wrapper
-     * - missing or broken in some php 5.x versions
-     *
-     * @param string $json
-     * @param bool $assoc
-     * @return mixed
-     */
-    public static function json_decode($json, $assoc = false)
-    {
-        if (self::useJsonLibrary()) {
-            return _json_decode($json, $assoc);
-        }
-
-        return json_decode($json, $assoc);
-    }
-
-    /*
-     * DataFiles
-     */
-
-    /**
-     * Returns list of continent codes
-     *
-     * @see core/DataFiles/Countries.php
-     *
-     * @return array  Array of 3 letter continent codes
-     */
-    public static function getContinentsList()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php';
-
-        $continentsList = $GLOBALS['Piwik_ContinentList'];
-        return $continentsList;
-    }
-
-    /**
-     * Returns list of valid country codes
-     *
-     * @see core/DataFiles/Countries.php
-     *
-     * @param bool $includeInternalCodes
-     * @return array  Array of (2 letter ISO codes => 3 letter continent code)
-     */
-    public static function getCountriesList($includeInternalCodes = false)
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php';
-
-        $countriesList = $GLOBALS['Piwik_CountryList'];
-        $extras = $GLOBALS['Piwik_CountryList_Extras'];
-
-        if ($includeInternalCodes) {
-            return array_merge($countriesList, $extras);
-        }
-        return $countriesList;
-    }
-
-    /**
-     * Returns list of valid language codes
-     *
-     * @see core/DataFiles/Languages.php
-     *
-     * @return array  Array of 2 letter ISO codes => Language name (in English)
-     */
-    public static function getLanguagesList()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Languages.php';
-
-        $languagesList = $GLOBALS['Piwik_LanguageList'];
-        return $languagesList;
-    }
-
-    /**
-     * Returns list of language to country mappings
-     *
-     * @see core/DataFiles/LanguageToCountry.php
-     *
-     * @return array  Array of ( 2 letter ISO language codes => 2 letter ISO country codes )
-     */
-    public static function getLanguageToCountryList()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/LanguageToCountry.php';
-
-        $languagesList = $GLOBALS['Piwik_LanguageToCountry'];
-        return $languagesList;
-    }
-
-    /**
-     * Returns list of search engines by URL
-     *
-     * @see core/DataFiles/SearchEngines.php
-     *
-     * @return array  Array of ( URL => array( searchEngineName, keywordParameter, path, charset ) )
-     */
-    public static function getSearchEngineUrls()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/SearchEngines.php';
-
-        $searchEngines = $GLOBALS['Piwik_SearchEngines'];
-        return $searchEngines;
-    }
-
-    /**
-     * Returns list of search engines by name
-     *
-     * @see core/DataFiles/SearchEngines.php
-     *
-     * @return array  Array of ( searchEngineName => URL )
-     */
-    public static function getSearchEngineNames()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/SearchEngines.php';
-
-        $searchEngines = $GLOBALS['Piwik_SearchEngines_NameToUrl'];
-        return $searchEngines;
-    }
-
-    /**
-     * Returns list of provider names
-     *
-     * @see core/DataFiles/Providers.php
-     *
-     * @return array  Array of ( dnsName => providerName )
-     */
-    public static function getProviderNames()
-    {
-        require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Providers.php';
-
-        $providers = $GLOBALS['Piwik_ProviderNames'];
-        return $providers;
-    }
-
-    /*
-     * Language, country, continent
-     */
-
-    /**
-     * Returns the browser language code, eg. "en-gb,en;q=0.5"
-     *
-     * @param string|null $browserLang  Optional browser language, otherwise taken from the request header
-     * @return string
-     */
-    public static function getBrowserLanguage($browserLang = NULL)
-    {
-        static $replacementPatterns = array(
-            // extraneous bits of RFC 3282 that we ignore
-            '/(\\\\.)/', // quoted-pairs
-            '/(\s+)/', // CFWcS white space
-            '/(\([^)]*\))/', // CFWS comments
-            '/(;q=[0-9.]+)/', // quality
+            // try to overcome restrictive umask (mis-)configuration
+            if (!is_writable($path)) {
+                @chmod($path, 0755);
+                if (!is_writable($path)) {
+                    @chmod($path, 0775);
 
-            // found in the LANG environment variable
-            '/\.(.*)/', // charset (e.g., en_CA.UTF-8)
-            '/^C$/', // POSIX 'C' locale
-        );
+                    // enough! we're not going to make the directory world-writeable
+                }
+            }
 
-        if (is_null($browserLang)) {
-            $browserLang = self::sanitizeInputValues(@$_SERVER['HTTP_ACCEPT_LANGUAGE']);
-            if (empty($browserLang) && self::isPhpCliMode()) {
-                $browserLang = @getenv('LANG');
+            if ($denyAccess) {
+                \Piwik\Core\self::createHtAccess($path, $overwrite = false);
             }
         }
 
-        if (is_null($browserLang)) {
-            // a fallback might be to infer the language in HTTP_USER_AGENT (i.e., localized build)
-            $browserLang = "";
-        } else {
-            // language tags are case-insensitive per HTTP/1.1 s3.10 but the region may be capitalized per ISO3166-1;
-            // underscores are not permitted per RFC 4646 or 4647 (which obsolete RFC 1766 and 3066),
-            // but we guard against a bad user agent which naively uses its locale
-            $browserLang = strtolower(str_replace('_', '-', $browserLang));
-
-            // filters
-            $browserLang = preg_replace($replacementPatterns, '', $browserLang);
-
-            $browserLang = preg_replace('/((^|,)chrome:.*)/', '', $browserLang, 1); // Firefox bug
-            $browserLang = preg_replace('/(,)(?:en-securid,)|(?:(^|,)en-securid(,|$))/', '$1', $browserLang, 1); // unregistered language tag
-
-            $browserLang = str_replace('sr-sp', 'sr-rs', $browserLang); // unofficial (proposed) code in the wild
+        /**
+         * Create .htaccess file in specified directory
+         *
+         * Apache-specific; for IIS @see web.config
+         *
+         * @param string $path     without trailing slash
+         * @param bool $overwrite whether to overwrite an existing file or not
+         * @param string $content
+         */
+        public static function createHtAccess($path, $overwrite = true, $content = "<Files \"*\">\n<IfModule mod_access.c>\nDeny from all\n</IfModule>\n<IfModule !mod_access_compat>\n<IfModule mod_authz_host.c>\nDeny from all\n</IfModule>\n</IfModule>\n<IfModule mod_access_compat>\nDeny from all\n</IfModule>\n</Files>\n")
+        {
+            if (\Piwik\Core\self::isApache()) {
+                $file = $path . '/.htaccess';
+                if ($overwrite || !file_exists($file)) {
+                    @file_put_contents($file, $content);
+                }
+            }
         }
 
-        return $browserLang;
-    }
+        /**
+         * Get canonicalized absolute path
+         * See http://php.net/realpath
+         *
+         * @param string $path
+         * @return string  canonicalized absolute path
+         */
+        public static function realpath($path)
+        {
+            if (file_exists($path)) {
+                return realpath($path);
+            }
+            return $path;
+        }
+
+        /**
+         * Returns true if the string is a valid filename
+         * File names that start with a-Z or 0-9 and contain a-Z, 0-9, underscore(_), dash(-), and dot(.) will be accepted.
+         * File names beginning with anything but a-Z or 0-9 will be rejected (including .htaccess for example).
+         * File names containing anything other than above mentioned will also be rejected (file names with spaces won't be accepted).
+         *
+         * @param string $filename
+         * @return bool
+         *
+         */
+        public static function isValidFilename($filename)
+        {
+            return (0 !== preg_match('/(^[a-zA-Z0-9]+([a-zA-Z_0-9.-]*))$/D', $filename));
+        }
+
+        /*
+         * String operations
+         */
+
+        /**
+         * byte-oriented substr() - ASCII
+         *
+         * @param string $string
+         * @param int $start
+         * @param int     ...      optional length
+         * @return string
+         */
+        public static function substr($string, $start)
+        {
+            // in case mbstring overloads substr function
+            $substr = function_exists('mb_orig_substr') ? 'mb_orig_substr' : 'substr';
+
+            $length = func_num_args() > 2
+                ? func_get_arg(2)
+                : \Piwik\Core\self::strlen($string);
+
+            return $substr($string, $start, $length);
+        }
+
+        /**
+         * byte-oriented strlen() - ASCII
+         *
+         * @param string $string
+         * @return int
+         */
+        public static function strlen($string)
+        {
+            // in case mbstring overloads strlen function
+            $strlen = function_exists('mb_orig_strlen') ? 'mb_orig_strlen' : 'strlen';
+            return $strlen($string);
+        }
+
+        /**
+         * multi-byte substr() - UTF-8
+         *
+         * @param string $string
+         * @param int $start
+         * @param int     ...      optional length
+         * @return string
+         */
+        public static function mb_substr($string, $start)
+        {
+            $length = func_num_args() > 2
+                ? func_get_arg(2)
+                : \Piwik\Core\self::mb_strlen($string);
+
+            if (function_exists('mb_substr')) {
+                return mb_substr($string, $start, $length, 'UTF-8');
+            }
 
-    /**
-     * Returns the visitor country based on the Browser 'accepted language'
-     * information, but provides a hook for geolocation via IP address.
-     *
-     * @param string $lang                          browser lang
-     * @param bool $enableLanguageToCountryGuess  If set to true, some assumption will be made and detection guessed more often, but accuracy could be affected
-     * @param string $ip
-     * @return string  2 letter ISO code
-     */
-    public static function getCountry($lang, $enableLanguageToCountryGuess, $ip)
-    {
-        $country = null;
-        Piwik_PostEvent('Common.getCountry', array(&$country, $ip));
-        if (!empty($country)) {
-            return strtolower($country);
+            return substr($string, $start, $length);
         }
 
-        if (empty($lang) || strlen($lang) < 2 || $lang == 'xx') {
-            return 'xx';
+        /**
+         * multi-byte strlen() - UTF-8
+         *
+         * @param string $string
+         * @return int
+         */
+        public static function mb_strlen($string)
+        {
+            if (function_exists('mb_strlen')) {
+                return mb_strlen($string, 'UTF-8');
+            }
+
+            return strlen($string);
         }
 
-        $validCountries = self::getCountriesList();
-        return self::extractCountryCodeFromBrowserLanguage($lang, $validCountries, $enableLanguageToCountryGuess);
-    }
+        /**
+         * multi-byte strtolower() - UTF-8
+         *
+         * @param string $string
+         * @return string
+         */
+        public static function mb_strtolower($string)
+        {
+            if (function_exists('mb_strtolower')) {
+                return mb_strtolower($string, 'UTF-8');
+            }
 
-    /**
-     * Returns list of valid country codes
-     *
-     * @param string $browserLanguage
-     * @param array $validCountries                 Array of valid countries
-     * @param bool $enableLanguageToCountryGuess  (if true, will guess country based on language that lacks region information)
-     * @return array Array of 2 letter ISO codes
-     */
-    public static function extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess)
-    {
-        $langToCountry = self::getLanguageToCountryList();
+            return strtolower($string);
+        }
+
+        /*
+         * Escaping input
+         */
+
+        /**
+         * Returns the variable after cleaning operations.
+         * NB: The variable still has to be escaped before going into a SQL Query!
+         *
+         * If an array is passed the cleaning is done recursively on all the sub-arrays.
+         * The array's keys are filtered as well!
+         *
+         * How this method works:
+         * - The variable returned has been htmlspecialchars to avoid the XSS security problem.
+         * - The single quotes are not protected so "Piwik's amazing" will still be "Piwik's amazing".
+         *
+         * - Transformations are:
+         *         - '&' (ampersand) becomes '&amp;'
+         *         - '"'(double quote) becomes '&quot;'
+         *         - '<' (less than) becomes '&lt;'
+         *         - '>' (greater than) becomes '&gt;'
+         * - It handles the magic_quotes setting.
+         * - A non string value is returned without modification
+         *
+         * @param mixed $value The variable to be cleaned
+         * @param bool $alreadyStripslashed
+         * @throws Exception
+         * @return mixed  The variable after cleaning
+         */
+        public static function sanitizeInputValues($value, $alreadyStripslashed = false)
+        {
+            if (is_numeric($value)) {
+                return $value;
+            } elseif (is_string($value)) {
+                $value = \Piwik\Core\self::sanitizeInputValue($value);
+
+                if (!$alreadyStripslashed) // a JSON array was already stripslashed, don't do it again for each value
+                {
+                    $value = \Piwik\Core\self::undoMagicQuotes($value);
+                }
+            } elseif (is_array($value)) {
+                foreach (array_keys($value) as $key) {
+                    $newKey = $key;
+                    $newKey = \Piwik\Core\self::sanitizeInputValues($newKey, $alreadyStripslashed);
+                    if ($key != $newKey) {
+                        $value[$newKey] = $value[$key];
+                        unset($value[$key]);
+                    }
 
-        if ($enableLanguageToCountryGuess) {
-            if (preg_match('/^([a-z]{2,3})(?:,|;|$)/', $browserLanguage, $matches)) {
-                // match language (without region) to infer the country of origin
-                if (array_key_exists($matches[1], $langToCountry)) {
-                    return $langToCountry[$matches[1]];
+                    $value[$newKey] = \Piwik\Core\self::sanitizeInputValues($value[$newKey], $alreadyStripslashed);
                 }
+            } elseif (!is_null($value)
+                && !is_bool($value)
+            ) {
+                throw new Exception("The value to escape has not a supported type. Value = " . var_export($value, true));
             }
+            return $value;
         }
 
-        if (!empty($validCountries) && preg_match_all('/[-]([a-z]{2})/', $browserLanguage, $matches, PREG_SET_ORDER)) {
-            foreach ($matches as $parts) {
-                // match location; we don't make any inferences from the language
-                if (array_key_exists($parts[1], $validCountries)) {
-                    return $parts[1];
+        /**
+         * Sanitize a single input value
+         *
+         * @param string $value
+         * @return string  sanitized input
+         */
+        public static function sanitizeInputValue($value)
+        {
+            // $_GET and $_REQUEST already urldecode()'d
+            // decode
+            // note: before php 5.2.7, htmlspecialchars() double encodes &#x hex items
+            $value = html_entity_decode($value, \Piwik\Core\Piwik_Common::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
+
+            // filter
+            $value = str_replace(array("\n", "\r", "\0"), '', $value);
+
+            // escape
+            $tmp = @htmlspecialchars($value, \Piwik\Core\self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
+
+            // note: php 5.2.5 and above, htmlspecialchars is destructive if input is not UTF-8
+            if ($value != '' && $tmp == '') {
+                // convert and escape
+                $value = utf8_encode($value);
+                $tmp = htmlspecialchars($value, \Piwik\Core\self::HTML_ENCODING_QUOTE_STYLE, 'UTF-8');
+            }
+            return $tmp;
+        }
+
+        /**
+         * Unsanitize a single input value
+         *
+         * @param string $value
+         * @return string  unsanitized input
+         */
+        public static function unsanitizeInputValue($value)
+        {
+            return htmlspecialchars_decode($value, \Piwik\Core\self::HTML_ENCODING_QUOTE_STYLE);
+        }
+
+        /**
+         * Unsanitize one or more values.
+         *
+         * @param string|array $value
+         * @return string|array  unsanitized input
+         */
+        public static function unsanitizeInputValues($value)
+        {
+            if (is_array($value)) {
+                $result = array();
+                foreach ($value as $key => $arrayValue) {
+                    $result[$key] = \Piwik\Core\self::unsanitizeInputValues($arrayValue);
                 }
+                return $result;
+            } else {
+                return \Piwik\Core\self::unsanitizeInputValue($value);
             }
         }
-        return 'xx';
-    }
 
-    /**
-     * Returns the visitor language based only on the Browser 'accepted language' information
-     *
-     * @param string $browserLanguage  Browser's accepted langauge header
-     * @param array  $validLanguages   array of valid language codes
-     * @return string  2 letter ISO 639 code
-     */
-    public static function extractLanguageCodeFromBrowserLanguage($browserLanguage, $validLanguages)
-    {
-        // assumes language preference is sorted;
-        // does not handle language-script-region tags or language range (*)
-        if (!empty($validLanguages) && preg_match_all('/(?:^|,)([a-z]{2,3})([-][a-z]{2})?/', $browserLanguage, $matches, PREG_SET_ORDER)) {
-            foreach ($matches as $parts) {
-                if (count($parts) == 3) {
-                    // match locale (language and location)
-                    if (in_array($parts[1] . $parts[2], $validLanguages)) {
-                        return $parts[1] . $parts[2];
+        /**
+         * Undo the damage caused by magic_quotes; deprecated in php 5.3 but not removed until php 5.4
+         *
+         * @param string
+         * @return string  modified or not
+         */
+        public static function undoMagicQuotes($value)
+        {
+            return version_compare(PHP_VERSION, '5.4', '<')
+            && get_magic_quotes_gpc()
+                ? stripslashes($value)
+                : $value;
+        }
+
+        /**
+         * Returns a sanitized variable value from the $_GET and $_POST superglobal.
+         * If the variable doesn't have a value or an empty value, returns the defaultValue if specified.
+         * If the variable doesn't have neither a value nor a default value provided, an exception is raised.
+         *
+         * @see sanitizeInputValues() for the applied sanitization
+         *
+         * @param string $varName            name of the variable
+         * @param string $varDefault         default value. If '', and if the type doesn't match, exit() !
+         * @param string $varType            Expected type, the value must be one of the following: array, int, integer, string, json
+         * @param array $requestArrayToUse
+         *
+         * @throws Exception  if the variable type is not known
+         *                    or if the variable we want to read doesn't have neither a value nor a default value specified
+         *
+         * @return mixed The variable after cleaning
+         */
+        public static function getRequestVar($varName, $varDefault = null, $varType = null, $requestArrayToUse = null)
+        {
+            if (is_null($requestArrayToUse)) {
+                $requestArrayToUse = $_GET + $_POST;
+            }
+            $varDefault = \Piwik\Core\self::sanitizeInputValues($varDefault);
+            if ($varType === 'int') {
+                // settype accepts only integer
+                // 'int' is simply a shortcut for 'integer'
+                $varType = 'integer';
+            }
+
+            // there is no value $varName in the REQUEST so we try to use the default value
+            if (empty($varName)
+                || !isset($requestArrayToUse[$varName])
+                || (!is_array($requestArrayToUse[$varName])
+                    && strlen($requestArrayToUse[$varName]) === 0
+                )
+            ) {
+                if (is_null($varDefault)) {
+                    throw new Exception("The parameter '$varName' isn't set in the Request, and a default value wasn't provided.");
+                } else {
+                    if (!is_null($varType)
+                        && in_array($varType, array('string', 'integer', 'array'))
+                    ) {
+                        settype($varDefault, $varType);
                     }
+                    return $varDefault;
+                }
+            }
+
+            // Normal case, there is a value available in REQUEST for the requested varName:
+
+            // we deal w/ json differently
+            if ($varType == 'json') {
+                $value = \Piwik\Core\self::undoMagicQuotes($requestArrayToUse[$varName]);
+                $value = \Piwik\Core\Piwik_Common::json_decode($value, $assoc = true);
+                return \Piwik\Core\self::sanitizeInputValues($value, $alreadyStripslashed = true);
+            }
+
+            $value = \Piwik\Core\self::sanitizeInputValues($requestArrayToUse[$varName]);
+            if (!is_null($varType)) {
+                $ok = false;
+
+                if ($varType === 'string') {
+                    if (is_string($value)) $ok = true;
+                } elseif ($varType === 'integer') {
+                    if ($value == (string)(int)$value) $ok = true;
+                } elseif ($varType === 'float') {
+                    if ($value == (string)(float)$value) $ok = true;
+                } elseif ($varType === 'array') {
+                    if (is_array($value)) $ok = true;
+                } else {
+                    throw new Exception("\$varType specified is not known. It should be one of the following: array, int, integer, float, string");
                 }
-                // match language only (where no region provided)
-                if (in_array($parts[1], $validLanguages)) {
-                    return $parts[1];
+
+                // The type is not correct
+                if ($ok === false) {
+                    if ($varDefault === null) {
+                        throw new Exception("The parameter '$varName' doesn't have a correct type, and a default value wasn't provided.");
+                    } // we return the default value with the good type set
+                    else {
+                        settype($varDefault, $varType);
+                        return $varDefault;
+                    }
                 }
+                settype($value, $varType);
             }
+            return $value;
         }
-        return 'xx';
-    }
 
-    /**
-     * Returns the continent of a given country
-     *
-     * @param string $country  2 letters isocode
-     *
-     * @return string  Continent (3 letters code : afr, asi, eur, amn, ams, oce)
-     */
-    public static function getContinent($country)
-    {
-        $countryList = self::getCountriesList();
-        if (isset($countryList[$country])) {
-            return $countryList[$country];
+        /*
+         * Generating unique strings
+         */
+
+        /**
+         * Returns a 32 characters long uniq ID
+         *
+         * @return string 32 chars
+         */
+        public static function generateUniqId()
+        {
+            return md5(uniqid(rand(), true));
+        }
+
+        /**
+         * Get salt from [superuser] section
+         *
+         * @return string
+         */
+        public static function getSalt()
+        {
+            static $salt = null;
+            if (is_null($salt)) {
+                $salt = @Config::getInstance()->superuser['salt'];
+            }
+            return $salt;
+        }
+
+        /**
+         * Configureable hash() algorithm (defaults to md5)
+         *
+         * @param string $str String to be hashed
+         * @param bool $raw_output
+         * @return string Hash string
+         */
+        public static function hash($str, $raw_output = false)
+        {
+            static $hashAlgorithm = null;
+            if (is_null($hashAlgorithm)) {
+                $hashAlgorithm = @Config::getInstance()->General['hash_algorithm'];
+            }
+
+            if ($hashAlgorithm) {
+                $hash = @hash($hashAlgorithm, $str, $raw_output);
+                if ($hash !== false)
+                    return $hash;
+            }
+
+            return md5($str, $raw_output);
         }
-        return 'unk';
-    }
 
-    /*
-     * Campaign
-     */
+        /**
+         * Generate random string
+         *
+         * @param int $length string length
+         * @param string $alphabet characters allowed in random string
+         * @return string  random string with given length
+         */
+        public static function getRandomString($length = 16, $alphabet = "abcdefghijklmnoprstuvwxyz0123456789")
+        {
+            $chars = $alphabet;
+            $str = '';
 
-    /**
-     * Returns the list of Campaign parameter names that will be read to classify
-     * a visit as coming from a Campaign
-     *
-     * @return array array(
-     *            0 => array( ... ) // campaign names parameters
-     *            1 => array( ... ) // campaign keyword parameters
-     * );
-     */
-    public static function getCampaignParameters()
-    {
-        $return = array(
-            Config::getInstance()->Tracker['campaign_var_name'],
-            Config::getInstance()->Tracker['campaign_keyword_var_name'],
-        );
-
-        foreach ($return as &$list) {
-            if (strpos($list, ',') !== false) {
-                $list = explode(',', $list);
-            } else {
-                $list = array($list);
+            list($usec, $sec) = explode(" ", microtime());
+            $seed = ((float)$sec + (float)$usec) * 100000;
+            mt_srand($seed);
+
+            for ($i = 0; $i < $length; $i++) {
+                $rand_key = mt_rand(0, strlen($chars) - 1);
+                $str .= substr($chars, $rand_key, 1);
+            }
+            return str_shuffle($str);
+        }
+
+        /*
+         * Conversions
+         */
+
+        /**
+         * Convert hexadecimal representation into binary data.
+         * !! Will emit warning if input string is not hex!!
+         *
+         * @see http://php.net/bin2hex
+         *
+         * @param string $str  Hexadecimal representation
+         * @return string
+         */
+        public static function hex2bin($str)
+        {
+            return pack("H*", $str);
+        }
+
+        /**
+         * This function will convert the input string to the binary representation of the ID
+         * but it will throw an Exception if the specified input ID is not correct
+         *
+         * This is used when building segments containing visitorId which could be an invalid string
+         * therefore throwing Unexpected PHP error [pack(): Type H: illegal hex digit i] severity [E_WARNING]
+         *
+         * It would be simply to silent fail the pack() call above but in all other cases, we don't expect an error,
+         * so better be safe and get the php error when something unexpected is happening
+         * @param string $id
+         * @throws Exception
+         * @return string  binary string
+         */
+        public static function convertVisitorIdToBin($id)
+        {
+            if (strlen($id) !== Piwik_Tracker::LENGTH_HEX_ID_STRING
+                || @bin2hex(\Piwik\Core\self::hex2bin($id)) != $id
+            ) {
+                throw new Exception("visitorId is expected to be a " . Piwik_Tracker::LENGTH_HEX_ID_STRING . " hex char string");
+            }
+            return \Piwik\Core\self::hex2bin($id);
+        }
+
+        /**
+         * Convert IP address (in network address format) to presentation format.
+         * This is a backward compatibility function for code that only expects
+         * IPv4 addresses (i.e., doesn't support IPv6).
+         *
+         * @see Piwik_IP::N2P()
+         *
+         * This function does not support the long (or its string representation)
+         * returned by the built-in ip2long() function, from Piwik 1.3 and earlier.
+         *
+         * @deprecated 1.4
+         *
+         * @param string $ip  IP address in network address format
+         * @return string
+         */
+        public static function long2ip($ip)
+        {
+            return Piwik_IP::long2ip($ip);
+        }
+
+        /**
+         * Should we use the replacement json_encode/json_decode functions?
+         *
+         * @return bool  True if broken; false otherwise
+         */
+        private static function useJsonLibrary()
+        {
+            static $useLib;
+
+            if (!isset($useLib)) {
+                /*
+                 * 5.1.x - doesn't have json extension; we use lib/upgradephp instead
+                 * 5.2 to 5.2.4 - broken in various ways, including:
+                 *
+                 * @see https://bugs.php.net/bug.php?id=38680 'json_decode cannot decode basic types'
+                 * @see https://bugs.php.net/bug.php?id=41403 'json_decode cannot decode floats'
+                 * @see https://bugs.php.net/bug.php?id=42785 'json_encode outputs numbers according to locale'
+                 */
+                $useLib = false;
+                if (version_compare(PHP_VERSION, '5.2.1') < 0) {
+                    $useLib = true;
+                } else if (version_compare(PHP_VERSION, '5.2.5') < 0) {
+                    $info = localeconv();
+                    $useLib = $info['decimal_point'] != '.';
+                }
             }
+
+            return $useLib;
         }
 
-        array_walk_recursive($return, 'trim');
-        return $return;
-    }
+        /**
+         * JSON encode wrapper
+         * - missing or broken in some php 5.x versions
+         *
+         * @param mixed $value
+         * @return string
+         */
+        public static function json_encode($value)
+        {
+            if (\Piwik\Core\self::useJsonLibrary()) {
+                return _json_encode($value);
+            }
 
-    /*
-     * Referrer
-     */
+            return @json_encode($value);
+        }
+
+        /**
+         * JSON decode wrapper
+         * - missing or broken in some php 5.x versions
+         *
+         * @param string $json
+         * @param bool $assoc
+         * @return mixed
+         */
+        public static function json_decode($json, $assoc = false)
+        {
+            if (\Piwik\Core\self::useJsonLibrary()) {
+                return _json_decode($json, $assoc);
+            }
 
-    /**
-     * Reduce URL to more minimal form.  2 letter country codes are
-     * replaced by '{}', while other parts are simply removed.
-     *
-     * Examples:
-     *   www.example.com -> example.com
-     *   search.example.com -> example.com
-     *   m.example.com -> example.com
-     *   de.example.com -> {}.example.com
-     *   example.de -> example.{}
-     *   example.co.uk -> example.{}
-     *
-     * @param string $url
-     * @return string
-     */
-    public static function getLossyUrl($url)
-    {
-        static $countries;
-        if (!isset($countries)) {
-            $countries = implode('|', array_keys(self::getCountriesList(true)));
-        }
-
-        return preg_replace(
-            array(
-                 '/^(w+[0-9]*|search)\./',
-                 '/(^|\.)m\./',
-                 '/(\.(com|org|net|co|it|edu))?\.(' . $countries . ')(\/|$)/',
-                 '/(^|\.)(' . $countries . ')\./',
-            ),
-            array(
-                 '',
-                 '$1',
-                 '.{}$4',
-                 '$1{}.',
-            ),
-            $url);
-    }
+            return json_decode($json, $assoc);
+        }
+
+        /*
+         * DataFiles
+         */
+
+        /**
+         * Returns list of continent codes
+         *
+         * @see core/DataFiles/Countries.php
+         *
+         * @return array  Array of 3 letter continent codes
+         */
+        public static function getContinentsList()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php';
+
+            $continentsList = $GLOBALS['Piwik_ContinentList'];
+            return $continentsList;
+        }
+
+        /**
+         * Returns list of valid country codes
+         *
+         * @see core/DataFiles/Countries.php
+         *
+         * @param bool $includeInternalCodes
+         * @return array  Array of (2 letter ISO codes => 3 letter continent code)
+         */
+        public static function getCountriesList($includeInternalCodes = false)
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Countries.php';
+
+            $countriesList = $GLOBALS['Piwik_CountryList'];
+            $extras = $GLOBALS['Piwik_CountryList_Extras'];
+
+            if ($includeInternalCodes) {
+                return array_merge($countriesList, $extras);
+            }
+            return $countriesList;
+        }
+
+        /**
+         * Returns list of valid language codes
+         *
+         * @see core/DataFiles/Languages.php
+         *
+         * @return array  Array of 2 letter ISO codes => Language name (in English)
+         */
+        public static function getLanguagesList()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Languages.php';
+
+            $languagesList = $GLOBALS['Piwik_LanguageList'];
+            return $languagesList;
+        }
+
+        /**
+         * Returns list of language to country mappings
+         *
+         * @see core/DataFiles/LanguageToCountry.php
+         *
+         * @return array  Array of ( 2 letter ISO language codes => 2 letter ISO country codes )
+         */
+        public static function getLanguageToCountryList()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/LanguageToCountry.php';
+
+            $languagesList = $GLOBALS['Piwik_LanguageToCountry'];
+            return $languagesList;
+        }
+
+        /**
+         * Returns list of search engines by URL
+         *
+         * @see core/DataFiles/SearchEngines.php
+         *
+         * @return array  Array of ( URL => array( searchEngineName, keywordParameter, path, charset ) )
+         */
+        public static function getSearchEngineUrls()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/SearchEngines.php';
+
+            $searchEngines = $GLOBALS['Piwik_SearchEngines'];
+            return $searchEngines;
+        }
+
+        /**
+         * Returns list of search engines by name
+         *
+         * @see core/DataFiles/SearchEngines.php
+         *
+         * @return array  Array of ( searchEngineName => URL )
+         */
+        public static function getSearchEngineNames()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/SearchEngines.php';
+
+            $searchEngines = $GLOBALS['Piwik_SearchEngines_NameToUrl'];
+            return $searchEngines;
+        }
+
+        /**
+         * Returns list of provider names
+         *
+         * @see core/DataFiles/Providers.php
+         *
+         * @return array  Array of ( dnsName => providerName )
+         */
+        public static function getProviderNames()
+        {
+            require_once PIWIK_INCLUDE_PATH . '/core/DataFiles/Providers.php';
+
+            $providers = $GLOBALS['Piwik_ProviderNames'];
+            return $providers;
+        }
+
+        /*
+         * Language, country, continent
+         */
+
+        /**
+         * Returns the browser language code, eg. "en-gb,en;q=0.5"
+         *
+         * @param string|null $browserLang  Optional browser language, otherwise taken from the request header
+         * @return string
+         */
+        public static function getBrowserLanguage($browserLang = NULL)
+        {
+            static $replacementPatterns = array(
+                // extraneous bits of RFC 3282 that we ignore
+                '/(\\\\.)/', // quoted-pairs
+                '/(\s+)/', // CFWcS white space
+                '/(\([^)]*\))/', // CFWS comments
+                '/(;q=[0-9.]+)/', // quality
+
+                // found in the LANG environment variable
+                '/\.(.*)/', // charset (e.g., en_CA.UTF-8)
+                '/^C$/', // POSIX 'C' locale
+            );
+
+            if (is_null($browserLang)) {
+                $browserLang = \Piwik\Core\self::sanitizeInputValues(@$_SERVER['HTTP_ACCEPT_LANGUAGE']);
+                if (empty($browserLang) && \Piwik\Core\self::isPhpCliMode()) {
+                    $browserLang = @getenv('LANG');
+                }
+            }
 
-    /**
-     * Extracts a keyword from a raw not encoded URL.
-     * Will only extract keyword if a known search engine has been detected.
-     * Returns the keyword:
-     * - in UTF8: automatically converted from other charsets when applicable
-     * - strtolowered: "QUErY test!" will return "query test!"
-     * - trimmed: extra spaces before and after are removed
-     *
-     * Lists of supported search engines can be found in /core/DataFiles/SearchEngines.php
-     * The function returns false when a keyword couldn't be found.
-     *     eg. if the url is "http://www.google.com/partners.html" this will return false,
-     *       as the google keyword parameter couldn't be found.
-     *
-     * @see unit tests in /tests/core/Common.test.php
-     * @param string $referrerUrl  URL referer URL, eg. $_SERVER['HTTP_REFERER']
-     * @return array|false false if a keyword couldn't be extracted,
-     *                        or array(
-     *                            'name' => 'Google',
-     *                            'keywords' => 'my searched keywords')
-     */
-    public static function extractSearchEngineInformationFromUrl($referrerUrl)
-    {
-        $refererParsed = @parse_url($referrerUrl);
-        $refererHost = '';
-        if (isset($refererParsed['host'])) {
-            $refererHost = $refererParsed['host'];
-        }
-        if (empty($refererHost)) {
-            return false;
-        }
-        // some search engines (eg. Bing Images) use the same domain
-        // as an existing search engine (eg. Bing), we must also use the url path
-        $refererPath = '';
-        if (isset($refererParsed['path'])) {
-            $refererPath = $refererParsed['path'];
-        }
-
-        // no search query
-        if (!isset($refererParsed['query'])) {
-            $refererParsed['query'] = '';
-        }
-        $query = $refererParsed['query'];
-
-        // Google Referrers URLs sometimes have the fragment which contains the keyword
-        if (!empty($refererParsed['fragment'])) {
-            $query .= '&' . $refererParsed['fragment'];
-        }
-
-        $searchEngines = self::getSearchEngineUrls();
-
-        $hostPattern = self::getLossyUrl($refererHost);
-        if (array_key_exists($refererHost . $refererPath, $searchEngines)) {
-            $refererHost = $refererHost . $refererPath;
-        } elseif (array_key_exists($hostPattern . $refererPath, $searchEngines)) {
-            $refererHost = $hostPattern . $refererPath;
-        } elseif (array_key_exists($hostPattern, $searchEngines)) {
-            $refererHost = $hostPattern;
-        } elseif (!array_key_exists($refererHost, $searchEngines)) {
-            if (!strncmp($query, 'cx=partner-pub-', 15)) {
-                // Google custom search engine
-                $refererHost = 'google.com/cse';
-            } elseif (!strncmp($refererPath, '/pemonitorhosted/ws/results/', 28)) {
-                // private-label search powered by InfoSpace Metasearch
-                $refererHost = 'wsdsold.infospace.com';
-            } elseif (strpos($refererHost, '.images.search.yahoo.com') != false) {
-                // Yahoo! Images
-                $refererHost = 'images.search.yahoo.com';
-            } elseif (strpos($refererHost, '.search.yahoo.com') != false) {
-                // Yahoo!
-                $refererHost = 'search.yahoo.com';
+            if (is_null($browserLang)) {
+                // a fallback might be to infer the language in HTTP_USER_AGENT (i.e., localized build)
+                $browserLang = "";
             } else {
-                return false;
+                // language tags are case-insensitive per HTTP/1.1 s3.10 but the region may be capitalized per ISO3166-1;
+                // underscores are not permitted per RFC 4646 or 4647 (which obsolete RFC 1766 and 3066),
+                // but we guard against a bad user agent which naively uses its locale
+                $browserLang = strtolower(str_replace('_', '-', $browserLang));
+
+                // filters
+                $browserLang = preg_replace($replacementPatterns, '', $browserLang);
+
+                $browserLang = preg_replace('/((^|,)chrome:.*)/', '', $browserLang, 1); // Firefox bug
+                $browserLang = preg_replace('/(,)(?:en-securid,)|(?:(^|,)en-securid(,|$))/', '$1', $browserLang, 1); // unregistered language tag
+
+                $browserLang = str_replace('sr-sp', 'sr-rs', $browserLang); // unofficial (proposed) code in the wild
             }
+
+            return $browserLang;
+        }
+
+        /**
+         * Returns the visitor country based on the Browser 'accepted language'
+         * information, but provides a hook for geolocation via IP address.
+         *
+         * @param string $lang                          browser lang
+         * @param bool $enableLanguageToCountryGuess  If set to true, some assumption will be made and detection guessed more often, but accuracy could be affected
+         * @param string $ip
+         * @return string  2 letter ISO code
+         */
+        public static function getCountry($lang, $enableLanguageToCountryGuess, $ip)
+        {
+            $country = null;
+            Piwik_PostEvent('Common.getCountry', array(&$country, $ip));
+            if (!empty($country)) {
+                return strtolower($country);
+            }
+
+            if (empty($lang) || strlen($lang) < 2 || $lang == 'xx') {
+                return 'xx';
+            }
+
+            $validCountries = \Piwik\Core\self::getCountriesList();
+            return \Piwik\Core\self::extractCountryCodeFromBrowserLanguage($lang, $validCountries, $enableLanguageToCountryGuess);
+        }
+
+        /**
+         * Returns list of valid country codes
+         *
+         * @param string $browserLanguage
+         * @param array $validCountries                 Array of valid countries
+         * @param bool $enableLanguageToCountryGuess  (if true, will guess country based on language that lacks region information)
+         * @return array Array of 2 letter ISO codes
+         */
+        public static function extractCountryCodeFromBrowserLanguage($browserLanguage, $validCountries, $enableLanguageToCountryGuess)
+        {
+            $langToCountry = \Piwik\Core\self::getLanguageToCountryList();
+
+            if ($enableLanguageToCountryGuess) {
+                if (preg_match('/^([a-z]{2,3})(?:,|;|$)/', $browserLanguage, $matches)) {
+                    // match language (without region) to infer the country of origin
+                    if (array_key_exists($matches[1], $langToCountry)) {
+                        return $langToCountry[$matches[1]];
+                    }
+                }
+            }
+
+            if (!empty($validCountries) && preg_match_all('/[-]([a-z]{2})/', $browserLanguage, $matches, PREG_SET_ORDER)) {
+                foreach ($matches as $parts) {
+                    // match location; we don't make any inferences from the language
+                    if (array_key_exists($parts[1], $validCountries)) {
+                        return $parts[1];
+                    }
+                }
+            }
+            return 'xx';
         }
-        $searchEngineName = $searchEngines[$refererHost][0];
-        $variableNames = null;
-        if (isset($searchEngines[$refererHost][1])) {
-            $variableNames = $searchEngines[$refererHost][1];
-        }
-        if (!$variableNames) {
-            $searchEngineNames = self::getSearchEngineNames();
-            $url = $searchEngineNames[$searchEngineName];
-            $variableNames = $searchEngines[$url][1];
-        }
-        if (!is_array($variableNames)) {
-            $variableNames = array($variableNames);
+
+        /**
+         * Returns the visitor language based only on the Browser 'accepted language' information
+         *
+         * @param string $browserLanguage  Browser's accepted langauge header
+         * @param array $validLanguages   array of valid language codes
+         * @return string  2 letter ISO 639 code
+         */
+        public static function extractLanguageCodeFromBrowserLanguage($browserLanguage, $validLanguages)
+        {
+            // assumes language preference is sorted;
+            // does not handle language-script-region tags or language range (*)
+            if (!empty($validLanguages) && preg_match_all('/(?:^|,)([a-z]{2,3})([-][a-z]{2})?/', $browserLanguage, $matches, PREG_SET_ORDER)) {
+                foreach ($matches as $parts) {
+                    if (count($parts) == 3) {
+                        // match locale (language and location)
+                        if (in_array($parts[1] . $parts[2], $validLanguages)) {
+                            return $parts[1] . $parts[2];
+                        }
+                    }
+                    // match language only (where no region provided)
+                    if (in_array($parts[1], $validLanguages)) {
+                        return $parts[1];
+                    }
+                }
+            }
+            return 'xx';
         }
 
-        $key = null;
-        if ($searchEngineName === 'Google Images'
-            || ($searchEngineName === 'Google' && strpos($referrerUrl, '/imgres') !== false)
-        ) {
-            if (strpos($query, '&prev') !== false) {
-                $query = urldecode(trim(self::getParameterFromQueryString($query, 'prev')));
-                $query = str_replace('&', '&amp;', strstr($query, '?'));
+        /**
+         * Returns the continent of a given country
+         *
+         * @param string $country  2 letters isocode
+         *
+         * @return string  Continent (3 letters code : afr, asi, eur, amn, ams, oce)
+         */
+        public static function getContinent($country)
+        {
+            $countryList = \Piwik\Core\self::getCountriesList();
+            if (isset($countryList[$country])) {
+                return $countryList[$country];
             }
-            $searchEngineName = 'Google Images';
-        } else if ($searchEngineName === 'Google'
-            && (strpos($query, '&as_') !== false || strpos($query, 'as_') === 0)
-        ) {
-            $keys = array();
-            $key = self::getParameterFromQueryString($query, 'as_q');
-            if (!empty($key)) {
-                array_push($keys, $key);
+            return 'unk';
+        }
+
+        /*
+         * Campaign
+         */
+
+        /**
+         * Returns the list of Campaign parameter names that will be read to classify
+         * a visit as coming from a Campaign
+         *
+         * @return array array(
+         *            0 => array( ... ) // campaign names parameters
+         *            1 => array( ... ) // campaign keyword parameters
+         * );
+         */
+        public static function getCampaignParameters()
+        {
+            $return = array(
+                Config::getInstance()->Tracker['campaign_var_name'],
+                Config::getInstance()->Tracker['campaign_keyword_var_name'],
+            );
+
+            foreach ($return as &$list) {
+                if (strpos($list, ',') !== false) {
+                    $list = explode(',', $list);
+                } else {
+                    $list = array($list);
+                }
             }
-            $key = self::getParameterFromQueryString($query, 'as_oq');
-            if (!empty($key)) {
-                array_push($keys, str_replace('+', ' OR ', $key));
+
+            array_walk_recursive($return, 'trim');
+            return $return;
+        }
+
+        /*
+         * Referrer
+         */
+
+        /**
+         * Reduce URL to more minimal form.  2 letter country codes are
+         * replaced by '{}', while other parts are simply removed.
+         *
+         * Examples:
+         *   www.example.com -> example.com
+         *   search.example.com -> example.com
+         *   m.example.com -> example.com
+         *   de.example.com -> {}.example.com
+         *   example.de -> example.{}
+         *   example.co.uk -> example.{}
+         *
+         * @param string $url
+         * @return string
+         */
+        public static function getLossyUrl($url)
+        {
+            static $countries;
+            if (!isset($countries)) {
+                $countries = implode('|', array_keys(\Piwik\Core\self::getCountriesList(true)));
             }
-            $key = self::getParameterFromQueryString($query, 'as_epq');
-            if (!empty($key)) {
-                array_push($keys, "\"$key\"");
+
+            return preg_replace(
+                array(
+                    '/^(w+[0-9]*|search)\./',
+                    '/(^|\.)m\./',
+                    '/(\.(com|org|net|co|it|edu))?\.(' . $countries . ')(\/|$)/',
+                    '/(^|\.)(' . $countries . ')\./',
+                ),
+                array(
+                    '',
+                    '$1',
+                    '.{}$4',
+                    '$1{}.',
+                ),
+                $url);
+        }
+
+        /**
+         * Extracts a keyword from a raw not encoded URL.
+         * Will only extract keyword if a known search engine has been detected.
+         * Returns the keyword:
+         * - in UTF8: automatically converted from other charsets when applicable
+         * - strtolowered: "QUErY test!" will return "query test!"
+         * - trimmed: extra spaces before and after are removed
+         *
+         * Lists of supported search engines can be found in /core/DataFiles/SearchEngines.php
+         * The function returns false when a keyword couldn't be found.
+         *     eg. if the url is "http://www.google.com/partners.html" this will return false,
+         *       as the google keyword parameter couldn't be found.
+         *
+         * @see unit tests in /tests/core/Common.test.php
+         * @param string $referrerUrl  URL referer URL, eg. $_SERVER['HTTP_REFERER']
+         * @return array|false false if a keyword couldn't be extracted,
+         *                        or array(
+         *                            'name' => 'Google',
+         *                            'keywords' => 'my searched keywords')
+         */
+        public static function extractSearchEngineInformationFromUrl($referrerUrl)
+        {
+            $refererParsed = @parse_url($referrerUrl);
+            $refererHost = '';
+            if (isset($refererParsed['host'])) {
+                $refererHost = $refererParsed['host'];
             }
-            $key = self::getParameterFromQueryString($query, 'as_eq');
-            if (!empty($key)) {
-                array_push($keys, "-$key");
+            if (empty($refererHost)) {
+                return false;
+            }
+            // some search engines (eg. Bing Images) use the same domain
+            // as an existing search engine (eg. Bing), we must also use the url path
+            $refererPath = '';
+            if (isset($refererParsed['path'])) {
+                $refererPath = $refererParsed['path'];
             }
-            $key = trim(urldecode(implode(' ', $keys)));
-        }
 
-        if ($searchEngineName === 'Google') {
-            // top bar menu
-            $tbm = self::getParameterFromQueryString($query, 'tbm');
-            switch ($tbm) {
-                case 'isch':
-                    $searchEngineName = 'Google Images';
-                    break;
-                case 'vid':
-                    $searchEngineName = 'Google Video';
-                    break;
-                case 'shop':
-                    $searchEngineName = 'Google Shopping';
-                    break;
+            // no search query
+            if (!isset($refererParsed['query'])) {
+                $refererParsed['query'] = '';
             }
-        }
+            $query = $refererParsed['query'];
 
-        if (empty($key)) {
-            foreach ($variableNames as $variableName) {
-                if ($variableName[0] == '/') {
-                    // regular expression match
-                    if (preg_match($variableName, $referrerUrl, $matches)) {
-                        $key = trim(urldecode($matches[1]));
-                        break;
-                    }
+            // Google Referrers URLs sometimes have the fragment which contains the keyword
+            if (!empty($refererParsed['fragment'])) {
+                $query .= '&' . $refererParsed['fragment'];
+            }
+
+            $searchEngines = \Piwik\Core\self::getSearchEngineUrls();
+
+            $hostPattern = \Piwik\Core\self::getLossyUrl($refererHost);
+            if (array_key_exists($refererHost . $refererPath, $searchEngines)) {
+                $refererHost = $refererHost . $refererPath;
+            } elseif (array_key_exists($hostPattern . $refererPath, $searchEngines)) {
+                $refererHost = $hostPattern . $refererPath;
+            } elseif (array_key_exists($hostPattern, $searchEngines)) {
+                $refererHost = $hostPattern;
+            } elseif (!array_key_exists($refererHost, $searchEngines)) {
+                if (!strncmp($query, 'cx=partner-pub-', 15)) {
+                    // Google custom search engine
+                    $refererHost = 'google.com/cse';
+                } elseif (!strncmp($refererPath, '/pemonitorhosted/ws/results/', 28)) {
+                    // private-label search powered by InfoSpace Metasearch
+                    $refererHost = 'wsdsold.infospace.com';
+                } elseif (strpos($refererHost, '.images.search.yahoo.com') != false) {
+                    // Yahoo! Images
+                    $refererHost = 'images.search.yahoo.com';
+                } elseif (strpos($refererHost, '.search.yahoo.com') != false) {
+                    // Yahoo!
+                    $refererHost = 'search.yahoo.com';
                 } else {
-                    // search for keywords now &vname=keyword
-                    $key = self::getParameterFromQueryString($query, $variableName);
-                    $key = trim(urldecode($key));
-
-                    // Special case: Google & empty q parameter
-                    if (empty($key)
-                        && $variableName == 'q'
-
-                        && (
-                            // Google search with no keyword
-                            ($searchEngineName == 'Google'
-                                && ( // First, they started putting an empty q= parameter
-                                    strpos($query, '&q=') !== false
+                    return false;
+                }
+            }
+            $searchEngineName = $searchEngines[$refererHost][0];
+            $variableNames = null;
+            if (isset($searchEngines[$refererHost][1])) {
+                $variableNames = $searchEngines[$refererHost][1];
+            }
+            if (!$variableNames) {
+                $searchEngineNames = \Piwik\Core\self::getSearchEngineNames();
+                $url = $searchEngineNames[$searchEngineName];
+                $variableNames = $searchEngines[$url][1];
+            }
+            if (!is_array($variableNames)) {
+                $variableNames = array($variableNames);
+            }
+
+            $key = null;
+            if ($searchEngineName === 'Google Images'
+                || ($searchEngineName === 'Google' && strpos($referrerUrl, '/imgres') !== false)
+            ) {
+                if (strpos($query, '&prev') !== false) {
+                    $query = urldecode(trim(\Piwik\Core\self::getParameterFromQueryString($query, 'prev')));
+                    $query = str_replace('&', '&amp;', strstr($query, '?'));
+                }
+                $searchEngineName = 'Google Images';
+            } else if ($searchEngineName === 'Google'
+                && (strpos($query, '&as_') !== false || strpos($query, 'as_') === 0)
+            ) {
+                $keys = array();
+                $key = \Piwik\Core\self::getParameterFromQueryString($query, 'as_q');
+                if (!empty($key)) {
+                    array_push($keys, $key);
+                }
+                $key = \Piwik\Core\self::getParameterFromQueryString($query, 'as_oq');
+                if (!empty($key)) {
+                    array_push($keys, str_replace('+', ' OR ', $key));
+                }
+                $key = \Piwik\Core\self::getParameterFromQueryString($query, 'as_epq');
+                if (!empty($key)) {
+                    array_push($keys, "\"$key\"");
+                }
+                $key = \Piwik\Core\self::getParameterFromQueryString($query, 'as_eq');
+                if (!empty($key)) {
+                    array_push($keys, "-$key");
+                }
+                $key = trim(urldecode(implode(' ', $keys)));
+            }
+
+            if ($searchEngineName === 'Google') {
+                // top bar menu
+                $tbm = \Piwik\Core\self::getParameterFromQueryString($query, 'tbm');
+                switch ($tbm) {
+                    case 'isch':
+                        $searchEngineName = 'Google Images';
+                        break;
+                    case 'vid':
+                        $searchEngineName = 'Google Video';
+                        break;
+                    case 'shop':
+                        $searchEngineName = 'Google Shopping';
+                        break;
+                }
+            }
+
+            if (empty($key)) {
+                foreach ($variableNames as $variableName) {
+                    if ($variableName[0] == '/') {
+                        // regular expression match
+                        if (preg_match($variableName, $referrerUrl, $matches)) {
+                            $key = trim(urldecode($matches[1]));
+                            break;
+                        }
+                    } else {
+                        // search for keywords now &vname=keyword
+                        $key = \Piwik\Core\self::getParameterFromQueryString($query, $variableName);
+                        $key = trim(urldecode($key));
+
+                        // Special case: Google & empty q parameter
+                        if (empty($key)
+                            && $variableName == 'q'
+
+                            && (
+                                // Google search with no keyword
+                                ($searchEngineName == 'Google'
+                                    && ( // First, they started putting an empty q= parameter
+                                        strpos($query, '&q=') !== false
                                         || strpos($query, '?q=') !== false
                                         // then they started sending the full host only (no path/query string)
                                         || (empty($query) && (empty($refererPath) || $refererPath == '/') && empty($refererParsed['fragment']))
+                                    )
                                 )
-                            )
                                 // search engines with no keyword
                                 || $searchEngineName == 'Google Images'
                                 || $searchEngineName == 'DuckDuckGo')
-                    ) {
-                        $key = false;
-                    }
-                    if (!empty($key)
-                        || $key === false
-                    ) {
-                        break;
+                        ) {
+                            $key = false;
+                        }
+                        if (!empty($key)
+                            || $key === false
+                        ) {
+                            break;
+                        }
                     }
                 }
             }
-        }
-
-        // $key === false is the special case "No keyword provided" which is a Search engine match
-        if ($key === null
-            || $key === ''
-        ) {
-            return false;
-        }
 
-        if (!empty($key)) {
-            if (function_exists('iconv')
-                && isset($searchEngines[$refererHost][3])
+            // $key === false is the special case "No keyword provided" which is a Search engine match
+            if ($key === null
+                || $key === ''
             ) {
-                // accepts string, array, or comma-separated list string in preferred order
-                $charsets = $searchEngines[$refererHost][3];
-                if (!is_array($charsets)) {
-                    $charsets = explode(',', $charsets);
-                }
+                return false;
+            }
 
-                if (!empty($charsets)) {
-                    $charset = $charsets[0];
-                    if (count($charsets) > 1
-                        && function_exists('mb_detect_encoding')
-                    ) {
-                        $charset = mb_detect_encoding($key, $charsets);
-                        if ($charset === false) {
-                            $charset = $charsets[0];
-                        }
+            if (!empty($key)) {
+                if (function_exists('iconv')
+                    && isset($searchEngines[$refererHost][3])
+                ) {
+                    // accepts string, array, or comma-separated list string in preferred order
+                    $charsets = $searchEngines[$refererHost][3];
+                    if (!is_array($charsets)) {
+                        $charsets = explode(',', $charsets);
                     }
 
-                    $newkey = @iconv($charset, 'UTF-8//IGNORE', $key);
-                    if (!empty($newkey)) {
-                        $key = $newkey;
+                    if (!empty($charsets)) {
+                        $charset = $charsets[0];
+                        if (count($charsets) > 1
+                            && function_exists('mb_detect_encoding')
+                        ) {
+                            $charset = mb_detect_encoding($key, $charsets);
+                            if ($charset === false) {
+                                $charset = $charsets[0];
+                            }
+                        }
+
+                        $newkey = @iconv($charset, 'UTF-8//IGNORE', $key);
+                        if (!empty($newkey)) {
+                            $key = $newkey;
+                        }
                     }
                 }
-            }
-
-            $key = self::mb_strtolower($key);
-        }
 
-        return array(
-            'name'     => $searchEngineName,
-            'keywords' => $key,
-        );
-    }
-
-    /*
-     * System environment
-     */
+                $key = \Piwik\Core\self::mb_strtolower($key);
+            }
 
-    /**
-     * Returns true if PHP was invoked from command-line interface (shell)
-     *
-     * @since added in 0.4.4
-     * @return bool true if PHP invoked as a CGI or from CLI
-     */
-    public static function isPhpCliMode()
-    {
-        $remoteAddr = @$_SERVER['REMOTE_ADDR'];
-        return PHP_SAPI == 'cli' ||
+            return array(
+                'name' => $searchEngineName,
+                'keywords' => $key,
+            );
+        }
+
+        /*
+         * System environment
+         */
+
+        /**
+         * Returns true if PHP was invoked from command-line interface (shell)
+         *
+         * @since added in 0.4.4
+         * @return bool true if PHP invoked as a CGI or from CLI
+         */
+        public static function isPhpCliMode()
+        {
+            $remoteAddr = @$_SERVER['REMOTE_ADDR'];
+            return PHP_SAPI == 'cli' ||
             (!strncmp(PHP_SAPI, 'cgi', 3) && empty($remoteAddr));
-    }
+        }
 
-    /**
-     * Is the current script execution triggered by misc/cron/archive.php ?
-     *
-     * Helpful for error handling: directly throw error without HTML (eg. when DB is down)
-     * @return bool
-     */
-    public static function isArchivePhpTriggered()
-    {
-        return !empty($_GET['trigger'])
+        /**
+         * Is the current script execution triggered by misc/cron/archive.php ?
+         *
+         * Helpful for error handling: directly throw error without HTML (eg. when DB is down)
+         * @return bool
+         */
+        public static function isArchivePhpTriggered()
+        {
+            return !empty($_GET['trigger'])
             && $_GET['trigger'] == 'archivephp';
-    }
+        }
 
-    /**
-     * Assign CLI parameters as if they were REQUEST or GET parameters.
-     * You can trigger Piwik from the command line by
-     * # /usr/bin/php5 /path/to/piwik/index.php -- "module=API&method=Actions.getActions&idSite=1&period=day&date=previous8&format=php"
-     */
-    public static function assignCliParametersToRequest()
-    {
-        if (isset($_SERVER['argc'])
-            && $_SERVER['argc'] > 0
-        ) {
-            for ($i = 1; $i < $_SERVER['argc']; $i++) {
-                parse_str($_SERVER['argv'][$i], $tmp);
-                $_GET = array_merge($_GET, $tmp);
+        /**
+         * Assign CLI parameters as if they were REQUEST or GET parameters.
+         * You can trigger Piwik from the command line by
+         * # /usr/bin/php5 /path/to/piwik/index.php -- "module=API&method=Actions.getActions&idSite=1&period=day&date=previous8&format=php"
+         */
+        public static function assignCliParametersToRequest()
+        {
+            if (isset($_SERVER['argc'])
+                && $_SERVER['argc'] > 0
+            ) {
+                for ($i = 1; $i < $_SERVER['argc']; $i++) {
+                    parse_str($_SERVER['argv'][$i], $tmp);
+                    $_GET = array_merge($_GET, $tmp);
+                }
             }
         }
-    }
-
-    /**
-     * Returns true if running on a Windows operating system
-     *
-     * @since 0.6.5
-     * @return bool true if PHP detects it is running on Windows; else false
-     */
-    public static function isWindows()
-    {
-        return DIRECTORY_SEPARATOR === '\\';
-    }
-
-    /**
-     * Returns true if running on MacOS
-     *
-     * @return bool true if PHP detects it is running on MacOS; else false
-     */
-    public static function isMacOS()
-    {
-        return PHP_OS === 'Darwin';
-    }
-
-    /**
-     * Returns true if running on an Apache web server
-     *
-     * @return bool
-     */
-    public static function isApache()
-    {
-        $apache = isset($_SERVER['SERVER_SOFTWARE']) &&
-            !strncmp($_SERVER['SERVER_SOFTWARE'], 'Apache', 6);
-
-        return $apache;
-    }
-
-    /**
-     * Returns true if running on Microsoft IIS 7 (or above)
-     *
-     * @return bool
-     */
-    public static function isIIS()
-    {
-        $iis = isset($_SERVER['SERVER_SOFTWARE']) &&
-            preg_match('/^Microsoft-IIS\/(.+)/', $_SERVER['SERVER_SOFTWARE'], $matches) &&
-            version_compare($matches[1], '7') >= 0;
-
-        return $iis;
-    }
 
-    /**
-     * Takes a list of fields defining numeric values and returns the corresponding
-     * unnamed parameters to be bound to the field names in the where clause of a SQL query
-     *
-     * @param array|string $fields  array( fieldName1, fieldName2, fieldName3)  Names of the mysql table fields to load
-     * @return string "?, ?, ?"
-     */
-    public static function getSqlStringFieldsArray($fields)
-    {
-        if (is_string($fields)) {
-            $fields = array($fields);
+        /**
+         * Returns true if running on a Windows operating system
+         *
+         * @since 0.6.5
+         * @return bool true if PHP detects it is running on Windows; else false
+         */
+        public static function isWindows()
+        {
+            return DIRECTORY_SEPARATOR === '\\';
+        }
+
+        /**
+         * Returns true if running on MacOS
+         *
+         * @return bool true if PHP detects it is running on MacOS; else false
+         */
+        public static function isMacOS()
+        {
+            return PHP_OS === 'Darwin';
+        }
+
+        /**
+         * Returns true if running on an Apache web server
+         *
+         * @return bool
+         */
+        public static function isApache()
+        {
+            $apache = isset($_SERVER['SERVER_SOFTWARE']) &&
+                !strncmp($_SERVER['SERVER_SOFTWARE'], 'Apache', 6);
+
+            return $apache;
+        }
+
+        /**
+         * Returns true if running on Microsoft IIS 7 (or above)
+         *
+         * @return bool
+         */
+        public static function isIIS()
+        {
+            $iis = isset($_SERVER['SERVER_SOFTWARE']) &&
+                preg_match('/^Microsoft-IIS\/(.+)/', $_SERVER['SERVER_SOFTWARE'], $matches) &&
+                version_compare($matches[1], '7') >= 0;
+
+            return $iis;
+        }
+
+        /**
+         * Takes a list of fields defining numeric values and returns the corresponding
+         * unnamed parameters to be bound to the field names in the where clause of a SQL query
+         *
+         * @param array|string $fields  array( fieldName1, fieldName2, fieldName3)  Names of the mysql table fields to load
+         * @return string "?, ?, ?"
+         */
+        public static function getSqlStringFieldsArray($fields)
+        {
+            if (is_string($fields)) {
+                $fields = array($fields);
+            }
+            $count = count($fields);
+            if ($count == 0) {
+                return "''";
+            }
+            return '?' . str_repeat(',?', $count - 1);
+        }
+
+        /**
+         * Sets outgoing header.
+         *
+         * @param string $header The header.
+         * @param bool $replace Whether to replace existing or not.
+         */
+        public static function sendHeader($header, $replace = true)
+        {
+            if (isset($GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) && $GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) {
+                @header($header, $replace);
+            } else {
+                header($header, $replace);
+            }
         }
-        $count = count($fields);
-        if ($count == 0) {
-            return "''";
+
+        /**
+         * Returns the ID of the current LocationProvider (see UserCountry plugin code) from
+         * the Tracker cache.
+         */
+        public static function getCurrentLocationProviderId()
+        {
+            $cache = Piwik_Tracker_Cache::getCacheGeneral();
+            return empty($cache['currentLocationProviderId'])
+                ? Piwik_UserCountry_LocationProvider_Default::ID
+                : $cache['currentLocationProviderId'];
+        }
+
+        /**
+         * Unprefix class name (if needed)
+         *
+         * @param string $class
+         * @return string
+         */
+        public static function unprefixClass($class)
+        {
+            $lenPrefix = strlen(\Piwik\Core\self::CLASSES_PREFIX);
+            if (!strncmp($class, \Piwik\Core\self::CLASSES_PREFIX, $lenPrefix)) {
+                return substr($class, $lenPrefix);
+            }
+            return $class;
         }
-        return '?' . str_repeat(',?', $count - 1);
     }
-
+}
+namespace {
     /**
-     * Sets outgoing header.
+     * Piwik - Open source web analytics
      *
-     * @param string $header The header.
-     * @param bool $replace Whether to replace existing or not.
+     * @link http://piwik.org
+     * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
+     *
+     * @category Piwik
+     * @package Piwik
      */
-    public static function sendHeader($header, $replace = true)
-    {
-        if (isset($GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) && $GLOBALS['PIWIK_TRACKER_LOCAL_TRACKING']) {
-            @header($header, $replace);
-        } else {
-            header($header, $replace);
-        }
-    }
+    use Piwik\Core\Config;
 
-    /**
-     * Returns the ID of the current LocationProvider (see UserCountry plugin code) from
-     * the Tracker cache.
-     */
-    public static function getCurrentLocationProviderId()
-    {
-        $cache = Piwik_Tracker_Cache::getCacheGeneral();
-        return empty($cache['currentLocationProviderId'])
-            ? Piwik_UserCountry_LocationProvider_Default::ID
-            : $cache['currentLocationProviderId'];
-    }
 
     /**
-     * Unprefix class name (if needed)
+     * Mark orphaned object for garbage collection
      *
-     * @param string $class
-     * @return string
+     * For more information: @link http://dev.piwik.org/trac/ticket/374
+     * @param $var
      */
-    public static function unprefixClass($class)
+    function destroy(&$var)
     {
-        $lenPrefix = strlen(self::CLASSES_PREFIX);
-        if (!strncmp($class, self::CLASSES_PREFIX, $lenPrefix)) {
-            return substr($class, $lenPrefix);
+        if (is_object($var) && method_exists($var, '__destruct')) {
+            $var->__destruct();
         }
-        return $class;
+        unset($var);
+        $var = null;
     }
-}
-
-/**
- * Mark orphaned object for garbage collection
- *
- * For more information: @link http://dev.piwik.org/trac/ticket/374
- * @param $var
- */
-function destroy(&$var)
-{
-    if (is_object($var) && method_exists($var, '__destruct')) {
-        $var->__destruct();
-    }
-    unset($var);
-    $var = null;
-}
 
-if (!function_exists('printDebug')) {
-    function printDebug($info = '')
-    {
-        if (isset($GLOBALS['PIWIK_TRACKER_DEBUG']) && $GLOBALS['PIWIK_TRACKER_DEBUG']) {
-            if (is_array($info) || is_object($info)) {
-                print("<pre>");
-                print(htmlspecialchars(var_export($info, true), ENT_QUOTES));
-                print("</pre>");
-            } else {
-                print(htmlspecialchars($info, ENT_QUOTES) . "<br />\n");
+    if (!function_exists('printDebug')) {
+        function printDebug($info = '')
+        {
+            if (isset($GLOBALS['PIWIK_TRACKER_DEBUG']) && $GLOBALS['PIWIK_TRACKER_DEBUG']) {
+                if (is_array($info) || is_object($info)) {
+                    print("<pre>");
+                    print(htmlspecialchars(var_export($info, true), ENT_QUOTES));
+                    print("</pre>");
+                } else {
+                    print(htmlspecialchars($info, ENT_QUOTES) . "<br />\n");
+                }
             }
         }
     }
diff --git a/core/Controller.php b/core/Controller.php
index b2e4dfa295..bfb37b59d8 100644
--- a/core/Controller.php
+++ b/core/Controller.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Parent class of all plugins Controllers (located in /plugins/PluginName/Controller.php
diff --git a/core/Cookie.php b/core/Cookie.php
index 69cd83c188..8165a6bc36 100644
--- a/core/Cookie.php
+++ b/core/Cookie.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Simple class to handle the cookies:
diff --git a/core/DataAccess/ArchiveSelector.php b/core/DataAccess/ArchiveSelector.php
index 299b292a49..46b677d7e8 100644
--- a/core/DataAccess/ArchiveSelector.php
+++ b/core/DataAccess/ArchiveSelector.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Data Access object used to query archives
diff --git a/core/DataAccess/ArchiveTableCreator.php b/core/DataAccess/ArchiveTableCreator.php
index d7c3446654..e501a9b28a 100644
--- a/core/DataAccess/ArchiveTableCreator.php
+++ b/core/DataAccess/ArchiveTableCreator.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/core/DataAccess/ArchiveWriter.php b/core/DataAccess/ArchiveWriter.php
index 167e3bcc92..413f9d76eb 100644
--- a/core/DataAccess/ArchiveWriter.php
+++ b/core/DataAccess/ArchiveWriter.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class is used to create a new Archive.
diff --git a/core/DataAccess/LogAggregator.php b/core/DataAccess/LogAggregator.php
index bac194ea0b..2992aa203c 100644
--- a/core/DataAccess/LogAggregator.php
+++ b/core/DataAccess/LogAggregator.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class queries the Visitor logs tables (visits, actions, conversions, ecommerce)
diff --git a/core/DataTable/Renderer/Csv.php b/core/DataTable/Renderer/Csv.php
index ba8a248849..555f35a71a 100644
--- a/core/DataTable/Renderer/Csv.php
+++ b/core/DataTable/Renderer/Csv.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * CSV export
diff --git a/core/DataTable/Renderer/Json.php b/core/DataTable/Renderer/Json.php
index bc973ea93a..6d815ea4bc 100644
--- a/core/DataTable/Renderer/Json.php
+++ b/core/DataTable/Renderer/Json.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * JSON export.
diff --git a/core/DataTable/Renderer/Rss.php b/core/DataTable/Renderer/Rss.php
index a9e6376455..4ea2c0453c 100644
--- a/core/DataTable/Renderer/Rss.php
+++ b/core/DataTable/Renderer/Rss.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * RSS Feed.
diff --git a/core/Db/Schema/Myisam.php b/core/Db/Schema/Myisam.php
index 248823e2d6..c8d6d9a040 100644
--- a/core/Db/Schema/Myisam.php
+++ b/core/Db/Schema/Myisam.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * MySQL schema
diff --git a/core/FrontController.php b/core/FrontController.php
index fb0df9b928..c201546ed7 100644
--- a/core/FrontController.php
+++ b/core/FrontController.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see core/PluginsManager.php
diff --git a/core/Http.php b/core/Http.php
index 00cc73618a..60f8ea6e65 100644
--- a/core/Http.php
+++ b/core/Http.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Server-side http client to retrieve content from remote servers, and optionally save to a local file.
diff --git a/core/IP.php b/core/IP.php
index 86f7555b80..3e528eb628 100644
--- a/core/IP.php
+++ b/core/IP.php
@@ -10,6 +10,7 @@
  */
 
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 if (Piwik_Common::isWindows() || !function_exists('inet_ntop')) {
     function _inet_ntop($in_addr)
diff --git a/core/Log.php b/core/Log.php
index 40ec5e88cf..2707b4a19c 100644
--- a/core/Log.php
+++ b/core/Log.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
@@ -175,7 +176,7 @@ class Piwik_Log_Formatter_ScreenFormatter implements Zend_Log_Formatter_Interfac
     function formatEvent($event)
     {
         // no injection in error messages, backtrace when displayed on screen
-        return array_map(array('Piwik_Common', 'sanitizeInputValue'), $event);
+        return array_map(array('Piwik\Core\Piwik_Common', 'sanitizeInputValue'), $event);
     }
 
     function format($string)
diff --git a/core/Log/Exception.php b/core/Log/Exception.php
index b18233b3e2..2865ad74a3 100644
--- a/core/Log/Exception.php
+++ b/core/Log/Exception.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class used to log an exception event.
diff --git a/core/Log/Message.php b/core/Log/Message.php
index f8ca15ba4c..6852f572c0 100644
--- a/core/Log/Message.php
+++ b/core/Log/Message.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class used to log a standard message event.
diff --git a/core/Menu/Abstract.php b/core/Menu/Abstract.php
index 4388a70032..1547a27eae 100644
--- a/core/Menu/Abstract.php
+++ b/core/Menu/Abstract.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik_Menu
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_Menu
diff --git a/core/Nonce.php b/core/Nonce.php
index f7763ee15b..4cb6b440d6 100644
--- a/core/Nonce.php
+++ b/core/Nonce.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Nonce class.
diff --git a/core/Option.php b/core/Option.php
index ab3a1c672f..179e25c23c 100644
--- a/core/Option.php
+++ b/core/Option.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik_Option provides a very simple mechanism to save/retrieve key-values pair
diff --git a/core/Period/Range.php b/core/Period/Range.php
index 27ef4bd015..e126ec835b 100644
--- a/core/Period/Range.php
+++ b/core/Period/Range.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * from a starting date to an ending date
diff --git a/core/Piwik.php b/core/Piwik.php
index d33725d09f..b377cd54a7 100644
--- a/core/Piwik.php
+++ b/core/Piwik.php
@@ -16,7 +16,7 @@ use Piwik\Core\Config;
 use Piwik_Access;
 use Piwik_Access_NoAccessException;
 use Piwik_AssetManager;
-use Piwik_Common;
+use Piwik\Core\Piwik_Common;
 use Piwik_Db_Adapter;
 use Piwik_Db_Schema;
 use Piwik_Log_APICall;
diff --git a/core/Plugin.php b/core/Plugin.php
index 2fbf45923a..582bb7ff51 100644
--- a/core/Plugin.php
+++ b/core/Plugin.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see core/Plugin/MetadataLoader.php
diff --git a/core/Plugin/MetadataLoader.php b/core/Plugin/MetadataLoader.php
index 1fe999edce..e96ce56ec4 100644
--- a/core/Plugin/MetadataLoader.php
+++ b/core/Plugin/MetadataLoader.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see core/Version.php
diff --git a/core/PluginsArchiver.php b/core/PluginsArchiver.php
index 782e2536cb..f568ac5459 100644
--- a/core/PluginsArchiver.php
+++ b/core/PluginsArchiver.php
@@ -10,6 +10,7 @@
  * @package Piwik_PluginArchiver
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Plugins that archive metrics for websites can implement an Archiver that extends this class
diff --git a/core/PluginsManager.php b/core/PluginsManager.php
index b256d65c0b..0d03e46078 100644
--- a/core/PluginsManager.php
+++ b/core/PluginsManager.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see core/Menu/Abstract.php
diff --git a/core/ProxyHeaders.php b/core/ProxyHeaders.php
index 5eb05b5076..4cd540e4da 100644
--- a/core/ProxyHeaders.php
+++ b/core/ProxyHeaders.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Proxy headers
diff --git a/core/ReportRenderer/Pdf.php b/core/ReportRenderer/Pdf.php
index a7e65d45c0..85a3c9dbda 100644
--- a/core/ReportRenderer/Pdf.php
+++ b/core/ReportRenderer/Pdf.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik_ReportRenderer
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see libs/tcpdf
diff --git a/core/Segment.php b/core/Segment.php
index dd3654b767..f4a2be255e 100644
--- a/core/Segment.php
+++ b/core/Segment.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/core/Session.php b/core/Session.php
index f08df94c60..7072c26c53 100644
--- a/core/Session.php
+++ b/core/Session.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Session initialization.
diff --git a/core/Session/Namespace.php b/core/Session/Namespace.php
index 3c18aa06db..0b65168ca4 100644
--- a/core/Session/Namespace.php
+++ b/core/Session/Namespace.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Session namespace.
diff --git a/core/Tracker.php b/core/Tracker.php
index fd8bb92bf5..f375ea35e4 100644
--- a/core/Tracker.php
+++ b/core/Tracker.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class used by the logging script piwik.php called by the javascript tag.
diff --git a/core/Tracker/Action.php b/core/Tracker/Action.php
index 5da8309682..b98f284f78 100644
--- a/core/Tracker/Action.php
+++ b/core/Tracker/Action.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Interface of the Action object.
diff --git a/core/Tracker/Db.php b/core/Tracker/Db.php
index acccd4e858..6ddb7b5183 100644
--- a/core/Tracker/Db.php
+++ b/core/Tracker/Db.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Simple database wrapper.
diff --git a/core/Tracker/GoalManager.php b/core/Tracker/GoalManager.php
index 4a33837ac4..1f47cfcef5 100644
--- a/core/Tracker/GoalManager.php
+++ b/core/Tracker/GoalManager.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/Tracker/Referer.php b/core/Tracker/Referer.php
index c941e0e480..85a456f95c 100644
--- a/core/Tracker/Referer.php
+++ b/core/Tracker/Referer.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/Tracker/Request.php b/core/Tracker/Request.php
index f1a6757806..243e6e4462 100644
--- a/core/Tracker/Request.php
+++ b/core/Tracker/Request.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/core/Tracker/Visit.php b/core/Tracker/Visit.php
index 27457ad860..7cdcff57bf 100644
--- a/core/Tracker/Visit.php
+++ b/core/Tracker/Visit.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/Tracker/VisitExcluded.php b/core/Tracker/VisitExcluded.php
index 64c9c8e8cc..062020dbe7 100644
--- a/core/Tracker/VisitExcluded.php
+++ b/core/Tracker/VisitExcluded.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class contains the logic to exclude some visitors from being tracked as per user settings
diff --git a/core/Translate.php b/core/Translate.php
index 95e6b9551f..a1ac503edd 100644
--- a/core/Translate.php
+++ b/core/Translate.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/TranslationWriter.php b/core/TranslationWriter.php
index e47ae10f89..c7b073712d 100644
--- a/core/TranslationWriter.php
+++ b/core/TranslationWriter.php
@@ -9,6 +9,7 @@
  * @package Piwik
  *
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Write translations to file
diff --git a/core/Twig.php b/core/Twig.php
index 023653959b..6af9f80413 100644
--- a/core/Twig.php
+++ b/core/Twig.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 
 /**
diff --git a/core/UpdateCheck.php b/core/UpdateCheck.php
index 7e94922f32..62fcc33415 100644
--- a/core/UpdateCheck.php
+++ b/core/UpdateCheck.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class to check if a newer version of Piwik is available
diff --git a/core/Updater.php b/core/Updater.php
index 4b86b7d9ed..9ec42e8b59 100644
--- a/core/Updater.php
+++ b/core/Updater.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see core/Option.php
diff --git a/core/Updates/0.2.10.php b/core/Updates/0.2.10.php
index 2f2f289c9a..627c626af8 100644
--- a/core/Updates/0.2.10.php
+++ b/core/Updates/0.2.10.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.12.php b/core/Updates/0.2.12.php
index f6ac41e839..72bde57ba1 100644
--- a/core/Updates/0.2.12.php
+++ b/core/Updates/0.2.12.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.13.php b/core/Updates/0.2.13.php
index 1572cd73bd..a70d1d68b8 100644
--- a/core/Updates/0.2.13.php
+++ b/core/Updates/0.2.13.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.24.php b/core/Updates/0.2.24.php
index 594a461805..e71b829bcd 100644
--- a/core/Updates/0.2.24.php
+++ b/core/Updates/0.2.24.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.27.php b/core/Updates/0.2.27.php
index 8aac68fe3a..dd43c0eb10 100644
--- a/core/Updates/0.2.27.php
+++ b/core/Updates/0.2.27.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.32.php b/core/Updates/0.2.32.php
index 7a3bbfac42..921a48ed79 100644
--- a/core/Updates/0.2.32.php
+++ b/core/Updates/0.2.32.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.33.php b/core/Updates/0.2.33.php
index cdf7551092..ac82c5d5ac 100644
--- a/core/Updates/0.2.33.php
+++ b/core/Updates/0.2.33.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.35.php b/core/Updates/0.2.35.php
index 9f0f80abe7..70e4c17fdd 100644
--- a/core/Updates/0.2.35.php
+++ b/core/Updates/0.2.35.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.2.37.php b/core/Updates/0.2.37.php
index ca859c5f94..adb9096327 100644
--- a/core/Updates/0.2.37.php
+++ b/core/Updates/0.2.37.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.4.1.php b/core/Updates/0.4.1.php
index 60223f845e..bae1d4c793 100644
--- a/core/Updates/0.4.1.php
+++ b/core/Updates/0.4.1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.4.2.php b/core/Updates/0.4.2.php
index e21135068b..7b629c97ca 100644
--- a/core/Updates/0.4.2.php
+++ b/core/Updates/0.4.2.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.4.php b/core/Updates/0.4.php
index dcbfffd578..5b578e7800 100644
--- a/core/Updates/0.4.php
+++ b/core/Updates/0.4.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.5.4.php b/core/Updates/0.5.4.php
index 45e69d1c18..bde45af871 100644
--- a/core/Updates/0.5.4.php
+++ b/core/Updates/0.5.4.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.5.5.php b/core/Updates/0.5.5.php
index 923f14cd2f..e781f02db2 100644
--- a/core/Updates/0.5.5.php
+++ b/core/Updates/0.5.5.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.5.php b/core/Updates/0.5.php
index 7877fba142..1a01bcf5f1 100644
--- a/core/Updates/0.5.php
+++ b/core/Updates/0.5.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.6-rc1.php b/core/Updates/0.6-rc1.php
index e4dc34d522..b1e83f3d3b 100644
--- a/core/Updates/0.6-rc1.php
+++ b/core/Updates/0.6-rc1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.6.3.php b/core/Updates/0.6.3.php
index 0cb43f125f..82041c3620 100644
--- a/core/Updates/0.6.3.php
+++ b/core/Updates/0.6.3.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.7.php b/core/Updates/0.7.php
index 685fe7c962..fa153883a9 100644
--- a/core/Updates/0.7.php
+++ b/core/Updates/0.7.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/0.9.1.php b/core/Updates/0.9.1.php
index 04658a23c5..31998ad17d 100644
--- a/core/Updates/0.9.1.php
+++ b/core/Updates/0.9.1.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.10.2-b1.php b/core/Updates/1.10.2-b1.php
index 1796863297..10a28c6143 100755
--- a/core/Updates/1.10.2-b1.php
+++ b/core/Updates/1.10.2-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.10.2-b2.php b/core/Updates/1.10.2-b2.php
index 26cfd3e004..7c05ea806c 100644
--- a/core/Updates/1.10.2-b2.php
+++ b/core/Updates/1.10.2-b2.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.12-b1.php b/core/Updates/1.12-b1.php
index 6fb3551d4f..c91dbb1df0 100644
--- a/core/Updates/1.12-b1.php
+++ b/core/Updates/1.12-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.12-b16.php b/core/Updates/1.12-b16.php
index 8ac3df70da..fb5ba2a9a6 100644
--- a/core/Updates/1.12-b16.php
+++ b/core/Updates/1.12-b16.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.2-rc1.php b/core/Updates/1.2-rc1.php
index ac6bbcb0e3..7f36539f7b 100644
--- a/core/Updates/1.2-rc1.php
+++ b/core/Updates/1.2-rc1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.2.3.php b/core/Updates/1.2.3.php
index 177b85a092..066cea1a82 100644
--- a/core/Updates/1.2.3.php
+++ b/core/Updates/1.2.3.php
@@ -9,6 +9,7 @@
  * @package Updates
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.2.5-rc1.php b/core/Updates/1.2.5-rc1.php
index 90b0399589..d17bfd3825 100644
--- a/core/Updates/1.2.5-rc1.php
+++ b/core/Updates/1.2.5-rc1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.2.5-rc7.php b/core/Updates/1.2.5-rc7.php
index aafc70c7a9..b1da1cd65a 100644
--- a/core/Updates/1.2.5-rc7.php
+++ b/core/Updates/1.2.5-rc7.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.4-rc1.php b/core/Updates/1.4-rc1.php
index ce99c40497..52e5589959 100644
--- a/core/Updates/1.4-rc1.php
+++ b/core/Updates/1.4-rc1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.4-rc2.php b/core/Updates/1.4-rc2.php
index b5273b0505..f38e8208a0 100644
--- a/core/Updates/1.4-rc2.php
+++ b/core/Updates/1.4-rc2.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.5-b1.php b/core/Updates/1.5-b1.php
index 7156719e3d..ba72c69a3f 100644
--- a/core/Updates/1.5-b1.php
+++ b/core/Updates/1.5-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.5-b2.php b/core/Updates/1.5-b2.php
index fee8f86e9a..4711c7a97f 100644
--- a/core/Updates/1.5-b2.php
+++ b/core/Updates/1.5-b2.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.5-b3.php b/core/Updates/1.5-b3.php
index e7d76bd2e5..2beb4ad583 100644
--- a/core/Updates/1.5-b3.php
+++ b/core/Updates/1.5-b3.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.5-b4.php b/core/Updates/1.5-b4.php
index 15479fb029..dcf67cf04d 100644
--- a/core/Updates/1.5-b4.php
+++ b/core/Updates/1.5-b4.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.5-b5.php b/core/Updates/1.5-b5.php
index c00eac3dce..87913e6153 100644
--- a/core/Updates/1.5-b5.php
+++ b/core/Updates/1.5-b5.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.6-b1.php b/core/Updates/1.6-b1.php
index 57e1deb889..f8d87d9945 100644
--- a/core/Updates/1.6-b1.php
+++ b/core/Updates/1.6-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.7-b1.php b/core/Updates/1.7-b1.php
index f5f084f892..62632a5183 100644
--- a/core/Updates/1.7-b1.php
+++ b/core/Updates/1.7-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.7.2-rc5.php b/core/Updates/1.7.2-rc5.php
index 6d9e88a8b2..d526d5f708 100644
--- a/core/Updates/1.7.2-rc5.php
+++ b/core/Updates/1.7.2-rc5.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.7.2-rc7.php b/core/Updates/1.7.2-rc7.php
index c901f37a7d..b6a25fae96 100755
--- a/core/Updates/1.7.2-rc7.php
+++ b/core/Updates/1.7.2-rc7.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.8.3-b1.php b/core/Updates/1.8.3-b1.php
index 2dfe336559..9605f15702 100644
--- a/core/Updates/1.8.3-b1.php
+++ b/core/Updates/1.8.3-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik‚
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.8.4-b1.php b/core/Updates/1.8.4-b1.php
index 2c0b5138c7..58b8139647 100644
--- a/core/Updates/1.8.4-b1.php
+++ b/core/Updates/1.8.4-b1.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.9-b16.php b/core/Updates/1.9-b16.php
index b4ec364801..dade3e37b3 100755
--- a/core/Updates/1.9-b16.php
+++ b/core/Updates/1.9-b16.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.9-b19.php b/core/Updates/1.9-b19.php
index e5fc17f1ba..9dc79c3d4a 100755
--- a/core/Updates/1.9-b19.php
+++ b/core/Updates/1.9-b19.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.9-b9.php b/core/Updates/1.9-b9.php
index f986381d97..c70169d3ef 100755
--- a/core/Updates/1.9-b9.php
+++ b/core/Updates/1.9-b9.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.9.1-b2.php b/core/Updates/1.9.1-b2.php
index af9954be9a..bf478a6fc8 100644
--- a/core/Updates/1.9.1-b2.php
+++ b/core/Updates/1.9.1-b2.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Updates/1.9.3-b8.php b/core/Updates/1.9.3-b8.php
index e0d29e0acd..67e296ea81 100755
--- a/core/Updates/1.9.3-b8.php
+++ b/core/Updates/1.9.3-b8.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Updates
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Updates
diff --git a/core/Url.php b/core/Url.php
index b4eacdff83..b31d854935 100644
--- a/core/Url.php
+++ b/core/Url.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Class to retrieve absolute URL or URI components of the current URL,
diff --git a/core/View.php b/core/View.php
index ea4a43b8b3..8047dc6230 100644
--- a/core/View.php
+++ b/core/View.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Transition for pre-Piwik 0.4.4
diff --git a/core/ViewDataTable.php b/core/ViewDataTable.php
index 46eabeecc7..91da163f47 100644
--- a/core/ViewDataTable.php
+++ b/core/ViewDataTable.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class is used to load (from the API) and customize the output of a given DataTable.
diff --git a/core/ViewDataTable/GenerateGraphData.php b/core/ViewDataTable/GenerateGraphData.php
index eab6293b63..8658093102 100644
--- a/core/ViewDataTable/GenerateGraphData.php
+++ b/core/ViewDataTable/GenerateGraphData.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Reads data from the API and prepares data to give to the renderer Piwik_Visualization_Chart.
diff --git a/core/ViewDataTable/GenerateGraphData/ChartEvolution.php b/core/ViewDataTable/GenerateGraphData/ChartEvolution.php
index 9237a5e427..d0cbb29f3e 100644
--- a/core/ViewDataTable/GenerateGraphData/ChartEvolution.php
+++ b/core/ViewDataTable/GenerateGraphData/ChartEvolution.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik_ViewDataTable_GenerateGraphData for the Evolution graph (eg. Last 30 days visits) using Piwik_Visualization_Chart_Evolution
diff --git a/core/ViewDataTable/GenerateGraphHTML.php b/core/ViewDataTable/GenerateGraphHTML.php
index f7b580eb3d..f34390404d 100644
--- a/core/ViewDataTable/GenerateGraphHTML.php
+++ b/core/ViewDataTable/GenerateGraphHTML.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class generates the HTML code to embed graphs in the page.
diff --git a/core/ViewDataTable/GenerateGraphHTML/ChartEvolution.php b/core/ViewDataTable/GenerateGraphHTML/ChartEvolution.php
index 73d0f3a167..aec31a7a3a 100644
--- a/core/ViewDataTable/GenerateGraphHTML/ChartEvolution.php
+++ b/core/ViewDataTable/GenerateGraphHTML/ChartEvolution.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Generates HTML embed for the Evolution graph
diff --git a/core/ViewDataTable/HtmlTable.php b/core/ViewDataTable/HtmlTable.php
index 08df07ffab..6267a2aca2 100644
--- a/core/ViewDataTable/HtmlTable.php
+++ b/core/ViewDataTable/HtmlTable.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Outputs an AJAX Table for a given DataTable.
diff --git a/core/ViewDataTable/HtmlTable/Goals.php b/core/ViewDataTable/HtmlTable/Goals.php
index 21740d0905..325253872f 100644
--- a/core/ViewDataTable/HtmlTable/Goals.php
+++ b/core/ViewDataTable/HtmlTable/Goals.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik
diff --git a/core/ViewDataTable/Sparkline.php b/core/ViewDataTable/Sparkline.php
index 062a9267b2..09a4d7373a 100644
--- a/core/ViewDataTable/Sparkline.php
+++ b/core/ViewDataTable/Sparkline.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Reads the requested DataTable from the API and prepare data for the Sparkline view.
diff --git a/core/Visualization/Chart.php b/core/Visualization/Chart.php
index 4cf3de47db..9c8f53700d 100644
--- a/core/Visualization/Chart.php
+++ b/core/Visualization/Chart.php
@@ -9,6 +9,7 @@
  * @package Piwik
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Generates the data in the Open Flash Chart format, from the given data.
diff --git a/core/Visualization/Cloud.php b/core/Visualization/Cloud.php
index c00c088e39..3458c70605 100644
--- a/core/Visualization/Cloud.php
+++ b/core/Visualization/Cloud.php
@@ -8,6 +8,7 @@
  * @category Piwik
  * @package Piwik
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Generates a tag cloud from a given data array.
diff --git a/libs/upgradephp/upgrade.php b/libs/upgradephp/upgrade.php
index c0d187aaca..e553110d36 100644
--- a/libs/upgradephp/upgrade.php
+++ b/libs/upgradephp/upgrade.php
@@ -35,6 +35,7 @@
  * Any contribution is appreciated. <milky*users#sf#net>
  *
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @since PHP 5
diff --git a/misc/cron/archive.php b/misc/cron/archive.php
index 2fbf894783..8985087491 100644
--- a/misc/cron/archive.php
+++ b/misc/cron/archive.php
@@ -1,6 +1,7 @@
 <?php
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 $USAGE = "
 Usage: 
diff --git a/misc/others/geoipUpdateRows.php b/misc/others/geoipUpdateRows.php
index 747cf4d62e..137b2bd1d0 100755
--- a/misc/others/geoipUpdateRows.php
+++ b/misc/others/geoipUpdateRows.php
@@ -1,6 +1,7 @@
 <?php
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 ini_set("memory_limit", "512M");
 error_reporting(E_ALL | E_NOTICE);
diff --git a/misc/others/iframeWidget_localhost.php b/misc/others/iframeWidget_localhost.php
index d01ba89227..7b4d87db9d 100644
--- a/misc/others/iframeWidget_localhost.php
+++ b/misc/others/iframeWidget_localhost.php
@@ -1,4 +1,6 @@
 <?php
+use Piwik\Core\Piwik_Common;
+
 exit;
 $date = date('Y-m-d');
 $period = 'month';
diff --git a/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php b/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php
index ac2539eca7..1b6ecf5361 100644
--- a/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php
+++ b/misc/others/test_cookies_GenerateHundredsWebsitesAndVisits.php
@@ -2,6 +2,7 @@
 // Script that creates 100 websites, then outputs a IMG that records a pageview in each website
 // Used initially to test how to handle cookies for this use case (see http://dev.piwik.org/trac/ticket/409)
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 exit;
 
diff --git a/misc/others/test_generateLotsVisitsWebsites.php b/misc/others/test_generateLotsVisitsWebsites.php
index 9a07768388..44d5bc031a 100644
--- a/misc/others/test_generateLotsVisitsWebsites.php
+++ b/misc/others/test_generateLotsVisitsWebsites.php
@@ -1,6 +1,7 @@
 <?php
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 define('PIWIK_INCLUDE_PATH', realpath(dirname(__FILE__) . "/../.."));
 define('PIWIK_ENABLE_DISPATCH', false);
diff --git a/plugins/API/API.php b/plugins/API/API.php
index 203d8295ff..a08e046c4b 100644
--- a/plugins/API/API.php
+++ b/plugins/API/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_API
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_API
@@ -552,7 +553,7 @@ class Piwik_API_API
         }
 
         $urls = array_map('urldecode', $urls);
-        $urls = array_map(array('Piwik_Common', 'unsanitizeInputValue'), $urls);
+        $urls = array_map(array('Piwik\Core\Piwik_Common', 'unsanitizeInputValue'), $urls);
 
         $result = array();
         foreach ($urls as $url) {
@@ -628,7 +629,7 @@ class Piwik_API_API
         arsort($values);
         $values = array_keys($values);
 
-        $values = array_map(array('Piwik_Common', 'unsanitizeInputValue'), $values);
+        $values = array_map(array('Piwik\Core\Piwik_Common', 'unsanitizeInputValue'), $values);
 
         $values = array_slice($values, 0, $maxSuggestionsToReturn);
         return $values;
diff --git a/plugins/API/Controller.php b/plugins/API/Controller.php
index a586b43b1a..8d70af3650 100644
--- a/plugins/API/Controller.php
+++ b/plugins/API/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_API
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/API/ProcessedReport.php b/plugins/API/ProcessedReport.php
index 3657ffab25..318929f1ce 100644
--- a/plugins/API/ProcessedReport.php
+++ b/plugins/API/ProcessedReport.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/API/RowEvolution.php b/plugins/API/RowEvolution.php
index cc762d11de..dfc24d6a6a 100644
--- a/plugins/API/RowEvolution.php
+++ b/plugins/API/RowEvolution.php
@@ -9,6 +9,7 @@
  * @package Piwik_API
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * This class generates a Row evolution dataset, from input request
diff --git a/plugins/Actions/API.php b/plugins/Actions/API.php
index 5a4ad1e181..25a21a2d8d 100644
--- a/plugins/Actions/API.php
+++ b/plugins/Actions/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_Actions
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The Actions API lets you request reports for all your Visitor Actions: Page URLs, Page titles (Piwik Events),
diff --git a/plugins/Actions/Actions.php b/plugins/Actions/Actions.php
index 0ad2593184..eb2171397a 100644
--- a/plugins/Actions/Actions.php
+++ b/plugins/Actions/Actions.php
@@ -9,6 +9,7 @@
  * @package Piwik_Actions
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Actions plugin
diff --git a/plugins/Annotations/Controller.php b/plugins/Annotations/Controller.php
index 3b88fadb9d..32ad2b4931 100755
--- a/plugins/Annotations/Controller.php
+++ b/plugins/Annotations/Controller.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_Annotations
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Controller for the Annotations plugin.
diff --git a/plugins/AnonymizeIP/AnonymizeIP.php b/plugins/AnonymizeIP/AnonymizeIP.php
index 4e14459fd7..e50c7386a1 100644
--- a/plugins/AnonymizeIP/AnonymizeIP.php
+++ b/plugins/AnonymizeIP/AnonymizeIP.php
@@ -9,6 +9,7 @@
  * @package Piwik_AnonymizeIP
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Anonymize visitor IP addresses to comply with the privacy laws/guidelines in countries, such as Germany.
diff --git a/plugins/CoreAdminHome/API.php b/plugins/CoreAdminHome/API.php
index 08108363e4..07cb1218e8 100644
--- a/plugins/CoreAdminHome/API.php
+++ b/plugins/CoreAdminHome/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_CoreAdminHome
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_CoreAdminHome
diff --git a/plugins/CoreAdminHome/Controller.php b/plugins/CoreAdminHome/Controller.php
index af0ef50a86..69344d2771 100644
--- a/plugins/CoreAdminHome/Controller.php
+++ b/plugins/CoreAdminHome/Controller.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/CoreHome/Controller.php b/plugins/CoreHome/Controller.php
index ee30059e45..c7758373d4 100644
--- a/plugins/CoreHome/Controller.php
+++ b/plugins/CoreHome/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_CoreHome
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php b/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php
index 1e761a0aae..cb4c49ab8a 100644
--- a/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php
+++ b/plugins/CoreHome/DataTableRowAction/MultiRowEvolution.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_CoreHome
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * MULTI ROW EVOLUTION
diff --git a/plugins/CoreHome/DataTableRowAction/RowEvolution.php b/plugins/CoreHome/DataTableRowAction/RowEvolution.php
index 9b8d958c88..22da9411f7 100644
--- a/plugins/CoreHome/DataTableRowAction/RowEvolution.php
+++ b/plugins/CoreHome/DataTableRowAction/RowEvolution.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_CoreHome
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * ROW EVOLUTION
diff --git a/plugins/CorePluginsAdmin/Controller.php b/plugins/CorePluginsAdmin/Controller.php
index 0bfb838a87..692ee1abd1 100644
--- a/plugins/CorePluginsAdmin/Controller.php
+++ b/plugins/CorePluginsAdmin/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_CorePluginsAdmin
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/CoreUpdater/Controller.php b/plugins/CoreUpdater/Controller.php
index dcf109113d..3d4040a6a5 100644
--- a/plugins/CoreUpdater/Controller.php
+++ b/plugins/CoreUpdater/Controller.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/CoreUpdater/CoreUpdater.php b/plugins/CoreUpdater/CoreUpdater.php
index e3aab1affb..72d5269000 100644
--- a/plugins/CoreUpdater/CoreUpdater.php
+++ b/plugins/CoreUpdater/CoreUpdater.php
@@ -9,6 +9,7 @@
  * @package Piwik_CoreUpdater
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/CustomVariables/Archiver.php b/plugins/CustomVariables/Archiver.php
index 8d8d018d67..bae7cb7066 100644
--- a/plugins/CustomVariables/Archiver.php
+++ b/plugins/CustomVariables/Archiver.php
@@ -1,5 +1,5 @@
 <?php
-use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/DBStats/API.php b/plugins/DBStats/API.php
index 81f0368749..8e99fc8fec 100644
--- a/plugins/DBStats/API.php
+++ b/plugins/DBStats/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_DBStats
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/DBStats/MySQLMetadataProvider.php
diff --git a/plugins/DBStats/MySQLMetadataProvider.php b/plugins/DBStats/MySQLMetadataProvider.php
index 80bc9be7c4..90185312cb 100755
--- a/plugins/DBStats/MySQLMetadataProvider.php
+++ b/plugins/DBStats/MySQLMetadataProvider.php
@@ -9,6 +9,7 @@
  * @package Piwik_DBStats
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Utility class that provides general information about databases, including the size of
diff --git a/plugins/Dashboard/Controller.php b/plugins/Dashboard/Controller.php
index 10b64bc164..589eb29e73 100644
--- a/plugins/Dashboard/Controller.php
+++ b/plugins/Dashboard/Controller.php
@@ -8,6 +8,7 @@
  * @package  Piwik_Dashboard
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Dashboard Controller
diff --git a/plugins/Dashboard/Dashboard.php b/plugins/Dashboard/Dashboard.php
index 25d33fd5f6..f6a0274dfe 100644
--- a/plugins/Dashboard/Dashboard.php
+++ b/plugins/Dashboard/Dashboard.php
@@ -9,6 +9,7 @@
  * @package Piwik_Dashboard
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_Dashboard
diff --git a/plugins/DevicesDetection/Controller.php b/plugins/DevicesDetection/Controller.php
index a76ede7038..9d09a35abe 100644
--- a/plugins/DevicesDetection/Controller.php
+++ b/plugins/DevicesDetection/Controller.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/DevicesDetection/DevicesDetection.php b/plugins/DevicesDetection/DevicesDetection.php
index 85324d7cbd..31c12d6b07 100644
--- a/plugins/DevicesDetection/DevicesDetection.php
+++ b/plugins/DevicesDetection/DevicesDetection.php
@@ -10,6 +10,7 @@
  * @package Piwik_DevicesDetection
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 require_once PIWIK_INCLUDE_PATH . "/plugins/DevicesDetection/UserAgentParserEnhanced/UserAgentParserEnhanced.php";
 require_once PIWIK_INCLUDE_PATH . '/plugins/DevicesDetection/functions.php';
diff --git a/plugins/ExamplePlugin/Controller.php b/plugins/ExamplePlugin/Controller.php
index c44edb73bf..73329f9270 100644
--- a/plugins/ExamplePlugin/Controller.php
+++ b/plugins/ExamplePlugin/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_ExamplePlugin
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/ExampleUI/Controller.php b/plugins/ExampleUI/Controller.php
index 1535c07220..1cb48ecb5e 100644
--- a/plugins/ExampleUI/Controller.php
+++ b/plugins/ExampleUI/Controller.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_ExampleUI
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_ExampleUI
diff --git a/plugins/Feedback/Controller.php b/plugins/Feedback/Controller.php
index 6d28c054f9..783a64dbb5 100644
--- a/plugins/Feedback/Controller.php
+++ b/plugins/Feedback/Controller.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Goals/API.php b/plugins/Goals/API.php
index 308d6dc9e8..f6fd240773 100644
--- a/plugins/Goals/API.php
+++ b/plugins/Goals/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_Goals
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Goals API lets you Manage existing goals, via "updateGoal" and "deleteGoal", create new Goals via "addGoal",
diff --git a/plugins/Goals/Controller.php b/plugins/Goals/Controller.php
index 8e89a78cd1..d96730e3b5 100644
--- a/plugins/Goals/Controller.php
+++ b/plugins/Goals/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Goals
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Goals/Goals.php b/plugins/Goals/Goals.php
index c491dabe22..80a6cfc8e9 100644
--- a/plugins/Goals/Goals.php
+++ b/plugins/Goals/Goals.php
@@ -9,6 +9,7 @@
  * @package Piwik_Goals
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/ImageGraph/API.php b/plugins/ImageGraph/API.php
index 92cc1767f5..d6d7feaa42 100644
--- a/plugins/ImageGraph/API.php
+++ b/plugins/ImageGraph/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_ImageGraph
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The ImageGraph.get API call lets you generate beautiful static PNG Graphs for any existing Piwik report.
diff --git a/plugins/ImageGraph/Controller.php b/plugins/ImageGraph/Controller.php
index 0e7839f127..56157a4f2a 100644
--- a/plugins/ImageGraph/Controller.php
+++ b/plugins/ImageGraph/Controller.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/ImageGraph/ImageGraph.php b/plugins/ImageGraph/ImageGraph.php
index 0604942cde..8cf15cd7ff 100644
--- a/plugins/ImageGraph/ImageGraph.php
+++ b/plugins/ImageGraph/ImageGraph.php
@@ -1,5 +1,5 @@
 <?php
-use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/Installation/Controller.php b/plugins/Installation/Controller.php
index 65d4c0c52f..26e5f23b72 100644
--- a/plugins/Installation/Controller.php
+++ b/plugins/Installation/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Installation
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Installation controller
diff --git a/plugins/Installation/FormDatabaseSetup.php b/plugins/Installation/FormDatabaseSetup.php
index 642753f760..bae926f4ed 100644
--- a/plugins/Installation/FormDatabaseSetup.php
+++ b/plugins/Installation/FormDatabaseSetup.php
@@ -9,6 +9,7 @@
  * @package Piwik_Installation
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Installation/Installation.php b/plugins/Installation/Installation.php
index 8e3c63fc08..36326a93ad 100644
--- a/plugins/Installation/Installation.php
+++ b/plugins/Installation/Installation.php
@@ -9,6 +9,7 @@
  * @package Piwik_Installation
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/LanguagesManager/API.php b/plugins/LanguagesManager/API.php
index 3f481e95f3..a4048e99b5 100644
--- a/plugins/LanguagesManager/API.php
+++ b/plugins/LanguagesManager/API.php
@@ -10,6 +10,7 @@
  *
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The LanguagesManager API lets you access existing Piwik translations, and change Users languages preferences.
diff --git a/plugins/LanguagesManager/Controller.php b/plugins/LanguagesManager/Controller.php
index 0538f4d540..2fbc094382 100644
--- a/plugins/LanguagesManager/Controller.php
+++ b/plugins/LanguagesManager/Controller.php
@@ -10,6 +10,7 @@
  *
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_LanguagesManager
diff --git a/plugins/LanguagesManager/LanguagesManager.php b/plugins/LanguagesManager/LanguagesManager.php
index 0100a78965..5d8f6a3a72 100644
--- a/plugins/LanguagesManager/LanguagesManager.php
+++ b/plugins/LanguagesManager/LanguagesManager.php
@@ -11,6 +11,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Live/API.php b/plugins/Live/API.php
index 78034dd50a..4928570526 100644
--- a/plugins/Live/API.php
+++ b/plugins/Live/API.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/Referers/functions.php
diff --git a/plugins/Live/Controller.php b/plugins/Live/Controller.php
index bd42e046ee..40058843c4 100644
--- a/plugins/Live/Controller.php
+++ b/plugins/Live/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Live
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_Live
diff --git a/plugins/Live/Visitor.php b/plugins/Live/Visitor.php
index 786d6491ab..0efd06ba63 100644
--- a/plugins/Live/Visitor.php
+++ b/plugins/Live/Visitor.php
@@ -9,6 +9,7 @@
  * @package Piwik_Live
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/Referers/functions.php
diff --git a/plugins/Login/Auth.php b/plugins/Login/Auth.php
index 4bcfe24d06..a9027cd864 100644
--- a/plugins/Login/Auth.php
+++ b/plugins/Login/Auth.php
@@ -9,6 +9,7 @@
  * @package Piwik_Login
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Login/Controller.php b/plugins/Login/Controller.php
index e255aba40b..135f6f3af6 100644
--- a/plugins/Login/Controller.php
+++ b/plugins/Login/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Login
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Login controller
diff --git a/plugins/MobileMessaging/API.php b/plugins/MobileMessaging/API.php
index ce4adeef49..d8b88da705 100644
--- a/plugins/MobileMessaging/API.php
+++ b/plugins/MobileMessaging/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_MobileMessaging
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The MobileMessaging API lets you manage and access all the MobileMessaging plugin features including :
diff --git a/plugins/MobileMessaging/Controller.php b/plugins/MobileMessaging/Controller.php
index 0796892c61..d720b62236 100644
--- a/plugins/MobileMessaging/Controller.php
+++ b/plugins/MobileMessaging/Controller.php
@@ -10,6 +10,7 @@
  */
 
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 require_once PIWIK_INCLUDE_PATH . '/plugins/UserCountry/functions.php';
 
diff --git a/plugins/MobileMessaging/ReportRenderer/Sms.php b/plugins/MobileMessaging/ReportRenderer/Sms.php
index 2fe2a3d111..39d10cad2f 100644
--- a/plugins/MobileMessaging/ReportRenderer/Sms.php
+++ b/plugins/MobileMessaging/ReportRenderer/Sms.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_MobileMessaging_ReportRenderer
  */
+use Piwik\Core\Piwik_Common;
 
 
 /**
diff --git a/plugins/MultiSites/API.php b/plugins/MultiSites/API.php
index 8ed333e3f5..1060129b8a 100755
--- a/plugins/MultiSites/API.php
+++ b/plugins/MultiSites/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_MultiSites
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The MultiSites API lets you request the key metrics (visits, page views, revenue) for all Websites in Piwik.
diff --git a/plugins/MultiSites/Controller.php b/plugins/MultiSites/Controller.php
index 0a86c09ed7..c63820a6a7 100644
--- a/plugins/MultiSites/Controller.php
+++ b/plugins/MultiSites/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_MultiSites
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Overlay/Controller.php b/plugins/Overlay/Controller.php
index 8fccad0a3a..0754731d49 100644
--- a/plugins/Overlay/Controller.php
+++ b/plugins/Overlay/Controller.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/PDFReports/API.php b/plugins/PDFReports/API.php
index 5c33b44e6d..5a048ed1dc 100644
--- a/plugins/PDFReports/API.php
+++ b/plugins/PDFReports/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_PDFReports
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The PDFReports API lets you manage Scheduled Email reports, as well as generate, download or email any existing report.
diff --git a/plugins/PDFReports/Controller.php b/plugins/PDFReports/Controller.php
index 9ec3dc91f5..1203246a1e 100644
--- a/plugins/PDFReports/Controller.php
+++ b/plugins/PDFReports/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_PDFReports
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/PDFReports/PDFReports.php b/plugins/PDFReports/PDFReports.php
index ca977f73a7..a7bc831e80 100644
--- a/plugins/PDFReports/PDFReports.php
+++ b/plugins/PDFReports/PDFReports.php
@@ -9,6 +9,7 @@
  * @package Piwik_PDFReports
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/PrivacyManager/Controller.php b/plugins/PrivacyManager/Controller.php
index 15508cb5db..3791d830c7 100644
--- a/plugins/PrivacyManager/Controller.php
+++ b/plugins/PrivacyManager/Controller.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/PrivacyManager/LogDataPurger.php b/plugins/PrivacyManager/LogDataPurger.php
index 7a4f846a69..6b9fc829ef 100755
--- a/plugins/PrivacyManager/LogDataPurger.php
+++ b/plugins/PrivacyManager/LogDataPurger.php
@@ -9,6 +9,7 @@
  * @package Piwik_PrivacyManager
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Purges the log_visit, log_conversion and related tables of old visit data.
diff --git a/plugins/PrivacyManager/PrivacyManager.php b/plugins/PrivacyManager/PrivacyManager.php
index 1c9cab13b0..39381d8cd2 100644
--- a/plugins/PrivacyManager/PrivacyManager.php
+++ b/plugins/PrivacyManager/PrivacyManager.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/PrivacyManager/LogDataPurger.php
diff --git a/plugins/Provider/Provider.php b/plugins/Provider/Provider.php
index 6a22f1ba4f..ab06434fe4 100644
--- a/plugins/Provider/Provider.php
+++ b/plugins/Provider/Provider.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_Provider
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Provider/functions.php b/plugins/Provider/functions.php
index 62f16590cd..1c36f8a929 100644
--- a/plugins/Provider/functions.php
+++ b/plugins/Provider/functions.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_Provider
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Return hostname portion of a domain name
diff --git a/plugins/Proxy/Controller.php b/plugins/Proxy/Controller.php
index 4a5ddc14dc..cac2e2505e 100644
--- a/plugins/Proxy/Controller.php
+++ b/plugins/Proxy/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Proxy
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Controller for proxy services
diff --git a/plugins/Referers/API.php b/plugins/Referers/API.php
index e4cf16596b..f71d3c2a45 100644
--- a/plugins/Referers/API.php
+++ b/plugins/Referers/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_Referers
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The Referrers API lets you access reports about Websites, Search engines, Keywords, Campaigns used to access your website.
diff --git a/plugins/Referers/Archiver.php b/plugins/Referers/Archiver.php
index 6c37226e26..1ebab392d6 100644
--- a/plugins/Referers/Archiver.php
+++ b/plugins/Referers/Archiver.php
@@ -1,5 +1,5 @@
 <?php
-use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/plugins/Referers/Controller.php b/plugins/Referers/Controller.php
index 267718a5fe..cc3d253f29 100644
--- a/plugins/Referers/Controller.php
+++ b/plugins/Referers/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_Referers
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Referers/functions.php b/plugins/Referers/functions.php
index 572eaa64d7..e22f28cd1a 100644
--- a/plugins/Referers/functions.php
+++ b/plugins/Referers/functions.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_Referers
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Returns path component from a URL
diff --git a/plugins/SEO/Controller.php b/plugins/SEO/Controller.php
index 68ae5caa12..00abd8337e 100644
--- a/plugins/SEO/Controller.php
+++ b/plugins/SEO/Controller.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_SEO
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_SEO
diff --git a/plugins/SEO/MajesticClient.php b/plugins/SEO/MajesticClient.php
index f6678be192..4834a66e8c 100644
--- a/plugins/SEO/MajesticClient.php
+++ b/plugins/SEO/MajesticClient.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_SEO
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Client for Majestic SEO's HTTP API.
diff --git a/plugins/SegmentEditor/API.php b/plugins/SegmentEditor/API.php
index 6b75833668..2d5aa2b714 100644
--- a/plugins/SegmentEditor/API.php
+++ b/plugins/SegmentEditor/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_SegmentEditor
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The SegmentEditor API lets you add, update, delete custom Segments, and list saved segments.a
diff --git a/plugins/SegmentEditor/Controller.php b/plugins/SegmentEditor/Controller.php
index f21c95bfff..8fc5b6871a 100644
--- a/plugins/SegmentEditor/Controller.php
+++ b/plugins/SegmentEditor/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_SegmentEditor
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_SegmentEditor
diff --git a/plugins/SegmentEditor/SegmentEditor.php b/plugins/SegmentEditor/SegmentEditor.php
index 194f0b2168..4dd4f163ac 100644
--- a/plugins/SegmentEditor/SegmentEditor.php
+++ b/plugins/SegmentEditor/SegmentEditor.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_SegmentEditor
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_SegmentEditor
diff --git a/plugins/SitesManager/API.php b/plugins/SitesManager/API.php
index cc537a43db..69a72e92cd 100644
--- a/plugins/SitesManager/API.php
+++ b/plugins/SitesManager/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_SitesManager
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The SitesManager API gives you full control on Websites in Piwik (create, update and delete), and many methods to retrieve websites based on various attributes.
diff --git a/plugins/SitesManager/Controller.php b/plugins/SitesManager/Controller.php
index adf875266f..3a73b32d60 100644
--- a/plugins/SitesManager/Controller.php
+++ b/plugins/SitesManager/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_SitesManager
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Transitions/API.php b/plugins/Transitions/API.php
index 912d54e525..4e4d0ab038 100644
--- a/plugins/Transitions/API.php
+++ b/plugins/Transitions/API.php
@@ -9,6 +9,7 @@
  * @package Piwik_Transitions
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @package Piwik_Transitions
diff --git a/plugins/UserCountry/Controller.php b/plugins/UserCountry/Controller.php
index ccab166581..b6ffad1963 100644
--- a/plugins/UserCountry/Controller.php
+++ b/plugins/UserCountry/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_UserCountry
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/UserCountry/GeoIPAutoUpdater.php b/plugins/UserCountry/GeoIPAutoUpdater.php
index d64b95c4f1..15e207edeb 100755
--- a/plugins/UserCountry/GeoIPAutoUpdater.php
+++ b/plugins/UserCountry/GeoIPAutoUpdater.php
@@ -9,6 +9,7 @@
  * @package Piwik_UserCountry
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Used to automatically update installed GeoIP databases, and manages the updater's
diff --git a/plugins/UserCountry/LocationProvider.php b/plugins/UserCountry/LocationProvider.php
index 0274f2b7fc..983d0f6839 100755
--- a/plugins/UserCountry/LocationProvider.php
+++ b/plugins/UserCountry/LocationProvider.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_UserCountry
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/UserCountry/LocationProvider/Default.php
diff --git a/plugins/UserCountry/LocationProvider/Default.php b/plugins/UserCountry/LocationProvider/Default.php
index b7467e71d3..703c1441ec 100755
--- a/plugins/UserCountry/LocationProvider/Default.php
+++ b/plugins/UserCountry/LocationProvider/Default.php
@@ -9,6 +9,7 @@
  * @package Piwik_UserCountry
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The default LocationProvider, this LocationProvider guesses a visitor's country
diff --git a/plugins/UserCountry/UserCountry.php b/plugins/UserCountry/UserCountry.php
index 5e57e053de..c7d559b289 100644
--- a/plugins/UserCountry/UserCountry.php
+++ b/plugins/UserCountry/UserCountry.php
@@ -9,6 +9,7 @@
  * @package Piwik_UserCountry
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * @see plugins/UserCountry/GeoIPAutoUpdater.php
diff --git a/plugins/UserCountryMap/Controller.php b/plugins/UserCountryMap/Controller.php
index 9345f37d73..8e732b399c 100644
--- a/plugins/UserCountryMap/Controller.php
+++ b/plugins/UserCountryMap/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_UserCountryMap
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/UserSettings/Archiver.php b/plugins/UserSettings/Archiver.php
index d6ba9e32b2..817b8b9a5e 100644
--- a/plugins/UserSettings/Archiver.php
+++ b/plugins/UserSettings/Archiver.php
@@ -9,6 +9,8 @@
  * @package Piwik_UserSettings
  */
 
+use Piwik\Core\Piwik_Common;
+
 require_once PIWIK_INCLUDE_PATH . '/plugins/UserSettings/functions.php';
 
 class Piwik_UserSettings_Archiver extends Piwik_PluginsArchiver
diff --git a/plugins/UsersManager/API.php b/plugins/UsersManager/API.php
index 1670b367df..411cd735a2 100644
--- a/plugins/UsersManager/API.php
+++ b/plugins/UsersManager/API.php
@@ -10,6 +10,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * The UsersManager API lets you Manage Users and their permissions to access specific websites.
diff --git a/plugins/UsersManager/Controller.php b/plugins/UsersManager/Controller.php
index 5ee315d2f2..322a4ebff0 100644
--- a/plugins/UsersManager/Controller.php
+++ b/plugins/UsersManager/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_UsersManager
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/VisitFrequency/Controller.php b/plugins/VisitFrequency/Controller.php
index 527b8c0ac8..0c32d3dcf6 100644
--- a/plugins/VisitFrequency/Controller.php
+++ b/plugins/VisitFrequency/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_VisitFrequency
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/VisitTime/VisitTime.php b/plugins/VisitTime/VisitTime.php
index 18e6fde02f..dee8d07368 100644
--- a/plugins/VisitTime/VisitTime.php
+++ b/plugins/VisitTime/VisitTime.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_VisitTime
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/VisitorGenerator/Controller.php b/plugins/VisitorGenerator/Controller.php
index 43f4669ea0..cb9a567b52 100644
--- a/plugins/VisitorGenerator/Controller.php
+++ b/plugins/VisitorGenerator/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_VisitorGenerator
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/VisitsSummary/Controller.php b/plugins/VisitsSummary/Controller.php
index ec058e6aab..3dc80647a4 100644
--- a/plugins/VisitsSummary/Controller.php
+++ b/plugins/VisitsSummary/Controller.php
@@ -9,6 +9,7 @@
  * @package Piwik_VisitsSummary
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/plugins/Widgetize/Controller.php b/plugins/Widgetize/Controller.php
index 1f326563b8..c8751b6b7b 100644
--- a/plugins/Widgetize/Controller.php
+++ b/plugins/Widgetize/Controller.php
@@ -8,6 +8,7 @@
  * @category Piwik_Plugins
  * @package Piwik_Widgetize
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  *
diff --git a/tests/PHPUnit/BaseFixture.php b/tests/PHPUnit/BaseFixture.php
index fae7717825..812fdc2960 100644
--- a/tests/PHPUnit/BaseFixture.php
+++ b/tests/PHPUnit/BaseFixture.php
@@ -6,6 +6,7 @@
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Base type for all integration test fixtures. Integration test fixtures
diff --git a/tests/PHPUnit/BenchmarkTestCase.php b/tests/PHPUnit/BenchmarkTestCase.php
index 46f2400d75..72df0a58dc 100755
--- a/tests/PHPUnit/BenchmarkTestCase.php
+++ b/tests/PHPUnit/BenchmarkTestCase.php
@@ -6,6 +6,7 @@
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/IntegrationTestCase.php';
 require_once PIWIK_INCLUDE_PATH . '/tests/LocalTracker.php';
diff --git a/tests/PHPUnit/Benchmarks/Fixtures/SqlDump.php b/tests/PHPUnit/Benchmarks/Fixtures/SqlDump.php
index fb73285612..ee8a4f8b49 100755
--- a/tests/PHPUnit/Benchmarks/Fixtures/SqlDump.php
+++ b/tests/PHPUnit/Benchmarks/Fixtures/SqlDump.php
@@ -7,6 +7,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Reusable fixture. Loads a ~1GB SQL dump into the DB.
diff --git a/tests/PHPUnit/Core/ArchiveProcessingTest.php b/tests/PHPUnit/Core/ArchiveProcessingTest.php
index 596c7973c4..dd1e9a8186 100644
--- a/tests/PHPUnit/Core/ArchiveProcessingTest.php
+++ b/tests/PHPUnit/Core/ArchiveProcessingTest.php
@@ -1,6 +1,7 @@
 <?php
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/tests/PHPUnit/Core/CommonTest.php b/tests/PHPUnit/Core/CommonTest.php
index 4f882e0933..f8d7b431b7 100644
--- a/tests/PHPUnit/Core/CommonTest.php
+++ b/tests/PHPUnit/Core/CommonTest.php
@@ -1,4 +1,6 @@
 <?php
+use Piwik\Core\Piwik_Common;
+
 /**
  * Piwik - Open source web analytics
  *
diff --git a/tests/PHPUnit/Core/IPTest.php b/tests/PHPUnit/Core/IPTest.php
index f9ae6bc3d3..3ca6be38dc 100644
--- a/tests/PHPUnit/Core/IPTest.php
+++ b/tests/PHPUnit/Core/IPTest.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Config;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/tests/PHPUnit/Core/OptionTest.php b/tests/PHPUnit/Core/OptionTest.php
index 63c5903636..eafb246501 100644
--- a/tests/PHPUnit/Core/OptionTest.php
+++ b/tests/PHPUnit/Core/OptionTest.php
@@ -5,6 +5,8 @@
  * @link http://piwik.org
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
+use Piwik\Core\Piwik_Common;
+
 require_once "Option.php";
 
 class OptionTest extends DatabaseTestCase
diff --git a/tests/PHPUnit/Core/ReleaseCheckListTest.php b/tests/PHPUnit/Core/ReleaseCheckListTest.php
index 04cb72a5a3..e24f9cf144 100644
--- a/tests/PHPUnit/Core/ReleaseCheckListTest.php
+++ b/tests/PHPUnit/Core/ReleaseCheckListTest.php
@@ -1,5 +1,6 @@
 <?php
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Piwik - Open source web analytics
diff --git a/tests/PHPUnit/Core/SegmentTest.php b/tests/PHPUnit/Core/SegmentTest.php
index 3f881e9eb3..bbc8f4d70e 100644
--- a/tests/PHPUnit/Core/SegmentTest.php
+++ b/tests/PHPUnit/Core/SegmentTest.php
@@ -1,4 +1,6 @@
 <?php
+use Piwik\Core\Piwik_Common;
+
 /**
  * Piwik - Open source web analytics
  *
diff --git a/tests/PHPUnit/Core/ServeStaticFileTest.php b/tests/PHPUnit/Core/ServeStaticFileTest.php
index 764fd85e17..034a64a4ba 100644
--- a/tests/PHPUnit/Core/ServeStaticFileTest.php
+++ b/tests/PHPUnit/Core/ServeStaticFileTest.php
@@ -13,6 +13,7 @@
 
 // This is Piwik logo, the static file used in this test suit
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 define("TEST_FILE_LOCATION", realpath(dirname(__FILE__) . "/../../resources/lipsum.txt"));
 define("TEST_FILE_CONTENT_TYPE", "text/plain");
diff --git a/tests/PHPUnit/Core/TranslationWriterTest.php b/tests/PHPUnit/Core/TranslationWriterTest.php
index 27a4fa597a..187996ed0b 100644
--- a/tests/PHPUnit/Core/TranslationWriterTest.php
+++ b/tests/PHPUnit/Core/TranslationWriterTest.php
@@ -1,4 +1,6 @@
 <?php
+use Piwik\Core\Piwik_Common;
+
 /**
  * Piwik - Open source web analytics
  *
diff --git a/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php b/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php
index 80f36f5544..df3fd04f16 100644
--- a/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php
+++ b/tests/PHPUnit/Fixtures/ManySitesImportedLogsWithXssAttempts.php
@@ -5,6 +5,8 @@
  * @link    http://piwik.org
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
+use Piwik\Core\Piwik_Common;
+
 require_once PIWIK_INCLUDE_PATH . '/tests/PHPUnit/Fixtures/ManySitesImportedLogs.php';
 
 /**
diff --git a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php
index e416615da9..92f495fac1 100755
--- a/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php
+++ b/tests/PHPUnit/Integration/OneVisitorOneWebsite_SeveralDaysDateRange_ArchivingTestsTest.php
@@ -6,6 +6,7 @@
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 /**
  * Tests some API using range periods & makes sure the correct amount of blob/numeric
diff --git a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php
index fd08f464cd..3fd750022b 100755
--- a/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php
+++ b/tests/PHPUnit/Integration/TwoVisitsWithCustomVariables_SegmentMatchVisitorTypeTest.php
@@ -5,6 +5,7 @@
  * @link    http://piwik.org
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
+use Piwik\Core\Piwik_Common;
 
 /**
  * Tests use of custom variable segments.
diff --git a/tests/PHPUnit/Integration/UrlNormalizationTest.php b/tests/PHPUnit/Integration/UrlNormalizationTest.php
index 690a2a57ba..a2b0e6c702 100644
--- a/tests/PHPUnit/Integration/UrlNormalizationTest.php
+++ b/tests/PHPUnit/Integration/UrlNormalizationTest.php
@@ -1,4 +1,6 @@
 <?php
+use Piwik\Core\Piwik_Common;
+
 /**
  * Tests the URL normalization.
  */
diff --git a/tests/PHPUnit/IntegrationTestCase.php b/tests/PHPUnit/IntegrationTestCase.php
index 2c662f39f5..86460d46d5 100755
--- a/tests/PHPUnit/IntegrationTestCase.php
+++ b/tests/PHPUnit/IntegrationTestCase.php
@@ -7,6 +7,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 require_once PIWIK_INCLUDE_PATH . '/libs/PiwikTracker/PiwikTracker.php';
 
diff --git a/tests/PHPUnit/Plugins/LanguagesManagerTest.php b/tests/PHPUnit/Plugins/LanguagesManagerTest.php
index 9acc5f3a9e..2b47a4bb80 100755
--- a/tests/PHPUnit/Plugins/LanguagesManagerTest.php
+++ b/tests/PHPUnit/Plugins/LanguagesManagerTest.php
@@ -5,6 +5,8 @@
  * @link    http://piwik.org
  * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
  */
+use Piwik\Core\Piwik_Common;
+
 require_once 'LanguagesManager/API.php';
 
 class Test_LanguagesManager extends PHPUnit_Framework_TestCase
diff --git a/tests/PHPUnit/Plugins/PrivacyManagerTest.php b/tests/PHPUnit/Plugins/PrivacyManagerTest.php
index ffcfe6a38f..2b81e55dad 100755
--- a/tests/PHPUnit/Plugins/PrivacyManagerTest.php
+++ b/tests/PHPUnit/Plugins/PrivacyManagerTest.php
@@ -7,6 +7,7 @@
  */
 use Piwik\Core\Config;
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 require_once 'PrivacyManager/PrivacyManager.php';
 
diff --git a/tests/resources/staticFileServer.php b/tests/resources/staticFileServer.php
index da49ceb7ad..e0e2a00dc1 100644
--- a/tests/resources/staticFileServer.php
+++ b/tests/resources/staticFileServer.php
@@ -10,6 +10,7 @@
  * serveStaticFile.test.php has been created to avoid making too many modifications to /tests/core/Piwik.test.php
  */
 use Piwik\Core\Piwik;
+use Piwik\Core\Piwik_Common;
 
 define('PIWIK_DOCUMENT_ROOT', dirname(__FILE__).'/../../');
 if(file_exists(PIWIK_DOCUMENT_ROOT . '/bootstrap.php'))
-- 
GitLab