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