xref: /webtrees/index.php (revision dda6100a2fee6ba4652b4949217b1926b947bbc5)
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 ($errno, $errstr, $errfile, $errline) {
110    // Ignore errors that are silenced with '@'
111    if (error_reporting() & $errno) {
112        throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
113    }
114});
115
116DebugBar::startMeasure('init database');
117
118// Load our configuration file, so we can connect to the database
119define('WT_CONFIG_FILE', 'data/config.ini.php');
120if (!file_exists(WT_ROOT . WT_CONFIG_FILE)) {
121    // No config file. Set one up.
122    define('WT_DATA_DIR', 'data/');
123    $request  = Request::createFromGlobals();
124    $response = (new SetupController())->setup($request);
125    $response->prepare($request)->send();
126
127    return;
128}
129
130// Connect to the database
131try {
132    // Read the connection settings and create the database
133    Database::createInstance(parse_ini_file(WT_ROOT . 'data/config.ini.php'));
134
135    // Update the database schema, if necessary.
136    Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', WT_SCHEMA_VERSION);
137} catch (PDOException $ex) {
138    DebugBar::addThrowable($ex);
139
140    define('WT_DATA_DIR', 'data/');
141    I18N::init();
142    if ($ex->getCode() === 1045) {
143        // Error during connection?
144        $content = view('errors/database-connection', ['error' => $ex->getMessage()]);
145    } else {
146        // Error in a migration script?
147        $content = view('errors/database-error', ['error' => $ex->getMessage()]);
148    }
149    $html     = view('layouts/error', ['content' => $content]);
150    $response = new Response($html, 503);
151    $response->prepare($request)->send();
152    return;
153} catch (Throwable $ex) {
154    DebugBar::addThrowable($ex);
155
156    define('WT_DATA_DIR', 'data/');
157    I18N::init();
158    $content  = view('errors/database-connection', ['error' => $ex->getMessage()]);
159    $html     = view('layouts/error', ['content' => $content]);
160    $response = new Response($html, 503);
161    $response->prepare($request)->send();
162    return;
163}
164
165DebugBar::stopMeasure('init database');
166
167// The config.ini.php file must always be in a fixed location.
168// Other user files can be stored elsewhere...
169define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR);
170
171// Some broken servers block access to their own temp folder using open_basedir...
172$data_dir = new Filesystem(new Local(WT_DATA_DIR));
173$data_dir->createDir('tmp');
174putenv('TMPDIR=' . WT_DATA_DIR . 'tmp');
175
176// Request more resources - if we can/want to
177$memory_limit = Site::getPreference('MEMORY_LIMIT');
178if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) {
179    ini_set('memory_limit', $memory_limit);
180}
181$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME');
182if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
183    set_time_limit((int) $max_execution_time);
184}
185
186// Sessions
187Session::start();
188
189DebugBar::startMeasure('init i18n');
190
191// With no parameters, init() looks to the environment to choose a language
192define('WT_LOCALE', I18N::init());
193Session::put('locale', WT_LOCALE);
194
195DebugBar::stopMeasure('init i18n');
196
197// Note that the database/webservers may not be synchronised, so use DB time throughout.
198define('WT_TIMESTAMP', (int) Database::prepare("SELECT UNIX_TIMESTAMP()")->fetchOne());
199
200// Users get their own time-zone. Visitors get the site time-zone.
201try {
202    if (Auth::check()) {
203        date_default_timezone_set(Auth::user()->getPreference('TIMEZONE'));
204    } else {
205        date_default_timezone_set(Site::getPreference('TIMEZONE'));
206    }
207} catch (ErrorException $ex) {
208    // Server upgrades and migrations can leave us with invalid timezone settings.
209    date_default_timezone_set('UTC');
210}
211
212define('WT_TIMESTAMP_OFFSET', date_offset_get(new DateTime('now')));
213
214define('WT_CLIENT_JD', 2440588 + (int) ((WT_TIMESTAMP + WT_TIMESTAMP_OFFSET) / 86400));
215
216// Update the last-login time no more than once a minute
217if (WT_TIMESTAMP - Session::get('activity_time') >= 60) {
218    if (Session::get('masquerade') === null) {
219        Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP);
220    }
221    Session::put('activity_time', WT_TIMESTAMP);
222}
223
224DebugBar::startMeasure('routing');
225
226// The HTTP request.
227$request = Request::createFromGlobals();
228$route   = $request->get('route');
229
230try {
231    // Most requests will need the current tree and user.
232    $all_trees = Tree::getAll();
233
234    $tree = $all_trees[$request->get('ged')] ?? null;
235
236    // No tree specified/available?  Choose one.
237    if ($tree === null && $request->getMethod() === Request::METHOD_GET) {
238        $tree = $all_trees[Site::getPreference('DEFAULT_GEDCOM')] ?? array_values($all_trees)[0] ?? null;
239    }
240
241    $request->attributes->set('tree', $tree);
242    $request->attributes->set('user', Auth::user());
243
244    // Most layouts will require a tree for the page header/footer
245    View::share('tree', $tree);
246
247    // Load the routing table.
248    $routes = require 'routes/web.php';
249
250    // Find the controller and action for the selected route
251    $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound';
252    list($controller_name, $action) = explode('@', $controller_action);
253    $controller_class = __NAMESPACE__ . '\\Http\\Controllers\\' . $controller_name;
254
255    // Set up dependency injection for the controllers.
256    $resolver = new Resolver();
257    $resolver->bind(Resolver::class, $resolver);
258    $resolver->bind(Tree::class, $tree);
259    $resolver->bind(User::class, Auth::user());
260    $resolver->bind(LocaleInterface::class, Locale::create(WT_LOCALE));
261
262    $controller = $resolver->resolve($controller_class);
263
264    DebugBar::stopMeasure('routing');
265
266    DebugBar::startMeasure('init theme');
267
268    // Last theme used?
269    $theme_id = Session::get('theme_id');
270    // Default for tree
271    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
272        $theme_id = $tree->getPreference('THEME_DIR');
273    }
274    // Default for site
275    if (!array_key_exists($theme_id, Theme::themeNames())) {
276        $theme_id = Site::getPreference('THEME_DIR');
277    }
278    // Default
279    if (!array_key_exists($theme_id, Theme::themeNames())) {
280        $theme_id = 'webtrees';
281    }
282    foreach (Theme::installedThemes() as $theme) {
283        if ($theme->themeId() === $theme_id) {
284            Theme::theme($theme)->init($request, $tree);
285            // Remember this setting
286            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
287                Session::put('theme_id', $theme_id);
288            }
289            break;
290        }
291    }
292
293    DebugBar::stopMeasure('init theme');
294
295    // Note that we can't stop this timer, as running the action will
296    // generate the response - which includes (and stops) the timer
297    DebugBar::startMeasure('controller_action', $controller_action);
298
299    $middleware_stack = [
300        CheckForMaintenanceMode::class,
301    ];
302
303    if ($request->getMethod() === Request::METHOD_GET) {
304        $middleware_stack[] = PageHitCounter::class;
305        $middleware_stack[] = Housekeeping::class;
306    }
307
308    if ($request->getMethod() === Request::METHOD_POST) {
309        $middleware_stack[] = UseTransaction::class;
310        $middleware_stack[] = CheckCsrf::class;
311    }
312
313    // Apply the middleware using the "onion" pattern.
314    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure {
315        // Create a closure to apply the middleware.
316        return function (Request $request) use ($middleware, $next, $resolver): Response {
317            return $resolver->resolve($middleware)->handle($request, $next);
318        };
319    }, function (Request $request) use ($controller, $action, $resolver): Response {
320        $resolver->bind(Request::class, $request);
321
322        return $resolver->dispatch($controller, $action);
323    });
324
325    $response = call_user_func($pipeline, $request);
326} catch (Exception $exception) {
327    DebugBar::addThrowable($exception);
328
329    $response = (new Handler())->render($request, $exception);
330}
331
332// Send response
333if ($response instanceof RedirectResponse) {
334    // Show the debug data on the next page
335    DebugBar::stackData();
336} elseif ($response instanceof JsonResponse) {
337    // Use HTTP headers and some jQuery to add debug to the current page.
338    DebugBar::sendDataInHeaders();
339}
340
341$response->prepare($request)->send();
342