Debian Codegraph @

utils/summary_report.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 *
24 * This script creates a summary report and sends it by email.
25 * The email addresses must be specified in the configuration file.
26 * The script have two required parameters: `domain` and `period`,
27 * and five optional: `offset`, `emailto`, `format`, `user`, `subject`.
28 * The `domain` parameter must contain a domain name, a comma-separated list of domains, or `all`.
29 * The `period` parameter must have one of these values:
30 * `lastmonth` - to make a report for the last month;
31 * `lastweek` - to make a report for the last week;
32 * `lastndays:N` - to make a report for the last N days;
33 * The `offset` parameter is optional. It is intended to be used in conjunction with the `period` parameter
34 * and allows you to specify a date range offset to the past. Must be the number days, weeks or months
35 * for `lastNDays`, `lastWeek` and `lastMonth` respectively. The default value is 0.
36 * The `emailto` parameter is optional. Set it if you want to use a different email address to sent the report to.
37 * The `format` parameter is optional. It provides the ability to specify the email message format.
38 * Possible values are: `text`, `html`, `text+html`, `markdown`. The default value is `text`.
39 * The `user` parameter is optional. It can be useful for specifying a list of assigned domains for a single user
40 * when the `domain` options is set to `all`. Only makes sense if the user_management mode is active.
41 * The default value is `admin`.
42 * The `subject` parameter is optional. It allows you to specify the subject line of the summary report message
43 * instead of the default subject line. Remember to escape spaces and special characters!
44 *
45 * Some examples:
46 *
47 * $ php utils/summary_report.php domain=example.com period=lastweek
48 * will send a summary report for the last week for the domain example.com via email
49 *
50 * $ php utils/summary_report.php domain=example.com period=lastweek offset=1
51 * will send a summary report for the week before last week for the domain example.com via email
52 *
53 * $ php utils/summary_report.php domain=example.com period=lastndays:10 "subject:My cool summary report"
54 * will send a summary report for last 10 days for the domain example.com via email with the specified subject line
55 *
56 * $ php utils/summary_report.php domain=all user=frederick1 period=lastmonth [email protected]
57 * will send a summary report for the last month for all domains assigned to user frederick1 to [email protected].
58 *
59 * The best place to use it is cron.
60 *
61 * @category Utilities
62 * @package DmarcSrg
63 * @author Aleksey Andreev (liuch)
64 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
65 */
66
67 namespace Liuch\DmarcSrg;
68
69 use Liuch\DmarcSrg\Mail\Mailer;
70 use Liuch\DmarcSrg\Mail\MailBody;
71 use Liuch\DmarcSrg\Domains\Domain;
72 use Liuch\DmarcSrg\Domains\DomainList;
73 use Liuch\DmarcSrg\Report\SummaryReport;
74 use Liuch\DmarcSrg\Report\OverallReport;
75 use Liuch\DmarcSrg\Exception\SoftException;
76 use Liuch\DmarcSrg\Exception\RuntimeException;
77
78 require realpath(__DIR__ . '/..') . '/init.php';
79
80 if (Core::isWEB()) {
81 echo 'Forbidden';
82 exit(1);
83 }
84
85 if (!isset($argv)) {
86 echo 'Cannot get the script arguments. Probably register_argc_argv is disabled.', PHP_EOL;
87 exit(1);
88 }
89
90 $domain = null;
91 $all_dom = false;
92 $period = null;
93 $offset = '0';
94 $emailto = null;
95 $format = 'text';
96 $uname = null;
97 $acount = count($argv);
98 $subject = '';
99 if ($acount <= 1) {
100 echo "Usage: {$argv[0]} domain=<domains>|all", PHP_EOL;
101 echo ' period=lastmonth|lastweek|lastndays:<days>', PHP_EOL;
102 echo ' [offset=<days>] [format=text|html|text+html|markdown]', PHP_EOL;
103 echo ' [emailto=<email address>] [user=<username>]', PHP_EOL;
104 exit(1);
105 }
106 for ($i = 1; $i < $acount; ++$i) {
107 $av = explode('=', $argv[$i]);
108 if (count($av) == 2) {
109 switch ($av[0]) {
110 case 'domain':
111 $domain = $av[1];
112 break;
113 case 'period':
114 $period = $av[1];
115 break;
116 case 'offset':
117 $offset = $av[1];
118 break;
119 case 'emailto':
120 $emailto = $av[1];
121 break;
122 case 'format':
123 $format = $av[1];
124 break;
125 case 'user':
126 $uname = $av[1];
127 break;
128 case 'subject':
129 $subject = $av[1];
130 break;
131 }
132 }
133 }
134
135 $core = Core::instance();
136 try {
137 $core->setCurrentUser($uname ?? 'admin');
138 if (!$domain) {
139 throw new SoftException('Parameter "domain" is not specified');
140 }
141 if (!$period) {
142 throw new SoftException('Parameter "period" is not specified');
143 }
144 if (filter_var($offset, FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 0 ] ]) === false) {
145 throw new SoftException('Parameter "offset" must be a positive integer');
146 }
147 if (!in_array($format, [ 'text', 'html', 'text+html', 'markdown' ], true)) {
148 throw new SoftException('Unknown email message format: ' . $format);
149 }
150 if (!$emailto) {
151 $emailto = $core->config('mailer/default', '');
152 }
153
154 if ($domain === 'all') {
155 $domains = (new DomainList($core->getCurrentUser()))->getList()['domains'];
156 $all_dom = true;
157 } else {
158 $domains = array_map(function ($d) {
159 return new Domain($d);
160 }, explode(',', $domain));
161 }
162
163 $rep = new SummaryReport($period, intval($offset));
164 switch ($format) {
165 case 'text':
166 case 'markdown':
167 $text = [];
168 $html = null;
169 break;
170 case 'html':
171 $text = null;
172 $html = [];
173 break;
174 default:
175 $text = [];
176 $html = [];
177 break;
178 }
179 $dom_cnt = count($domains);
180 if ($dom_cnt == 0) {
181 throw new SoftException('The user has no assigned domains');
182 }
183 $overall = null;
184 if ($dom_cnt > 1) {
185 $overall = new OverallReport();
186 $rep->bindSection($overall);
187 }
188 $add_sep = function () use (&$text, &$html) {
189 if (!is_null($text)) {
190 $text[] = '-----------------------------------';
191 $text[] = '';
192 }
193 if (!is_null($html)) {
194 $html[] = '<hr style="margin:2em 0;" />';
195 }
196 };
197 $rep_cnt = 0;
198 $err_cnt = 0;
199 for ($i = 0; $i < $dom_cnt; ++$i) {
200 $domain = $domains[$i];
201 if ($domain->isAssigned($core->getCurrentUser())) {
202 $rep->setDomain($domain);
203 if (!$all_dom || $domain->active() || !$rep->isEmpty()) {
204 if ($rep_cnt || $err_cnt) {
205 $add_sep();
206 }
207 if (!is_null($text)) {
208 if ($format === 'markdown') {
209 foreach ($rep->markdown() as &$row) {
210 $text[] = $row;
211 }
212 } else {
213 foreach ($rep->text() as &$row) {
214 $text[] = $row;
215 }
216 }
217 unset($row);
218 }
219 if (!is_null($html)) {
220 foreach ($rep->html() as &$row) {
221 $html[] = $row;
222 }
223 unset($row);
224 }
225 ++$rep_cnt;
226 } else {
227 $overall->removeRow($domain);
228 }
229 } else {
230 if ($rep_cnt || $err_cnt) {
231 $add_sep();
232 }
233 $nf_message = "Domain \"{$domain->fqdn()}\" does not exist";
234 if ($dom_cnt === 1) {
235 throw new SoftException($nf_message);
236 }
237 if (!is_null($text)) {
238 $text[] = "# {$nf_message}";
239 $text[] = '';
240 }
241 if (!is_null($html)) {
242 $html[] = '<h2>' . htmlspecialchars($nf_message) . '</h2>';
243 }
244 ++$err_cnt;
245 }
246 }
247 if (!is_null($text)) {
248 if (!$rep_cnt && !$err_cnt) {
249 $text[] = 'There are no active domains';
250 } elseif ($overall) {
251 if ($format === 'markdown') {
252 $text = array_merge($overall->markdown(), [ '---', '' ], $text);
253 } else {
254 $text = array_merge($overall->text(), [ '-----------------------------------', '' ], $text);
255 }
256 }
257 }
258 if (!is_null($html)) {
259 if (!$rep_cnt && !$err_cnt) {
260 $html[] = '<p>There are no active domains</p>';
261 } elseif ($overall) {
262 $html = array_merge($overall->html(), [ '<hr style="margin:2em 0;" />' ], $html);
263 }
264 }
265 $mbody = new MailBody();
266 $mbody->text = $text;
267 $mbody->html = $html;
268
269 $mailer = Mailer::get($core->config('mailer', []));
270 $mailer->setFrom($core->config('mailer/from', ''));
271 $mailer->addAddress($emailto);
272 if (!empty($subject)) {
273 $mailer->setSubject($subject);
274 } elseif ($dom_cnt === 1) {
275 $mailer->setSubject("{$rep->subject()} for {$domain->fqdn()}");
276 } elseif ($uname && $all_dom) {
277 $mailer->setSubject("{$rep->subject()} for {$uname}'s domains");
278 } else {
279 $dom_cnt = $rep_cnt + $err_cnt;
280 $mailer->setSubject("{$rep->subject()} for {$dom_cnt} domains");
281 }
282 $mailer->setBody($mbody);
283 $mailer->send();
284 } catch (SoftException $e) {
285 echo 'Error: ' . $e->getMessage() . PHP_EOL;
286 exit(1);
287 } catch (RuntimeException $e) {
288 echo ErrorHandler::exceptionText($e);
289 exit(1);
290 }
291
292 exit(0);