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