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