1<?php 2/** 3 * webtrees: online genealogy 4 * Copyright (C) 2019 webtrees development team 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * You should have received a copy of the GNU General Public License 14 * along with this program. If not, see <http://www.gnu.org/licenses/>. 15 */ 16declare(strict_types=1); 17 18namespace Fisharebest\Webtrees; 19 20use Illuminate\Database\Capsule\Manager as DB; 21use Psr\Http\Message\ServerRequestInterface; 22use SessionHandlerInterface; 23 24/** 25 * Session handling - stores sessions in the database. 26 */ 27class SessionDatabaseHandler implements SessionHandlerInterface 28{ 29 /** @var ServerRequestInterface */ 30 private $request; 31 32 public function __construct(ServerRequestInterface $request) { 33 $this->request = $request; 34 } 35 36 /** 37 * @param $save_path 38 * @param $name 39 * 40 * @return bool 41 */ 42 public function open($save_path, $name): bool 43 { 44 return true; 45 } 46 47 /** 48 * @return bool 49 */ 50 public function close(): bool 51 { 52 return true; 53 } 54 55 /** 56 * @param string $id 57 * 58 * @return string 59 */ 60 public function read($id): string 61 { 62 return (string) DB::table('session') 63 ->where('session_id', '=', $id) 64 ->value('session_data'); 65 } 66 67 /** 68 * @param string $id 69 * @param string $data 70 * 71 * @return bool 72 */ 73 public function write($id, $data): bool 74 { 75 DB::table('session')->updateOrInsert([ 76 'session_id' => $id, 77 ], [ 78 'session_time' => Carbon::now(), 79 'user_id' => (int) Auth::id(), 80 'ip_address' => $this->request->getServerParams()['REMOTE_ADDR'] ?? '127.0.0.1', 81 'session_data' => $data, 82 ]); 83 84 return true; 85 } 86 87 /** 88 * @param string $id 89 * 90 * @return bool 91 */ 92 public function destroy($id): bool 93 { 94 DB::table('session') 95 ->where('session_id', '=', $id) 96 ->delete(); 97 98 return true; 99 } 100 101 /** 102 * @param int $maxlifetime 103 * 104 * @return bool 105 */ 106 public function gc($maxlifetime): bool 107 { 108 DB::table('session') 109 ->where('session_time', '<', Carbon::now()->subSeconds($maxlifetime)) 110 ->delete(); 111 112 return true; 113 } 114 115} 116