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