Debian Codegraph @

classes/Database/Common/CommonDomainMapper.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) 2022-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 CommonDomainMapper 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\ErrorCodes;
36 use Liuch\DmarcSrg\Database\DomainMapperInterface;
37 use Liuch\DmarcSrg\Exception\SoftException;
38 use Liuch\DmarcSrg\Exception\LogicException;
39 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
40 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
41
42 /**
43 * Universal implementation of DomainMapper class
44 */
45 class CommonDomainMapper implements DomainMapperInterface
46 {
47 /** @var \Liuch\DmarcSrg\Database\DatabaseConnector */
48 private $connector = null;
49
50 /**
51 * The constructor
52 *
53 * @param \Liuch\DmarcSrg\Database\DatabaseConnector $connector DatabaseConnector instance of the current database
54 */
55 public function __construct(object $connector)
56 {
57 $this->connector = $connector;
58 }
59
60 /**
61 * Return true if the domain exists or false otherwise.
62 *
63 * @param array $data Array with domain data to search
64 *
65 * @return bool
66 */
67 public function exists(array &$data): bool
68 {
69 try {
70 $st = $this->connector->dbh()->prepare(
71 'SELECT id FROM ' . $this->connector->tablePrefix('domains') .
72 ' WHERE ' . $this->sqlCondition($data)
73 );
74 $this->sqlBindValues($st, $data, 1);
75 $st->execute();
76 $res = $st->fetch(\PDO::FETCH_NUM);
77 $st->closeCursor();
78 if (!$res) {
79 return false;
80 }
81 $data['id'] = intval($res[0]);
82 } catch (\PDOException $e) {
83 throw new DatabaseFatalException('Failed to get domain ID', -1, $e);
84 }
85 return true;
86 }
87
88 /**
89 * Returns true if the domain exists and is assigned to the user
90 *
91 * @param array $data Array with domain data to check
92 * @param int $user_id User ID to check
93 *
94 * @return bool
95 */
96 public function isAssigned(array &$data, int $user_id): bool
97 {
98 $res = null;
99 try {
100 $st = $this->connector->dbh()->prepare(
101 'SELECT 1 FROM ' . $this->connector->tablePrefix('userdomains') . ' INNER JOIN '
102 . $this->connector->tablePrefix('domains') . ' ON domain_id = id WHERE user_id = ? AND '
103 . $this->sqlCondition($data)
104 );
105 $st->bindValue(1, $user_id, \PDO::PARAM_INT);
106 $this->sqlBindValues($st, $data, 2);
107 $st->execute();
108 $res = $st->fetch(\PDO::FETCH_NUM);
109 $st->closeCursor();
110 } catch (\PDOException $e) {
111 throw new DatabaseFatalException('Failed to get user domain data', -1, $e);
112 }
113 return boolval($res);
114 }
115
116 /**
117 * Fetch the domain data from the database by its id or name
118 *
119 * @param array $data Domain data to update
120 *
121 * @return void
122 */
123 public function fetch(array &$data): void
124 {
125 try {
126 $st = $this->connector->dbh()->prepare(
127 'SELECT id, fqdn, active, description, created_time, updated_time FROM '
128 . $this->connector->tablePrefix('domains') . ' WHERE ' . $this->sqlCondition($data)
129 );
130 $this->sqlBindValues($st, $data, 1);
131 $st->execute();
132 $res = $st->fetch(\PDO::FETCH_NUM);
133 $st->closeCursor();
134 if (!$res) {
135 throw new DatabaseNotFoundException('Domain not found');
136 }
137 $data['id'] = intval($res[0]);
138 $data['fqdn'] = $res[1];
139 $data['active'] = boolval($res[2]);
140 $data['description'] = $res[3];
141 $data['created_time'] = new DateTime($res[4]);
142 $data['updated_time'] = new DateTime($res[5]);
143 } catch (\PDOException $e) {
144 throw new DatabaseFatalException('Failed to fetch the domain data', -1, $e);
145 }
146 }
147
148 /**
149 * Saves domain data to the database (updates or inserts an record)
150 *
151 * @param array $data Domain data
152 *
153 * @return void
154 */
155 public function save(array &$data): void
156 {
157 $db = $this->connector->dbh();
158 $data['updated_time'] = new DateTime();
159 if ($this->exists($data)) {
160 try {
161 $st = $db->prepare(
162 'UPDATE ' . $this->connector->tablePrefix('domains')
163 . ' SET active = ?, description = ?, updated_time = ? WHERE id = ?'
164 );
165 $st->bindValue(1, $data['active'], \PDO::PARAM_BOOL);
166 $st->bindValue(2, $data['description'], \PDO::PARAM_STR);
167 $st->bindValue(3, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
168 $st->bindValue(4, $data['id'], \PDO::PARAM_INT);
169 $st->execute();
170 $st->closeCursor();
171 } catch (\PDOException $e) {
172 throw new DatabaseFatalException('Failed to update the domain data', -1, $e);
173 }
174 } else {
175 try {
176 $active = $data['active'] ?? false;
177 $data['created_time'] = $data['updated_time'];
178 if (is_null($data['description'])) {
179 $sql1 = '';
180 $sql2 = '';
181 } else {
182 $sql1 = ', description';
183 $sql2 = ', ?';
184 }
185 $st = $db->prepare(
186 'INSERT INTO ' . $this->connector->tablePrefix('domains')
187 . ' (fqdn, active' . $sql1 . ', created_time, updated_time)'
188 . ' VALUES (?, ?' . $sql2 . ', ?, ?)'
189 );
190 $idx = 0;
191 $st->bindValue(++$idx, $data['fqdn'], \PDO::PARAM_STR);
192 $st->bindValue(++$idx, $active, \PDO::PARAM_BOOL);
193 if (!is_null($data['description'])) {
194 $st->bindValue(++$idx, $data['description'], \PDO::PARAM_STR);
195 }
196 $st->bindValue(++$idx, $data['created_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
197 $st->bindValue(++$idx, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
198 $st->execute();
199 $st->closeCursor();
200 $data['id'] = intval($db->lastInsertId());
201 $data['active'] = $active;
202 } catch (\PDOException $e) {
203 throw new DatabaseFatalException('Failed to insert the domain data', -1, $e);
204 }
205 }
206 }
207
208 /**
209 * Deletes the domain from the database
210 *
211 * Deletes the domain if there are no reports for this domain in the database.
212 *
213 * @param int $id Domain ID
214 * @param bool $force If there are incoming reports for this domain.
215 * True: Remove the incoming report with the domain
216 * False: Cancel domain deletion
217 *
218 * @return void
219 */
220 public function delete(int $id, bool $force): void
221 {
222 $db = $this->connector->dbh();
223 $db->beginTransaction();
224 try {
225 $filter = [ 'domain' => $id ];
226 $limit = [ 'offset' => 0, 'count' => 0 ];
227 if ($force) {
228 $order = [];
229 $this->connector->getMapper('report')->delete($filter, $order, $limit);
230 } else {
231 $r_count = $this->connector->getMapper('report')->count($filter, $limit, 0);
232 if ($r_count > 0) {
233 switch ($r_count) {
234 case 1:
235 $s1 = 'is';
236 $s2 = '';
237 break;
238 default:
239 $s1 = 'are';
240 $s2 = 's';
241 break;
242 }
243 throw new SoftException(
244 "Failed to delete: there {$s1} {$r_count} incoming report{$s2} for this domain",
245 ErrorCodes::DOMAIN_HAS_REPORTS
246 );
247 }
248 }
249 $st = $db->prepare(
250 'DELETE FROM ' . $this->connector->tablePrefix('userdomains') . ' WHERE domain_id = ?'
251 );
252 $st->bindValue(1, $id, \PDO::PARAM_INT);
253 $st->execute();
254 $st->closeCursor();
255 $st = $db->prepare('DELETE FROM ' . $this->connector->tablePrefix('domains') . ' WHERE id = ?');
256 $st->bindValue(1, $id, \PDO::PARAM_INT);
257 $st->execute();
258 $st->closeCursor();
259 $db->commit();
260 } catch (\PDOException $e) {
261 $db->rollBack();
262 throw new DatabaseFatalException('Failed to delete the domain', -1, $e);
263 } catch (\Exception $e) {
264 $db->rollBack();
265 throw $e;
266 }
267 }
268
269 /**
270 * Returns a list of domains data from the database
271 *
272 * @param int $user_id User ID to retrieve the list for
273 *
274 * @return array
275 */
276 public function list(int $user_id): array
277 {
278 $list = [];
279 try {
280 $query_str = 'SELECT id, fqdn, active, description, created_time, updated_time FROM ';
281 if ($user_id) {
282 $query_str .= $this->connector->tablePrefix('userdomains') . ' INNER JOIN '
283 . $this->connector->tablePrefix('domains') . ' ON domain_id = id WHERE user_id = '
284 . $user_id;
285 } else {
286 $query_str .= $this->connector->tablePrefix('domains');
287 }
288 $st = $this->connector->dbh()->query($query_str);
289 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
290 $list[] = [
291 'id' => intval($row[0]),
292 'fqdn' => $row[1],
293 'active' => boolval($row[2]),
294 'description' => $row[3],
295 'created_time' => new DateTime($row[4]),
296 'updated_time' => new DateTime($row[5])
297 ];
298 }
299 $st->closeCursor();
300 } catch (\PDOException $e) {
301 throw new DatabaseFatalException('Failed to get the domain list', -1, $e);
302 }
303 return $list;
304 }
305
306 /**
307 * Returns an ordered array with domain names from the database
308 *
309 * @param int $user_id User ID to retrieve the list for
310 *
311 * @return array
312 */
313 public function names(int $user_id): array
314 {
315 $res = [];
316 try {
317 if ($user_id) {
318 $query_str = 'SELECT fqdn FROM ' . $this->connector->tablePrefix('userdomains')
319 . ' INNER JOIN ' . $this->connector->tablePrefix('domains')
320 . ' ON domain_id = id WHERE user_id = ' . $user_id . ' ORDER BY fqdn';
321 } else {
322 $query_str = 'SELECT fqdn FROM ' . $this->connector->tablePrefix('domains') . ' ORDER BY fqdn';
323 }
324 $st = $this->connector->dbh()->query($query_str, \PDO::FETCH_NUM);
325 while ($name = $st->fetchColumn(0)) {
326 $res[] = $name;
327 }
328 $st->closeCursor();
329 } catch (\PDOException $e) {
330 throw new DatabaseFatalException('Failed to get a list of domain names', -1, $e);
331 }
332 return $res;
333 }
334
335 /**
336 * Returns the total number of domains in the database
337 *
338 * @param int $user_id User ID
339 * @param int $max The maximum number of records to count. 0 means no limitation.
340 *
341 * @return int The total number of domains
342 */
343 public function count(int $user_id, int $max = 0): int
344 {
345 $number = 0;
346 try {
347 if ($user_id === 0) {
348 $tn = 'domains';
349 $wr = '';
350 } else {
351 $tn = 'userdomains';
352 $wr = " WHERE user_id = {$user_id}";
353 }
354 $tn = $this->connector->tablePrefix($tn);
355 $query_str = "SELECT COUNT(*) FROM {$tn}{$wr}";
356 if ($max > 0) {
357 $query_str .= " LIMIT {$max}";
358 }
359 $st = $this->connector->dbh()->query($query_str, \PDO::FETCH_NUM);
360 $number = intval($st->fetchColumn(0));
361 $st->closeCursor();
362 } catch (\PDOException $e) {
363 throw new DatabaseFatalException('Failed to get the number of domains', -1, $e);
364 }
365 return $number;
366 }
367
368 /**
369 * Assigns the domain to a user
370 *
371 * @param array $data Domain data
372 * @param int $user_id User ID
373 *
374 * @return void
375 */
376 public function assignUser(array &$data, int $user_id): void
377 {
378 if (!$user_id) {
379 throw new LogicException('Attempting to assign a domain to admin');
380 }
381
382 $db = $this->connector->dbh();
383 $db->beginTransaction();
384 try {
385 $st = $db->prepare(
386 'SELECT id FROM ' . $this->connector->tablePrefix('domains')
387 . ' WHERE ' . $this->sqlCondition($data)
388 );
389 $this->sqlBindValues($st, $data, 1);
390 $st->execute();
391 $id = $st->fetchColumn(0);
392 $st->closeCursor();
393 if ($id !== false) {
394 $data['id'] = intval($id);
395 $st = $db->prepare(
396 'SELECT 1 FROM ' . $this->connector->tablePrefix('users') . ' WHERE id = ?'
397 );
398 $st->bindValue(1, $user_id, \PDO::PARAM_INT);
399 $st->execute();
400 $res = $st->fetchColumn(0);
401 $st->closeCursor();
402 if ($res) {
403 $ud_tn = $this->connector->tablePrefix('userdomains');
404 $st = $db->prepare('SELECT 1 FROM ' . $ud_tn . ' WHERE domain_id = ? AND user_id = ?');
405 $st->bindValue(1, $data['id'], \PDO::PARAM_INT);
406 $st->bindValue(2, $user_id, \PDO::PARAM_INT);
407 $st->execute();
408 $res = $st->fetchColumn(0);
409 $st->closeCursor();
410 if (!$res) {
411 $st = $db->prepare('INSERT INTO ' . $ud_tn . ' (domain_id, user_id) VALUES (?, ?)');
412 $st->bindValue(1, $data['id'], \PDO::PARAM_INT);
413 $st->bindValue(2, $user_id, \PDO::PARAM_INT);
414 $st->execute();
415 $st->closeCursor();
416 }
417 }
418 }
419 $db->commit();
420 } catch (\Exception $e) {
421 $db->rollBack();
422 throw new DatabaseFatalException('Failed to assign a domain', -1, $e);
423 }
424 }
425
426 /**
427 * Unassign the domain from a user
428 *
429 * @param array $data Domain data
430 * @param int $user_id User ID
431 *
432 * @return void
433 */
434 public function unassignUser(array &$data, int $user_id): void
435 {
436 if (!$user_id) {
437 throw new LogicException('Attempting to unassign a domain from admin');
438 }
439
440 try {
441 $dm_tn = $this->connector->tablePrefix('domains');
442 $ud_tn = $this->connector->tablePrefix('userdomains');
443 $st = $this->connector->dbh()->prepare(
444 "DELETE {$ud_tn} FROM {$ud_tn} INNER JOIN {$dm_tn} ON domain_id = id WHERE "
445 . $this->sqlCondition($data)
446 );
447 $this->sqlBindValues($st, $data, 1);
448 $st->execute();
449 $st->closeCursor();
450 } catch (\PDOException $e) {
451 throw new DatabaseFatalException('Failed to unassign a domain', -1, $e);
452 }
453 }
454
455 /**
456 * Updates the list of domains assigned to a user
457 *
458 * @param array $domains List of domains
459 * @param int $user_id User ID
460 *
461 * @return void
462 */
463 public function updateUserDomains(array &$domains, int $user_id): void
464 {
465 if (!$user_id) {
466 throw new LogicException('Attempting to udpate domains for admin');
467 }
468
469 $db = $this->connector->dbh();
470 $db->beginTransaction();
471 try {
472 $st = $db->prepare(
473 'DELETE FROM ' . $this->connector->tablePrefix('userdomains') . ' WHERE user_id = ?'
474 );
475 $st->bindValue(1, $user_id, \PDO::PARAM_INT);
476 $st->execute();
477 $st->closeCursor();
478 $cnt = count($domains);
479 if ($cnt) {
480 $query_str = 'INSERT INTO ' . $this->connector->tablePrefix('userdomains')
481 . ' (domain_id, user_id) SELECT id, ' . $user_id . ' FROM '
482 . $this->connector->tablePrefix('domains') . ' WHERE fqdn IN ('
483 . substr(str_repeat('?,', $cnt), 0, -1) . ')';
484 $st = $db->prepare($query_str);
485 $pos = 0;
486 foreach ($domains as $dom_str) {
487 $st->bindValue(++$pos, $dom_str, \PDO::PARAM_STR);
488 }
489 $st->execute();
490 $st->closeCursor();
491 }
492 $db->commit();
493 } catch (\Exception $e) {
494 $db->rollBack();
495 throw new DatabaseFatalException('Failed to update the user\'s domains', -1, $e);
496 }
497 }
498
499 /**
500 * Returns a condition string for a WHERE statement based on existing domain data
501 *
502 * @param array $data Domain data
503 *
504 * @return string Condition string
505 */
506 private function sqlCondition(array &$data): string
507 {
508 if (isset($data['id'])) {
509 return 'id = ?';
510 }
511 return 'fqdn = ?';
512 }
513
514 /**
515 * Binds values for SQL queries based on existing domain data
516 *
517 * @param \PDOStatement $st PDO Statement to bind to
518 * @param array $data Domain data
519 * @param int $pos Start position for binding
520 *
521 * @return void
522 */
523 private function sqlBindValues($st, array &$data, int $pos): void
524 {
525 if (isset($data['id'])) {
526 $st->bindValue($pos, $data['id'], \PDO::PARAM_INT);
527 } else {
528 $st->bindValue($pos, $data['fqdn'], \PDO::PARAM_STR);
529 }
530 }
531 }