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