xref: /webtrees/index.php (revision 708b06c1245be7c6dea40826c3ffd62805f375b0)
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
120const WT_CONFIG_FILE = 'data/config.ini.php';
121
122// Connect to the database
123try {
124    // No config file? Run the setup wizard
125    if (!file_exists(WT_ROOT . WT_CONFIG_FILE)) {
126        define('WT_DATA_DIR', 'data/');
127        $request    = Request::createFromGlobals();
128        $controller = new SetupController();
129        $response   = $controller->setup($request);
130        $response->prepare($request)->send();
131
132        return;
133    }
134
135    $database_config = parse_ini_file(WT_ROOT . WT_CONFIG_FILE);
136
137    if ($database_config === false) {
138        throw new Exception('Invalid config file: ' . WT_CONFIG_FILE);
139    }
140
141    // Read the connection settings and create the database
142    Database::createInstance($database_config);
143
144    // Update the database schema, if necessary.
145    Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', WT_SCHEMA_VERSION);
146} catch (PDOException $ex) {
147    DebugBar::addThrowable($ex);
148
149    define('WT_DATA_DIR', 'data/');
150    I18N::init();
151    if ($ex->getCode() === 1045) {
152        // Error during connection?
153        $content = view('errors/database-connection', ['error' => $ex->getMessage()]);
154    } else {
155        // Error in a migration script?
156        $content = view('errors/database-error', ['error' => $ex->getMessage()]);
157    }
158    $html     = view('layouts/error', ['content' => $content]);
159    $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE);
160    $response->prepare($request)->send();
161    return;
162} catch (Throwable $ex) {
163    DebugBar::addThrowable($ex);
164
165    define('WT_DATA_DIR', 'data/');
166    I18N::init();
167    $content  = view('errors/database-connection', ['error' => $ex->getMessage()]);
168    $html     = view('layouts/error', ['content' => $content]);
169    $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE);
170    $response->prepare($request)->send();
171    return;
172}
173
174DebugBar::stopMeasure('init database');
175
176// The config.ini.php file must always be in a fixed location.
177// Other user files can be stored elsewhere...
178define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR);
179
180// Some broken servers block access to their own temp folder using open_basedir...
181$data_dir = new Filesystem(new Local(WT_DATA_DIR));
182$data_dir->createDir('tmp');
183putenv('TMPDIR=' . WT_DATA_DIR . 'tmp');
184
185// Request more resources - if we can/want to
186$memory_limit = Site::getPreference('MEMORY_LIMIT');
187if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) {
188    ini_set('memory_limit', $memory_limit);
189}
190$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME');
191if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
192    set_time_limit((int) $max_execution_time);
193}
194
195// Sessions
196Session::start();
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', (new DateTime('now'))->getOffset());
214
215define('WT_CLIENT_JD', 2440588 + intdiv(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', (string) 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    // Select a locale
243    define('WT_LOCALE', I18N::init('', $tree));
244    Session::put('locale', WT_LOCALE);
245
246    // Most layouts will require a tree for the page header/footer
247    View::share('tree', $tree);
248
249    // Load the routing table.
250    $routes = require 'routes/web.php';
251
252    // Find the controller and action for the selected route
253    $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound';
254    list($controller_name, $action) = explode('@', $controller_action);
255    $controller_class = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name;
256
257    // Set up dependency injection for the controllers.
258    $resolver = new Resolver();
259    $resolver->bind(Resolver::class, $resolver);
260    $resolver->bind(Tree::class, $tree);
261    $resolver->bind(User::class, Auth::user());
262    $resolver->bind(LocaleInterface::class, WebtreesLocale::create(WT_LOCALE));
263    $resolver->bind(TimeoutService::class, new TimeoutService(microtime(true)));
264    $resolver->bind(Filesystem::class, new Filesystem(new Local(WT_DATA_DIR)));
265
266    $controller = $resolver->resolve($controller_class);
267
268    DebugBar::stopMeasure('routing');
269
270    DebugBar::startMeasure('init theme');
271
272    // Last theme used?
273    $theme_id = Session::get('theme_id');
274    // Default for tree
275    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
276        $theme_id = $tree->getPreference('THEME_DIR');
277    }
278    // Default for site
279    if (!array_key_exists($theme_id, Theme::themeNames())) {
280        $theme_id = Site::getPreference('THEME_DIR');
281    }
282    // Default
283    if (!array_key_exists($theme_id, Theme::themeNames())) {
284        $theme_id = 'webtrees';
285    }
286    foreach (Theme::installedThemes() as $theme) {
287        if ($theme->themeId() === $theme_id) {
288            Theme::theme($theme)->init($request, $tree);
289            // Remember this setting
290            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
291                Session::put('theme_id', $theme_id);
292            }
293            break;
294        }
295    }
296
297    DebugBar::stopMeasure('init theme');
298
299    // Note that we can't stop this timer, as running the action will
300    // generate the response - which includes (and stops) the timer
301    DebugBar::startMeasure('controller_action');
302
303    $middleware_stack = [
304        CheckForMaintenanceMode::class,
305    ];
306
307    if ($request->getMethod() === Request::METHOD_GET) {
308        $middleware_stack[] = PageHitCounter::class;
309        $middleware_stack[] = Housekeeping::class;
310    }
311
312    if ($request->getMethod() === Request::METHOD_POST) {
313        $middleware_stack[] = UseTransaction::class;
314        $middleware_stack[] = CheckCsrf::class;
315    }
316
317    // Apply the middleware using the "onion" pattern.
318    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure {
319        // Create a closure to apply the middleware.
320        return function (Request $request) use ($middleware, $next, $resolver): Response {
321            return $resolver->resolve($middleware)->handle($request, $next);
322        };
323    }, function (Request $request) use ($controller, $action, $resolver): Response {
324        $resolver->bind(Request::class, $request);
325
326        return $resolver->dispatch($controller, $action);
327    });
328
329    $response = call_user_func($pipeline, $request);
330} catch (Exception $exception) {
331    DebugBar::addThrowable($exception);
332
333    $response = (new Handler())->render($request, $exception);
334}
335
336// Send response
337if ($response instanceof RedirectResponse) {
338    // Show the debug data on the next page
339    DebugBar::stackData();
340} elseif ($response instanceof JsonResponse) {
341    // Use HTTP headers and some jQuery to add debug to the current page.
342    DebugBar::sendDataInHeaders();
343}
344
345$response->prepare($request)->send();
346