/** * Setup the database and create the base tables for all tests */ public function setUp() { parent::setUp(); static::$fixture->extraDefinitions = array_merge(static::provideContainerConfigBeforeClass(), $this->provideContainerConfig()); static::$fixture->createEnvironmentInstance(); Db::createDatabaseObject(); Fixture::loadAllPlugins(new TestingEnvironmentVariables(), get_class($this), self::$fixture->extraPluginsToLoad); Access::getInstance()->setSuperUserAccess(true); if (!empty(self::$tableData)) { self::restoreDbTables(self::$tableData); } PiwikCache::getEagerCache()->flushAll(); PiwikCache::getTransientCache()->flushAll(); MenuAbstract::clearMenus(); }
/** * Used to initialize core Piwik components on a piwik.php request * Eg. when cache is missed and we will be calling some APIs to generate cache */ public static function initCorePiwikInTrackerMode() { if (SettingsServer::isTrackerApiRequest() && self::$initTrackerMode === false) { self::$initTrackerMode = true; require_once PIWIK_INCLUDE_PATH . '/core/Option.php'; Access::getInstance(); Config::getInstance(); try { Db::get(); } catch (Exception $e) { Db::createDatabaseObject(); } \Piwik\Plugin\Manager::getInstance()->loadCorePluginsDuringTracker(); } }
/** * Creates database object based on form data. * * @throws Exception|Zend_Db_Adapter_Exception * @return array The database connection info. Can be passed into Piwik::createDatabaseObject. */ public function createDatabaseObject() { $dbname = $this->getSubmitValue('dbname'); if (empty($dbname)) { throw new Exception("No database name"); } $adapter = $this->getSubmitValue('adapter'); $port = Adapter::getDefaultPortForAdapter($adapter); $dbInfos = array('host' => $this->getSubmitValue('host'), 'username' => $this->getSubmitValue('username'), 'password' => $this->getSubmitValue('password'), 'dbname' => $dbname, 'tables_prefix' => $this->getSubmitValue('tables_prefix'), 'adapter' => $adapter, 'port' => $port, 'schema' => Config::getInstance()->database['schema'], 'type' => $this->getSubmitValue('type')); if (($portIndex = strpos($dbInfos['host'], '/')) !== false) { // unix_socket=/path/sock.n $dbInfos['port'] = substr($dbInfos['host'], $portIndex); $dbInfos['host'] = ''; } else { if (($portIndex = strpos($dbInfos['host'], ':')) !== false) { // host:port $dbInfos['port'] = substr($dbInfos['host'], $portIndex + 1); $dbInfos['host'] = substr($dbInfos['host'], 0, $portIndex); } } try { @Db::createDatabaseObject($dbInfos); } catch (Zend_Db_Adapter_Exception $e) { $db = Adapter::factory($adapter, $dbInfos, $connect = false); // database not found, we try to create it if ($db->isErrNo($e, '1049')) { $dbInfosConnectOnly = $dbInfos; $dbInfosConnectOnly['dbname'] = null; @Db::createDatabaseObject($dbInfosConnectOnly); @DbHelper::createDatabase($dbInfos['dbname']); // select the newly created database @Db::createDatabaseObject($dbInfos); } else { throw $e; } } return $dbInfos; }
/** * Must be called before dispatch() * - checks that directories are writable, * - loads the configuration file, * - loads the plugin, * - inits the DB connection, * - etc. * * @throws Exception * @return void */ public function init() { static $initialized = false; if ($initialized) { return; } $initialized = true; $tmpPath = StaticContainer::get('path.tmp'); $directoriesToCheck = array($tmpPath, $tmpPath . '/assets/', $tmpPath . '/cache/', $tmpPath . '/logs/', $tmpPath . '/tcpdf/', $tmpPath . '/templates_c/'); Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck); $this->handleMaintenanceMode(); $this->handleProfiler(); $this->handleSSLRedirection(); Plugin\Manager::getInstance()->loadPluginTranslations(); Plugin\Manager::getInstance()->loadActivatedPlugins(); // try to connect to the database try { Db::createDatabaseObject(); Db::fetchAll("SELECT DATABASE()"); } catch (Exception $exception) { if (self::shouldRethrowException()) { throw $exception; } Log::debug($exception); /** * Triggered when Piwik cannot connect to the database. * * This event can be used to start the installation process or to display a custom error * message. * * @param Exception $exception The exception thrown from creating and testing the database * connection. */ Piwik::postEvent('Db.cannotConnectToDb', array($exception), $pending = true); throw $exception; } // try to get an option (to check if data can be queried) try { Option::get('TestingIfDatabaseConnectionWorked'); } catch (Exception $exception) { if (self::shouldRethrowException()) { throw $exception; } Log::debug($exception); /** * Triggered when Piwik cannot access database data. * * This event can be used to start the installation process or to display a custom error * message. * * @param Exception $exception The exception thrown from trying to get an option value. */ Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true); throw $exception; } // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs Access::getInstance(); /** * Triggered just after the platform is initialized and plugins are loaded. * * This event can be used to do early initialization. * * _Note: At this point the user is not authenticated yet._ */ Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen'); $this->throwIfPiwikVersionIsOlderThanDBSchema(); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); // ensure the current Piwik URL is known for later use if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) { SettingsPiwik::getPiwikUrl(); } /** * Triggered before the user is authenticated, when the global authentication object * should be created. * * Plugins that provide their own authentication implementation should use this event * to set the global authentication object (which must derive from {@link Piwik\Auth}). * * **Example** * * Piwik::addAction('Request.initAuthenticationObject', function() { * StaticContainer::getContainer()->set('Piwik\Auth', new MyAuthImplementation()); * }); */ Piwik::postEvent('Request.initAuthenticationObject'); try { $authAdapter = StaticContainer::get('Piwik\\Auth'); } catch (Exception $e) { $message = "Authentication object cannot be found in the container. Maybe the Login plugin is not activated?\n <br />You can activate the plugin by adding:<br />\n <code>Plugins[] = Login</code><br />\n under the <code>[Plugins]</code> section in your config/config.ini.php"; $ex = new AuthenticationFailedException($message); $ex->setIsHtmlMessage(); throw $ex; } Access::getInstance()->reloadAccess($authAdapter); // Force the auth to use the token_auth if specified, so that embed dashboard // and all other non widgetized controller methods works fine if (Common::getRequestVar('token_auth', false, 'string') !== false) { Request::reloadAuthUsingTokenAuth(); } SettingsServer::raiseMemoryLimitIfNecessary(); \Piwik\Plugin\Manager::getInstance()->postLoadPlugins(); /** * Triggered after the platform is initialized and after the user has been authenticated, but * before the platform has handled the request. * * Piwik uses this event to check for updates to Piwik. */ Piwik::postEvent('Platform.initialized'); }
/** * Connects to MySQL w/o specifying a database. */ public static function connectWithoutDatabase() { $dbConfig = Config::getInstance()->database; $oldDbName = $dbConfig['dbname']; $dbConfig['dbname'] = null; Db::createDatabaseObject($dbConfig); $dbConfig['dbname'] = $oldDbName; }
/** * Must be called before dispatch() * - checks that directories are writable, * - loads the configuration file, * - loads the plugin, * - inits the DB connection, * - etc. * * @throws Exception * @return void */ public function init() { static $initialized = false; if ($initialized) { return; } $initialized = true; try { Registry::set('timer', new Timer()); $directoriesToCheck = array('/tmp/', '/tmp/assets/', '/tmp/cache/', '/tmp/logs/', '/tmp/tcpdf/', '/tmp/templates_c/'); Filechecks::dieIfDirectoriesNotWritable($directoriesToCheck); self::assignCliParametersToRequest(); Translate::loadEnglishTranslation(); $exceptionToThrow = self::createConfigObject(); if (Session::isFileBasedSessions()) { Session::start(); } $this->handleMaintenanceMode(); $this->handleSSLRedirection(); $this->handleProfiler(); $pluginsManager = \Piwik\Plugin\Manager::getInstance(); $pluginsToLoad = Config::getInstance()->Plugins['Plugins']; $pluginsManager->loadPlugins($pluginsToLoad); if ($exceptionToThrow) { throw $exceptionToThrow; } try { Db::createDatabaseObject(); Option::get('TestingIfDatabaseConnectionWorked'); } catch (Exception $exception) { if (self::shouldRethrowException()) { throw $exception; } /** * Triggered if the INI config file has the incorrect format or if certain required configuration * options are absent. * * This event can be used to start the installation process or to display a custom error message. * * @param Exception $exception The exception thrown from creating and testing the database * connection. */ Piwik::postEvent('Config.badConfigurationFile', array($exception), $pending = true); throw $exception; } // Init the Access object, so that eg. core/Updates/* can enforce Super User and use some APIs Access::getInstance(); /** * Triggered just after the platform is initialized and plugins are loaded. * * This event can be used to do early initialization. * * _Note: At this point the user is not authenticated yet._ */ Piwik::postEvent('Request.dispatchCoreAndPluginUpdatesScreen'); \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins(); // ensure the current Piwik URL is known for later use if (method_exists('Piwik\\SettingsPiwik', 'getPiwikUrl')) { $host = SettingsPiwik::getPiwikUrl(); } /** * Triggered before the user is authenticated, when the global authentication object * should be created. * * Plugins that provide their own authentication implementation should use this event * to set the global authentication object (which must derive from {@link Piwik\Auth}). * * **Example** * * Piwik::addAction('Request.initAuthenticationObject', function() { * Piwik\Registry::set('auth', new MyAuthImplementation()); * }); */ Piwik::postEvent('Request.initAuthenticationObject'); try { $authAdapter = Registry::get('auth'); } catch (Exception $e) { throw new Exception("Authentication object cannot be found in the Registry. Maybe the Login plugin is not activated?\n <br />You can activate the plugin by adding:<br />\n <code>Plugins[] = Login</code><br />\n under the <code>[Plugins]</code> section in your config/config.ini.php"); } Access::getInstance()->reloadAccess($authAdapter); // Force the auth to use the token_auth if specified, so that embed dashboard // and all other non widgetized controller methods works fine if (($token_auth = Common::getRequestVar('token_auth', false, 'string')) !== false) { Request::reloadAuthUsingTokenAuth(); } SettingsServer::raiseMemoryLimitIfNecessary(); Translate::reloadLanguage(); $pluginsManager->postLoadPlugins(); /** * Triggered after the platform is initialized and after the user has been authenticated, but * before the platform has handled the request. * * Piwik uses this event to check for updates to Piwik. */ Piwik::postEvent('Updater.checkForUpdates'); } catch (Exception $e) { if (self::shouldRethrowException()) { throw $e; } $debugTrace = $e->getTraceAsString(); Piwik_ExitWithMessage($e->getMessage(), $debugTrace, true); } }
/** * Used to initialize core Piwik components on a piwik.php request * Eg. when cache is missed and we will be calling some APIs to generate cache */ public static function initCorePiwikInTrackerMode() { if (!empty($GLOBALS['PIWIK_TRACKER_MODE']) && self::$initTrackerMode === false) { self::$initTrackerMode = true; require_once PIWIK_INCLUDE_PATH . '/core/Loader.php'; require_once PIWIK_INCLUDE_PATH . '/core/Option.php'; $access = Access::getInstance(); $config = Config::getInstance(); try { $db = Db::get(); } catch (Exception $e) { Db::createDatabaseObject(); } $pluginsManager = \Piwik\Plugin\Manager::getInstance(); $pluginsToLoad = Config::getInstance()->Plugins['Plugins']; $pluginsForcedNotToLoad = Tracker::getPluginsNotToLoad(); $pluginsToLoad = array_diff($pluginsToLoad, $pluginsForcedNotToLoad); $pluginsToLoad = array_merge($pluginsToLoad, Tracker::getPluginsToLoad()); $pluginsManager->loadPlugins($pluginsToLoad); } }
/** * Create database connection from session-store */ protected function createDbFromSessionInformation() { $dbInfos = $this->session->db_infos; Config::getInstance()->database = $dbInfos; Db::createDatabaseObject($dbInfos); }
/** * @param bool $noLoadConfig * @return void */ public function initPiwikDatabase($noLoadConfig = FALSE) { $this->initPiwikFrameWork(); if ($this->initPiwikDb) { $this->initPiwikDb = TRUE; return; } \Piwik\Db::createDatabaseObject(); }