xref: /webtrees/index.php (revision e5a6b4d4f6f6e7ff2fba7ae2cf27546ae68a79cc)
1<?php
2/**
3 * webtrees: online genealogy
4 * Copyright (C) 2019 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 as WebtreesLocale;
19use Fisharebest\Localization\Locale\LocaleInterface;
20use Fisharebest\Webtrees\Auth;
21use Fisharebest\Webtrees\Contracts\UserInterface;
22use Fisharebest\Webtrees\Database;
23use Fisharebest\Webtrees\DebugBar;
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\DebugBarData;
29use Fisharebest\Webtrees\Http\Middleware\Housekeeping;
30use Fisharebest\Webtrees\Http\Middleware\UseTransaction;
31use Fisharebest\Webtrees\I18N;
32use Fisharebest\Webtrees\Module\ModuleThemeInterface;
33use Fisharebest\Webtrees\Module\WebtreesTheme;
34use Fisharebest\Webtrees\Services\ModuleService;
35use Fisharebest\Webtrees\Services\TimeoutService;
36use Fisharebest\Webtrees\Session;
37use Fisharebest\Webtrees\Site;
38use Fisharebest\Webtrees\Tree;
39use Fisharebest\Webtrees\User;
40use Fisharebest\Webtrees\View;
41use Fisharebest\Webtrees\Webtrees;
42use Illuminate\Cache\ArrayStore;
43use Illuminate\Cache\Repository;
44use Illuminate\Database\Capsule\Manager as DB;
45use Illuminate\Support\Collection;
46use League\Flysystem\Adapter\Local;
47use League\Flysystem\Cached\CachedAdapter;
48use League\Flysystem\Cached\Storage\Memory;
49use League\Flysystem\Filesystem;
50use Symfony\Component\HttpFoundation\Request;
51use Symfony\Component\HttpFoundation\Response;
52
53require __DIR__ . '/vendor/autoload.php';
54
55// Regular expressions for validating user input, etc.
56const WT_MINIMUM_PASSWORD_LENGTH = 6;
57const WT_REGEX_PASSWORD          = '.{' . WT_MINIMUM_PASSWORD_LENGTH . ',}';
58
59const WT_ROOT = __DIR__ . DIRECTORY_SEPARATOR;
60
61Webtrees::init();
62
63// Initialise the DebugBar for development.
64// Use `composer install --dev` on a development build to enable.
65// Note that you may need to increase the size of the fcgi buffers on nginx.
66// e.g. add these lines to your fastcgi_params file:
67// fastcgi_buffers 16 16m;
68// fastcgi_buffer_size 32m;
69DebugBar::init(class_exists('\\DebugBar\\StandardDebugBar'));
70
71// Use an array cache for database calls, etc.
72app()->instance('cache.array', new Repository(new ArrayStore()));
73
74// Extract the request parameters.
75$request = Request::createFromGlobals();
76app()->instance(Request::class, $request);
77
78// Dummy value, until we have created our first tree.
79app()->bind(Tree::class, function () {
80    return null;
81});
82
83// Calculate the base URL, so we can generate absolute URLs.
84$request_uri = $request->getSchemeAndHttpHost() . $request->getRequestUri();
85
86// Remove any PHP script name and parameters.
87$base_uri = preg_replace('/[^\/]+\.php(\?.*)?$/', '', $request_uri);
88define('WT_BASE_URL', $base_uri);
89
90DebugBar::startMeasure('init database');
91
92// Connect to the database
93try {
94    // No config file? Run the setup wizard
95    if (!file_exists(Webtrees::CONFIG_FILE)) {
96        define('WT_DATA_DIR', 'data/');
97        $controller = new SetupController();
98        $response   = $controller->setup($request);
99        $response->prepare($request)->send();
100
101        return;
102    }
103
104    $database_config = parse_ini_file(Webtrees::CONFIG_FILE);
105
106    if ($database_config === false) {
107        throw new Exception('Invalid config file: ' . Webtrees::CONFIG_FILE);
108    }
109
110    // Read the connection settings and create the database
111    Database::createInstance($database_config);
112
113    // Update the database schema, if necessary.
114    Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
115} catch (PDOException $exception) {
116    define('WT_DATA_DIR', 'data/');
117    I18N::init();
118    if ($exception->getCode() === 1045) {
119        // Error during connection?
120        $content = view('errors/database-connection', ['error' => $exception->getMessage()]);
121    } else {
122        // Error in a migration script?
123        $content = view('errors/database-error', ['error' => $exception->getMessage()]);
124    }
125    $html     = view('layouts/error', ['content' => $content]);
126    $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE);
127    $response->prepare($request)->send();
128
129    return;
130} catch (Throwable $exception) {
131    define('WT_DATA_DIR', 'data/');
132    I18N::init();
133    $content  = view('errors/database-connection', ['error' => $exception->getMessage()]);
134    $html     = view('layouts/error', ['content' => $content]);
135    $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE);
136    $response->prepare($request)->send();
137
138    return;
139}
140
141DebugBar::stopMeasure('init database');
142
143// The config.ini.php file must always be in a fixed location.
144// Other user files can be stored elsewhere...
145define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR);
146
147$filesystem = new Filesystem(new CachedAdapter(new Local(WT_DATA_DIR), new Memory()));
148
149// Some broken servers block access to their own temp folder using open_basedir...
150$filesystem->createDir('tmp');
151putenv('TMPDIR=' . WT_DATA_DIR . 'tmp');
152Swift_Preferences::getInstance()->setTempDir(WT_DATA_DIR . 'tmp');
153
154// Request more resources - if we can/want to
155$memory_limit = Site::getPreference('MEMORY_LIMIT');
156if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) {
157    ini_set('memory_limit', $memory_limit);
158}
159$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME');
160if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
161    set_time_limit((int) $max_execution_time);
162}
163
164// Sessions
165Session::start();
166
167// Note that the database/webservers may not be synchronised, so use DB time throughout.
168define('WT_TIMESTAMP', DB::select('SELECT UNIX_TIMESTAMP() AS unix_timestamp')[0]->unix_timestamp);
169
170// Users get their own time-zone. Visitors get the site time-zone.
171try {
172    if (Auth::check()) {
173        date_default_timezone_set(Auth::user()->getPreference('TIMEZONE'));
174    } else {
175        date_default_timezone_set(Site::getPreference('TIMEZONE'));
176    }
177} catch (ErrorException $exception) {
178    // Server upgrades and migrations can leave us with invalid timezone settings.
179    date_default_timezone_set('UTC');
180}
181
182define('WT_TIMESTAMP_OFFSET', (new DateTime('now'))->getOffset());
183
184define('WT_CLIENT_JD', 2440588 + intdiv(WT_TIMESTAMP + WT_TIMESTAMP_OFFSET, 86400));
185
186// Update the last-login time no more than once a minute
187if (WT_TIMESTAMP - Session::get('activity_time') >= 60) {
188    if (Session::get('masquerade') === null) {
189        Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP);
190    }
191    Session::put('activity_time', WT_TIMESTAMP);
192}
193
194DebugBar::startMeasure('routing');
195
196try {
197    // Most requests will need the current tree and user.
198    $tree = Tree::findByName($request->get('ged')) ?? null;
199
200    // No tree specified/available?  Choose one.
201    if ($tree === null && $request->getMethod() === Request::METHOD_GET) {
202        $tree = Tree::findByName(Site::getPreference('DEFAULT_GEDCOM')) ?? array_values(Tree::getAll())[0] ?? null;
203    }
204
205    // Select a locale
206    define('WT_LOCALE', I18N::init('', $tree));
207    Session::put('locale', WT_LOCALE);
208
209    // Most layouts will require a tree for the page header/footer
210    View::share('tree', $tree);
211
212    // Load the route and routing table.
213    $route  = $request->get('route');
214    $routes = require 'routes/web.php';
215
216    // Find the controller and action for the selected route
217    $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound';
218    [$controller_name, $action] = explode('@', $controller_action);
219    $controller_class = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name;
220
221    app()->instance(Tree::class, $tree);
222    app()->instance(UserInterface::class, Auth::user());
223    app()->instance(LocaleInterface::class, WebtreesLocale::create(WT_LOCALE));
224    app()->instance(TimeoutService::class, new TimeoutService(microtime(true)));
225    app()->instance(Filesystem::class, $filesystem);
226
227    $controller = app()->make($controller_class);
228
229    DebugBar::stopMeasure('routing');
230
231    DebugBar::startMeasure('init theme');
232
233    // Don't initialize themes for POST requests.  They don't need themes.
234    if ($request->getMethod() === Request::METHOD_GET) {
235        /** @var Collection|ModuleThemeInterface[] $themes */
236        $themes = app()->make(ModuleService::class)->findByInterface(ModuleThemeInterface::class);
237
238        // Last theme used?
239        $theme = $themes->get(Session::get('theme_id', ''));
240
241        // Default for tree?
242        if ($theme === null && $tree instanceof Tree) {
243            $theme = $themes->get($tree->getPreference('THEME_DIR'));
244        }
245
246        // Default for site?
247        if ($theme === null) {
248            $theme = $themes->get(Site::getPreference('THEME_DIR'));
249        }
250
251        // Default
252        if ($theme === null) {
253            $theme = app()->make(WebtreesTheme::class);
254        }
255
256        // Bind this theme into the container
257        app()->instance(ModuleThemeInterface::class, $theme);
258
259        // Remember this setting
260        Session::put('theme_id', $theme->name());
261    }
262    DebugBar::stopMeasure('init theme');
263
264    // Note that we can't stop this timer, as running the action will
265    // generate the response - which includes (and stops) the timer
266    DebugBar::startMeasure('controller_action');
267
268    $middleware_stack = [
269        CheckForMaintenanceMode::class,
270    ];
271
272    if (class_exists(DebugBar::class)) {
273        $middleware_stack[] = DebugBarData::class;
274    }
275
276    if ($request->getMethod() === Request::METHOD_GET) {
277        $middleware_stack[] = Housekeeping::class;
278    }
279
280    if ($request->getMethod() === Request::METHOD_POST) {
281        $middleware_stack[] = UseTransaction::class;
282        $middleware_stack[] = CheckCsrf::class;
283    }
284
285    // Apply the middleware using the "onion" pattern.
286    $pipeline = array_reduce($middleware_stack, function (Closure $next, string $middleware): Closure {
287        // Create a closure to apply the middleware.
288        return function (Request $request) use ($middleware, $next): Response {
289            return app()->make($middleware)->handle($request, $next);
290        };
291    }, function (Request $request) use ($controller, $action): Response {
292        return app()->dispatch($controller, $action);
293    });
294
295    $response = call_user_func($pipeline, $request);
296} catch (Exception $exception) {
297    $response = (new Handler())->render($request, $exception);
298}
299
300// Send response
301$response->prepare($request)->send();
302