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\Database\Capsule\Manager as DB; 46use Illuminate\Support\Collection; 47use League\Flysystem\Adapter\Local; 48use League\Flysystem\Cached\CachedAdapter; 49use League\Flysystem\Cached\Storage\Memory; 50use League\Flysystem\Filesystem; 51use Symfony\Component\HttpFoundation\Request; 52use Symfony\Component\HttpFoundation\Response; 53 54require __DIR__ . '/vendor/autoload.php'; 55 56const WT_ROOT = __DIR__ . DIRECTORY_SEPARATOR; 57 58Webtrees::init(); 59 60// Initialise the DebugBar for development. 61// Use `composer install --dev` on a development build to enable. 62// Note that you may need to increase the size of the fcgi buffers on nginx. 63// e.g. add these lines to your fastcgi_params file: 64// fastcgi_buffers 16 16m; 65// fastcgi_buffer_size 32m; 66DebugBar::init(class_exists('\\DebugBar\\StandardDebugBar')); 67 68// Use an array cache for database calls, etc. 69app()->instance('cache.array', new Repository(new ArrayStore())); 70 71// Extract the request parameters. 72$request = Request::createFromGlobals(); 73app()->instance(Request::class, $request); 74 75// Dummy value, until we have created our first tree. 76app()->bind(Tree::class, function () { 77 return null; 78}); 79 80// Calculate the base URL, so we can generate absolute URLs. 81$request_uri = $request->getSchemeAndHttpHost() . $request->getRequestUri(); 82 83// Remove any PHP script name and parameters. 84$base_uri = preg_replace('/[^\/]+\.php(\?.*)?$/', '', $request_uri); 85define('WT_BASE_URL', $base_uri); 86 87DebugBar::startMeasure('init database'); 88 89// Connect to the database 90try { 91 // No config file? Run the setup wizard 92 if (!file_exists(Webtrees::CONFIG_FILE)) { 93 define('WT_DATA_DIR', 'data/'); 94 /** @var SetupController $controller */ 95 $controller = app()->make(SetupController::class); 96 $response = $controller->setup($request); 97 $response->prepare($request)->send(); 98 99 return; 100 } 101 102 $database_config = parse_ini_file(Webtrees::CONFIG_FILE); 103 104 if ($database_config === false) { 105 throw new Exception('Invalid config file: ' . Webtrees::CONFIG_FILE); 106 } 107 108 // Read the connection settings and create the database 109 Database::connect($database_config); 110 111 // Update the database schema, if necessary. 112 app()->make(MigrationService::class) 113 ->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION); 114} catch (PDOException $exception) { 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 I18N::init(); 130 $content = view('errors/database-connection', ['error' => $exception->getMessage()]); 131 $html = view('layouts/error', ['content' => $content]); 132 $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE); 133 $response->prepare($request)->send(); 134 135 return; 136} 137 138DebugBar::stopMeasure('init database'); 139 140// The config.ini.php file must always be in a fixed location. 141// Other user files can be stored elsewhere... 142define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR); 143 144$filesystem = new Filesystem(new CachedAdapter(new Local(WT_DATA_DIR), new Memory())); 145 146// Some broken servers block access to their own temp folder using open_basedir... 147$filesystem->createDir('tmp'); 148putenv('TMPDIR=' . WT_DATA_DIR . 'tmp'); 149Swift_Preferences::getInstance()->setTempDir(WT_DATA_DIR . 'tmp'); 150 151// Request more resources - if we can/want to 152$memory_limit = Site::getPreference('MEMORY_LIMIT'); 153if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) { 154 ini_set('memory_limit', $memory_limit); 155} 156$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME'); 157if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { 158 set_time_limit((int) $max_execution_time); 159} 160 161// Sessions 162Session::start(); 163 164// Note that the database/webservers may not be synchronised, so use DB time throughout. 165define('WT_TIMESTAMP', Carbon::now()->timestamp); 166 167// Users get their own time-zone. Visitors get the site time-zone. 168try { 169 if (Auth::check()) { 170 date_default_timezone_set(Auth::user()->getPreference('TIMEZONE')); 171 } else { 172 date_default_timezone_set(Site::getPreference('TIMEZONE')); 173 } 174} catch (ErrorException $exception) { 175 // Server upgrades and migrations can leave us with invalid timezone settings. 176 date_default_timezone_set('UTC'); 177} 178 179define('WT_TIMESTAMP_OFFSET', (new DateTime('now'))->getOffset()); 180 181define('WT_CLIENT_JD', 2440588 + intdiv(WT_TIMESTAMP + WT_TIMESTAMP_OFFSET, 86400)); 182 183// Update the last-login time no more than once a minute 184if (WT_TIMESTAMP - Session::get('activity_time') >= 60) { 185 if (Session::get('masquerade') === null) { 186 Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP); 187 } 188 Session::put('activity_time', WT_TIMESTAMP); 189} 190 191DebugBar::startMeasure('routing'); 192 193try { 194 // Most requests will need the current tree and user. 195 $tree = Tree::findByName($request->get('ged')) ?? null; 196 197 // No tree specified/available? Choose one. 198 if ($tree === null && $request->getMethod() === Request::METHOD_GET) { 199 $tree = Tree::findByName(Site::getPreference('DEFAULT_GEDCOM')) ?? array_values(Tree::getAll())[0] ?? null; 200 } 201 202 // Select a locale 203 define('WT_LOCALE', I18N::init('', $tree)); 204 Session::put('locale', WT_LOCALE); 205 206 // Most layouts will require a tree for the page header/footer 207 View::share('tree', $tree); 208 209 // Load the route and routing table. 210 $route = $request->get('route'); 211 $routes = require 'routes/web.php'; 212 213 // Find the controller and action for the selected route 214 $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound'; 215 [$controller_name, $action] = explode('@', $controller_action); 216 $controller_class = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name; 217 218 app()->instance(Tree::class, $tree); 219 app()->instance(UserInterface::class, Auth::user()); 220 app()->instance(LocaleInterface::class, WebtreesLocale::create(WT_LOCALE)); 221 app()->instance(TimeoutService::class, new TimeoutService(microtime(true))); 222 app()->instance(Filesystem::class, $filesystem); 223 224 $controller = app()->make($controller_class); 225 226 DebugBar::stopMeasure('routing'); 227 228 DebugBar::startMeasure('init theme'); 229 230 /** @var Collection|ModuleThemeInterface[] $themes */ 231 $themes = app()->make(ModuleService::class)->findByInterface(ModuleThemeInterface::class); 232 233 // Last theme used? 234 $theme = $themes->get(Session::get('theme_id', '')); 235 236 // Default for tree? 237 if ($theme === null && $tree instanceof Tree) { 238 $theme = $themes->get($tree->getPreference('THEME_DIR')); 239 } 240 241 // Default for site? 242 if ($theme === null) { 243 $theme = $themes->get(Site::getPreference('THEME_DIR')); 244 } 245 246 // Default 247 if ($theme === null) { 248 $theme = app()->make(WebtreesTheme::class); 249 } 250 251 // Bind this theme into the container 252 app()->instance(ModuleThemeInterface::class, $theme); 253 254 // Remember this setting 255 Session::put('theme_id', $theme->name()); 256 257 DebugBar::stopMeasure('init theme'); 258 259 // Note that we can't stop this timer, as running the action will 260 // generate the response - which includes (and stops) the timer 261 DebugBar::startMeasure('controller_action'); 262 263 $middleware_stack = [ 264 CheckForMaintenanceMode::class, 265 ]; 266 267 if (class_exists(DebugBar::class)) { 268 $middleware_stack[] = DebugBarData::class; 269 } 270 271 if ($request->getMethod() === Request::METHOD_GET) { 272 $middleware_stack[] = Housekeeping::class; 273 } 274 275 if ($request->getMethod() === Request::METHOD_POST) { 276 $middleware_stack[] = UseTransaction::class; 277 $middleware_stack[] = CheckCsrf::class; 278 } 279 280 // Apply the middleware using the "onion" pattern. 281 $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware): Closure { 282 // Create a closure to apply the middleware. 283 return function (Request $request) use ($middleware, $next): Response { 284 return app()->make($middleware)->handle($request, $next); 285 }; 286 }, function (Request $request) use ($controller, $action): Response { 287 return app()->dispatch($controller, $action); 288 }); 289 290 $response = call_user_func($pipeline, $request); 291} catch (Exception $exception) { 292 $response = (new Handler())->render($request, $exception); 293} 294 295// Send response 296$response->prepare($request)->send(); 297