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