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
541328
public function init()
    {
        if ($this->initialized) {
            return;
        }

        self::setRequestIdHeader();

        $this->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();

        $module = Piwik::getModule();
        $action = Piwik::getAction();

        if (empty($module)
            || empty($action)
            || $module !== 'Installation'
            || !in_array($action, array('getInstallationCss', 'getInstallationJs'))) {
            \Piwik\Plugin\Manager::getInstance()->installLoadedPlugins();
        }

        // ensure the current Piwik URL is known for later use
        if (method_exists('Piwik\SettingsPiwik', 'getPiwikUrl')) {
            SettingsPiwik::getPiwikUrl();
        }

        $loggedIn = false;

        // try authenticating w/ session first...
        $sessionAuth = $this->makeSessionAuthenticator();
        if ($sessionAuth) {
            $loggedIn = Access::getInstance()->reloadAccess($sessionAuth);
        }

        // ... if session auth fails try normal auth (which will login the anonymous user)
        if (!$loggedIn) {
            $authAdapter = $this->makeAuthenticator();
            Access::getInstance()->reloadAccess($authAdapter);
        } else {
            $this->makeAuthenticator($sessionAuth); // Piwik\Auth must be set to the correct Login plugin
        }

        // 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');
    }
789724
public function init()
    {
        if (!isset($this->attrs->server['FR_PATH'])) {
            $this->status(404);
            $this->finish();
            return;
        }
        $job = new \PHPDaemon\Core\ComplexJob(function ($job) {
            $this->wakeup();
        });
        $this->job = $job;
        $this->sleep(5, true);
        $this->attrs->server['FR_PATH'] = \PHPDaemon\FS\FileSystem::sanitizePath($this->attrs->server['FR_PATH']);
        $job('stat', function ($name, $job) {
            /** @var \PHPDaemon\Core\ComplexJob $job */
            \PHPDaemon\FS\FileSystem::stat($this->attrs->server['FR_PATH'], function ($path, $stat) use ($job) {
                if ($stat === -1) {
                    $this->fileNotFound();
                    $job->setResult('stat', false);
                    return;
                }
                if ($stat['type'] === 'd') {
                    if (!\PHPDaemon\FS\FileSystem::$supported) {
                        $this->file(rtrim($path, '/') . '/index.html');
                    } else {
                        $job('readdir', function ($name, $job) use ($path) {
                            /** @var \PHPDaemon\Core\ComplexJob $job */
                            \PHPDaemon\FS\FileSystem::readdir(rtrim($path, '/'), function ($path, $dir) use ($job) {
                                $found = false;
                                if (is_array($dir)) {
                                    foreach ($dir['dents'] as $file) {
                                        if ($file['type'] === \EIO_DT_REG) { // is file
                                            if (in_array($file['name'], $this->appInstance->indexFiles)) {
                                                $this->file($path . '/' . $file['name']);
                                                $found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                                if (!$found) {
                                    if (isset($this->attrs->server['FR_AUTOINDEX']) && $this->attrs->server['FR_AUTOINDEX']) {
                                        $this->autoindex($path, $dir);
                                    } else {
                                        $this->fileNotFound();
                                    }
                                }

                                $job->setResult('readdir');
                            }, \EIO_READDIR_STAT_ORDER | \EIO_READDIR_DENTS);
                        });
                    }
                } elseif ($stat['type'] === 'f') {
                    $this->file($path);
                }
                $job->setResult('stat', $stat);
            });
        });
        $job();
    }
648106
protected function populate()
    {
        if (!file_exists('config.json')) {
            return;
        }

        $config = json_decode(file_get_contents('config.json'), true);
        if (!\is_array($config)) {
            throw new Exception(
                'The config.json file is not valid or there is no Zephir extension initialized in this directory.'
            );
        }

        foreach ($config as $key => $configSection) {
            $this->offsetSet($key, $configSection);
        }
    }
705079
protected function onInit()
    {
        $username = Util::get($this->params, "username", "");
        $password = Util::get($this->params, "password", "");
        $connString = Util::get($this->params, "connectionString", "");

        $key = md5($username.$password.$connString);

        if (isset(OracleDataSource::$connections[$key])) {
            $this->connection = OracleDataSource::$connections[$key];
        } else {
            $conn = oci_connect($username, $password, $connString);
            if ($conn) {
                $this->connection = $conn;
            } else {
                throw new \Exception("Connection failed: " . print_r(oci_error(), true));
            }
            OracleDataSource::$connections[$key] = $this->connection;
        }
    }
733854
public function loadPluginConfiguration(): void
	{
		// Receive container builder
		$builder = $this->getContainerBuilder();
		$globalConfig = $this->compiler->getExtension()->getConfig();

		$builder->addDefinition($this->prefix('dispatcher'))
			->setFactory(JsonDispatcher::class)
			->setAutowired(false);

		// Catch exception only in debug mode if explicitly enabled
		$catchException = !$globalConfig['debug'] || $globalConfig['catchException'];

		$errorHandler = $builder->addDefinition($this->prefix('errorHandler'))
			->setFactory(SimpleErrorHandler::class)
			->setType(IErrorHandler::class)
			->addSetup('setCatchException', [$catchException]);

		// Set handler with logging, if logger available
		if ($builder->findByType(LoggerInterface::class) !== []) {
			$errorHandler->setFactory(PsrLogErrorHandler::class);
		}

		$builder->addDefinition($this->prefix('dispatcher.wrapper'))
			->setFactory(WrappedDispatcher::class, ['@' . $this->prefix('dispatcher')]);

		$builder->addDefinition($this->prefix('application'))
			->setFactory(Application::class)
			->setType(IApplication::class);

		$builder->addDefinition($this->prefix('router'))
			->setType(IRouter::class)
			->setFactory(SimpleRouter::class);

		$builder->addDefinition($this->prefix('handler'))
			->setType(IHandler::class)
			->setFactory(ServiceHandler::class);

		$builder->addDefinition($this->prefix('schema'))
			->setFactory(Schema::class);
	}
276835
protected function onInit()
    {
        $key = Utility::get($this->params, "key", "");
        $reportSource = Utility::get($this->params, "report");
        $reportParams = Utility::get($this->params, "params", array());

        if ($reportSource==null) {
            throw new \Exception("ReportDataSource require 'source' parameter which is the classname of source report");
        }

        if (ReportDataSource::$reports==null) {
            ReportDataSource::$reports = array();
        }

        if (isset(ReportDataSource::$reports[$reportSource.$key])) {
            $this->report = ReportDataSource::$reports[$reportSource.$key];
        } else {
            try
            {
                $this->report = new $reportSource($reportParams);
            }
            catch(\Exception $e)
            {
                throw new \Exception("Could not create report '$reportSource'");
            }
            
            ReportDataSource::$reports[$reportSource.$key]=$this->report;
            $this->report->run();
        }
    }
1111383
def _load(self, ):
        
        try:
            self.init()
        except Exception as e:
            log.exception("Load failed!")
            raise errors.PluginInitError('%s' % e)
        self.__status = self.__LOADED
622745
public function init() {
        if (!extension_loaded('redis')) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension is not loaded');
        }

        if (empty($this->host)) {
            throw new exception('sessionhandlerproblem', 'error', '', null,
                    '$CFG->session_redis_host must be specified in config.php');
        }

        // The session handler requires a version of Redis with the SETEX command (at least 2.0).
        $version = phpversion('Redis');
        if (!$version or version_compare($version, '2.0') <= 0) {
            throw new exception('sessionhandlerproblem', 'error', '', null, 'redis extension version must be at least 2.0');
        }

        $this->connection = new \Redis();

        $result = session_set_save_handler(array($this, 'handler_open'),
            array($this, 'handler_close'),
            array($this, 'handler_read'),
            array($this, 'handler_write'),
            array($this, 'handler_destroy'),
            array($this, 'handler_gc'));
        if (!$result) {
            throw new exception('redissessionhandlerproblem', 'error');
        }

        // MDL-59866: Add retries for connections (up to 5 times) to make sure it goes through.
        $counter = 1;
        $maxnumberofretries = 5;

        while ($counter <= $maxnumberofretries) {

            try {

                $delay = rand(100000, 500000);

                // One second timeout was chosen as it is long for connection, but short enough for a user to be patient.
                if (!$this->connection->connect($this->host, $this->port, 1, null, $delay)) {
                    throw new RedisException('Unable to connect to host.');
                }

                if ($this->auth !== '') {
                    if (!$this->connection->auth($this->auth)) {
                        throw new RedisException('Unable to authenticate.');
                    }
                }

                if (!$this->connection->setOption(\Redis::OPT_SERIALIZER, $this->serializer)) {
                    throw new RedisException('Unable to set Redis PHP Serializer option.');
                }

                if ($this->prefix !== '') {
                    // Use custom prefix on sessions.
                    if (!$this->connection->setOption(\Redis::OPT_PREFIX, $this->prefix)) {
                        throw new RedisException('Unable to set Redis Prefix option.');
                    }
                }
                if ($this->database !== 0) {
                    if (!$this->connection->select($this->database)) {
                        throw new RedisException('Unable to select Redis database '.$this->database.'.');
                    }
                }
                $this->connection->ping();
                return true;
            } catch (RedisException $e) {
                $logstring = "Failed to connect (try {$counter} out of {$maxnumberofretries}) to redis ";
                $logstring .= "at {$this->host}:{$this->port}, error returned was: {$e->getMessage()}";

                // @codingStandardsIgnoreStart
                error_log($logstring);
                // @codingStandardsIgnoreEnd
            }

            $counter++;

            // Introduce a random sleep between 100ms and 500ms.
            usleep(rand(100000, 500000));
        }

        // We have exhausted our retries, time to give up.
        return false;
    }
358321
protected function loadDatabaseConfig()
    {
        if (!$this->databaseConfigFile) {
            return null;
        }

        $configPath = "{$this->path}/{$this->databaseConfigFile}";
        if (file_exists($configPath)) {
            $this->databaseConfig = require $configPath;
        } else {
            throw new Exception("Unable to load database configuration.");
        }
    }
743990
public function onConstruct()
    {
        $this->userLinkedSourcesModel = new UserLinkedSources();
        $this->userModel = new Users();

        if (!isset($this->config->jwt)) {
            throw new Exception('You need to configure your app JWT');
        }
    }
17312
public function afterFetch()
    {
        /*
         * Override the database columns with the plugin details
         * found in the plugin registration file.
         */
        $manager = PluginManager::instance();
        $pluginObj = $manager->findByIdentifier($this->code);

        if ($pluginObj) {
            $pluginInfo = $pluginObj->pluginDetails();
            foreach ($pluginInfo as $attribute => $info) {
                if (property_exists($this, $attribute)) {
                    $this->{$attribute} = Lang::get($info);
                }
            }

            if ($this->is_disabled) {
                $manager->disablePlugin($this->code, true);
            }
            else {
                $manager->enablePlugin($this->code, true);
            }

            $this->disabledBySystem = $pluginObj->disabled;

            if (($configDisabled = Config::get('cms.disablePlugins')) && is_array($configDisabled)) {
                $this->disabledByConfig = in_array($this->code, $configDisabled);
            }
        }
        else {
            $this->name = $this->code;
            $this->description = Lang::get('system::lang.plugins.unknown_plugin');
            $this->orphaned = true;
        }
    }
696225
public function loadConfigurations(): void
	{
		foreach ($this->plugins as $plugin) {
			$plugin['inst']->setupPlugin($plugin['config']);
			$plugin['inst']->loadPluginConfiguration();
		}
	}
770474
protected function prepare()
        {
            if (!Core::getDBlink() instanceof \PDO) {
                throw new Exception('Connection not up, can\'t prepare the statement');
            }

            $this->statement = Core::getDBlink()->prepare($this->query->getSql());
        }
580570
protected function init()
    {
        // WebDocBook booting
        $this->boot();

        // the logger
        $this->logger = new Logger(array(
            'directory'         => Kernel::getPath('log'),
            'logfile'           => Kernel::getConfig('app:logfile', 'history'),
            'error_logfile'     => Kernel::getConfig('app:error_logfile', 'errors'),
            'duplicate_errors'  => false,
        ));

        // user configuration
        $internal_config    = Kernel::getConfig('userconf', array());
        $user_config_file   = Kernel::getPath('user_config_filepath');
        if (true===file_exists($user_config_file)) {
            $user_config = FilesystemHelper::parseIni($user_config_file);
            if (!empty($user_config)) {
                Kernel::setConfig($user_config, 'user_config');
            } else {
                throw new Exception(
                    sprintf('Can not read you configuration file "%s"!', Kernel::getPath('user_config_filepath', true))
                );
            }
        } else {
            Kernel::setConfig($internal_config, 'user_config');
        }

        // creating the application default headers
        $charset        = Kernel::getConfig('html:charset', 'utf-8');
        $content_type   = Kernel::getConfig('html:content-type', 'text/html');
        $app_name       = Kernel::getConfig('title', null, 'manifest');
        $app_version    = Kernel::getConfig('version', null, 'manifest');
        $app_website    = Kernel::getConfig('homepage', null, 'manifest');
        $this->response->addHeader('Content-type', $content_type.'; charset: '.$charset);

        // expose app ?
        $expose_wdb = Kernel::getConfig('app:expose_webdocbook', true);
        if (true===$expose_wdb || 'true'===$expose_wdb || '1'===$expose_wdb) {
            $this->response->addHeader('Composed-by', $app_name.' '.$app_version.' ('.$app_website.')');
        }

        // the template builder
        $this->setTemplateBuilder(new TemplateBuilder);

        // some PHP configs
        @date_default_timezone_set( Kernel::getConfig('user_config:timezone', 'Europe/London') );
        
        // the internationalization
        $langs = Kernel::getConfig('languages:langs', array('en'=>'English'));
        $i18n_loader_opts = array(
            'language_directory'            => Kernel::getPath('i18n'),
            'language_strings_db_directory' => Kernel::getPath('user_config'),
            'language_strings_db_filename'  => basename(Kernel::get('app_i18n_filepath')),
            'force_rebuild'                 => true,
            'available_languages'           => array_combine(array_keys($langs), array_keys($langs)),
        );

        if (Kernel::isDevMode()) {
            $i18n_loader_opts['show_untranslated'] = true;
        }
        $translator = I18n::getInstance(new I18n_Loader($i18n_loader_opts));

        // language
        $def_ln = Kernel::getConfig('languages:default', 'auto');
        if (!empty($def_ln) && $def_ln==='auto') {
            $translator->setDefaultFromHttp();
            $def_ln = Kernel::getConfig('languages:fallback_language', 'en');
        }
        $trans_ln = $translator->getLanguage();
        if (empty($trans_ln)) {
            $translator->setLanguage($def_ln);
        }

        $this->getTemplateBuilder()
            ->getTwigEngine()
            ->addExtension(new I18n_Twig_Extension($translator));
    }
310708
protected function initConfig()
    {
        if (!($this->config instanceof Repository)) {
            $filePath   = $this->configPath();
            if (!is_file($filePath)) {
                throw new Exception("Application config file can not found({$filePath}).");
            }

            $this->setConfig(new Repository(require $filePath));
            date_default_timezone_set($this->config['timezone']);
        }
    }
33937
protected function initAdminDirectory()
    {
        $this->directory = config('admin.directory');

        if (is_dir($this->directory)) {
            $this->line("<error>{$this->directory} directory already exists !</error> ");

            return;
        }

        $this->makeDir('/');
        $this->line('<info>Admin directory was created:</info> '.str_replace(base_path(), '', $this->directory));

        $this->makeDir('Controllers');

        $this->createHomeController();
        $this->createExampleController();
        //$this->createAuthController();
        //$this->createAdministratorController();

        //$this->createMenuFile();
        $this->createBootstrapFile();
        $this->createRoutesFile();

        //$this->copyLanguageFiles();
    }
435464
public function dispatch()
    {
        $request  = Container::getRequest();
        $response = Container::getResponse();
        
        PluginManager::handleApplicationPlugins(PluginManager::STEP_BEFORE_DISPATCH_LOOP);
        //self::debug('Begin dispatch loop...');
        while (!$this->dispatched) {
            
            try {
                PluginManager::handleApplicationPlugins(PluginManager::STEP_BEFORE_ACTION);
                //self::debug('Begin dispatch ' . $request->getController() . '::' . $request->getAction() . ' [' . json_encode($request->getParams()) . ']');
                $this->dispatchProcess($request, $response);
                //self::debug('End dispatch ' . $request->getController() . '::' . $request->getAction() . ' [' . json_encode($request->getParams()) . ']');
                PluginManager::handleApplicationPlugins(PluginManager::STEP_AFTER_ACTION);
            }
            catch (Exception $e) {
                if ($request->getController(false) == 'event' 
                 && $request->getAction(false) == 'error') {
                    throw $e;
                }
                Container::getView()->addValue('exception', $e);
                $this->renderView = true;
                $request->setController('event')->setAction('error');
                $this->setDispatched(false);
            }
        }
        PluginManager::handleApplicationPlugins(PluginManager::STEP_AFTER_DISPATCH_LOOP);
        self::debug('End dispatch loop');
        if ($this->dispatched && $this->renderLayout) {
            $layout = Container::getConfig()->getConfig('layout');
            if ($layout !== null) {
                if (!file_exists($layout)) {
                    throw new ArchException('Layout file ' . $layout . ' not found');
                }
                $response->setBody(Container::getLayout(true)->render($layout));
            }
        }
        if ($this->renderResponse) {
            $response->fixHeaders()->putTypeHeadersInResponse();
            foreach ($response->getHeaders() as $header) {
                header($header);
            }
            $response->executeCallback();
            if ($response->hasBody()) {
                echo $response->getBody();
            }
        }
        return $this;
    }