Debian Codegraph @

utils/domains_admin.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) 2024 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 is designed to manipulate the list of domains in the database.
25 * Usage: php domains_admin.php <command> [<args>]
26 * The available commands are:
27 * `list` - Outputs a list of domains sorted by FQDN. No parameters.
28 * `add` - Adds a new domain to the database. Parameters:
29 * name=<FQDN> Required.
30 * active=<true|false> Optional. The default value is false. The valid values are:
31 * true, false, 1, 0, yes, no. The value is case insensitive.
32 * description=<description> Optional. The default value is null.
33 * `show` - Displays domain information. Parameters:
34 * id=<domain ID>|name=<domain name> Required.
35 * `modify` - Modifies domain. Parameters:
36 * id=<domain ID>|name=<domain name> Required.
37 * active=<true|false> Optional.
38 * description=<description> Optional.
39 * Note: The command changes only the specified domain data. The rest of the data remains unchanged.
40 * `delete` - Deletes a domain from the database. Parameters:
41 * id=<domain ID>|name=<domain name> Required.
42 * force=<true|false> Optional. The default value is false. The valid values are:
43 * true, false, 1, 0, yes, no. The value is case insensitive.
44 *
45 * Some examples:
46 *
47 * $php utils/domains_admin.php list
48 * will display a list of available domains from the database
49 *
50 * $php utils/domains_admin.php add name=b.net active=yes description=The\ backup\ mail\ domain
51 * will create a new domain b.net with description. Do not forget to escape special characters!
52 *
53 * $php utils/domains_admin.php show id=1
54 * will display information about the domain with ID=1
55 *
56 * $php utils/domains_admin.php show name=b.net
57 * will display information about the domain b.net
58 *
59 * $php utils/domains_admin.php modify id=1 active=no
60 * will deactivate the domain with ID=1
61 *
62 * $php utils/domains_admin.php delete name=b.net
63 * will delete the domain named b.net
64 *
65 * @category Utilities
66 * @package DmarcSrg
67 * @author Aleksey Andreev (liuch)
68 * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
69 */
70
71 namespace Liuch\DmarcSrg;
72
73 use Liuch\DmarcSrg\ErrorCodes;
74 use Liuch\DmarcSrg\Domains\Domain;
75 use Liuch\DmarcSrg\Domains\DomainList;
76 use Liuch\DmarcSrg\Exception\SoftException;
77 use Liuch\DmarcSrg\Exception\RuntimeException;
78
79 require realpath(__DIR__ . '/..') . '/init.php';
80
81 if (Core::isWEB()) {
82 echo 'Forbidden';
83 exit(1);
84 }
85
86 if (!isset($argv)) {
87 echo 'Cannot get the script arguments. Probably register_argc_argv is disabled.', PHP_EOL;
88 exit(1);
89 }
90
91 $parseArguments = function (array $allowed) use (&$argv): array {
92 $res = [];
93 if (count($argv) > 2) {
94 for ($i = 2; $i < count($argv); ++$i) {
95 $av = explode('=', $argv[$i], 2);
96 if (count($av) == 1 || !in_array($av[0], $allowed)) {
97 throw new SoftException("Incorrect parameter \"{$av[0]}\"");
98 }
99 $res[$av[0]] = $av[1];
100 }
101 }
102 return $res;
103 };
104 $getBoolParameter = function (string $name, array $args) {
105 $ac = array_search(strtolower($args[$name]), [ '', '0', 'false', 'no', '1', 'true', 'yes' ], true);
106 if ($ac === false) {
107 throw new SoftException('Incorrect value of the "' . $name . '" parameter');
108 }
109 return $ac > 3;
110 };
111 $getDomain = function (array $args) {
112 if (isset($args['id'])) {
113 if (isset($args['name'])) {
114 throw new SoftException('To identify a domain you need to specify either its id or name, not both');
115 }
116 $id = filter_var($args['id'], FILTER_VALIDATE_INT, [ 'options' => [ 'min_range' => 0 ] ]);
117 if (!$id) {
118 throw new SoftException('Incorrect domain ID');
119 }
120 $domain = new Domain($id);
121 } elseif (!empty($args['name'])) {
122 $domain = new Domain($args['name']);
123 } else {
124 throw new SoftException('Either the "id" or "name" parameter must be specified');
125 }
126 return $domain;
127 };
128
129 try {
130 $core = Core::instance();
131 $core->setCurrentUser('admin');
132 $action = $argv[1] ?? '';
133 switch ($action) {
134 case 'list':
135 $parseArguments([]);
136 $list = (new DomainList($core->getCurrentUser()))->getList()['domains'];
137 $table = new TextTable([ 'ID', 'FQDN', 'Active', 'Updated', 'Description' ]);
138 foreach ($list as $dom) {
139 $da = $dom->toArray();
140 $table->appendRow([
141 $dom->id(),
142 $da['fqdn'],
143 $da['active'] ? '+' : '',
144 $da['updated_time']->format('c'),
145 empty($da['description']) ? '' : '+'
146 ]);
147 }
148 $table->setMinColumnWidth(1, 15)->sortBy(1)->output();
149 break;
150 case 'add':
151 $args = $parseArguments([ 'name', 'active', 'description' ]);
152 if (empty($args['name'])) {
153 throw new SoftException('Parameter "name" must be specified');
154 }
155 $dd = [ 'fqdn' => $args['name'] ];
156 $dd['active'] = isset($args['active']) ? $getBoolParameter('active', $args) : false;
157 if (!empty($args['description'])) {
158 $dd['description'] = $args['description'];
159 }
160 $domain = new Domain($dd);
161 $domain->ensure('nonexist');
162 $domain->save();
163 echo 'Done.', PHP_EOL;
164 break;
165 case 'show':
166 $domain = $getDomain($parseArguments([ 'id', 'name' ]));
167 $dd = $domain->toArray();
168 echo 'ID: ', $domain->id(), PHP_EOL;
169 echo 'FQDN: ', $dd['fqdn'], PHP_EOL;
170 echo 'Acitve: ', ($dd['active'] ? 'Yes' : 'No'), PHP_EOL;
171 echo 'Created: ', $dd['created_time']->format('c'), PHP_EOL;
172 echo 'Updated: ', $dd['updated_time']->format('c'), PHP_EOL;
173 if (!empty($dd['description'])) {
174 echo 'Description: ', $dd['description'], PHP_EOL;
175 }
176 break;
177 case 'modify':
178 $args = $parseArguments([ 'id', 'name', 'active', 'description' ]);
179 $domain = $getDomain($args);
180 $domain->ensure('exist');
181 $mf = false;
182 $dd = $domain->toArray();
183 if (isset($args['active'])) {
184 $ac = $getBoolParameter('active', $args);
185 if ($dd['active'] != $ac) {
186 $dd['active'] = $ac;
187 $mf = true;
188 }
189 }
190 if (isset($args['description'])) {
191 $ds = $args['description'];
192 if ($dd['description'] != $ds) {
193 $dd['description'] = $ds;
194 $mf = true;
195 }
196 }
197 if ($mf) {
198 (new Domain($dd))->save();
199 echo 'Done.', PHP_EOL;
200 } else {
201 echo 'There is nothing to change', PHP_EOL;
202 }
203 break;
204 case 'delete':
205 $args = $parseArguments([ 'id', 'name', 'force' ]);
206 $domain = $getDomain($args);
207 $domain->ensure('exist');
208 $domain->delete(isset($args['force']) ? $getBoolParameter('force', $args) : false);
209 echo 'Done.', PHP_EOL;
210 break;
211 default:
212 echo 'Unknown command ', $action, PHP_EOL, PHP_EOL;
213 // no break needed
214 case '':
215 echo "Usage: {$argv[0]} <command> [<parameters>]", PHP_EOL, PHP_EOL;
216 echo 'Commands:', PHP_EOL;
217 echo ' list Outputs a list of domains sorted by FQDN. No parameters.', PHP_EOL;
218 echo ' add Adds a new domain to the database.', PHP_EOL;
219 echo ' Required parameter: name.', PHP_EOL;
220 echo ' Optional parameters: active, description.', PHP_EOL;
221 echo ' show Displays domain information.', PHP_EOL;
222 echo ' Required parameters: id or name.', PHP_EOL;
223 echo ' modify Makes changes to a domain record.', PHP_EOL;
224 echo ' Required parameters: id or name.', PHP_EOL;
225 echo ' Optional parameters: active, description.', PHP_EOL;
226 echo ' delete Deletes a domain record from the database.', PHP_EOL;
227 echo ' Required parameters: id or name.', PHP_EOL;
228 echo ' Optional parameter: force.', PHP_EOL, PHP_EOL;
229 echo 'Parameters:', PHP_EOL;
230 echo ' id Domain internal ID. Cannot be changed.', PHP_EOL;
231 echo ' Used for domain identification only.', PHP_EOL;
232 echo ' name Domain name. Cannot be changed.', PHP_EOL;
233 echo ' Used when adding a domain and for it identification.', PHP_EOL;
234 echo ' active Whether the domain is active or not. ', PHP_EOL;
235 echo ' Incoming reports for inactive domains are not processed.', PHP_EOL;
236 echo ' description Domain description.', PHP_EOL;
237 echo ' force If true, allows you to delete a domains', PHP_EOL;
238 echo ' when there are incoming reports for it.', PHP_EOL;
239 exit(1);
240 }
241 } catch (SoftException $e) {
242 echo 'Error: ' . $e->getMessage() . PHP_EOL;
243 if ($e->getCode() === ErrorCodes::DOMAIN_HAS_REPORTS) {
244 echo 'If you want to delete the domain with its reports, use force=true parameter.', PHP_EOL;
245 }
246 exit(1);
247 } catch (RuntimeException $e) {
248 echo ErrorHandler::exceptionText($e);
249 exit(1);
250 }
251
252 exit(0);