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