xref: /webtrees/app/Http/RequestHandlers/SetupWizard.php (revision 202c018b592d5a516e4a465dc6dc515f3be37399)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2023 webtrees development team
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Exception;
23use Fisharebest\Localization\Locale;
24use Fisharebest\Localization\Locale\LocaleEnUs;
25use Fisharebest\Localization\Locale\LocaleInterface;
26use Fisharebest\Webtrees\Auth;
27use Fisharebest\Webtrees\Contracts\UserInterface;
28use Fisharebest\Webtrees\DB;
29use Fisharebest\Webtrees\Factories\CacheFactory;
30use Fisharebest\Webtrees\Http\ViewResponseTrait;
31use Fisharebest\Webtrees\I18N;
32use Fisharebest\Webtrees\Module\ModuleLanguageInterface;
33use Fisharebest\Webtrees\Registry;
34use Fisharebest\Webtrees\Services\MigrationService;
35use Fisharebest\Webtrees\Services\ModuleService;
36use Fisharebest\Webtrees\Services\ServerCheckService;
37use Fisharebest\Webtrees\Services\UserService;
38use Fisharebest\Webtrees\Session;
39use Fisharebest\Webtrees\Validator;
40use Fisharebest\Webtrees\Webtrees;
41use Psr\Http\Message\ResponseInterface;
42use Psr\Http\Message\ServerRequestInterface;
43use Psr\Http\Server\RequestHandlerInterface;
44use Throwable;
45
46use function e;
47use function file_get_contents;
48use function file_put_contents;
49use function ini_get;
50use function random_bytes;
51use function realpath;
52use function redirect;
53use function substr;
54use function touch;
55use function unlink;
56use function view;
57
58/**
59 * Controller for the installation wizard
60 */
61class SetupWizard implements RequestHandlerInterface
62{
63    use ViewResponseTrait;
64
65    private const DEFAULT_DBTYPE = 'mysql';
66    private const DEFAULT_PREFIX = 'wt_';
67    private const DEFAULT_DATA   = [
68        'baseurl' => '',
69        'lang'    => '',
70        'dbtype'  => self::DEFAULT_DBTYPE,
71        'dbhost'  => '',
72        'dbport'  => '',
73        'dbuser'  => '',
74        'dbpass'  => '',
75        'dbname'  => '',
76        'tblpfx'  => self::DEFAULT_PREFIX,
77        'wtname'  => '',
78        'wtuser'  => '',
79        'wtpass'  => '',
80        'wtemail' => '',
81    ];
82
83    private const DEFAULT_PORTS = [
84        'mysql'  => '3306',
85        'pgsql'  => '5432',
86        'sqlite' => '',
87        'sqlsrv' => '', // Do not use default, as it is valid to have no port number.
88    ];
89
90    private MigrationService $migration_service;
91
92    private ModuleService $module_service;
93
94    private ServerCheckService $server_check_service;
95
96    private UserService $user_service;
97
98    /**
99     * @param MigrationService   $migration_service
100     * @param ModuleService      $module_service
101     * @param ServerCheckService $server_check_service
102     * @param UserService        $user_service
103     */
104    public function __construct(
105        MigrationService $migration_service,
106        ModuleService $module_service,
107        ServerCheckService $server_check_service,
108        UserService $user_service
109    ) {
110        $this->user_service         = $user_service;
111        $this->migration_service    = $migration_service;
112        $this->module_service       = $module_service;
113        $this->server_check_service = $server_check_service;
114    }
115
116    /**
117     * Installation wizard - check user input and proceed to the next step.
118     *
119     * @param ServerRequestInterface $request
120     *
121     * @return ResponseInterface
122     */
123    public function handle(ServerRequestInterface $request): ResponseInterface
124    {
125        $this->layout = 'layouts/setup';
126
127        // Some functions need a cache, but we don't have one yet.
128        Registry::cache(new CacheFactory());
129
130        // We will need an IP address for the logs.
131        $ip_address = Validator::serverParams($request)->string('REMOTE_ADDR', '127.0.0.1');
132        $request    = $request->withAttribute('client-ip', $ip_address);
133
134        Registry::container()->set(ServerRequestInterface::class, $request);
135
136        $data = $this->userData($request);
137
138        $step = Validator::parsedBody($request)->integer('step', 1);
139
140        $locales = $this->module_service
141            ->setupLanguages()
142            ->map(static fn(ModuleLanguageInterface $module): LocaleInterface => $module->locale());
143
144        if ($data['lang'] === '') {
145            $default = new LocaleEnUs();
146
147            $locale  = Locale::httpAcceptLanguage($request->getServerParams(), $locales->all(), $default);
148
149            $data['lang'] = $locale->languageTag();
150        }
151
152        I18N::init($data['lang'], true);
153
154        $data['cpu_limit']    = $this->maxExecutionTime();
155        $data['locales']      = $locales;
156        $data['memory_limit'] = $this->memoryLimit();
157
158        // Only show database errors after the user has chosen a driver.
159        if ($step >= 4) {
160            $data['errors']   = $this->server_check_service->serverErrors($data['dbtype']);
161            $data['warnings'] = $this->server_check_service->serverWarnings($data['dbtype']);
162        } else {
163            $data['errors']   = $this->server_check_service->serverErrors();
164            $data['warnings'] = $this->server_check_service->serverWarnings();
165        }
166
167        if (!$this->checkFolderIsWritable(Webtrees::DATA_DIR)) {
168            $data['errors']->push(
169                '<code>' . e(realpath(Webtrees::DATA_DIR)) . '</code><br>' .
170                I18N::translate('Oops! webtrees was unable to create files in this folder.') . ' ' .
171                I18N::translate('This usually means that you need to change the folder permissions to 777.')
172            );
173        }
174
175        switch ($step) {
176            default:
177            case 1:
178                return $this->step1Language($data);
179            case 2:
180                return $this->step2CheckServer($data);
181            case 3:
182                return $this->step3DatabaseType($data);
183            case 4:
184                return $this->step4DatabaseConnection($data);
185            case 5:
186                return $this->step5Administrator($data);
187            case 6:
188                return $this->step6Install($data);
189        }
190    }
191
192    /**
193     * @param ServerRequestInterface $request
194     *
195     * @return array<string,mixed>
196     */
197    private function userData(ServerRequestInterface $request): array
198    {
199        $data = [];
200
201        foreach (self::DEFAULT_DATA as $key => $default) {
202            $data[$key] = Validator::parsedBody($request)->string($key, $default);
203        }
204
205        return $data;
206    }
207
208    /**
209     * The server's memory limit
210     *
211     * @return int
212     */
213    private function maxExecutionTime(): int
214    {
215        return (int) ini_get('max_execution_time');
216    }
217
218    /**
219     * The server's memory limit (in MB).
220     *
221     * @return int
222     */
223    private function memoryLimit(): int
224    {
225        $memory_limit = ini_get('memory_limit');
226
227        $number = (int) $memory_limit;
228
229        switch (substr($memory_limit, -1)) {
230            case 'g':
231            case 'G':
232                return $number * 1024;
233            case 'm':
234            case 'M':
235                return $number;
236            case 'k':
237            case 'K':
238                return (int) ($number / 1024);
239            default:
240                return (int) ($number / 1048576);
241        }
242    }
243
244    /**
245     * Check we can write to the data folder.
246     *
247     * @param string $data_dir
248     *
249     * @return bool
250     */
251    private function checkFolderIsWritable(string $data_dir): bool
252    {
253        $text1 = random_bytes(32);
254
255        try {
256            file_put_contents($data_dir . 'test.txt', $text1);
257            $text2 = file_get_contents(Webtrees::DATA_DIR . 'test.txt');
258            unlink(Webtrees::DATA_DIR . 'test.txt');
259        } catch (Exception) {
260            return false;
261        }
262
263        return $text1 === $text2;
264    }
265
266    /**
267     * @param array<string,mixed> $data
268     *
269     * @return ResponseInterface
270     */
271    private function step1Language(array $data): ResponseInterface
272    {
273        return $this->viewResponse('setup/step-1-language', $data);
274    }
275
276    /**
277     * @param array<string,mixed> $data
278     *
279     * @return ResponseInterface
280     */
281    private function step2CheckServer(array $data): ResponseInterface
282    {
283        return $this->viewResponse('setup/step-2-server-checks', $data);
284    }
285
286    /**
287     * @param array<string,mixed> $data
288     *
289     * @return ResponseInterface
290     */
291    private function step3DatabaseType(array $data): ResponseInterface
292    {
293        if ($data['errors']->isNotEmpty()) {
294            return $this->viewResponse('setup/step-2-server-checks', $data);
295        }
296
297        return $this->viewResponse('setup/step-3-database-type', $data);
298    }
299
300    /**
301     * @param array<string,mixed> $data
302     *
303     * @return ResponseInterface
304     */
305    private function step4DatabaseConnection(array $data): ResponseInterface
306    {
307        if ($data['errors']->isNotEmpty()) {
308            return $this->step3DatabaseType($data);
309        }
310
311        return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
312    }
313
314    /**
315     * @param array<string,mixed> $data
316     *
317     * @return ResponseInterface
318     */
319    private function step5Administrator(array $data): ResponseInterface
320    {
321        // Use default port, if none specified.
322        $data['dbport'] = $data['dbport'] ?: self::DEFAULT_PORTS[$data['dbtype']];
323
324        try {
325            $this->connectToDatabase($data);
326        } catch (Throwable $ex) {
327            $data['errors']->push($ex->getMessage());
328
329            // Don't jump to step 4, as the error will make it jump to step 3.
330            return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
331        }
332
333        return $this->viewResponse('setup/step-5-administrator', $data);
334    }
335
336    /**
337     * @param array<string,mixed> $data
338     *
339     * @return ResponseInterface
340     */
341    private function step6Install(array $data): ResponseInterface
342    {
343        $error = $this->checkAdminUser($data['wtname'], $data['wtuser'], $data['wtpass'], $data['wtemail']);
344
345        if ($error !== '') {
346            $data['errors']->push($error);
347
348            return $this->step5Administrator($data);
349        }
350
351        try {
352            $this->createConfigFile($data);
353        } catch (Throwable $exception) {
354            return $this->viewResponse('setup/step-6-failed', ['exception' => $exception]);
355        }
356
357        // Done - start using webtrees!
358        return redirect($data['baseurl']);
359    }
360
361    /**
362     * @param string $wtname
363     * @param string $wtuser
364     * @param string $wtpass
365     * @param string $wtemail
366     *
367     * @return string
368     */
369    private function checkAdminUser(string $wtname, string $wtuser, string $wtpass, string $wtemail): string
370    {
371        if ($wtname === '' || $wtuser === '' || $wtpass === '' || $wtemail === '') {
372            return I18N::translate('You must enter all the administrator account fields.');
373        }
374
375        if (mb_strlen($wtpass) < 6) {
376            return I18N::translate('The password needs to be at least six characters long.');
377        }
378
379        return '';
380    }
381
382    /**
383     * @param array<string,mixed> $data
384     *
385     * @return void
386     */
387    private function createConfigFile(array $data): void
388    {
389        // Create/update the database tables.
390        $this->connectToDatabase($data);
391        $this->migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
392
393        // Add some default/necessary configuration data.
394        $this->migration_service->seedDatabase();
395
396        // If we are re-installing, then this user may already exist.
397        $admin = $this->user_service->findByIdentifier($data['wtemail']);
398        if ($admin === null) {
399            $admin = $this->user_service->findByIdentifier($data['wtuser']);
400        }
401        // Create the user
402        if ($admin === null) {
403            $admin = $this->user_service->create($data['wtuser'], $data['wtname'], $data['wtemail'], $data['wtpass']);
404            $admin->setPreference(UserInterface::PREF_LANGUAGE, $data['lang']);
405            $admin->setPreference(UserInterface::PREF_IS_VISIBLE_ONLINE, '1');
406        } else {
407            $admin->setPassword($_POST['wtpass']);
408        }
409        // Make the user an administrator
410        $admin->setPreference(UserInterface::PREF_IS_ADMINISTRATOR, '1');
411        $admin->setPreference(UserInterface::PREF_IS_EMAIL_VERIFIED, '1');
412        $admin->setPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED, '1');
413
414        // Write the config file. We already checked that this would work.
415        $config_ini_php = view('setup/config.ini', $data);
416
417        file_put_contents(Webtrees::CONFIG_FILE, $config_ini_php);
418
419        // Login as the new user
420        $request = Registry::container()->get(ServerRequestInterface::class)
421            ->withAttribute('base_url', $data['baseurl']);
422
423        Session::start($request);
424        Auth::login($admin);
425        Session::put('language', $data['lang']);
426    }
427
428    /**
429     * @param array<string,mixed> $data
430     *
431     * @return void
432     */
433    private function connectToDatabase(array $data): void
434    {
435        $capsule = new DB();
436
437        // Try to create the database, if it does not already exist.
438        switch ($data['dbtype']) {
439            case 'sqlite':
440                $data['dbname'] = Webtrees::ROOT_DIR . 'data/' . $data['dbname'] . '.sqlite';
441                touch($data['dbname']);
442                break;
443
444            case 'mysql':
445                $capsule->addConnection([
446                    'driver'                  => $data['dbtype'],
447                    'host'                    => $data['dbhost'],
448                    'port'                    => $data['dbport'],
449                    'database'                => '',
450                    'username'                => $data['dbuser'],
451                    'password'                => $data['dbpass'],
452                ], 'temp');
453                $capsule->getConnection('temp')->statement('CREATE DATABASE IF NOT EXISTS `' . $data['dbname'] . '` COLLATE utf8_unicode_ci');
454                break;
455        }
456
457        // Connect to the database.
458        $capsule->addConnection([
459            'driver'                  => $data['dbtype'],
460            'host'                    => $data['dbhost'],
461            'port'                    => $data['dbport'],
462            'database'                => $data['dbname'],
463            'username'                => $data['dbuser'],
464            'password'                => $data['dbpass'],
465            'prefix'                  => $data['tblpfx'],
466            'prefix_indexes'          => true,
467            // For MySQL
468            'charset'                 => 'utf8',
469            'collation'               => 'utf8_unicode_ci',
470            'timezone'                => '+00:00',
471            'engine'                  => 'InnoDB',
472            'modes'                   => [
473                'ANSI',
474                'STRICT_TRANS_TABLES',
475                'NO_ZERO_IN_DATE',
476                'NO_ZERO_DATE',
477                'ERROR_FOR_DIVISION_BY_ZERO',
478            ],
479            // For SQLite
480            'foreign_key_constraints' => true,
481        ]);
482
483        $capsule->setAsGlobal();
484
485        if ($data['dbtype'] === 'sqlsrv') {
486            DB::connection()->unprepared('SET language us_english'); // For timestamp columns
487        }
488    }
489}
490