Debian Codegraph @

classes/Database/Common/CommonUserMapper.php

raw symbols SCIP
1 <?php
2
3 /**
4 * dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
5 * Copyright (C) 2023-2025 Aleksey Andreev (liuch)
6 *
7 * Available at:
8 * https://github.com/liuch/dmarc-srg
9 *
10 * This program is free software: you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the Free
12 * Software Foundation, either version 3 of the License.
13 *
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
17 * more details.
18 *
19 * You should have received a copy of the GNU General Public License along with
20 * this program. If not, see <http://www.gnu.org/licenses/>.
21 *
22 * =========================
23 *
24 * This file contains the CommonUserMapper class
25 *
26 * @category API
27 * @package DmarcSrg
28 * @author Aleksey Andreev (liuch)
29 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
30 */
31
32 namespace Liuch\DmarcSrg\Database\Common;
33
34 use Liuch\DmarcSrg\DateTime;
35 use Liuch\DmarcSrg\Database\UserMapperInterface;
36 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
37 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
38
39 /**
40 * Universal implementation of UserMapper class
41 */
42 class CommonUserMapper implements UserMapperInterface
43 {
44 /** @var \Liuch\DmarcSrg\Database\DatabaseConnector */
45 private $connector = null;
46
47 /**
48 * The constructor
49 *
50 * @param \Liuch\DmarcSrg\Database\DatabaseConnector $connector DatabaseConnector instance of the current database
51 */
52 public function __construct(object $connector)
53 {
54 $this->connector = $connector;
55 }
56
57 /**
58 * Return true if the user exists or false otherwise.
59 *
60 * @param array $data Array with user data to search
61 *
62 * @return bool
63 */
64 public function exists(array &$data): bool
65 {
66 try {
67 $st = $this->connector->dbh()->prepare(
68 'SELECT id FROM ' . $this->connector->tablePrefix('users') . ' WHERE ' . $this->sqlCondition($data)
69 );
70 $this->sqlBindValues($st, $data, 1);
71 $st->execute();
72 $res = $st->fetch(\PDO::FETCH_NUM);
73 $st->closeCursor();
74 if (!$res) {
75 return false;
76 }
77 $data['id'] = intval($res[0]);
78 } catch (\PDOException $e) {
79 throw new DatabaseFatalException('Failed to verify the user existence', -1, $e);
80 }
81 return true;
82 }
83
84 /**
85 * Fetch the user data from the database by its id or name
86 *
87 * @param array $data User data to update
88 *
89 * @return void
90 */
91 public function fetch(array &$data): void
92 {
93 try {
94 $st = $this->connector->dbh()->prepare(
95 'SELECT id, name, level, enabled, IF(password IS NULL OR password = \'\', FALSE, TRUE),'
96 . ' email, "key", session, created_time, updated_time FROM '
97 . $this->connector->tablePrefix('users') . ' WHERE ' . $this->sqlCondition($data)
98 );
99 $this->sqlBindValues($st, $data, 1);
100 $st->execute();
101 $res = $st->fetch(\PDO::FETCH_NUM);
102 $st->closeCursor();
103 if (!$res) {
104 throw new DatabaseNotFoundException('User not found');
105 }
106 $data['id'] = intval($res[0]);
107 $data['name'] = $res[1];
108 $data['level'] = intval($res[2]);
109 $data['enabled'] = boolval($res[3]);
110 $data['password'] = boolval($res[4]);
111 $data['email'] = $res[5];
112 $data['key'] = $res[6];
113 $data['session'] = intval($res[7]);
114 $data['created_time'] = new DateTime($res[8]);
115 $data['updated_time'] = new DateTime($res[9]);
116 } catch (\PDOException $e) {
117 throw new DatabaseFatalException('Failed to fetch the user data', -1, $e);
118 }
119 }
120
121 /**
122 * Saves user data to the database (updates or inserts an record)
123 *
124 * @param array $data User data
125 *
126 * @return void
127 */
128 public function save(array &$data): void
129 {
130 $db = $this->connector->dbh();
131 $data['updated_time'] = new DateTime();
132 $enabled = $data['enabled'] ?? false;
133 if ($this->exists($data)) {
134 try {
135 $id = $data['id'];
136 $db->beginTransaction();
137 $u_tn = $this->connector->tablePrefix('users');
138 $extra = '';
139 if (!$enabled) {
140 $st = $db->prepare("SELECT enabled FROM {$u_tn} WHERE id = ?");
141 $st->bindValue(1, $id, \PDO::PARAM_INT);
142 $st->execute();
143 $res = $st->fetch(\PDO::FETCH_NUM);
144 $st->closeCursor();
145 if ($res && boolval($res[0])) {
146 // The user got deactivated. Reset its active sessions.
147 $extra = ', session = session + 1';
148 }
149 }
150 $st = $db->prepare(
151 'UPDATE ' . $u_tn
152 . ' SET level = ?, enabled = ?, email = ?, "key" = ?, updated_time = ?'
153 . $extra . ' WHERE id = ?'
154 );
155 $st->bindValue(1, $data['level'], \PDO::PARAM_INT);
156 $st->bindValue(2, $enabled, \PDO::PARAM_BOOL);
157 if (empty($data['email'])) {
158 $st->bindValue(3, null, \PDO::PARAM_NULL);
159 } else {
160 $st->bindValue(3, $data['email'], \PDO::PARAM_STR);
161 }
162 if (empty($data['key'])) {
163 $st->bindValue(4, null, \PDO::PARAM_NULL);
164 } else {
165 $st->bindValue(4, $data['key'], \PDO::PARAM_STR);
166 }
167 $st->bindValue(5, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
168 $st->bindValue(6, $id, \PDO::PARAM_INT);
169 $st->execute();
170 $st->closeCursor();
171 $db->commit();
172 } catch (\PDOException $e) {
173 $db->rollBack();
174 throw new DatabaseFatalException('Failed to update the user data', -1, $e);
175 } catch (\Exception $e) {
176 $db->rollBack();
177 throw $e;
178 }
179 } else {
180 try {
181 $data['created_time'] = $data['updated_time'];
182 if (!is_null($data['email'])) {
183 $ss1 = ', email';
184 $ss2 = ', ?';
185 } else {
186 $ss1 = '';
187 $ss2 = '';
188 }
189 if (!is_null($data['key'])) {
190 $ss1 .= ', "key"';
191 $ss2 .= ', ?';
192 }
193 $st = $db->prepare(
194 'INSERT INTO ' . $this->connector->tablePrefix('users')
195 . ' (name, level, enabled' . $ss1 . ', session, created_time, updated_time)'
196 . ' VALUES (?, ?, ?' . $ss2 . ', ?, ?, ?)'
197 );
198 $idx = 0;
199 $st->bindValue(++$idx, $data['name'], \PDO::PARAM_STR);
200 $st->bindValue(++$idx, $data['level'], \PDO::PARAM_INT);
201 $st->bindValue(++$idx, $enabled, \PDO::PARAM_BOOL);
202 if (!is_null($data['email'])) {
203 $st->bindValue(++$idx, $data['email'], \PDO::PARAM_STR);
204 }
205 if (!is_null($data['key'])) {
206 $st->bindValue(++$idx, $data['key'], \PDO::PARAM_STR);
207 }
208 $st->bindValue(++$idx, 0, \PDO::PARAM_INT);
209 $st->bindValue(++$idx, $data['created_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
210 $st->bindValue(++$idx, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
211 $st->execute();
212 $st->closeCursor();
213 $data['id'] = intval($db->lastInsertId());
214 $data['enabled'] = $enabled;
215 $data['session'] = 0;
216 } catch (\PDOException $e) {
217 throw new DatabaseFatalException('Failed to insert the user data', -1, $e);
218 }
219 }
220 }
221
222 /**
223 * Deletes the user from the database
224 *
225 * @param array $data User data
226 *
227 * @return void
228 */
229 public function delete(array &$data): void
230 {
231 $db = $this->connector->dbh();
232 $db->beginTransaction();
233 try {
234 $id = $data['id'];
235 $st = $db->prepare('DELETE FROM ' . $this->connector->tablePrefix('userdomains')
236 . ' WHERE user_id = ?');
237 $st->bindValue(1, $id, \PDO::PARAM_INT);
238 $st->execute();
239 $st->closeCursor();
240 $st = $db->prepare('DELETE FROM "' . $this->connector->tablePrefix('system') . '" WHERE user_id = ?');
241 $st->bindValue(1, $id, \PDO::PARAM_INT);
242 $st->execute();
243 $st->closeCursor();
244 $st = $db->prepare('DELETE FROM ' . $this->connector->tablePrefix('users') . ' WHERE id = ?');
245 $st->bindValue(1, $id, \PDO::PARAM_INT);
246 $st->execute();
247 $st->closeCursor();
248 $db->commit();
249 } catch (\PDOException $e) {
250 $db->rollBack();
251 throw new DatabaseFatalException('Failed to delete the user', -1, $e);
252 } catch (\Exception $e) {
253 $db->rollBack();
254 throw $e;
255 }
256 }
257
258 /**
259 * Returns a list of users data from the database
260 *
261 * @return array
262 */
263 public function list(): array
264 {
265 $list = [];
266 try {
267 $st = $this->connector->dbh()->query(
268 'SELECT id, name, level, enabled, email, "key", created_time, updated_time, '
269 . '(SELECT COUNT(*) FROM ' . $this->connector->tablePrefix('userdomains')
270 . ' WHERE user_id = id) AS domains FROM ' . $this->connector->tablePrefix('users')
271 );
272 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
273 $list [] = [
274 'id' => intval($row[0]),
275 'name' => $row[1],
276 'level' => intval($row[2]),
277 'enabled' => boolval($row[3]),
278 'email' => $row[4],
279 'key' => $row[5],
280 'created_time' => new DateTime($row[6]),
281 'updated_time' => new DateTime($row[7]),
282 'domains' => intval($row[8])
283 ];
284 }
285 $st->closeCursor();
286 } catch (\PDOException $e) {
287 throw new DatabaseFatalException('Failed to get the domain list', -1, $e);
288 }
289 return $list;
290 }
291
292 /**
293 * Returns the user's password hash
294 *
295 * @param array $data User data
296 *
297 * @return string
298 */
299 public function getPasswordHash(array &$data): string
300 {
301 $hash = '';
302 try {
303 $st = $this->connector->dbh()->prepare(
304 'SELECT password FROM ' . $this->connector->tablePrefix('users')
305 . ' WHERE ' . $this->sqlCondition($data)
306 );
307 $this->sqlBindValues($st, $data, 1);
308 $st->execute();
309 $res = $st->fetch(\PDO::FETCH_NUM);
310 $st->closeCursor();
311 if (!$res) {
312 throw new DatabaseNotFoundException('User not found');
313 }
314 $hash = strval($res[0]);
315 } catch (\PDOException $e) {
316 throw new DatabaseFatalException('Failed to get user data', -1, $e);
317 }
318 return $hash;
319 }
320
321 /**
322 * Replaces the user's password hash with the passed one
323 *
324 * @param array $data User data
325 * @param string $hash Password hash to save
326 */
327 public function savePasswordHash(array &$data, string $hash): void
328 {
329 try {
330 $st = $this->connector->dbh()->prepare(
331 'UPDATE ' . $this->connector->tablePrefix('users')
332 . ' SET password = ?, session = session + 1 WHERE ' . $this->sqlCondition($data)
333 );
334 $st->bindValue(1, $hash, \PDO::PARAM_STR);
335 $this->sqlBindValues($st, $data, 2);
336 $st->execute();
337 $st->closeCursor();
338 } catch (\PDOException $e) {
339 throw new DatabaseFatalException('Failed to save user data', -1, $e);
340 }
341 }
342
343 /**
344 * Updates the user's key string
345 *
346 * @param array $data User data
347 * @param string $key User key string to set
348 *
349 * @return void
350 */
351 public function setUserKey(array &$data, string $key): void
352 {
353 try {
354 $st = $this->connector->dbh()->prepare(
355 'UPDATE ' . $this->connector->tablePrefix('users')
356 . ' SET "key" = ? WHERE ' . $this->sqlCondition($data)
357 );
358 $st->bindValue(1, $key, \PDO::PARAM_STR);
359 $this->sqlBindValues($st, $data, 2);
360 $st->execute();
361 $st->closeCursor();
362 $data['key'] = $key;
363 } catch (\PDOException $e) {
364 throw new DatabaseFatalException('Failed to update user key', -1, $e);
365 }
366 }
367
368 /**
369 * Returns a condition string for a WHERE statement based on existing user data
370 *
371 * @param array $data User data
372 *
373 * @return string
374 */
375 private function sqlCondition(array &$data): string
376 {
377 if (isset($data['id'])) {
378 return 'id = ?';
379 }
380 return 'name = ?';
381 }
382
383 /**
384 * Binds values for SQL queries based on existing user data
385 *
386 * @param \PDOStatement $st PDO statement to bind to
387 * @param array $data User data
388 * @param int $pos Bind position
389 *
390 * @return void
391 */
392 private function sqlBindValues($st, array &$data, int $pos): void
393 {
394 if (isset($data['id'])) {
395 $st->bindValue($pos, $data['id'], \PDO::PARAM_INT);
396 } else {
397 $st->bindValue($pos, $data['name'], \PDO::PARAM_STR);
398 }
399 }
400 }