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