summaryrefslogtreecommitdiff
path: root/app/Http/RequestHandlers/SetupWizard.php
blob: d31b3bc1c74e3a00cf74bf84e22365f45cffacb6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
<?php

/**
 * webtrees: online genealogy
 * Copyright (C) 2026 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Fisharebest\Webtrees\Http\RequestHandlers;

use Exception;
use Fisharebest\Localization\Locale;
use Fisharebest\Localization\Locale\LocaleEnUs;
use Fisharebest\Localization\Locale\LocaleInterface;
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Contracts\UserInterface;
use Fisharebest\Webtrees\DB;
use Fisharebest\Webtrees\Factories\CacheFactory;
use Fisharebest\Webtrees\Http\ViewResponseTrait;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Module\ModuleLanguageInterface;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Services\MigrationService;
use Fisharebest\Webtrees\Services\ModuleService;
use Fisharebest\Webtrees\Services\PhpService;
use Fisharebest\Webtrees\Services\ServerCheckService;
use Fisharebest\Webtrees\Services\UserService;
use Fisharebest\Webtrees\Session;
use Fisharebest\Webtrees\Validator;
use Fisharebest\Webtrees\Webtrees;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;

use function e;
use function file_get_contents;
use function file_put_contents;
use function intdiv;
use function random_bytes;
use function realpath;
use function redirect;
use function touch;
use function unlink;
use function view;

final class SetupWizard implements RequestHandlerInterface
{
    use ViewResponseTrait;

    private const string DEFAULT_DBTYPE = DB::MYSQL;
    private const string DEFAULT_PREFIX = 'wt_';
    private const array DEFAULT_DATA    = [
        'baseurl'  => '',
        'lang'     => '',
        'dbtype'   => self::DEFAULT_DBTYPE,
        'dbhost'   => '',
        'dbport'   => '',
        'dbuser'   => '',
        'dbpass'   => '',
        'dbname'   => '',
        'tblpfx'   => self::DEFAULT_PREFIX,
        'dbkey'    => '',
        'dbcert'   => '',
        'dbca'     => '',
        'dbverify' => '',
        'wtname'   => '',
        'wtuser'   => '',
        'wtpass'   => '',
        'wtemail'  => '',
    ];

    private const array DEFAULT_PORTS = [
        DB::MYSQL      => '3306',
        DB::POSTGRESQL => '5432',
        DB::SQLITE     => '',
        DB::SQL_SERVER => '', // Do not use default, as it is valid to have no port number.
    ];

    public function __construct(
        private readonly MigrationService $migration_service,
        private readonly ModuleService $module_service,
        private readonly PhpService $php_service,
        private readonly ServerCheckService $server_check_service,
        private readonly UserService $user_service
    ) {
    }

    /**
     * Installation wizard - check user input and proceed to the next step.
     */
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $this->layout = 'layouts/setup';

        // Some functions need a cache, but we don't have one yet.
        Registry::cache(new CacheFactory());

        // We will need an IP address for the logs.
        $ip_address = Validator::serverParams($request)->string('REMOTE_ADDR', '127.0.0.1');
        $request    = $request->withAttribute('client-ip', $ip_address);

        Registry::container()->set(ServerRequestInterface::class, $request);

        $data = $this->userData($request);

        $step = Validator::parsedBody($request)->integer('step', 1);

        $locales = $this->module_service
            ->setupLanguages()
            ->map(static fn (ModuleLanguageInterface $module): LocaleInterface => $module->locale());

        if ($data['lang'] === '') {
            $default = new LocaleEnUs();

            $locale  = Locale::httpAcceptLanguage($request->getServerParams(), $locales->all(), $default);

            $data['lang'] = $locale->languageTag();
        }

        I18N::init($data['lang'], true);

        $data['cpu_limit']    = $this->php_service->maxExecutionTime();
        $data['locales']      = $locales;
        $data['memory_limit'] = $this->php_service->memoryLimit();

        // Only show database errors after the user has chosen a driver.
        if ($step >= 4) {
            $data['errors']   = $this->server_check_service->serverErrors($data['dbtype']);
            $data['warnings'] = $this->server_check_service->serverWarnings($data['dbtype']);
        } else {
            $data['errors']   = $this->server_check_service->serverErrors();
            $data['warnings'] = $this->server_check_service->serverWarnings();
        }

        if (!$this->checkFolderIsWritable(Webtrees::DATA_DIR)) {
            $data['errors']->push(
                '<code>' . e(realpath(Webtrees::DATA_DIR)) . '</code><br>' .
                I18N::translate('Oops! webtrees was unable to create files in this folder.') . ' ' .
                I18N::translate('This usually means that you need to change the folder permissions to 777.')
            );
        }

        switch ($step) {
            default:
            case 1:
                return $this->step1Language($data);
            case 2:
                return $this->step2CheckServer($data);
            case 3:
                return $this->step3DatabaseType($data);
            case 4:
                return $this->step4DatabaseConnection($data);
            case 5:
                return $this->step5Administrator($data);
            case 6:
                return $this->step6Install($data);
        }
    }

    /**
     * @return array<string,mixed>
     */
    private function userData(ServerRequestInterface $request): array
    {
        $data = [];

        foreach (self::DEFAULT_DATA as $key => $default) {
            $data[$key] = Validator::parsedBody($request)->string($key, $default);
        }

        return $data;
    }

    /**
     * Check we can write to the data folder.
     */
    private function checkFolderIsWritable(string $data_dir): bool
    {
        $text1 = random_bytes(32);

        try {
            file_put_contents($data_dir . 'test.txt', $text1);
            $text2 = file_get_contents(Webtrees::DATA_DIR . 'test.txt');
            unlink(Webtrees::DATA_DIR . 'test.txt');
        } catch (Exception) {
            return false;
        }

        return $text1 === $text2;
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step1Language(array $data): ResponseInterface
    {
        return $this->viewResponse('setup/step-1-language', $data);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step2CheckServer(array $data): ResponseInterface
    {
        return $this->viewResponse('setup/step-2-server-checks', $data);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step3DatabaseType(array $data): ResponseInterface
    {
        if ($data['errors']->isNotEmpty()) {
            return $this->viewResponse('setup/step-2-server-checks', $data);
        }

        return $this->viewResponse('setup/step-3-database-type', $data);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step4DatabaseConnection(array $data): ResponseInterface
    {
        if ($data['errors']->isNotEmpty()) {
            return $this->step3DatabaseType($data);
        }

        $data['mysql_local'] = 'localhost:' . $this->php_service->pdoMysqlDefaultSocket();

        return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step5Administrator(array $data): ResponseInterface
    {
        // Use default port, if none specified.
        $data['dbport'] = $data['dbport'] ?: self::DEFAULT_PORTS[$data['dbtype']];

        try {
            $this->connectToDatabase($data);
        } catch (Throwable $ex) {
            $data['errors']->push($ex->getMessage());

            // Don't jump to step 4, as the error will make it jump to step 3.
            $data['mysql_local'] = 'localhost:' . $this->php_service->pdoMysqlDefaultSocket();

            return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
        }

        return $this->viewResponse('setup/step-5-administrator', $data);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function step6Install(array $data): ResponseInterface
    {
        $error = $this->checkAdminUser($data['wtname'], $data['wtuser'], $data['wtpass'], $data['wtemail']);

        if ($error !== '') {
            $data['errors']->push($error);

            return $this->step5Administrator($data);
        }

        try {
            $this->createConfigFile($data);
        } catch (Throwable $exception) {
            return $this->viewResponse('setup/step-6-failed', ['exception' => $exception]);
        }

        // Done - start using webtrees!
        return redirect($data['baseurl']);
    }

    private function checkAdminUser(string $wtname, string $wtuser, string $wtpass, string $wtemail): string
    {
        if ($wtname === '' || $wtuser === '' || $wtpass === '' || $wtemail === '') {
            return I18N::translate('You must enter all the administrator account fields.');
        }

        if (mb_strlen($wtpass) < 6) {
            return I18N::translate('The password needs to be at least six characters long.');
        }

        return '';
    }

    /**
     * @param array<string,mixed> $data
     */
    private function createConfigFile(array $data): void
    {
        // Create/update the database tables.
        $this->connectToDatabase($data);
        $this->migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);

        // Add some default/necessary configuration data.
        $this->migration_service->seedDatabase();

        // If we are re-installing, then this user may already exist.
        $admin = $this->user_service->findByIdentifier($data['wtemail']);
        if ($admin === null) {
            $admin = $this->user_service->findByIdentifier($data['wtuser']);
        }
        // Create the user
        if ($admin === null) {
            $admin = $this->user_service->create($data['wtuser'], $data['wtname'], $data['wtemail'], $data['wtpass']);
            $admin->setPreference(UserInterface::PREF_LANGUAGE, $data['lang']);
            $admin->setPreference(UserInterface::PREF_IS_VISIBLE_ONLINE, '1');
        } else {
            $admin->setPassword($data['wtpass']);
        }
        // Make the user an administrator
        $admin->setPreference(UserInterface::PREF_IS_ADMINISTRATOR, '1');
        $admin->setPreference(UserInterface::PREF_IS_EMAIL_VERIFIED, '1');
        $admin->setPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED, '1');

        // Write the config file. We already checked that this would work.
        $config_ini_php = view('setup/config.ini', $data);

        file_put_contents(Webtrees::CONFIG_FILE, $config_ini_php);

        // Login as the new user
        $request = Registry::container()->get(ServerRequestInterface::class)
            ->withAttribute('base_url', $data['baseurl']);

        Session::start($request);
        Auth::login($admin);
        Session::put('language', $data['lang']);
    }

    /**
     * @param array<string,mixed> $data
     */
    private function connectToDatabase(array $data): void
    {
        // Try to create the database, if it does not already exist.
        switch ($data['dbtype']) {
            case DB::SQLITE:
                touch(Webtrees::ROOT_DIR . 'data/' . $data['dbname'] . '.sqlite');
                break;

            case DB::MYSQL:
                DB::connect(
                    driver: $data['dbtype'],
                    host: $data['dbhost'],
                    port: $data['dbport'],
                    database: '',
                    username: $data['dbuser'],
                    password: $data['dbpass'],
                    prefix: $data['tblpfx'],
                    key: $data['dbkey'],
                    certificate: $data['dbcert'],
                    ca: $data['dbca'],
                    verify_certificate: (bool) $data['dbverify'],
                );
                DB::exec('CREATE DATABASE IF NOT EXISTS `' . $data['dbname'] . '` COLLATE utf8mb4_unicode_ci');
                break;
        }

        DB::connect(
            driver: $data['dbtype'],
            host: $data['dbhost'],
            port: $data['dbport'],
            database: $data['dbname'],
            username: $data['dbuser'],
            password: $data['dbpass'],
            prefix: $data['tblpfx'],
            key: $data['dbkey'],
            certificate: $data['dbcert'],
            ca: $data['dbca'],
            verify_certificate: (bool) $data['dbverify'],
        );
    }
}