xref: /webtrees/app/Http/Middleware/UseDatabase.php (revision a5068f91b4349f8a5e47576f9dd749d221f61a10)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2021 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\Middleware;
21
22use Fisharebest\Webtrees\Webtrees;
23use Illuminate\Database\Capsule\Manager as DB;
24use PDO;
25use PDOException;
26use Psr\Http\Message\ResponseInterface;
27use Psr\Http\Message\ServerRequestInterface;
28use Psr\Http\Server\MiddlewareInterface;
29use Psr\Http\Server\RequestHandlerInterface;
30use RuntimeException;
31
32/**
33 * Middleware to connect to the database.
34 */
35class UseDatabase implements MiddlewareInterface
36{
37    /**
38     * @param ServerRequestInterface  $request
39     * @param RequestHandlerInterface $handler
40     *
41     * @return ResponseInterface
42     */
43    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
44    {
45        // Earlier versions of webtrees did not have a dbtype config option.  They always used mysql.
46        $driver = $request->getAttribute('dbtype', 'mysql');
47
48        $dbname = $request->getAttribute('dbname');
49
50        if ($driver === 'sqlite') {
51            $dbname = Webtrees::ROOT_DIR . 'data/' . $dbname . '.sqlite';
52        }
53
54        $capsule = new DB();
55
56        // Newer versions of webtrees support utf8mb4.  Older ones only support 3-byte utf8
57        if ($driver === 'mysql' && $request->getAttribute('mysql_utf8mb4') === '1') {
58            $charset   = 'utf8mb4';
59            $collation = 'utf8mb4_unicode_ci';
60        } else {
61            $charset   = 'utf8';
62            $collation = 'utf8_unicode_ci';
63        }
64
65        $options = [
66            // Some drivers do this and some don't.  Make them consistent.
67            PDO::ATTR_STRINGIFY_FETCHES => true,
68        ];
69
70        $dbkey    = (string) $request->getAttribute('dbkey');
71        $dbcert   = (string) $request->getAttribute('dbcert');
72        $dbca     = (string) $request->getAttribute('dbca');
73        $dbverify = (bool) $request->getAttribute('dbverify');
74
75        // MySQL/MariaDB support encrypted connections
76        if ($dbkey !== '' && $dbcert !== '' && $dbca !== '') {
77            $options[PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT] = $dbverify;
78            $options[PDO::MYSQL_ATTR_SSL_KEY]                = Webtrees::ROOT_DIR . 'data/' . $dbkey;
79            $options[PDO::MYSQL_ATTR_SSL_CERT]               = Webtrees::ROOT_DIR . 'data/' . $dbcert;
80            $options[PDO::MYSQL_ATTR_SSL_CA]                 = Webtrees::ROOT_DIR . 'data/' . $dbca;
81        }
82
83        $capsule->addConnection([
84            'driver'                  => $driver,
85            'host'                    => $request->getAttribute('dbhost'),
86            'port'                    => $request->getAttribute('dbport'),
87            'database'                => $dbname,
88            'username'                => $request->getAttribute('dbuser'),
89            'password'                => $request->getAttribute('dbpass'),
90            'prefix'                  => $request->getAttribute('tblpfx'),
91            'prefix_indexes'          => true,
92            'options'                 => $options,
93            // For MySQL
94            'charset'                 => $charset,
95            'collation'               => $collation,
96            'timezone'                => '+00:00',
97            'engine'                  => 'InnoDB',
98            'modes'                   => [
99                'ANSI',
100                'STRICT_ALL_TABLES',
101                // Use SQL injection(!) to override MAX_JOIN_SIZE and GROUP_CONCAT_MAX_LEN settings.
102                "', SQL_BIG_SELECTS=1, GROUP_CONCAT_MAX_LEN=1048576, @foobar='"
103            ],
104            // For SQLite
105            'foreign_key_constraints' => true,
106        ]);
107
108        $capsule->setAsGlobal();
109
110        try {
111            // Eager-load the connection, to prevent database credentials appearing in error logs.
112            DB::connection()->getPdo();
113        } catch (PDOException $exception) {
114            throw new RuntimeException($exception->getMessage());
115        }
116
117        return $handler->handle($request);
118    }
119}
120