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\Webtrees; 23use Illuminate\Database\Capsule\Manager as DB; 24use Illuminate\Database\Query\Builder; 25use Psr\Http\Message\ResponseInterface; 26use Psr\Http\Message\ServerRequestInterface; 27use Psr\Http\Server\MiddlewareInterface; 28use Psr\Http\Server\RequestHandlerInterface; 29 30/** 31 * Middleware to connect to the database. 32 */ 33class UseDatabase implements MiddlewareInterface 34{ 35 /** 36 * @param ServerRequestInterface $request 37 * @param RequestHandlerInterface $handler 38 * 39 * @return ResponseInterface 40 */ 41 public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface 42 { 43 // Earlier versions of webtrees did not have a dbtype config option. They always used mysql. 44 $driver = $request->getAttribute('dbtype', 'mysql'); 45 46 $dbname = $request->getAttribute('dbname'); 47 48 if ($driver === 'sqlite') { 49 $dbname = Webtrees::ROOT_DIR . 'data/' . $dbname . '.sqlite'; 50 } 51 52 $capsule = new DB(); 53 54 $capsule->addConnection([ 55 'driver' => $driver, 56 'host' => $request->getAttribute('dbhost'), 57 'port' => $request->getAttribute('dbport'), 58 'database' => $dbname, 59 'username' => $request->getAttribute('dbuser'), 60 'password' => $request->getAttribute('dbpass'), 61 'prefix' => $request->getAttribute('tblpfx'), 62 'prefix_indexes' => true, 63 // For MySQL 64 'charset' => 'utf8', 65 'collation' => 'utf8_unicode_ci', 66 'timezone' => '+00:00', 67 'engine' => 'InnoDB', 68 'modes' => [ 69 'ANSI', 70 'STRICT_TRANS_TABLES', 71 'NO_ZERO_IN_DATE', 72 'NO_ZERO_DATE', 73 'ERROR_FOR_DIVISION_BY_ZERO', 74 ], 75 // For SQLite 76 'foreign_key_constraints' => true, 77 ]); 78 79 $capsule->setAsGlobal(); 80 81 Builder::macro('whereContains', function ($column, string $search, string $boolean = 'and'): Builder { 82 $search = strtr($search, ['\\' => '\\\\', '%' => '\\%', '_' => '\\_', ' ' => '%']); 83 84 return $this->where($column, 'LIKE', '%' . $search . '%', $boolean); 85 }); 86 87 return $handler->handle($request); 88 } 89} 90