xref: /webtrees/app/Http/RequestHandlers/SetupWizard.php (revision 59a6bd4ad405c01c16d2ad2999655ba1e44be99c)
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 function (ModuleLanguageInterface $module): LocaleInterface {
143                return $module->locale();
144            });
145
146        if ($data['lang'] === '') {
147            $default = new LocaleEnUs();
148
149            $locale  = Locale::httpAcceptLanguage($request->getServerParams(), $locales->all(), $default);
150
151            $data['lang'] = $locale->languageTag();
152        }
153
154        I18N::init($data['lang'], true);
155
156        $data['cpu_limit']    = $this->maxExecutionTime();
157        $data['locales']      = $locales;
158        $data['memory_limit'] = $this->memoryLimit();
159
160        // Only show database errors after the user has chosen a driver.
161        if ($step >= 4) {
162            $data['errors']   = $this->server_check_service->serverErrors($data['dbtype']);
163            $data['warnings'] = $this->server_check_service->serverWarnings($data['dbtype']);
164        } else {
165            $data['errors']   = $this->server_check_service->serverErrors();
166            $data['warnings'] = $this->server_check_service->serverWarnings();
167        }
168
169        if (!$this->checkFolderIsWritable(Webtrees::DATA_DIR)) {
170            $data['errors']->push(
171                '<code>' . e(realpath(Webtrees::DATA_DIR)) . '</code><br>' .
172                I18N::translate('Oops! webtrees was unable to create files in this folder.') . ' ' .
173                I18N::translate('This usually means that you need to change the folder permissions to 777.')
174            );
175        }
176
177        switch ($step) {
178            default:
179            case 1:
180                return $this->step1Language($data);
181            case 2:
182                return $this->step2CheckServer($data);
183            case 3:
184                return $this->step3DatabaseType($data);
185            case 4:
186                return $this->step4DatabaseConnection($data);
187            case 5:
188                return $this->step5Administrator($data);
189            case 6:
190                return $this->step6Install($data);
191        }
192    }
193
194    /**
195     * @param ServerRequestInterface $request
196     *
197     * @return array<string,mixed>
198     */
199    private function userData(ServerRequestInterface $request): array
200    {
201        $data = [];
202
203        foreach (self::DEFAULT_DATA as $key => $default) {
204            $data[$key] = Validator::parsedBody($request)->string($key, $default);
205        }
206
207        return $data;
208    }
209
210    /**
211     * The server's memory limit
212     *
213     * @return int
214     */
215    private function maxExecutionTime(): int
216    {
217        return (int) ini_get('max_execution_time');
218    }
219
220    /**
221     * The server's memory limit (in MB).
222     *
223     * @return int
224     */
225    private function memoryLimit(): int
226    {
227        $memory_limit = ini_get('memory_limit');
228
229        $number = (int) $memory_limit;
230
231        switch (substr($memory_limit, -1)) {
232            case 'g':
233            case 'G':
234                return $number * 1024;
235            case 'm':
236            case 'M':
237                return $number;
238            case 'k':
239            case 'K':
240                return (int) ($number / 1024);
241            default:
242                return (int) ($number / 1048576);
243        }
244    }
245
246    /**
247     * Check we can write to the data folder.
248     *
249     * @param string $data_dir
250     *
251     * @return bool
252     */
253    private function checkFolderIsWritable(string $data_dir): bool
254    {
255        $text1 = random_bytes(32);
256
257        try {
258            file_put_contents($data_dir . 'test.txt', $text1);
259            $text2 = file_get_contents(Webtrees::DATA_DIR . 'test.txt');
260            unlink(Webtrees::DATA_DIR . 'test.txt');
261        } catch (Exception) {
262            return false;
263        }
264
265        return $text1 === $text2;
266    }
267
268    /**
269     * @param array<string,mixed> $data
270     *
271     * @return ResponseInterface
272     */
273    private function step1Language(array $data): ResponseInterface
274    {
275        return $this->viewResponse('setup/step-1-language', $data);
276    }
277
278    /**
279     * @param array<string,mixed> $data
280     *
281     * @return ResponseInterface
282     */
283    private function step2CheckServer(array $data): ResponseInterface
284    {
285        return $this->viewResponse('setup/step-2-server-checks', $data);
286    }
287
288    /**
289     * @param array<string,mixed> $data
290     *
291     * @return ResponseInterface
292     */
293    private function step3DatabaseType(array $data): ResponseInterface
294    {
295        if ($data['errors']->isNotEmpty()) {
296            return $this->viewResponse('setup/step-2-server-checks', $data);
297        }
298
299        return $this->viewResponse('setup/step-3-database-type', $data);
300    }
301
302    /**
303     * @param array<string,mixed> $data
304     *
305     * @return ResponseInterface
306     */
307    private function step4DatabaseConnection(array $data): ResponseInterface
308    {
309        if ($data['errors']->isNotEmpty()) {
310            return $this->step3DatabaseType($data);
311        }
312
313        return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
314    }
315
316    /**
317     * @param array<string,mixed> $data
318     *
319     * @return ResponseInterface
320     */
321    private function step5Administrator(array $data): ResponseInterface
322    {
323        // Use default port, if none specified.
324        $data['dbport'] = $data['dbport'] ?: self::DEFAULT_PORTS[$data['dbtype']];
325
326        try {
327            $this->connectToDatabase($data);
328        } catch (Throwable $ex) {
329            $data['errors']->push($ex->getMessage());
330
331            // Don't jump to step 4, as the error will make it jump to step 3.
332            return $this->viewResponse('setup/step-4-database-' . $data['dbtype'], $data);
333        }
334
335        return $this->viewResponse('setup/step-5-administrator', $data);
336    }
337
338    /**
339     * @param array<string,mixed> $data
340     *
341     * @return ResponseInterface
342     */
343    private function step6Install(array $data): ResponseInterface
344    {
345        $error = $this->checkAdminUser($data['wtname'], $data['wtuser'], $data['wtpass'], $data['wtemail']);
346
347        if ($error !== '') {
348            $data['errors']->push($error);
349
350            return $this->step5Administrator($data);
351        }
352
353        try {
354            $this->createConfigFile($data);
355        } catch (Throwable $exception) {
356            return $this->viewResponse('setup/step-6-failed', ['exception' => $exception]);
357        }
358
359        // Done - start using webtrees!
360        return redirect($data['baseurl']);
361    }
362
363    /**
364     * @param string $wtname
365     * @param string $wtuser
366     * @param string $wtpass
367     * @param string $wtemail
368     *
369     * @return string
370     */
371    private function checkAdminUser(string $wtname, string $wtuser, string $wtpass, string $wtemail): string
372    {
373        if ($wtname === '' || $wtuser === '' || $wtpass === '' || $wtemail === '') {
374            return I18N::translate('You must enter all the administrator account fields.');
375        }
376
377        if (mb_strlen($wtpass) < 6) {
378            return I18N::translate('The password needs to be at least six characters long.');
379        }
380
381        return '';
382    }
383
384    /**
385     * @param array<string,mixed> $data
386     *
387     * @return void
388     */
389    private function createConfigFile(array $data): void
390    {
391        // Create/update the database tables.
392        $this->connectToDatabase($data);
393        $this->migration_service->updateSchema('\Fisharebest\Webtrees\Schema', 'WT_SCHEMA_VERSION', Webtrees::SCHEMA_VERSION);
394
395        // Add some default/necessary configuration data.
396        $this->migration_service->seedDatabase();
397
398        // If we are re-installing, then this user may already exist.
399        $admin = $this->user_service->findByIdentifier($data['wtemail']);
400        if ($admin === null) {
401            $admin = $this->user_service->findByIdentifier($data['wtuser']);
402        }
403        // Create the user
404        if ($admin === null) {
405            $admin = $this->user_service->create($data['wtuser'], $data['wtname'], $data['wtemail'], $data['wtpass']);
406            $admin->setPreference(UserInterface::PREF_LANGUAGE, $data['lang']);
407            $admin->setPreference(UserInterface::PREF_IS_VISIBLE_ONLINE, '1');
408        } else {
409            $admin->setPassword($_POST['wtpass']);
410        }
411        // Make the user an administrator
412        $admin->setPreference(UserInterface::PREF_IS_ADMINISTRATOR, '1');
413        $admin->setPreference(UserInterface::PREF_IS_EMAIL_VERIFIED, '1');
414        $admin->setPreference(UserInterface::PREF_IS_ACCOUNT_APPROVED, '1');
415
416        // Write the config file. We already checked that this would work.
417        $config_ini_php = view('setup/config.ini', $data);
418
419        file_put_contents(Webtrees::CONFIG_FILE, $config_ini_php);
420
421        // Login as the new user
422        $request = Registry::container()->get(ServerRequestInterface::class)
423            ->withAttribute('base_url', $data['baseurl']);
424
425        Session::start($request);
426        Auth::login($admin);
427        Session::put('language', $data['lang']);
428    }
429
430    /**
431     * @param array<string,mixed> $data
432     *
433     * @return void
434     */
435    private function connectToDatabase(array $data): void
436    {
437        $capsule = new DB();
438
439        // Try to create the database, if it does not already exist.
440        switch ($data['dbtype']) {
441            case 'sqlite':
442                $data['dbname'] = Webtrees::ROOT_DIR . 'data/' . $data['dbname'] . '.sqlite';
443                touch($data['dbname']);
444                break;
445
446            case 'mysql':
447                $capsule->addConnection([
448                    'driver'                  => $data['dbtype'],
449                    'host'                    => $data['dbhost'],
450                    'port'                    => $data['dbport'],
451                    'database'                => '',
452                    'username'                => $data['dbuser'],
453                    'password'                => $data['dbpass'],
454                ], 'temp');
455                $capsule->getConnection('temp')->statement('CREATE DATABASE IF NOT EXISTS `' . $data['dbname'] . '` COLLATE utf8_unicode_ci');
456                break;
457        }
458
459        // Connect to the database.
460        $capsule->addConnection([
461            'driver'                  => $data['dbtype'],
462            'host'                    => $data['dbhost'],
463            'port'                    => $data['dbport'],
464            'database'                => $data['dbname'],
465            'username'                => $data['dbuser'],
466            'password'                => $data['dbpass'],
467            'prefix'                  => $data['tblpfx'],
468            'prefix_indexes'          => true,
469            // For MySQL
470            'charset'                 => 'utf8',
471            'collation'               => 'utf8_unicode_ci',
472            'timezone'                => '+00:00',
473            'engine'                  => 'InnoDB',
474            'modes'                   => [
475                'ANSI',
476                'STRICT_TRANS_TABLES',
477                'NO_ZERO_IN_DATE',
478                'NO_ZERO_DATE',
479                'ERROR_FOR_DIVISION_BY_ZERO',
480            ],
481            // For SQLite
482            'foreign_key_constraints' => true,
483        ]);
484
485        $capsule->setAsGlobal();
486
487        if ($data['dbtype'] === 'sqlsrv') {
488            DB::connection()->unprepared('SET language us_english'); // For timestamp columns
489        }
490    }
491}
492