1<?php 2/** 3 * webtrees: online genealogy 4 * Copyright (C) 2019 webtrees development team 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16declare(strict_types=1); 17 18use Carbon\Carbon; 19use Fisharebest\Localization\Locale as WebtreesLocale; 20use Fisharebest\Localization\Locale\LocaleInterface; 21use Fisharebest\Webtrees\Auth; 22use Fisharebest\Webtrees\Contracts\UserInterface; 23use Fisharebest\Webtrees\Database; 24use Fisharebest\Webtrees\DebugBar; 25use Fisharebest\Webtrees\Exceptions\Handler; 26use Fisharebest\Webtrees\Http\Controllers\SetupController; 27use Fisharebest\Webtrees\Http\Middleware\CheckCsrf; 28use Fisharebest\Webtrees\Http\Middleware\CheckForMaintenanceMode; 29use Fisharebest\Webtrees\Http\Middleware\DebugBarData; 30use Fisharebest\Webtrees\Http\Middleware\Housekeeping; 31use Fisharebest\Webtrees\Http\Middleware\UseTransaction; 32use Fisharebest\Webtrees\I18N; 33use Fisharebest\Webtrees\Module\ModuleThemeInterface; 34use Fisharebest\Webtrees\Module\WebtreesTheme; 35use Fisharebest\Webtrees\Services\MigrationService; 36use Fisharebest\Webtrees\Services\ModuleService; 37use Fisharebest\Webtrees\Services\TimeoutService; 38use Fisharebest\Webtrees\Session; 39use Fisharebest\Webtrees\Site; 40use Fisharebest\Webtrees\Tree; 41use Fisharebest\Webtrees\View; 42use Fisharebest\Webtrees\Webtrees; 43use Illuminate\Cache\ArrayStore; 44use Illuminate\Cache\Repository; 45use Illuminate\Support\Collection; 46use League\Flysystem\Adapter\Local; 47use League\Flysystem\Cached\CachedAdapter; 48use League\Flysystem\Cached\Storage\Memory; 49use League\Flysystem\Filesystem; 50use Symfony\Component\HttpFoundation\Request; 51use Symfony\Component\HttpFoundation\Response; 52 53require __DIR__ . '/vendor/autoload.php'; 54 55const WT_ROOT = __DIR__ . DIRECTORY_SEPARATOR; 56 57Webtrees::init(); 58 59// Initialise the DebugBar for development. 60// Use `composer install --dev` on a development build to enable. 61// Note that you may need to increase the size of the fcgi buffers on nginx. 62// e.g. add these lines to your fastcgi_params file: 63// fastcgi_buffers 16 16m; 64// fastcgi_buffer_size 32m; 65DebugBar::init(class_exists('\\DebugBar\\StandardDebugBar')); 66 67// Use an array cache for database calls, etc. 68app()->instance('cache.array', new Repository(new ArrayStore())); 69 70// Extract the request parameters. 71$request = Request::createFromGlobals(); 72app()->instance(Request::class, $request); 73 74// Dummy value, until we have created our first tree. 75app()->bind(Tree::class, function () { 76 return null; 77}); 78 79// Calculate the base URL, so we can generate absolute URLs. 80$request_uri = $request->getSchemeAndHttpHost() . $request->getRequestUri(); 81 82// Remove any PHP script name and parameters. 83$base_uri = preg_replace('/[^\/]+\.php(\?.*)?$/', '', $request_uri); 84define('WT_BASE_URL', $base_uri); 85 86DebugBar::startMeasure('init database'); 87 88// Connect to the database 89try { 90 // No config file? Run the setup wizard 91 if (!file_exists(Webtrees::CONFIG_FILE)) { 92 define('WT_DATA_DIR', 'data/'); 93 /** @var SetupController $controller */ 94 $controller = app()->make(SetupController::class); 95 $response = $controller->setup($request); 96 $response->prepare($request)->send(); 97 98 return; 99 } 100 101 $database_config = parse_ini_file(Webtrees::CONFIG_FILE); 102 103 if ($database_config === false) { 104 throw new Exception('Invalid config file: ' . Webtrees::CONFIG_FILE); 105 } 106 107 // Read the connection settings and create the database 108 Database::connect($database_config); 109 110 // Update the database schema, if necessary. 111 app()->make(MigrationService::class) 112 ->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION); 113} catch (PDOException $exception) { 114 defined('WT_DATA_DIR') || define('WT_DATA_DIR', 'data/'); 115 I18N::init(); 116 if ($exception->getCode() === 1045) { 117 // Error during connection? 118 $content = view('errors/database-connection', ['error' => $exception->getMessage()]); 119 } else { 120 // Error in a migration script? 121 $content = view('errors/database-error', ['error' => $exception->getMessage()]); 122 } 123 $html = view('layouts/error', ['content' => $content]); 124 $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE); 125 $response->prepare($request)->send(); 126 127 return; 128} catch (Throwable $exception) { 129 defined('WT_DATA_DIR') || define('WT_DATA_DIR', 'data/'); 130 I18N::init(); 131 $content = view('errors/database-connection', ['error' => $exception->getMessage()]); 132 $html = view('layouts/error', ['content' => $content]); 133 $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE); 134 $response->prepare($request)->send(); 135 136 return; 137} 138 139DebugBar::stopMeasure('init database'); 140 141// The config.ini.php file must always be in a fixed location. 142// Other user files can be stored elsewhere... 143define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR); 144 145$filesystem = new Filesystem(new CachedAdapter(new Local(WT_DATA_DIR), new Memory())); 146 147// Request more resources - if we can/want to 148$memory_limit = Site::getPreference('MEMORY_LIMIT'); 149if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) { 150 ini_set('memory_limit', $memory_limit); 151} 152$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME'); 153if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { 154 set_time_limit((int) $max_execution_time); 155} 156 157// Sessions 158Session::start(); 159 160define('WT_TIMESTAMP', Carbon::now('UTC')->timestamp); 161 162// Update the last-login time no more than once a minute 163if (WT_TIMESTAMP - Session::get('activity_time') >= 60) { 164 if (Session::get('masquerade') === null) { 165 Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP); 166 } 167 Session::put('activity_time', WT_TIMESTAMP); 168} 169 170DebugBar::startMeasure('routing'); 171 172try { 173 // Most requests will need the current tree and user. 174 $tree = Tree::findByName($request->get('ged')) ?? null; 175 176 // No tree specified/available? Choose one. 177 if ($tree === null && $request->getMethod() === Request::METHOD_GET) { 178 $tree = Tree::findByName(Site::getPreference('DEFAULT_GEDCOM')) ?? array_values(Tree::getAll())[0] ?? null; 179 } 180 181 // Select a locale 182 define('WT_LOCALE', I18N::init('', $tree)); 183 Session::put('locale', WT_LOCALE); 184 185 // Most layouts will require a tree for the page header/footer 186 View::share('tree', $tree); 187 188 // Load the route and routing table. 189 $route = $request->get('route'); 190 $routes = require 'routes/web.php'; 191 192 // Find the controller and action for the selected route 193 $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound'; 194 [$controller_name, $action] = explode('@', $controller_action); 195 $controller_class = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name; 196 197 app()->instance(Tree::class, $tree); 198 app()->instance(UserInterface::class, Auth::user()); 199 app()->instance(LocaleInterface::class, WebtreesLocale::create(WT_LOCALE)); 200 app()->instance(TimeoutService::class, new TimeoutService(microtime(true))); 201 app()->instance(Filesystem::class, $filesystem); 202 203 $controller = app()->make($controller_class); 204 205 DebugBar::stopMeasure('routing'); 206 207 DebugBar::startMeasure('init theme'); 208 209 /** @var Collection|ModuleThemeInterface[] $themes */ 210 $themes = app()->make(ModuleService::class)->findByInterface(ModuleThemeInterface::class); 211 212 // Last theme used? 213 $theme = $themes->get(Session::get('theme_id', '')); 214 215 // Default for tree? 216 if ($theme === null && $tree instanceof Tree) { 217 $theme = $themes->get($tree->getPreference('THEME_DIR')); 218 } 219 220 // Default for site? 221 if ($theme === null) { 222 $theme = $themes->get(Site::getPreference('THEME_DIR')); 223 } 224 225 // Default 226 if ($theme === null) { 227 $theme = app()->make(WebtreesTheme::class); 228 } 229 230 // Bind this theme into the container 231 app()->instance(ModuleThemeInterface::class, $theme); 232 233 // Remember this setting 234 Session::put('theme_id', $theme->name()); 235 236 DebugBar::stopMeasure('init theme'); 237 238 // Note that we can't stop this timer, as running the action will 239 // generate the response - which includes (and stops) the timer 240 DebugBar::startMeasure('controller_action'); 241 242 $middleware_stack = [ 243 CheckForMaintenanceMode::class, 244 ]; 245 246 if (class_exists(DebugBar::class)) { 247 $middleware_stack[] = DebugBarData::class; 248 } 249 250 if ($request->getMethod() === Request::METHOD_GET) { 251 $middleware_stack[] = Housekeeping::class; 252 } 253 254 if ($request->getMethod() === Request::METHOD_POST) { 255 $middleware_stack[] = UseTransaction::class; 256 $middleware_stack[] = CheckCsrf::class; 257 } 258 259 // Apply the middleware using the "onion" pattern. 260 $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware): Closure { 261 // Create a closure to apply the middleware. 262 return function (Request $request) use ($middleware, $next): Response { 263 return app()->make($middleware)->handle($request, $next); 264 }; 265 }, function (Request $request) use ($controller, $action): Response { 266 return app()->dispatch($controller, $action); 267 }); 268 269 $response = call_user_func($pipeline, $request); 270} catch (Exception $exception) { 271 $response = (new Handler())->render($request, $exception); 272} 273 274// Send response 275$response->prepare($request)->send(); 276