xref: /webtrees/index.php (revision 4947e7089adb08f24bf1eef67994a106a8df60aa)
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\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 Fisharebest\Webtrees\Webtrees;
40use Illuminate\Cache\ArrayStore;
41use Illuminate\Cache\Repository;
42use Illuminate\Database\Capsule\Manager as DB;
43use League\Flysystem\Adapter\Local;
44use League\Flysystem\Cached\CachedAdapter;
45use League\Flysystem\Cached\Storage\Memory;
46use League\Flysystem\Filesystem;
47use Symfony\Component\HttpFoundation\Request;
48use Symfony\Component\HttpFoundation\Response;
49
50require __DIR__ . '/vendor/autoload.php';
51
52// Regular expressions for validating user input, etc.
53const WT_MINIMUM_PASSWORD_LENGTH = 6;
54const WT_REGEX_PASSWORD          = '.{' . WT_MINIMUM_PASSWORD_LENGTH . ',}';
55
56const WT_ROOT = __DIR__ . DIRECTORY_SEPARATOR;
57
58Webtrees::init();
59
60// Initialise the DebugBar for development.
61// Use `composer install --dev` on a development build to enable.
62// Note that you may need to increase the size of the fcgi buffers on nginx.
63// e.g. add these lines to your fastcgi_params file:
64// fastcgi_buffers 16 16m;
65// fastcgi_buffer_size 32m;
66DebugBar::init(class_exists('\\DebugBar\\StandardDebugBar'));
67
68// Use an array cache for database calls, etc.
69app()->instance('cache.array', new Repository(new ArrayStore()));
70
71// Extract the request parameters.
72$request = Request::createFromGlobals();
73app()->instance(Request::class, $request);
74
75// Dummy value, until we have created our first tree.
76app()->bind(Tree::class, function () { return null; });
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        $controller = new SetupController();
93        $response   = $controller->setup($request);
94        $response->prepare($request)->send();
95
96        return;
97    }
98
99    $database_config = parse_ini_file(Webtrees::CONFIG_FILE);
100
101    if ($database_config === false) {
102        throw new Exception('Invalid config file: ' . Webtrees::CONFIG_FILE);
103    }
104
105    // Read the connection settings and create the database
106    Database::createInstance($database_config);
107
108    // Update the database schema, if necessary.
109    Database::updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
110} catch (PDOException $exception) {
111    define('WT_DATA_DIR', 'data/');
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    define('WT_DATA_DIR', 'data/');
127    I18N::init();
128    $content  = view('errors/database-connection', ['error' => $exception->getMessage()]);
129    $html     = view('layouts/error', ['content' => $content]);
130    $response = new Response($html, Response::HTTP_SERVICE_UNAVAILABLE);
131    $response->prepare($request)->send();
132
133    return;
134}
135
136DebugBar::stopMeasure('init database');
137
138// The config.ini.php file must always be in a fixed location.
139// Other user files can be stored elsewhere...
140define('WT_DATA_DIR', realpath(Site::getPreference('INDEX_DIRECTORY', 'data/')) . DIRECTORY_SEPARATOR);
141
142$filesystem = new Filesystem(new CachedAdapter(new Local(WT_DATA_DIR), new Memory()));
143
144// Some broken servers block access to their own temp folder using open_basedir...
145$filesystem->createDir('tmp');
146putenv('TMPDIR=' . WT_DATA_DIR . 'tmp');
147Swift_Preferences::getInstance()->setTempDir(WT_DATA_DIR . 'tmp');
148
149// Request more resources - if we can/want to
150$memory_limit = Site::getPreference('MEMORY_LIMIT');
151if ($memory_limit !== '' && strpos(ini_get('disable_functions'), 'ini_set') === false) {
152    ini_set('memory_limit', $memory_limit);
153}
154$max_execution_time = Site::getPreference('MAX_EXECUTION_TIME');
155if ($max_execution_time !== '' && strpos(ini_get('disable_functions'), 'set_time_limit') === false) {
156    set_time_limit((int) $max_execution_time);
157}
158
159// Sessions
160Session::start();
161
162// Note that the database/webservers may not be synchronised, so use DB time throughout.
163define('WT_TIMESTAMP', DB::select('SELECT UNIX_TIMESTAMP() AS unix_timestamp')[0]->unix_timestamp);
164
165// Users get their own time-zone. Visitors get the site time-zone.
166try {
167    if (Auth::check()) {
168        date_default_timezone_set(Auth::user()->getPreference('TIMEZONE'));
169    } else {
170        date_default_timezone_set(Site::getPreference('TIMEZONE'));
171    }
172} catch (ErrorException $exception) {
173    // Server upgrades and migrations can leave us with invalid timezone settings.
174    date_default_timezone_set('UTC');
175}
176
177define('WT_TIMESTAMP_OFFSET', (new DateTime('now'))->getOffset());
178
179define('WT_CLIENT_JD', 2440588 + intdiv(WT_TIMESTAMP + WT_TIMESTAMP_OFFSET, 86400));
180
181// Update the last-login time no more than once a minute
182if (WT_TIMESTAMP - Session::get('activity_time') >= 60) {
183    if (Session::get('masquerade') === null) {
184        Auth::user()->setPreference('sessiontime', (string) WT_TIMESTAMP);
185    }
186    Session::put('activity_time', WT_TIMESTAMP);
187}
188
189DebugBar::startMeasure('routing');
190
191try {
192    // Most requests will need the current tree and user.
193    $tree = Tree::findByName($request->get('ged')) ?? null;
194
195    // No tree specified/available?  Choose one.
196    if ($tree === null && $request->getMethod() === Request::METHOD_GET) {
197        $tree = Tree::findByName(Site::getPreference('DEFAULT_GEDCOM')) ?? array_values(Tree::getAll())[0] ?? null;
198    }
199
200    // Select a locale
201    define('WT_LOCALE', I18N::init('', $tree));
202    Session::put('locale', WT_LOCALE);
203
204    // Most layouts will require a tree for the page header/footer
205    View::share('tree', $tree);
206
207    // Load the route and routing table.
208    $route  = $request->get('route');
209    $routes = require 'routes/web.php';
210
211    // Find the controller and action for the selected route
212    $controller_action = $routes[$request->getMethod() . ':' . $route] ?? 'ErrorController@noRouteFound';
213    [$controller_name, $action] = explode('@', $controller_action);
214    $controller_class = '\\Fisharebest\\Webtrees\\Http\\Controllers\\' . $controller_name;
215
216    app()->instance(Tree::class, $tree);
217    app()->instance(User::class, Auth::user());
218    app()->instance(LocaleInterface::class, WebtreesLocale::create(WT_LOCALE));
219    app()->instance(TimeoutService::class, new TimeoutService(microtime(true)));
220    app()->instance(Filesystem::class, $filesystem);
221
222    $controller = app()->make($controller_class);
223
224    DebugBar::stopMeasure('routing');
225
226    DebugBar::startMeasure('init theme');
227
228    // Last theme used?
229    $theme_id = Session::get('theme_id');
230    // Default for tree
231    if (!array_key_exists($theme_id, Theme::themeNames()) && $tree) {
232        $theme_id = $tree->getPreference('THEME_DIR');
233    }
234    // Default for site
235    if (!array_key_exists($theme_id, Theme::themeNames())) {
236        $theme_id = Site::getPreference('THEME_DIR');
237    }
238    // Default
239    if (!array_key_exists($theme_id, Theme::themeNames())) {
240        $theme_id = 'webtrees';
241    }
242    foreach (Theme::installedThemes() as $theme) {
243        if ($theme->themeId() === $theme_id) {
244            Theme::theme($theme)->init($request, $tree);
245            // Remember this setting
246            if (Site::getPreference('ALLOW_USER_THEMES') === '1') {
247                Session::put('theme_id', $theme_id);
248            }
249            break;
250        }
251    }
252
253    DebugBar::stopMeasure('init theme');
254
255    // Note that we can't stop this timer, as running the action will
256    // generate the response - which includes (and stops) the timer
257    DebugBar::startMeasure('controller_action');
258
259    $middleware_stack = [
260        CheckForMaintenanceMode::class,
261    ];
262
263    if (class_exists(DebugBar::class)) {
264        $middleware_stack[] = DebugBarData::class;
265    }
266
267    if ($request->getMethod() === Request::METHOD_GET) {
268        $middleware_stack[] = PageHitCounter::class;
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