Debian Codegraph @

classes/Report/ReportData.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) 2020-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 namespace Liuch\DmarcSrg\Report;
24
25 use Liuch\DmarcSrg\DateTime;
26 use Liuch\DmarcSrg\Exception\RuntimeException;
27
28 class ReportData
29 {
30 private $rep_data = null;
31 private $tag_id = null;
32 private $skip_depth = 0;
33 private $strict_mode = false;
34
35 private function __construct(bool $strict = false)
36 {
37 $this->strict_mode = $strict;
38 }
39
40 public static function fromArray(array $data, bool $strict = false)
41 {
42 $new_data = [];
43 self::copyFields(self::$fields, $data, $new_data);
44 self::copySubdata(self::$dfields, $data, $new_data, 'date');
45 self::copySubdata(self::$pfields, $data, $new_data, 'policy');
46 if (isset($data['records']) && gettype($data['records']) === 'array') {
47 $new_data['records'] = [];
48 foreach ($data['records'] as &$rec) {
49 $new_rec = [];
50 self::copyFields(self::$rfields, $rec, $new_rec);
51 $new_data['records'][] = $new_rec;
52 }
53 unset($rec);
54 }
55 $rdata = new self($strict);
56 $rdata->rep_data = $new_data;
57 return $rdata;
58 }
59
60 public static function fromXmlFile($fd, $strict = false)
61 {
62 $rdata = new self($strict);
63 $rdata->tag_id = '<root>';
64 $rdata->rep_data = [ 'date' => [], 'policy' => [], 'records' => [] ];
65
66 $parser = xml_parser_create();
67 xml_set_element_handler($parser, [ $rdata, 'xmlStartTag' ], [ $rdata, 'xmlEndTag' ]);
68 xml_set_character_data_handler($parser, [ $rdata, 'xmlTagData' ]);
69 xml_set_external_entity_ref_handler($parser, function () {
70 throw new RuntimeException('The XML document has an external entity!');
71 });
72 try {
73 while ($file_data = fread($fd, 4096)) {
74 if (!xml_parse($parser, $file_data, feof($fd))) {
75 $pc = xml_get_error_code($parser);
76 $error_str = 'XML error!' . PHP_EOL;
77 $error_str .= 'Parser code: ' . $pc . PHP_EOL;
78 $error_str .= 'Parser message: ' . xml_error_string($pc) . PHP_EOL;
79 $error_str .= 'Line: ' . xml_get_current_line_number($parser);
80 $error_str .= '; Column: ' . xml_get_current_column_number($parser) . PHP_EOL;
81 throw new RuntimeException('Incorrect XML report file', -1, new RuntimeException($error_str));
82 }
83 }
84 } finally {
85 unset($parser);
86 }
87 return $rdata;
88 }
89
90 public function toArray(): array
91 {
92 return $this->rep_data;
93 }
94
95 public function &__get(string $name)
96 {
97 if (!array_key_exists($name, self::$fields)) {
98 throw new RuntimeException('Getting an unknown report property: ' . $name);
99 }
100 if (!array_key_exists($name, $this->rep_data)) {
101 throw new RuntimeException('Getting an undefined report property: ' . $name);
102 }
103 return $this->rep_data[$name];
104 }
105
106 public function __set(string $name, $value): void
107 {
108 if (!array_key_exists($name, self::$fields)) {
109 throw new RuntimeException('Accessing an unknown report property: ' . $name);
110 }
111 $this->rep_data[$name] = $value;
112 }
113
114 public function __isset(string $name): bool
115 {
116 return isset($this->rep_data);
117 }
118
119 /**
120 * Checks report data for correctness and completeness
121 *
122 * @return bool
123 */
124 public function isValid(): bool
125 {
126 if (!self::checkRow($this->rep_data, self::$fields) || count($this->rep_data['records']) === 0) {
127 return false;
128 }
129 if (!self::checkRow($this->rep_data['date'], self::$dfields)) {
130 return false;
131 }
132 if (!self::checkRow($this->rep_data['policy'], self::$pfields)) {
133 return false;
134 }
135 foreach ($this->rep_data['records'] as &$rec) {
136 if (gettype($rec) !== 'array' || !self::checkRow($rec, self::$rfields)) {
137 return false;
138 }
139 }
140 return true;
141 }
142
143 /**
144 * Checks one row of report data
145 *
146 * @param array $row Data row
147 * @param array $def Row definition
148 *
149 * @return bool
150 */
151 private static function checkRow(array &$row, array &$def): bool
152 {
153 foreach ($def as $key => &$dd) {
154 if (isset($row[$key])) {
155 if (gettype($row[$key]) !== $dd['type']) {
156 return false;
157 }
158 } elseif ($dd['required']) {
159 return false;
160 }
161 }
162 return true;
163 }
164
165 private function xmlStartTag($parser, string $name, array $attributes): void
166 {
167 if ($this->skip_depth || !$this->xmlEnterTag($name)) {
168 ++$this->skip_depth;
169 return;
170 }
171
172 switch ($this->tag_id) {
173 case 'rec':
174 $this->rep_data['records'][] = [];
175 break;
176 case 'error_string':
177 if (!isset($this->rep_data['error_string'])) {
178 $this->rep_data['error_string'] = [];
179 }
180 break;
181 case 'reason':
182 case 'dkim_auth':
183 case 'spf_auth':
184 $idx = array_key_last($this->rep_data['records']);
185 if (!isset($this->rep_data['records'][$idx][$this->tag_id])) {
186 $this->rep_data['records'][$idx][$this->tag_id] = [];
187 }
188 $this->report_tags[$this->tag_id]['tmp_data'] = [];
189 break;
190 }
191 }
192
193 private function xmlEndTag($parser, string $name): void
194 {
195 if ($this->skip_depth) {
196 --$this->skip_depth;
197 return;
198 }
199
200 switch ($this->tag_id) {
201 case 'reason':
202 case 'dkim_auth':
203 case 'spf_auth':
204 $idx = array_key_last($this->rep_data['records']);
205 $this->rep_data['records'][$idx][$this->tag_id][] = $this->report_tags[$this->tag_id]['tmp_data'];
206 unset($this->report_tags[$this->tag_id]['tmp_data']);
207 break;
208 case 'feedback':
209 // Set the default value if it's necessary and there is no data
210 foreach ($this->report_tags as $tag_id => &$tag_data) {
211 if (array_key_exists('default', $tag_data)) { // not isset() because of null values
212 $def = $tag_data['default'];
213 $key = $tag_data['key'] ?? $tag_id;
214 $ptr = null;
215 switch ($tag_data['type'] ?? '') {
216 case 'M': // metadata
217 $ptr = &$this->rep_data;
218 break;
219 case 'D': // data range
220 $ptr = &$this->rep_data['date'];
221 break;
222 case 'P': // policy
223 $ptr = &$this->rep_data['policy'];
224 break;
225 default: // record
226 foreach ($this->rep_data['records'] as &$rec_val) {
227 if (!isset($rec_val[$key])) {
228 $rec_val[$key] = $def;
229 }
230 }
231 unset($rec_val);
232 }
233 if ($ptr) {
234 if (!isset($ptr[$key])) {
235 $ptr[$key] = $def;
236 }
237 unset($ptr);
238 }
239 }
240 }
241 unset($tag_data);
242 $b_ts = intval($this->rep_data['date']['begin'] ?? 0);
243 $e_ts = intval($this->rep_data['date']['end'] ?? 0);
244 $this->rep_data['date']['begin'] = new DateTime('@' . ($b_ts < 0 ? 0 : $b_ts));
245 $this->rep_data['date']['end'] = new DateTime('@' . ($e_ts < 0 ? 0 : $e_ts));
246 foreach ($this->rep_data['records'] as &$rec_data) {
247 $rec_data['count'] = intval($rec_data['rcount']);
248 }
249 unset($rec_data);
250 break;
251 }
252 $this->xmlLeaveTag();
253 }
254
255 private function xmlTagData($parser, $data): void
256 {
257 if ($this->skip_depth) {
258 return;
259 }
260
261 switch ($this->tag_id) {
262 case 'error_string':
263 if ($this->tag_id === 'error_string') {
264 $this->rep_data['error_string'][] = $data;
265 }
266 break;
267 case 'reason_type':
268 $this->report_tags['reason']['tmp_data']['type'] = $data;
269 break;
270 case 'reason_comment':
271 $this->report_tags['reason']['tmp_data']['comment'] = $data;
272 break;
273 case 'dkim_domain':
274 $this->report_tags['dkim_auth']['tmp_data']['domain'] = $data;
275 break;
276 case 'dkim_selector':
277 $this->report_tags['dkim_auth']['tmp_data']['selector'] = $data;
278 break;
279 case 'dkim_result':
280 $this->report_tags['dkim_auth']['tmp_data']['result'] = $data;
281 break;
282 case 'dkim_human_result':
283 $this->report_tags['dkim_auth']['tmp_data']['human_result'] = $data;
284 break;
285 case 'spf_domain':
286 $this->report_tags['spf_auth']['tmp_data']['domain'] = $data;
287 break;
288 case 'spf_scope':
289 $this->report_tags['spf_auth']['tmp_data']['scope'] = $data;
290 break;
291 case 'spf_result':
292 $this->report_tags['spf_auth']['tmp_data']['result'] = $data;
293 break;
294 default:
295 $t_id = $this->tag_id;
296 if (!isset($this->report_tags[$t_id]['children'])) {
297 $key = $this->report_tags[$t_id]['key'] ?? $t_id;
298 switch ($this->report_tags[$t_id]['type'] ?? '') {
299 case 'M': // metadata
300 $ptr = &$this->rep_data;
301 break;
302 case 'D': // date range
303 $ptr = &$this->rep_data['date'];
304 break;
305 case 'P': // policy
306 $ptr = &$this->rep_data['policy'];
307 break;
308 default: // record
309 $ptr = &$this->rep_data['records'][array_key_last($this->rep_data['records'])];
310 break;
311 }
312 if (isset($ptr[$key])) {
313 $ptr[$key] .= $data;
314 } else {
315 $ptr[$key] = $data;
316 }
317 unset($ptr);
318 }
319 }
320 }
321
322 private function xmlEnterTag(string $name): bool
323 {
324 if (!isset($this->report_tags[$this->tag_id]['children'][$name])) {
325 if ($this->strict_mode) {
326 throw new RuntimeException("Unknown tag: {$name}");
327 }
328 return false;
329 }
330
331 $this->tag_id = $this->report_tags[$this->tag_id]['children'][$name];
332 return true;
333 }
334
335 private function xmlLeaveTag(): void
336 {
337 $this->tag_id = $this->report_tags[$this->tag_id]['parent'];
338 }
339
340 private static function copyFields(array &$flist, array &$sou_data, array &$des_data): void
341 {
342 foreach ($flist as $fn => &$fp) {
343 $ft = $fp['type'];
344 if ($ft !== 'array' && array_key_exists($fn, $sou_data) && gettype($sou_data[$fn]) === $ft) {
345 $des_data[$fn] = $sou_data[$fn];
346 }
347 }
348 unset($fp);
349 }
350
351 private static function copySubdata(array &$flist, array &$sou_data, array &$des_data, string $key): void
352 {
353 if (isset($sou_data[$key]) && gettype($sou_data[$key]) === 'array') {
354 $des_data[$key] = [];
355 self::copyFields($flist, $sou_data[$key], $des_data[$key]);
356 }
357 }
358
359 private static $fields = [
360 'domain' => [ 'required' => true, 'type' => 'string' ],
361 'date' => [ 'required' => true, 'type' => 'array' ],
362 'org_name' => [ 'required' => true, 'type' => 'string' ],
363 'report_id' => [ 'required' => true, 'type' => 'string' ],
364 'email' => [ 'required' => false, 'type' => 'string' ],
365 'extra_contact_info' => [ 'required' => false, 'type' => 'string' ],
366 'error_string' => [ 'required' => false, 'type' => 'array' ],
367 'policy' => [ 'required' => true, 'type' => 'array' ],
368 'loaded_time' => [ 'required' => false, 'type' => 'object' ],
369 'records' => [ 'required' => true, 'type' => 'array' ]
370 ];
371 private static $dfields = [
372 'begin' => [ 'required' => true, 'type' => 'object' ],
373 'end' => [ 'required' => true, 'type' => 'object' ],
374 ];
375 private static $pfields = [
376 'adkim' => [ 'required' => false, 'type' => 'string' ],
377 'aspf' => [ 'required' => false, 'type' => 'string' ],
378 'p' => [ 'required' => false, 'type' => 'string' ],
379 'sp' => [ 'required' => false, 'type' => 'string' ],
380 'np' => [ 'required' => false, 'type' => 'string' ],
381 'pct' => [ 'required' => false, 'type' => 'string' ],
382 'fo' => [ 'required' => false, 'type' => 'string' ],
383 ];
384 private static $rfields = [
385 'ip' => [ 'required' => true, 'type' => 'string' ],
386 'count' => [ 'required' => true, 'type' => 'integer' ],
387 'disposition' => [ 'required' => true, 'type' => 'string' ],
388 'reason' => [ 'required' => false, 'type' => 'array' ],
389 'dkim_auth' => [ 'required' => false, 'type' => 'array' ],
390 'spf_auth' => [ 'required' => false, 'type' => 'array' ],
391 'dkim_align' => [ 'required' => true, 'type' => 'string' ],
392 'spf_align' => [ 'required' => true, 'type' => 'string' ],
393 'envelope_to' => [ 'required' => false, 'type' => 'string' ],
394 'envelope_from' => [ 'required' => false, 'type' => 'string' ],
395 'header_from' => [ 'required' => false, 'type' => 'string' ]
396 ];
397 private $report_tags = [
398 '<root>' => [
399 'children' => [
400 'FEEDBACK' => 'feedback'
401 ]
402 ],
403 'feedback' => [
404 'parent' => '<root>',
405 'children' => [
406 'VERSION' => 'ver',
407 'REPORT_METADATA' => 'rmd',
408 'POLICY_PUBLISHED' => 'p_p',
409 'RECORD' => 'rec'
410 ]
411 ],
412 'ver' => [ 'parent' => 'feedback', 'type' => 'M', 'default' => null ],
413 'rmd' => [
414 'parent' => 'feedback',
415 'children' => [
416 'ORG_NAME' => 'org_name',
417 'EMAIL' => 'email',
418 'EXTRA_CONTACT_INFO' => 'extra_contact_info',
419 'REPORT_ID' => 'report_id',
420 'DATE_RANGE' => 'd_range',
421 'ERROR' => 'error_string'
422 ]
423 ],
424 'p_p' => [
425 'parent' => 'feedback',
426 'children' => [
427 'DOMAIN' => 'domain',
428 'ADKIM' => 'policy_adkim',
429 'ASPF' => 'policy_aspf',
430 'P' => 'policy_p',
431 'SP' => 'policy_sp',
432 'NP' => 'policy_np',
433 'PCT' => 'policy_pct',
434 'FO' => 'policy_fo'
435 ]
436 ],
437 'rec' => [
438 'parent' => 'feedback',
439 'children' => [
440 'ROW' => 'row',
441 'IDENTIFIERS' => 'ident',
442 'AUTH_RESULTS' => 'au_res'
443 ]
444 ],
445 'org_name' => [ 'parent' => 'rmd', 'type' => 'M' ],
446 'email' => [ 'parent' => 'rmd', 'type' => 'M', 'default' => null ],
447 'extra_contact_info' => [ 'parent' => 'rmd', 'type' => 'M', 'default' => null ],
448 'report_id' => [ 'parent' => 'rmd', 'type' => 'M' ],
449 'd_range' => [
450 'parent' => 'rmd',
451 'children' => [
452 'BEGIN' => 'begin_time',
453 'END' => 'end_time'
454 ]
455 ],
456 'domain' => [ 'parent' => 'p_p', 'type' => 'M' ],
457 'error_string' => [ 'parent' => 'rmd', 'type' => 'M', 'default' => null ],
458 'begin_time' => [ 'parent' => 'd_range', 'type' => 'D', 'key' => 'begin' ],
459 'end_time' => [ 'parent' => 'd_range', 'type' => 'D', 'key' => 'end' ],
460 'policy_adkim' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'adkim', 'default' => null ],
461 'policy_aspf' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'aspf', 'default' => null ],
462 'policy_p' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'p', 'default' => null ],
463 'policy_sp' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'sp', 'default' => null ],
464 'policy_np' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'np', 'default' => null ],
465 'policy_pct' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'pct', 'default' => null ],
466 'policy_fo' => [ 'parent' => 'p_p', 'type' => 'P', 'key' => 'fo', 'default' => null ],
467 'row' => [
468 'parent' => 'rec',
469 'children' => [
470 'SOURCE_IP' => 'ip',
471 'COUNT' => 'rcount',
472 'POLICY_EVALUATED' => 'p_e'
473 ]
474 ],
475 'ident' => [
476 'parent' => 'rec',
477 'children' => [
478 'ENVELOPE_TO' => 'envelope_to',
479 'ENVELOPE_FROM' => 'envelope_from',
480 'HEADER_FROM' => 'header_from'
481 ]
482 ],
483 'au_res' => [
484 'parent' => 'rec',
485 'children' => [
486 'DKIM' => 'dkim_auth',
487 'SPF' => 'spf_auth'
488 ]
489 ],
490 'ip' => [ 'parent' => 'row' ],
491 'rcount' => [ 'parent' => 'row' ],
492 'p_e' => [
493 'parent' => 'row',
494 'children' => [
495 'DISPOSITION' => 'disposition',
496 'DKIM' => 'dkim_align',
497 'SPF' => 'spf_align',
498 'REASON' => 'reason'
499 ]
500 ],
501 'disposition' => [ 'parent' => 'p_e' ],
502 'dkim_align' => [ 'parent' => 'p_e' ],
503 'spf_align' => [ 'parent' => 'p_e' ],
504 'reason' => [
505 'parent' => 'p_e',
506 'default' => null,
507 'children' => [
508 'TYPE' => 'reason_type',
509 'COMMENT' => 'reason_comment'
510 ]
511 ],
512 'envelope_to' => [ 'parent' => 'ident', 'default' => null ],
513 'envelope_from' => [ 'parent' => 'ident', 'default' => null ],
514 'header_from' => [ 'parent' => 'ident', 'default' => null ],
515 'dkim_auth' => [
516 'parent' => 'au_res',
517 'default' => null,
518 'children' => [
519 'DOMAIN' => 'dkim_domain',
520 'SELECTOR' => 'dkim_selector',
521 'RESULT' => 'dkim_result',
522 'HUMAN_RESULT' => 'dkim_human_result'
523 ]
524 ],
525 'spf_auth' => [
526 'parent' => 'au_res',
527 'default' => null,
528 'children' => [
529 'DOMAIN' => 'spf_domain',
530 'SCOPE' => 'spf_scope',
531 'RESULT' => 'spf_result'
532 ]
533 ],
534 'reason_type' => [ 'parent' => 'reason' ],
535 'reason_comment' => [ 'parent' => 'reason' ],
536 'dkim_domain' => [ 'parent' => 'dkim_auth' ],
537 'dkim_selector' => [ 'parent' => 'dkim_auth' ],
538 'dkim_result' => [ 'parent' => 'dkim_auth' ],
539 'dkim_human_result' => [ 'parent' => 'dkim_auth' ],
540 'spf_domain' => [ 'parent' => 'spf_auth' ],
541 'spf_scope' => [ 'parent' => 'spf_auth' ],
542 'spf_result' => [ 'parent' => 'spf_auth' ]
543 ];
544 }