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