xref: /webtrees/app/Http/Middleware/UseDatabase.php (revision b8d46257f9ef0575cb2b5cc7741e75beca7221bf)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2019 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\Exceptions\HttpServerErrorException;
23use Fisharebest\Webtrees\Webtrees;
24use Illuminate\Database\Capsule\Manager as DB;
25use Illuminate\Database\Query\Builder;
26use LogicException;
27use PDO;
28use PDOException;
29use Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31use Psr\Http\Server\MiddlewareInterface;
32use Psr\Http\Server\RequestHandlerInterface;
33
34/**
35 * Middleware to connect to the database.
36 */
37class UseDatabase implements MiddlewareInterface
38{
39    // The following errors are likely to be caused by server issues, not by webtrees.
40    private const SERVER_ERRORS = [
41        'mysql'  => [1203],
42        'pgsql'  => [],
43        'sqlite' => [],
44        'sqlsvr' => [],
45    ];
46
47    /**
48     * @param ServerRequestInterface  $request
49     * @param RequestHandlerInterface $handler
50     *
51     * @return ResponseInterface
52     */
53    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
54    {
55        // Earlier versions of webtrees did not have a dbtype config option.  They always used mysql.
56        $driver = $request->getAttribute('dbtype', 'mysql');
57
58        $dbname = $request->getAttribute('dbname');
59
60        if ($driver === 'sqlite') {
61            $dbname = Webtrees::ROOT_DIR . 'data/' . $dbname . '.sqlite';
62        }
63
64        $capsule = new DB();
65
66        $capsule->addConnection([
67            'driver'                  => $driver,
68            'host'                    => $request->getAttribute('dbhost'),
69            'port'                    => $request->getAttribute('dbport'),
70            'database'                => $dbname,
71            'username'                => $request->getAttribute('dbuser'),
72            'password'                => $request->getAttribute('dbpass'),
73            'prefix'                  => $request->getAttribute('tblpfx'),
74            'prefix_indexes'          => true,
75            'options'                 => [
76                // Some drivers do this and some don't.  Make them consistent.
77                PDO::ATTR_STRINGIFY_FETCHES => true,
78            ],
79            // For MySQL
80            'charset'                 => 'utf8',
81            'collation'               => 'utf8_unicode_ci',
82            'timezone'                => '+00:00',
83            'engine'                  => 'InnoDB',
84            'modes'                   => [
85                'ANSI',
86                'STRICT_ALL_TABLES',
87                // Use SQL injection(!) to override MAX_JOIN_SIZE setting.
88                "', SQL_BIG_SELECTS=1, @dummy='"
89            ],
90            // For SQLite
91            'foreign_key_constraints' => true,
92        ]);
93
94        $capsule->setAsGlobal();
95
96        Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder {
97            // Assertion helps static analysis tools understand where we will be using this closure.
98            assert($this instanceof Builder, new LogicException());
99
100            $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']);
101
102            return $this->where($column, 'LIKE', '%' . $search . '%', $boolean);
103        });
104
105        try {
106            return $handler->handle($request);
107        } catch (PDOException $exception) {
108            if (in_array($exception->errorInfo[1], self::SERVER_ERRORS[$driver], true)) {
109                $message = 'A database error occurred.  This is most likely caused by an issue with your server.' . PHP_EOL . PHP_EOL;
110                $message .= $exception->getMessage() . PHP_EOL . PHP_EOL;
111                $message .= $exception->getFile() . ':' . $exception->getLine();
112                throw new HttpServerErrorException($message);
113            }
114
115            throw $exception;
116        }
117    }
118}
119