Application.php 8.62 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php

namespace ACP3\Core;

use ACP3\Core\Modules;
use ACP3\Core\Logger as ACP3Logger;
use Monolog\ErrorHandler;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Patchwork\Utf8;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\DependencyInjection\ContainerBuilder;
14
use Symfony\Component\DependencyInjection\ContainerInterface;
15 16 17 18 19 20 21 22
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;

/**
 * Bootstraps the application
 * @package ACP3
 */
23
class Application extends AbstractApplication
24 25 26 27 28 29 30
{
    /**
     * @var array
     */
    protected $systemSettings = [];

    /**
31
     * @inheritdoc
32 33 34 35 36 37 38 39 40 41 42
     */
    public function run()
    {
        $this->defineDirConstants();
        $this->startupChecks();
        $this->setErrorHandler();
        $this->initializeClasses();
        $this->outputPage();
    }

    /**
43
     * @inheritdoc
44 45 46 47 48 49
     */
    public function startupChecks()
    {
        // Standardzeitzone festlegen
        date_default_timezone_set('UTC');

50
        $this->checkForDbConfig();
51 52 53
    }

    /**
54
     * @inheritdoc
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
     */
    public function defineDirConstants()
    {
        define('PHP_SELF', htmlentities($_SERVER['SCRIPT_NAME']));
        define('ROOT_DIR', substr(PHP_SELF, 0, strrpos(PHP_SELF, '/') + 1));
        define('HOST_NAME', 'http://' . $_SERVER['HTTP_HOST']);
        define('ROOT_DIR_ABSOLUTE', HOST_NAME . ROOT_DIR);
        define('ACP3_DIR', ACP3_ROOT_DIR . 'ACP3/');
        define('CLASSES_DIR', ACP3_DIR . 'Core/');
        define('MODULES_DIR', ACP3_DIR . 'Modules/');
        define('LIBRARIES_DIR', ACP3_ROOT_DIR . 'libraries/');
        define('UPLOADS_DIR', ACP3_ROOT_DIR . 'uploads/');
        define('CACHE_DIR', UPLOADS_DIR . 'cache/');
    }

    /**
     * Set monolog as the default PHP error handler
     */
    public function setErrorHandler()
    {
        $errorLevelMap = [
            E_ERROR => Logger::ERROR,
            E_WARNING => Logger::WARNING,
            E_PARSE => Logger::ERROR,
            E_NOTICE => Logger::NOTICE,
            E_CORE_ERROR => Logger::ERROR,
            E_CORE_WARNING => Logger::WARNING,
            E_COMPILE_ERROR => Logger::ERROR,
            E_COMPILE_WARNING => Logger::WARNING,
            E_USER_ERROR => Logger::ERROR,
            E_USER_WARNING => Logger::WARNING,
            E_USER_NOTICE => Logger::NOTICE,
            E_STRICT => Logger::WARNING,
            E_RECOVERABLE_ERROR => Logger::ERROR,
            E_DEPRECATED => Logger::WARNING,
            E_USER_DEPRECATED => Logger::WARNING,
        ];

        $stream = new StreamHandler(UPLOADS_DIR . 'logs/system.log', Logger::NOTICE);
        $stream->setFormatter(new LineFormatter(null, null, true));

        $logger = new Logger('system', [$stream]);
        ErrorHandler::register($logger, $errorLevelMap);
    }

    /**
101
     * Checks, whether the maintenance mode is active
102 103 104 105 106 107
     */
    private function _checkForMaintenanceMode()
    {
        $request = $this->container->get('core.request');

        if ((bool)$this->systemSettings['maintenance_mode'] === true &&
108
            ($request->area !== 'admin' && strpos($request->query, 'users/index/login/') !== 0)
109 110 111 112 113 114 115 116 117 118 119 120
        ) {
            header('HTTP/1.0 503 Service Unavailable');

            $view = $this->container->get('core.view');
            $view->assign('PAGE_TITLE', 'ACP3');
            $view->assign('CONTENT', $this->systemSettings['maintenance_message']);
            $view->displayTemplate('system/maintenance.tpl');
            exit;
        }
    }

    /**
121
     * @inheritdoc
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
     */
    public function initializeClasses()
    {
        Utf8\Bootup::initAll(); // Enables the portability layer and configures PHP for UTF-8
        Utf8\Bootup::filterRequestUri(); // Redirects to an UTF-8 encoded URL if it's not already the case
        Utf8\Bootup::filterRequestInputs(); // Normalizes HTTP inputs to UTF-8 NFC

        $file = CACHE_DIR . 'sql/container.php';
        $containerConfigCache = new ConfigCache($file, (defined('DEBUG') && DEBUG === true));

        if (!$containerConfigCache->isFresh()) {
            $containerBuilder = new ContainerBuilder();
            $loader = new YamlFileLoader($containerBuilder, new FileLocator(__DIR__));
            $loader->load(CLASSES_DIR . 'config/services.yml');
            $loader->load(CLASSES_DIR . 'View/Renderer/Smarty/config/services.yml');

            // Try to get all available services
            /** @var Modules $modules */
            $modules = $containerBuilder->get('core.modules');
            $activeModules = $modules->getActiveModules();
            $moduleNamespaces = $modules->getModuleNamespaces();

            foreach ($activeModules as $module) {
                foreach ($moduleNamespaces as $namespace) {
                    $path = MODULES_DIR . $namespace . '/' . $module['dir'] . '/config/services.yml';

                    if (is_file($path)) {
                        $loader->load($path);
                    }
                }
            }

            $containerBuilder->compile();

            $dumper = new PhpDumper($containerBuilder);
            $containerConfigCache->write(
                $dumper->dump(['class' => 'ACP3ServiceContainer']),
                $containerBuilder->getResources()
            );
        }

        require_once $file;
        $this->container = new \ACP3ServiceContainer();

        // Load system settings
        $this->systemSettings = $this->container->get('core.config')->getSettings('system');

        $this->container->get('core.auth')->authenticate();

        $this->_setThemeConstants();

        $this->container->get('core.view')->setRenderer('smarty');
    }

    /**
     * Pfade zum Theme setzen
     */
    private function _setThemeConstants()
    {
        define('DESIGN_PATH', ROOT_DIR . 'designs/' . $this->systemSettings['design'] . '/');
        define('DESIGN_PATH_INTERNAL', ACP3_ROOT_DIR . 'designs/' . $this->systemSettings['design'] . '/');
        define('DESIGN_PATH_ABSOLUTE', HOST_NAME . DESIGN_PATH);
    }

    /**
187
     * @inheritdoc
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
     */
    public function outputPage()
    {
        $this->_checkForMaintenanceMode();

        /** @var \ACP3\Core\Request $request */
        $request = $this->container->get('core.request');
        $request->processQuery();

        /** @var \ACP3\Core\Redirect $redirect */
        $redirect = $this->container->get('core.redirect');

        try {
            $frontController = new FrontController($this->container);
            $frontController->dispatch();
        } catch (Exceptions\ResultNotExists $e) {
            if ($e->getMessage()) {
                ACP3Logger::error('404', $e);
            } else {
                ACP3Logger::error('404', 'Could not find any results for request: ' . $request->query);
            }

            $redirect->temporary('errors/index/404');
        } catch (Exceptions\UnauthorizedAccess $e) {
            $redirectUri = base64_encode($request->originalQuery);
            $redirect->temporary('users/index/login/redirect_' . $redirectUri);
        } catch (Exceptions\AccessForbidden $e) {
            $redirect->temporary('errors/index/403');
        } catch (Exceptions\ControllerActionNotFound $e) {
            ACP3Logger::error('404', 'Request: ' . $request->query);
            ACP3Logger::error('404', $e);

220
            $this->handleException($e, $redirect, 'errors/index/404');
221 222 223
        } catch (\Exception $e) {
            ACP3Logger::error('exception', $e);

224
            $this->handleException($e, $redirect, 'errors/index/500');
225 226 227 228
        }
    }

    /**
229
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
230
     */
231
    public function setContainer(ContainerInterface $container)
232 233 234 235 236 237 238
    {
        $this->container = $container;
    }

    /**
     * Renders an exception
     *
239
     * @param string $errorMessage
240 241 242 243 244 245 246 247 248
     */
    private function _renderApplicationException($errorMessage)
    {
        $view = $this->container->get('core.view');
        $view->assign('ROOT_DIR', ROOT_DIR);
        $view->assign('PAGE_TITLE', 'ACP3');
        $view->assign('CONTENT', $errorMessage);
        $view->displayTemplate('system/exception.tpl');
    }
249 250

    /**
251 252 253
     * @param \Exception          $exception
     * @param \ACP3\Core\Redirect $redirect
     * @param string              $path
254 255 256 257 258 259 260 261 262 263
     */
    protected function handleException(\Exception $exception, Redirect $redirect, $path)
    {
        if (defined('DEBUG') && DEBUG === true) {
            $errorMessage = $exception->getMessage();
            $this->_renderApplicationException($errorMessage);
        } else {
            $redirect->temporary($path);
        }
    }
264
}