Debian Codegraph @

classes/Database/Common/CommonStatisticsMapper.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 CommonStatisticsMapper 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\Common;
35 use Liuch\DmarcSrg\Exception\SoftException;
36 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
37 use Liuch\DmarcSrg\Database\StatisticsMapperInterface;
38
39 /**
40 * Universal implementation of StatisticsMapper class
41 */
42 class CommonStatisticsMapper implements StatisticsMapperInterface
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 * Returns summary information for the specified domain and date range
59 *
60 * @param \Liuch\DmarcSrg\Domains\Domain|null $domain Domain for which the information is needed.
61 * Null is for all domains.
62 * @param array $range Array with two dates
63 * @param array $filter Array with filtering parameters
64 * @param int $user_id User ID to get statistics for
65 *
66 * @return array Array with Summary information:
67 * 'emails' => [
68 * 'total' => total email processed (int)
69 * 'dkim_spf_aligned' => Both DKIM and SPF aligned (int)
70 * 'dkim_aligned' => Only DKIM aligned (int)
71 * 'spf_aligned' => Only SPF aligned (int)
72 * 'quarantined' => Quarantined (int)
73 * 'rejected' => Rejected (int)
74 * ];
75 */
76 public function summary($domain, array &$range, array &$filter, int $user_id): array
77 {
78 $is_domain = $domain ? true : false;
79 $db = $this->connector->dbh();
80 try {
81 $users = $this->sqlUserRestriction($user_id);
82 $f_data = $this->prepareFilterData($domain, $range, $user_id, $filter);
83 $st = $db->prepare(
84 'SELECT SUM(rcount), SUM(IF(dkim_align = 2 AND spf_align = 2, rcount, 0)),'
85 . ' SUM(IF(dkim_align = 2 AND spf_align <> 2, rcount, 0)),'
86 . ' SUM(IF(dkim_align <> 2 AND spf_align = 2, rcount, 0)),'
87 . ' SUM(IF(disposition = 0, rcount, 0)),'
88 . ' SUM(IF(disposition = 1, rcount, 0))'
89 . ' FROM ' . $this->connector->tablePrefix('rptrecords') . ' AS rr'
90 . ' INNER JOIN ' . $this->connector->tablePrefix('reports')
91 . ' AS rp ON rr.report_id = rp.id' . $users
92 . $this->sqlCondition($f_data, ' WHERE ', 0) . $this->sqlCondition($f_data, ' AND ', 1)
93 );
94 $this->sqlBindValues($st, $f_data, [ 0, 1 ]);
95 $st->execute();
96 $row = $st->fetch(\PDO::FETCH_NUM);
97 $ems = [
98 'total' => intval($row[0]),
99 'dkim_spf_aligned' => intval($row[1]),
100 'dkim_aligned' => intval($row[2]),
101 'spf_aligned' => intval($row[3]),
102 'rejected' => intval($row[4]),
103 'quarantined' => intval($row[5])
104 ];
105 $st->closeCursor();
106
107 if (!isset($filter['dkim']) && !isset($filter['spf']) && !isset($filter['disposition'])) {
108 $st = $db->prepare(
109 'SELECT COUNT(*) FROM (SELECT org FROM ' . $this->connector->tablePrefix('reports') . ' AS rp'
110 . $users . $this->sqlCondition($f_data, ' WHERE ', 0) . ' GROUP BY org) AS orgs'
111 );
112 } else {
113 $st = $db->prepare(
114 'SELECT COUNT(*) FROM (SELECT org FROM ('
115 . 'SELECT org, MIN(dkim_align) as dkim_align, MIN(spf_align) AS spf_align,'
116 . ' MIN(disposition) AS disposition FROM '
117 . $this->connector->tablePrefix('reports') . ' AS rp'
118 . ' INNER JOIN ' . $this->connector->tablePrefix('rptrecords') . ' AS rr'
119 . ' ON rp.id = rr.report_id' . $users . $this->sqlCondition($f_data, ' WHERE ', 0)
120 . ' GROUP BY rr.report_id'
121 . ') AS sr' . $this->sqlCondition($f_data, ' WHERE ', 1) . ' GROUP BY org) AS orgs'
122 );
123 }
124
125 $this->sqlBindValues($st, $f_data, [ 0, 1 ]);
126 $st->execute();
127 $row = $st->fetch(\PDO::FETCH_NUM);
128 $st->closeCursor();
129 } catch (\PDOException $e) {
130 throw new DatabaseFatalException('Failed to get summary information', -1, $e);
131 }
132
133 return [
134 'emails' => $ems,
135 'organizations' => intval($row[0])
136 ];
137 }
138
139 /**
140 * Returns a list of ip-addresses from which the e-mail messages were received, with some statistics for each one
141 *
142 * @param \Liuch\DmarcSrg\Domains\Domain|null $domain Domain for which the information is needed.
143 * Null is for all domains.
144 * @param array $range Array with two dates
145 * @param array $filter Array with filtering parameters
146 * @param int $user_id User ID to get statistics for
147 *
148 * @return array A list of ip-addresses with fields `ip`, `emails`, `dkim_aligned`, `spf_aligned`
149 */
150 public function ips($domain, array &$range, array &$filter, int $user_id): array
151 {
152 try {
153 $f_data = $this->prepareFilterData($domain, $range, $user_id, $filter);
154 $st = $this->connector->dbh()->prepare(
155 'SELECT ip, SUM(rcount) AS rcount,'
156 . ' SUM(IF(dkim_align = 2 AND spf_align = 2, rcount, 0)) AS dkim_spf_aligned,'
157 . ' SUM(IF(dkim_align = 2 AND spf_align <> 2, rcount, 0)) AS dkim_aligned,'
158 . ' SUM(IF(dkim_align <> 2 AND spf_align = 2, rcount, 0)) AS spf_aligned,'
159 . ' SUM(IF(disposition = 0, rcount, 0)),'
160 . ' SUM(IF(disposition = 1, rcount, 0))'
161 . ' FROM ' . $this->connector->tablePrefix('rptrecords') . ' AS rr'
162 . ' INNER JOIN ' . $this->connector->tablePrefix('reports')
163 . ' AS rp ON rr.report_id = rp.id' . $this->sqlUserRestriction($user_id)
164 . $this->sqlCondition($f_data, ' WHERE ', 0) . $this->sqlCondition($f_data, ' AND ', 1)
165 . ' GROUP BY ip ORDER BY rcount DESC'
166 );
167 $this->sqlBindValues($st, $f_data, [ 0, 1 ]);
168 $st->execute();
169 $res = [];
170 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
171 $res[] = [
172 'ip' => inet_ntop($row[0]),
173 'emails' => intval($row[1]),
174 'dkim_spf_aligned' => intval($row[2]),
175 'dkim_aligned' => intval($row[3]),
176 'spf_aligned' => intval($row[4]),
177 'rejected' => intval($row[5]),
178 'quarantined' => intval($row[6])
179 ];
180 }
181 $st->closeCursor();
182 } catch (\PDOException $e) {
183 throw new DatabaseFatalException('Failed to get IPs summary information', -1, $e);
184 }
185 return $res;
186 }
187
188 /**
189 * Returns a list of organizations that sent the reports with some statistics for each one
190 *
191 * @param \Liuch\DmarcSrg\Domains\Domain|null $domain Domain for which the information is needed.
192 * Null is for all domains.
193 * @param array $range Array with two dates
194 * @param array $filter Array with filtering parameters
195 * @param int $user_id User ID to get statistics for
196 *
197 * @return array List of organizations with fields `name`, `reports`, `emails`
198 */
199 public function organizations($domain, array &$range, array &$filter, int $user_id): array
200 {
201 try {
202 $f_data = $this->prepareFilterData($domain, $range, $user_id, $filter);
203 $st = $this->connector->dbh()->prepare(
204 'SELECT org, COUNT(*), SUM(rr.rcount) AS rcount,'
205 . ' SUM(rr.dkim_spf_aligned), SUM(rr.dkim_aligned), SUM(rr.spf_aligned),'
206 . ' SUM(rr.rejected), SUM(rr.quarantined) FROM '
207 . $this->connector->tablePrefix('reports') . ' AS rp'
208 . ' INNER JOIN (SELECT report_id, SUM(rcount) AS rcount,'
209 . ' SUM(IF(dkim_align = 2 AND spf_align = 2, rcount, 0)) AS dkim_spf_aligned,'
210 . ' SUM(IF(dkim_align = 2 AND spf_align <> 2, rcount, 0)) AS dkim_aligned,'
211 . ' SUM(IF(dkim_align <> 2 AND spf_align = 2, rcount, 0)) AS spf_aligned,'
212 . ' SUM(IF(disposition = 0, rcount, 0)) AS rejected,'
213 . ' SUM(IF(disposition = 1, rcount, 0)) AS quarantined FROM '
214 . $this->connector->tablePrefix('rptrecords')
215 . $this->sqlCondition($f_data, ' WHERE ', 1)
216 . ' GROUP BY report_id) AS rr ON rp.id = rr.report_id'
217 . $this->sqlUserRestriction($user_id) . $this->sqlCondition($f_data, ' WHERE ', 0)
218 . ' GROUP BY org ORDER BY rcount DESC'
219 );
220 $this->sqlBindValues($st, $f_data, [ 1, 0 ]);
221 $st->execute();
222 $res = [];
223 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
224 $res[] = [
225 'name' => $row[0],
226 'reports' => intval($row[1]),
227 'emails' => intval($row[2]),
228 'dkim_spf_aligned' => intval($row[3]),
229 'dkim_aligned' => intval($row[4]),
230 'spf_aligned' => intval($row[5]),
231 'rejected' => intval($row[6]),
232 'quarantined' => intval($row[7])
233 ];
234 }
235 $st->closeCursor();
236 } catch (\PDOException $e) {
237 throw new DatabaseFatalException('Failed to get summary information of reporting organizations', -1, $e);
238 }
239 return $res;
240 }
241
242 /**
243 * Valid filter item names
244 */
245 private static $filters_available = [
246 'organization', 'dkim', 'spf', 'disposition', 'status'
247 ];
248
249 /**
250 * Returns prepared filter data for SQL queries
251 *
252 * @param \Liuch\DmarcSrg\Domains\Domain|null $domain Domain for the condition
253 * @param array $range Date range
254 * @param int $user_id User ID
255 * @param array $filter Key-value array with filtering parameters
256 *
257 * @return array
258 */
259 private function prepareFilterData($domain, array &$range, int $user_id, array &$filter): array
260 {
261 $sql_cond1 = [];
262 $sql_cond2 = [];
263 $bindings1 = [];
264 $bindings2 = [];
265 if ($user_id) {
266 $sql_cond1[] = 'user_id = ?';
267 $bindings1[] = [ $user_id, \PDO::PARAM_INT ];
268 }
269 if ($domain) {
270 $sql_cond1[] = 'rp.domain_id = ?';
271 $bindings1[] = [ $domain->id(), \PDO::PARAM_INT ];
272 }
273 $sql_cond1[] = 'begin_time < ? AND end_time >= ?';
274 $bindings1[] = [
275 (clone $range['date2'])->sub(new \DateInterval('PT10S'))->format('Y-m-d H:i:s'), \PDO::PARAM_STR
276 ];
277 $bindings1[] = [
278 (clone $range['date1'])->add(new \DateInterval('PT10S'))->format('Y-m-d H:i:s'), \PDO::PARAM_STR
279 ];
280 foreach (self::$filters_available as $fname) {
281 if (empty($filter[$fname])) {
282 continue;
283 }
284 $fvalue = $filter[$fname];
285 switch ($fname) {
286 case 'organization':
287 $sql_cond1[] = 'org = ?';
288 $bindings1[] = [ $fvalue, \PDO::PARAM_STR ];
289 break;
290 case 'dkim':
291 if ($fvalue === Common::$align_res[0]) {
292 $val = 0;
293 } else {
294 $val = count(Common::$align_res) - 1;
295 if ($fvalue !== Common::$align_res[$val]) {
296 throw new SoftException('Filter: Incorrect DKIM value');
297 }
298 }
299 $sql_cond2[] = 'dkim_align = ?';
300 $bindings2[] = [ $val, \PDO::PARAM_INT ];
301 break;
302 case 'spf':
303 if ($fvalue === Common::$align_res[0]) {
304 $val = 0;
305 } else {
306 $val = count(Common::$align_res) - 1;
307 if ($fvalue !== Common::$align_res[$val]) {
308 throw new SoftException('Filter: Incorrect SPF value');
309 }
310 }
311 $sql_cond2[] = 'spf_align = ?';
312 $bindings2[] = [ $val, \PDO::PARAM_INT ];
313 break;
314 case 'disposition':
315 $val = array_search($fvalue, Common::$disposition);
316 if ($val === false) {
317 throw new SoftException('Filter: Incorrect value of disposition');
318 }
319 $sql_cond2[] = 'disposition = ?';
320 $bindings2[] = [ $val, \PDO::PARAM_INT ];
321 break;
322 case 'status':
323 if ($fvalue === 'read') {
324 $val = true;
325 } elseif ($fvalue === 'unread') {
326 $val = false;
327 } else {
328 throw new SoftException('Filter: Incorrect status value');
329 }
330 $sql_cond1[] = 'seen = ?';
331 $bindings1[] = [ $val, \PDO::PARAM_BOOL ];
332 break;
333 }
334 }
335 return [
336 'sql_cond' => [ $sql_cond1, $sql_cond2 ],
337 'bindings' => [ $bindings1, $bindings2 ]
338 ];
339 }
340
341 /**
342 * Returns the part of sql query restricting the select result by user_id
343 *
344 * @param int $user_id User ID
345 *
346 * @return string
347 */
348 private function sqlUserRestriction(int $user_id): string
349 {
350 if (!$user_id) {
351 return '';
352 }
353 return ' INNER JOIN ' . $this->connector->tablePrefix('userdomains')
354 . ' AS ud ON rp.domain_id = ud.domain_id';
355 }
356
357 /**
358 * Returns a condition string for WHERE statement
359 *
360 * @param array $f_data Array with prepared filter data
361 * @param string $prefix Prefix, which will be added to the beginning of the condition string,
362 * but only in the case when the condition string is not empty.
363 * @param int $num Part number
364 *
365 * @return string Condition string
366 */
367 private function sqlCondition(array &$f_data, string $prefix, int $num): string
368 {
369 if (count($f_data['sql_cond'][$num]) > 0) {
370 return $prefix . implode(' AND ', $f_data['sql_cond'][$num]);
371 }
372 return '';
373 }
374
375 /**
376 * Binds values for SQL queries
377 *
378 * @param \PDOStatement $st PDO Statement to bind to
379 * @param array $f_data Array with prepared filter data
380 * @param array $order Parameter binding order
381 *
382 * @return void
383 */
384 private function sqlBindValues(object $st, array &$f_data, array $order): void
385 {
386 $pnum = 0;
387 foreach ($order as $idx) {
388 foreach ($f_data['bindings'][$idx] as &$it) {
389 $st->bindValue(++$pnum, $it[0], $it[1]);
390 }
391 unset($it);
392 }
393 }
394 }