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