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