Passed
Push — analysis-zD3RPJ ( 02743d )
by Greg
14:36 queued 05:47
created

anonymous()

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
nc 1
nop 1
dl 0
loc 4
c 0
b 0
f 0
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
 */
16
declare(strict_types=1);
17
18
use Fisharebest\Localization\Locale as WebtreesLocale;
19
use Fisharebest\Localization\Locale\LocaleInterface;
20
use Fisharebest\Webtrees\Auth;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Auth. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
21
use Fisharebest\Webtrees\Database;
22
use Fisharebest\Webtrees\DebugBar;
23
use Fisharebest\Webtrees\Exceptions\Handler;
24
use Fisharebest\Webtrees\Http\Controllers\SetupController;
25
use Fisharebest\Webtrees\Http\Middleware\CheckCsrf;
26
use Fisharebest\Webtrees\Http\Middleware\CheckForMaintenanceMode;
27
use Fisharebest\Webtrees\Http\Middleware\DebugBarData;
28
use Fisharebest\Webtrees\Http\Middleware\Housekeeping;
29
use Fisharebest\Webtrees\Http\Middleware\PageHitCounter;
30
use Fisharebest\Webtrees\Http\Middleware\UseTransaction;
31
use Fisharebest\Webtrees\I18N;
32
use Fisharebest\Webtrees\Resolver;
33
use Fisharebest\Webtrees\Services\TimeoutService;
34
use Fisharebest\Webtrees\Session;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Session. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
35
use Fisharebest\Webtrees\Site;
36
use Fisharebest\Webtrees\Theme;
37
use Fisharebest\Webtrees\Tree;
38
use Fisharebest\Webtrees\User;
39
use Fisharebest\Webtrees\View;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, View. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
40
use Fisharebest\Webtrees\Webtrees;
41
use League\Flysystem\Adapter\Local;
42
use League\Flysystem\Filesystem;
43
use Symfony\Component\HttpFoundation\Request;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Request. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
44
use Symfony\Component\HttpFoundation\Response;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Response. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

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