Debian Codegraph @

classes/Database/Mariadb/Connector.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 DatabaseConnector 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\Mariadb;
33
34 use Liuch\DmarcSrg\ErrorCodes;
35 use Liuch\DmarcSrg\ErrorHandler;
36 use Liuch\DmarcSrg\Database\DatabaseConnector;
37 use Liuch\DmarcSrg\Exception\SoftException;
38 use Liuch\DmarcSrg\Exception\RuntimeException;
39 use Liuch\DmarcSrg\Exception\DatabaseFatalException;
40 use Liuch\DmarcSrg\Exception\DatabaseExceptionFactory;
41 use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
42
43 class Connector extends DatabaseConnector
44 {
45 protected $dbh = null;
46 protected $ansiMode = true;
47
48 /**
49 * Returns an instance of PDO class
50 *
51 * @return \PDO
52 */
53 public function dbh(): object
54 {
55 $this->ensureConnection();
56 return $this->dbh;
57 }
58
59 /**
60 * Returns information about the database as an array.
61 *
62 * @return array May contain the following fields:
63 * `tables` - an array of tables with their properties;
64 * `correct` - true if the database is correct;
65 * `version` - the current version of the database structure;
66 * `message` - a state message;
67 * `error_code` - an error code;
68 */
69 public function state(): array
70 {
71 $this->ensureConnection();
72
73 $res = [];
74 $p_len = strlen($this->prefix);
75 if ($p_len > 0) {
76 $like_str = ' WHERE NAME LIKE "' . str_replace('_', '\\_', $this->prefix) . '%"';
77 } else {
78 $like_str = '';
79 }
80
81 try {
82 $this->setANSIMode(false);
83 $tables = [];
84 $st = $this->dbh->query(
85 'SHOW TABLE STATUS FROM `' . str_replace('`', '', $this->name) . '`' . $like_str
86 );
87 while ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
88 $tname = $row['Name'];
89 $rcnt = $this->dbh->query('SELECT COUNT(*) FROM `' . $tname . '`')->fetch(\PDO::FETCH_NUM)[0];
90 $tables[substr($tname, $p_len)] = [
91 'engine' => $row['Engine'],
92 'rows' => intval($rcnt),
93 'data_length' => intval($row['Data_length']),
94 'index_length' => intval($row['Index_length']),
95 'create_time' => $row['Create_time'],
96 'update_time' => $row['Update_time']
97 ];
98 }
99 foreach (array_keys(self::$schema) as $table) {
100 if (!isset($tables[$table])) {
101 $tables[$table] = false;
102 }
103 }
104 $exist_cnt = 0;
105 $absent_cnt = 0;
106 $tables_res = [];
107 $system_exs = false;
108 foreach ($tables as $tname => $tval) {
109 $t = null;
110 if ($tval) {
111 $t = $tval;
112 $t['exists'] = true;
113 if (isset(self::$schema[$tname])) {
114 ++$exist_cnt;
115 $t['message'] = 'Ok';
116 } else {
117 $t['message'] = 'Unknown table';
118 }
119 if ($tname === 'system') {
120 $system_exs = true;
121 }
122 } else {
123 ++$absent_cnt;
124 $t = [
125 'error_code' => 1,
126 'message' => 'Not exist'
127 ];
128 }
129 $t['name'] = $tname;
130 $tables_res[] = $t;
131 }
132 $res['tables'] = $tables_res;
133 if ($absent_cnt === 0) {
134 $res['correct'] = true;
135 $res['message'] = 'Ok';
136 } else {
137 if ($exist_cnt == 0) {
138 $res['error_code'] = -1;
139 $res['message'] = 'The database schema is not initiated';
140 } else {
141 $res['error_code'] = ErrorCodes::INCORRECT_TABLE_SET;
142 $res['message'] = 'Incomplete set of the tables';
143 }
144 }
145 if ($system_exs) {
146 try {
147 $this->setANSIMode(true);
148 $res['version'] = $this->getMapper('setting')->value('version', 0);
149 $this->setANSIMode(false);
150 } catch (DatabaseNotFoundException $e) {
151 }
152 }
153 } catch (\PDOException $e) {
154 $res = array_replace($res, ErrorHandler::exceptionResult(
155 new DatabaseFatalException('Failed to get the database information', -1, $e)
156 ));
157 } catch (RuntimeException $e) {
158 $res = array_replace($res, ErrorHandler::exceptionResult($e));
159 } finally {
160 $this->setANSIMode(true);
161 }
162 return $res;
163 }
164
165 /**
166 * Initiates the database.
167 *
168 * This method creates needed tables and indexes in the database.
169 * The method will fail if the database already have tables with the table prefix.
170 *
171 * @param string $version The current version of the database schema
172 *
173 * @return void
174 */
175 public function initDb(string $version): void
176 {
177 $this->ensureConnection();
178 try {
179 $this->setANSIMode(false);
180 $st = $this->dbh->query($this->sqlShowTablesQuery());
181 try {
182 if ($st->fetch()) {
183 if (empty($this->tablePrefix())) {
184 throw new SoftException('The database is not empty', ErrorCodes::DB_NOT_EMPTY);
185 } else {
186 throw new SoftException(
187 'Database tables already exist with the given prefix',
188 ErrorCodes::DB_NOT_EMPTY
189 );
190 }
191 }
192 foreach (self::$schema as $t_name => &$t_schema) {
193 $this->createDbTable($this->tablePrefix($t_name), $t_schema);
194 }
195 unset($t_schema);
196 } finally {
197 $st->closeCursor();
198 }
199 $st = $this->dbh->prepare(
200 'INSERT INTO `' . $this->tablePrefix('system')
201 . '` (`key`, user_id, value) VALUES ("version", 0, ?)'
202 );
203 $st->bindValue(1, $version, \PDO::PARAM_STR);
204 $st->execute();
205 $st->closeCursor();
206 } catch (\PDOException $e) {
207 throw new DatabaseFatalException('Failed to create required tables in the database', -1, $e);
208 } finally {
209 $this->setANSIMode(true);
210 }
211 }
212
213 /**
214 * Cleans up the database
215 *
216 * Drops tables with the table prefix in the database or all tables in the database
217 * if no table prefix is set.
218 *
219 * @return void
220 */
221 public function cleanDb(): void
222 {
223 $this->ensureConnection();
224 try {
225 $this->setANSIMode(false);
226 $db = $this->dbh;
227 $db->query('SET foreign_key_checks = 0');
228 $st = $db->query($this->sqlShowTablesQuery());
229 while ($table = $st->fetchColumn(0)) {
230 $db->query('DROP TABLE `' . $table . '`');
231 }
232 $st->closeCursor();
233 $db->query('SET foreign_key_checks = 1');
234 } catch (\PDOException $e) {
235 throw new DatabaseFatalException('Failed to drop the database tables', -1, $e);
236 } finally {
237 $this->setANSIMode(true);
238 }
239 }
240
241 /**
242 * Enables or disables ANSI query mode for the current datatabase connection
243 *
244 * @param bool $on True turns ANSI mode on, False turns it off
245 *
246 * @return void
247 */
248 public function setANSIMode(bool $on): void
249 {
250 if ($on !== $this->ansiMode) {
251 $this->ansiMode = $on;
252 if ($this->dbh) {
253 if ($on) {
254 $this->dbh->query('SET SESSION sql_mode=\'ANSI\'');
255 } else {
256 $this->dbh->query('SET SESSION sql_mode=@prev_sql_mode');
257 }
258 }
259 }
260 }
261
262 /**
263 * Sets the database connection if it hasn't connected yet.
264 *
265 * @return void
266 */
267 private function ensureConnection(): void
268 {
269 if (!$this->dbh) {
270 try {
271 $this->dbh = new \PDO(
272 "mysql:host={$this->host};dbname={$this->name};charset=utf8",
273 $this->user,
274 $this->password,
275 [ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ]
276 );
277 $this->dbh->query('SET @prev_sql_mode=@@sql_mode');
278 if ($this->ansiMode) {
279 $this->dbh->query('SET SESSION sql_mode=\'ANSI\'');
280 }
281 $this->dbh->query('SET time_zone = \'+00:00\'');
282 } catch (\PDOException $e) {
283 throw DatabaseExceptionFactory::fromException($e);
284 }
285 }
286 }
287
288 /**
289 * Return SHOW TABLES SQL query string for tables with the table prefix
290 *
291 * @return string
292 */
293 private function sqlShowTablesQuery(): string
294 {
295 $res = 'SHOW TABLES';
296 $prefix = $this->tablePrefix();
297 if (strlen($prefix) > 0) {
298 $res .= ' WHERE `tables_in_' . str_replace('`', '', $this->name)
299 . '` LIKE "' . str_replace('_', '\\_', $prefix) . '%"';
300 }
301 return $res;
302 }
303
304 /**
305 * Creates a table in the database.
306 *
307 * @param string $name Table name
308 * @param array $definitions Table structure
309 *
310 * @return void
311 */
312 private function createDbTable(string $name, array $definitions): void
313 {
314 $query = 'CREATE TABLE `' . $name . '` (';
315 $col_num = 0;
316 foreach ($definitions['columns'] as $column) {
317 if ($col_num > 0) {
318 $query .= ', ';
319 }
320 $query .= '`' . $column['name'] . '` ' . $column['definition'];
321 $col_num += 1;
322 }
323 $query .= ', ' . $definitions['additional'] . ') ' . $definitions['table_options'];
324 $this->dbh->query($query);
325 }
326
327 private static $schema = [
328 'system' => [
329 'columns' => [
330 [
331 'name' => 'key',
332 'definition' => 'varchar(64) NOT NULL'
333 ],
334 [
335 'name' => 'user_id',
336 'definition' => 'int(10) unsigned NOT NULL DEFAULT 0'
337 ],
338 [
339 'name' => 'value',
340 'definition' => 'varchar(255) DEFAULT NULL'
341 ]
342 ],
343 'additional' => 'PRIMARY KEY (user_id, `key`)',
344 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
345 ],
346 'domains' => [
347 'columns' => [
348 [
349 'name' => 'id',
350 'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
351 ],
352 [
353 'name' => 'fqdn',
354 'definition' => 'varchar(255) NOT NULL'
355 ],
356 [
357 'name' => 'active',
358 'definition' => 'boolean NOT NULL'
359 ],
360 [
361 'name' => 'description',
362 'definition' => 'TEXT NULL'
363 ],
364 [
365 'name' => 'created_time',
366 'definition' => 'datetime NOT NULL'
367 ],
368 [
369 'name' => 'updated_time',
370 'definition' => 'datetime NOT NULL'
371 ]
372 ],
373 'additional' => 'PRIMARY KEY (id), UNIQUE KEY fqdn (fqdn)',
374 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
375 ],
376 'users' => [
377 'columns' => [
378 [
379 'name' => 'id',
380 'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
381 ],
382 [
383 'name' => 'name',
384 'definition' => 'varchar(32) NOT NULL'
385 ],
386 [
387 'name' => 'level',
388 'definition' => 'smallint unsigned NOT NULL'
389 ],
390 [
391 'name' => 'enabled',
392 'definition' => 'boolean NOT NULL'
393 ],
394 [
395 'name' => 'password',
396 'definition' => 'varchar(255) NULL'
397 ],
398 [
399 'name' => 'email',
400 'definition' => 'varchar(64) NULL'
401 ],
402 [
403 'name' => 'key',
404 'definition' => 'varchar(64) NULL'
405 ],
406 [
407 'name' => 'session',
408 'definition' => 'int(10) unsigned NOT NULL'
409 ],
410 [
411 'name' => 'created_time',
412 'definition' => 'datetime NOT NULL'
413 ],
414 [
415 'name' => 'updated_time',
416 'definition' => 'datetime NOT NULL'
417 ]
418 ],
419 'additional' => 'PRIMARY KEY (id), UNIQUE KEY name (name)',
420 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
421 ],
422 'userdomains' => [
423 'columns' => [
424 [
425 'name' => 'domain_id',
426 'definition' => 'int(10) unsigned NOT NULL'
427 ],
428 [
429 'name' => 'user_id',
430 'definition' => 'int(10) unsigned NOT NULL'
431 ]
432 ],
433 'additional' => 'PRIMARY KEY (domain_id, user_id)',
434 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
435 ],
436 'reports' => [
437 'columns' => [
438 [
439 'name' => 'id',
440 'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
441 ],
442 [
443 'name' => 'domain_id',
444 'definition' => 'int(10) NOT NULL'
445 ],
446 [
447 'name' => 'begin_time',
448 'definition' => 'datetime NOT NULL'
449 ],
450 [
451 'name' => 'end_time',
452 'definition' => 'datetime NOT NULL'
453 ],
454 [
455 'name' => 'loaded_time',
456 'definition' => 'datetime NOT NULL'
457 ],
458 [
459 'name' => 'org',
460 'definition' => 'varchar(255) NOT NULL'
461 ],
462 [
463 'name' => 'external_id',
464 'definition' => 'varchar(255) NOT NULL'
465 ],
466 [
467 'name' => 'email',
468 'definition' => 'varchar(255) NOT NULL'
469 ],
470 [
471 'name' => 'extra_contact_info',
472 'definition' => 'varchar(255) NULL'
473 ],
474 [
475 'name' => 'error_string',
476 'definition' => 'text NULL'
477 ],
478 [
479 'name' => 'policy_adkim',
480 'definition' => 'varchar(20) NULL'
481 ],
482 [
483 'name' => 'policy_aspf',
484 'definition' => 'varchar(20) NULL'
485 ],
486 [
487 'name' => 'policy_p',
488 'definition' => 'varchar(20) NULL'
489 ],
490 [
491 'name' => 'policy_sp',
492 'definition' => 'varchar(20) NULL'
493 ],
494 [
495 'name' => 'policy_np',
496 'definition' => 'varchar(20) NULL'
497 ],
498 [
499 'name' => 'policy_pct',
500 'definition' => 'varchar(20) NULL'
501 ],
502 [
503 'name' => 'policy_fo',
504 'definition' => 'varchar(20) NULL'
505 ],
506 [
507 'name' => 'seen',
508 'definition' => 'boolean NOT NULL'
509 ]
510 ],
511 'additional' => 'PRIMARY KEY (id),' .
512 ' UNIQUE KEY org_time_id_u (domain_id, begin_time, org, external_id),' .
513 ' KEY (begin_time), KEY (end_time),' .
514 ' KEY org (org, begin_time)',
515 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
516 ],
517 'rptrecords' => [
518 'columns' => [
519 [
520 'name' => 'id',
521 'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
522 ],
523 [
524 'name' => 'report_id',
525 'definition' => 'int(10) unsigned NOT NULL'
526 ],
527 [
528 'name' => 'ip',
529 'definition' => 'varbinary(16) NOT NULL'
530 ],
531 [
532 'name' => 'rcount',
533 'definition' => 'int(10) unsigned NOT NULL'
534 ],
535 [
536 'name' => 'disposition',
537 'definition' => 'tinyint unsigned NOT NULL'
538 ],
539 [
540 'name' => 'reason',
541 'definition' => 'text NULL'
542 ],
543 [
544 'name' => 'dkim_auth',
545 'definition' => 'text NULL'
546 ],
547 [
548 'name' => 'spf_auth',
549 'definition' => 'text NULL'
550 ],
551 [
552 'name' => 'dkim_align',
553 'definition' => 'tinyint unsigned NOT NULL'
554 ],
555 [
556 'name' => 'spf_align',
557 'definition' => 'tinyint unsigned NOT NULL'
558 ],
559 [
560 'name' => 'envelope_to',
561 'definition' => 'varchar(255) NULL'
562 ],
563 [
564 'name' => 'envelope_from',
565 'definition' => 'varchar(255) NULL'
566 ],
567 [
568 'name' => 'header_from',
569 'definition' => 'varchar(255) NULL'
570 ]
571 ],
572 'additional' => 'PRIMARY KEY (id), KEY (report_id), KEY (ip)',
573 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
574 ],
575 'reportlog' => [
576 'columns' => [
577 [
578 'name' => 'id',
579 'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
580 ],
581 [
582 'name' => 'user_id',
583 'definition' => 'int(10) unsigned NOT NULL DEFAULT 0'
584 ],
585 [
586 'name' => 'domain',
587 'definition' => 'varchar(255) NULL'
588 ],
589 [
590 'name' => 'external_id',
591 'definition' => 'varchar(255) NULL'
592 ],
593 [
594 'name' => 'event_time',
595 'definition' => 'datetime NOT NULL'
596 ],
597 [
598 'name' => 'filename',
599 'definition' => 'varchar(255) NULL'
600 ],
601 [
602 'name' => 'source',
603 'definition' => 'tinyint unsigned NOT NULL'
604 ],
605 [
606 'name' => 'success',
607 'definition' => 'boolean NOT NULL'
608 ],
609 [
610 'name' => 'message',
611 'definition' => 'text NULL'
612 ]
613 ],
614 'additional' => 'PRIMARY KEY (id), KEY(event_time), KEY user_id (user_id, event_time)',
615 'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
616 ]
617 ];
618 }