Debian Codegraph @

classes/Database/Common/CommonReportMapper.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 CommonReportMapper 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\Core;
35 use Liuch\DmarcSrg\Common;
36 use Liuch\DmarcSrg\DateTime;
37 use Liuch\DmarcSrg\Report\ReportData;
38 use Liuch\DmarcSrg\Settings\SettingsList;
39 use Liuch\DmarcSrg\Database\ReportMapperInterface;
40 use Liuch\DmarcSrg\Exception\SoftException;
41 use Liuch\DmarcSrg\Exception\LogicException;
42 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
43 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
44
45 /**
46 * Universal implementation of ReportMapper class
47 */
48 class CommonReportMapper implements ReportMapperInterface
49 {
50 /** @var \Liuch\DmarcSrg\Database\DatabaseConnector */
51 private $connector = null;
52
53 private static $allowed_domains = null;
54
55 /**
56 * The constructor
57 *
58 * @param \Liuch\DmarcSrg\Database\DatabaseConnector $connector DatabaseConnector instance of the current database
59 */
60 public function __construct(object $connector)
61 {
62 $this->connector = $connector;
63 }
64
65 /**
66 * Fetches report data from the database and stores it in the passed array
67 *
68 * @param ReportData $data Report data class.
69 * To identify the report it must contain at least these fields:
70 * `report_id` - External report id from the xml file
71 * `domain` - Fully Qualified Domain Name without a trailing dot
72 * `org_name` - Organization name
73 * `date=>begin` - Begin timestamp of the report time range
74 *
75 * @return void
76 */
77 public function fetch($data): void
78 {
79 $db = $this->connector->dbh();
80 try {
81 $st = $db->prepare(
82 'SELECT rp.id, end_time, loaded_time, email, extra_contact_info,'
83 . ' error_string, policy_adkim, policy_aspf, policy_p, policy_sp, policy_np,'
84 . ' policy_pct, policy_fo FROM ' . $this->connector->tablePrefix('reports')
85 . ' AS rp INNER JOIN ' . $this->connector->tablePrefix('domains')
86 . ' AS dom ON dom.id = rp.domain_id'
87 . ' WHERE fqdn = ? AND begin_time = ? AND org = ? AND external_id = ?'
88 );
89 $st->bindValue(1, $data->domain, \PDO::PARAM_STR);
90 $st->bindValue(2, $data->date['begin']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
91 $st->bindValue(3, $data->org_name, \PDO::PARAM_STR);
92 $st->bindValue(4, $data->report_id, \PDO::PARAM_STR);
93 $st->execute();
94 if (!($res = $st->fetch(\PDO::FETCH_NUM))) {
95 throw new DatabaseNotFoundException('The report is not found');
96 }
97 $id = intval($res[0]);
98 $data->date['end'] = new DateTime($res[1]);
99 $data->loaded_time = new DateTime($res[2]);
100 $data->email = $res[3];
101 $data->extra_contact_info = $res[4];
102 $data->error_string = json_decode($res[5] ?? '', true);
103 $data->policy = [
104 'adkim' => $res[6],
105 'aspf' => $res[7],
106 'p' => $res[8],
107 'sp' => $res[9],
108 'np' => $res[10],
109 'pct' => $res[11],
110 'fo' => $res[12]
111 ];
112
113 $order_str = $this->sqlOrderRecords();
114 $st = $db->prepare(
115 'SELECT report_id, ip, rcount, disposition, reason, dkim_auth , spf_auth, dkim_align,'
116 . ' spf_align, envelope_to, envelope_from, header_from FROM '
117 . $this->connector->tablePrefix('rptrecords') . ' WHERE report_id = ?' . $order_str
118 );
119 $st->bindValue(1, $id, \PDO::PARAM_INT);
120 $st->execute();
121 $data->records = [];
122 while ($res = $st->fetch(\PDO::FETCH_NUM)) {
123 $data->records[] = [
124 'ip' => inet_ntop($res[1]),
125 'count' => intval($res[2]),
126 'disposition' => Common::$disposition[$res[3]],
127 'reason' => json_decode($res[4] ?? '', true),
128 'dkim_auth' => json_decode($res[5] ?? '', true),
129 'spf_auth' => json_decode($res[6] ?? '', true),
130 'dkim_align' => Common::$align_res[$res[7]],
131 'spf_align' => Common::$align_res[$res[8]],
132 'envelope_to' => $res[9],
133 'envelope_from' => $res[10],
134 'header_from' => $res[11]
135 ];
136 }
137 $st->closeCursor();
138 } catch (\PDOException $e) {
139 throw new DatabaseFatalException('Failed to get the report from DB', -1, $e);
140 }
141 }
142
143 /**
144 * Inserts report data into the database.
145 *
146 * @param ReportData $data Report data
147 *
148 * @return void
149 */
150 public function save($data): void
151 {
152 $db = $this->connector->dbh();
153 $db->beginTransaction();
154 try {
155 $domain_data = [ 'fqdn' => strtolower($data->domain) ];
156 $domain_mapper = $this->connector->getMapper('domain');
157 try {
158 $domain_mapper->fetch($domain_data);
159 if (!$domain_data['active']) {
160 throw new SoftException('Failed to add an incoming report: the domain is inactive');
161 }
162 $user_id = Core::instance()->getCurrentUser()->id();
163 if ($user_id !== 0 && !$domain_mapper->isAssigned($domain_data, $user_id)) {
164 // The domain exists but is not assigned to the current user
165 $this->unknownDomain($domain_data);
166 }
167 } catch (DatabaseNotFoundException $e) {
168 // The domain is not found. Let's try to add it automatically.
169 if (Core::instance()->getCurrentUser()->id() !== 0) {
170 $this->unknownDomain($domain_data);
171 }
172 $this->insertDomain($domain_data, $domain_mapper);
173 }
174
175 $ct = new DateTime();
176 $st = $db->prepare(
177 'INSERT INTO ' . $this->connector->tablePrefix('reports')
178 . ' (domain_id, begin_time, end_time, loaded_time, org, external_id, email,'
179 . ' extra_contact_info, error_string, policy_adkim, policy_aspf, policy_p,'
180 . ' policy_sp, policy_np, policy_pct, policy_fo, seen)'
181 . ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)'
182 );
183 $st->bindValue(1, $domain_data['id'], \PDO::PARAM_INT);
184 $st->bindValue(2, $data->date['begin']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
185 $st->bindValue(3, $data->date['end']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
186 $st->bindValue(4, $ct->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
187 $st->bindValue(5, $data->org_name, \PDO::PARAM_STR);
188 $st->bindValue(6, $data->report_id, \PDO::PARAM_STR);
189 $st->bindValue(7, $data->email ?? '', \PDO::PARAM_STR);
190 $st->bindValue(8, $data->extra_contact_info, \PDO::PARAM_STR);
191 self::sqlBindJson($st, 9, $data->error_string);
192 $st->bindValue(10, $data->policy['adkim'], \PDO::PARAM_STR);
193 $st->bindValue(11, $data->policy['aspf'], \PDO::PARAM_STR);
194 $st->bindValue(12, $data->policy['p'], \PDO::PARAM_STR);
195 $st->bindValue(13, $data->policy['sp'], \PDO::PARAM_STR);
196 $st->bindValue(14, $data->policy['np'], \PDO::PARAM_STR);
197 $st->bindValue(15, $data->policy['pct'], \PDO::PARAM_STR);
198 $st->bindValue(16, $data->policy['fo'], \PDO::PARAM_STR);
199 $st->execute();
200 $new_id = intval($db->lastInsertId());
201 $st->closeCursor();
202
203 $st = $db->prepare(
204 'INSERT INTO ' . $this->connector->tablePrefix('rptrecords')
205 . ' (report_id, ip, rcount, disposition, reason, dkim_auth, spf_auth, dkim_align,'
206 . ' spf_align, envelope_to, envelope_from, header_from)'
207 . ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
208 );
209 foreach ($data->records as &$rec_data) {
210 $st->bindValue(1, $new_id, \PDO::PARAM_INT);
211 $st->bindValue(2, inet_pton($rec_data['ip']), \PDO::PARAM_STR);
212 $st->bindValue(3, $rec_data['count'], \PDO::PARAM_INT);
213 $st->bindValue(4, array_search($rec_data['disposition'], Common::$disposition), \PDO::PARAM_INT);
214 self::sqlBindJson($st, 5, $rec_data['reason']);
215 self::sqlBindJson($st, 6, $rec_data['dkim_auth']);
216 self::sqlBindJson($st, 7, $rec_data['spf_auth']);
217 $st->bindValue(8, array_search($rec_data['dkim_align'], Common::$align_res), \PDO::PARAM_INT);
218 $st->bindValue(9, array_search($rec_data['spf_align'], Common::$align_res), \PDO::PARAM_INT);
219 $st->bindValue(10, $rec_data['envelope_to'], \PDO::PARAM_STR);
220 $st->bindValue(11, $rec_data['envelope_from'], \PDO::PARAM_STR);
221 $st->bindValue(12, $rec_data['header_from'], \PDO::PARAM_STR);
222 $st->execute();
223 }
224 unset($rec_data);
225 $db->commit();
226 $data->loaded_time = $ct;
227 } catch (\PDOException $e) {
228 $db->rollBack();
229 if ($e->getCode() == '23000') {
230 throw new SoftException('This report has already been loaded');
231 }
232 throw new DatabaseFatalException('Failed to insert the report', -1, $e);
233 } catch (\Exception $e) {
234 $db->rollBack();
235 throw $e;
236 }
237 }
238
239 /**
240 * Sets report record property in database.
241 *
242 * It has nothing to do with the fields of the report itself.
243 *
244 * @param ReportData $data Report data
245 * @param string $name Name of property to change. Currently only `seen` is supported.
246 * @param mixed $value New property value
247 *
248 * @return void
249 */
250 public function setProperty($data, string $name, $value): void
251 {
252 if ($name !== 'seen' && gettype($value) !== 'boolean') {
253 throw new LogicException('Incorrect parameters');
254 }
255
256 try {
257 $st = $this->connector->dbh()->prepare(
258 'UPDATE ' . $this->connector->tablePrefix('reports') . ' AS rp'
259 . ' INNER JOIN ' . $this->connector->tablePrefix('domains') . ' AS dom'
260 . ' ON rp.domain_id = dom.id SET seen = ?'
261 . ' WHERE fqdn = ? AND begin_time = ? AND org = ? AND external_id = ?'
262 );
263 $st->bindValue(1, $value, \PDO::PARAM_BOOL);
264 $st->bindValue(2, $data->domain, \PDO::PARAM_STR);
265 $st->bindValue(3, $data->date['begin']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
266 $st->bindValue(4, $data->org_name, \PDO::PARAM_STR);
267 $st->bindValue(5, $data->report_id, \PDO::PARAM_STR);
268 $st->execute();
269 $st->closeCursor();
270 } catch (\PDOException $e) {
271 throw new DatabaseFatalException('Failed to update the DB record', -1, $e);
272 }
273 }
274
275 /**
276 * Returns a list of reports with specified parameters
277 *
278 * This method returns a list of reports that depends on the $filter, $order and $limit.
279 *
280 * @param array $filter Key-value array with filtering parameters
281 * @param array $order Key-value array:
282 * 'field' => string, 'begin_time'
283 * 'direction' => string, 'ascent' or 'descent'
284 * @param array $limit Key-value array with two keys: `offset` and `count`
285 * @param int $user_id User ID to retrieve the list for
286 *
287 * @return array
288 */
289 public function list(array &$filter, array &$order, array &$limit, int $user_id): array
290 {
291 $db = $this->connector->dbh();
292 $list = [];
293 $f_data = $this->prepareFilterData($filter, 'rp');
294 $user_doms = $this->sqlUserRestriction($user_id, 'd.id');
295 $order_str = $this->sqlOrderList($order, 'rp.id');
296 $cond_str0 = $this->sqlConditionList($f_data, ' AND ', 0);
297 $cond_str1 = $this->sqlConditionList($f_data, ' HAVING ', 1);
298 $limit_str = $this->sqlLimit($limit);
299 try {
300 $st = $db->prepare(
301 'SELECT org, begin_time, end_time, fqdn, external_id, seen, SUM(rcount) AS rcount,'
302 . ' SUM(IF(dkim_align = 0, rcount, 0)) AS dkim_align_fail,'
303 . ' SUM(IF(dkim_align = 1, rcount, 0)) AS dkim_align_unknown,'
304 . ' SUM(IF(spf_align = 0, rcount, 0)) AS spf_align_fail,'
305 . ' SUM(IF(spf_align = 1, rcount, 0)) AS spf_align_unknown,'
306 . ' SUM(IF(disposition = 0, rcount, 0)) AS rejected,'
307 . ' SUM(IF(disposition = 1, rcount, 0)) AS quarantined'
308 . ' FROM ' . $this->connector->tablePrefix('rptrecords')
309 . ' AS rr RIGHT JOIN (SELECT rp.id, org, begin_time, end_time, external_id,'
310 . ' fqdn, seen FROM ' . $this->connector->tablePrefix('reports')
311 . ' AS rp INNER JOIN ' . $this->connector->tablePrefix('domains')
312 . ' AS d ON d.id = rp.domain_id' . $user_doms . $cond_str0 . $order_str
313 . ') AS rp ON rp.id = rr.report_id GROUP BY rp.id'
314 . $cond_str1 . $order_str . $limit_str
315 );
316 $this->sqlBindValues($st, $f_data, $limit);
317 $st->execute();
318 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
319 $messages = intval($row[6]);
320 $dkim_fail = intval($row[7]);
321 $dkim_unkn = intval($row[8]);
322 $spf_fail = intval($row[9]);
323 $spf_unkn = intval($row[10]);
324 $list[] = [
325 'org_name' => $row[0],
326 'date' => [
327 'begin' => new DateTime($row[1]),
328 'end' => new DateTime($row[2])
329 ],
330 'domain' => $row[3],
331 'report_id' => $row[4],
332 'seen' => (bool) $row[5],
333 'messages' => $messages,
334 'dkim_align' => [
335 'fail' => $dkim_fail,
336 'unknown' => $dkim_unkn,
337 'pass' => $messages - $dkim_fail - $dkim_unkn
338 ],
339 'spf_align' => [
340 'fail' => $spf_fail,
341 'unknown' => $spf_unkn,
342 'pass' => $messages - $spf_fail - $spf_unkn
343 ],
344 'rejected' => intval($row[11]),
345 'quarantined' => intval($row[12])
346 ];
347 }
348 $st->closeCursor();
349 } catch (\PDOException $e) {
350 throw new DatabaseFatalException('Failed to get the report list', -1, $e);
351 }
352 return $list;
353 }
354
355 /**
356 * Returns the number of reports matching the specified filter and limits
357 *
358 * @param array $filter Key-value array with filtering parameters
359 * @param array $limit Key-value array with two keys: `offset` and `count`
360 * @param int $user_id User ID to count reports for
361 *
362 * @return int
363 */
364 public function count(array &$filter, array &$limit, int $user_id): int
365 {
366 $cnt = 0;
367 $f_data = $this->prepareFilterData($filter, 'rp');
368 try {
369 if (isset($filter['dkim']) || isset($filter['spf']) || isset($filter['disposition'])) {
370 $st = $this->connector->dbh()->prepare(
371 'SELECT COUNT(*) FROM ('
372 . 'SELECT SUM(IF(dkim_align = 0, rcount, 0)) AS dkim_align_fail,'
373 . ' SUM(IF(dkim_align = 1, rcount, 0)) AS dkim_align_unknown,'
374 . ' SUM(IF(spf_align = 0, rcount, 0)) AS spf_align_fail,'
375 . ' SUM(IF(spf_align = 1, rcount, 0)) AS spf_align_unknown,'
376 . ' SUM(IF(disposition = 0, rcount, 0)) AS rejected,'
377 . ' SUM(IF(disposition = 1, rcount, 0)) AS quarantined'
378 . ' FROM ' . $this->connector->tablePrefix('rptrecords')
379 . ' AS rr RIGHT JOIN (SELECT rp.id FROM ' . $this->connector->tablePrefix('reports')
380 . ' AS rp INNER JOIN ' . $this->connector->tablePrefix('domains')
381 . ' AS d ON d.id = rp.domain_id' . $this->sqlUserRestriction($user_id, 'd.id')
382 . $this->sqlConditionList($f_data, ' AND ', 0)
383 . ') AS rp ON rp.id = rr.report_id GROUP BY rp.id'
384 . $this->sqlConditionList($f_data, ' HAVING ', 1)
385 . ') AS ct'
386 );
387 } elseif ($user_id) {
388 $st = $this->connector->dbh()->prepare(
389 'SELECT COUNT(*) FROM ' . $this->connector->tablePrefix('reports') . ' AS rp'
390 . ' INNER JOIN ' . $this->connector->tablePrefix('domains')
391 . ' AS d ON d.id = rp.domain_id' . $this->sqlUserRestriction($user_id, 'd.id')
392 . $this->sqlConditionList($f_data, ' AND ', 0)
393 );
394 } else {
395 $st = $this->connector->dbh()->prepare(
396 'SELECT COUNT(*) FROM ' . $this->connector->tablePrefix('reports') . ' AS rp'
397 . $this->sqlConditionList($f_data, ' WHERE ', 0)
398 );
399 }
400 $l_empty = [ 'offset' => 0, 'count' => 0 ];
401 $this->sqlBindValues($st, $f_data, $l_empty);
402 $st->execute();
403 $cnt = intval($st->fetch(\PDO::FETCH_NUM)[0]);
404 $st->closeCursor();
405
406 $offset = $limit['offset'];
407 if ($offset > 0) {
408 $cnt -= $offset;
409 if ($cnt < 0) {
410 $cnt = 0;
411 }
412 }
413 $max = $limit['count'];
414 if ($max > 0 && $max < $cnt) {
415 $cnt = $max;
416 }
417 } catch (\PDOException $e) {
418 throw new DatabaseFatalException('Failed to get the number of reports', -1, $e);
419 }
420 return $cnt;
421 }
422
423 /**
424 * Deletes reports from the database
425 *
426 * It deletes repors form the database. The filter options `dkim`, `spf` and `disposition` do not affect this.
427 *
428 * @param array $filter Key-value array with filtering parameters
429 * @param array $order Key-value array:
430 * 'field' => string, 'begin_time'
431 * 'direction' => string, 'ascent' or 'descent'
432 * @param array $limit Key-value array with two keys: `offset` and `count`
433 *
434 * @return void
435 */
436 public function delete(array &$filter, array &$order, array &$limit): void
437 {
438 if (Core::instance()->getCurrentUser()->id()) {
439 throw new LogicException('Attempted deletion of reports by non-admin user');
440 }
441 $f_data = $this->prepareFilterData($filter, '');
442 $cond_str = $this->sqlConditionList($f_data, ' WHERE ', 0);
443 $order_str = $this->sqlOrderList($order, 'id');
444 $limit_str = $this->sqlLimit($limit);
445 $db = $this->connector->dbh();
446 if (!$db->inTransaction()) {
447 $db->beginTransaction();
448 $nested = false;
449 } else {
450 $nested = true;
451 }
452 try {
453 $st = $db->prepare(
454 'DELETE rr FROM ' . $this->connector->tablePrefix('rptrecords')
455 . ' AS rr INNER JOIN (SELECT id FROM ' . $this->connector->tablePrefix('reports')
456 . $cond_str . $order_str . $limit_str . ') AS rp ON rp.id = rr.report_id'
457 );
458 $this->sqlBindValues($st, $f_data, $limit);
459 $st->execute();
460 $st->closeCursor();
461
462 $st = $db->prepare(
463 'DELETE FROM ' . $this->connector->tablePrefix('reports') . "{$cond_str}{$order_str}{$limit_str}"
464 );
465 $this->sqlBindValues($st, $f_data, $limit);
466 $st->execute();
467 $st->closeCursor();
468
469 if (!$nested) {
470 $db->commit();
471 }
472 } catch (\PDOException $e) {
473 if (!$nested) {
474 $db->rollBack();
475 }
476 throw new DatabaseFatalException('Failed to delete reports', -1, $e);
477 } catch (\Exception $e) {
478 if (!$nested) {
479 $db->rollBack();
480 }
481 throw $e;
482 }
483 }
484
485 /**
486 * Returns a list of months with years of the form: 'yyyy-mm' for which there is at least one report
487 *
488 * @param int $user_id User ID to retrieve the list for
489 *
490 * @return array
491 */
492 public function months(int $user_id): array
493 {
494 $res = [];
495 $rep_tn = $this->connector->tablePrefix('reports');
496 try {
497 $ud = $this->sqlUserRestriction($user_id, 'rp.domain_id');
498 $st = $this->connector->dbh()->query(
499 'SELECT DISTINCT DATE_FORMAT(date, \'%Y-%m\') AS month FROM'
500 . ' ((SELECT DISTINCT begin_time AS date FROM ' . $rep_tn
501 . ' AS rp' . $ud . ') UNION (SELECT DISTINCT end_time AS date FROM ' . $rep_tn
502 . ' AS rp' . $ud . ')) AS r ORDER BY month DESC'
503 );
504 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
505 $res[] = $row[0];
506 }
507 $st->closeCursor();
508 } catch (\PDOException $e) {
509 throw new DatabaseFatalException('Failed to get a list of months', -1, $e);
510 }
511 return $res;
512 }
513
514 /**
515 * Returns a list of reporting organizations from which there is at least one report
516 *
517 * @param int $user_id User ID to retrieve the list for
518 *
519 * @return array
520 */
521 public function organizations(int $user_id): array
522 {
523 $res = [];
524 $rep_tn = $this->connector->tablePrefix('reports');
525 try {
526 $ud = $this->sqlUserRestriction($user_id, 'rp.domain_id');
527 $st = $this->connector->dbh()->query(
528 'SELECT DISTINCT org FROM ' . $rep_tn . " AS rp{$ud} ORDER BY org"
529 );
530 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
531 $res[] = $row[0];
532 }
533 $st->closeCursor();
534 } catch (\PDOException $e) {
535 throw new DatabaseFatalException('Failed to get a list of organizations', -1, $e);
536 }
537 return $res;
538 }
539
540 /**
541 * Returns the part of sql query restricting the select result by user_id
542 *
543 * @param int $user_id User ID
544 * @param string $column Column name to join
545 *
546 * @return string
547 */
548 private function sqlUserRestriction(int $user_id, string $column): string
549 {
550 if (!$user_id) {
551 return '';
552 }
553 return ' INNER JOIN ' . $this->connector->tablePrefix('userdomains') . ' AS ud ON '
554 . $column . ' = ud.domain_id WHERE user_id = ' . $user_id;
555 }
556
557 /**
558 * Returns `ORDER BY ...` part of the SQL query for report records
559 *
560 * @return string
561 */
562 private function sqlOrderRecords(): string
563 {
564 $o_set = explode(',', SettingsList::getSettingByName('report-view.sort-records-by')->value());
565 switch ($o_set[0]) {
566 case 'ip':
567 $fname = 'ip';
568 break;
569 case 'message-count':
570 default:
571 $fname = 'rcount';
572 break;
573 }
574 $dir = $o_set[1] === 'descent' ? 'DESC' : 'ASC';
575
576 return " ORDER BY {$fname} {$dir}";
577 }
578
579 /**
580 * Checks if the domain exists and adds it to the database if necessary
581 *
582 * It automatically adds the domain if there are no domains in the database
583 * or if the domain match the `allowed_domains` reqular expression in the configuration file.
584 * Otherwise, throws a SoftException.
585 *
586 * @param array $data Domain data
587 * @param object $mapper Domain mapper
588 *
589 * @throws SoftException
590 *
591 * @return void
592 */
593 private function insertDomain(array &$data, $mapper): void
594 {
595 $core = Core::instance();
596
597 if (is_null(self::$allowed_domains)) {
598 $allowed = $core->config('fetcher/allowed_domains', '');
599 if (!empty($allowed)) {
600 self::$allowed_domains = "<{$allowed}>i";
601 }
602 }
603
604 $add_f = false;
605 if ($mapper->count(0, 1) === 0) {
606 $add_f = true;
607 } else {
608 try {
609 $add_f = !empty(self::$allowed_domains) && preg_match(self::$allowed_domains, $data['fqdn']) === 1;
610 } catch (\ErrorException $e) {
611 $core->logger()->warning(
612 'The allow_domains parameter in the settings has an incorrect regular expression value.'
613 );
614 }
615 }
616
617 if (!$add_f) {
618 $this->unknownDomain($data);
619 }
620 $data['active'] = true;
621 $data['description'] = 'The domain was added automatically.';
622 $mapper->save($data);
623 }
624
625 /**
626 * Throws an exception Unknown domain
627 *
628 * @param array $data Domain data
629 *
630 * @throws SoftException
631 *
632 * @return void
633 */
634 private function unknownDomain(array &$data): void
635 {
636 $msg = 'Failed to add an incoming report: unknown domain';
637 if (!empty($data['fqdn'])) {
638 $msg .= " {$data['fqdn']}";
639 }
640 throw new SoftException($msg);
641 }
642
643 /**
644 * Binds a nullable array to an SQL query as a json string
645 *
646 * @param \PDOStatement $st DB statement object
647 * @param int $idx Bind position
648 * @param array|null $data JSON data or null
649 *
650 * @return void
651 */
652 private static function sqlBindJson($st, int $idx, $data): void
653 {
654 if (is_null($data)) {
655 $val = null;
656 $type = \PDO::PARAM_NULL;
657 } else {
658 $val = json_encode($data);
659 $type = \PDO::PARAM_STR;
660 }
661 $st->bindValue($idx, $val, $type);
662 }
663
664 /**
665 * Returns `ORDER BY ...` part of the SQL query
666 *
667 * @param array $order Key-value array with ordering options
668 * @param string $tail_field Table field for predictable sorting
669 *
670 * @return string
671 */
672 private function sqlOrderList(array &$order, string $tail_field): string
673 {
674 if (count($order) == 0) {
675 return '';
676 }
677
678 $dir = $order['direction'] === 'ascent' ? 'ASC' : 'DESC';
679 $res = " ORDER BY {$order['field']} {$dir}";
680 if (!empty($tail_field)) {
681 $res .= ", {$tail_field} {$dir}";
682 }
683 return $res;
684 }
685
686 /**
687 * The valid filter item names
688 */
689 private static $filters_available = [
690 'domain', 'month', 'before_time', 'organization', 'dkim', 'spf', 'disposition', 'status'
691 ];
692
693 /**
694 * Returns prepared filter data for sql queries
695 *
696 * @param array $filter Key-value array with filter options
697 * @param string $tname Table name prefix for the domain_id field
698 *
699 * @return array
700 */
701 private function prepareFilterData(array &$filter, string $tname = ''): array
702 {
703 $filters = [];
704 for ($i = 0; $i < 2; ++$i) {
705 $filters[] = [
706 'a_str' => [],
707 'bindings' => []
708 ];
709 }
710 if (!empty($tname)) {
711 $tname = "{$tname}.";
712 }
713 foreach (self::$filters_available as $fn) {
714 if (isset($filter[$fn])) {
715 $fv = $filter[$fn];
716 switch (gettype($fv)) {
717 case 'string':
718 if (!empty($fv)) {
719 if ($fn == 'domain') {
720 $filters[0]['a_str'][] = $tname . 'domain_id = ?';
721 $d_data = [ 'fqdn' => $fv ];
722 $this->connector->getMapper('domain')->fetch($d_data);
723 $filters[0]['bindings'][] = [ $d_data['id'], \PDO::PARAM_INT ];
724 } elseif ($fn == 'month') {
725 $ma = explode('-', $fv);
726 if (count($ma) != 2) {
727 throw new SoftException('Report list filter: Incorrect date format');
728 }
729 $year = (int)$ma[0];
730 $month = (int)$ma[1];
731 if ($year < 0 || $month < 1 || $month > 12) {
732 throw new SoftException('Report list filter: Incorrect month or year value');
733 }
734 $filters[0]['a_str'][] = 'begin_time < ? AND end_time >= ?';
735 $date1 = new DateTime("{$year}-{$month}-01");
736 $date2 = (clone $date1)->modify('first day of next month');
737 $date1->add(new \DateInterval('PT10S'));
738 $date2->sub(new \DateInterval('PT10S'));
739 $filters[0]['bindings'][] = [ $date2->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
740 $filters[0]['bindings'][] = [ $date1->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
741 } elseif ($fn == 'organization') {
742 $filters[0]['a_str'][] = 'org = ?';
743 $filters[0]['bindings'][] = [ $fv, \PDO::PARAM_STR ];
744 } elseif ($fn == 'dkim') {
745 if (!in_array($fv, Common::$align_res, true)) {
746 throw new SoftException('Report list filter: Incorrect DKIM value');
747 }
748 if ($fv === 'pass') {
749 $filters[1]['a_str'][] = 'dkim_align_fail = 0 AND dkim_align_unknown = 0';
750 } else {
751 $filters[1]['a_str'][] = "dkim_align_{$fv} > 0";
752 }
753 } elseif ($fn == 'spf') {
754 if (!in_array($fv, Common::$align_res, true)) {
755 throw new SoftException('Report list filter: Incorrect SPF value');
756 }
757 if ($fv === 'pass') {
758 $filters[1]['a_str'][] = 'spf_align_fail = 0 AND spf_align_unknown = 0';
759 } else {
760 $filters[1]['a_str'][] = "spf_align_{$fv} > 0";
761 }
762 } elseif ($fn == 'disposition') {
763 switch ($fv) {
764 case 'none':
765 $str = 'rejected = 0 AND quarantined = 0';
766 break;
767 case 'quarantine':
768 $str = 'quarantined > 0';
769 break;
770 case 'reject':
771 $str = 'rejected > 0';
772 break;
773 default:
774 throw new SoftException('Report list filter: Incorrect value of disposition');
775 }
776 $filters[1]['a_str'][] = $str;
777 } elseif ($fn == 'status') {
778 if ($fv === 'read') {
779 $val = true;
780 } elseif ($fv === 'unread') {
781 $val = false;
782 } else {
783 throw new SoftException('Report list filter: Incorrect status value');
784 }
785 $filters[0]['a_str'][] = 'seen = ?';
786 $filters[0]['bindings'][] = [ $val, \PDO::PARAM_BOOL ];
787 }
788 }
789 break;
790 case 'object':
791 if ($fn == 'domain') {
792 $filters[0]['a_str'][] = $tname . 'domain_id = ?';
793 $filters[0]['bindings'][] = [ $fv->id(), \PDO::PARAM_INT ];
794 } elseif ($fn == 'before_time') {
795 $filters[0]['a_str'][] = 'begin_time < ?';
796 $filters[0]['bindings'][] = [ $fv->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
797 }
798 break;
799 case 'integer':
800 if ($fn == 'domain') {
801 $filters[0]['a_str'][] = $tname . 'domain_id = ?';
802 $filters[0]['bindings'][] = [ $fv, \PDO::PARAM_INT ];
803 }
804 break;
805 }
806 }
807 }
808 $f_data = [];
809 for ($i = 0; $i < count($filters); ++$i) {
810 $filter = &$filters[$i];
811 if (count($filter['a_str']) > 0) {
812 $f_data[$i] = [
813 'str' => implode(' AND ', $filter['a_str']),
814 'bindings' => $filter['bindings']
815 ];
816 }
817 unset($filter);
818 }
819 return $f_data;
820 }
821
822 /**
823 * Returns the SQL condition for a filter by filter id
824 *
825 * @param array $f_data Array with prepared filter data
826 * @param string $prefix Prefix, which will be added to the beginning of the condition string,
827 * but only in the case when the condition string is not empty.
828 * @param int $f_idx Index of the filter
829 *
830 * @return string the condition string
831 */
832 private function sqlConditionList(array &$f_data, string $prefix, int $f_idx): string
833 {
834 return isset($f_data[$f_idx]) ? ($prefix . $f_data[$f_idx]['str']) : '';
835 }
836
837 /**
838 * Returns `LIMIT ...` part of the SQL query
839 *
840 * @param array $limit Key-value array with two keys: `offset` and `count`
841 *
842 * @return string
843 */
844 private function sqlLimit(array &$limit): string
845 {
846 $res = '';
847 if ($limit['count'] > 0) {
848 $res = ' LIMIT ?';
849 if ($limit['offset'] > 0) {
850 $res .= ', ?';
851 }
852 }
853 return $res;
854 }
855
856 /**
857 * Binds the values of the filter and the limit to SQL query
858 *
859 * @param \PDOStatement $st Prepared SQL statement to bind to
860 * @param array $f_data Array with prepared filter data
861 * @param array $limit Key-value array with two keys: `offset` and `count`
862 *
863 * @return void
864 */
865 private function sqlBindValues($st, array &$f_data, array &$limit): void
866 {
867 $pos = 0;
868 if (isset($f_data[0])) {
869 $this->sqlBindFilterValues($st, $f_data, 0, $pos);
870 }
871 if (isset($f_data[1])) {
872 $this->sqlBindFilterValues($st, $f_data, 1, $pos);
873 }
874 if ($limit['count'] > 0) {
875 if ($limit['offset'] > 0) {
876 $st->bindValue(++$pos, $limit['offset'], \PDO::PARAM_INT);
877 }
878 $st->bindValue(++$pos, $limit['count'], \PDO::PARAM_INT);
879 }
880 }
881
882 /**
883 * Binds the values of the specified filter item to SQL query
884 *
885 * @param \PDOStatement $st Prepared SQL statement to bind to
886 * @param array $f_data Array with prepared filter data
887 * @param int $filter_idx Index of the filter to bind to
888 * @param int $bind_pos Start bind position (pointer). It will be increased with each binding.
889 *
890 * @return void
891 */
892 private function sqlBindFilterValues($st, array &$f_data, int $filter_idx, int &$bind_pos): void
893 {
894 foreach ($f_data[$filter_idx]['bindings'] as &$bv) {
895 $st->bindValue(++$bind_pos, $bv[0], $bv[1]);
896 }
897 }
898 }