xref: /webtrees/index.php (revision cdaafeee7d44ae3491555b0c6eaf2bceea8e9d6e)
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;
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
120// Load our configuration file, so we can connect to the database
121const 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, Response::HTTP_SERVICE_UNAVAILABLE);
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, Response::HTTP_SERVICE_UNAVAILABLE);
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', (new DateTime('now'))->getOffset());
215
216define('WT_CLIENT_JD', 2440588 + intdiv(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    // 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 = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name;
253
254    // Set up dependency injection for the controllers.
255    $resolver = new Resolver();
256    $resolver->bind(Resolver::class, $resolver);
257    $resolver->bind(Tree::class, $tree);
258    $resolver->bind(User::class, Auth::user());
259    $resolver->bind(LocaleInterface::class, Locale::create(WT_LOCALE));
260    $resolver->bind(TimeoutService::class, new TimeoutService(microtime(true)));
261    $resolver->bind(Filesystem::class, new Filesystem(new Local(WT_DATA_DIR)));
262
263    $controller = $resolver->resolve($controller_class);
264
265    DebugBar::stopMeasure('routing');
266
267    DebugBar::startMeasure('init theme');
268
269    // Last theme used?
270    $theme_id = Session::get('theme_id');
271    // Default for tree
272    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
273        $theme_id = $tree->getPreference('THEME_DIR');
274    }
275    // Default for site
276    if (!array_key_exists($theme_id, Theme::themeNames())) {
277        $theme_id = Site::getPreference('THEME_DIR');
278    }
279    // Default
280    if (!array_key_exists($theme_id, Theme::themeNames())) {
281        $theme_id = 'webtrees';
282    }
283    foreach (Theme::installedThemes() as $theme) {
284        if ($theme->themeId() === $theme_id) {
285            Theme::theme($theme)->init($request, $tree);
286            // Remember this setting
287            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
288                Session::put('theme_id', $theme_id);
289            }
290            break;
291        }
292    }
293
294    DebugBar::stopMeasure('init theme');
295
296    // Note that we can't stop this timer, as running the action will
297    // generate the response - which includes (and stops) the timer
298    DebugBar::startMeasure('controller_action', $controller_action);
299
300    $middleware_stack = [
301        CheckForMaintenanceMode::class,
302    ];
303
304    if ($request->getMethod() === Request::METHOD_GET) {
305        $middleware_stack[] = PageHitCounter::class;
306        $middleware_stack[] = Housekeeping::class;
307    }
308
309    if ($request->getMethod() === Request::METHOD_POST) {
310        $middleware_stack[] = UseTransaction::class;
311        $middleware_stack[] = CheckCsrf::class;
312    }
313
314    // Apply the middleware using the "onion" pattern.
315    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware) use ($resolver): Closure {
316        // Create a closure to apply the middleware.
317        return function (Request $request) use ($middleware, $next, $resolver): Response {
318            return $resolver->resolve($middleware)->handle($request, $next);
319        };
320    }, function (Request $request) use ($controller, $action, $resolver): Response {
321        $resolver->bind(Request::class, $request);
322
323        return $resolver->dispatch($controller, $action);
324    });
325
326    $response = call_user_func($pipeline, $request);
327} catch (Exception $exception) {
328    DebugBar::addThrowable($exception);
329
330    $response = (new Handler())->render($request, $exception);
331}
332
333// Send response
334if ($response instanceof RedirectResponse) {
335    // Show the debug data on the next page
336    DebugBar::stackData();
337} elseif ($response instanceof JsonResponse) {
338    // Use HTTP headers and some jQuery to add debug to the current page.
339    DebugBar::sendDataInHeaders();
340}
341
342$response->prepare($request)->send();
343