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 18namespace Fisharebest\Webtrees; 19 20use Closure; 21use DateTime; 22use ErrorException; 23use Exception; 24use Fisharebest\Localization\Locale; 25use Fisharebest\Localization\Locale\LocaleInterface; 26use Fisharebest\Webtrees\Exceptions\Handler; 27use Fisharebest\Webtrees\Http\Controllers\SetupController; 28use Fisharebest\Webtrees\Http\Middleware\CheckCsrf; 29use Fisharebest\Webtrees\Http\Middleware\CheckForMaintenanceMode; 30use Fisharebest\Webtrees\Http\Middleware\Housekeeping; 31use Fisharebest\Webtrees\Http\Middleware\PageHitCounter; 32use Fisharebest\Webtrees\Http\Middleware\UseTransaction; 33use Fisharebest\Webtrees\Services\TimeoutService; 34use League\Flysystem\Adapter\Local; 35use League\Flysystem\Filesystem; 36use PDOException; 37use Symfony\Component\HttpFoundation\JsonResponse; 38use Symfony\Component\HttpFoundation\RedirectResponse; 39use Symfony\Component\HttpFoundation\Request; 40use Symfony\Component\HttpFoundation\Response; 41use Throwable; 42 43// Identify ourself 44define('WT_WEBTREES', 'webtrees'); 45define('WT_VERSION', '2.0.0-dev'); 46define('WT_WEBTREES_URL', 'https://www.webtrees.net/'); 47 48// Location of our modules and themes. These are used as URLs and folder paths. 49define('WT_MODULES_DIR', 'modules_v3/'); 50define('WT_THEMES_DIR', 'themes/'); 51define('WT_ASSETS_URL', 'public/assets-2.0.0/'); // See also webpack.mix.js 52define('WT_CKEDITOR_BASE_URL', 'public/ckeditor-4.5.2-custom/'); 53 54// Enable debugging output on development builds 55define('WT_DEBUG', strpos(WT_VERSION, 'dev') !== false); 56 57// Required version of database tables/columns/indexes/etc. 58define('WT_SCHEMA_VERSION', 40); 59 60// Regular expressions for validating user input, etc. 61define('WT_MINIMUM_PASSWORD_LENGTH', 6); 62define('WT_REGEX_XREF', '[A-Za-z0-9:_-]+'); 63define('WT_REGEX_TAG', '[_A-Z][_A-Z0-9]*'); 64define('WT_REGEX_INTEGER', '-?\d+'); 65define('WT_REGEX_BYTES', '[0-9]+[bBkKmMgG]?'); 66define('WT_REGEX_PASSWORD', '.{' . WT_MINIMUM_PASSWORD_LENGTH . ',}'); 67 68define('WT_UTF8_BOM', "\xEF\xBB\xBF"); // U+FEFF (Byte order mark) 69 70// Alternatives to BMD events for lists, charts, etc. 71define('WT_EVENTS_BIRT', 'BIRT|CHR|BAPM|_BRTM|ADOP'); 72define('WT_EVENTS_DEAT', 'DEAT|BURI|CREM'); 73define('WT_EVENTS_MARR', 'MARR|_NMR'); 74define('WT_EVENTS_DIV', 'DIV|ANUL|_SEPR'); 75 76define('WT_ROOT', __DIR__ . DIRECTORY_SEPARATOR); 77 78// We want to know about all PHP errors during development, and fewer in production. 79if (WT_DEBUG) { 80 error_reporting(E_ALL | E_STRICT | E_NOTICE | E_DEPRECATED); 81} else { 82 error_reporting(E_ALL); 83} 84 85require WT_ROOT . 'vendor/autoload.php'; 86 87// Initialise the DebugBar for development. 88// Use `composer install --dev` on a development build to enable. 89// Note that you may need to increase the size of the fcgi buffers on nginx. 90// e.g. add these lines to your fastcgi_params file: 91// fastcgi_buffers 16 16m; 92// fastcgi_buffer_size 32m; 93DebugBar::init(WT_DEBUG && class_exists('\\DebugBar\\StandardDebugBar')); 94 95// PHP requires a time zone to be set. We'll set a better one later on. 96date_default_timezone_set('UTC'); 97 98// Calculate the base URL, so we can generate absolute URLs. 99$request = Request::createFromGlobals(); 100$request_uri = $request->getSchemeAndHttpHost() . $request->getRequestUri(); 101 102// Remove any PHP script name and parameters. 103$base_uri = preg_replace('/[^\/]+\.php(\?.*)?$/', '', $request_uri); 104define('WT_BASE_URL', $base_uri); 105 106// Convert PHP warnings/notices into exceptions 107set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline): bool { 108 // Ignore errors that are silenced with '@' 109 if (error_reporting() & $errno) { 110 throw new ErrorException($errstr, 0, $errno, $errfile, $errline); 111 } 112 113 return true; 114}); 115 116DebugBar::startMeasure('init database'); 117 118// Load our configuration file, so we can connect to the database 119define('WT_CONFIG_FILE', 'data/config.ini.php'); 120if (!file_exists(WT_ROOT . WT_CONFIG_FILE)) { 121 // No config file. Set one up. 122 define('WT_DATA_DIR', 'data/'); 123 $request = Request::createFromGlobals(); 124 $response = (new SetupController())->setup($request); 125 $response->prepare($request)->send(); 126 127 return; 128} 129 130// Connect to the database 131try { 132 // Read the connection settings and create the database 133 Database::createInstance(parse_ini_file(WT_ROOT . 'data/config.ini.php')); 134 135 // Update the database schema, if necessary. 136 Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', WT_SCHEMA_VERSION); 137} catch (PDOException $ex) { 138 DebugBar::addThrowable($ex); 139 140 define('WT_DATA_DIR', 'data/'); 141 I18N::init(); 142 if ($ex->getCode() === 1045) { 143 // Error during connection? 144 $content = view('errors/database-connection', ['error' => $ex->getMessage()]); 145 } else { 146 // Error in a migration script? 147 $content = view('errors/database-error', ['error' => $ex->getMessage()]); 148 } 149 $html = view('layouts/error', ['content' => $content]); 150 $response = new Response($html, 503); 151 $response->prepare($request)->send(); 152 return; 153} catch (Throwable $ex) { 154 DebugBar::addThrowable($ex); 155 156 define('WT_DATA_DIR', 'data/'); 157 I18N::init(); 158 $content = view('errors/database-connection', ['error' => $ex->getMessage()]); 159 $html = view('layouts/error', ['content' => $content]); 160 $response = new Response($html, 503); 161 $response->prepare($request)->send(); 162 return; 163} 164 165DebugBar::stopMeasure('init database'); 166 167// The config.ini.php file must always be in a fixed location. 168// Other user files can be stored elsewhere... 169define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR); 170 171// Some broken servers block access to their own temp folder using open_basedir... 172$data_dir = new Filesystem(new Local(WT_DATA_DIR)); 173$data_dir->createDir('tmp'); 174putenv('TMPDIR=' . WT_DATA_DIR . 'tmp'); 175 176// Request more resources - if we can/want to 177$memory_limit = Site::getPreference('MEMORY_LIMIT'); 178if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) { 179 ini_set('memory_limit', $memory_limit); 180} 181$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME'); 182if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) { 183 set_time_limit((int) $max_execution_time); 184} 185 186// Sessions 187Session::start(); 188 189DebugBar::startMeasure('init i18n'); 190 191// With no parameters, init() looks to the environment to choose a language 192define('WT_LOCALE', I18N::init()); 193Session::put('locale', WT_LOCALE); 194 195DebugBar::stopMeasure('init i18n'); 196 197// Note that the database/webservers may not be synchronised, so use DB time throughout. 198define('WT_TIMESTAMP', (int) Database::prepare("SELECT UNIX_TIMESTAMP()")->fetchOne()); 199 200// Users get their own time-zone. Visitors get the site time-zone. 201try { 202 if (Auth::check()) { 203 date_default_timezone_set(Auth::user()->getPreference('TIMEZONE')); 204 } else { 205 date_default_timezone_set(Site::getPreference('TIMEZONE')); 206 } 207} catch (ErrorException $ex) { 208 // Server upgrades and migrations can leave us with invalid timezone settings. 209 date_default_timezone_set('UTC'); 210} 211 212define('WT_TIMESTAMP_OFFSET', (new DateTime('now'))->getOffset()); 213 214define('WT_CLIENT_JD', 2440588 + (int) ((WT_TIMESTAMP + WT_TIMESTAMP_OFFSET) / 86400)); 215 216// Update the last-login time no more than once a minute 217if (WT_TIMESTAMP - Session::get('activity_time') >= 60) { 218 if (Session::get('masquerade') === null) { 219 Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP); 220 } 221 Session::put('activity_time', WT_TIMESTAMP); 222} 223 224DebugBar::startMeasure('routing'); 225 226// The HTTP request. 227$request = Request::createFromGlobals(); 228$route = $request->get('route'); 229 230try { 231 // Most requests will need the current tree and user. 232 $all_trees = Tree::getAll(); 233 234 $tree = $all_trees[$request->get('ged')] ?? null; 235 236 // No tree specified/available? Choose one. 237 if ($tree === null && $request->getMethod() === Request::METHOD_GET) { 238 $tree = $all_trees[Site::getPreference('DEFAULT_GEDCOM')] ?? array_values($all_trees)[0] ?? null; 239 } 240 241 // Most layouts will require a tree for the page header/footer 242 View::share('tree', $tree); 243 244 // Load the routing table. 245 $routes = require 'routes/web.php'; 246 247 // Find the controller and action for the selected route 248 $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound'; 249 list($controller_name, $action) = explode('@', $controller_action); 250 $controller_class = __NAMESPACE__ . '\\Http\\Controllers\\' . $controller_name; 251 252 // Set up dependency injection for the controllers. 253 $resolver = new Resolver(); 254 $resolver->bind(Resolver::class, $resolver); 255 $resolver->bind(Tree::class, $tree); 256 $resolver->bind(User::class, Auth::user()); 257 $resolver->bind(LocaleInterface::class, Locale::create(WT_LOCALE)); 258 $resolver->bind(TimeoutService::class, new TimeoutService(microtime(true))); 259 $resolver->bind(Filesystem::class, new Filesystem(new Local(WT_DATA_DIR))); 260 261 $controller = $resolver->resolve($controller_class); 262 263 DebugBar::stopMeasure('routing'); 264 265 DebugBar::startMeasure('init theme'); 266 267 // Last theme used? 268 $theme_id = Session::get('theme_id'); 269 // Default for tree 270 if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) { 271 $theme_id = $tree->getPreference('THEME_DIR'); 272 } 273 // Default for site 274 if (!array_key_exists($theme_id, Theme::themeNames())) { 275 $theme_id = Site::getPreference('THEME_DIR'); 276 } 277 // Default 278 if (!array_key_exists($theme_id, Theme::themeNames())) { 279 $theme_id = 'webtrees'; 280 } 281 foreach (Theme::installedThemes() as $theme) { 282 if ($theme->themeId() === $theme_id) { 283 Theme::theme($theme)->init($request, $tree); 284 // Remember this setting 285 if (Site::getPreference('ALLOW_USER_THEMES') === '1') { 286 Session::put('theme_id', $theme_id); 287 } 288 break; 289 } 290 } 291 292 DebugBar::stopMeasure('init theme'); 293 294 // Note that we can't stop this timer, as running the action will 295 // generate the response - which includes (and stops) the timer 296 DebugBar::startMeasure('controller_action', $controller_action); 297 298 $middleware_stack = [ 299 CheckForMaintenanceMode::class, 300 ]; 301 302 if ($request->getMethod() === Request::METHOD_GET) { 303 $middleware_stack[] = PageHitCounter::class; 304 $middleware_stack[] = Housekeeping::class; 305 } 306 307 if ($request->getMethod() === Request::METHOD_POST) { 308 $middleware_stack[] = UseTransaction::class; 309 $middleware_stack[] = CheckCsrf::class; 310 } 311 312 // Apply the middleware using the "onion" pattern. 313 $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure { 314 // Create a closure to apply the middleware. 315 return function (Request $request) use ($middleware, $next, $resolver): Response { 316 return $resolver->resolve($middleware)->handle($request, $next); 317 }; 318 }, function (Request $request) use ($controller, $action, $resolver): Response { 319 $resolver->bind(Request::class, $request); 320 321 return $resolver->dispatch($controller, $action); 322 }); 323 324 $response = call_user_func($pipeline, $request); 325} catch (Exception $exception) { 326 DebugBar::addThrowable($exception); 327 328 $response = (new Handler())->render($request, $exception); 329} 330 331// Send response 332if ($response instanceof RedirectResponse) { 333 // Show the debug data on the next page 334 DebugBar::stackData(); 335} elseif ($response instanceof JsonResponse) { 336 // Use HTTP headers and some jQuery to add debug to the current page. 337 DebugBar::sendDataInHeaders(); 338} 339 340$response->prepare($request)->send(); 341