Debian Codegraph @

classes/Domains/Domain.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) 2021-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 class Domain
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\Domains;
33
34 use Liuch\DmarcSrg\Core;
35 use Liuch\DmarcSrg\Exception\SoftException;
36 use Liuch\DmarcSrg\Exception\LogicException;
37 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
38
39 /**
40 * It's a class for accessing to stored domains data
41 *
42 * This class is designed for storing and manipulating domain data.
43 * All queries to the database are made in lazy mode.
44 */
45 class Domain
46 {
47 private $db = null;
48 private $ex_f = null;
49 private $data = [
50 'id' => null,
51 'fqdn' => null,
52 'active' => null,
53 'description' => null,
54 'created_time' => null,
55 'updated_time' => null
56 ];
57
58 /**
59 * It's a constructor of the class
60 *
61 * Some examples of using:
62 * (new Domain(1))->fqdn(); - will return the fully qualified domain name for the domain with id = 1
63 * (new Domain('example.com'))->description(); - will return the description for the domain example.com
64 * (new Domain([ 'fqdn' => 'example.com', 'description' => 'an expample domain' ])->save(); - will add
65 * this domain to the database if it does not exist in it.
66 *
67 * @param int|string|array $data Some domain data to identify it
68 * int value is treated as domain id
69 * string value is treated as a FQDN
70 * array has these fields: `id`, `fqdn`, `active`, `description`
71 * and usually uses for creating a new domain item.
72 * Note: The values of the fields `created_time` and `updated_time`
73 * will be ignored while saving to the database.
74 * @param \Liuch\DmarcSrg\Database\DatabaseController $db The database controller
75 *
76 * @return void
77 */
78 public function __construct($data, $db = null)
79 {
80 $this->db = $db ?? Core::instance()->database();
81 switch (gettype($data)) {
82 case 'integer':
83 $this->data['id'] = $data;
84 return;
85 case 'string':
86 $this->data['fqdn'] = strtolower($data);
87 $this->checkFqdn();
88 return;
89 case 'array':
90 if (isset($data['id'])) {
91 if (gettype($data['id']) !== 'integer') {
92 break;
93 }
94 $this->data['id'] = $data['id'];
95 }
96 if (isset($data['fqdn'])) {
97 if (gettype($data['fqdn']) !== 'string') {
98 break;
99 }
100 $this->data['fqdn'] = strtolower($data['fqdn']);
101 $this->checkFqdn();
102 }
103 if (isset($data['active'])) {
104 if (gettype($data['active']) !== 'boolean') {
105 break;
106 }
107 $this->data['active'] = $data['active'];
108 } else {
109 $this->data['active'] = false;
110 }
111 if (isset($data['description'])) {
112 if (gettype($data['description']) !== 'string') {
113 break;
114 }
115 $this->data['description'] = $data['description'];
116 }
117 if (isset($data['created_time'])) {
118 if (gettype($data['created_time']) !== 'object') {
119 break;
120 }
121 $this->data['created_time'] = $data['created_time'];
122 }
123 if (isset($data['updated_time'])) {
124 if (gettype($data['updated_time']) !== 'object') {
125 break;
126 }
127 $this->data['updated_time'] = $data['updated_time'];
128 }
129 if (!is_null($this->data['id']) || !is_null($this->data['fqdn'])) {
130 return;
131 }
132 }
133 throw new LogicException('Wrong domain data');
134 }
135
136 /**
137 * Returns true if the domain exists in the database or false otherwise
138 *
139 * @return bool Whether the domain exists
140 */
141 public function exists(): bool
142 {
143 if (is_null($this->ex_f)) {
144 $this->ex_f = $this->db->getMapper('domain')->exists($this->data);
145 }
146 return $this->ex_f;
147 }
148
149 /**
150 * Ensures the domain is in the specified state and throws an exception if it is not.
151 *
152 * @param string $state Can be one of these values: 'exist', 'nonexist'
153 *
154 * @throws SoftException
155 *
156 * @return void
157 */
158 public function ensure(string $state): void
159 {
160 switch ($state) {
161 case 'exist':
162 if (!$this->exists()) {
163 $this->unknownDomain();
164 }
165 break;
166 case 'nonexist':
167 if ($this->exists()) {
168 throw new SoftException('The domain already exists');
169 }
170 break;
171 default:
172 throw new LogicException('Unknown domain state');
173 }
174 }
175
176 /**
177 * Returns the domain id
178 *
179 * @return int The domain id
180 */
181 public function id(): int
182 {
183 if (is_null($this->data['id'])) {
184 $this->fetchData();
185 }
186 return $this->data['id'];
187 }
188
189 /**
190 * Returns the domain's FQDN
191 *
192 * @return string FQDN for the domain
193 */
194 public function fqdn(): string
195 {
196 if (is_null($this->data['fqdn'])) {
197 $this->fetchData();
198 }
199 return $this->data['fqdn'];
200 }
201
202 /**
203 * Whether the domain is active or not
204 *
205 * When the domain is inactive, all incoming reports for it are ignored
206 * but the domain will still be included in summary reports.
207 *
208 * @return bool
209 */
210 public function active(): bool
211 {
212 if (is_null($this->data['active'])) {
213 $this->fetchData();
214 }
215 return $this->data['active'];
216 }
217
218 /**
219 * Returns the domain's description
220 *
221 * @return string|null The description of the domain if it exists or null otherwise
222 */
223 public function description()
224 {
225 if (is_null($this->data['id']) || is_null($this->data['fqdn'])) {
226 $this->fetchData();
227 }
228 return $this->data['description'];
229 }
230
231 /**
232 * Returns an array with domain data
233 *
234 * @return array Domain data
235 */
236 public function toArray(): array
237 {
238 foreach ([ 'id', 'fqdn', 'active' ] as $it) {
239 if (is_null($this->data[$it])) {
240 $this->fetchData();
241 break;
242 }
243 }
244 $res = $this->data;
245 unset($res['id']);
246 return $res;
247 }
248
249 /**
250 * Returns true if the domain exists in the database and is assigned to the user
251 *
252 * @param \Liuch\DmarcSrg\Users\User $user User to check
253 * @param bool $exception Throw an exception instead of returning false
254 *
255 * @return bool
256 */
257 public function isAssigned($user, bool $exception = false): bool
258 {
259 if ($this->ex_f !== false) {
260 $user_id = $user->id();
261 if ($user_id === 0) {
262 // It is the admin
263 if ($this->exists()) {
264 return true;
265 }
266 } elseif ($this->db->getMapper('domain')->isAssigned($this->data, $user_id)) {
267 $this->ex_f = true;
268 return true;
269 }
270 }
271 if ($exception) {
272 $this->unknownDomain();
273 }
274 return false;
275 }
276
277 /**
278 * Assigns the domain to a user
279 *
280 * @param \Liuch\DmarcSrg\Users\User $user The user to whom the domain should be assigned
281 *
282 * @return void
283 */
284 public function assignUser($user): void
285 {
286 $user_id = $user->id();
287 if ($user_id !== 0) {
288 $this->db->getMapper('domain')->assignUser($this->data, $user_id);
289 }
290 }
291
292 /**
293 * Unassigns the domain from a user
294 *
295 * @param \Liuch\DmarcSrg\Users\User $user The user from whom the domain should be unassigned
296 *
297 * @return void
298 */
299 public function unassignUser($user): void
300 {
301 $user_id = $user->id();
302 if ($user_id !== 0) {
303 $this->db->getMapper('domain')->unassignUser($this->data, $user_id);
304 }
305 }
306
307 /**
308 * Saves the domain to the database
309 *
310 * Updates the domain's description in the database if the domain exists or insert a new record otherwise.
311 * The domain id is ignored in the insert mode.
312 *
313 * @return void
314 */
315 public function save(): void
316 {
317 $this->db->getMapper('domain')->save($this->data);
318 $this->ex_f = true;
319 }
320
321 /**
322 * Deletes the domain from the database
323 *
324 * Deletes the domain if there are no reports for this domain in the database.
325 * If you want to stop handling reports for this domain, just make it inactive.
326 *
327 * @param bool $force If there are incoming reports for this domain.
328 * True: Remove the incoming report with the domain
329 * False: Cancel domain deletion
330 *
331 * @return void
332 */
333 public function delete(bool $force): void
334 {
335 if (is_null($this->data['id'])) {
336 $this->fetchData();
337 }
338 $this->db->getMapper('domain')->delete($this->data['id'], $force);
339 $this->ex_f = false;
340 }
341
342 /**
343 * Verifies domain ownership
344 *
345 * @throws SoftException
346 *
347 * @param string $key Verification key
348 * @param string $method Verification method
349 *
350 * return void
351 */
352 public function verifyOwnership(string $key, string $method): void
353 {
354 $passed = false;
355 switch ($method) {
356 case 'dns':
357 $dr = dns_get_record($this->data['fqdn'], DNS_TXT);
358 if ($dr) {
359 $str = 'dmarcsrg-verification=' . $key;
360 foreach ($dr as &$rec) {
361 if (trim($rec['txt']) === $str) {
362 $passed = true;
363 break;
364 }
365 }
366 unset($rec);
367 }
368 break;
369 }
370 if (!$passed) {
371 throw new SoftException('Domain verification failed');
372 }
373 }
374
375 /**
376 * Removes the trailing dot from the domain name and checks it for an empty value.
377 *
378 * @return void
379 */
380 private function checkFqdn(): void
381 {
382 $fqdn = trim($this->data['fqdn']);
383 if (substr($fqdn, -1) === '.') {
384 $fqdn = trim(substr($fqdn, 0, -1));
385 }
386 if ($fqdn === '') {
387 throw new SoftException('The domain name must not be an empty string');
388 }
389 $this->data['fqdn'] = $fqdn;
390 }
391
392 /**
393 * Fetches the domain data from the database by its id or name
394 *
395 * @return void
396 */
397 private function fetchData(): void
398 {
399 if ($this->ex_f === false) {
400 return;
401 }
402
403 try {
404 $this->db->getMapper('domain')->fetch($this->data);
405 $this->ex_f = true;
406 } catch (DatabaseNotFoundException $e) {
407 $this->ex_f = false;
408 $this->unknownDomain();
409 }
410 }
411
412 /**
413 * Throws an exception that the domain doesn't exist
414 *
415 * @throws SoftException
416 *
417 * @return void
418 */
419 private function unknownDomain(): void
420 {
421 $name = '';
422 if (!empty($this->data['fqdn'])) {
423 $name = ': ' . $this->data['fqdn'];
424 }
425 throw new SoftException('Unknown domain' . $name);
426 }
427 }