xref: /webtrees/index.php (revision e9fd18363a906a73ba946d65139e8b01c0674c1b)
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 Symfony\Component\HttpFoundation\JsonResponse;
37use Symfony\Component\HttpFoundation\RedirectResponse;
38use Symfony\Component\HttpFoundation\Request;
39use Symfony\Component\HttpFoundation\Response;
40use Throwable;
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
75define('WT_ROOT', __DIR__ . DIRECTORY_SEPARATOR);
76
77// Keep track of time so we can handle timeouts gracefully.
78define('WT_START_TIME', microtime(true));
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
121define('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, 503);
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, 503);
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
191DebugBar::startMeasure('init i18n');
192
193// With no parameters, init() looks to the environment to choose a language
194define('WT_LOCALE', I18N::init());
195Session::put('locale', WT_LOCALE);
196
197DebugBar::stopMeasure('init i18n');
198
199// Note that the database/webservers may not be synchronised, so use DB time throughout.
200define('WT_TIMESTAMP', (int) Database::prepare("SELECT UNIX_TIMESTAMP()")->fetchOne());
201
202// Users get their own time-zone. Visitors get the site time-zone.
203try {
204    if (Auth::check()) {
205        date_default_timezone_set(Auth::user()->getPreference('TIMEZONE'));
206    } else {
207        date_default_timezone_set(Site::getPreference('TIMEZONE'));
208    }
209} catch (ErrorException $ex) {
210    // Server upgrades and migrations can leave us with invalid timezone settings.
211    date_default_timezone_set('UTC');
212}
213
214define('WT_TIMESTAMP_OFFSET', date_offset_get(new DateTime('now')));
215
216define('WT_CLIENT_JD', 2440588 + (int) ((WT_TIMESTAMP + WT_TIMESTAMP_OFFSET) / 86400));
217
218// Update the last-login time no more than once a minute
219if (WT_TIMESTAMP - Session::get('activity_time') >= 60) {
220    if (Session::get('masquerade') === null) {
221        Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP);
222    }
223    Session::put('activity_time', WT_TIMESTAMP);
224}
225
226DebugBar::startMeasure('routing');
227
228// The HTTP request.
229$request = Request::createFromGlobals();
230$route   = $request->get('route');
231
232try {
233    // Most requests will need the current tree and user.
234    $all_trees = Tree::getAll();
235
236    $tree = $all_trees[$request->get('ged')] ?? null;
237
238    // No tree specified/available?  Choose one.
239    if ($tree === null && $request->getMethod() === Request::METHOD_GET) {
240        $tree = $all_trees[Site::getPreference('DEFAULT_GEDCOM')] ?? array_values($all_trees)[0] ?? null;
241    }
242
243    $request->attributes->set('tree', $tree);
244    $request->attributes->set('user', Auth::user());
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 = __NAMESPACE__ . '\\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, Locale::create(WT_LOCALE));
263
264    $controller = $resolver->resolve($controller_class);
265
266    DebugBar::stopMeasure('routing');
267
268    DebugBar::startMeasure('init theme');
269
270    // Last theme used?
271    $theme_id = Session::get('theme_id');
272    // Default for tree
273    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
274        $theme_id = $tree->getPreference('THEME_DIR');
275    }
276    // Default for site
277    if (!array_key_exists($theme_id, Theme::themeNames())) {
278        $theme_id = Site::getPreference('THEME_DIR');
279    }
280    // Default
281    if (!array_key_exists($theme_id, Theme::themeNames())) {
282        $theme_id = 'webtrees';
283    }
284    foreach (Theme::installedThemes() as $theme) {
285        if ($theme->themeId() === $theme_id) {
286            Theme::theme($theme)->init($request, $tree);
287            // Remember this setting
288            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
289                Session::put('theme_id', $theme_id);
290            }
291            break;
292        }
293    }
294
295    DebugBar::stopMeasure('init theme');
296
297    // Note that we can't stop this timer, as running the action will
298    // generate the response - which includes (and stops) the timer
299    DebugBar::startMeasure('controller_action', $controller_action);
300
301    $middleware_stack = [
302        CheckForMaintenanceMode::class,
303    ];
304
305    if ($request->getMethod() === Request::METHOD_GET) {
306        $middleware_stack[] = PageHitCounter::class;
307        $middleware_stack[] = Housekeeping::class;
308    }
309
310    if ($request->getMethod() === Request::METHOD_POST) {
311        $middleware_stack[] = UseTransaction::class;
312        $middleware_stack[] = CheckCsrf::class;
313    }
314
315    // Apply the middleware using the "onion" pattern.
316    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure {
317        // Create a closure to apply the middleware.
318        return function (Request $request) use ($middleware, $next, $resolver): Response {
319            return $resolver->resolve($middleware)->handle($request, $next);
320        };
321    }, function (Request $request) use ($controller, $action, $resolver): Response {
322        $resolver->bind(Request::class, $request);
323
324        return $resolver->dispatch($controller, $action);
325    });
326
327    $response = call_user_func($pipeline, $request);
328} catch (Exception $exception) {
329    DebugBar::addThrowable($exception);
330
331    $response = (new Handler())->render($request, $exception);
332}
333
334// Send response
335if ($response instanceof RedirectResponse) {
336    // Show the debug data on the next page
337    DebugBar::stackData();
338} elseif ($response instanceof JsonResponse) {
339    // Use HTTP headers and some jQuery to add debug to the current page.
340    DebugBar::sendDataInHeaders();
341}
342
343$response->prepare($request)->send();
344