Debian Codegraph @

classes/Database/Common/CommonReportLogMapper.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 CommonReportLogMapper 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\ReportLogMapperInterface;
36 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
37 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
38
39 /**
40 * Universal implementation of ReportLogMapper class
41 */
42 class CommonReportLogMapper implements ReportLogMapperInterface
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 * Fetches data of report log item from the database by id
59 *
60 * @param array $data Log data
61 *
62 * @return void
63 */
64 public function fetch(array &$data): void
65 {
66 try {
67 $st = $this->connector->dbh()->prepare(
68 'SELECT domain, external_id, event_time, filename, source, success, message FROM '
69 . $this->connector->tablePrefix('reportlog') . ' WHERE id = ?'
70 );
71 $st->bindValue(1, $data['id'], \PDO::PARAM_INT);
72 $st->execute();
73 if (!($row = $st->fetch(\PDO::FETCH_NUM))) {
74 throw new DatabaseNotFoundException();
75 }
76 $data['domain'] = $row[0];
77 $data['report_id'] = $row[1];
78 $data['event_time'] = new DateTime($row[2]);
79 $data['filename'] = $row[3];
80 $data['source'] = intval($row[4]);
81 $data['success'] = boolval($row[5]);
82 $data['message'] = $row[6];
83 $st->closeCursor();
84 } catch (\PDOException $e) {
85 throw new DatabaseFatalException('Failed to get the log item', -1, $e);
86 }
87 }
88
89 /**
90 * Saves data of report log item to the database
91 *
92 * @return void
93 */
94 public function save(array &$data): void
95 {
96 $db = $this->connector->dbh();
97 try {
98 $id = $data['id'];
99 if (is_null($id)) {
100 $st = $db->prepare(
101 'INSERT INTO ' . $this->connector->tablePrefix('reportlog')
102 . ' (domain, external_id, event_time, filename, source, success, message)'
103 . ' VALUES (?, ?, ?, ?, ?, ?, ?)'
104 );
105 } else {
106 $st = $db->prepare(
107 'UPDATE ' . $this->connector->tablePrefix('reportlog')
108 . ' SET domain = ?, external_id = ?, event_time = ?, filename = ?,'
109 . ' source = ?, success = ?, message = ? WHERE id = ?'
110 );
111 $st->bindValue(8, $id, \PDO::PARAM_INT);
112 }
113 $ts = $data['event_time'] ?? (new DateTime());
114 $st->bindValue(1, $data['domain'], \PDO::PARAM_STR);
115 $st->bindValue(2, $data['report_id'], \PDO::PARAM_STR);
116 $st->bindValue(3, $ts->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
117 $st->bindValue(4, $data['filename'], \PDO::PARAM_STR);
118 $st->bindValue(5, $data['source'], \PDO::PARAM_INT);
119 $st->bindValue(6, $data['success'], \PDO::PARAM_BOOL);
120 $st->bindValue(7, $data['message'], \PDO::PARAM_STR);
121 $st->execute();
122 if (is_null($id)) {
123 $data['id'] = intval($db->lastInsertId());
124 }
125 $st->closeCursor();
126 $data['event_time'] = $ts;
127 } catch (\PDOException $e) {
128 throw new DatabaseFatalException('Failed to save a report log item');
129 }
130 }
131
132 /**
133 * Returns a list of report log items with given criteria
134 *
135 * @param array $filter Key-value array:
136 * 'from_time' => DateTime
137 * 'till_time' => DateTime
138 * @param array $order Key-value array with order options:
139 * 'direction' => string, 'ascent' or 'descent'
140 * @param array $limit Key-value array:
141 * 'offset' => int
142 * 'count' => int
143 *
144 * @return array
145 */
146 public function list(array &$filter, array &$order, array &$limit): array
147 {
148 $list = [];
149 try {
150 $st = $this->connector->dbh()->prepare(
151 'SELECT id, domain, event_time, source, success, message FROM '
152 . $this->connector->tablePrefix('reportlog')
153 . $this->sqlCondition($filter)
154 . $this->sqlOrder($order)
155 . $this->sqlLimit($limit)
156 );
157 $this->sqlBindValues($st, $filter, $limit);
158 $st->execute();
159 while ($row = $st->fetch(\PDO::FETCH_NUM)) {
160 $list[] = [
161 'id' => intval($row[0]),
162 'domain' => $row[1],
163 'event_time' => new DateTime($row[2]),
164 'source' => intval($row[3]),
165 'success' => boolval($row[4]),
166 'message' => $row[5]
167 ];
168 }
169 $st->closeCursor();
170 } catch (\PDOException $e) {
171 throw new DatabaseFatalException('Failed to get the logs', -1, $e);
172 }
173 return $list;
174 }
175
176 /**
177 * Returns the number of report log items matching the specified filter and limits
178 *
179 * @param array $filter Key-value array with filtering parameters
180 * @param array $limit Key-value array with limits
181 *
182 * @return int
183 */
184 public function count(array &$filter, array &$limit): int
185 {
186 $cnt = 0;
187 try {
188 $st = $this->connector->dbh()->prepare(
189 'SELECT COUNT(*) FROM ' . $this->connector->tablePrefix('reportlog')
190 . $this->sqlCondition($filter)
191 . $this->sqlLimit($limit)
192 );
193 $this->sqlBindValues($st, $filter, $limit);
194 $st->execute();
195 $cnt = intval($st->fetch(\PDO::FETCH_NUM)[0]);
196 $st->closeCursor();
197 } catch (\PDOException $e) {
198 throw new DatabaseFatalException('Failed to get the log data', -1, $e);
199 }
200 return $cnt;
201 }
202
203 /**
204 * Deletes report log items from the database
205 *
206 * @param array $filter Key-value array with filtering parameters
207 * @param array $order Key-value array with order options:
208 * 'direction' => string, 'ascent' or 'descent'
209 * @param array $limit Key-value array with limits
210 *
211 * @return void
212 */
213 public function delete(array &$filter, array &$order, array &$limit): void
214 {
215 try {
216 $st = $this->connector->dbh()->prepare(
217 'DELETE FROM ' . $this->connector->tablePrefix('reportlog')
218 . $this->sqlCondition($filter)
219 . $this->sqlOrder($order)
220 . $this->sqlLimit($limit)
221 );
222 $this->sqlBindValues($st, $filter, $limit);
223 $st->execute();
224 $st->closeCursor();
225 } catch (\PDOException $e) {
226 throw new DatabaseFatalException('Failed to remove the log data', -1, $e);
227 }
228 }
229
230 /**
231 * Returns a string with an SQL condition 'WHERE ...'
232 *
233 * @param array $filter Key-value with filtering paremeters
234 *
235 * @return string
236 */
237 private function sqlCondition(array &$filter): string
238 {
239 $res = [];
240 if (isset($filter['from_time'])) {
241 $res[] = 'event_time >= ?';
242 }
243 if (isset($filter['till_time'])) {
244 $res[] = 'event_time < ?';
245 }
246 if (isset($filter['success'])) {
247 $res[] = 'success = ?';
248 }
249 if (isset($filter['source'])) {
250 $res[] = 'source = ?';
251 }
252 return count($res) > 0 ? (' WHERE ' . implode(' AND ', $res)) : '';
253 }
254
255 /**
256 * Returns 'ORDER BY ...' part of the SQL query
257 *
258 * @param array $order Key-value array with ordering options
259 *
260 * @return string
261 */
262 private function sqlOrder(array &$order): string
263 {
264 return ' ORDER BY event_time ' . ($order['direction'] === 'descent' ? 'DESC' : 'ASC');
265 }
266
267 /**
268 * Returns 'LIMIT ...' part of the SQL string
269 *
270 * @param array $limit Key-value array with keys 'offset' and 'count'
271 *
272 * @return string
273 */
274 private function sqlLimit(array &$limit): string
275 {
276 $res = '';
277 if ($limit['count'] > 0) {
278 $res = ' LIMIT ?';
279 if ($limit['offset'] > 0) {
280 $res .= ', ?';
281 }
282 }
283 return $res;
284 }
285
286 /**
287 * Binds the values of the filter and the limit to SQL query
288 *
289 * @param \PDOStatement $st Prepared SOL statement to bind to
290 * @param array $filter Key-value array with filter data
291 * @param array $limit Key-value array with limit data
292 *
293 * @return void
294 */
295 private function sqlBindValues($st, array &$filter, array &$limit): void
296 {
297 $pos = 0;
298 if (isset($filter['from_time'])) {
299 $st->bindValue(++$pos, $filter['from_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
300 }
301 if (isset($filter['till_time'])) {
302 $st->bindValue(++$pos, $filter['till_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
303 }
304 if (isset($filter['success'])) {
305 $st->bindValue(++$pos, $filter['success'], \PDO::PARAM_BOOL);
306 }
307 if (isset($filter['source'])) {
308 $st->bindValue(++$pos, $filter['source'], \PDO::PARAM_INT);
309 }
310 if ($limit['count'] > 0) {
311 if ($limit['offset'] > 0) {
312 $st->bindValue(++$pos, $limit['offset'], \PDO::PARAM_INT);
313 }
314 $st->bindValue(++$pos, $limit['count'], \PDO::PARAM_INT);
315 }
316 }
317 }