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