xref: /webtrees/index.php (revision 5ee5c06b93c45111068e599a0853bcff1f24c3c8)
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\Housekeeping;
29use Fisharebest\Webtrees\Http\Middleware\MiddlewareInterface;
30use Fisharebest\Webtrees\Http\Middleware\PageHitCounter;
31use Fisharebest\Webtrees\Http\Middleware\UseTransaction;
32use League\Flysystem\Adapter\Local;
33use League\Flysystem\Filesystem;
34use PDOException;
35use Throwable;
36use Symfony\Component\HttpFoundation\JsonResponse;
37use Symfony\Component\HttpFoundation\RedirectResponse;
38use Symfony\Component\HttpFoundation\Request;
39use Symfony\Component\HttpFoundation\Response;
40
41// Identify ourself
42define('WT_WEBTREES', 'webtrees');
43define('WT_VERSION', '2.0.0-dev');
44define('WT_WEBTREES_URL', 'https://www.webtrees.net/');
45
46// Location of our modules and themes. These are used as URLs and folder paths.
47define('WT_MODULES_DIR', 'modules_v3/');
48define('WT_THEMES_DIR', 'themes/');
49define('WT_ASSETS_URL', 'public/assets-2.0.0/'); // See also webpack.mix.js
50define('WT_CKEDITOR_BASE_URL', 'public/ckeditor-4.5.2-custom/');
51
52// Enable debugging output on development builds
53define('WT_DEBUG', strpos(WT_VERSION, 'dev') !== false);
54
55// Required version of database tables/columns/indexes/etc.
56define('WT_SCHEMA_VERSION', 40);
57
58// Regular expressions for validating user input, etc.
59define('WT_MINIMUM_PASSWORD_LENGTH', 6);
60define('WT_REGEX_XREF', '[A-Za-z0-9:_-]+');
61define('WT_REGEX_TAG', '[_A-Z][_A-Z0-9]*');
62define('WT_REGEX_INTEGER', '-?\d+');
63define('WT_REGEX_BYTES', '[0-9]+[bBkKmMgG]?');
64define('WT_REGEX_PASSWORD', '.{' . WT_MINIMUM_PASSWORD_LENGTH . ',}');
65
66define('WT_UTF8_BOM', "\xEF\xBB\xBF"); // U+FEFF (Byte order mark)
67
68// Alternatives to BMD events for lists, charts, etc.
69define('WT_EVENTS_BIRT', 'BIRT|CHR|BAPM|_BRTM|ADOP');
70define('WT_EVENTS_DEAT', 'DEAT|BURI|CREM');
71define('WT_EVENTS_MARR', 'MARR|_NMR');
72define('WT_EVENTS_DIV', 'DIV|ANUL|_SEPR');
73
74// For performance, it is quicker to refer to files using absolute paths
75define('WT_ROOT', realpath(__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', 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 controller.
256    $resolver = new Resolver;
257    $resolver->bind(Resolver::class, $resolver);
258    $resolver->bind(Tree::class, $tree);
259    $resolver->bind(User::class, Auth::user());
260
261    $controller = $resolver->resolve($controller_class);
262
263    DebugBar::stopMeasure('routing');
264
265    DebugBar::startMeasure('init theme');
266
267    // Last theme used?
268    $theme_id = Session::get('theme_id');
269    // Default for tree
270    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
271        $theme_id = $tree->getPreference('THEME_DIR');
272    }
273    // Default for site
274    if (!array_key_exists($theme_id, Theme::themeNames())) {
275        $theme_id = Site::getPreference('THEME_DIR');
276    }
277    // Default
278    if (!array_key_exists($theme_id, Theme::themeNames())) {
279        $theme_id = 'webtrees';
280    }
281    foreach (Theme::installedThemes() as $theme) {
282        if ($theme->themeId() === $theme_id) {
283            Theme::theme($theme)->init($tree);
284            // Remember this setting
285            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
286                Session::put('theme_id', $theme_id);
287            }
288            break;
289        }
290    }
291
292    DebugBar::stopMeasure('init theme');
293
294    // Note that we can't stop this timer, as running the action will
295    // generate the response - which includes (and stops) the timer
296    DebugBar::startMeasure('controller_action', $controller_action);
297
298    $middleware_stack = [
299        CheckForMaintenanceMode::class,
300    ];
301
302    if ($request->getMethod() === Request::METHOD_GET) {
303        $middleware_stack[] = PageHitCounter::class;
304        $middleware_stack[] = Housekeeping::class;
305    }
306
307    if ($request->getMethod() === Request::METHOD_POST) {
308        $middleware_stack[] = UseTransaction::class;
309        $middleware_stack[] = CheckCsrf::class;
310    }
311
312    // Apply the middleware using the "onion" pattern.
313    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure {
314        // Create a closure to apply the middleware.
315        return function (Request $request) use ($middleware, $next, $resolver): Response {
316            return $resolver->resolve($middleware)->handle($request, $next);
317        };
318    }, function (Request $request) use ($controller, $action, $resolver): Response {
319        $resolver->bind(Request::class, $request);
320
321        return $resolver->dispatch($controller, $action);
322    });
323
324    $response = call_user_func($pipeline, $request);
325} catch (Exception $exception) {
326    DebugBar::addThrowable($exception);
327
328    $response = (new Handler)->render($request, $exception);
329}
330
331// Send response
332if ($response instanceof RedirectResponse) {
333    // Show the debug data on the next page
334    DebugBar::stackData();
335} elseif ($response instanceof JsonResponse) {
336    // Use HTTP headers and some jQuery to add debug to the current page.
337    DebugBar::sendDataInHeaders();
338}
339
340$response->prepare($request)->send();
341