Add in software files and templates

This commit is contained in:
Brian Read 2023-06-21 14:19:40 +01:00
parent f42fdb947c
commit 5228fc5e9f
143 changed files with 23175 additions and 2 deletions

View File

@ -13,6 +13,9 @@ $event = 'smeserver-dmarc-srg-update';
foreach my $file (qw( foreach my $file (qw(
/etc/systemd/system-preset/49-koozali.preset /etc/systemd/system-preset/49-koozali.preset
/etc/httpd/conf/httpd.conf
/etc/cron.daily/dmarc-srg.cron
/opt/config/conf.php
)) ))
{ {
templates2events( $file, $event ); templates2events( $file, $event );
@ -22,7 +25,7 @@ event_link('systemd-default', $event, '10');
event_link('systemd-reload', $event, '50'); event_link('systemd-reload', $event, '50');
#services we might need to restart #services we might need to restart
#event_services(event, 'xxxx' => 'restart', 'yyyy' => 'restart'); event_services($event, 'httpd-e-smith' => 'restart');
#Backup contrib files #Backup contrib files
# backup_includes("smeserver-dmarc-srg", qw( # backup_includes("smeserver-dmarc-srg", qw(
@ -33,7 +36,7 @@ event_link('systemd-reload', $event, '50');
#Server manager entry #Server manager entry
#panel_link("smeserver-dmarc-srg", 'manager'); #panel_link("smeserver-dmarc-srg", 'manager');
#Events to smeserver-dmarc-srg #Events to smeserver-dmarc-srg
#$event = 'smeserver-dmarc-srg-smeserver-dmarc-srg'; #$event = 'smeserver-dmarc-srg-';
# safe_symlink("restart", "root/etc/e-smith/events/$event/services2adjust/smeserver-dmarc-srg"); # safe_symlink("restart", "root/etc/e-smith/events/$event/services2adjust/smeserver-dmarc-srg");
# templates2events("/etc/smeserver-dmarc-srg/smeserver-dmarc-srg.conf", $event); # templates2events("/etc/smeserver-dmarc-srg/smeserver-dmarc-srg.conf", $event);

View File

@ -0,0 +1,4 @@
#!/bin/bash
cd /opt/dmarc-srg
php80 utils/fetch_reports.php source=email
php80 utils/summary_report.php domain=bjsystems.co.uk period=lastweek

View File

@ -0,0 +1,2 @@
CREATE database dmarc;
GRANT all on dmarc.* to dmarc_user@localhost identified by '32katy55';

View File

@ -0,0 +1,27 @@
Alias /dmarc-srg /opt/dmarc-srg
ErrorLog /var/log/httpd/dmarc-srg-error.log
<Location /dmarc-srg>
AuthName "dmarc-srg"
AuthType Basic
AuthBasicProvider external
AuthExternal pwauth
require user admin
</Location>
<Directory /opt/dmarc-srg>
SSLRequireSSL
Options -Indexes
AllowOverride None
<RequireAll>
Require ip 127.0.0.1 192.168.100.0/255.255.255.0
</RequireAll>
AddType application/x-httpd-php .php
<FilesMatch .php$>
SetHandler "proxy:unix:/var/run/php-fpm/php80.sock|fcgi://localhost"
</FilesMatch>
# SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
</Directory>
<Directory /opt/dmarc-srg/utils/>
Require all denied
</Directory>

View File

@ -0,0 +1,130 @@
<?php
// Set 1 to enable debug messages
$debug = 1;
// Settings for assessing the database in which reports will be saved
$database = [
'host' => 'localhost',
'type' => 'mysql',
'name' => 'dmarc',
'user' => 'dmarc_user',
'password' => '32katy55',
/**
* This pamemeter can be usefull if the database is shared with other applications
* to avoid conflicting table names. You do not need to specify this parameter
* if you use a dedicated database.
* Example value: dmarc_
* Caution! Do not use an empty string as the table prefix value if you share the database with
* other applications.
* Caution! Do not change this parameter if you have already created the tables in the database
* because the tables will not be renamed automatically.
*/
'table_prefix' => ''
];
/**
* It is only required if you want to get reports from a mailbox automatically.
* In order to collect reports from several mailboxes, you should put each
* mailbox settings in an array.
*/
$mailboxes = [
// Just for displaying in web-admin. Not necessary.
'name' => 'Dmarc@bjsystems',
// Host of the email server. You can specify a port separated by a colon.
'host' => 'mail.bjsystems.co.uk',
// Connection encryption method. The valid values are:
// 'none' - without encryption (strongly not recommend).
// 'ssl' - SSL/TLS on a separate port, for IMAP it is usually port 993.
// 'starttls' - STARTTLS method, usually on the standard IMAP port 143. Default value.
'encryption' => 'ssl',
// Set true if you want to connect to the IMAP server without certificate validation
'novalidate-cert' => false,
// Mailbox user name.
'username' => 'dmarc',
// Mailbox password.
'password' => '32katy55',
// Mailbox name
'mailbox' => 'INBOX'
];
/**
* It is only required if you want to get reports from a server directory.
* In order to collect report from several directories, you should put each
* directory settings in an array. Processing of the directories is not recursive.
* It is recommended to use atomic methods for adding files to these directories.
* Attention! All successfully processed files will be deleted from the directories
* and all others will be moved to subdirectory `failed`, that will be created
* automatically if it does not exist.
*/
$directories = [
// Just for displaying in web-admin. Not necessary.
'name' => 'Rua-Dir',
// The directory location
'location' => '/var/spool/dmarc-srg/rua'
];
$admin = [
// Set this value to null or remove this parameter to disable authentication
// Note: The authentication is always failed with an empty password. Change it if you want to use the web ui.
];
//
$fetcher = [
'mailboxes' => [
// How many messages will be fetched at once maximum. 0 to disable any limiting.
'messages_maximum' => 0
],
'directories' => [
// How many report files will be processed at once maximum. 0 to disable any limiting.
'files_maximum' => 50
],
/**
* Domains matching this regular expression will be automatically added to the database from processed
* reports. This option does not affect domains that have already been added to the database.
* It is not necessary to use this option in most cases. The option can be useful if you have many domains
* or subdomains and do not want to add them manually in the GUI. An empty string or null doesn't match any domain.
* Note: The first domain from the first report will be automatically added anyway.
* Some examples:
* '.+\\.example\\.net$' - Matches any subdomain of the domain example.net
* '^mymail[0-9]+\\.net$' - Matches the domains mymail01.net, mymail02.net, mymail99999.net, etc.
*/
'allowed_domains' => ''
];
// Settings for sending summary reports if it is necessary.
// It uses in utils/summary_report.php
$mailer = [
'from' => 'postmaster@bjsystems.co.uk',
'default' => 'dmarc@bjsystems.co.uk'
];
//
$cleaner = [
// It is used in utils/mailbox_cleaner.php
'mailboxes' => [
// Will remove messages older than (days)
'days_old' => 30,
// How many messages will be removed at once maximum.
'delete_maximum' => 50,
// How many messages must be leave in the mailbox minimum.
'leave_minimum' => 100,
// Cleaning up the mailbox that failed reports are moved to. This box is also subject
// to the restrictions mentioned above. The valid values are:
// 'none' - no action with it. Default value.
// 'seen' - only seen messages will be removed
// 'any' - all messages will be removed
'failed' => 'none'
],
// It is used in utils/reports_cleaner.php
'reports' => [
'days_old' => 30,
'delete_maximum' => 50,
'leave_minimum' => 100
],
// It is used in utils/reportlog_cleaner.php
'reportlog' => [
'days_old' => 30,
'delete_maximum' => 50,
'leave_minimum' => 100
]
];

2
root/opt/dmarc-srg/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.phpunit*
config/conf.php

674
root/opt/dmarc-srg/LICENSE Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,137 @@
# DmarcSrg
A php parser, viewer and summary report generator for incoming DMARC reports.
## Features
* View a table of parsed reports;
* Easily identify potential DMARC related issues through colors;
* Filter report list by domain, month, reporting organization and more;
* View DKIM/SPF details for each report;
* Password protection of the web interface (can be disabled);
* Receiving and processing incoming DMARC reports from specified mailboxes;
* Receiving and processing incoming DMARC reports from specified server local directories;
* Uploading and processing incoming DMARC reports by using the web interface;
* Ability to configure deletion of old reports from the database and mailboxes;
* Generation of summary reports for the last week, last month or last N days and sending them to the specified mailbox;
* Uses AJAX calls to the backend; no external Javascript libraries are needed;
## Screenshots
### Screenshot: Report List
![Report list](/screenshots/dmarc-srg-report-list-small.png?raw=true "Screenshot: Report List")
[Larger version](/screenshots/dmarc-srg-report-list.png?raw=true)
### Screenshot: Report Detail
![Report detail](/screenshots/dmarc-srg-report-detail-small.png?raw=true "Screenshot: Report Detail")
[Larger version](/screenshots/dmarc-srg-report-detail.png?raw=true)
### Screenshot: Admin Panel
![Admin Panel](/screenshots/dmarc-srg-admin-panel-small.png?raw=true "Screenshot: Admin Panel")
[Larger version](/screenshots/dmarc-srg-admin-panel.png?raw=true)
## Installation and Configuration
Ensure that all the files are in their own sub-folder.
### Requirements
* MariaDB or MySQL
* PHP 7.3 or higher
* Installed php-mysql, php-xml, php-zip, php-json, and php-imap
* A working webserver (not necessary)
### Create the database
Login as mysql root user to the MariaDB/MySQL server using the shell, run:
`# mysql -u root -p`
and type the password.
Once you have a MariaDB or MySQL prompt, create a new database, where `dmarc` is a new database name (you can specify a different database name):
`CREATE database dmarc;`
Create a new user called `dmarc_user` for the new database (you can specify a different user name):
`GRANT all on dmarc.* to dmarc_user@localhost identified by 'new_user_password';`
**Remember** to replace `new_user_password` with a more secure one!
**Note:** If there is a need to use an existing database with other tables, you can specify the table prefix in the `conf/conf.php` file.
### conf.php
Copy `conf/conf.sample.php` to `conf/conf.php` and configure it. Learn more by reading the comments in it.
### Database initialization
There are two ways to do that: by using the web interface or by running the follow command:
`$ php utils/database_admin.php init`
**Note:** This command must be run from the directory which contains the directories classes and config.
## Usage
In general, DmarcSrg is designed to automatically receive incoming DMARC reports, process them and send summary reports to the specified e-mail address, so a web interface as well as a web-server is optional. Most of the work is done by periodically running php scripts, which are located in the utils directory.
### Utils
- `utils/check_config.php` - checks your configuration.
- `utils/database_admin.php` - performs some administration functions with the database.
- `utils/fetch_reports.php` - fetches DMARC reports from mailboxes and server local directories and saves them to the database.
- `utils/mailbox_cleaner.php` - deletes old DMARC report email messages in mailboxes.
- `utils/reportlog_cleaner.php` - deletes old log entries.
- `utils/reports_cleaner.php` - deletes old reports from the database.
- `utils/summary_report.php` - creates a summary report and sends it by email.
You can find more detailed information about each script in the comments to it.
**Note:** These scripts must be run from the directory which contains the directories classes and config.
**Note:** Despite the fact that these scripts can only be run from the console, it is recommended to close access to the utils directory from the web server.
For example, if you want to get a summary report for the last week, you should run a command like this:
`$ cd /usr/local/share/dmarc-srg && php utils/summary_report.php domain=example.com period=lastweek`
# Web interface
Navigate in your browser to the location of the `index.html` file. You will see the basic Report List view, allowing you to navigate through the reports that have been parsed. Using the menu go to the Admin section and create tables in the database and check the accessibility of the mailboxes if necessary.
If Content Security Policy (CSP) is used on your web server, it is enough to add the following permissions:
- style-src 'self';
- img-src 'self';
- script-src 'self';
- connect-src 'self';
- media-src 'self';
- form-action 'self';
That is, this rather strict policy will work well with the current web interface: `Content-Security-Policy: default-src 'none'; style-src 'self'; img-src 'self'; script-src 'self'; connect-src 'self'; media-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`
# How the report file processing works
## General rules for processing report files
- Only files of the following formats are accepted: zip, gzip, xml.
- Reports that do not have required fields (domain, time, org, id, records, and so on) are rejected.
- Reports that have already been accepted are also rejected.
- Reports for domains that are not listed in the database as allowed for processing are rejected. The first domain is automatically added to the database from the first correct report.
- For any attempt to download a report file, an entry is added to the internal log that can be viewed in the web interface (Administration --> Logs).
## Mailboxes
An IMAP connection is sequentially established to each mailbox, and the following actions are performed:
- Obtaining a list of unread messages.
- Checking the content of each message (number of attachments, attachment size, file extension).
- Extracting a report file from the message and parsing it and adding the report data to the database.
- If the report is successfully added to the database, the message is set as SEEN.
- If the report is rejected, the message remains marked as UNSEEN and is moved to the `failed` folder of the current mailbox. If the folder does not exist, it will be created.
**Note:** The total number of processed messages depends on the limit specified in the configuration file. The limitation is valid for each mail box separately.
## Local directories of the server
Each directory specified in the configuration file is scanned for presence of files in it (not recursively). Each file in each directory is processed as follows:
- Parsing the report file and adding the report data to the database.
- If the report is successfully added to the database, the file is removed from the directory.
- If the report is rejected, the file is moved to the `failed` subdirectory of the directory in which the file is currently located. If the subdirectory does not exist, it will be created.
**Note:** The total number of processed report files depends on the limit specified in the configuration file. The limitation is valid for each directory separately.
## Uploaded report files from the web interface
Uploading report files via the web interface is pretty standard. The upload result can be seen in a popup message and in the internal log. The number of simultaneously uploaded files and their size are limited only by the settings of your server (See `upload_max_filesize` and `post_max_size` in your `php.ini` file).

View File

@ -0,0 +1,87 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Exception\RuntimeException;
require 'init.php';
if (Core::isJson()) {
try {
$core = Core::instance();
$core->auth()->isAllowed();
if (Core::method() == 'GET') {
Core::sendJson($core->admin()->state());
return;
} elseif (Core::method() == 'POST') {
$data = Core::getJsonData();
if ($data) {
$cmd = $data['cmd'];
if (in_array($cmd, [ 'initdb', 'cleandb', 'upgradedb' ])) {
if ($core->auth()->isEnabled()) {
$pwd = isset($data['password']) ? $data['password'] : null;
$core->auth()->checkAdminPassword($pwd);
}
}
if ($cmd === 'initdb') {
Core::sendJson($core->database()->initDb());
return;
} elseif ($cmd === 'cleandb') {
Core::sendJson($core->database()->cleanDb());
return;
} elseif ($cmd === 'checksource') {
if (isset($data['id']) && isset($data['type'])) {
$id = $data['id'];
$type = $data['type'];
if (gettype($id) === 'integer' && gettype($type) === 'string') {
Core::sendJson(
$core->admin()->checkSource($id, $type)
);
return;
}
}
} elseif ($cmd === 'upgradedb') {
$db = Core::instance()->database();
$db->getMapper('upgrader')->go($db::REQUIRED_VERSION);
Core::sendJson(
[
'error_code' => 0,
'message' => 'Upgrated successfully'
]
);
return;
}
}
}
Core::sendJson([ 'error_code' => -1, 'message' => 'Bad request' ]);
} catch (RuntimeException $e) {
Core::sendJson(ErrorHandler::exceptionResult($e));
}
return;
} elseif (Core::method() == 'GET') {
Core::sendHtml();
return;
}
Core::sendBad();

View File

@ -0,0 +1,99 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains Admin class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Mail\MailBoxes;
use Liuch\DmarcSrg\Directories\DirectoryList;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* It's the main class for accessing administration functions.
*/
class Admin
{
private $core = null;
/**
* The constructor of the class
*
* @param Core $core Instace of the Core class
*/
public function __construct($core)
{
$this->core = $core;
}
/**
* Returns information about the database, directories, and mailboxes as an array.
*
* @return array Contains fields: `database`, `state`, `mailboxes`, `directories`.
*/
public function state(): array
{
$res = [];
$res['database'] = $this->core->database()->state();
$res['mailboxes'] = (new MailBoxes())->list();
$res['directories'] = array_map(function ($dir) {
return $dir->toArray();
}, (new DirectoryList())->list());
if ($res['database']['correct'] ?? false) {
$res['state'] = 'Ok';
} else {
$res['state'] = 'Err';
}
return $res;
}
/**
* Checks the availability of report sources.
*
* @param int $id Id of the checked source. If $id == 0 then all available sources with the passed type
* will be checked.
* @param string $type Type of the checked source.
*
* @return array Result array with `error_code` and `message` fields.
* For one resource and if there is no error,
* a field `status` will be added to the result.
*/
public function checkSource(int $id, string $type): array
{
switch ($type) {
case 'mailbox':
return (new MailBoxes())->check($id);
case 'directory':
return (new DirectoryList())->check($id);
}
throw new LogicException('Unknown resource type');
}
}

View File

@ -0,0 +1,147 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains Auth class.
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Exception\AuthException;
/**
* Class for working with authentication data.
*/
class Auth
{
private $core = null;
/**
* The constructor
*
* @param Core $core
*/
public function __construct(object $core)
{
$this->core = $core;
}
/**
* Checks if authentication is enabled.
*
* The method examines the key `password` in $admin array from the config file.
* It must exist and not be null.
*
* @return bool
*/
public function isEnabled(): bool
{
return $this->core->config('admin/password') !== null;
}
/**
* The authetication with a username and password.
*
* This method checks the password passed in $password and creates a user session.
* This method throws an exception if the passed password is wrong.
* The password with an empty string is always wrong!
*
* @param string $username - Must be an empty string, it is currently not used.
* @param string $password - Must not be an empty string.
*
* @return array Array with `error_code` and `message` fields.
*/
public function login(string $username, string $password): array
{
if ($username !== '' || $this->core->config('admin/password') === '' || !$this->isAdminPassword($password)) {
throw new AuthException('Authentication failed. Try again');
}
$this->core->userId(0);
return [
'error_code' => 0,
'message' => 'Authentication succeeded'
];
}
/**
* Removes the current user's session.
*
* @return array Array with `error_code` and `message` fields.
*/
public function logout(): array
{
$this->core->destroySession();
return [
'error_code' => 0,
'message' => 'Logged out successfully'
];
}
/**
* Checks if the user session exists.
*
* This method throws an exception if authentication needed.
*
* @return void
*/
public function isAllowed(): void
{
if ($this->isEnabled()) {
if ($this->core->userId() === false) {
throw new AuthException('Authentication needed', -2);
}
}
}
/**
* Checks if the passed password is the admin password.
*
* Throws an exception if the passed password is not the admin password.
*
* @param string $password Password to check
*
* @return void
*/
public function checkAdminPassword(string $password): void
{
if (!$this->isAdminPassword($password)) {
throw new AuthException('Incorrect password');
}
}
/**
* Checks if $password equals the admin password.
*
* @param string $password Password to check
*
* @return bool
*/
private function isAdminPassword(string $password): bool
{
return $password === $this->core->config('admin/password');
}
}

View File

@ -0,0 +1,50 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains common classes
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
/**
* Static common arrays
*/
class Common
{
/**
* This array needs for converting the align result text constant to integer value and back
* in Report and ReportList classes
*/
public static $align_res = [ 'fail', 'unknown', 'pass' ];
/**
* This array needs for converting the the disposition result text constant to integer value and back
* in Report and ReportList classes
*/
public static $disposition = [ 'reject', 'quarantine', 'none' ];
}

View File

@ -0,0 +1,89 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Config
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* This class is for storing configuration data to avoid using globas variables
*/
class Config
{
private $data = [];
/**
* The constructor
*
* @param string $config_file A php config file to load.
*/
public function __construct(string $config_file)
{
require($config_file);
foreach ([
'debug', 'database', 'mailboxes', 'directories',
'admin', 'mailer', 'fetcher', 'cleaner'
] as $key
) {
$this->data[$key] = $$key ?? null;
}
}
/**
* Returns config value by its name
*
* @param string $name Setting name. Hierarchy supported via '/'
* @param mixed $default Value to be returned if the required config item is missing or null
*
* @return mixed
*/
public function get(string $name, $default = null)
{
$nm_i = 0;
$path = explode('/', $name);
$data = $this->data;
do {
$key = $path[$nm_i++];
if (empty($key)) {
throw new LogicException('Incorrect setting name: ' .$name);
}
if (!isset($data[$key])) {
return $default;
}
$data = $data[$key];
if (!isset($path[$nm_i])) {
return $data ?? $default;
}
} while (gettype($data) === 'array');
return $default;
}
}

View File

@ -0,0 +1,362 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the Core class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* It's class for accessing to most methods for working with http, json data,
* the user session, getting instances of some classes
*/
class Core
{
public const APP_VERSION = '1.7';
private const SESSION_NAME = 'session';
private const HTML_FILE_NAME = 'index.html';
private $modules = [];
private static $instance = null;
/**
* The constructor
*
* @param array $params Array with modules to be bind to
*/
public function __construct($params)
{
foreach ([ 'admin', 'auth', 'config', 'database', 'ehandler', 'status' ] as $key) {
if (isset($params[$key])) {
$this->modules[$key] = $params[$key];
}
}
self::$instance = $this;
}
/**
* Returns the method of the current http request.
*
* @return string http method
*/
public static function method(): string
{
return $_SERVER['REQUEST_METHOD'];
}
/**
* Returns array of request headers in lowercase mode.
*
* @return array
*/
public static function getHeaders(): array
{
return array_change_key_case(getallheaders(), CASE_LOWER);
}
/**
* Sets or gets the current user's id
*
* In case $id is null, the method returns the current user's id.
* In case $id is integer value, the method sets this value as the current user's id.
* It returns false if there is an error.
*
* @param int|void $id User id to set it.
*
* @return int|bool User id or false in case of error.
*/
public function userId($id = null)
{
$start_f = false;
if ((self::cookie(self::SESSION_NAME) !== '' || $id !== null) && session_status() !== PHP_SESSION_ACTIVE) {
$start_f = true;
self::sessionStart();
}
$res = null;
if (gettype($id) === 'integer') {
$_SESSION['user_id'] = $id;
}
$res = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : false;
if ($start_f) {
session_write_close();
}
return $res;
}
/**
* Deletes the session of the current user and the corresponding cookie.
*
* @return void
*/
public function destroySession(): void
{
if (self::cookie(self::SESSION_NAME)) {
if (session_status() !== PHP_SESSION_ACTIVE) {
self::sessionStart();
}
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$scp = session_get_cookie_params();
$cep = [
'expires' => time() - 42000,
'path' => $scp['path'],
'domain' => $scp['domain'],
'secure' => $scp['secure'],
'httponly' => $scp['httponly'],
'samesite' => $scp['samesite']
];
setcookie(self::SESSION_NAME, '', $cep);
session_write_close();
}
}
}
/**
* Returns true if the http request asks for json data.
*
* @return bool
*/
public static function isJson(): bool
{
$headers = self::getHeaders();
return (isset($headers['accept']) && $headers['accept'] === 'application/json');
}
/**
* Sends the html file to the client.
*
* @return void
*/
public static function sendHtml(): void
{
if (file_exists(Core::HTML_FILE_NAME)) {
readfile(Core::HTML_FILE_NAME);
}
}
/**
* Sends data from an array as json string to the client.
*
* @param array $data - Data to send.
*
* @return void
*/
public static function sendJson(array $data): void
{
$res_str = json_encode($data);
if ($res_str === false) {
$res_str = '[]';
}
header('content-type: application/json; charset=UTF-8');
echo $res_str;
}
/**
* Sends a Bad Request response to the client.
*
* @return void
*/
public static function sendBad(): void
{
http_response_code(400);
echo 'Bad request';
}
/**
* Retrieves json data from the request and return it as an array.
*
* Returns an array with data or null if there is an error.
*
* @return array|null Data from the request
*/
public static function getJsonData()
{
$res = null;
$headers = self::getHeaders();
if (isset($headers['content-type']) && $headers['content-type'] === 'application/json') {
$str = file_get_contents('php://input');
if ($str) {
$res = json_decode($str, true);
}
}
return $res;
}
/**
* Returns an instance of the class Auth.
*
* @return Auth
*/
public function auth()
{
return $this->getModule('auth', true);
}
/**
* Returns an instance of the class Status.
*
* @return Status instance of Status
*/
public function status()
{
return $this->getModule('status', true);
}
/**
* Returns an instance of the class Admin.
*
* @return Admin instance of Admin
*/
public function admin()
{
return $this->getModule('admin', true);
}
/**
* Returns an instance of the class Database.
*
* @return DatabaseController
*/
public function database()
{
return $this->getModule('database', true);
}
/**
* Returns an instance of the class ErrorHandler
*
* @return ErrorHandler
*/
public function errorHandler()
{
return $this->getModule('ehandler', true);
}
/**
* Returns the current logger.
* Just a proxy method to return the logger from ErrorHandler
*
* @return LoggerInterface
*/
public function logger()
{
return $this->errorHandler()->logger();
}
/**
* Returns instance of the object
*
* @return self
*/
public static function instance()
{
return self::$instance;
}
/**
* Returns the config value by its name
*
* @param string $name Config item name. Hierarchy supported via '/'
* @param mixed $default Value to be returned if the required config item is missing or null
*
* @return mixed
*/
public function config(string $name, $default = null)
{
return $this->getModule('config', false)->get($name, $default);
}
/**
* Gets or sets a cookie with the specified name.
*
* @param string $name the cookie name to get or to set
* @param string|null $value
* @param array|null $params
*
* @return string|boolean The cookie value or false if there is an error
*/
private static function cookie($name, $value = null, $params = null)
{
if (!$value) {
return isset($_COOKIE[$name]) ? $_COOKIE[$name] : '';
}
if (setcookie($name, $value, $params)) {
return $value;
}
return false;
}
/**
* Starts the user session
*
* @return void
*/
private static function sessionStart(): void
{
if (!session_start(
[
'name' => self::SESSION_NAME,
'cookie_path' => dirname($_SERVER['REQUEST_URI']),
'cookie_httponly' => true,
'cookie_samesite' => 'Strict'
]
)
) {
throw new SoftException('Failed to start a user session');
}
}
/**
* Returns a module instance by its name. Lazy initialization is used.
*
* @param string $name Module name
* @param bool $core Whether to pass $this to the constructor
*
* @return object
*/
private function getModule(string $name, bool $core)
{
$module = $this->modules[$name] ?? null;
switch (gettype($module)) {
case 'array':
if ($core) {
$module = new $module[0]($this, ...($module[1] ?? []));
} else {
$module = new $module[0](...($module[1] ?? []));
}
$this->modules[$name] = $module;
break;
case 'NULL':
throw new LogicException('Attempt to initiate an unloaded module ' . $name);
}
return $module;
}
}

View File

@ -0,0 +1,543 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Database;
use Liuch\DmarcSrg\Settings\SettingString;
class Database
{
public const REQUIRED_VERSION = '2.0';
private $conn;
private static $instance = null;
private function __construct()
{
$this->conn = null;
$this->establishConnection();
}
public static function connection()
{
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance->conn;
}
public static function type()
{
global $database;
return $database['type'];
}
public static function name()
{
global $database;
return $database['name'];
}
public static function location()
{
global $database;
return $database['host'];
}
/**
* Returns the prefix for tables of the database
*
* @param string $postfix String to be concatenated with the prefix.
* Usually, this is a table name.
*
* @return string
*/
public static function tablePrefix(string $postfix = ''): string
{
global $database;
return ($database['table_prefix'] ?? '') . $postfix;
}
/**
* Returns information about the database as an array.
*
* @return array May contain the following fields:
* `tables` - an array of tables with their properties;
* `needs_upgrade` - true if the database needs upgrading;
* `correct` - true if the database is correct;
* `type` - the database type;
* `name` - the database name;
* `location` - the database location;
* `version` - the current version of the database structure;
* `message` - a state message;
* `error_code` - an error code;
*/
public static function state(): array
{
$res = [];
try {
$prefix = self::tablePrefix();
$p_len = strlen($prefix);
if ($p_len > 0) {
$like_str = ' WHERE NAME LIKE "' . str_replace('_', '\\_', $prefix) . '%"';
} else {
$like_str = '';
}
$db = self::connection();
$tables = [];
$st = $db->query(
'SHOW TABLE STATUS FROM `' . str_replace('`', '', self::name()) . '`' . $like_str
);
while ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
$tnm = $row['Name'];
$st2 = $db->query('SELECT COUNT(*) FROM `' . $tnm . '`');
$rows = $st2->fetch(\PDO::FETCH_NUM)[0];
$tables[substr($tnm, $p_len)] = [
'engine' => $row['Engine'],
'rows' => intval($rows),
'data_length' => intval($row['Data_length']),
'index_length' => intval($row['Index_length']),
'create_time' => $row['Create_time'],
'update_time' => $row['Update_time']
];
}
foreach (array_keys(self::$schema) as $table) {
if (!isset($tables[$table])) {
$tables[$table] = false;
}
}
$exist_sys = false;
$exist_cnt = 0;
$absent_cnt = 0;
$tables_res = [];
foreach ($tables as $tname => $tval) {
$t = null;
if ($tval) {
$t = $tval;
$t['exists'] = true;
if (isset(self::$schema[$tname])) {
$exist_cnt += 1;
$t['message'] = 'Ok';
if (!$exist_sys && $tname === 'system') {
$exist_sys = true;
}
} else {
$t['message'] = 'Unknown table';
}
} else {
$absent_cnt += 1;
$t = [
'error_code' => 1,
'message' => 'Not exist'
];
}
$t['name'] = $tname;
$tables_res[] = $t;
}
$res['tables'] = $tables_res;
$ver = $exist_sys ? (new SettingString('version'))->value() : null;
if ($exist_sys && $ver !== self::REQUIRED_VERSION) {
self::setDbMessage('The database structure needs upgrading', 0, $res);
$res['needs_upgrade'] = true;
} elseif ($absent_cnt == 0) {
$res['correct'] = true;
self::setDbMessage('Ok', 0, $res);
} else {
if ($exist_cnt == 0) {
self::setDbMessage('The database schema is not initiated', -1, $res);
} else {
self::setDbMessage('Incomplete set of the tables', -1, $res);
}
}
if ($ver) {
$res['version'] = $ver;
}
} catch (\Exception $e) {
$res['error_code'] = $e->getCode();
$res['message'] = $e->getMessage();
}
$res['type'] = self::type();
$res['name'] = self::name();
$res['location'] = self::location();
return $res;
}
/**
* Inites the database.
*
* This method creates needed tables and indexes in the database.
* The method will fail if the database already have tables with the table prefix.
*
* @return array Result array with `error_code` and `message` fields.
*/
public static function initDb(): array
{
try {
$db = self::connection();
$st = $db->query(self::sqlShowTablesQuery());
try {
if ($st->fetch()) {
if (empty(self::tablePrefix())) {
throw new \Exception('The database is not empty', -4);
} else {
throw new \Exception('Database tables already exist with the given prefix', -4);
}
}
foreach (array_keys(self::$schema) as $table) {
self::createDbTable(self::tablePrefix($table), self::$schema[$table]);
}
} finally {
$st->closeCursor();
}
$st = $db->prepare(
'INSERT INTO `' . self::tablePrefix('system') . '` (`key`, `value`) VALUES ("version", ?)'
);
$st->bindValue(1, self::REQUIRED_VERSION, \PDO::PARAM_STR);
$st->execute();
$st->closeCursor();
} catch (\Exception $e) {
return [
'error_code' => $e->getCode(),
'message' => $e->getMessage()
];
}
return [ 'message' => 'The database has been initiated' ];
}
/**
* Cleans up the database.
*
* Drops tables with the table prefix in the database or all tables in the database if no table prefix is set.
*
* @return array Result array with `error_code` and `message` fields.
*/
public static function dropTables(): array
{
try {
$db = self::connection();
$db->query('SET foreign_key_checks = 0');
$st = $db->query(self::sqlShowTablesQuery());
while ($table = $st->fetchColumn(0)) {
$db->query('DROP TABLE `' . $table . '`');
}
$st->closeCursor();
$db->query('SET foreign_key_checks = 1');
} catch (\PDOException $e) {
return [
'error_code' => $e->getCode(),
'message' => $e->getMessage()
];
}
return [ 'message' => 'Database tables have been dropped' ];
}
private function establishConnection()
{
global $database;
try {
$dsn = "{$database['type']}:host={$database['host']};dbname={$database['name']};charset=utf8";
$this->conn = new \PDO(
$dsn,
$database['user'],
$database['password'],
[ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ]
);
$this->conn->query('SET time_zone = "+00:00"');
} catch (\Exception $e) {
throw new \Exception($e->getMessage(), -1);
}
}
/**
* Return SHOW TABLES SQL query string for tables with the table prefix
*
* @return string
*/
private static function sqlShowTablesQuery(): string
{
$res = 'SHOW TABLES';
$prefix = self::tablePrefix();
if (strlen($prefix) > 0) {
$res .= ' WHERE `tables_in_' . str_replace('`', '', self::name())
. '` LIKE "' . str_replace('_', '\\_', $prefix) . '%"';
}
return $res;
}
/**
* Creates a table in the database.
*
* @param string $name Table name
* @param array $definitions Table structure
*
* @return void
*/
private static function createDbTable(string $name, array $definitions): void
{
$query = 'CREATE TABLE `' . $name . '` (';
$col_num = 0;
foreach ($definitions['columns'] as $column) {
if ($col_num > 0) {
$query .= ', ';
}
$query .= '`' . $column['name'] . '` ' . $column['definition'];
$col_num += 1;
}
$query .= ', ' . $definitions['additional'] . ') ' . $definitions['table_options'];
self::connection()->query($query);
}
/**
* Sets the database message and error code for the state array
*
* @param string $message Message string
* @param int $err_code Error code
* @param array $state Database state array
*
* @return void
*/
private static function setDbMessage(string $message, int $err_code, array &$state): void
{
$state['message'] = $message;
if ($err_code !== 0) {
$state['error_code'] = $err_code;
}
}
private static $schema = [
'system' => [
'columns' => [
[
'name' => 'key',
'definition' => 'varchar(64) NOT NULL'
],
[
'name' => 'value',
'definition' => 'varchar(255) DEFAULT NULL'
]
],
'additional' => 'PRIMARY KEY (`key`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'domains' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'fqdn',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'active',
'definition' => 'boolean NOT NULL'
],
[
'name' => 'description',
'definition' => 'TEXT NULL'
],
[
'name' => 'created_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'updated_time',
'definition' => 'datetime NOT NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), UNIQUE KEY `fqdn` (`fqdn`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'reports' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'domain_id',
'definition' => 'int(10) NOT NULL'
],
[
'name' => 'begin_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'end_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'loaded_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'org',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'external_id',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'email',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'extra_contact_info',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'error_string',
'definition' => 'text NULL'
],
[
'name' => 'policy_adkim',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_aspf',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_p',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_sp',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_pct',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_fo',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'seen',
'definition' => 'boolean NOT NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), UNIQUE KEY `external_id` (`domain_id`, `external_id`), KEY (`begin_time`), KEY (`end_time`), KEY `org` (`org`, `begin_time`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'rptrecords' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'report_id',
'definition' => 'int(10) unsigned NOT NULL'
],
[
'name' => 'ip',
'definition' => 'varbinary(16) NOT NULL'
],
[
'name' => 'rcount',
'definition' => 'int(10) unsigned NOT NULL'
],
[
'name' => 'disposition',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'reason',
'definition' => 'text NULL'
],
[
'name' => 'dkim_auth',
'definition' => 'text NULL'
],
[
'name' => 'spf_auth',
'definition' => 'text NULL'
],
[
'name' => 'dkim_align',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'spf_align',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'envelope_to',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'envelope_from',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'header_from',
'definition' => 'varchar(255) NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), KEY (`report_id`), KEY (`ip`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'reportlog' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'domain',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'external_id',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'event_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'filename',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'source',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'success',
'definition' => 'boolean NOT NULL'
],
[
'name' => 'message',
'definition' => 'text NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), KEY(`event_time`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
]
];
}

View File

@ -0,0 +1,131 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the abstract DatabaseConnector class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
use Liuch\DmarcSrg\Exception\LogicException;
abstract class DatabaseConnector
{
protected static $names = [
'domain' => 'DomainMapper',
'report' => 'ReportMapper',
'report-log' => 'ReportLogMapper',
'setting' => 'SettingMapper',
'statistics' => 'StatisticsMapper',
'upgrader' => 'UpgraderMapper'
];
protected $host = null;
protected $name = null;
protected $user = null;
protected $password = null;
protected $prefix = '';
protected $mappers = [];
/**
* The constructor
*
* @param array $conf Configuration data from the conf.php file
*/
public function __construct(array $conf)
{
$this->host = $conf['host'] ?? '';
$this->name = $conf['name'] ?? '';
$this->user = $conf['user'] ?? '';
$this->password = $conf['password'] ?? '';
$this->prefix = $conf['table_prefix'] ?? '';
}
/**
* Returns an instance of PDO class
*
* @return PDO
*/
abstract public function dbh(): object;
/**
* Returns the database state as an array
*
* @return array
*/
abstract public function state(): array;
/**
* Returns a data mapper by its name.
*
* @param string $name Mapper name
*
* @return object
*/
public function getMapper(string $name): object
{
if (isset($this->mappers[$name])) {
return $this->mappers[$name];
}
if (!isset(self::$names[$name])) {
throw new LogicException('Unknown mapper name: ' . $name);
}
$mapper_name = (new \ReflectionClass($this))->getNamespaceName() . '\\' . self::$names[$name];
$mapper = new $mapper_name($this);
$this->mappers[$name] = $mapper;
return $mapper;
}
/**
* Inites the database.
*
* @return void
*/
abstract public function initDb(string $version): void;
/**
* Cleans up the database
*
* @return void
*/
abstract public function cleanDb(): void;
/**
* Returns the prefix for tables of the database
*
* @param string $postfix String to be concatenated with the prefix.
* Usually, this is a table name.
*
* @return string
*/
public function tablePrefix(string $postfix = ''): string
{
return $this->prefix . $postfix;
}
}

View File

@ -0,0 +1,184 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the DatabaseController class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
use Liuch\DmarcSrg\Exception\RuntimeException;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
/**
* Proxy class for accessing a database of the selected type
*/
class DatabaseController
{
public const REQUIRED_VERSION = '3.0';
private $conf_data = null;
private $connector = null;
/**
* The constructor
*
* @param Core $core Instace of the Core class
* @param class $connector The connector class of the current database
*/
public function __construct($core, $connector = null)
{
$this->conf_data = $core->config('database');
$this->connector = $connector;
}
/**
* Returns the database type
*
* @return string
*/
public function type(): string
{
return $this->conf_data['type'] ?? '';
}
/**
* Returns the database name
*
* @return string
*/
public function name(): string
{
return $this->conf_data['name'] ?? '';
}
/**
* Returns the database host
*
* @return string
*/
public function location(): string
{
return $this->conf_data['host'] ?? '';
}
/**
* Returns information about the database as an array.
*
* @return array May contain the following fields:
* `tables` - an array of tables with their properties;
* `needs_upgrade` - true if the database needs upgrading;
* `correct` - true if the database is correct;
* `type` - the database type;
* `name` - the database name;
* `location` - the database location;
* `version` - the current version of the database structure;
* `message` - a state message;
* `error_code` - an error code;
*/
public function state(): array
{
$this->ensureConnector();
$res = $this->connector->state();
$res['type'] = $this->type();
$res['name'] = $this->name();
$res['location'] = $this->location();
if (($res['correct'] ?? false) && ($res['version'] ?? 'null') !== self::REQUIRED_VERSION) {
$res['correct'] = false;
$res['message'] = 'The database structure needs upgrading';
$res['needs_upgrade'] = true;
}
return $res;
}
/**
* Inites the database.
*
* This method creates needed tables and indexes in the database.
* The method will fail if the database already have tables with the table prefix.
*
* @return array Result array with `error_code` and `message` fields.
*/
public function initDb(): array
{
$this->ensureConnector();
$this->connector->initDb(self::REQUIRED_VERSION);
return [ 'message' => 'The database has been initiated' ];
}
/**
* Cleans up the database.
*
* Drops tables with the table prefix in the database or all tables in the database if no table prefix is set.
*
* @return array Result array with `error_code` and `message` fields.
*/
public function cleanDb(): array
{
$this->ensureConnector();
$this->connector->cleanDb();
return [ 'message' => 'The database tables have been dropped' ];
}
/**
* Returns a data mapper by its name from the current database connector
*
* @param string $name Mapper name
*
* @return object
*/
public function getMapper(string $name): object
{
$this->ensureConnector();
return $this->connector->getMapper($name);
}
/**
* Finds the connector of the specified database type and initializes it
* if it hasn't already been initialized
*
* @return void
*/
private function ensureConnector(): void
{
if (!$this->connector) {
switch ($this->conf_data['type']) {
case 'mysql':
case 'mariadb':
$type = 'mariadb';
break;
default:
throw new RuntimeException('Unknown database type: ' . $this->conf_data['type']);
$type = null;
break;
}
$c_name = __NAMESPACE__ . '\\' . \ucfirst($type) . '\\Connector';
$this->connector = new $c_name($this->conf_data);
}
}
}

View File

@ -0,0 +1,121 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Database;
use PDO;
use Exception;
use Liuch\DmarcSrg\Settings\SettingString;
class DatabaseUpgrader
{
public static function go()
{
$ver = (new SettingString('version'))->value();
if ($ver == '') {
$ver = 'null';
}
while ($ver !== Database::REQUIRED_VERSION) {
if (!isset(self::$upways['ver_' . $ver])) {
throw new Exception('Upgrading failed: There is no way to upgrade from ' . $ver . ' to ' . Database::REQUIRED_VERSION, -1);
}
$um = self::$upways['ver_' . $ver];
$ver = self::$um();
}
}
private static $upways = [
'ver_null' => 'upNull',
'ver_0.1' => 'up01',
'ver_1.0' => 'up10'
];
private static function upNull()
{
$db = Database::connection();
$db->beginTransaction();
try {
$db->query(
'INSERT INTO `' . Database::tablePrefix('system') . '` (`key`, `value`) VALUES ("version", "0.1")'
);
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
return '0.1';
}
private static function up01()
{
$db = Database::connection();
$db->beginTransaction();
try {
$dom_tn = Database::tablePrefix('domains');
if (!self::columnExists($db, $dom_tn, 'active')) {
$db->query('ALTER TABLE `' . $dom_tn . '` ADD COLUMN `active` boolean NOT NULL AFTER `fqdn`');
}
if (!self::columnExists($db, $dom_tn, 'created_time')) {
$db->query('ALTER TABLE `' . $dom_tn . '` ADD COLUMN `created_time` datetime NOT NULL');
}
if (!self::columnExists($db, $dom_tn, 'updated_time')) {
$db->query('ALTER TABLE `' . $dom_tn . '` ADD COLUMN `updated_time` datetime NOT NULL');
}
$db->query('UPDATE `' . $dom_tn . '` SET `active` = TRUE, `created_time` = NOW(), `updated_time` = NOW()');
$db->query('UPDATE `' . Database::tablePrefix('system') . '` SET `value` = "1.0" WHERE `key` = "version"');
$db->commit();
} catch (Exception $e) {
$db->rollBack();
throw $e;
}
return '1.0';
}
private static function up10()
{
$db = Database::connection();
$db->beginTransaction();
try {
$sys_tn = Database::tablePrefix('system');
$db->query('ALTER TABLE `' . $sys_tn . '` MODIFY COLUMN `key` varchar(64) NOT NULL');
$db->query('UPDATE `' . $sys_tn . '` SET `value` = "2.0" WHERE `key` = "version"');
$db->commit();
} catch (Exception $d) {
$db->rollBack();
throw $e;
}
return '2.0';
}
private static function columnExists($db, $table, $column)
{
$st = $db->prepare('SELECT NULL FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `table_schema` = ? AND `table_name` = ? AND `column_name` = ?');
$st->bindValue(1, Database::name(), PDO::PARAM_STR);
$st->bindValue(2, $table, PDO::PARAM_STR);
$st->bindValue(3, $column, PDO::PARAM_STR);
$st->execute();
$res = $st->fetch(PDO::FETCH_NUM);
$st->closeCursor();
return $res ? true : false;
}
}

View File

@ -0,0 +1,96 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the DomainMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface DomainMapperInterface
{
/**
* Return true if the domain exists or false otherwise.
*
* @param array $data Array with domain data to search
*
* @return bool
*/
public function exists(array &$data): bool;
/**
* Fetch the domain data from the database by its id or name
*
* @param array $data Domain data to update
*
* @return void
*/
public function fetch(array &$data): void;
/**
* Saves domain data to the database (updates or inserts an record)
*
* @param array $data Domain data
*
* @return void
*/
public function save(array &$data): void;
/**
* Deletes the domain from the database
*
* Deletes the domain if there are no reports for this domain in the database.
*
* @param array $data Domain data
*
* @return void
*/
public function delete(array &$data): void;
/**
* Returns a list of domains data from the database
*
* @return array
*/
public function list(): array;
/**
* Returns an ordered array with domain names from the database
*
* @return array
*/
public function names(): array;
/**
* Returns the total number of domains in the database
*
* @param int $max The maximum number of records to count. 0 means no limitation.
*
* @return int The total number of domains
*/
public function count(int $max = 0): int;
}

View File

@ -0,0 +1,511 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the DatabaseConnector class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Database\DatabaseConnector;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\RuntimeException;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseExceptionFactory;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
class Connector extends DatabaseConnector
{
protected $dbh = null;
/**
* Returns an instance of PDO class
*
* @return \PDO
*/
public function dbh(): object
{
$this->ensureConnection();
return $this->dbh;
}
/**
* Returns the name of the database
*
* @return string
*/
public function dbName(): string
{
return $this->name;
}
/**
* Returns information about the database as an array.
*
* @return array May contain the following fields:
* `tables` - an array of tables with their properties;
* `correct` - true if the database is correct;
* `version` - the current version of the database structure;
* `message` - a state message;
* `error_code` - an error code;
*/
public function state(): array
{
$this->ensureConnection();
$res = [];
$p_len = strlen($this->prefix);
if ($p_len > 0) {
$like_str = ' WHERE NAME LIKE "' . str_replace('_', '\\_', $this->prefix) . '%"';
} else {
$like_str = '';
}
try {
$tables = [];
$st = $this->dbh->query(
'SHOW TABLE STATUS FROM `' . str_replace('`', '', $this->name) . '`' . $like_str
);
while ($row = $st->fetch(\PDO::FETCH_ASSOC)) {
$tname = $row['Name'];
$rcnt = $this->dbh->query('SELECT COUNT(*) FROM `' . $tname . '`')->fetch(\PDO::FETCH_NUM)[0];
$tables[substr($tname, $p_len)] = [
'engine' => $row['Engine'],
'rows' => intval($rcnt),
'data_length' => intval($row['Data_length']),
'index_length' => intval($row['Index_length']),
'create_time' => $row['Create_time'],
'update_time' => $row['Update_time']
];
}
foreach (array_keys(self::$schema) as $table) {
if (!isset($tables[$table])) {
$tables[$table] = false;
}
}
$exist_cnt = 0;
$absent_cnt = 0;
$tables_res = [];
foreach ($tables as $tname => $tval) {
$t = null;
if ($tval) {
$t = $tval;
$t['exists'] = true;
if (isset(self::$schema[$tname])) {
++$exist_cnt;
$t['message'] = 'Ok';
} else {
$t['message'] = 'Unknown table';
}
} else {
++$absent_cnt;
$t = [
'error_code' => 1,
'message' => 'Not exist'
];
}
$t['name'] = $tname;
$tables_res[] = $t;
}
$res['tables'] = $tables_res;
if ($absent_cnt === 0) {
$res['correct'] = true;
$res['message'] = 'Ok';
try {
$res['version'] = $this->getMapper('setting')->value('version');
} catch (DatabaseNotFoundException $e) {
}
} else {
$res['error_code'] = -1;
if ($exist_cnt == 0) {
$res['message'] = 'The database schema is not initiated';
} else {
$res['message'] = 'Incomplete set of the tables';
}
}
} catch (\PDOException $e) {
$res = array_replace($res, ErrorHandler::exceptionResult(
new DatabaseFatalException('Failed to get the database information', -1, $e)
));
} catch (RuntimeException $e) {
$res = array_replace($res, ErrorHandler::exceptionResult($e));
}
return $res;
}
/**
* Inites the database.
*
* This method creates needed tables and indexes in the database.
* The method will fail if the database already have tables with the table prefix.
*
* @param $version The current version of the database schema
*
* @return void
*/
public function initDb(string $version): void
{
$this->ensureConnection();
try {
$st = $this->dbh->query($this->sqlShowTablesQuery());
try {
if ($st->fetch()) {
if (empty($this->tablePrefix())) {
throw new SoftException('The database is not empty', -4);
} else {
throw new SoftException('Database tables already exist with the given prefix', -4);
}
}
foreach (self::$schema as $t_name => &$t_schema) {
$this->createDbTable($this->tablePrefix($t_name), $t_schema);
}
unset($t_schema);
} finally {
$st->closeCursor();
}
$st = $this->dbh->prepare(
'INSERT INTO `' . $this->tablePrefix('system') . '` (`key`, `value`) VALUES ("version", ?)'
);
$st->bindValue(1, $version, \PDO::PARAM_STR);
$st->execute();
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to create required tables in the database', -1, $e);
}
}
/**
* Cleans up the database
*
* Drops tables with the table prefix in the database or all tables in the database
* if no table prefix is set.
*
* @return void
*/
public function cleanDb(): void
{
$this->ensureConnection();
try {
$db = $this->dbh;
$db->query('SET foreign_key_checks = 0');
$st = $db->query($this->sqlShowTablesQuery());
while ($table = $st->fetchColumn(0)) {
$db->query('DROP TABLE `' . $table . '`');
}
$st->closeCursor();
$db->query('SET foreign_key_checks = 1');
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to drop the database tables', -1, $e);
}
}
/**
* Sets the database connection if it hasn't connected yet.
*
* @return void
*/
private function ensureConnection(): void
{
if (!$this->dbh) {
try {
$this->dbh = new \PDO(
"mysql:host={$this->host};dbname={$this->name};charset=utf8",
$this->user,
$this->password,
[ \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ]
);
$this->dbh->query('SET time_zone = "+00:00"');
} catch (\PDOException $e) {
throw DatabaseExceptionFactory::fromException($e);
}
}
}
/**
* Return SHOW TABLES SQL query string for tables with the table prefix
*
* @return string
*/
private function sqlShowTablesQuery(): string
{
$res = 'SHOW TABLES';
$prefix = $this->tablePrefix();
if (strlen($prefix) > 0) {
$res .= ' WHERE `tables_in_' . str_replace('`', '', $this->name)
. '` LIKE "' . str_replace('_', '\\_', $prefix) . '%"';
}
return $res;
}
/**
* Creates a table in the database.
*
* @param string $name Table name
* @param array $definitions Table structure
*
* @return void
*/
private function createDbTable(string $name, array $definitions): void
{
$query = 'CREATE TABLE `' . $name . '` (';
$col_num = 0;
foreach ($definitions['columns'] as $column) {
if ($col_num > 0) {
$query .= ', ';
}
$query .= '`' . $column['name'] . '` ' . $column['definition'];
$col_num += 1;
}
$query .= ', ' . $definitions['additional'] . ') ' . $definitions['table_options'];
$this->dbh->query($query);
}
private static $schema = [
'system' => [
'columns' => [
[
'name' => 'key',
'definition' => 'varchar(64) NOT NULL'
],
[
'name' => 'value',
'definition' => 'varchar(255) DEFAULT NULL'
]
],
'additional' => 'PRIMARY KEY (`key`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'domains' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'fqdn',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'active',
'definition' => 'boolean NOT NULL'
],
[
'name' => 'description',
'definition' => 'TEXT NULL'
],
[
'name' => 'created_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'updated_time',
'definition' => 'datetime NOT NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), UNIQUE KEY `fqdn` (`fqdn`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'reports' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'domain_id',
'definition' => 'int(10) NOT NULL'
],
[
'name' => 'begin_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'end_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'loaded_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'org',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'external_id',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'email',
'definition' => 'varchar(255) NOT NULL'
],
[
'name' => 'extra_contact_info',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'error_string',
'definition' => 'text NULL'
],
[
'name' => 'policy_adkim',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_aspf',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_p',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_sp',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_np',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_pct',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'policy_fo',
'definition' => 'varchar(20) NULL'
],
[
'name' => 'seen',
'definition' => 'boolean NOT NULL'
]
],
'additional' => 'PRIMARY KEY (`id`),' .
' UNIQUE KEY `external_id` (`domain_id`, `external_id`),' .
' KEY (`begin_time`), KEY (`end_time`),' .
' KEY `org` (`org`, `begin_time`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'rptrecords' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'report_id',
'definition' => 'int(10) unsigned NOT NULL'
],
[
'name' => 'ip',
'definition' => 'varbinary(16) NOT NULL'
],
[
'name' => 'rcount',
'definition' => 'int(10) unsigned NOT NULL'
],
[
'name' => 'disposition',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'reason',
'definition' => 'text NULL'
],
[
'name' => 'dkim_auth',
'definition' => 'text NULL'
],
[
'name' => 'spf_auth',
'definition' => 'text NULL'
],
[
'name' => 'dkim_align',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'spf_align',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'envelope_to',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'envelope_from',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'header_from',
'definition' => 'varchar(255) NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), KEY (`report_id`), KEY (`ip`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
],
'reportlog' => [
'columns' => [
[
'name' => 'id',
'definition' => 'int(10) unsigned NOT NULL AUTO_INCREMENT'
],
[
'name' => 'domain',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'external_id',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'event_time',
'definition' => 'datetime NOT NULL'
],
[
'name' => 'filename',
'definition' => 'varchar(255) NULL'
],
[
'name' => 'source',
'definition' => 'tinyint unsigned NOT NULL'
],
[
'name' => 'success',
'definition' => 'boolean NOT NULL'
],
[
'name' => 'message',
'definition' => 'text NULL'
]
],
'additional' => 'PRIMARY KEY (`id`), KEY(`event_time`)',
'table_options' => 'ENGINE=InnoDB DEFAULT CHARSET=utf8'
]
];
}

View File

@ -0,0 +1,332 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the DomainMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\DateTime;
use Liuch\DmarcSrg\Database\DomainMapperInterface;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* DomainMapper class implementation for MariaDB
*/
class DomainMapper implements DomainMapperInterface
{
private $connector = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Return true if the domain exists or false otherwise.
*
* @param array $data Array with domain data to search
*
* @return bool
*/
public function exists(array &$data): bool
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `id` FROM `' . $this->connector->tablePrefix('domains') .
'` WHERE ' . $this->sqlCondition($data)
);
$this->sqlBindValue($st, 1, $data);
$st->execute();
$res = $st->fetch(\PDO::FETCH_NUM);
$st->closeCursor();
if (!$res) {
return false;
}
$data['id'] = intval($res[0]);
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get domain ID', -1, $e);
}
return true;
}
/**
* Fetch the domain data from the database by its id or name
*
* @param array $data Domain data to update
*
* @return void
*/
public function fetch(array &$data): void
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `id`, `fqdn`, `active`, `description`, `created_time`, `updated_time` FROM `'
. $this->connector->tablePrefix('domains') . '` WHERE ' . $this->sqlCondition($data)
);
$this->sqlBindValue($st, 1, $data);
$st->execute();
$res = $st->fetch(\PDO::FETCH_NUM);
$st->closeCursor();
if (!$res) {
throw new DatabaseNotFoundException('Domain not found');
}
$data['id'] = intval($res[0]);
$data['fqdn'] = $res[1];
$data['active'] = boolval($res[2]);
$data['description'] = $res[3];
$data['created_time'] = new DateTime($res[4]);
$data['updated_time'] = new DateTime($res[5]);
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to fetch the domain data', -1, $e);
}
}
/**
* Saves domain data to the database (updates or inserts an record)
*
* @param array $data Domain data
*
* @return void
*/
public function save(array &$data): void
{
$db = $this->connector->dbh();
$data['updated_time'] = new DateTime();
if ($this->exists($data)) {
try {
$st = $db->prepare(
'UPDATE `' . $this->connector->tablePrefix('domains')
. '` SET `active` = ?, `description` = ?, `updated_time` = ? WHERE `id` = ?'
);
$st->bindValue(1, $data['active'], \PDO::PARAM_BOOL);
$st->bindValue(2, $data['description'], \PDO::PARAM_STR);
$st->bindValue(3, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(4, $data['id'], \PDO::PARAM_INT);
$st->execute();
$st->closeCursor();
} catch (\PDOException $e) {
throw new DababaseException('Failed to update the domain data', -1, $e);
}
} else {
try {
$active = $data['active'] ?? false;
$data['created_time'] = $data['updated_time'];
if (is_null($data['description'])) {
$sql1 = '';
$sql2 = '';
} else {
$sql1 = ', `description`';
$sql2 = ', ?';
}
$st = $db->prepare(
'INSERT INTO `' . $this->connector->tablePrefix('domains')
. '` (`fqdn`, `active`' . $sql1 . ', `created_time`, `updated_time`)'
. ' VALUES (?, ?' . $sql2 . ', ?, ?)'
);
$idx = 0;
$st->bindValue(++$idx, $data['fqdn'], \PDO::PARAM_STR);
$st->bindValue(++$idx, $active, \PDO::PARAM_BOOL);
if (!is_null($data['description'])) {
$st->bindValue(++$idx, $data['description'], \PDO::PARAM_STR);
}
$st->bindValue(++$idx, $data['created_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(++$idx, $data['updated_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->execute();
$st->closeCursor();
$data['id'] = intval($db->lastInsertId());
$data['active'] = $active;
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to insert the domain data', -1, $e);
}
}
}
/**
* Deletes the domain from the database
*
* Deletes the domain if there are no reports for this domain in the database.
*
* @param array $data Domain data
*
* @return void
*/
public function delete(array &$data): void
{
$db = $this->connector->dbh();
$db->beginTransaction();
try {
$filter = [ 'domain' => $data['id'] ];
$limit = [ 'offset' => 0, 'count' => 0 ];
$r_count = $this->connector->getMapper('report')->count($filter, $limit);
if ($r_count > 0) {
switch ($r_count) {
case 1:
$s1 = 'is';
$s2 = '';
break;
default:
$s1 = 'are';
$s2 = 's';
break;
}
throw new SoftException(
"Failed to delete: there {$s1} {$r_count} incoming report{$s2} for this domain"
);
}
$st = $db->prepare('DELETE FROM `' . $this->connector->tablePrefix('domains') . '` WHERE `id` = ?');
$st->bindValue(1, $data['id'], \PDO::PARAM_INT);
$st->execute();
$st->closeCursor();
$db->commit();
} catch (\PDOException $e) {
$db->rollBack();
throw new DatabaseFatalException('Failed to delete the domain', -1, $e);
} catch (\Exception $e) {
$db->rollBack();
throw $e;
}
}
/**
* Returns a list of domains data from the database
*
* @return array
*/
public function list(): array
{
$list = [];
try {
$st = $this->connector->dbh()->query(
'SELECT `id`, `fqdn`, `active`, `description`, `created_time`, `updated_time` FROM `'
. $this->connector->tablePrefix('domains') . '`'
);
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$list[] = [
'id' => intval($row[0]),
'fqdn' => $row[1],
'active' => boolval($row[2]),
'description' => $row[3],
'created_time' => new DateTime($row[4]),
'updated_time' => new DateTime($row[5])
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the domain list', -1, $e);
}
return $list;
}
/**
* Returns an ordered array with domain names from the database
*
* @return array
*/
public function names(): array
{
$res = [];
try {
$st = $this->connector->dbh()->query(
'SELECT `fqdn` FROM `' . $this->connector->tablePrefix('domains') . '` ORDER BY `fqdn`',
\PDO::FETCH_NUM
);
while ($name = $st->fetchColumn(0)) {
$res[] = $name;
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get a list of domain names', -1, $e);
}
return $res;
}
/**
* Returns the total number of domains in the database
*
* @param int $max The maximum number of records to count. 0 means no limitation.
*
* @return int The total number of domains
*/
public function count(int $max = 0): int
{
$number = 0;
try {
$query_str = 'SELECT COUNT(*) FROM `' . $this->connector->tablePrefix('domains') . '`';
if ($max > 0) {
$query_str .= " LIMIT {$max}";
}
$st = $this->connector->dbh()->query($query_str, \PDO::FETCH_NUM);
$number = intval($st->fetchColumn(0));
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the number of domains', -1, $e);
}
return $number;
}
/**
* Returns a condition string for a WHERE statement based on existing domain data
*
* @param array $data Domain data
*
* @return string Condition string
*/
private function sqlCondition(array &$data): string
{
if (isset($data['id'])) {
return '`id` = ?';
}
return '`fqdn` = ?';
}
/**
* Binds values for SQL queries based on existing domain data
*
* @param PDOStatement $st PDO Statement to bind to
* @param ind $pos Start position for binding
* @param array $data Domain data
*
* @return void
*/
private function sqlBindValue($st, int $pos, array &$data): void
{
if (isset($data['id'])) {
$st->bindValue($pos, $data['id'], \PDO::PARAM_INT);
} else {
$st->bindValue($pos, $data['fqdn'], \PDO::PARAM_STR);
}
}
}

View File

@ -0,0 +1,311 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the ReportLogMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\DateTime;
use Liuch\DmarcSrg\Database\ReportLogMapperInterface;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* ReportLogMapper class implementation for MariaDB
*/
class ReportLogMapper implements ReportLogMapperInterface
{
private $connector = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Fetches data of report log item from the database by id
*
* @param Report log data
*
* @return void
*/
public function fetch(array &$data): void
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `domain`, `external_id`, `event_time`, `filename`, `source`, `success`, `message` FROM `'
. $this->connector->tablePrefix('reportlog') . '` WHERE `id` = ?'
);
$st->bindValue(1, $data['id'], \PDO::PARAM_INT);
$st->execute();
if (!($row = $st->fetch(\PDO::FETCH_NUM))) {
throw new DatabaseNotFoundException();
}
$data['domain'] = $row[0];
$data['external_id'] = $row[1];
$data['event_time'] = new DateTime($row[2]);
$data['filename'] = $row[3];
$data['source'] = intval($row[4]);
$data['success'] = boolval($row[5]);
$data['message'] = $row[6];
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the log item', -1, $e);
}
}
/**
* Saves data of report log item to the database
*
* @return void
*/
public function save(array &$data): void
{
$db = $this->connector->dbh();
try {
$id = $data['id'];
if (is_null($id)) {
$st = $db->prepare(
'INSERT INTO `' . $this->connector->tablePrefix('reportlog')
. '` (`domain`, `external_id`, `event_time`, `filename`, `source`, `success`, `message`)'
. ' VALUES (?, ?, ?, ?, ?, ?, ?)'
);
} else {
$st = $db->prepare(
'UPDATE `' . $this->connector->tablePrefix('reportlog')
. '` SET `domain` = ?, `external_id` = ?, `event_time` = ?, `filename` = ?,'
. ' `source` = ?, `success` = ?, `message` = ? WHERE `id` = ?'
);
$st->bindValue(8, $id, \PDO::PARAM_INT);
}
$ts = $data['event_time'] ?? (new DateTime());
$st->bindValue(1, $data['domain'], \PDO::PARAM_STR);
$st->bindValue(2, $data['external_id'], \PDO::PARAM_STR);
$st->bindValue(3, $ts->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(4, $data['filename'], \PDO::PARAM_STR);
$st->bindValue(5, $data['source'], \PDO::PARAM_INT);
$st->bindValue(6, $data['success'], \PDO::PARAM_BOOL);
$st->bindValue(7, $data['message'], \PDO::PARAM_STR);
$st->execute();
if (is_null($id)) {
$data['id'] = intval($db->lastInsertId());
}
$st->closeCursor();
$data['event_time'] = $ts;
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to save a report log item');
}
}
/**
* Returns a list of report log items with given criteria
*
* @param array $filter Key-value array:
* 'from_time' => DateTime
* 'till_time' => DateTime
* @param array $order Key-value array with order options:
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array:
* 'offset' => int
* 'count' => int
*
* @return array
*/
public function list(array &$filter, array &$order, array &$limit): array
{
$list = [];
try {
$st = $this->connector->dbh()->prepare(
'SELECT `id`, `domain`, `event_time`, `source`, `success`, `message` FROM `'
. $this->connector->tablePrefix('reportlog') . '`'
. $this->sqlCondition($filter)
. $this->sqlOrder($order)
. $this->sqlLimit($limit)
);
$this->sqlBindValues($st, $filter, $limit);
$st->execute();
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$list[] = [
'id' => intval($row[0]),
'domain' => $row[1],
'event_time' => new DateTime($row[2]),
'source' => intval($row[3]),
'success' => boolval($row[4]),
'message' => $row[5]
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the logs', -1, $e);
}
return $list;
}
/**
* Returns the number of report log items matching the specified filter and limits
*
* @param array $filter Key-value array with filtering parameters
* @param array $limit Key-value array with limits
*
* @return int
*/
public function count(array &$filter, array &$limit): int
{
$cnt = 0;
try {
$st = $this->connector->dbh()->prepare(
'SELECT COUNT(*) FROM `' . $this->connector->tablePrefix('reportlog') . '`'
. $this->sqlCondition($filter)
. $this->sqlLimit($limit)
);
$this->sqlBindValues($st, $filter, $limit);
$st->execute();
$cnt = intval($st->fetch(\PDO::FETCH_NUM)[0]);
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the log data', -1, $e);
}
return $cnt;
}
/**
* Deletes report log items from the database
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array with order options:
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with limits
*
* @return void
*/
public function delete(array &$filter, array &$order, array &$limit): void
{
try {
$st = $this->connector->dbh()->prepare(
'DELETE FROM `' . $this->connector->tablePrefix('reportlog') . '`'
. $this->sqlCondition($filter)
. $this->sqlOrder($order)
. $this->sqlLimit($limit)
);
$this->sqlBindValues($st, $filter, $limit);
$st->execute();
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to remove the log data', -1, $e);
}
}
/**
* Returns a string with an SQL condition 'WHERE ...'
*
* @param array $filter Key-value with filtering paremeters
*
* @return string
*/
private function sqlCondition(array &$filter): string
{
$res = '';
if (!is_null($filter['from_time']) || !is_null($filter['till_time'])) {
$res = ' WHERE';
$till_time = $filter['till_time'];
if (!is_null($filter['from_time'])) {
$res .= ' `event_time` >= ?';
if (!is_null($till_time)) {
$res .= ' AND';
}
}
if (!is_null($till_time)) {
$res .= ' `event_time` < ?';
}
}
return $res;
}
/**
* Returns 'ORDER BY ...' part of the SQL query
*
* @param array $order Key-value array with ordering options
*
* @return string
*/
private function sqlOrder(array &$order): string
{
return ' ORDER BY `event_time` ' . ($order['direction'] === 'descent' ? 'DESC' : 'ASC');
}
/**
* Returns 'LIMIT ...' part of the SQL string
*
* @param array $limit Key-value array with keys 'offset' and 'count'
*
* @return string
*/
private function sqlLimit(array &$limit): string
{
$res = '';
if ($limit['count'] > 0) {
$res = ' LIMIT ?';
if ($limit['offset'] > 0) {
$res .= ', ?';
}
}
return $res;
}
/**
* Binds the values of the filter and the limit to SQL query
*
* @param PDOStatement $st Prepared SOL statement to bind to
* @param array $filter Key-value array with filter data
* @param array $limit Key-value array with limit data
*
* @return void
*/
private function sqlBindValues($st, array &$filter, array &$limit): void
{
$pos = 0;
if (!is_null($filter['from_time'])) {
$st->bindValue(++$pos, $filter['from_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
}
if (!is_null($filter['till_time'])) {
$st->bindValue(++$pos, $filter['till_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
}
if ($limit['count'] > 0) {
if ($limit['offset'] > 0) {
$st->bindValue(++$pos, $limit['offset'], \PDO::PARAM_INT);
}
$st->bindValue(++$pos, $limit['count'], \PDO::PARAM_INT);
}
}
}

View File

@ -0,0 +1,753 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the ReportMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Common;
use Liuch\DmarcSrg\DateTime;
use Liuch\DmarcSrg\Settings\SettingsList;
use Liuch\DmarcSrg\Database\ReportMapperInterface;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* ReportMapper class implementation for MariaDB
*/
class ReportMapper implements ReportMapperInterface
{
private $connector = null;
private static $allowed_domains = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Fetches report data from the database and stores it in the passed array
*
* @param array $data Array with report data. To identify the report,
* the array must contain at least two fields:
* `report_id` - External report id from the xml file
* `domain` - Fully Qualified Domain Name without a trailing dot
*
* @return void
*/
public function fetch(array &$data): void
{
$db = $this->connector->dbh();
try {
$st = $db->prepare(
'SELECT `rp`.`id`, `begin_time`, `end_time`, `loaded_time`, `org`, `email`, `extra_contact_info`,'
. ' `error_string`, `policy_adkim`, `policy_aspf`, `policy_p`, `policy_sp`, `policy_np`,'
. ' `policy_pct`, `policy_fo`'
. ' FROM `' . $this->connector->tablePrefix('reports') . '` AS `rp`'
. ' INNER JOIN `' . $this->connector->tablePrefix('domains')
. '` AS `dom` ON `dom`.`id` = `rp`.`domain_id`'
. ' WHERE `fqdn` = ? AND `external_id` = ?'
);
$st->bindValue(1, $data['domain'], \PDO::PARAM_STR);
$st->bindValue(2, $data['report_id'], \PDO::PARAM_STR);
$st->execute();
if (!($res = $st->fetch(\PDO::FETCH_NUM))) {
throw new DatabaseNotFoundException('The report is not found');
}
$id = intval($res[0]);
$data['date'] = [
'begin' => new DateTime($res[1]),
'end' => new DateTime($res[2])
];
$data['loaded_time'] = new DateTime($res[3]);
$data['org_name'] = $res[4];
$data['email'] = $res[5];
$data['extra_contact_info'] = $res[6];
$data['error_string'] = json_decode($res[7] ?? '', true);
$data['policy'] = [
'adkim' => $res[8],
'aspf' => $res[9],
'p' => $res[10],
'sp' => $res[11],
'np' => $res[12],
'pct' => $res[13],
'fo' => $res[14]
];
$order_str = $this->sqlOrderRecords();
$st = $db->prepare(
'SELECT `report_id`, `ip`, `rcount`, `disposition`, `reason`, `dkim_auth` , `spf_auth`, `dkim_align`,'
. ' `spf_align`, `envelope_to`, `envelope_from`, `header_from`'
. ' FROM `' . $this->connector->tablePrefix('rptrecords') . '` WHERE `report_id` = ?' . $order_str
);
$st->bindValue(1, $id, \PDO::PARAM_INT);
$st->execute();
$data['records'] = [];
while ($res = $st->fetch(\PDO::FETCH_NUM)) {
$data['records'][] = [
'ip' => inet_ntop($res[1]),
'count' => intval($res[2]),
'disposition' => Common::$disposition[$res[3]],
'reason' => json_decode($res[4] ?? '', true),
'dkim_auth' => json_decode($res[5] ?? '', true),
'spf_auth' => json_decode($res[6] ?? '', true),
'dkim_align' => Common::$align_res[$res[7]],
'spf_align' => Common::$align_res[$res[8]],
'envelope_to' => $res[9],
'envelope_from' => $res[10],
'header_from' => $res[11]
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the report from DB', -1, $e);
}
}
/**
* Inserts report data into the database.
*
* @param array $data Report data
*
* @return void
*/
public function save(array &$data): void
{
$db = $this->connector->dbh();
$db->beginTransaction();
try {
$domain_data = [ 'fqdn' => strtolower($data['domain']) ];
$domain_mapper = $this->connector->getMapper('domain');
try {
$domain_mapper->fetch($domain_data);
if (!$domain_data['active']) {
throw new SoftException('Failed to add an incoming report: the domain is inactive');
}
} catch (DatabaseNotFoundException $e) {
// The domain is not found. Let's try to add it automatically.
$this->insertDomain($domain_data, $domain_mapper);
}
$ct = new DateTime();
$st = $db->prepare(
'INSERT INTO `' . $this->connector->tablePrefix('reports')
. '` (`domain_id`, `begin_time`, `end_time`, `loaded_time`, `org`, `external_id`, `email`,'
. ' `extra_contact_info`, `error_string`, `policy_adkim`, `policy_aspf`, `policy_p`,'
. ' `policy_sp`, `policy_np`, `policy_pct`, `policy_fo`, `seen`)'
. ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)'
);
$st->bindValue(1, $domain_data['id'], \PDO::PARAM_INT);
$st->bindValue(2, $data['begin_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(3, $data['end_time']->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(4, $ct->format('Y-m-d H:i:s'), \PDO::PARAM_STR);
$st->bindValue(5, $data['org'], \PDO::PARAM_STR);
$st->bindValue(6, $data['external_id'], \PDO::PARAM_STR);
$st->bindValue(7, $data['email'], \PDO::PARAM_STR);
$st->bindValue(8, $data['extra_contact_info'], \PDO::PARAM_STR);
self::sqlBindJson($st, 9, $data['error_string']);
$st->bindValue(10, $data['policy_adkim'], \PDO::PARAM_STR);
$st->bindValue(11, $data['policy_aspf'], \PDO::PARAM_STR);
$st->bindValue(12, $data['policy_p'], \PDO::PARAM_STR);
$st->bindValue(13, $data['policy_sp'], \PDO::PARAM_STR);
$st->bindValue(14, $data['policy_np'], \PDO::PARAM_STR);
$st->bindValue(15, $data['policy_pct'], \PDO::PARAM_STR);
$st->bindValue(16, $data['policy_fo'], \PDO::PARAM_STR);
$st->execute();
$new_id = intval($db->lastInsertId());
$st->closeCursor();
$st = $db->prepare(
'INSERT INTO `' . $this->connector->tablePrefix('rptrecords')
. '` (`report_id`, `ip`, `rcount`, `disposition`, `reason`, `dkim_auth`, `spf_auth`, `dkim_align`,'
. ' `spf_align`, `envelope_to`, `envelope_from`, `header_from`)'
. ' VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
);
foreach ($data['records'] as &$rec_data) {
$st->bindValue(1, $new_id, \PDO::PARAM_INT);
$st->bindValue(2, inet_pton($rec_data['ip']), \PDO::PARAM_STR);
$st->bindValue(3, $rec_data['rcount'], \PDO::PARAM_INT);
$st->bindValue(4, array_search($rec_data['disposition'], Common::$disposition), \PDO::PARAM_INT);
self::sqlBindJson($st, 5, $rec_data['reason']);
self::sqlBindJson($st, 6, $rec_data['dkim_auth']);
self::sqlBindJson($st, 7, $rec_data['spf_auth']);
$st->bindValue(8, array_search($rec_data['dkim_align'], Common::$align_res), \PDO::PARAM_INT);
$st->bindValue(9, array_search($rec_data['spf_align'], Common::$align_res), \PDO::PARAM_INT);
$st->bindValue(10, $rec_data['envelope_to'], \PDO::PARAM_STR);
$st->bindValue(11, $rec_data['envelope_from'], \PDO::PARAM_STR);
$st->bindValue(12, $rec_data['header_from'], \PDO::PARAM_STR);
$st->execute();
}
unset($rec_data);
$db->commit();
$data['loaded_time'] = $ct;
} catch (\PDOException $e) {
$db->rollBack();
if ($e->getCode() == '23000') {
throw new SoftException('This report has already been loaded');
}
throw new DatabaseFatalException('Failed to insert the report', -1, $e);
} catch (\Exception $e) {
$db->rollBack();
throw $e;
}
}
/**
* Sets report record property in database.
*
* It has nothing to do with the fields of the report itself.
*
* @param array $data Report data
* @param string $name Property name. Currently only `seen` is supported.
* @param variant $value Property value
*
* @return void
*/
public function setProperty(array &$data, string $name, $value): void
{
if ($name !== 'seen' && gettype($value) !== 'boolean') {
throw new LogicException('Incorrect parameters');
}
try {
$st = $this->connector->dbh()->prepare(
'UPDATE `' . $this->connector->tablePrefix('reports') . '` AS `rp`'
. ' INNER JOIN `' . $this->connector->tablePrefix('domains') . '` AS `dom`'
. ' ON `rp`.`domain_id` = `dom`.`id` SET `seen` = ? WHERE `fqdn` = ? AND `external_id` = ?'
);
$st->bindValue(1, $value, \PDO::PARAM_BOOL);
$st->bindValue(2, $data['domain'], \PDO::PARAM_STR);
$st->bindValue(3, $data['report_id'], \PDO::PARAM_STR);
$st->execute();
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to update the DB record', -1, $e);
}
}
/**
* Returns a list of reports with specified parameters
*
* This method returns a list of reports that depends on the $filter, $order and $limit.
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array:
* 'field' => string, 'begin_time'
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return array
*/
public function list(array &$filter, array &$order, array &$limit): array
{
$db = $this->connector->dbh();
$list = [];
$f_data = $this->prepareFilterData($filter);
$order_str = $this->sqlOrderList($order);
$cond_str0 = $this->sqlConditionList($f_data, ' AND ', 0);
$cond_str1 = $this->sqlConditionList($f_data, ' HAVING ', 1);
$limit_str = $this->sqlLimit($limit);
try {
$st = $db->prepare(
'SELECT `org`, `begin_time`, `end_time`, `fqdn`, external_id, `seen`, SUM(`rcount`) AS `rcount`,'
. ' MIN(`dkim_align`) AS `dkim_align`, MIN(`spf_align`) AS `spf_align`,'
. ' MIN(`disposition`) AS `disposition` FROM `' . $this->connector->tablePrefix('rptrecords')
. '` AS `rr` RIGHT JOIN (SELECT `rp`.`id`, `org`, `begin_time`, `end_time`, `external_id`,'
. ' `fqdn`, `seen` FROM `' . $this->connector->tablePrefix('reports')
. '` AS `rp` INNER JOIN `' . $this->connector->tablePrefix('domains')
. '` AS `d` ON `d`.`id` = `rp`.`domain_id`' . $cond_str0 . $order_str
. ') AS `rp` ON `rp`.`id` = `rr`.`report_id` GROUP BY `rp`.`id`'
. $cond_str1 . $order_str . $limit_str
);
$this->sqlBindValues($st, $f_data, $limit);
$st->execute();
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$list[] = [
'org_name' => $row[0],
'date' => [
'begin' => new DateTime($row[1]),
'end' => new DateTime($row[2])
],
'domain' => $row[3],
'report_id' => $row[4],
'seen' => (bool) $row[5],
'messages' => $row[6],
'dkim_align' => Common::$align_res[$row[7]],
'spf_align' => Common::$align_res[$row[8]],
'disposition' => Common::$disposition[$row[9]]
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the report list', -1, $e);
}
return $list;
}
/**
* Returns the number of reports matching the specified filter and limits
*
* @param array $filter Key-value array with filtering parameters
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return int
*/
public function count(array &$filter, array &$limit): int
{
$cnt = 0;
$f_data = $this->prepareFilterData($filter);
try {
$st = $this->connector->dbh()->prepare(
'SELECT COUNT(*) FROM `' . $this->connector->tablePrefix('reports') . '` AS `rp`'
. $this->sqlConditionList($f_data, ' WHERE ', 0)
);
$l_empty = [ 'offset' => 0, 'count' => 0 ];
$this->sqlBindValues($st, $f_data, $l_empty);
$st->execute();
$cnt = intval($st->fetch(\PDO::FETCH_NUM)[0]);
$st->closeCursor();
$offset = $limit['offset'];
if ($offset > 0) {
$cnt -= $offset;
if ($cnt < 0) {
$cnt = 0;
}
}
$max = $limit['count'];
if ($max > 0 && $max < $cnt) {
$cnt = $max;
}
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get the number of reports', -1, $e);
}
return $cnt;
}
/**
* Deletes reports from the database
*
* It deletes repors form the database. The filter options `dkim` and `spf` do not affect this.
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array:
* 'field' => string, 'begin_time'
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return void
*/
public function delete(array &$filter, array &$order, array &$limit): void
{
$f_data = $this->prepareFilterData($filter);
$cond_str = $this->sqlConditionList($f_data, ' WHERE ', 0);
$order_str = $this->sqlOrderList($order);
$limit_str = $this->sqlLimit($limit);
$db = $this->connector->dbh();
$db->beginTransaction();
try {
$st = $db->prepare(
'DELETE `rr` FROM `' . $this->connector->tablePrefix('rptrecords')
. '` AS `rr` INNER JOIN (SELECT `id` FROM `' . $this->connector->tablePrefix('reports') . '`'
. $cond_str . $order_str . $limit_str . ') AS `rp` ON `rp`.`id` = `rr`.`report_id`'
);
$this->sqlBindValues($st, $f_data, $limit);
$st->execute();
$st->closeCursor();
$st = $db->prepare(
'DELETE FROM `' . $this->connector->tablePrefix('reports') . "`{$cond_str}{$order_str}{$limit_str}"
);
$this->sqlBindValues($st, $f_data, $limit);
$st->execute();
$st->closeCursor();
$db->commit();
} catch (\PDOException $e) {
$db->rollBack();
throw new DatabaseFatalException('Failed to delete reports', -1, $e);
} catch (\Exception $e) {
$db->rollBack();
throw $e;
}
}
/**
* Returns a list of months with years of the form: 'yyyy-mm' for which there is at least one report
*
* @return array
*/
public function months(): array
{
$res = [];
$rep_tn = $this->connector->tablePrefix('reports');
try {
$st = $this->connector->dbh()->query(
'SELECT DISTINCT DATE_FORMAT(`date`, "%Y-%m") AS `month` FROM'
. ' ((SELECT DISTINCT `begin_time` AS `date` FROM `' . $rep_tn
. '`) UNION (SELECT DISTINCT `end_time` AS `date` FROM `' . $rep_tn
. '`)) AS `r` ORDER BY `month` DESC'
);
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$res[] = $row[0];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get a list of months', -1, $e);
}
return $res;
}
/**
* Returns a list of reporting organizations from which there is at least one report
*
* @return array
*/
public function organizations(): array
{
$res = [];
$rep_tn = $this->connector->tablePrefix('reports');
try {
$st = $this->connector->dbh()->query(
'SELECT DISTINCT `org` FROM `' . $rep_tn . '` ORDER BY `org`'
);
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$res[] = $row[0];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get a list of organizations', -1, $e);
}
return $res;
}
/**
* Returns `ORDER BY ...` part of the SQL query for report records
*
* @return string
*/
private function sqlOrderRecords(): string
{
$o_set = explode(',', SettingsList::getSettingByName('report-view.sort-records-by')->value());
switch ($o_set[0]) {
case 'ip':
$fname = 'ip';
break;
case 'message-count':
default:
$fname = 'rcount';
break;
}
$dir = $o_set[1] === 'descent' ? 'DESC' : 'ASC';
return " ORDER BY `{$fname}` {$dir}";
}
/**
* Checks if the domain exists and adds it to the database if necessary
*
* It automatically adds the domain if there are no domains in the database
* or if the domain match the `allowed_domains` reqular expression in the configuration file.
* Otherwise, throws a SoftException.
*
* @param array $data Domain data
* @param object $mapper Domain mapper
*
* @return void
*/
private function insertDomain(array &$data, $mapper): void
{
$mapper = $this->connector->getMapper('domain');
if ($mapper->count(1) !== 0) {
if (is_null(self::$allowed_domains)) {
$allowed = Core::instance()->config('fetcher/allowed_domains', '');
if (!empty($allowed)) {
self::$allowed_domains = "<{$allowed}>i";
}
}
try {
$add = !empty(self::$allowed_domains) && preg_match(self::$allowed_domains, $data['fqdn']) === 1;
} catch (\ErrorException $e) {
$add = false;
Core::instance()->logger()->warning(
'The allow_domains parameter in the settings has an incorrect regular expression value.'
);
}
if (!$add) {
throw new SoftException('Failed to add an incoming report: unknown domain: ' . $data['fqdn']);
}
}
$data['active'] = true;
$data['description'] = 'The domain was added automatically.';
$mapper->save($data);
}
/**
* Binds a nullable array to an SQL query as a json string
*
* @param PDOStatement $st DB statement object
* @param int $idx Bind position
* @param array $data JSON data or null
*
* @return void
*/
private static function sqlBindJson($st, int $idx, $data): void
{
if (is_null($data)) {
$val = null;
$type = \PDO::PARAM_NULL;
} else {
$val = json_encode($data);
$type = \PDO::PARAM_STR;
}
$st->bindValue($idx, $val, $type);
}
/**
* Returns `ORDER BY ...` part of the SQL query
*
* @param array $order Key-value array with ordering options
*
* @return string
*/
private function sqlOrderList(array &$order): string
{
$dir = $order['direction'] === 'ascent' ? 'ASC' : 'DESC';
return " ORDER BY `{$order['field']}` {$dir}";
}
/**
* The valid filter item names
*/
private static $filters_available = [
'domain', 'month', 'before_time', 'organization', 'dkim', 'spf', 'status'
];
/**
* Returns prepared filter data for sql queries
*
* @param array $filter Key-value array with filter options
*
* @return array
*/
private function prepareFilterData(array &$filter): array
{
$filters = [];
for ($i = 0; $i < 2; ++$i) {
$filters[] = [
'a_str' => [],
'bindings' => []
];
}
foreach (self::$filters_available as $fn) {
if (isset($filter[$fn])) {
$fv = $filter[$fn];
switch (gettype($fv)) {
case 'string':
if (!empty($fv)) {
if ($fn == 'domain') {
$filters[0]['a_str'][] = '`rp`.`domain_id` = ?';
$d_data = [ 'fqdn' => $fv ];
$this->connector->getMapper('domain')->fetch($d_data);
$filters[0]['bindings'][] = [ $d_data['id'], \PDO::PARAM_INT ];
} elseif ($fn == 'month') {
$ma = explode('-', $fv);
if (count($ma) != 2) {
throw new SoftException('Report list filter: Incorrect date format');
}
$year = (int)$ma[0];
$month = (int)$ma[1];
if ($year < 0 || $month < 1 || $month > 12) {
throw new SoftException('Report list filter: Incorrect month or year value');
}
$filters[0]['a_str'][] = '`begin_time` < ? AND `end_time` >= ?';
$date1 = new DateTime("{$year}-{$month}-01");
$date2 = (clone $date1)->modify('first day of next month');
$date1->add(new \DateInterval('PT10S'));
$date2->sub(new \DateInterval('PT10S'));
$filters[0]['bindings'][] = [ $date2->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
$filters[0]['bindings'][] = [ $date1->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
} elseif ($fn == 'organization') {
$filters[0]['a_str'][] = '`org` = ?';
$filters[0]['bindings'][] = [ $fv, \PDO::PARAM_STR ];
} elseif ($fn == 'dkim') {
if ($fv === Common::$align_res[0]) {
$val = 0;
} else {
$val = count(Common::$align_res) - 1;
if ($fv !== Common::$align_res[$val]) {
throw new SoftException('Report list filter: Incorrect DKIM value');
}
}
$filters[1]['a_str'][] = '`dkim_align` = ?';
$filters[1]['bindings'][] = [ $val, \PDO::PARAM_INT ];
} elseif ($fn == 'spf') {
if ($fv === Common::$align_res[0]) {
$val = 0;
} else {
$val = count(Common::$align_res) - 1;
if ($fv !== Common::$align_res[$val]) {
throw new SoftException('Report list filter: Incorrect SPF value');
}
}
$filters[1]['a_str'][] = '`spf_align` = ?';
$filters[1]['bindings'][] = [ $val, \PDO::PARAM_INT ];
} elseif ($fn == 'status') {
if ($fv === 'read') {
$val = true;
} elseif ($fv === 'unread') {
$val = false;
} else {
throw new SoftException('Report list filter: Incorrect status value');
}
$filters[0]['a_str'][] = '`seen` = ?';
$filters[0]['bindings'][] = [ $val, \PDO::PARAM_BOOL ];
}
}
break;
case 'object':
if ($fn == 'domain') {
$filters[0]['a_str'][] = '`rp`.`domain_id` = ?';
$filters[0]['bindings'][] = [ $fv->id(), \PDO::PARAM_INT ];
} elseif ($fn == 'before_time') {
$filters[0]['a_str'][] = '`begin_time` < ?';
$filters[0]['bindings'][] = [ $fv->format('Y-m-d H:i:s'), \PDO::PARAM_STR ];
}
break;
case 'integer':
if ($fn == 'domain') {
$filters[0]['a_str'][] = '`rp`.`domain_id` = ?';
$filters[0]['bindings'][] = [ $fv, \PDO::PARAM_INT ];
}
break;
}
}
}
$f_data = [];
for ($i = 0; $i < count($filters); ++$i) {
$filter = &$filters[$i];
if (count($filter['a_str']) > 0) {
$f_data[$i] = [
'str' => implode(' AND ', $filter['a_str']),
'bindings' => $filter['bindings']
];
}
unset($filter);
}
return $f_data;
}
/**
* Returns the SQL condition for a filter by filter id
*
* @param array $f_data Array with prepared filter data
* @param string $prefix Prefix, which will be added to the beginning of the condition string,
* but only in the case when the condition string is not empty.
* @param int $f_id Index of the filter
*
* @return string the condition string
*/
private function sqlConditionList(array &$f_data, string $prefix, int $f_idx): string
{
return isset($f_data[$f_idx]) ? ($prefix . $f_data[$f_idx]['str']) : '';
}
/**
* Returns `LIMIT ...` part of the SQL query
*
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return string
*/
private function sqlLimit(array &$limit): string
{
$res = '';
if ($limit['count'] > 0) {
$res = ' LIMIT ?';
if ($limit['offset'] > 0) {
$res .= ', ?';
}
}
return $res;
}
/**
* Binds the values of the filter and the limit to SQL query
*
* @param PDOStatement $st Prepared SQL statement to bind to
* @param array $f_data Array with prepared filter data
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return void
*/
private function sqlBindValues($st, array &$f_data, array &$limit): void
{
$pos = 0;
if (isset($f_data[0])) {
$this->sqlBindFilterValues($st, $f_data, 0, $pos);
}
if (isset($f_data[1])) {
$this->sqlBindFilterValues($st, $f_data, 1, $pos);
}
if ($limit['count'] > 0) {
if ($limit['offset'] > 0) {
$st->bindValue(++$pos, $limit['offset'], \PDO::PARAM_INT);
}
$st->bindValue(++$pos, $limit['count'], \PDO::PARAM_INT);
}
}
/**
* Binds the values of the specified filter item to SQL query
*
* @param PDOStatement $st Prepared SQL statement to bind to
* @param array $f_data Array with prepared filter data
* @param int $filter_idx Index of the filter to bind to
* @param int $bind_pos Start bind position (pointer). It will be increaded with each binding.
*
* @return void
*/
private function sqlBindFilterValues($st, array &$f_data, int $filter_idx, int &$bind_pos): void
{
foreach ($f_data[$filter_idx]['bindings'] as &$bv) {
$st->bindValue(++$bind_pos, $bv[0], $bv[1]);
}
}
}

View File

@ -0,0 +1,130 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the SettingMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\Database\SettingMapperInterface;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* SettingMapper class implementation for MariaDB
*/
class SettingMapper implements SettingMapperInterface
{
private $connector = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Returns setting value as a string by key
*
* @param string $key
*
* @return string
*/
public function value(string $key): string
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `value` FROM `' . $this->connector->tablePrefix('system') . '` WHERE `key` = ?'
);
$st->bindValue(1, $key, \PDO::PARAM_STR);
$st->execute();
if (!$res = $st->fetch(\PDO::FETCH_NUM)) {
throw new DatabaseNotFoundException('Setting not found: ' . $key);
}
$st->closeCursor();
return $res[0];
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get a setting', -1, $e);
}
}
/**
* Returns a key-value array of the setting list like this:
* [ 'name1' => 'value1', 'name2' => 'value2' ]
*
* @return array
*/
public function list(): array
{
$res = [];
try {
$st = $this->connector->dbh()->query(
'SELECT `key`, `value` FROM `' . $this->connector->tablePrefix('system') . '` ORDER BY `key`'
);
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$res[$row[0]] = $row[1];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get a list of the settings', -1, $e);
}
return $res;
}
/**
* Saves the setting to the database
*
* Updates the value of the setting in the database if the setting exists there or insert a new record otherwise.
*
* @param string $name Setting name
* @param string $value Setting value
*
* @return void
*/
public function save(string $name, string $value): void
{
$db = $this->connector->dbh();
try {
$st = $db->prepare(
'INSERT INTO `' . $this->connector->tablePrefix('system') .
'` (`key`, `value`) VALUES (?, ?) ON DUPLICATE KEY UPDATE `value` = ?'
);
$st->bindValue(1, $name, \PDO::PARAM_STR);
$st->bindValue(2, $value, \PDO::PARAM_STR);
$st->bindValue(3, $value, \PDO::PARAM_STR);
$st->execute();
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to update a setting', -1, $e);
}
}
}

View File

@ -0,0 +1,222 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the StatisticsMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\Database\StatisticsMapperInterface;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
/**
* StatisticsMapper class implementation for MariaDB
*/
class StatisticsMapper implements StatisticsMapperInterface
{
private $connector = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Returns summary information for the specified domain and date range
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array Array with Summary information:
* 'emails' => [
* 'total' => total email processed (int)
* 'dkim_spf_aligned' => Both DKIM and SPF aligned (int)
* 'dkim_aligned' => Only DKIM aligned (int)
* 'spf_aligned' => Only SPF aligned (int)
* ];
*/
public function summary($domain, array &$range): array
{
$is_domain = $domain ? true : false;
$db = $this->connector->dbh();
try {
$st = $db->prepare(
'SELECT SUM(`rcount`), SUM(IF(`dkim_align` = 2 AND `spf_align` = 2, `rcount`, 0)),'
. ' SUM(IF(`dkim_align` = 2 AND `spf_align` <> 2, `rcount`, 0)),'
. ' SUM(IF(`dkim_align` <> 2 AND `spf_align` = 2, `rcount`, 0))'
. ' FROM `' . $this->connector->tablePrefix('rptrecords') . '` AS `rr`'
. ' INNER JOIN `' . $this->connector->tablePrefix('reports')
. '` AS `rp` ON `rr`.`report_id` = `rp`.`id`'
. $this->sqlCondition($is_domain)
);
$this->sqlBindValues($st, $domain, $range);
$st->execute();
$row = $st->fetch(\PDO::FETCH_NUM);
$ems = [
'total' => intval($row[0]),
'dkim_spf_aligned' => intval($row[1]),
'dkim_aligned' => intval($row[2]),
'spf_aligned' => intval($row[3])
];
$st->closeCursor();
$st = $db->prepare(
'SELECT COUNT(*) FROM (SELECT `org` FROM `' . $this->connector->tablePrefix('reports') . '`'
. $this->sqlCondition($is_domain) . ' GROUP BY `org`) AS `orgs`'
);
$this->sqlBindValues($st, $domain, $range);
$st->execute();
$row = $st->fetch(\PDO::FETCH_NUM);
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get summary information', -1, $e);
}
return [
'emails' => $ems,
'organizations' => intval($row[0])
];
}
/**
* Returns a list of ip-addresses from which the e-mail messages were received, with some statistics for each one
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array A list of ip-addresses with fields `ip`, `emails`, `dkim_aligned`, `spf_aligned`
*/
public function ips($domain, array &$range): array
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `ip`, SUM(`rcount`) AS `rcount`, SUM(IF(`dkim_align` = 2, `rcount`, 0)) AS `dkim_aligned`,'
. ' SUM(IF(`spf_align` = 2, `rcount`, 0)) AS `spf_aligned`'
. ' FROM `' . $this->connector->tablePrefix('rptrecords') . '` AS `rr`'
. ' INNER JOIN `' . $this->connector->tablePrefix('reports')
. '` AS `rp` ON `rr`.`report_id` = `rp`.`id`'
. $this->sqlCondition($domain ? true : false) . ' GROUP BY `ip` ORDER BY `rcount` DESC'
);
$this->sqlBindValues($st, $domain, $range);
$st->execute();
$res = [];
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$res[] = [
'ip' => inet_ntop($row[0]),
'emails' => intval($row[1]),
'dkim_aligned' => intval($row[2]),
'spf_aligned' => intval($row[3])
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get IPs summary information', -1, $e);
}
return $res;
}
/**
* Returns a list of organizations that sent the reports with some statistics for each one
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array List of organizations with fields `name`, `reports`, `emails`
*/
public function organizations($domain, array &$range): array
{
try {
$st = $this->connector->dbh()->prepare(
'SELECT `org`, COUNT(*), SUM(`rr`.`rcount`) AS `rcount`'
. ' FROM `' . $this->connector->tablePrefix('reports') . '` AS `rp`'
. ' INNER JOIN (SELECT `report_id`, SUM(`rcount`) AS `rcount` FROM `'
. $this->connector->tablePrefix('rptrecords')
. '` GROUP BY `report_id`) AS `rr` ON `rp`.`id` = `rr`.`report_id`'
. $this->sqlCondition($domain ? true : false)
. ' GROUP BY `org` ORDER BY `rcount` DESC'
);
$this->sqlBindValues($st, $domain, $range);
$st->execute();
$res = [];
while ($row = $st->fetch(\PDO::FETCH_NUM)) {
$res[] = [
'name' => $row[0],
'reports' => intval($row[1]),
'emails' => intval($row[2])
];
}
$st->closeCursor();
} catch (\PDOException $e) {
throw new DatabaseFatalException('Failed to get summary information of reporting organizations', -1, $e);
}
return $res;
}
/**
* Returns a condition string for WHERE statement
*
* @param bool $with_domain Is it needed to add a condition for a domain
*
* @return string Condition string
*/
private function sqlCondition($with_domain): string
{
$res = ' WHERE ';
if ($with_domain) {
$res .= 'domain_id = ? AND ';
}
$res .= '`begin_time` < ? AND `end_time` >= ?';
return $res;
}
/**
* Binds values for SQL queries
*
* @param PDOStatement $st PDO Statement to bind to
* @param Domain|null $domain Domain for the condition
* @param array $range Date range for the condition
*
* @return void
*/
private function sqlBindValues(object $st, $domain, array &$range): void
{
$pnum = 0;
if ($domain) {
$st->bindValue(++$pnum, $domain->id(), \PDO::PARAM_INT);
}
$ds1 = (clone $range['date1'])->add(new \DateInterval('PT10S'))->format('Y-m-d H:i:s');
$ds2 = (clone $range['date2'])->sub(new \DateInterval('PT10S'))->format('Y-m-d H:i:s');
$st->bindValue(++$pnum, $ds2, \PDO::PARAM_STR);
$st->bindValue(++$pnum, $ds1, \PDO::PARAM_STR);
}
}

View File

@ -0,0 +1,236 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the UpgraderMapper class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database\Mariadb;
use Liuch\DmarcSrg\Database\UpgraderMapperInterface;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\DatabaseFatalException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* UpgraderMapper class implementation for MariaDB
*/
class UpgraderMapper implements UpgraderMapperInterface
{
private $connector = null;
/**
* The constructor
*
* @param Connector $connector DatabaseConnector
*/
public function __construct(object $connector)
{
$this->connector = $connector;
}
/**
* Starts upgrading the database structure
*
* @param string $target Target version of the database structure to upgrade to
*
* @return void
*/
public function go(string $target): void
{
try {
$cur_ver = $this->connector->getMapper('setting')->value('version');
} catch (DatabaseNotFoundException $e) {
$cur_ver = 'null';
}
while ($cur_ver !== $target) {
if (!isset(self::$upways['ver_' . $cur_ver])) {
throw new SoftException(
"Upgrading failed: There is no way to upgrade from {$cur_ver} to {$target}"
);
}
$um = self::$upways['ver_' . $cur_ver];
$cur_ver = $this->$um();
}
}
/**
* Upgrades the database structure from None to 0.1
*
* @return string New version of the database structure
*/
private function upNull(): string
{
$db = $this->connector->dbh();
$db->beginTransaction();
try {
$db->query(
'INSERT INTO `' . $this->connector->tablePrefix('system')
. '` (`key`, `value`) VALUES ("version", "0.1")'
);
$db->commit();
} catch (\PDOException $e) {
$db->rollBack();
throw $this->dbFatalException($e);
} catch (\Exception $e) {
$db->rollBack();
throw $e;
}
return '0.1';
}
/**
* Upgrades the database structure from 0.1 to 1.0
*
* @return string New version of the database structure
*/
private function up01(): string
{
$db = $this->connector->dbh();
// Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
try {
$dom_tn = $this->connector->tablePrefix('domains');
if (!$this->columnExists($db, $dom_tn, 'active')) {
$db->query(
'ALTER TABLE `' . $dom_tn . '` ADD COLUMN `active` boolean NOT NULL AFTER `fqdn`'
);
}
if (!$this->columnExists($db, $dom_tn, 'created_time')) {
$db->query(
'ALTER TABLE `' . $dom_tn . '` ADD COLUMN `created_time` datetime NOT NULL'
);
}
if (!$this->columnExists($db, $dom_tn, 'updated_time')) {
$db->query(
'ALTER TABLE `' . $dom_tn . '` ADD COLUMN `updated_time` datetime NOT NULL'
);
}
$db->query(
'UPDATE `' . $dom_tn . '` SET `active` = TRUE, `created_time` = NOW(), `updated_time` = NOW()'
);
$db->query(
'UPDATE `' . $this->connector->tablePrefix('system') . '` SET `value` = "1.0" WHERE `key` = "version"'
);
} catch (\PDOException $e) {
throw $this->dbFatalException($e);
}
return '1.0';
}
/**
* Upgrades the database structure from 1.0 to 2.0
*
* @return string New version of the database structure
*/
private function up10(): string
{
$db = $this->connector->dbh();
// Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
try {
$sys_tn = $this->connector->tablePrefix('system');
$db->query(
'ALTER TABLE `' . $sys_tn . '` MODIFY COLUMN `key` varchar(64) NOT NULL'
);
$db->query(
'UPDATE `' . $sys_tn . '` SET `value` = "2.0" WHERE `key` = "version"'
);
} catch (\PDOException $e) {
throw $this->dbFatalException($e);
}
return '2.0';
}
/**
* Upgrades the database structure from v2.0 to v3.0
*
* @return string New version of the database structure
*/
private function up20(): string
{
$db = $this->connector->dbh();
// Transaction would be useful here but it doesn't work with ALTER TABLE in MySQL/MariaDB
try {
$rep_tn = $this->connector->tablePrefix('reports');
if (!$this->columnExists($db, $rep_tn, 'policy_np')) {
$db->query(
'ALTER TABLE `' . $rep_tn . '` ADD COLUMN `policy_np` varchar(20) NULL AFTER `policy_sp`'
);
}
$sys_tn = $this->connector->tablePrefix('system');
$db->query(
'UPDATE `' . $sys_tn . '` SET `value` = "3.0" WHERE `key` = "version"'
);
} catch (\PDOException $e) {
throw $this->dbFatalException($e);
}
return '3.0';
}
/**
* Checks if the spefied column exists in the spefied table of the database
*
* @param object $db Connection handle of the database
* @param string $table Table name with the prefix
* @param string $columb Column name
*
* @return bool
*/
private function columnExists($db, string $table, string $column): bool
{
$st = $db->prepare(
'SELECT NULL FROM `INFORMATION_SCHEMA`.`COLUMNS`'
. ' WHERE `table_schema` = ? AND `table_name` = ? AND `column_name` = ?'
);
$st->bindValue(1, $this->connector->dbName(), \PDO::PARAM_STR);
$st->bindValue(2, $table, \PDO::PARAM_STR);
$st->bindValue(3, $column, \PDO::PARAM_STR);
$st->execute();
$res = $st->fetch(\PDO::FETCH_NUM);
$st->closeCursor();
return $res ? true : false;
}
/**
* Return an instance of DatabaseFatalException
*
* @param Exception $e The original exception
*
* @return DatabaseFatalException
*/
private function dbFatalException($e)
{
return new DatabaseFatalException('Failed to upgrade the database structure', -1, $e);
}
private static $upways = [
'ver_null' => 'upNull',
'ver_0.1' => 'up01',
'ver_1.0' => 'up10',
'ver_2.0' => 'up20'
];
}

View File

@ -0,0 +1,89 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the ReportLogMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface ReportLogMapperInterface
{
/**
* Fetches data of report log item from the database by id
*
* @param Report log data
*
* @return void
*/
public function fetch(array &$data): void;
/**
* Saves data of report log item to the database
*
* @return void
*/
public function save(array &$data): void;
/**
* Returns a list of report log items with given criteria
*
* @param array $filter Key-value array:
* 'from_time' => DateTime
* 'till_time' => DateTime
* @param array $order Key-value array with order options:
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array:
* 'offset' => int
* 'count' => int
*
* @return array
*/
public function list(array &$filter, array &$order, array &$limit): array;
/**
* Returns the number of report log items matching the specified filter and limits
*
* @param array $filter Key-value array with filtering parameters
* @param array $limit Key-value array with limits
*
* @return int
*/
public function count(array &$filter, array &$limit): int;
/**
* Deletes report log items from the database
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array with order options:
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with limits
*
* @return void
*/
public function delete(array &$filter, array &$order, array &$limit): void;
}

View File

@ -0,0 +1,123 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the ReportMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface ReportMapperInterface
{
/**
* Fetches report data from the database and stores it in the passed array
*
* @param array $data Array with report data. To identify the report,
* the array must contain at least two fields:
* `report_id` - External report id from the xml file
* `domain` - Fully Qualified Domain Name without a trailing dot
*
* @return void
*/
public function fetch(array &$data): void;
/**
* Inserts report data into the database.
*
* @param array $data Report data
*
* @return void
*/
public function save(array &$data): void;
/**
* Sets report record property in database.
*
* It has nothing to do with the fields of the report itself.
*
* @param array $data Report data
* @param string $name Property name. Currently only `seen` is supported.
* @param variant $value Property value
*
* @return void
*/
public function setProperty(array &$data, string $name, $value): void;
/**
* Returns a list of reports with specified parameters
*
* This method returns a list of reports that depends on the $filter, $order and $limit.
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array:
* 'field' => string, 'begin_time'
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return array
*/
public function list(array &$filter, array &$order, array &$limit): array;
/**
* Returns the number of reports matching the specified filter and limits
*
* @param array $filter Key-value array with filtering parameters
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return int
*/
public function count(array &$filter, array &$limit): int;
/**
* Deletes reports from the database
*
* It deletes repors form the database. The filter options `dkim` and `spf` do not affect this.
*
* @param array $filter Key-value array with filtering parameters
* @param array $order Key-value array:
* 'field' => string, 'begin_time'
* 'direction' => string, 'ascent' or 'descent'
* @param array $limit Key-value array with two keys: `offset` and `count`
*
* @return void
*/
public function delete(array &$filter, array &$order, array &$limit): void;
/**
* Returns a list of months with years of the form: 'yyyy-mm' for which there is at least one report
*
* @return array
*/
public function months(): array;
/**
* Returns a list of reporting organizations from which there is at least one report
*
* @return array
*/
public function organizations(): array;
}

View File

@ -0,0 +1,64 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the SettingMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface SettingMapperInterface
{
/**
* Returns setting value as a string by key
*
* @param string $key
*
* @return string
*/
public function value(string $key): string;
/**
* Returns a key-value array of the setting list like this:
* [ 'name1' => 'value1', 'name2' => 'value2' ]
*
* @return array
*/
public function list(): array;
/**
* Saves the setting to the database
*
* Updates the value of the setting in the database if the setting exists there or insert a new record otherwise.
*
* @param string $name Setting name
* @param string $value Setting value
*
* @return void
*/
public function save(string $name, string $value): void;
}

View File

@ -0,0 +1,71 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the StatisticsMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface StatisticsMapperInterface
{
/**
* Returns summary information for the specified domain and date range
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array Array with Summary information:
* 'emails' => [
* 'total' => total email processed (int)
* 'dkim_spf_aligned' => Both DKIM and SPF aligned (int)
* 'dkim_aligned' => Only DKIM aligned (int)
* 'spf_aligned' => Only SPF aligned (int)
* ];
*/
public function summary($domain, array &$range): array;
/**
* Returns a list of ip-addresses from which the e-mail messages were received, with some statistics for each one
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array A list of ip-addresses with fields `ip`, `emails`, `dkim_aligned`, `spf_aligned`
*/
public function ips($domain, array &$range): array;
/**
* Returns a list of organizations that sent the reports with some statistics for each one
*
* @param Domain|null $domain Domain for which the information is needed. Null is for all domains.
* @param array $range Array with two dates
*
* @return array List of organizations with fields `name`, `reports`, `emails`
*/
public function organizations($domain, array &$range): array;
}

View File

@ -0,0 +1,44 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the UpgraderMapperInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Database;
interface UpgraderMapperInterface
{
/**
* Starts upgrading the database structure
*
* @param string $target Target version of the database structure to upgrade to
*
* @return void
*/
public function go(string $target): void;
}

View File

@ -0,0 +1,43 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class DateTime
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
/**
* This class extends the standard class to get ISO 8601 value in json_encode.
*/
class DateTime extends \DateTime implements \JsonSerializable
{
public function jsonSerialize(): string
{
return $this->format(\DateTime::ATOM);
}
}

View File

@ -0,0 +1,165 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Directory
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Directories;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\RuntimeException;
/**
* This class is designed to work with the report directories which are listed in the configuration file.
*/
class Directory
{
private $id = null;
private $name = null;
private $location = null;
/**
* It's the constructor of the class
*
* @param int $id Id of the directory. In fact, it is a serial number in the configuration file.
* @param array $data An array with the following fields:
* `location` (string) - Location of the directory in the file system.
* `name` (string) - Name of the directory. It is optional.
*
* @return void
*/
public function __construct(int $id, array $data)
{
if (isset($data['name']) && gettype($data['name']) !== 'string') {
throw new LogicException('Directory name must be either null or a string value');
}
if (!isset($data['location']) || gettype($data['location']) !== 'string') {
throw new LogicException('Directory location must be a string value');
}
if (empty($data['location'])) {
throw new LogicException('Directory location must not be an empty string');
}
$this->id = $id;
$this->name = $data['name'] ?? null;
$this->location = $data['location'];
if (empty($this->name)) {
$this->name = 'Directory ' . $this->id;
}
if (substr($this->location, -1) !== '/') {
$this->location .= '/';
}
}
/**
* Returns an array with directory configuration data.
*
* @return array
*/
public function toArray(): array
{
return [
'id' => $this->id,
'name' => $this->name,
'location' => $this->location
];
}
/**
* Checks the existence and accessibility of the directory. Returns the result as an array.
*
* @return array
*/
public function check(): array
{
try {
self::checkPath($this->location, true);
self::checkPath($this->location . 'failed/', false);
} catch (RuntimeException $e) {
return ErrorHandler::exceptionResult($e);
}
return [
'error_code' => 0,
'message' => 'Successfully',
'status' => [
'files' => $this->count()
]
];
}
/**
* Returns the total number of files in the directory.
*
* @return int
*/
public function count(): int
{
$cnt = 0;
try {
$fs = new \FilesystemIterator($this->location);
} catch (\Exception $e) {
throw new RuntimeException("Error accessing directory {$this->location}", -1, $e);
}
foreach ($fs as $entry) {
if ($entry->isFile()) {
++$cnt;
}
}
return $cnt;
}
/**
* Checks accessibility of a directory by its path. Throws an exception in case of any error.
*
* @param string $path Path to the directory to check.
* @param bool $existence If true, the absence of the directory causes an error.
*
* @return void
*/
private static function checkPath(string $path, bool $existence): void
{
if (!file_exists($path)) {
if ($existence) {
throw new SoftException($path . ' directory does not exist!');
}
return;
}
if (!is_dir($path)) {
throw new SoftException($path . ' is not a directory!');
}
if (!is_readable($path)) {
throw new SoftException($path . ' directory is not readable!');
}
if (!is_writable($path)) {
throw new SoftException($path . ' directory is not writable!');
}
}
}

View File

@ -0,0 +1,147 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class DirectoryList
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Directories;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* This class is designed to work with the list of report directories which are listed in the configuration file.
*/
class DirectoryList
{
private $list = null;
/**
* Returns a list of directories for the setting file
*
* @return array Array with instances of Directory class
*/
public function list(): array
{
$this->ensureList();
return $this->list;
}
/**
* Returns an instance of the Directory class by its Id
*
* @param int $id Id of the required directory
*
* @return Directory
*/
public function directory(int $id)
{
$this->ensureList();
if ($id <= 0 || $id > count($this->list)) {
throw new LogicException('Incorrect directory Id');
}
return $this->list[$id - 1];
}
/**
* Checks the accessibility of the specified directory or all the directories from configuration file if $id is 0.
*
* @param int $id Directory Id to check
*
* @return array Result array with `error_code` and `message` fields. For one directory and if there is no error,
* a field `status` will be added to the result.
*/
public function check(int $id): array
{
if ($id !== 0) {
$dir = $this->directory($id);
return $dir->check();
}
$this->ensureList();
$results = [];
$err_cnt = 0;
$dir_cnt = count($this->list);
for ($i = 0; $i < $dir_cnt; ++$i) {
$r = $this->list[$i]->check();
if ($r['error_code'] !== 0) {
++$err_cnt;
}
$results[] = $r;
}
$res = [];
if ($err_cnt === 0) {
$res['error_code'] = 0;
$res['message'] = 'Successfully';
} else {
$res['error_code'] = -1;
$res['message'] = sprintf('%d of %d directories have failed the check', $err_cnt, $dir_cnt);
}
$res['results'] = $results;
return $res;
}
/**
* Creates an array of directories from the configuration file if it does not exist
* for using in other methods of the class.
*
* @return void
*/
private function ensureList(): void
{
if (!is_null($this->list)) {
return;
}
$directories = Core::instance()->config('directories');
$this->list = [];
if (is_array($directories)) {
$cnt = count($directories);
if ($cnt > 0) {
if (isset($directories[0])) {
$id = 1;
for ($i = 0; $i < $cnt; ++$i) {
try {
$this->list[] = new Directory($id, $directories[$i]);
++$id;
} catch (LogicException $d) {
// Just ignore this directory setting.
}
}
} else {
try {
$this->list[] = new Directory(1, $directories);
} catch (LogicException $e) {
// Just ignore this directory setting.
}
}
}
}
}
}

View File

@ -0,0 +1,286 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Domain
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Domains;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* It's a class for accessing to stored domains data
*
* This class is designed for storing and manipulating domain data.
* All queries to the datatabase are made in lazy mode.
*/
class Domain
{
private $db = null;
private $ex_f = null;
private $data = [
'id' => null,
'fqdn' => null,
'active' => null,
'description' => null,
'created_time' => null,
'updated_time' => null
];
/**
* It's a constructor of the class
*
* Some examples of using:
* (new Domain(1))->fqdn(); - will return the fully qualified domain name for the domain with id = 1
* (new Domain('example.com'))->description(); - will return the description for the domain example.com
* (new Domain([ 'fqdn' => 'example.com', 'description' => 'an expample domain' ])->save(); - will add
* this domain to the database if it does not exist in it.
*
* @param int|string|array $data Some domain data to identify it
* int value is treated as domain id
* string value is treated as a FQDN
* array has these fields: `id`, `fqdn`, `active`, `description`
* and usually uses for creating a new domain item.
* Note: The values of the fields `created_time` and `updated_time`
* will be ignored while saving to the database.
* @param DatabaseController $db The database controller
*
* @return void
*/
public function __construct($data, $db = null)
{
$this->db = $db ?? Core::instance()->database();
switch (gettype($data)) {
case 'integer':
$this->data['id'] = $data;
return;
case 'string':
$this->data['fqdn'] = strtolower($data);
$this->checkFqdn();
return;
case 'array':
if (isset($data['id'])) {
if (gettype($data['id']) !== 'integer') {
break;
}
$this->data['id'] = $data['id'];
}
if (isset($data['fqdn'])) {
if (gettype($data['fqdn']) !== 'string') {
break;
}
$this->data['fqdn'] = strtolower($data['fqdn']);
$this->checkFqdn();
}
if (isset($data['active'])) {
if (gettype($data['active']) !== 'boolean') {
break;
}
$this->data['active'] = $data['active'];
} else {
$this->data['active'] = false;
}
if (isset($data['description'])) {
if (gettype($data['description']) !== 'string') {
break;
}
$this->data['description'] = $data['description'];
}
if (isset($data['created_time'])) {
if (gettype($data['created_time']) !== 'object') {
break;
}
$this->data['created_time'] = $data['created_time'];
}
if (isset($data['updated_time'])) {
if (gettype($data['updated_time']) !== 'object') {
break;
}
$this->data['updated_time'] = $data['updated_time'];
}
if (!is_null($this->data['id']) || !is_null($this->data['fqdn'])) {
return;
}
}
throw new LogicException('Wrong domain data');
}
/**
* Returns true if the domain exists in the database or false otherwise
*
* @return bool Whether the domain exists
*/
public function exists(): bool
{
if (is_null($this->ex_f)) {
$this->ex_f = $this->db->getMapper('domain')->exists($this->data);
}
return $this->ex_f;
}
/**
* Returns the domain id
*
* @return int The domain id
*/
public function id(): int
{
if (is_null($this->data['id'])) {
$this->fetchData();
}
return $this->data['id'];
}
/**
* Returns the domain's FQDN
*
* @return string FQDN for the domain
*/
public function fqdn(): string
{
if (is_null($this->data['fqdn'])) {
$this->fetchData();
}
return $this->data['fqdn'];
}
/**
* Whether the domain is active or not
*
* When the domain is inactive, all incoming reports for it are ignored
* but the domain will still be included in summary reports.
*
* @return bool
*/
public function active(): bool
{
if (is_null($this->data['active'])) {
$this->fetchData();
}
return $this->data['active'];
}
/**
* Returns the domain's description
*
* @return string|null The description of the domain if it exists or null otherwise
*/
public function description()
{
if (is_null($this->data['id']) || is_null($this->data['fqdn'])) {
$this->fetchData();
}
return $this->data['description'];
}
/**
* Returns an array with domain data
*
* @return array Domain data
*/
public function toArray(): array
{
if (is_null($this->data['id']) || is_null($this->data['fqdn'])) {
$this->fetchData();
}
$res = $this->data;
unset($res['id']);
return $res;
}
/**
* Saves the domain to the database
*
* Updates the domain's description in the database if the domain exists or insert a new record otherwise.
* The domain id is ignored in the insert mode.
*
* @return void
*/
public function save(): void
{
$this->db->getMapper('domain')->save($this->data);
$this->ex_f = true;
}
/**
* Deletes the domain from the database
*
* Deletes the domain if there are no reports for this domain in the database.
* If you want to stop handling reports for this domain, just make it inactive.
*
* @return void
*/
public function delete(): void
{
if (is_null($this->data['id'])) {
$this->fetchData();
}
$this->db->getMapper('domain')->delete($this->data);
$this->ex_f = false;
}
/**
* Removes the trailing dot from the domain name and checks it for an empty value.
*
* @return void
*/
private function checkFqdn(): void
{
$fqdn = trim($this->data['fqdn']);
if (substr($fqdn, -1) === '.') {
$fqdn = trim(substr($fqdn, 0, -1));
}
if ($fqdn === '') {
throw new SoftException('The domain name must not be an empty string');
}
$this->data['fqdn'] = $fqdn;
}
/**
* Fetches the domain data from the database by its id or name
*
* @return void
*/
private function fetchData(): void
{
if ($this->ex_f === false) {
return;
}
try {
$this->db->getMapper('domain')->fetch($this->data);
$this->ex_f = true;
} catch (DatabaseNotFoundException $e) {
$this->ex_f = false;
throw new SoftException('Domain not found');
}
}
}

View File

@ -0,0 +1,79 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class DomainList
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Domains;
use Liuch\DmarcSrg\Core;
/**
* This class is designed to work with the list of domains
*/
class DomainList
{
private $db = null;
/**
* The constructor
*
* @param DatabaseController $db The database controller
*/
public function __construct($db = null)
{
$this->db = $db ?? Core::instance()->database();
}
/**
* Returns a list of domains from the database
*
* @return array Array with instances of Domain class
*/
public function getList(): array
{
$list = [];
foreach ($this->db->getMapper('domain')->list() as $dd) {
$list[] = new Domain($dd, $this->db);
}
return [
'domains' => $list,
'more' => false
];
}
/**
* Returns an ordered array with domain names from the database
*
* @return array Array of strings
*/
public function names(): array
{
return $this->db->getMapper('domain')->names();
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains ErrorHandler class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Log\LoggerInterface;
use Liuch\DmarcSrg\Log\LoggerAwareInterface;
use Liuch\DmarcSrg\Exception\SoftException;
/**
* Uncaught exception handler
*/
class ErrorHandler implements LoggerAwareInterface
{
private $core = null;
private $logger = null;
/**
* The constructor
*
* @param Core $core
*/
public function __construct(object $core)
{
$this->core = $core;
}
/**
* Handle uncaught exceptions. Used by set_exception_handler and set_error_handler functions
*
* @param Throwable $e an exception to handle. For set_error_handler it is ErrorException.
*
* @return void
*/
public function handleException(\Throwable $e): void
{
$debug = $this->core->config('debug', 0);
if ($this->logger) {
$this->logger->error(strval($e));
}
if (php_sapi_name() === 'cli') {
echo self::getText($e, $debug);
exit(1);
} else {
Core::sendJson(self::getResult($e, $debug));
}
}
/**
* Returns an result array based on the passed exception's data.
* If the debug mode is enabled, the `debug_info` field will be added to the result.
*
* @param Throwable $e an exception for which the result is generated
*
* @return array
*/
public static function exceptionResult(\Throwable $e): array
{
return self::getResult($e, Core::instance()->config('debug', 0));
}
/**
* Returns information about the passed exception as text.
* If the debug is enabled, debug information will be added.
*
* @param Throwable $e an exception for which the text is generated
*
* @return string
*/
public static function exceptionText(\Throwable $e): string
{
return self::getText($e, Core::instance()->config('debug', 0));
}
/**
* Sets a logger to log uncaught exceptions and errors
*/
public function setLogger(LoggerInterface $logger): void
{
$this->logger = $logger;
}
/**
* Returns the current logger
*/
public function logger()
{
return $this->logger;
}
private static function getResult(\Throwable $e, int $debug): array
{
$code = $e->getCode();
if ($code === 0) {
$code = -1;
}
$res = [
'error_code' => $code,
'message' => $e->getMessage()
];
if ($debug &&
(Core::instance()->userId() !== false || php_sapi_name() === 'cli') &&
!($e instanceof SoftException)
) {
$prev = $e->getPrevious();
$res['debug_info'] = [
'code' => ($prev ?? $e)->getCode(),
'content' => strval($prev ?? $e)
];
}
return $res;
}
private static function getText(\Throwable $e, int $debug): string
{
$msg = 'Error: ' . $e->getMessage() . ' (' . $e->getCode() . ')' . PHP_EOL;
if (!$debug) {
return $msg;
}
return '-----' . PHP_EOL
. $msg
. '-----' . PHP_EOL
. $e . PHP_EOL;
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains AuthException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Represents an authentication error
*/
class AuthException extends SoftException
{
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains DatabaseException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Represents an error in the database
*/
class DatabaseException extends RuntimeException
{
}

View File

@ -0,0 +1,66 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains DatabaseExceptionFactory class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Factory class for DatabaseException
*/
class DatabaseExceptionFactory
{
/**
* Creates a DatabaseException instance with an appropriate message based on the passed class's name and error code.
*
* @param Exception $origin The original exception
*
* @return DatabaseException
*/
public static function fromException(\Throwable $origin)
{
$msg = null;
if (get_class($origin) === 'PDOException') {
switch ($origin->getCode()) {
case 1044:
case 1045:
$msg = 'Database access denied';
break;
case 2002:
case 2006:
$msg = 'Database connection error';
break;
}
}
if (!$msg) {
$msg = 'Database error';
}
return new DatabaseException($msg, -1, $origin);
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains DatabaseFatalException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Represents an error in the database
*/
class DatabaseFatalException extends LogicException
{
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains DatabaseNotFoundException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Represents the case where a row was not found in the database
*/
class DatabaseNotFoundException extends DatabaseException
{
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains LogicException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Base LogicException
*/
class LogicException extends \LogicException
{
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains MailboxException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Represents an error of a mailbox
*/
class MailboxException extends RuntimeException
{
}

View File

@ -0,0 +1,43 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains RuntimeException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* Base RuntimeException
*/
class RuntimeException extends \RuntimeException
{
public function __construct(string $message = '', int $code = -1, \Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}

View File

@ -0,0 +1,39 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains SoftException class
*
* @category Common
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Exception;
/**
* This exception is ignored in the debug mode
*/
class SoftException extends RuntimeException
{
}

View File

@ -0,0 +1,47 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class LogLevel
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Log;
/**
* Describes log levels
*/
class LogLevel
{
const EMERGENCY = 'emergency';
const ALERT = 'alert';
const CRITICAL = 'critical';
const ERROR = 'error';
const WARNING = 'warning';
const NOTICE = 'notice';
const INFO = 'info';
const DEBUG = 'debug';
}

View File

@ -0,0 +1,47 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the interface LoggerAwareInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Log;
/**
* Describes a logger-aware instance
*/
interface LoggerAwareInterface
{
/**
* Sets a logger instance on the object
*
* @param LoggerInterface $logger
*
* @return void
*/
public function setLogger(LoggerInterface $logger): void;
}

View File

@ -0,0 +1,131 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the interface LoggerInterface
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Log;
/**
* Describes a logger instance
* The message MUST be a string or object implementing __toString().
*/
interface LoggerInterface
{
/**
* System is unusable
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = []): void;
/**
* Action must be taken immediately
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = []): void;
/**
* Critical conditions
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = []): void;
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = []): void;
/**
* Exceptional occurrences that are not errors
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = []): void;
/**
* Normal but significant events
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = []): void;
/**
* Interesting events
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = []): void;
/**
* Detailed debug information
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = []): void;
/**
* Logs with an arbitrary level
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = []): void;
}

View File

@ -0,0 +1,172 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2022 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class PhpSystemLogger;
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Log;
/**
* Implements a logger to log messages via PHP's system logger,
* using the OS's system logging mechanism or a file, depending on
* what the error_log PHP configuration directive is set to.
*/
class PhpSystemLogger implements LoggerInterface
{
/**
* System is unusable
*
* @param string $message
* @param array $context
*
* @return void
*/
public function emergency($message, array $context = []): void
{
$this->log(LogLevel::EMERGENCY, $message, $context);
}
/**
* Action must be taken immediately
*
* @param string $message
* @param array $context
*
* @return void
*/
public function alert($message, array $context = []): void
{
$this->log(LogLevel::ALERT, $message, $context);
}
/**
* Critical conditions
*
* @param string $message
* @param array $context
*
* @return void
*/
public function critical($message, array $context = []): void
{
$this->log(LogLevel::CRITICAL, $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored
*
* @param string $message
* @param array $context
*
* @return void
*/
public function error($message, array $context = []): void
{
$this->log(LogLevel::ERROR, $message, $context);
}
/**
* Exceptional occurrences that are not errors
*
* @param string $message
* @param array $context
*
* @return void
*/
public function warning($message, array $context = []): void
{
$this->log(LogLevel::WARNING, $message, $context);
}
/**
* Normal but significant events
*
* @param string $message
* @param array $context
*
* @return void
*/
public function notice($message, array $context = []): void
{
$this->log(LogLevel::NOTICE, $message, $context);
}
/**
* Interesting events
*
* @param string $message
* @param array $context
*
* @return void
*/
public function info($message, array $context = []): void
{
$this->log(LogLevel::INFO, $message, $context);
}
/**
* Detailed debug information
*
* @param string $message
* @param array $context
*
* @return void
*/
public function debug($message, array $context = []): void
{
$this->log(LogLevel::DEBUG, $message, $context);
}
/**
* Logs with an arbitrary level
*
* @param mixed $level
* @param string $message
* @param array $context
*
* @return void
*/
public function log($level, $message, array $context = []): void
{
switch ($level) {
case LogLevel::EMERGENCY:
case LogLevel::ALERT:
case LogLevel::CRITICAL:
case LogLevel::ERROR:
case LogLevel::WARNING:
case LogLevel::NOTICE:
case LogLevel::INFO:
case LogLevel::DEBUG:
break;
default:
throw new \InvalidArgumentException('Invalid log level argument');
}
\error_log("dmarc-srg [{$level}]: {$message}");
}
}

View File

@ -0,0 +1,110 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Mail;
use Liuch\DmarcSrg\ReportFile\ReportFile;
use Liuch\DmarcSrg\Exception\SoftException;
class MailAttachment
{
private $conn;
private $filename;
private $bytes;
private $number;
private $mnumber;
private $encoding;
private $stream;
private $mime_type;
public function __construct($conn, $params)
{
$this->conn = $conn;
$this->filename = $params['filename'];
$this->bytes = $params['bytes'];
$this->number = $params['number'];
$this->mnumber = $params['mnumber'];
$this->encoding = $params['encoding'];
$this->stream = null;
$this->mime_type = null;
}
public function __destruct()
{
if (!is_null($this->stream) && get_resource_type($this->stream) == 'stream') {
fclose($this->stream);
}
}
public function mimeType()
{
if (is_null($this->mime_type)) {
$this->mime_type = ReportFile::getMimeType($this->filename, $this->datastream());
}
return $this->mime_type;
}
public function size()
{
return $this->bytes;
}
public function filename()
{
return $this->filename;
}
public function extension()
{
return pathinfo($this->filename, PATHINFO_EXTENSION);
}
public function datastream()
{
if (is_null($this->stream)) {
$this->stream = fopen('php://temp', 'r+');
fwrite($this->stream, $this->toString());
}
rewind($this->stream);
return $this->stream;
}
private function fetchBody()
{
return imap_fetchbody($this->conn, $this->mnumber, strval($this->number), FT_PEEK);
}
private function toString()
{
switch ($this->encoding) {
case ENC7BIT:
case ENC8BIT:
case ENCBINARY:
return $this->fetchBody();
case ENCBASE64:
return base64_decode($this->fetchBody());
case ENCQUOTEDPRINTABLE:
return imap_qprint($this->fetchBody());
}
throw new SoftException('Encoding failed: Unknown encoding');
}
}

View File

@ -0,0 +1,142 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Mail;
/**
* The class is designed to easily create multipart/alternative message bodies.
*/
class MailBody
{
private $text = null;
private $html = null;
private $boundary = null;
/**
* Sets text content as a part of the message body
*
* @param array $text Text part of the message as an array of strings
*
* @return void
*/
public function setText(array &$text): void
{
$this->text = $text;
}
/**
* Sets html content as a part of the message body
*
* @param array $html Html part of the message as and array of strings
*
* @return void
*/
public function setHtml(array $html): void
{
$this->html = $html;
}
/**
* Return Content-Type header value for the whole message
*
* @return string
*/
public function contentType(): string
{
if ($this->boundary()) {
$ctype = 'multipart/alternative; boundary="' . $this->boundary() . '"';
} else {
if (!is_null($this->html)) {
$ctype = 'text/html';
} else {
$ctype = 'text/plain';
}
$ctype .= '; charset=utf-8';
}
return $ctype;
}
/**
* Returns all the message parts with required headers as an array of strings
*
* @return array
*/
public function content(): array
{
$content = [];
if ($this->text) {
$this->addBodyPart('text', $this->text, $content);
}
if ($this->html) {
$this->addBodyPart('html', $this->html, $content);
}
return $content;
}
/**
* Generates a boundary string of the message. If the body has only one part of the content
* it returns null
*
* @return string|null
*/
private function boundary()
{
if (!$this->boundary) {
if ($this->text && $this->html) {
$this->boundary = '==========' . sha1(uniqid()) . '=====';
}
}
return $this->boundary;
}
/**
* Adds the specified part of the content to the array passed as the third parameter
* with the required headers.
*
* @param string $type Type of the content to add
* @param array $part Part of the content to add
* @param array $content Where the data with headers should be added
*
* @return void
*/
private function addBodyPart(string $type, array &$part, array &$content): void
{
if ($this->boundary()) {
$content[] = '--' . $this->boundary();
switch ($type) {
case 'text':
$ctype = 'text/plain';
break;
case 'html':
$ctype = 'text/html';
break;
}
$content[] = 'Content-Type: ' . $ctype . '; charset=utf-8';
$content[] = 'Content-Transfer-Encoding: 7bit';
$content[] = '';
}
foreach ($part as $row) {
$content[] = $row;
}
unset($part);
}
}

View File

@ -0,0 +1,468 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Mail;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\MailboxException;
class MailBox
{
private $conn;
private $server;
private $host;
private $mbox;
private $name;
private $uname;
private $passw;
private $delim;
private $attrs;
private $expunge;
private $options;
public function __construct($params)
{
if (!is_array($params)) {
throw new LogicException('Incorrect mailbox params');
}
$this->conn = null;
$this->uname = $params['username'];
$this->passw = $params['password'];
if (isset($params['name']) && is_string($params['name']) && strlen($params['name']) > 0) {
$this->name = $params['name'];
} else {
$name = $this->uname;
$pos = strpos($name, '@');
if ($pos !== false && $pos !== 0) {
$name = substr($name, 0, $pos);
}
$this->name = $name;
}
$this->mbox = $params['mailbox'];
$this->host = $params['host'];
$flags = $params['encryption'] ?? '';
switch ($flags) {
case 'ssl':
default:
$flags = '/ssl';
break;
case 'none':
$flags = '/notls';
break;
case 'starttls':
$flags = '/tls';
break;
}
if (isset($params['novalidate-cert']) && $params['novalidate-cert'] === true) {
$flags .= '/novalidate-cert';
}
$this->server = sprintf('{%s/imap%s}', $this->host, $flags);
$this->expunge = false;
$this->options = [];
if (isset($params['auth_exclude'])) {
$auth_exclude = $params['auth_exclude'];
switch (gettype($auth_exclude)) {
case 'string':
$auth_exclude = [ $auth_exclude ];
break;
case 'array':
break;
default:
$auth_exclude = null;
break;
}
if ($auth_exclude) {
$this->options['DISABLE_AUTHENTICATOR'] = $auth_exclude;
}
}
}
public function __destruct()
{
if (extension_loaded('imap')) {
$this->cleanup();
}
}
public function childMailbox(string $mailbox_name)
{
$this->ensureConnection();
try {
$mb_list = imap_list(
$this->conn,
self::utf8ToMutf7($this->server),
self::utf8ToMutf7($this->mbox) . $this->delim . self::utf8ToMutf7($mailbox_name)
);
} catch (\ErrorException $e) {
$mb_list = false;
}
$this->ensureErrorLog('imap_list');
if (!$mb_list) {
return null;
}
$child = clone $this;
$child->mbox .= $this->delim . $mailbox_name;
$child->conn = null;
$child->expunge = false;
return $child;
}
public function name()
{
return $this->name;
}
public function host()
{
return $this->host;
}
public function mailbox()
{
return $this->mbox;
}
public function check()
{
try {
$this->ensureConnection();
try {
$res = imap_status(
$this->conn,
self::utf8ToMutf7($this->server . $this->mbox),
SA_MESSAGES | SA_UNSEEN
);
} catch (\ErrorException $e) {
$res = false;
}
$error_message = $this->ensureErrorLog();
if (!$res) {
throw new MailboxException($error_message ?? 'Failed to get the mail box status');
}
if ($this->attrs & \LATT_NOSELECT) {
throw new MailboxException('The resource is not a mailbox');
}
$this->checkRights();
} catch (MailboxException $e) {
return ErrorHandler::exceptionResult($e);
}
return [
'error_code' => 0,
'message' => 'Successfully',
'status' => [
'messages' => $res->messages,
'unseen' => $res->unseen
]
];
}
public function search($criteria)
{
$this->ensureConnection();
try {
$res = imap_search($this->conn, $criteria);
} catch (\ErrorException $e) {
$res = false;
}
$error_message = $this->ensureErrorLog('imap_search');
if ($res === false) {
if (!$error_message) {
return [];
}
throw new MailboxException(
'Failed to search email messages',
-1,
new \ErrorException($error_message)
);
}
return $res;
}
public function sort($criteria, $search_criteria, $reverse)
{
$this->ensureConnection();
try {
$res = imap_sort($this->conn, $criteria, $reverse ? 1 : 0, SE_NOPREFETCH, $search_criteria);
} catch (\ErrorException $e) {
$res = false;
}
$error_message = $this->ensureErrorLog('imap_sort');
if ($res === false) {
if (!$error_message) {
return [];
}
throw new MailboxException(
'Failed to sort email messages',
-1,
new \ErrorException($error_message)
);
}
return $res;
}
public function message($number)
{
return new MailMessage($this->conn, $number);
}
public function ensureMailbox($mailbox_name)
{
$mbn = self::utf8ToMutf7($mailbox_name);
$srv = self::utf8ToMutf7($this->server);
$mbo = self::utf8ToMutf7($this->mbox);
$this->ensureConnection();
try {
$mb_list = imap_list($this->conn, $srv, $mbo . $this->delim . $mbn);
} catch (\ErrorException $e) {
$mb_list = false;
}
$error_message = $this->ensureErrorLog('imap_list');
if (empty($mb_list)) {
if ($error_message) {
throw new MailboxException(
'Failed to get the list of mailboxes',
-1,
new \ErrorException($error_message)
);
}
$new_mailbox = "{$srv}{$mbo}{$this->delim}{$mbn}";
try {
$res = imap_createmailbox($this->conn, $new_mailbox);
} catch (\ErrorException $e) {
$res = false;
}
$error_message = $this->ensureErrorLog('imap_createmailbox');
if (!$res) {
throw new MailboxException(
'Failed to create a new mailbox',
-1,
new \ErrorException($error_message ?? 'Unknown')
);
}
try {
imap_subscribe($this->conn, $new_mailbox);
} catch (\ErrorException $e) {
}
$this->ensureErrorLog('imap_subscribe');
}
}
public function moveMessage($number, $mailbox_name)
{
$this->ensureConnection();
$target = self::utf8ToMutf7($this->mbox) . $this->delim . self::utf8ToMutf7($mailbox_name);
try {
$res = imap_mail_move($this->conn, strval($number), $target);
} catch (\ErrorException $e) {
$res = false;
}
$error_message = $this->ensureErrorLog('imap_mail_move');
if (!$res) {
throw new MailboxException(
'Failed to move a message',
-1,
new \ErrorException($error_message ?? 'Unknown')
);
}
$this->expunge = true;
}
public function deleteMessage($number)
{
$this->ensureConnection();
try {
imap_delete($this->conn, strval($number));
} catch (\ErrorException $e) {
}
$this->ensureErrorLog('imap_delete');
$this->expunge = true;
}
public static function resetErrorStack()
{
imap_errors();
imap_alerts();
}
private function ensureConnection()
{
if (is_null($this->conn)) {
$error_message = null;
$srv = self::utf8ToMutf7($this->server);
try {
$this->conn = imap_open(
$srv,
$this->uname,
$this->passw,
OP_HALFOPEN,
0,
$this->options
);
} catch (\ErrorException $e) {
$this->conn = null;
}
if ($this->conn) {
$mbx = self::utf8ToMutf7($this->mbox);
try {
$mb_list = imap_getmailboxes($this->conn, $srv, $mbx);
} catch (\ErrorException $e) {
$mb_list = null;
}
if ($mb_list && count($mb_list) === 1) {
$this->delim = $mb_list[0]->delimiter ?? '/';
$this->attrs = $mb_list[0]->attributes ?? 0;
try {
if (imap_reopen($this->conn, $srv . $mbx)) {
return;
}
} catch (\ErrorException $e) {
}
} else {
$error_message = "Mailbox `{$this->mbox}` not found";
}
}
if (!$error_message) {
$error_message = imap_last_error();
if (!$error_message) {
$error_message = 'Cannot connect to the mail server';
}
}
Core::instance()->logger()->error("IMAP error: {$error_message}");
self::resetErrorStack();
if ($this->conn) {
try {
imap_close($this->conn);
} catch (\ErrorException $e) {
}
$this->ensureErrorLog('imap_close');
}
$this->conn = null;
throw new MailboxException($error_message);
}
}
private function ensureErrorLog(string $prefix = 'IMAP error')
{
if ($error_message = imap_last_error()) {
self::resetErrorStack();
$error_message = "{$prefix}: {$error_message}";
Core::instance()->logger()->error($error_message);
return $error_message;
}
return null;
}
private function checkRights(): void
{
if ($this->attrs & \LATT_NOINFERIORS) {
throw new SoftException('The mailbox may not have any children mailboxes');
}
if (!function_exists('imap_getacl')) {
return;
}
$mbox = self::utf8ToMutf7($this->mbox);
try {
$acls = imap_getacl($this->conn, $mbox);
} catch (\ErrorException $e) {
// It's not possible to get the ACLs information
$acls = false;
}
$this->ensureErrorLog('imap_getacl');
if ($acls !== false) {
$needed_rights_map = [
'l' => 'LOOKUP',
'r' => 'READ',
's' => 'WRITE-SEEN',
't' => 'WRITE-DELETE',
'k' => 'CREATE'
];
$result = [];
$needed_rights = array_keys($needed_rights_map);
foreach ([ "#{$this->uname}", '#authenticated', '#anyone' ] as $identifier) {
if (isset($acls[$identifier])) {
$rights = $acls[$identifier];
foreach ($needed_rights as $r) {
if (!str_contains($rights, $r)) {
$result[] = $needed_rights_map[$r];
}
}
break;
}
}
if (count($result) > 0) {
throw new SoftException(
'Not enough rights. Additionally, these rights are required: ' . implode(', ', $result)
);
}
}
}
/**
* Deletes messages marked for deletion, if any, and closes the connection
*
* @return void
*/
private function cleanup(): void
{
self::resetErrorStack();
if (!is_null($this->conn)) {
try {
if ($this->expunge) {
imap_expunge($this->conn);
}
} catch (\ErrorException $e) {
}
$this->ensureErrorLog('imap_expunge');
try {
imap_close($this->conn);
} catch (\ErrorException $e) {
}
$this->ensureErrorLog('imap_close');
}
}
/**
* It's a replacement for the standard function imap_utf8_to_mutf7
*
* @param string $s A UTF-8 encoded string
*
* @return string|false
*/
private static function utf8ToMutf7(string $s)
{
return mb_convert_encoding($s, 'UTF7-IMAP', 'UTF-8');
}
}

View File

@ -0,0 +1,137 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Mail;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\RuntimeException;
use Liuch\DmarcSrg\Exception\MailboxException;
class MailBoxes implements \Iterator
{
private $box_list;
private $index = 0;
public function __construct()
{
$mailboxes = Core::instance()->config('mailboxes');
$this->box_list = [];
if (is_array($mailboxes)) {
$cnt = count($mailboxes);
if ($cnt > 0) {
if (isset($mailboxes[0])) {
for ($i = 0; $i < $cnt; ++$i) {
$this->box_list[] = new MailBox($mailboxes[$i]);
}
} else {
$this->box_list[] = new MailBox($mailboxes);
}
}
}
}
public function count()
{
return count($this->box_list);
}
public function list()
{
$id = 0;
$res = [];
foreach ($this->box_list as &$mbox) {
$id += 1;
$res[] = [
'id' => $id,
'name' => $mbox->name(),
'host' => $mbox->host(),
'mailbox' => $mbox->mailbox()
];
}
unset($mbox);
return $res;
}
public function mailbox($id)
{
if (!is_int($id) || $id <= 0 || $id > count($this->box_list)) {
throw new LogicException("Incorrect mailbox Id: {$i}");
}
return $this->box_list[$id - 1];
}
public function check($id)
{
if ($id !== 0) {
return $this->mailbox($id)->check();
}
$results = [];
$err_cnt = 0;
$box_cnt = count($this->box_list);
for ($i = 0; $i < $box_cnt; ++$i) {
$r = $this->box_list[$i]->check();
if ($r['error_code'] !== 0) {
++$err_cnt;
}
$results[] = $r;
}
$res = [];
if ($err_cnt == 0) {
$res['error_code'] = 0;
$res['message'] = 'Success';
} else {
$res['error_code'] = -1;
$res['message'] = sprintf('%d of the %d mailboxes failed the check', $err_cnt, $box_cnt);
}
$res['results'] = $results;
return $res;
}
public function current(): object
{
return $this->box_list[$this->index];
}
public function key(): int
{
return $this->index;
}
public function next(): void
{
++$this->index;
}
public function rewind(): void
{
$this->index = 0;
}
public function valid(): bool
{
return isset($this->box_list[$this->index]);
}
}

View File

@ -0,0 +1,154 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Mail;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\MailboxException;
class MailMessage
{
private $conn;
private $number;
private $attachment;
private $attachments_cnt;
public function __construct($conn, $number)
{
$this->conn = $conn;
$this->number = $number;
$this->attachment = null;
$this->attachments_cnt = -1;
}
public function overview()
{
$res = @imap_fetch_overview($this->conn, strval($this->number));
if (!isset($res[0])) {
if ($error_message = imap_last_error()) {
Core::instance()->logger()->error("imap_fetch_overview failed: {$error_message}");
}
MailBox::resetErrorStack();
return false;
}
return $res[0];
}
public function setSeen()
{
if (!@imap_setflag_full($this->conn, strval($this->number), '\\Seen')) {
if ($error_message = imap_last_error()) {
$error_message = '?';
}
MailBox::resetErrorStack();
Core::instance()->logger()->error("imap_setflag_full failed: {$error_message}");
throw new MailboxException("Failed to make a message seen: {$error_message}");
}
}
public function validate()
{
$this->ensureAttachment();
if ($this->attachments_cnt !== 1) {
throw new SoftException("Attachment count is not valid ({$this->attachments_cnt})");
}
$bytes = $this->attachment->size();
if ($bytes === -1) {
throw new SoftException("Failed to get attached file size. Wrong message format?");
}
if ($bytes < 50 || $bytes > 1 * 1024 * 1024) {
throw new SoftException("Attachment file size is not valid ({$bytes} bytes)");
}
$mime_type = $this->attachment->mimeType();
if (!in_array($mime_type, [ 'application/zip', 'application/gzip', 'application/x-gzip', 'text/xml' ])) {
throw new SoftException("Attachment file type is not valid ({$mime_type})");
}
}
public function attachment()
{
return $this->attachment;
}
private function ensureAttachment()
{
if ($this->attachments_cnt === -1) {
$structure = imap_fetchstructure($this->conn, $this->number);
if ($structure === false) {
throw new MailboxException('FetchStructure failed: ' . imap_last_error());
}
$this->attachments_cnt = 0;
$parts = isset($structure->parts) ? $structure->parts : [ $structure ];
foreach ($parts as $index => &$part) {
$att_part = $this->scanAttachmentPart($part, $index + 1);
if ($att_part) {
++$this->attachments_cnt;
if (!$this->attachment) {
$this->attachment = new MailAttachment($this->conn, $att_part);
}
}
}
unset($part);
}
}
private function scanAttachmentPart(&$part, $number)
{
$filename = null;
if ($part->ifdparameters) {
$filename = $this->getAttribute($part->dparameters, 'filename');
}
if (empty($filename) && $part->ifparameters) {
$filename = $this->getAttribute($part->parameters, 'name');
}
if (empty($filename)) {
return null;
}
return [
'filename' => imap_utf8($filename),
'bytes' => isset($part->bytes) ? $part->bytes : -1,
'number' => $number,
'mnumber' => $this->number,
'encoding' => $part->encoding
];
}
private function getAttribute(&$params, $name)
{
// need to check all objects as imap_fetchstructure
// returns multiple objects with the same attribute name,
// but first entry contains a truncated value
$value = null;
foreach ($params as &$obj) {
if (strcasecmp($obj->attribute, $name) === 0) {
$value = $obj->value;
}
}
return $value;
}
}

View File

@ -0,0 +1,165 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Report;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
class Report
{
private $db = null;
private $data = null;
public function __construct($data, $db = null)
{
$this->data = $data;
$this->db = $db ?? Core::instance()->database();
}
public static function fromXmlFile($fd)
{
$data = ReportData::fromXmlFile($fd);
if (!self::checkData($data)) {
throw new SoftException('Incorrect or incomplete report data');
}
return new Report($data);
}
public function fetch()
{
$domain = $this->data['domain'];
$report_id = $this->data['report_id'];
if (empty($domain) || empty($report_id)) {
throw new SoftException('Not specified report\'s domain or id');
}
$this->data = [ 'domain' => $domain, 'report_id' => $report_id ];
try {
$this->db->getMapper('report')->fetch($this->data);
} catch (DatabaseNotFoundException $e) {
throw new SoftException('The report is not found');
}
}
public function save(string $real_fname)
{
$b_ts = $this->data['begin_time'];
$e_ts = $this->data['end_time'];
if (!$b_ts->getTimestamp() || !$e_ts->getTimestamp() || $b_ts > $e_ts) {
throw new SoftException('Failed to add an incoming report: wrong date range');
}
$this->db->getMapper('report')->save($this->data);
return [ 'message' => 'The report is loaded successfully' ];
}
public function get()
{
return $this->data;
}
public function set($name, $value)
{
if (empty($this->data['domain']) || empty($this->data['report_id'])) {
throw new SoftException('Not specified report\'s domain or id');
}
$this->db->getMapper('report')->setProperty($this->data, $name, $value);
return [ 'message' => 'Ok' ];
}
/**
* Checks report data for correctness and completeness
*
* @param array $data Report data
*
* @return bool
*/
private static function checkData(array $data): bool
{
static $fields = [
'domain' => [ 'required' => true, 'type' => 'string' ],
'begin_time' => [ 'required' => true, 'type' => 'object' ],
'end_time' => [ 'required' => true, 'type' => 'object' ],
'org' => [ 'required' => true, 'type' => 'string' ],
'external_id' => [ 'required' => true, 'type' => 'string' ],
'email' => [ 'required' => false, 'type' => 'string' ],
'extra_contact_info' => [ 'required' => false, 'type' => 'string' ],
'error_string' => [ 'required' => false, 'type' => 'array' ],
'policy_adkim' => [ 'required' => false, 'type' => 'string' ],
'policy_aspf' => [ 'required' => false, 'type' => 'string' ],
'policy_p' => [ 'required' => false, 'type' => 'string' ],
'policy_sp' => [ 'required' => false, 'type' => 'string' ],
'policy_np' => [ 'required' => false, 'type' => 'string' ],
'policy_pct' => [ 'required' => false, 'type' => 'string' ],
'policy_fo' => [ 'required' => false, 'type' => 'string' ],
'records' => [ 'required' => true, 'type' => 'array' ]
];
if (!self::checkRow($data, $fields) || count($data['records']) === 0) {
return false;
}
static $rfields = [
'ip' => [ 'required' => true, 'type' => 'string' ],
'rcount' => [ 'required' => true, 'type' => 'integer' ],
'disposition' => [ 'required' => true, 'type' => 'string' ],
'reason' => [ 'required' => false, 'type' => 'array' ],
'dkim_auth' => [ 'required' => false, 'type' => 'array' ],
'spf_auth' => [ 'required' => false, 'type' => 'array' ],
'dkim_align' => [ 'required' => true, 'type' => 'string' ],
'spf_align' => [ 'required' => true, 'type' => 'string' ],
'envelope_to' => [ 'required' => false, 'type' => 'string' ],
'envelope_from' => [ 'required' => false, 'type' => 'string' ],
'header_from' => [ 'required' => false, 'type' => 'string' ]
];
foreach ($data['records'] as &$rec) {
if (gettype($rec) !== 'array' || !self::checkRow($rec, $rfields)) {
return false;
}
}
return true;
}
/**
* Checks one row of report data
*
* @param array $row Data row
* @param array $def Row definition
*
* @return bool
*/
private static function checkRow(array &$row, array &$def): bool
{
foreach ($def as $key => &$dd) {
if (isset($row[$key])) {
if (gettype($row[$key]) !== $dd['type']) {
return false;
}
} elseif ($dd['required']) {
return false;
}
}
return true;
}
}

View File

@ -0,0 +1,370 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\Report;
use Liuch\DmarcSrg\DateTime;
use Liuch\DmarcSrg\Exception\RuntimeException;
class ReportData
{
public static $rep_data = null;
public static $tag_id = null;
public static function fromXmlFile($fd)
{
self::$tag_id = '<root>';
self::$rep_data = [ 'records' => [] ];
$parser = xml_parser_create();
xml_set_element_handler(
$parser,
'Liuch\DmarcSrg\Report\ReportData::xmlStartTag',
'Liuch\DmarcSrg\Report\ReportData::xmlEndTag'
);
xml_set_character_data_handler($parser, 'Liuch\DmarcSrg\Report\ReportData::xmlTagData');
xml_set_external_entity_ref_handler($parser, function () {
throw new RuntimeException('The XML document has an external entity!');
});
try {
while ($file_data = fread($fd, 4096)) {
if (!xml_parse($parser, $file_data, feof($fd))) {
throw new RuntimeException('XML error!');
}
}
} finally {
xml_parser_free($parser);
unset($parser);
}
return self::$rep_data;
}
public static function xmlStartTag($parser, $name, $attrs)
{
self::xmlEnterTag($name);
switch (self::$tag_id) {
case 'rec':
self::$rep_data['records'][] = [];
break;
case 'error_string':
if (!isset(self::$rep_data['error_string'])) {
self::$rep_data['error_string'] = [];
}
break;
case 'reason':
$idx = count(self::$rep_data['records']) - 1;
if (!isset(self::$rep_data['records'][$idx]['reason'])) {
self::$rep_data['records'][$idx]['reason'] = [];
}
self::$report_tags['reason']['tmp_data'] = [];
break;
case 'dkim_auth':
$idx = count(self::$rep_data['records']) - 1;
if (!isset(self::$rep_data['records'][$idx]['dkim_auth'])) {
self::$rep_data['records'][$idx]['dkim_auth'] = [];
}
self::$report_tags['dkim_auth']['tmp_data'] = [];
break;
case 'spf_auth':
$idx = count(self::$rep_data['records']) - 1;
if (!isset(self::$rep_data['records'][$idx]['spf_auth'])) {
self::$rep_data['records'][$idx]['spf_auth'] = [];
}
self::$report_tags['spf_auth']['tmp_data'] = [];
break;
}
}
public static function xmlEndTag($parser, $name)
{
switch (self::$tag_id) {
case 'reason':
$idx = count(self::$rep_data['records']) - 1;
self::$rep_data['records'][$idx]['reason'][] = self::$report_tags['reason']['tmp_data'];
unset(self::$report_tags['reason']['tmp_data']);
break;
case 'dkim_auth':
$idx = count(self::$rep_data['records']) - 1;
self::$rep_data['records'][$idx]['dkim_auth'][] = self::$report_tags['dkim_auth']['tmp_data'];
unset(self::$report_tags['dkim_auth']['tmp_data']);
break;
case 'spf_auth':
$idx = count(self::$rep_data['records']) - 1;
self::$rep_data['records'][$idx]['spf_auth'][] = self::$report_tags['spf_auth']['tmp_data'];
unset(self::$report_tags['spf_auth']['tmp_data']);
break;
case 'feedback':
// Set the default value if it's necessary and there is no data
foreach (self::$report_tags as $tag_id => &$tag_data) {
if (array_key_exists('default', $tag_data)) { // not isset() because of null values
if (isset($tag_data['header']) && $tag_data['header']) {
if (!isset(self::$rep_data[$tag_id])) {
self::$rep_data[$tag_id] = $tag_data['default'];
}
} else {
foreach (self::$rep_data['records'] as $idx => &$rec_val) {
if (!isset($rec_val[$tag_id])) {
$rec_val[$tag_id] = $tag_data['default'];
}
}
unset($rec_val);
}
}
}
unset($tag_data);
$b_ts = intval(self::$rep_data['begin_time']);
$e_ts = intval(self::$rep_data['end_time']);
self::$rep_data['begin_time'] = new DateTime('@' . ($b_ts < 0 ? 0 : $b_ts));
self::$rep_data['end_time'] = new DateTime('@' . ($e_ts < 0 ? 0 : $e_ts));
foreach (self::$rep_data['records'] as &$rec_data) {
$rec_data['rcount'] = intval($rec_data['rcount']);
}
unset($rec_data);
break;
}
self::xmlLeaveTag();
}
public static function xmlTagData($parser, $data)
{
switch (self::$tag_id) {
case 'error_string':
if (self::$tag_id === 'error_string') {
self::$rep_data['error_string'][] = $data;
}
break;
case 'reason_type':
self::$report_tags['reason']['tmp_data']['type'] = $data;
break;
case 'reason_comment':
self::$report_tags['reason']['tmp_data']['comment'] = $data;
break;
case 'dkim_domain':
self::$report_tags['dkim_auth']['tmp_data']['domain'] = $data;
break;
case 'dkim_selector':
self::$report_tags['dkim_auth']['tmp_data']['selector'] = $data;
break;
case 'dkim_result':
self::$report_tags['dkim_auth']['tmp_data']['result'] = $data;
break;
case 'dkim_human_result':
self::$report_tags['dkim_auth']['tmp_data']['human_result'] = $data;
break;
case 'spf_domain':
self::$report_tags['spf_auth']['tmp_data']['domain'] = $data;
break;
case 'spf_scope':
self::$report_tags['spf_auth']['tmp_data']['scope'] = $data;
break;
case 'spf_result':
self::$report_tags['spf_auth']['tmp_data']['result'] = $data;
break;
default:
if (!isset(self::$report_tags[self::$tag_id]['children'])) {
if (isset(self::$report_tags[self::$tag_id]['header']) &&
self::$report_tags[self::$tag_id]['header']
) {
if (!isset(self::$rep_data[self::$tag_id])) {
self::$rep_data[self::$tag_id] = $data;
} else {
self::$rep_data[self::$tag_id] .= $data;
}
} else {
$last_idx = count(self::$rep_data['records']) - 1;
$last_rec =& self::$rep_data['records'][$last_idx];
if (!isset($last_rec[self::$tag_id])) {
$last_rec[self::$tag_id] = $data;
} else {
$last_rec[self::$tag_id] .= $data;
}
unset($last_rec);
}
}
}
}
public static function xmlEnterTag($name)
{
if (!isset(self::$report_tags[self::$tag_id]['children']) ||
!isset(self::$report_tags[self::$tag_id]['children'][$name])
) {
throw new RuntimeException("Unknown tag: {$name}");
}
self::$tag_id = self::$report_tags[self::$tag_id]['children'][$name];
}
public static function xmlLeaveTag()
{
self::$tag_id = self::$report_tags[self::$tag_id]['parent'];
}
public static $report_tags = [
'<root>' => [
'children' => [
'FEEDBACK' => 'feedback'
]
],
'feedback' => [
'parent' => '<root>',
'children' => [
'VERSION' => 'ver',
'REPORT_METADATA' => 'rmd',
'POLICY_PUBLISHED' => 'p_p',
'RECORD' => 'rec'
]
],
'ver' => [ 'parent' => 'feedback', 'header' => true, 'default' => null ],
'rmd' => [
'parent' => 'feedback',
'children' => [
'ORG_NAME' => 'org',
'EMAIL' => 'email',
'EXTRA_CONTACT_INFO' => 'extra_contact_info',
'REPORT_ID' => 'external_id',
'DATE_RANGE' => 'd_range',
'ERROR' => 'error_string'
]
],
'p_p' => [
'parent' => 'feedback',
'children' => [
'DOMAIN' => 'domain',
'ADKIM' => 'policy_adkim',
'ASPF' => 'policy_aspf',
'P' => 'policy_p',
'SP' => 'policy_sp',
'NP' => 'policy_np',
'PCT' => 'policy_pct',
'FO' => 'policy_fo'
]
],
'rec' => [
'parent' => 'feedback',
'children' => [
'ROW' => 'row',
'IDENTIFIERS' => 'ident',
'AUTH_RESULTS' => 'au_res'
]
],
'org' => [ 'parent' => 'rmd', 'header' => true ],
'email' => [ 'parent' => 'rmd', 'header' => true, 'default' => null ],
'extra_contact_info' => [ 'parent' => 'rmd', 'header' => true, 'default' => null ],
'external_id' => [ 'parent' => 'rmd', 'header' => true ],
'd_range' => [
'parent' => 'rmd',
'children' => [
'BEGIN' => 'begin_time',
'END' => 'end_time'
]
],
'error_string' => [ 'parent' => 'rmd', 'header' => true, 'default' => null ],
'begin_time' => [ 'parent' => 'd_range', 'header' => true ],
'end_time' => [ 'parent' => 'd_range', 'header' => true ],
'domain' => [ 'parent' => 'p_p', 'header' => true ],
'policy_adkim' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_aspf' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_p' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_sp' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_np' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_pct' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'policy_fo' => [ 'parent' => 'p_p', 'header' => true, 'default' => null ],
'row' => [
'parent' => 'rec',
'children' => [
'SOURCE_IP' => 'ip',
'COUNT' => 'rcount',
'POLICY_EVALUATED' => 'p_e'
]
],
'ident' => [
'parent' => 'rec',
'children' => [
'ENVELOPE_TO' => 'envelope_to',
'ENVELOPE_FROM' => 'envelope_from',
'HEADER_FROM' => 'header_from'
]
],
'au_res' => [
'parent' => 'rec',
'children' => [
'DKIM' => 'dkim_auth',
'SPF' => 'spf_auth'
]
],
'ip' => [ 'parent' => 'row' ],
'rcount' => [ 'parent' => 'row' ],
'p_e' => [
'parent' => 'row',
'children' => [
'DISPOSITION' => 'disposition',
'DKIM' => 'dkim_align',
'SPF' => 'spf_align',
'REASON' => 'reason'
]
],
'disposition' => [ 'parent' => 'p_e' ],
'dkim_align' => [ 'parent' => 'p_e' ],
'spf_align' => [ 'parent' => 'p_e' ],
'reason' => [
'parent' => 'p_e',
'default' => null,
'children' => [
'TYPE' => 'reason_type',
'COMMENT' => 'reason_comment'
]
],
'envelope_to' => [ 'parent' => 'ident', 'default' => null ],
'envelope_from' => [ 'parent' => 'ident', 'default' => null ],
'header_from' => [ 'parent' => 'ident', 'default' => null ],
'dkim_auth' => [
'parent' => 'au_res',
'default' => null,
'children' => [
'DOMAIN' => 'dkim_domain',
'SELECTOR' => 'dkim_selector',
'RESULT' => 'dkim_result',
'HUMAN_RESULT' => 'dkim_human_result'
]
],
'spf_auth' => [
'parent' => 'au_res',
'default' => null,
'children' => [
'DOMAIN' => 'spf_domain',
'SCOPE' => 'spf_scope',
'RESULT' => 'spf_result'
]
],
'reason_type' => [ 'parent' => 'reason' ],
'reason_comment' => [ 'parent' => 'reason' ],
'dkim_domain' => [ 'parent' => 'dkim_auth' ],
'dkim_selector' => [ 'parent' => 'dkim_auth' ],
'dkim_result' => [ 'parent' => 'dkim_auth' ],
'dkim_human_result' => [ 'parent' => 'dkim_auth' ],
'spf_domain' => [ 'parent' => 'spf_auth' ],
'spf_scope' => [ 'parent' => 'spf_auth' ],
'spf_result' => [ 'parent' => 'spf_auth' ]
];
}

View File

@ -0,0 +1,242 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class ReportFetcher
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Report;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Report\Report;
use Liuch\DmarcSrg\Sources\Source;
use Liuch\DmarcSrg\ReportLog\ReportLogItem;
use Liuch\DmarcSrg\Exception\RuntimeException;
/**
* This class is designed to fetch report files from report sources and store them to the database.
*/
class ReportFetcher
{
private $source = null;
/**
* It's the constructor of the class.
*
* @param Source $sou Source for fetching report files.
*
* @return void
*/
public function __construct($sou)
{
$this->source = $sou;
}
/**
* Retrieves report files from the source and stores them in the database
* taking into account the limits from the configuration file.
*
* @return array Array of results.
*/
public function fetch(): array
{
try {
$this->source->rewind();
} catch (RuntimeException $e) {
return [[ 'source_error' => $e->getMessage() ]];
}
$core = Core::instance();
$limit = 0;
$stype = $this->source->type();
switch ($stype) {
case Source::SOURCE_MAILBOX:
$s_act = $core->config('fetcher/mailboxes/when_done', '');
$f_act = $core->config('fetcher/mailboxes/when_failed', '');
$limit = $core->config('fetcher/mailboxes/messages_maximum', 0);
break;
case Source::SOURCE_DIRECTORY:
$s_act = $core->config('fetcher/directories/when_done', '');
$f_act = $core->config('fetcher/directories/when_failed', '');
$limit = $core->config('fetcher/directories/files_maximum', 0);
break;
}
$limit = intval($limit);
if ($stype === Source::SOURCE_MAILBOX || $stype === Source::SOURCE_DIRECTORY) {
$this->source->setParams([
'when_done' => $s_act,
'when_failed' => $f_act
]);
}
$results = [];
while ($this->source->valid()) {
$result = null;
$fname = null;
$report = null;
$success = false;
$err_msg = null;
// Extracting and saving reports
try {
$rfile = $this->source->current();
$fname = $rfile->filename();
$report = Report::fromXmlFile($rfile->datastream());
$result = $report->save($fname);
$success = true;
} catch (RuntimeException $e) {
$err_msg = $e->getMessage();
$result = ErrorHandler::exceptionResult($e);
}
unset($rfile);
// Post processing
try {
if ($success) {
$this->source->accepted();
} else {
$this->source->rejected();
}
} catch (RuntimeException $e) {
$err_msg = $e->getMessage();
$result['post_processing_message'] = $err_msg;
}
// Adding a record to the log.
if (!$err_msg) {
$log = ReportLogItem::success($stype, $report, $fname, null)->save();
} else {
$log = ReportLogItem::failed($stype, $report, $fname, $err_msg)->save();
if ($this->source->type() === Source::SOURCE_MAILBOX) {
$msg = $this->source->mailMessage();
$ov = $msg->overview();
if ($ov) {
if (property_exists($ov, 'from')) {
$result['emailed_from'] = $ov->from;
}
if (property_exists($ov, 'date')) {
$result['emailed_date'] = $ov->date;
}
}
}
if ($report) {
$rd = $report->get();
if (isset($rd['external_id'])) {
$result['report_id'] = $rd['external_id'];
}
}
}
unset($report);
// Adding result to the results array.
$results[] = $result;
// Checking the fetcher limits
if ($limit > 0) {
if (--$limit === 0) {
break;
}
}
$this->source->next();
}
return $results;
}
/**
* Generates the final result based on the results of loading individual report files.
*
* @param array $results Array with results of loading report files.
*
* @return array Array of the final result to be sent to the client.
*/
public static function makeSummaryResult(array $results): array
{
$reps = [];
$others = [];
$r_count = 0;
$loaded = 0;
foreach ($results as &$r) {
if (isset($r['source_error'])) {
$others[] = $r['source_error'];
} else {
$reps[] = $r;
++$r_count;
if (!isset($r['error_code']) || $r['error_code'] === 0) {
++$loaded;
}
if (isset($r['post_processing_message'])) {
$others[] = $r['post_processing_message'];
}
}
}
unset($r);
$result = null;
$o_count = count($others);
if ($r_count + $o_count === 1) {
if ($r_count === 1) {
$result = $reps[0];
} else {
$result = [
'error_code' => -1,
'message' => $others[0]
];
}
} else {
$err_code = null;
$message = null;
if ($loaded === $r_count) {
$err_code = 0;
if ($r_count > 0) {
$message = strval($r_count) . ' report files have been loaded successfully';
} elseif ($o_count === 0) {
$message = 'There are no report files to load';
} else {
$err_code = -1;
}
} else {
$err_code = -1;
if ($loaded > 0) {
$message = "Only {$loaded} of the {$r_count} report files have been loaded";
} else {
$message = "None of the {$r_count} report files has been loaded";
}
}
$result['error_code'] = $err_code;
$result['message'] = $message;
if ($r_count > 0) {
$result['results'] = $reps;
}
if ($o_count > 0) {
$result['other_errors'] = $others;
}
}
return $result;
}
}

View File

@ -0,0 +1,212 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains ReportList class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Report;
use Liuch\DmarcSrg\Core;
/**
* It's the main class for working with the incoming reports, such as:
* - getting a list of reports
* - deleting several reports at once
* - getting the number of reports stored in the database
*/
class ReportList
{
public const ORDER_NONE = 0;
public const ORDER_BEGIN_TIME = 1;
public const ORDER_ASCENT = 2;
public const ORDER_DESCENT = 3;
private $db = null;
private $limit = 0;
private $filter = [];
private $order = null;
/**
* The constructor
*
* @param DatabaseController $db The database controller
*/
public function __construct($db = null)
{
$this->db = $db ?? Core::instance()->database();
}
/**
* Returns a list of reports with specified parameters from position $pos
*
* This method returns a list of reports that depends on the filter and order.
* The filter, order, and limit for the list can be set using the setFilter, setOrder and setMaxCount methods.
*
* @param int $pos The starting position from which the list will be returned
*
* @return array An array with keys `reports` and `more`.
* `reports` is an array of incoming reports which contains maximum 25 records by default.
* Another value of the number of records can be specified by calling
* the method setMaxCount.
* `more` is true if there are more records in the database, false otherwise.
*/
public function getList(int $pos): array
{
$order = [
'field' => 'begin_time',
'direction' => ($this->order ?? self::ORDER_DESCENT) === self::ORDER_ASCENT ? 'ascent' : 'descent'
];
$max_rec = $this->limit > 0 ? $this->limit : 25;
$limit = [
'offset' => $pos,
'count' => $max_rec + 1
];
$list = $this->db->getMapper('report')->list($this->filter, $order, $limit);
if (count($list) > $max_rec) {
$more = true;
unset($list[$max_rec]);
} else {
$more = false;
}
return [
'reports' => $list,
'more' => $more
];
}
/**
* Sets the sort order for the list and for deleting several reports at once
*
* @param int $field The field to sort by. Currently only ORDER_BEGIN_TIME is available.
* @param int $direction The sorting direction. ORDER_ASCENT or ORDER_DESCENT must be used here.
*
* @return void
*/
public function setOrder(int $field, int $direction): void
{
$this->order = null;
if ($field > self::ORDER_NONE && $field < self::ORDER_ASCENT) {
if ($direction !== self::ORDER_ASCENT) {
$direction = self::ORDER_DESCENT;
}
$this->order = [
'field' => $field,
'direction' => $direction
];
}
}
/**
* Sets maximum numbers of records in the list and for deleting reports
*
* @param int $num Maximum number of records in the list
*
* @return void
*/
public function setMaxCount(int $num): void
{
if ($num > 0) {
$this->limit = $num;
} else {
$this->limit = 0;
}
}
/**
* Sets filter values for the list and for deleting reports
*
* @param array $filter Key-value array:
* 'before_time' => DateTime, timestamp
* 'dkim' => string, 'fail' or 'pass'
* 'domain' => string or instance of Domain class
* 'month' => string, yyyy-mm format
* 'organization' => string
* 'spf' => string, 'fail' or 'pass'
* 'status' => string, 'read' or 'unread'
* Note! 'dkim' and 'spf' do not affect the delete and count methods
*
* @return void
*/
public function setFilter(array $filter): void
{
$this->filter = $filter;
}
/**
* Returns the number of reports in the database
*
* It returns the number of reports in the database.
* The limit and some filter items (`dkim`, `spf`) do not affect this.
*
* @return int The number of reports in the database
*/
public function count(): int
{
$limit = [ 'offset' => 0, 'count' => $this->limit ];
return $this->db->getMapper('report')->count($this->filter, $limit);
}
/**
* Deletes reports from the database
*
* It deletes repors form the database. The filter items `dkim` and `spf` do not affect this.
*
* @return void
*/
public function delete(): void
{
$order = [
'field' => 'begin_time',
'direction' => ($this->order ?? self::ORDER_DESCENT) === self::ORDER_ASCENT ? 'ascent' : 'descent'
];
$limit = [ 'offset' => 0, 'count' => $this->limit ];
$this->db->getMapper('report')->delete($this->filter, $order, $limit);
}
/**
* Returns a list of values for each filter item except for `before_time`
*
* @return array An key-value array, where the key is the filter item name
* and the value is an array of possible values for the item
*/
public function getFilterList(): array
{
$domainMapper = $this->db->getMapper('domain');
$reportMapper = $this->db->getMapper('report');
return [
'domain' => $domainMapper->names(),
'month' => $reportMapper->months(),
'organization' => $reportMapper->organizations(),
'dkim' => [ 'pass', 'fail' ],
'spf' => [ 'pass', 'fail' ],
'status' => [ 'read', 'unread' ]
];
}
}

View File

@ -0,0 +1,400 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains SummaryReport class
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Report;
use Liuch\DmarcSrg\Statistics;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* This class is for generating summary data for the specified period and domain
*/
class SummaryReport
{
private const LAST_WEEK = -1;
private const LAST_MONTH = -2;
private $period = 0;
private $domain = null;
private $stat = null;
private $subject = '';
/**
* Constructor
*
* @param string $period The period for which the report is created
* Must me one of the following values: `lastweek`, `lastmonth`, and `lastndays:N`
* where N is the number of days the report is created for
*/
public function __construct(string $period)
{
switch ($period) {
case 'lastweek':
$period = self::LAST_WEEK;
$subject = ' weekly';
break;
case 'lastmonth':
$period = self::LAST_MONTH;
$subject = ' monthly';
break;
default:
$ndays = 0;
$av = explode(':', $period);
if (count($av) === 2 && $av[0] === 'lastndays') {
$ndays = intval($av[1]);
if ($ndays <= 0) {
throw new SoftException('The parameter "days" has an incorrect value');
}
$subject = sprintf(' %d day%s', $ndays, ($ndays > 1 ? 's' : ''));
}
$period = $ndays;
break;
}
if (empty($subject)) {
throw new SoftException('The parameter "period" has an incorrect value');
}
$this->period = $period;
$this->subject = "DMARC{$subject} digest";
}
/**
* Binds a domain to the report
*
* @param Domain $domain The domain for which the report is created
*
* @return self
*/
public function setDomain($domain)
{
$this->domain = $domain;
$this->stat = null;
return $this;
}
/**
* Returns the report data as an array
*
* @return array
*/
public function toArray(): array
{
$this->ensureData();
$res = [];
$stat = $this->stat;
$range = $stat->range();
$res['date_range'] = [ 'begin' => $range[0], 'end' => $range[1] ];
$res['summary'] = $stat->summary();
$res['sources'] = $stat->ips();
$res['organizations'] = $stat->organizations();
return $res;
}
/**
* Returns the subject string. It is used in email messages.
*
* @return string
*/
public function subject(): string
{
return $this->subject;
}
/**
* Returns the report as an array of text strings
*
* @return array
*/
public function text(): array
{
$rdata = $this->reportData();
$res = [];
$res[] = '# Domain: ' . $this->domain->fqdn();
$res[] = ' Range: ' . $rdata['range'];
$res[] = '';
$res[] = '## Summary';
$total = $rdata['summary']['total'];
$res[] = sprintf(' Total: %d', $total);
$res[] = sprintf(' DKIM or SPF aligned: %s', self::num2percent($rdata['summary']['aligned'], $total));
$res[] = sprintf(' Not aligned: %s', self::num2percent($rdata['summary']['n_aligned'], $total));
$res[] = sprintf(' Organizations: %d', $rdata['summary']['organizations']);
$res[] = '';
if (count($rdata['sources']) > 0) {
$res[] = '## Sources';
$res[] = sprintf(
' %-25s %13s %13s %13s',
'',
'Total',
'SPF aligned',
'DKIM aligned'
);
foreach ($rdata['sources'] as &$it) {
$total = $it['emails'];
$spf_a = $it['spf_aligned'];
$dkim_a = $it['dkim_aligned'];
$spf_str = self::num2percent($spf_a, $total);
$dkim_str = self::num2percent($dkim_a, $total);
$res[] = sprintf(
' %-25s %13d %13s %13s',
$it['ip'],
$total,
$spf_str,
$dkim_str
);
}
unset($it);
$res[] = '';
}
if (count($rdata['organizations']) > 0) {
$res[] = '## Organizations';
$org_len = 15;
foreach ($rdata['organizations'] as &$org) {
$org_len = max($org_len, mb_strlen($org['name']));
}
unset($org);
$org_len = min($org_len, 55);
$res[] = sprintf(" %-{$org_len}s %8s %8s", '', 'emails', 'reports');
$frm_str = " %-{$org_len}s %8d %8d";
foreach ($rdata['organizations'] as &$org) {
$res[] = sprintf(
$frm_str,
trim($org['name']),
$org['emails'],
$org['reports']
);
}
unset($org);
$res[] = '';
}
return $res;
}
/**
* Returns the report as an array of html strings
*
* @return array
*/
public function html(): array
{
$h2a = 'style="margin:15px 0 5px;"';
$t2a = 'style="border-collapse:collapse;border-spacing:0;"';
$c1a = 'style="font-style:italic;"';
$d1s = 'padding-left:1em;';
$d2s = 'min-width:4em;';
$d3s = 'border:1px solid #888;';
$d4s = 'text-align:right;';
$d5s = 'padding:.3em;';
$add_red = function (int $num) {
return $num > 0 ? 'color:#f00;' : '';
};
$add_green = function (int $num) {
return $num > 0 ? 'color:#080;' : '';
};
$rdata = $this->reportData();
$res = [];
$res[] = "<h2 {$h2a}>Domain: " . htmlspecialchars($this->domain->fqdn()) . '</h2>';
$res[] = '<p style="margin:0;">Range: ' . htmlspecialchars($rdata['range']) . '</p>';
$res[] = "<h3 {$h2a}>Summary</h3>";
$res[] = '<table>';
$total = $rdata['summary']['total'];
$a_cnt = $rdata['summary']['aligned'];
$n_cnt = $rdata['summary']['n_aligned'];
$res[] = " <tr><td>Total: </td><td style=\"{$d1s}\">" . $total . '</td></tr>';
$color = $add_green($a_cnt);
$res[] = " <tr><td>DKIM or SPF aligned: </td><td style=\"{$d1s}{$color}\">{$a_cnt}</td></tr>";
$color = $add_red($n_cnt);
$res[] = " <tr><td>Not aligned: </td><td style=\"{$d1s}{$color}\">{$n_cnt}</td></tr>";
$res[] = " <tr><td>Organizations: </td><td style=\"{$d1s}\">" .
$rdata['summary']['organizations'] .
'</td></tr>';
$res[] = '</table>';
$rs2 = 'rowspan="2"';
$cs3 = 'colspan="3"';
$s_cnt = count($rdata['sources']);
if ($s_cnt > 0) {
$res[] = "<h3 {$h2a}>Sources</h3>";
$res[] = "<table {$t2a}>";
$res[] = " <caption {$c1a}>Total records: {$s_cnt}</caption>";
$res[] = ' <thead>';
$style = "style=\"{$d3s}{$d5s}\"";
$res[] = " <tr><th {$rs2} {$style}>IP address</th><th {$rs2} {$style}>Email volume</th>" .
"<th {$cs3} {$style}>SPF</th><th {$cs3} {$style}>DKIM</th></tr>";
$style = "style=\"{$d2s}{$d3s}{$d5s}\"";
$res[] = " <tr><th {$style}>pass</th><th {$style}>fail</th><th {$style}>rate</th>" .
"<th {$style}>pass</th><th {$style}>fail</th><th {$style}>rate</th></tr>";
$res[] = ' </thead>';
$res[] = ' <tbody>';
foreach ($rdata['sources'] as &$row) {
$ip = htmlspecialchars($row['ip']);
$total = $row['emails'];
$spf_a = $row['spf_aligned'];
$spf_n = $total - $spf_a;
$spf_p = sprintf('%.0f%%', $spf_a / $total * 100);
$dkim_a = $row['dkim_aligned'];
$dkim_n = $total - $dkim_a;
$dkim_p = sprintf('%.0f%%', $dkim_a / $total * 100);
$style = "style=\"{$d3s}{$d5s}";
$row_str = " <tr><td {$style}\">{$ip}</td><td {$style}{$d4s}\">{$total}</td>";
$row_str .= "<td {$style}{$d4s}{$add_green($spf_a)}\">{$spf_a}</td>";
$row_str .= "<td {$style}{$d4s}{$add_red($spf_n)}\">{$spf_n}</td>";
$row_str .= "<td {$style}{$d4s}\">{$spf_p}</td>";
$row_str .= "<td {$style}{$d4s}{$add_green($dkim_a)}\">{$dkim_a}</td>";
$row_str .= "<td {$style}{$d4s}{$add_red($dkim_n)}\">{$dkim_n}</td>";
$row_str .= "<td {$style}{$d4s}\">{$dkim_p}</td>";
$res[] = $row_str . '</tr>';
}
unset($row);
$res[] = ' </tbody>';
$res[] = '</table>';
}
$o_cnt = count($rdata['organizations']);
if ($o_cnt) {
$res[] = "<h3 {$h2a}>Organizations</h3>";
$res[] = "<table {$t2a}>";
$res[] = " <caption {$c1a}>Total records: {$o_cnt}</caption>";
$res[] = ' <thead>';
$style = "style=\"{$d3s}{$d5s}\"";
$res[] = " <tr><th {$style}>Name</th><th {$style}>Emails</th><th {$style}>Reports</th></tr>";
$res[] = ' </thead>';
$res[] = ' <tbody>';
foreach ($rdata['organizations'] as &$row) {
$name = htmlspecialchars($row['name']);
$style2 = "style=\"{$d3s}{$d4s}{$d5s}\"";
$res[] = " <tr><td {$style}>{$name}</td>" .
"<td {$style2}>{$row['emails']}</td>" .
"<td {$style2}>{$row['reports']}</td></tr>";
}
unset($row);
$res[] = ' </tbody>';
$res[] = '</table>';
}
return $res;
}
/**
* Returns the percentage with the original number. If $per is 0 then '0' is returned.
*
* @param int $per Value
* @param int $cent Divisor for percentage calculation
*
* @return string
*/
private static function num2percent(int $per, int $cent): string
{
if (!$per) {
return '0';
}
return sprintf('%.0f%%(%d)', $per / $cent * 100, $per);
}
/**
* Generates the report if it has not already been done
*
* @return void
*/
private function ensureData(): void
{
if (!$this->domain) {
throw new LogicException('No one domain was specified');
}
if (!$this->stat) {
switch ($this->period) {
case self::LAST_WEEK:
$this->stat = Statistics::lastWeek($this->domain);
break;
case self::LAST_MONTH:
$this->stat = Statistics::lastMonth($this->domain);
break;
default:
$this->stat = Statistics::lastNDays($this->domain, $this->period);
break;
}
}
}
/**
* Returns prepared data for the report
*
* @return array
*/
private function reportData(): array
{
$this->ensureData();
$stat = $this->stat;
$rdata = [];
$range = $stat->range();
$cyear = (new \Datetime())->format('Y');
$dform = ($range[0]->format('Y') !== $cyear || $range[1]->format('Y') !== $cyear) ? 'M d Y' : 'M d';
$rdata['range'] = $range[0]->format($dform) . ' - ' . $range[1]->format($dform);
$summ = $stat->summary();
$total = $summ['emails']['total'];
$aligned = $summ['emails']['dkim_spf_aligned'] +
$summ['emails']['dkim_aligned'] +
$summ['emails']['spf_aligned'];
$n_aligned = $total - $aligned;
$rdata['summary'] = [
'total' => $total,
'organizations' => $summ['organizations']
];
if ($total > 0) {
$rdata['summary']['aligned'] = $aligned;
$rdata['summary']['n_aligned'] = $n_aligned;
} else {
$rdata['summary']['aligned'] = $aligned;
$rdata['summary']['n_aligned'] = $aligned;
}
$rdata['sources'] = $stat->ips();
$rdata['organizations'] = $stat->organizations();
return $rdata;
}
}

View File

@ -0,0 +1,194 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\ReportFile;
use Liuch\DmarcSrg\Exception\SoftException;
class ReportFile
{
private $fd = null;
private $zip = null;
private $type = null;
private $remove = false;
private $filename = null;
private $filepath = null;
private $gzcutfilter = null;
private $gzinflatefilter = null;
private static $filters = [];
private static $ext_mime_map = [
'xml' => 'text/xml',
'gz' => 'application/gzip',
'zip' => 'application/zip'
];
private function __construct($filename, $type = null, $fd = null, $remove = false, $filepath = null)
{
$this->filename = $filename;
$this->type = $type ?? self::getMimeType($filename, $fd, $filepath);
$this->remove = $remove;
$this->filepath = $filepath;
switch ($this->type) {
case 'application/gzip':
case 'application/x-gzip':
$this->fd = $fd;
break;
case 'application/zip':
if ($fd) {
$tmpfname = tempnam(sys_get_temp_dir(), 'dmarc_');
if ($tmpfname === false) {
throw new SoftException('Failed to create a temporary file');
}
rewind($fd);
if (file_put_contents($tmpfname, $fd) === false) {
throw new SoftException('Failed to copy data to a temporary file');
}
$this->filepath = $tmpfname;
$this->remove = true;
}
break;
}
}
public function __destruct()
{
if ($this->fd) {
if ($this->isGzipStream()) {
$this->enableGzFilter(false);
}
gzclose($this->fd);
}
if ($this->zip) {
$this->zip->close();
}
if ($this->remove && $this->filepath) {
unlink($this->filepath);
}
}
public static function getMimeType($filename, $fd = null, $filepath = null)
{
if (function_exists('mime_content_type')) {
if ($fd && ($res = mime_content_type($fd))) {
return $res;
}
if ($filepath && ($res = mime_content_type($filepath))) {
return $res;
}
}
$ext = pathinfo(basename($filename), PATHINFO_EXTENSION);
return self::$ext_mime_map[$ext] ?? 'application/octet-stream';
}
public static function fromFile($filepath, $filename = null, $remove = false)
{
if (!is_file($filepath)) {
throw new SoftException('ReportFile: it is not a file');
}
return new ReportFile(
$filename ? basename($filename) : basename($filepath),
null,
null,
$remove,
$filepath
);
}
public static function fromStream($fd, $filename, $type)
{
return new ReportFile($filename, $type, $fd);
}
public function filename()
{
return $this->filename;
}
public function datastream()
{
if (!$this->fd) {
$fd = null;
switch ($this->type) {
case 'application/zip':
$this->zip = new \ZipArchive();
$this->zip->open($this->filepath);
if ($this->zip->count() !== 1) {
throw new SoftException('The archive must have only one file in it');
}
$zfn = $this->zip->getNameIndex(0);
if ($zfn !== pathinfo($zfn, PATHINFO_BASENAME)) {
throw new SoftException('There must not be any directories in the archive');
}
$fd = $this->zip->getStream($zfn);
break;
default:
// gzopen() can be used to read a file which is not in gzip format;
// in this case gzread() will directly read from the file without decompression.
$fd = gzopen($this->filepath, 'r');
break;
}
if (!$fd) {
throw new SoftException('Failed to open a report file');
}
$this->fd = $fd;
}
if ($this->isGzipStream()) {
ReportFile::ensureRegisterFilter(
'report_gzfile_cut_filter',
'Liuch\DmarcSrg\ReportFile\ReportGZFileCutFilter'
);
$this->enableGzFilter(true);
}
return $this->fd;
}
private static function ensureRegisterFilter($filtername, $classname)
{
if (!isset(ReportFile::$filters[$filtername])) {
stream_filter_register($filtername, $classname);
ReportFile::$filters[$filtername] = true;
}
}
private function enableGzFilter($enable)
{
if ($enable) {
if (!$this->gzcutfilter) {
$this->gzcutfilter = stream_filter_append($this->fd, 'report_gzfile_cut_filter', STREAM_FILTER_READ);
$this->gzinflatefilter = stream_filter_append($this->fd, 'zlib.inflate', STREAM_FILTER_READ);
}
} else {
if ($this->gzcutfilter) {
stream_filter_remove($this->gzinflatefilter);
stream_filter_remove($this->gzcutfilter);
}
}
}
private function isGzipStream(): bool
{
return (in_array($this->type, [ 'application/gzip', 'application/x-gzip' ]) && !$this->filepath);
}
}

View File

@ -0,0 +1,114 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\ReportFile;
use php_user_filter;
class ReportGZFileCutFilter extends php_user_filter
{
private $head = true;
private $header_data = '';
private $tail_data = '';
public function filter($in, $out, &$consumed, $closing): int
{
$b_cnt = 0;
while ($bucket = stream_bucket_make_writeable($in)) {
$consumed += $bucket->datalen;
$data = null;
if ($this->head) {
$data = $this->skipGzHeader($bucket->data);
} else {
$data = $bucket->data;
}
$data = $this->cutGzTail($data);
if (strlen($data) > 0) {
$bucket->data = $data;
stream_bucket_append($out, $bucket);
$b_cnt += 1;
}
}
return ($b_cnt > 0) ? PSFS_PASS_ON : PSFS_FEED_ME;
}
private function skipGzHeader($data)
{
// https://tools.ietf.org/html/rfc1952
$this->header_data .= $data;
$len = strlen($this->header_data);
if ($len < 10) { // minimal gz header
return '';
}
$pos = 10;
$flags = ord($this->header_data[3]);
if ($flags & 4) { // FLG.FEXTRA
$pos += (ord($this->header_data[$pos + 1]) | (ord($this->header_data[$pos + 2]) << 8)) + 2;
if ($pos > $len) {
return '';
}
}
if ($flags & 8) { // FLG.FNAME
$pos = $this->skipZeroTerminatedString($this->header_data, $len, $pos);
if ($pos > $len) {
return '';
}
}
if ($flags & 16) { // FLG.FCOMMENT
$pos = $this->skipZeroTerminatedString($this->header_data, $len, $pos);
if ($pos > $len) {
return '';
}
}
if ($flags & 2) { // FLG.FHCRC
$pos += 2;
if ($pos > $len) {
return '';
}
}
$res = substr($this->header_data, $pos);
$this->head = false;
$this->header_data = '';
return $res;
}
private function cutGzTail($data)
{
$res = $this->tail_data . $data;
$this->tail_data = substr($res, -8);
if (strlen($res) <= 8) {
return '';
}
return substr($res, 0, -8);
}
private function skipZeroTerminatedString($str, $len, $pos)
{
for ($i = $pos; $i < $len; ++$i) {
if ($str[$i] === "\0") {
return $i + 1;
}
}
return $len + 1;
}
}

View File

@ -0,0 +1,96 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\ReportLog;
use Liuch\DmarcSrg\Core;
class ReportLog
{
public const ORDER_ASCENT = 1;
public const ORDER_DESCENT = 2;
private $db = null;
private $filter = [
'from_time' => null,
'till_time' => null
];
private $order = [
'direction' => 'ascent'
];
private $rec_limit = 0;
private $position = 0;
public function __construct($from_time, $till_time, $db = null)
{
$this->filter['from_time'] = $from_time;
$this->filter['till_time'] = $till_time;
$this->db = $db ?? Core::instance()->database();
}
public function setOrder(int $dir)
{
$this->order['direction'] = ($dir === self::ORDER_DESCENT ? 'descent' : 'ascent');
}
public function setMaxCount(int $n)
{
$this->rec_limit = $n;
}
public function count()
{
$limit = [ 'offset' => 0, 'count' => $this->rec_limit ];
return $this->db->getMapper('report-log')->count($this->filter, $limit);
}
public function getList(int $pos)
{
$this->position = $pos;
$max_rec = $this->rec_limit > 0 ? $this->rec_limit : 25;
$limit = [ 'offset' => $pos, 'count' => $max_rec + 1 ];
$list = $this->db->getMapper('report-log')->list($this->filter, $this->order, $limit);
if (count($list) > $max_rec) {
$more = true;
unset($list[$max_rec]);
} else {
$more = false;
}
foreach ($list as &$it) {
$it['source'] = ReportLogItem::sourceToString($it['source']);
}
unset($it);
return [
'items' => $list,
'more' => $more
];
}
public function delete()
{
$limit = [ 'offset' => 0, 'count' => $this->rec_limit ];
$this->db->getMapper('report-log')->delete($this->filter, $this->order, $limit);
}
}

View File

@ -0,0 +1,147 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg\ReportLog;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Sources\Source;
use Liuch\DmarcSrg\Exception\LogicException;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
class ReportLogItem
{
private $db = null;
private $data = [
'id' => null,
'domain' => null,
'external_id' => null,
'event_time' => null,
'filename' => null,
'source' => 0,
'success' => false,
'message' => null
];
private function __construct($source, $filename, $db)
{
if (!is_null($source)) {
if (gettype($source) !== 'integer' || $source <= 0) {
throw new LogicException('Invalid parameter passed');
}
}
$this->data['source'] = $source;
$this->data['filename'] = gettype($filename) == 'string' ? $filename : null;
$this->db = $db ?? Core::instance()->database();
}
public static function success(int $source, $report, $filename, $message, $db = null)
{
$li = new ReportLogItem($source, $filename, $db);
$li->data['success'] = true;
$rdata = $report->get();
$li->data['domain'] = $rdata['domain'];
$li->data['external_id'] = $rdata['external_id'];
$li->data['message'] = $message;
return $li;
}
public static function failed(int $source, $report, $filename, $message, $db = null)
{
$li = new ReportLogItem($source, $filename, $db);
$li->data['success'] = false;
if (!is_null($report)) {
$rdata = $report->get();
$li->data['domain'] = $rdata['domain'];
$li->data['external_id'] = $rdata['external_id'];
} else {
$li->data['domain'] = null;
$li->data['external_id'] = null;
}
$li->data['message'] = $message;
return $li;
}
/**
* Returns an instance of ReportLogItem with the passed Id
*
* @param int $id Item Id to return
* @param DatabaseController $db The database controller
*
* @return ReportLogItem an instance of ReportLogItem with the specified Id.
*/
public static function byId(int $id, $db = null)
{
$li = new ReportLogItem(null, null, $db);
$li->data['id'] = $id;
try {
$li->db->getMapper('report-log')->fetch($li->data);
} catch (DatabaseNotFoundException $e) {
throw new SoftException('The log item is not found');
}
return $li;
}
/**
* Converts an integer source value to a string representation
*
* Returns a string with the source name or an empty string if the integer value is incorrect.
*
* @param int $source - an integer value to convert
*
* @return string A string value of the passed source
*/
public static function sourceToString(int $source): string
{
switch ($source) {
case Source::SOURCE_UPLOADED_FILE:
return 'uploaded_file';
case Source::SOURCE_MAILBOX:
return 'email';
case Source::SOURCE_DIRECTORY:
return 'directory';
}
return '';
}
/**
* Returns an array with log item data
*
* @return array Log item data
*/
public function toArray(): array
{
$res = $this->data;
$res['source'] = static::sourceToString($this->data['source']);
return $res;
}
/**
* Saves the report log item to the database
*
* @return void
*/
public function save(): void
{
$this->db->getMapper('report-log')->save($this->data);
}
}

View File

@ -0,0 +1,242 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains implementation of the class Setting
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Settings;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\DatabaseNotFoundException;
/**
* It's a class for accessing to settings item data
*
* This class is designed for storing and manipulating one item of settings data.
* All queries to the datatabase are made in lazy mode.
*/
abstract class Setting
{
public const TYPE_STRING = 1;
public const TYPE_INTEGER = 2;
public const TYPE_STRING_SELECT = 3;
protected $db = null;
protected $name = null;
protected $value = null;
protected $wignore = false;
/**
* Returns the type of the setting
*
* @return int Type of the setting
*/
abstract public function type(): int;
/**
* Checks if the value is correct
*
* @return bool True if the value is correct or false otherwise
*/
abstract protected function checkValue(): bool;
/**
* Converts a string to the value
*
* @param string $s String for conversion
*
* @return void
*/
abstract protected function stringToValue(string $s): void;
/**
* Returns a string representation of the value
*
* @return string The string value
*/
abstract protected function valueToString(): string;
/**
* It's a constructor of the class
*
* Some examples of using:
* (new Setting('some.setting'))->value(); - will return the value of the setting 'some.setting'.
* (new Setting([ 'name' => 'some.setting', 'value' => 'some string value' ])->save(); - will add
* this setting to the database if it does not exist in it or update the value of the setting.
*
* @param string|array $data Some setting data to identify it
* string value is treated as a name
* array has these fields: `name`, `value`
* and usually uses for creating a new setting item.
* @param boolean $wignore If true the wrong value is reset to the default
* or it throws an exception otherwise.
* @param DatabaseController $db The database controller
*
* @return void
*/
public function __construct($data, bool $wignore = false, $db = null)
{
$this->wignore = $wignore;
$this->db = $db ?? Core::instance()->database();
switch (gettype($data)) {
case 'string':
$this->name = $data;
SettingsList::checkName($this->name);
return;
case 'array':
if (!isset($data['name']) || gettype($data['name']) !== 'string') {
break;
}
$this->name = $data['name'];
SettingsList::checkName($this->name);
if (isset($data['value'])) {
$this->value = $data['value'];
if (!$this->checkValue()) {
if (!$wignore) {
break;
}
$this->resetToDefault();
}
}
return;
}
throw new SoftException('Wrong setting data');
}
/**
* Returns the name of the setting
*
* @return string The name of the setting
*/
public function name(): string
{
return $this->name;
}
/**
* Returns the value of the setting
*
* @return mixed The value of the setting
*/
public function value()
{
if (is_null($this->value)) {
$this->fetchData();
}
return $this->value;
}
/**
* Assigns the passed value to the setting
*
* @param mixed Value to assign
*
* @return void
*/
public function setValue($value): void
{
$this->value = $value;
if (!$this->checkValue()) {
if (!$this->wignore) {
throw new SoftException('Wrong setting value');
}
$this->resetToDefault();
}
}
/**
* Returns an array with setting data
*
* @return array Setting data
*/
public function toArray(): array
{
if (is_null($this->value)) {
$this->fetchData();
}
switch ($this->type()) {
case self::TYPE_STRING:
$type = 'string';
break;
case self::TYPE_INTEGER:
$type = 'integer';
break;
case self::TYPE_STRING_SELECT:
$type = 'select';
break;
}
return [
'type' => $type,
'name' => $this->name,
'value' => $this->value,
'default' => SettingsList::$schema[$this->name]['default']
];
}
/**
* Saves the setting to the database
*
* Updates the value of the setting in the database if the setting exists there or insert a new record otherwise.
*
* @return void
*/
public function save(): void
{
$this->db->getMapper('setting')->save($this->name, $this->valueToString());
}
/**
* Fetches the setting data from the database by its name
*
* @return void
*/
private function fetchData(): void
{
try {
$res = $this->db->getMapper('setting')->value($this->name);
} catch (DatabaseNotFoundException $e) {
$this->resetToDefault();
return;
}
$this->stringToValue($res);
if (!$this->checkValue()) {
$this->resetToDefault();
}
}
/**
* Resets the setting value to its default value
*
* @return void
*/
private function resetToDefault(): void
{
$this->value = SettingsList::$schema[$this->name]['default'];
}
}

View File

@ -0,0 +1,109 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains implementation of the class SettingInteger
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Settings;
/**
* It's a class for accessing to settings item data
*
* This class contains the implementation of the setting for integer values.
*/
class SettingInteger extends Setting
{
/**
* Returns the type of the setting
*
* @return int Type of the setting
*/
public function type(): int
{
return Setting::TYPE_INTEGER;
}
/**
* Checks if the value is correct
*
* @return bool True if the value is correct or false otherwise
*/
protected function checkValue(): bool
{
if (gettype($this->value) === 'integer') {
$sch = &SettingsList::$schema[$this->name];
if (!isset($sch['minimum']) || $this->value >= $sch['minimum']) {
if (!isset($sch['maximum']) || $this->value <= $sch['maximum']) {
return true;
}
}
}
return false;
}
/**
* Converts a string to the value
*
* @param string $s String for conversion
*
* @return void
*/
protected function stringToValue(string $s): void
{
$this->value = intval($s);
}
/**
* Returns a string representation of the value
*
* @return string The string value
*/
protected function valueToString(): string
{
return strval($this->value);
}
/**
* Returns an array with setting data
*
* @return array Setting data
*/
public function toArray(): array
{
$res = parent::toArray();
$sch = &SettingsList::$schema[$this->name];
if (isset($sch['minimum'])) {
$res['minimum'] = $sch['minimum'];
}
if (isset($sch['maximum'])) {
$res['maximum'] = $sch['maximum'];
}
return $res;
}
}

View File

@ -0,0 +1,83 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains implementation of the class SettingString
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Settings;
/**
* It's a class for accessing to settings item data
*
* This class contains the implementation of the setting for string values.
*/
class SettingString extends Setting
{
/**
* Returns the type of the setting
*
* @return int Type of the setting
*/
public function type(): int
{
return Setting::TYPE_STRING;
}
/**
* Checks if the value is correct
*
* @return bool True if the value is correct or false otherwise
*/
protected function checkValue(): bool
{
return (gettype($this->value) === 'string');
}
/**
* Converts a string to the value
*
* @param string $s String for conversion
*
* @return void
*/
protected function stringToValue(string $s): void
{
$this->value = $s;
}
/**
* Returns a string representation of the value
*
* @return string The string value
*/
protected function valueToString(): string
{
return $this->value;
}
}

View File

@ -0,0 +1,78 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains implementation of the class SettingStringSelect
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Settings;
/**
* It's a class for accessing to settings item data
*
* This class contains the implementation of the setting for string with a limited set of values.
*/
class SettingStringSelect extends SettingString
{
/**
* Returns the type of the setting
*
* @return int Type of the setting
*/
public function type(): int
{
return Setting::TYPE_STRING_SELECT;
}
/**
* Checks if the value is correct
*
* @return bool True if the value is correct or false otherwise
*/
protected function checkValue(): bool
{
if (parent::checkValue()) {
if (in_array($this->value, SettingsList::$schema[$this->name]['options'])) {
return true;
}
}
return false;
}
/**
* Returns an array with setting data
*
* @return array Setting data
*/
public function toArray(): array
{
$res = parent::toArray();
$res['options'] = SettingsList::$schema[$this->name]['options'];
return $res;
}
}

View File

@ -0,0 +1,207 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class SettingsList
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Settings;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\Exception\SoftException;
/**
* This class is designed to work with the list of the settings
*/
class SettingsList
{
public const ORDER_ASCENT = 0;
public const ORDER_DESCENT = 1;
private $db = null;
private $order = self::ORDER_ASCENT;
/**
* The constructor
*
* @param DatabaseController $db Connector to the current database
*/
public function __construct($db = null)
{
$this->db = $db ?? Core::instance()->database();
}
/**
* Returns a list of the settings
*
* It returns a list of the settings that are marked public.
* The value is taken from the database, if any, or the default.
*
* @return array Array with instances of Setting class
*/
public function getList(): array
{
$db_map = $this->db->getMapper('setting')->list();
foreach (static::$schema as $name => &$sch_data) {
if ($sch_data['public'] ?? false) {
$value = $db_map[$name] ?? $sch_data['default'];
switch ($sch_data['type']) {
case 'select':
$list[] = new SettingStringSelect([
'name' => $name,
'value' => $value
], true, $this->db);
break;
case 'integer':
$list[] = new SettingInteger([
'name' => $name,
'value' => intval($value)
], true, $this->db);
break;
case 'string':
$list[] = new SettingString([
'name' => $name,
'value' => $value
], true, $this->db);
break;
}
}
}
unset($sch_data);
$dir = $this->order == self::ORDER_ASCENT ? 1 : -1;
usort($list, static function ($a, $b) use ($dir) {
return ($a->name() <=> $b->name()) * $dir;
});
return [
'list' => $list,
'more' => false
];
}
/**
* Sets the sorting direction for the list
*
* @param int $direction The sorting direction. ORDER_ASCENT or ORDER_DESCENT must be used here.
*
* @return SettingsList $this
*/
public function setOrder(int $direction)
{
if ($direction !== self::ORDER_DESCENT) {
$direction = self::ORDER_ASCENT;
}
$this->order = $direction;
return $this;
}
/**
* Throws an exception if there is no setting with name $name
*
* @param string $name Setting name to check
*
* @return void
*/
public static function checkName($name): void
{
if (!isset(self::$schema[$name])) {
throw new SoftException('Unknown setting name: ' . $name);
}
}
/**
* Returns an instance of the Setting class by its name
*
* It returns an instance of the Setting class but only if it is marked public.
*
* @param string $name Setting name
*
* @return Setting
*/
public static function getSettingByName(string $name)
{
self::checkName($name);
if (!(self::$schema[$name]['public'] ?? false)) {
throw new SoftException('Attempt to access an internal variable');
}
switch (self::$schema[$name]['type']) {
case 'string':
return new SettingString($name);
case 'select':
return new SettingStringSelect($name);
case 'integer':
return new SettingInteger($name);
}
}
/**
* List of the possible setting items that must be returned in getList method, their types and other data
*/
public static $schema = [
'version' => [
'type' => 'string',
'default' => ''
],
'status.emails-for-last-n-days' => [
'type' => 'integer',
'public' => true,
'minimum' => 1,
'maximum' => 365,
'default' => 30
],
'report-view.sort-records-by' => [
'type' => 'select',
'public' => true,
'options' => [ 'ip,ascent', 'ip,descent', 'message-count,ascent', 'message-count,descent' ],
'default' => 'message-count,descent'
],
'log-view.sort-list-by' => [
'type' => 'select',
'public' => true,
'options' => [ 'event-time,ascent', 'event-time,descent' ],
'default' => 'event-time,ascent'
],
'ui.datetime.offset' => [
'type' => 'select',
'public' => true,
'options' => [ 'auto', 'utc', 'local' ],
'default' => 'auto'
],
'ui.ipv4.url' => [
'type' => 'string',
'public' => true,
'default' => 'https://who.is/whois-ip/ip-address/{$ip}'
],
'ui.ipv6.url' => [
'type' => 'string',
'public' => true,
'default' => 'https://who.is/whois-ip/ip-address/{$ip}'
]
];
}

View File

@ -0,0 +1,255 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class DirectorySource
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Sources;
use Liuch\DmarcSrg\Core;
use Liuch\DmarcSrg\ReportFile\ReportFile;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\RuntimeException;
/**
* This class is designed to process report files from local server directories.
*/
class DirectorySource extends Source
{
private $path = null;
private $list = null;
private $index = 0;
private $params = null;
/**
* Sets parameters that difine the behavior of the source
*
* @param $params Key-value array
* 'when_done' => one or more rules to be executed after successful report processing
* (array|string)
* 'when_failed' => one or more rules to be executed after report processing fails
* (array|string)
*
* @return void
*/
public function setParams(array $params): void
{
$this->params = [];
$this->params['when_done'] = SourceAction::fromSetting(
$params['when_done'] ?? [],
SourceAction::FLAG_BASENAME,
'delete'
);
$this->params['when_failed'] = SourceAction::fromSetting(
$params['when_failed'] ?? [],
SourceAction::FLAG_BASENAME,
'move_to:failed'
);
}
/**
* Returns an instance of the ReportFile class for the current file.
*
* @return ReportFile
*/
public function current(): object
{
return ReportFile::fromFile($this->list[$this->index]);
}
/**
* Returns the index of the currect file.
*
* @return int
*/
public function key(): int
{
return $this->index;
}
/**
* Moves forward to the next file.
*
* @return void
*/
public function next(): void
{
++$this->index;
}
/**
* Rewinds the position to the first file.
*
* @return void
*/
public function rewind(): void
{
if (is_null($this->list)) {
$this->path = $this->data->toArray()['location'];
if (!is_dir($this->path)) {
throw new SoftException("The {$this->path} directory does not exist!");
}
try {
$fs = new \FilesystemIterator($this->path);
} catch (\Exception $e) {
throw new RuntimeException("Error accessing directory {$this->path}", -1, $e);
}
$this->list = [];
foreach ($fs as $entry) {
if ($entry->isFile()) {
$this->list[] = $entry->getPathname();
}
}
}
if (is_null($this->params)) {
$this->setParams([]);
}
$this->index = 0;
}
/**
* Checks if the current postion is valid
*
* @return bool
*/
public function valid(): bool
{
return isset($this->list[$this->index]);
}
/**
* Processes the accepted report file according to the settings
*
* @return void
*/
public function accepted(): void
{
$this->processReportFileActions($this->params['when_done']);
}
/**
* Processes the rejected report file according to the settings
*
* @return void
*/
public function rejected(): void
{
$this->processReportFileActions($this->params['when_failed']);
}
/**
* Returns type of the source.
*
* @return int
*/
public function type(): int
{
return Source::SOURCE_DIRECTORY;
}
/**
* Logs an error message
*
* @param string $message
*/
private function logError(string $message): void
{
Core::instance()->logger()->error($message);
}
/**
* Processes the current report file according to settings
*
* @param array $actions List of actions to apply to the file
*
* @return void
*/
private function processReportFileActions(array &$actions): void
{
foreach ($actions as $sa) {
switch ($sa->type) {
case SourceAction::ACTION_DELETE:
$this->deleteReportFile();
break;
case SourceAction::ACTION_MOVE:
$this->moveReportFile($sa->param);
break;
}
}
}
/**
* Deletes the current report file
*
* @return void
*/
private function deleteReportFile(): void
{
try {
unlink($this->list[$this->index]);
} catch (\ErrorException $e) {
$error_message = "Error deleting file from directory {$this->path}";
$this->logError($error_message);
throw new RuntimeException($error_message, -1, $e);
}
}
/**
* Moves the current report file
*
* @param string $dir_name Directory name where to move the report file to
*
* @return void
*/
private function moveReportFile(string $dir_name): void
{
$fdir = $this->path . $dir_name;
if (!is_dir($fdir)) {
try {
mkdir($fdir);
} catch (\ErrorException $e) {
$e = new RuntimeException("Error creating directory {$fdir}/", -1, $e);
$this->logError(strval($e));
throw $e;
}
try {
chmod($fdir, 0700);
} catch (\ErrorException $e) {
$this->logError(strval($e));
}
}
$file = $this->list[$this->index];
try {
rename($file, $fdir . '/' . basename($file));
} catch (\ErrorException $e) {
$e = new RuntimeException("Error moving file to directory {$fdir}/", -1, $e);
$this->logError(strval($e));
throw $e;
}
}
}

View File

@ -0,0 +1,238 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class MailboxSource
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Sources;
use Liuch\DmarcSrg\ReportFile\ReportFile;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\RuntimeException;
/**
* This class is designed to process report files from an mail box.
*/
class MailboxSource extends Source
{
private $list = null;
private $index = 0;
private $msg = null;
private $params = null;
/**
* Sets parameters that difine the behavior of the source
*
* @param $params Key-value array
* 'when_done' => one or more rules to be executed after successful report processing
* (array|string)
* 'when_failed' => one or more rules to be executed after report processing fails
* (array|string)
*
* @return void
*/
public function setParams(array $params): void
{
$this->params = [];
$this->params['when_done'] = SourceAction::fromSetting(
$params['when_done'] ?? [],
0,
'mark_seen'
);
$this->params['when_failed'] = SourceAction::fromSetting(
$params['when_failed'] ?? [],
0,
'move_to:failed'
);
}
/**
* Returns an instance of the ReportFile class for the current email message.
*
* @return ReportFile
*/
public function current(): object
{
$this->msg = $this->data->message($this->list[$this->index]);
try {
$this->msg->validate();
} catch (SoftException $e) {
throw new SoftException('Incorrect message: ' . $e->getMessage(), $e->getCode());
} catch (RuntimeException $e) {
throw new RuntimeException('Incorrect message', -1, $e);
}
$att = $this->msg->attachment();
return ReportFile::fromStream($att->datastream(), $att->filename(), $att->mimeType());
}
/**
* Returns the index of the currect email message.
*
* @return int
*/
public function key(): int
{
return $this->index;
}
/**
* Moves forward to the next email message
*
* @return void
*/
public function next(): void
{
$this->msg = null;
++$this->index;
}
/**
* Gets a list of unread messages and rewinds the position to the first email message.
*
* @return void
*/
public function rewind(): void
{
$this->msg = null;
$this->list = $this->data->sort(SORTDATE, 'UNSEEN', false);
$this->index = 0;
if (is_null($this->params)) {
$this->setParams([]);
}
}
/**
* Checks if the current postion is valid
*
* @return bool
*/
public function valid(): bool
{
return isset($this->list[$this->index]);
}
/**
* Processes the accepted email messages according to the settings
*
* @return void
*/
public function accepted(): void
{
if ($this->msg) {
$this->processMessageActions($this->params['when_done']);
}
}
/**
* Processes the rejected email messages according to the settings
*
* @return void
*/
public function rejected(): void
{
$this->processMessageActions($this->params['when_failed']);
}
/**
* Returns type of the source.
*
* @return int
*/
public function type(): int
{
return Source::SOURCE_MAILBOX;
}
/**
* Returns the current email message.
*
* @return MailMessage|null
*/
public function mailMessage()
{
return $this->msg;
}
/**
* Processes the current report message according to settings
*
* @param array $actions List of actions to apply to the message
*
* @return void
*/
private function processMessageActions(array &$actions): void
{
foreach ($actions as $sa) {
switch ($sa->type) {
case SourceAction::ACTION_SEEN:
$this->markMessageSeen();
break;
case SourceAction::ACTION_MOVE:
$this->moveMessage($sa->param);
break;
case SourceAction::ACTION_DELETE:
$this->deleteMessage();
break;
}
}
}
/**
* Marks the current report message as seen
*
* @return void
*/
public function markMessageSeen(): void
{
$this->msg->setSeen();
}
/**
* Moves the current report message
*
* @param string $mbox_name Child mailbox name where to move the current message to.
* If the target mailbox does not exists, it will be created.
*
* @return void
*/
private function moveMessage(string $mbox_name): void
{
$this->data->ensureMailbox($mbox_name);
$this->data->moveMessage($this->list[$this->index], $mbox_name);
}
/**
* Deletes the current report message
*
* @return void
*/
private function deleteMessage(): void
{
$this->data->deleteMessage($this->list[$this->index]);
}
}

View File

@ -0,0 +1,115 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Source
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Sources;
/**
* It's an abstract class for easy access to reports of a report source
*/
abstract class Source implements \Iterator
{
public const SOURCE_UPLOADED_FILE = 1;
public const SOURCE_MAILBOX = 2;
public const SOURCE_DIRECTORY = 3;
protected $data = null;
/**
* Constructor
*
* @param mixed Data to reach report files
*
* @return void
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Sets parameters that difine the behavior of the source
*
* @param $params Key-value array
* 'when_done' => one or more rules to be executed after successful report processing
* (array|string)
* 'when_failed' => one or more rules to be executed after report processing fails
* (array|string)
*
* @return void
*/
public function setParams(array $params): void
{
}
/**
* Iterator interface methods
*/
abstract public function current(): object;
abstract public function key(): int;
abstract public function next(): void;
abstract public function rewind(): void;
abstract public function valid(): bool;
/**
* Called when the current report has been successfully processed.
*
* @return void
*/
public function accepted(): void
{
}
/**
* Called when the current report has been rejected.
*
* @return void
*/
public function rejected(): void
{
}
/**
* Returns type of source, i.e. one of Source::SOURCE_* values
*
* @return int
*/
abstract public function type(): int;
/**
* Returns the source itself that was passed to the constructor
*
* @return class
*/
public function container()
{
return $this->data;
}
}

View File

@ -0,0 +1,156 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class SourceAction
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Sources;
use Liuch\DmarcSrg\Exception\LogicException;
/**
* It's a class for describing one action of source
*/
class SourceAction
{
public const ACTION_SEEN = 1;
public const ACTION_MOVE = 2;
public const ACTION_DELETE = 3;
public const FLAG_BASENAME = 1;
private $valid = false;
private $type = 0;
private $param = null;
/**
* The constructor
*
* @param string $action Action name with parameter separated by colon
* Examples: 'move_to:failed', 'delete'
*
* @return void
*/
private function __construct(string $action)
{
if (($delim_offset = mb_strpos($action, ':')) === false) {
$name = $action;
$param = null;
} else {
$name = mb_substr($action, 0, $delim_offset);
$param = mb_substr($action, $delim_offset + 1);
}
switch ($name) {
case 'mark_seen':
$this->type = self::ACTION_SEEN;
if (!empty($param)) {
return;
}
break;
case 'move_to':
$this->type = self::ACTION_MOVE;
if (empty($param)) {
return;
}
break;
case 'delete':
$this->type = self::ACTION_DELETE;
if (!empty($param)) {
return;
}
break;
default:
return;
}
$this->param = $param;
$this->valid = true;
}
/**
* The getter
*
* @param string $name Property name. Must be one of the following: 'type', 'param'
*
* @return mixed
*/
public function __get(string $name)
{
if (in_array($name, [ 'type', 'param' ])) {
return $this->$name;
}
throw new LogicException('Undefined property: ' . $name);
}
/**
* Handles a setting, flags, and returns an array of SourceAction instances
*
* @param string|array $setting Setting from the conf.php
* @param int $flags Flags of extra checking the result
* @param string $default Action to add if the result array is empty
*
* @return array
*/
public static function fromSetting($setting, int $flags, string $default): array
{
if (gettype($setting) !== 'array') {
$setting = [ $setting ];
}
$tmap = [];
$list = [];
foreach ($setting as $it) {
if (gettype($it) === 'string') {
$sa = new self($it);
if ($sa->valid && !isset($tmap[$sa->type])) {
if (($flags & self::FLAG_BASENAME) && !self::checkBasename($sa)) {
continue;
}
$list[] = $sa;
$tmap[$sa->type] = true;
}
}
}
if (count($list) === 0) {
$sa = new self($default);
if ($sa->valid) {
$list[] = $sa;
}
}
return $list;
}
/**
* Checks if the param is just a directory name without a path
*
* @param self $sa
*
* @return bool
*/
private static function checkBasename($sa): bool
{
return ($sa->type !== self::ACTION_MOVE || basename($sa->param) === $sa->param);
}
}

View File

@ -0,0 +1,113 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class UploadedFilesSource
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg\Sources;
use Liuch\DmarcSrg\ReportFile\ReportFile;
use Liuch\DmarcSrg\Exception\SoftException;
/**
* This class is designed to process report files from uploaded files.
*/
class UploadedFilesSource extends Source
{
private $index = 0;
/**
* Returns an instance of the ReportFile class for the current file.
*
* @return ReportFile
*/
public function current(): object
{
if ($this->data['error'][$this->index] !== UPLOAD_ERR_OK) {
throw new SoftException('Failed to upload the report file');
}
$realfname = $this->data['name'][$this->index];
$tempfname = $this->data['tmp_name'][$this->index];
if (!is_uploaded_file($tempfname)) {
throw new SoftException('Possible file upload attack');
}
return ReportFile::fromFile($tempfname, $realfname, false);
}
/**
* Returns the index of the currect file.
*
* @return int
*/
public function key(): int
{
return $this->index;
}
/**
* Moves forward to the next file.
*
* @return void
*/
public function next(): void
{
++$this->index;
}
/**
* Rewinds the position to the first file.
*
* @return void
*/
public function rewind(): void
{
$this->index = 0;
}
/**
* Checks if the current postion is valid
*
* @return bool
*/
public function valid(): bool
{
return isset($this->data['name'][$this->index]);
}
/**
* Returns type of the source.
*
* @return int
*/
public function type(): int
{
return Source::SOURCE_UPLOADED_FILE;
}
}

View File

@ -0,0 +1,169 @@
<?php
/**
* dmarc-srg - a php parser, viewer and summary report generator for incoming dmarc reports.
* copyright (c) 2020 aleksey andreev (liuch)
*
* available at:
* https://github.com/liuch/dmarc-srg
*
* this program is free software: you can redistribute it and/or modify it
* under the terms of the gnu general public license as published by the free
* software foundation, either version 3 of the license.
*
* this program is distributed in the hope that it will be useful, but without
* any warranty; without even the implied warranty of merchantability or
* fitness for a particular purpose. see the gnu general public license for
* more details.
*
* you should have received a copy of the gnu general public license along with
* this program. if not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Statistics
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\DateTime;
/**
* This class is designed to get statistics on DMARC reports of a specified period
*/
class Statistics
{
private $db = null;
private $domain = null;
private $range = [
'date1' => null,
'date2' => null
];
/**
* The constructor of the class, it only uses in static methods of this class
*
* @param Domain|null $domain The domain for which you need to get statistics, null for all the domains.
* @param DatabaseController $db The database controller
*
* @return void
*/
private function __construct($domain, $db)
{
$this->domain = $domain;
$this->db = $db ?? Core::instance()->database();
}
/**
* Returns an instance of the class for the period from $date1 to $date2
*
* @param Domain|null $domain See the constructor for the details
* @param DateTime $date1 The date you need statistics from
* @param DateTime $date2 The date you need statistics to (not included)
* @param DatabaseController $db The database controller
*
* @return Statistics Instance of the class
*/
public static function fromTo($domain, $date1, $date2, $db = null)
{
$r = new Statistics($domain, $db);
$r->range['date1'] = $date1;
$r->range['date2'] = $date2;
return $r;
}
/**
* Returns an instance of the class for the last week
*
* @param Domain|null $domain See the constructor for the details
* @param DatabaseController $db The database controller
*
* @return Statistics Instance of the class
*/
public static function lastWeek($domain, $db = null)
{
$r = new Statistics($domain, $db);
$r->range['date1'] = new DateTime('monday last week');
$r->range['date2'] = (clone $r->range['date1'])->add(new \DateInterval('P7D'));
return $r;
}
/**
* Returns an instance of the class for the last month
*
* @param Domain|null $domain See the construct for the details
* @param DatabaseController $db The database controller
*
* @return Statistics Instance of the class
*/
public static function lastMonth($domain, $db = null)
{
$r = new Statistics($domain, $db);
$r->range['date1'] = new DateTime('midnight first day of last month');
$r->range['date2'] = new DateTime('midnight first day of this month');
return $r;
}
/**
* Returns an instance of the class for the last N days
*
* @param Domain|null $domain See the construct for the details
* @param int $ndays Number of days
* @param DatabaseController $db The database controller
*
* @return Statistics Instance of the class
*/
public static function lastNDays($domain, int $ndays, $db = null)
{
$r = new Statistics($domain, $db);
$r->range['date2'] = new DateTime('midnight');
$r->range['date1'] = (clone $r->range['date2'])->sub(new \DateInterval("P{$ndays}D"));
return $r;
}
/**
* Returns the date from and the date to in an array
*
* @return array - The range of the statistics
*/
public function range(): array
{
return [ (clone $this->range['date1']), (clone $this->range['date2'])->sub(new \DateInterval('PT1S')) ];
}
/**
* Returns summary information for e-mail messages as an array
*
* @return array Array with summary information
*/
public function summary(): array
{
return $this->db->getMapper('statistics')->summary($this->domain, $this->range);
}
/**
* Returns a list of ip-addresses from which the e-mail messages were received, with some statistics for each one
*
* @return array A list of ip-addresses with fields
* `ip`, `emails`, `dkim_aligned`, `spf_aligned`
*/
public function ips(): array
{
return $this->db->getMapper('statistics')->ips($this->domain, $this->range);
}
/**
* Returns a list of organizations that sent the reports with some statistics for each one
*
* @return array List of organizations with fields `name`, `reports`, `emails`
*/
public function organizations(): array
{
return $this->db->getMapper('statistics')->organizations($this->domain, $this->range);
}
}

View File

@ -0,0 +1,109 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This file contains the class Status
*
* @category API
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\Settings\SettingsList;
/**
* This class is designed to get the general state of DmarcSrg
*/
class Status
{
private $core = null;
/**
* The constructor
*
* @param Core $core
*/
public function __construct(object $core)
{
$this->core = $core;
}
/**
* Returns general state of DmarcSrg
*
* This method returns an array with general state of the modules Admin, Auth
* and statistics for the last N days.
*
* @return array
*/
public function get(): array
{
$adm_res = $this->core->admin()->state();
$res = [
'state' => $adm_res['state']
];
if (isset($adm_res['error_code'])) {
$res['error_code'] = $adm_res['error_code'];
if (isset($adm_res['message'])) {
$res['message'] = $adm_res['message'];
}
if (isset($adm_res['debug_info'])) {
$res['debug_info'] = $adm_res['debug_info'];
}
} elseif (isset($adm_res['database']['error_code'])) {
$res['error_code'] = $adm_res['database']['error_code'];
if (isset($adm_res['database']['message'])) {
$res['message'] = $adm_res['database']['message'];
}
if (isset($adm_res['database']['debug_info'])) {
$res['debug_info'] = $adm_res['database']['debug_info'];
}
} elseif (isset($adm_res['message'])) {
$res['message'] = $adm_res['message'];
} elseif (isset($adm_res['database']['message'])) {
$res['message'] = $adm_res['database']['message'];
}
if (!isset($res['error_code']) || $res['error_code'] === 0) {
$days = SettingsList::getSettingByName('status.emails-for-last-n-days')->value();
$stat = Statistics::lastNDays(null, $days);
$res['emails'] = $stat->summary()['emails'];
$res['emails']['days'] = $days;
}
$auth = null;
if ($this->core->auth()->isEnabled()) {
$auth = $this->core->userId() !== false ? 'yes' : 'no';
} else {
$auth = 'disabled';
}
$res['authenticated'] = $auth;
$res['version'] = Core::APP_VERSION;
$res['php_version'] = phpversion();
return $res;
}
}

View File

@ -0,0 +1,181 @@
<?php
// Set 1 to enable debug messages
$debug = 0;
// Settings for assessing the database in which reports will be saved
$database = [
'host' => 'localhost',
'type' => 'mysql',
'name' => 'dmarc',
'user' => 'dmarc_user',
'password' => 'password',
/**
* This pamemeter can be usefull if the database is shared with other applications
* to avoid conflicting table names. You do not need to specify this parameter
* if you use a dedicated database.
* Example value: dmarc_
* Caution! Do not use an empty string as the table prefix value if you share the database with
* other applications.
* Caution! Do not change this parameter if you have already created the tables in the database
* because the tables will not be renamed automatically.
*/
'table_prefix' => ''
];
/**
* It is only required if you want to get reports from a mailbox automatically.
* In order to collect reports from several mailboxes, you should put each
* mailbox settings in an array.
*/
$mailboxes = [
// Just for displaying in the web-admin and utilities. Not necessary.
'name' => 'Dmarc-Rua',
// Host of the email server. You can specify a port separated by a colon.
'host' => 'yourdomain.net',
// Connection encryption method. The valid values are:
// 'none' - without encryption (strongly not recommend).
// 'ssl' - SSL/TLS on a separate port, for IMAP it is usually port 993. Default value.
// 'starttls' - STARTTLS method, usually on the standard IMAP port 143.
'encryption' => 'ssl',
// Set true if you want to connect to the IMAP server without certificate validation
'novalidate-cert' => false,
// Mailbox user name.
'username' => 'dmarc-rua@yourdomain.net',
// Mailbox password.
'password' => 'password',
// Mailbox name
'mailbox' => 'INBOX',
// IMAP authorization methods to be excluded.
// For example: 'auth_exclude' => [ 'GSSAPI', 'NTLM' ]
'auth_exclude' => []
];
/**
* It is only required if you want to get reports from a server directory.
* In order to collect report from several directories, you should put each
* directory settings in an array. Processing of the directories is not recursive.
* It is recommended to use atomic methods for adding files to these directories.
* Attention! All successfully processed files will be deleted from the directories
* and all others will be moved to subdirectory `failed`, that will be created
* automatically if it does not exist.
*/
//$directories = [
// // Just for displaying in the web-admin and utilities. Not necessary.
// 'name' => 'Rua-Dir',
// // The directory location
// 'location' => '/var/spool/dmarc-srg/rua'
//];
$admin = [
// Set this value to null or remove this parameter to disable authentication
// Note: The authentication always fails with an empty string password. Change it if you want to use the web ui.
'password' => '',
];
//
$fetcher = [
'mailboxes' => [
// How many messages will be fetched at once maximum. 0 to disable any limiting.
'messages_maximum' => 10,
/**
* What to do with the email message when a report from it has been successfully processed
* and saved to the database. The following actions are available:
* 'mark_seen' - Mark the email message as seen.
* 'delete' - Delete email message from the mailbox.
* 'move_to:dir' - Move the email message to child mailbox with name 'dir'.
* The child mailbox will be created it doesn't exist.
* Note: You can specify multiple actions by putting them in an array. For example:
* 'when_done' => [ 'mark_seen', 'move_to:done' ],
* The default value is 'mark_seen'.
*/
'when_done' => 'mark_seen',
/**
* What to do with the email message when a report from it has been rejected.
* The same actions are available as for the when_done.
* The default value is 'move_to:failed'.
*/
'when_failed' => 'move_to:failed'
],
'directories' => [
// How many report files will be processed at once maximum. 0 to disable any limiting.
'files_maximum' => 50,
/**
* What to do with the report file when it has been successfully processed.
* The folowing actions are available: 'delete', 'move_to'. See the when_done for mailboxes
* for detailed description.
* The default value is 'delete'.
*/
'when_done' => 'delete',
/**
* What to do with the report file when it has been rejected.
* The same actions are available as for the when_done.
* The default value is 'move_to:failed'.
*
*/
'when_failed' => 'move_to:failed'
],
/**
* Domains matching this regular expression will be automatically added to the database from processed
* reports. This option does not affect domains that have already been added to the database.
* It is not necessary to use this option in most cases. The option can be useful if you have many domains
* or subdomains and do not want to add them manually in the GUI. An empty string or null doesn't match any domain.
* Note: The first domain from the first report will be automatically added anyway.
* Some examples:
* '.+\\.example\\.net$' - Matches any subdomain of the domain example.net
* '^mymail[0-9]+\\.net$' - Matches the domains mymail01.net, mymail02.net, mymail99999.net, etc.
*/
'allowed_domains' => ''
];
// Settings for sending summary reports if it is necessary.
// It uses in utils/summary_report.php
$mailer = [
'from' => 'postmaster@yourdomain.net',
'default' => 'user@yourdomain.net'
];
//
$cleaner = [
// It is used in utils/mailbox_cleaner.php
'mailboxes' => [
// Will remove messages older than (days)
'days_old' => 30,
// How many messages will be removed at once maximum.
'delete_maximum' => 50,
// How many messages must be leave in the mailbox minimum.
'leave_minimum' => 100,
/**
* Status of emails to be deleted for mailboxes where successfully processed emails and rejected emails
* are located. If it is the same mailbox, then the more forgiving criteria of the two will be used.
* The valid values are:
* 'none' - no action with it. The default value for rejected mail messages.
* 'seen' - only seen messages will be removed. The default value for successully processed mail messages.
* 'any' - all messages will be removed.
* Note: In the mailbox, where letters with incoming DMARC reports initially come in, unseen messages
* will not be deleted in any case.
*/
'done' => 'seen',
'failed' => 'none'
],
// It is used in utils/reports_cleaner.php
'reports' => [
'days_old' => 30,
'delete_maximum' => 50,
'leave_minimum' => 100
],
// It is used in utils/reportlog_cleaner.php
'reportlog' => [
'days_old' => 30,
'delete_maximum' => 50,
'leave_minimum' => 100
]
];

View File

@ -0,0 +1,727 @@
@media (prefers-color-scheme: light) {
:root {
--color-fg-default: #000;
--color-fg-disabled: #666;
--color-fg-muted: #666;
--color-fg-accent: #0969da;
--color-fg-custom: #666;
--color-fg-menu: #333;
--color-bg-default: #fff;
--color-bg-header: #eee;
--color-bg-title: #ddd;
--color-bg-dialog: #fff;
--color-bg-selected: #eef;
--color-bg-focused: #ccf;
--color-bg-button: #f0f0f0;
--color-bg-dbutton: #f4f4f4;
--color-bg-hover: #d8d8d8;
--color-bg-input: #fff;
--color-br-default: #ccc;
--color-br-weak: #eee;
--color-br-strong: #777;
--color-br-focused: #66f;
--color-br-input: rgba(0,0,0,0.5);
--color-br-disabled: #e0e0e0;
--color-br-menu: #ccc;
--color-br-submenu: #eee;
--color-dg-wait: #080;
--color-st-txtblue: #00f;
--color-st-txtgreen: #080;
--color-st-txtred: #f00;
--color-nt-error: #f88;
--color-nt-warning: #ff8;
--color-nt-inform: #8f8;
--color-sh-default: rgba(0,0,0,0.5);
--color-lk-default: #00e;
--color-lk-visited: #551a8b;
}
}
@media (prefers-color-scheme: dark) {
:root {
--color-fg-default: #c9d1d9;
--color-fg-disabled: #484f58;
--color-fg-muted: #8b949e;
--color-fg-accent: #2f81f7;
--color-fg-custom: #aaadbb;
--color-fg-menu: #9ca6b1;
--color-bg-default: #0d1117;
--color-bg-header: #161b22;
--color-bg-title: #262b32;
--color-bg-dialog: #111a24;
--color-bg-selected: #161b22;
--color-bg-focused: #161b33;
--color-bg-button: #21262d;
--color-bg-dbutton: #21262d;
--color-bg-hover: #30363d;
--color-bg-input: #0d1117;
--color-br-default: #30363d;
--color-br-weak: #21262b;
--color-br-strong: #40464d;
--color-br-focused: #f78166;
--color-br-input: rgba(240,246,252,0.1);
--color-br-disabled: #30363d;
--color-br-menu: #505860;
--color-br-submenu: #30363d;
--color-dg-wait: #c58208;
--color-st-txtblue: #4040ff;
--color-st-txtgreen: #009300;
--color-st-txtred: #f22;
--color-nt-error: #da3633;
--color-nt-warning: #e7a100;
--color-nt-inform: #3fb950;
--color-sh-default: rgba(255,255,255,0.3);
--color-lk-default: #0050c0;
--color-lk-visited: #606090;
}
}
html, body, div, span, h1, h2, h3, h4, h5, ul, li, fieldset, form, label, legend,
button, table, caption, tbody, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
outline: 0;
font-size: 100%;
}
html {
color: var(--color-fg-default);
background-color: var(--color-bg-default);
}
body {
margin: 0.5em;
}
button, select, textarea, input {
padding: 0.3em .5em;
color: var(--color-fg-default);
border: .07em solid var(--color-br-input);
border-radius: 0.4rem;
}
button, select {
background-color: var(--color-bg-button);
}
button:hover, select:hover {
background-color: var(--color-bg-hover);
}
button:disabled, select:disabled{
background-color: var(--color-bg-dbutton);
}
button:disabled, select:disabled, textarea:disabled, input:disabled {
color: var(--color-fg-disabled);
border-color: var(--color-br-disabled);
}
a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible {
outline: 2px solid var(--color-fg-accent);
outline-offset: -2px;
}
textarea, input {
background-color: var(--color-bg-input);
}
a {
color: var(--color-lk-default);
}
a:visited {
color: var(--color-lk-visited);
}
h1 {
font-size: 1.4em;
margin: .35rem;
display: inline-block;
}
h2 {
font-size: 1.4em;
margin: 1em 0 .2em;
}
h3 {
font-size: 1.3em;
margin: 1em 0 .2em;
}
h4, h5 {
margin: 0 0 0.5rem 0;
text-transform: uppercase;
}
h4:not(:first-child), .info-block {
margin-top: 1rem;
}
fieldset {
display: block;
margin-bottom: 0.7em;
padding: 0.7em;
border: 0.07rem solid var(--color-br-strong);
}
legend {
margin: 0;
padding: 0 0.2em;
}
hr {
border: 0;
border-top: 0.07em solid var(--color-br-menu);
}
textarea.description {
height: 7em;
}
#stat-block ul {
display: flex;
justify-content: center;
column-gap: 1em;
margin: .2em 0;
padding: .1em;
list-style-type: none;
border-top: 0.07em solid var(--color-br-default);
border-bottom: 0.07em solid var(--color-br-default);
}
#stat-block .stat-msg {
display: none;
}
.main-table .table-body .table-cell {
border-top: 0.1em solid var(--color-br-weak);
}
.main-table .table-body .table-row.selected {
background-color: var(--color-bg-selected);
color: var(--color-fg-default);
}
.main-table.focused .table-body .table-row.selected {
background-color: var(--color-bg-focused);
}
.domains.table .table-cell.fqdn {
overflow-wrap: anywhere;
}
.unseen, .custom-value .setting-value {
font-weight: bold;
color: var(--color-fg-custom);
}
@media screen and (min-width:30em) {
h1 {
font-size: 2em;
margin: 0 .5rem;
}
}
@media screen and (min-width:35em) {
textarea.description {
min-width: 25em;
}
input[type=number] {
width: 4em;
}
}
@media screen and (min-width:46em) {
#stat-block {
float: right;
margin-bottom: 0.5rem;
}
#stat-block ul {
display: block;
margin: 0;
padding: 0;
border: none;
}
#stat-block li div {
display: inline-grid;
margin: 0.5em;
width: 6em;
height: 6em;
text-align: center;
font-size: 0.7em;
border: 0.07em solid var(--color-br-strong);
border-radius: 0.4em;
}
#stat-block .stat-msg {
display: inline;
margin: 0 1px;
}
.stat-val {
display: block;
height: 50%;
line-height: 180%;
font-size: 1.8em;
font-weight: bold;
}
}
@media screen and (max-width:40em) {
.root-list-block .db-type, .list-container .mailbox-host, .list-container .dbtable-size, .small-cards .table-header {
display: none;
}
.domains.table, .domains .table-header, .domains .table-body, .domains .table-cell,
.small-cards.table, .small-cards .table-body, .small-cards .table-row {
display: block;
}
.small-cards .table-cell {
display: flow-root;
}
.domains .table-row {
display: grid;
grid-template-columns: 2em 1fr 1fr;
}
.domains .table-cell.descr {
grid-column: 1 / 4;
grid-row: 2;
border: none;
text-align: center;
border-top: none;
}
.domains .table-body .table-cell.descr {
border-left: 0.2em solid #0000;
}
.domains .table-body .table-row.focused .table-cell.descr, .small-cards .table-body .table-row.focused {
border-left: 0.2em solid var(--color-br-focused);
}
.small-cards .table-body .table-row {
border-left: 0.2em solid #0000;
}
.small-cards .table-body .table-cell {
text-align: right;
max-width: none;
margin: 0 1em;
}
.small-cards .table-body .table-cell > div {
margin-left: auto;
}
.small-cards .table-body .table-cell::before {
content: attr(data-label);
float: left;
text-align: left;
font-weight: bold;
font-style: normal;
padding-right: .5em;
}
.small-cards .table-body .table-cell:first-child {
padding-top: 1em;
}
.small-cards .table-body .table-cell:last-child {
border-bottom: 0.13em solid var(--color-br-weak);
}
.small-cards .table-body .table-row .table-cell {
border-left: none !important;
}
.domains .table-body .table-row.selected, .domains.focused .table-body .table-row.selected,
.small-cards .table-body .table-row.selected, .small-cards.focused .table-body .table-row.selected {
background-color: unset;
}
.small-cards .table-row.colspanned .table-cell {
text-align: center;
border: none !important;
}
.custom-value .setting-value {
font-weight: normal;
}
}
@media screen and (max-width:60em) {
.report-list .table-cell.report-id {
display: none;
}
}
.bottom-border {
border-bottom: 0.07rem solid var(--color-br-strong);
}
.popup-menu ul {
display: block;
margin: 0;
padding: 0;
list-style-type: none;
}
#stat-block li {
margin: 0;
padding: 0;
display: inline-flex;
}
.disabled {
color: #888;
cursor: default;
pointer-events: none;
}
.round-border {
border: 0.07em solid var(--color-br-strong);
border-radius: 0.4em;
}
.wait-message {
margin: 0.3em;
}
.panel-container .wait-message, .panel-container .error-message {
margin: 1em;
}
.dialog .wait-message {
color: var(--color-dg-wait);
text-align: center;
}
.dialog .error-message {
text-align: center;
}
.hidden {
display: none !important;
}
#main-block {
clear: both;
}
.error-message {
color: var(--color-st-txtred);
margin: 0.3rem;
}
.main-table-container {
position: fixed;
overflow-x: hidden;
overflow-y: auto;
top: 6rem;
left: 0.5rem;
right: 0.5rem;
bottom: 0.5rem;
border: 0.1rem solid var(--color-br-weak);
border-radius: 0.4rem;
}
.main-table {
color: var(--color-fg-muted);
text-align: left;
border-spacing: 0;
width: 100%;
}
.subtable {
font-size: 90%;
border: 0.1rem solid var(--color-br-weak);
border-radius: 0.4rem;
}
.main-table .table-header {
position: sticky;
top: 0;
}
.main-table .table-header .table-cell {
position: relative;
background-color: var(--color-bg-header);
}
.main-table .table-cell {
padding: .3em 1em;
}
.main-table .table-body .table-row {
cursor: pointer;
}
.main-table .table-body .table-row:not(.colspanned):hover, .main-table .table-row.virtual-item:hover .table-cell {
background-color: var(--color-bg-selected);
}
.focused {
outline: none;
}
.main-table .table-body .table-cell:first-child {
border-left: 0.2em solid #0000;
}
.main-table .table-body .table-row.focused .table-cell:first-child {
border-left: 0.2em solid var(--color-br-focused);
}
.summary-report {
overflow-y: auto;
}
.report-table {
font-size: 90%;
border-spacing: 0;
border-collapse: collapse;
}
.custom-value .setting-value, .report-table caption {
font-style: italic;
}
.report-table th {
min-width: 4em;
padding: .3em .6em;
}
.report-table td {
padding: .3em;
text-align: right;
}
.report-table td:first-child {
text-align: left;
padding-right: 1em;
}
.report-table td, .report-table th {
border: 0.1rem solid var(--color-br-default);
}
.state-red .state-text {
color: var(--color-st-txtred);
}
.state-red .state-background {
background-color: #f00;
}
.state-green .state-text {
color: var(--color-st-txtgreen);
}
.state-green .state-background {
background-color: #080;
}
.state-yellow .state-text {
color: #f80;
}
.state-yellow .state-background {
background-color: #f80;
}
.state-gray .state-text {
color: #888;
}
.state-gray .state-background {
background-color: #888;
}
.state-blue .state-text {
color: var(--color-st-txtblue);
}
.state-blue .state-background {
background-color: #00f;
}
.panel-container {
margin: 0.5rem 0;
padding: 1rem;
}
.block-item-column {
display: flex;
margin: .2rem 0;
}
.block-item-column .value {
margin-left: 0.5em;
}
.root-list-block, .block-list-item {
display: flex;
gap: .5rem;
align-items: center;
padding: 0 .5rem;
}
.root-list-block {
min-height: 4rem;
font-size: 1.3rem;
cursor: pointer;
}
.block-list-item {
height: 3.25rem;
background-color: var(--color-bg-header);
margin: 0 0 1rem 0;
}
.list-container {
margin: 1rem 0.8rem 0 1.5rem;
}
.title-item-wrap, .db-type, .db-location, .dbtable-records, .dbtable-size, .mailbox-host, .mailbox-location {
flex: 1;
}
.message-item, .directory-location {
flex: 2;
}
.status-indicator {
width: 1rem;
min-width: 1rem;
margin: auto 0.5rem auto 0;
height: 1rem;
border-radius: 50%;
background: radial-gradient(circle farthest-corner at 35% 35%, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0));
}
.root-list-block .status-indicator {
width: 1.2rem;
height: 1.2rem;
}
.db-menu-button {
position: relative;
width: 1.7em;
}
.db-menu-button span[role="button"] {
font-weight: bold;
color: #888;
user-select: none;
}
.db-menu-button>div>span:hover {
color: #00f;
}
.source-check-button {
margin-right: 0.7em;
}
.popup-menu {
position: absolute;
top: 130%;
left: -5.3em;
width: 7em;
text-align: center;
background-color: var(--color-bg-default);
}
.popup-menu::after {
content: "";
display: block;
position: absolute;
top: -0.3em;
bottom: auto;
right: auto;
left: 5.4em;
width: 0;
border-width: 0 0.4em 0.4em;
border-style: solid;
border-color: var(--color-bg-default) transparent;
}
.popup-menu::before {
content: "";
display: block;
position: absolute;
top: -0.4em;
bottom: auto;
right: auto;
left: 5.4em;
width: 0;
border-width: 0 0.4em 0.4em;
border-style: solid;
border-color: var(--color-br-strong) transparent;
}
.popup-menu li {
margin: 0.2em 0 0.2em 0;
}
.popup-menu li:hover {
color: #00f;
}
.report-result {
display: inline-block;
border-color: var(--color-br-strong);
border-style: solid;
border-width: 0.07em;
border-radius: 0.4em;
padding: 0.2em;
margin: 0 0.2em 0 0.2em;
}
.main-table .report-result {
font-size: 75%;
}
.report-result-pass {
color: var(--color-st-txtgreen);
}
.report-result-unknown {
color: #888;
}
.report-result-fail {
color: var(--color-st-txtred);
}
.report-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: var(--color-bg-default);
text-align: center;
transition: all 600ms cubic-bezier(0.86, 0, 0.07, 1);
overflow: auto;
}
.report-modal > .report-header {
position: sticky;
top: 0;
padding: 1rem;
cursor: pointer;
border-bottom: solid 0.1rem var(--color-br-default);
background-color: var(--color-bg-title);
}
.report-modal > .report-header > .header-text {
padding: 0.5rem;
cursor: auto;
}
.report-record > .header {
padding: 0.4em 0;
border-bottom: solid 0.1rem var(--color-br-default);
border-radius: 0.3em 0.3em 0 0;
background-color: var(--color-bg-header);
}
.report-modal > .body {
padding: 1rem;
}
.report-modal.report-hidden {
top: 100%;
}
.report-modal .close-btn {
position: relative;
display: inline-block;
padding: 0.7em 1.5em;
color: var(--color-fg-default);
background-color: var(--color-bg-button);
border: solid 0.07rem #888;
border-radius: 1.8em;
cursor: pointer;
transition: all .4s ease;
}
.report-modal .content {
width: 50rem;
max-width: 100%;
margin: 0 auto;
}
.report-modal .close-btn:hover {
box-shadow: 0 3px 15px var(--color-sh-default);
}
.report-records {
margin-top: 1rem;
padding-top: 1rem;
border-top: solid 0.1rem var(--color-br-default);
}
.report-record {
margin: 0 0 1rem 0;
border-color: var(--color-br-default);
}
.report-item {
display: inline-flex;
width: 98%;
padding: .3em 0;
}
.report-record .report-item {
min-height: 1.9em;
}
.report-record .report-item:not(:last-child) {
border-bottom: 0.1em solid var(--color-br-weak);
}
.report-item .title {
min-width: 30%;
}
.value.rows {
display: flex;
flex-direction: column;
row-gap: .3em;
}
.report-item .title, .report-item .value {
text-align: left;
margin: auto 0;
}
.table-cell.report-id, .table-cell.setting-value {
max-width: 15em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.options-button {
color: #888;
font-size: 80%;
margin-left: 0.3em;
cursor: pointer;
}
button.options-button {
color: inherit;
margin-left: 1em;
}
.options-button:hover, .options-button.active {
color: #080;
}
.options-block {
display: flex;
align-items: center;
}
.buttons-block {
display: flex;
gap: .5em;
margin-top: .5em;
}
.table-cell.cell-status {
width: 1em;
}
.virtual-item, .nodata {
color: #888;
font-style: italic;
}
.left-titled {
display: grid;
grid-template-columns: auto 1fr;
row-gap: .3em;
column-gap: 1em;
align-items: center;
}
.vertical-content {
display: flex;
flex-direction: column;
gap: 1em;
}
.vertical-content > * {
margin-top: 0;
margin-bottom: 0;
}
.about .vertical-content {
max-width: 30em;
}

View File

@ -0,0 +1,138 @@
#main-menu-button {
float: left;
display: block;
width: 25px;
height: 22px;
margin: 0.2rem;
background-color: var(--color-bg-default);
}
#main-menu-toggle {
display: none;
}
#main-menu-button .button-decor, #main-menu-button .button-decor::after, #main-menu-button .button-decor::before {
width: 25px;
height: 4px;
background-color: #666;
border-radius: 3px;
border-width: 0;
backface-visibility: hidden;
transition: all 600ms cubic-bezier(0.86, 0, 0.07, 1);
z-index: 2;
}
#main-menu-button .button-decor::after, #main-menu-button .button-decor::before {
content: "";
position: absolute;
left: 0;
}
#main-menu-button .button-decor {
position: relative;
top: 4px;
}
#main-menu-button .button-decor::after {
top: 18px;
}
#main-menu-button .button-decor::before {
top: 9px;
}
#main-menu-button .toggle-button {
display: block;
position: relative;
top: -10%;
left: -10%;
width: 120%;
height: 120%;
cursor: pointer;
z-index: 3;
}
#main-menu-toggle:checked ~ .button-decor {
top: 13px;
transform: rotate(45deg);
}
#main-menu-toggle:checked ~ .button-decor::after {
top: 0;
transform: rotate(90deg);
}
#main-menu-toggle:checked ~ .button-decor::before {
top: 0;
transform: rotate(0);
}
.menu-box {
display: block;
position: fixed;
visibility: hidden;
top: 0;
left: -100%;
bottom: 0;
margin: 0;
min-width: 16rem;
padding: 3rem 0;
overflow: auto;
list-style: none;
background-color: var(--color-bg-header);
box-shadow: 3px 0px 6px var(--color-sh-default);
transition: all 600ms cubic-bezier(0.86, 0, 0.07, 1);
z-index: 1;
}
.menu-box ul {
list-style: none;
padding: 0;
}
.menu-box > li {
border-top: 1px solid var(--color-br-menu);
}
.menu-box > li:last-child {
border-bottom: 1px solid var(--color-br-menu);
}
.menu-box li li {
background-color: var(--color-bg-default);
border-bottom: 1px solid var(--color-br-submenu);
}
.menu-box li a, .menu-box li span {
display: block;
padding: 0.5rem 1.5rem;
color: var(--color-fg-menu);
font-size: 125%;
text-decoration: none;
cursor: pointer;
}
.menu-box a:hover {
color: #fff;
background-color: #c45;
}
#main-menu-toggle:checked ~ .menu-box {
visibility: visible;
left: 0;
}
.menu-box li span::after {
content: "";
width: 10px;
height: 10px;
margin-top: 9px;
border-top: 3px solid #444;
border-right: 3px solid #444;
float: right;
border-top-right-radius: 3px;
transform: rotate(315deg);
}
.menu-box li.closed span::after {
margin: 3px;
transform: rotate(135deg);
}
.menu-box .closed .submenu {
display: none;
}
.menu-box .about {
position: absolute;
top: 0;
right: 0;
font-size: 75%;
border: 0;
}
.menu-box .about a {
padding: .95rem;
text-decoration: underline;
}
.submenu .selected {
border-left: 0.2em solid #c45;
}

View File

@ -0,0 +1,65 @@
#notifications-block {
position: fixed;
top: 0;
right: 0;
width: 100%;
z-index: 200;
}
.notification {
overflow: hidden;
color: #000;
font-size: 0.9rem;
opacity: 0.9;
background-clip: padding-box;
border: 1px solid rgba(0, 0, 0, 1);
box-shadow: 0 0.25rem 0.75rem var(--color-sh-default);
position: relative;
padding: 0.75rem 2rem 0.75rem 0.75rem;
overflow-wrap: break-word;
word-break: normal;
}
.notification:not(:last-child) {
margin-bottom: 0.2rem;
}
@media screen and (min-width:20em) {
#notifications-block {
top: 2rem;
right: 1em;
width: 15em;
}
.notification {
border-radius: 0.25rem;
}
.notification:not(:last-child) {
margin-bottom: 0.5rem;
}
}
.notif-close {
position: absolute;
top: 0;
right: 0.3rem;
padding: 0;
color: #000;
border: 0;
float: right;
cursor: pointer;
font-size: 1.2rem;
font-weight: 700;
line-height: 1;
text-shadow: 0 1px 0 #fff;
opacity: 0.6;
background-color: transparent;
margin: 0;
border-radius: 0;
}
.notif-error {
background-color: var(--color-nt-error);
}
.notif-warn {
background-color: var(--color-nt-warning);
}
.notif-info {
background-color: var(--color-nt-inform);
}

View File

@ -0,0 +1,162 @@
.table {
display: table;
empty-cells: show;
}
.table-header {
display: table-header-group;
font-weight: bold;
}
.table-body {
display: table-row-group;
}
.table-row {
display: table-row;
}
.table-cell {
display: table-cell;
}
.colspanned {
position: relative;
}
.colspanned .table-cell:first-child {
position: absolute;
left: 0;
right: 0;
}
.dialog {
display: inline-block;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.dialog .container {
display: flex;
flex-direction: column;
height: 100%;
text-align: left;
white-space: normal;
background-color: var(--color-bg-dialog);
}
.dialog form {
margin: auto 0;
padding: 1em;
overflow: auto;
}
.titled-input {
display: flex;
flex-direction: column;
row-gap: .7em;
}
.titled-input > label {
display: flex;
flex-direction: column;
row-gap: .2em;
}
.dialog-buttons {
display: flex;
flex-flow: column;
justify-content: center;
gap: 1em;
margin: 1em 0 0 0;
}
@media screen and (min-width:35em) {
.dialog {
position: static;
}
.dialog .container {
border: solid 0.1rem #888;
}
.titled-input {
display: table;
margin: -.5em 0;
border-spacing: 1em .5em;
}
.titled-input > label {
display: table-row;
}
.titled-input > label > * {
display: table-cell;
vertical-align: middle;
}
.titled-input select {
width: 100%;
}
fieldset.titled-input {
margin-bottom: 0;
}
.dialog-buttons {
flex-flow: row wrap;
}
}
.dialog-overlay {
display: flex;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.3);
align-items: center;
justify-content: center;
white-space: nowrap;
z-index: 100;
}
.dialog .title {
display: flex;
align-items: center;
justify-content: center;
min-height: 2em;
background-color: var(--color-bg-title);
white-space: nowrap;
}
.dialog .title-text {
display: flex;
margin: auto;
padding-left: 0.7em;
}
.dialog .close-btn {
display: flex;
margin-right: 0.1em;
color: var(--color-fg-default);
font-size: 1.2rem;
font-weight: 700;
opacity: 0.5;
text-shadow: 0 1px 0 #fff;
cursor: pointer;
border: 0;
background-color: transparent;
}
.dialog-buttons button {
min-width: 7em;
}
.table-cell.sortable {
cursor: pointer;
}
.sortable.arrows::before, .sortable.arrows::after {
content: '';
border-style: solid;
border-width: 0.4em 0.3em;
border-color: transparent;
height: 0;
position: absolute;
right: 0.6em;
width: 0;
}
.sortable.arrows::before {
border-bottom-color: #bbb;
top: 0;
}
.sortable.arrows::after {
border-top-color: #bbb;
bottom: 0;
}
.sortable.arrows.sorted-asc::before {
border-bottom-color: #777;
}
.sortable.arrows.sorted-des::after {
border-top-color: #777;
}

View File

@ -0,0 +1,28 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (isset($debug) && $debug === 1) {
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
}

View File

@ -0,0 +1,131 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
* =========================
*
* This script returns the domains information
*
* HTTP GET query:
* when the header 'Accept' is 'application/json':
* It returns a list of the domains or data for the domain specified in the parameter domain.
* otherwise:
* it returns the content of the index.html file
* HTTP POST query:
* Inserts or updates data for specified domain. The data must be in json format with the following fields:
* `fqdn` string FQDN of the domain.
* `action` string Must be one of the following values: `add`, `update`, `delete`.
* If the value is `delete`, all the fields below will be ignored.
* `active` boolean Whether reports for the domain will be accepted or not.
* `description` string Description of the domain.
* Example:
* { "fqnd": "example.com", "action": "update", "active": true, "description": "My description" }
* Other HTTP methods:
* it returns an error
*
* All the data is in json format.
*
* @category Web
* @package DmarcSrg
* @author Aleksey Andreev (liuch)
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPLv3
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Domains\Domain;
use Liuch\DmarcSrg\Domains\DomainList;
use Liuch\DmarcSrg\Exception\SoftException;
use Liuch\DmarcSrg\Exception\RuntimeException;
require 'init.php';
if (Core::isJson()) {
try {
Core::instance()->auth()->isAllowed();
if (Core::method() == 'GET') {
if (isset($_GET['domain'])) {
Core::sendJson((new Domain($_GET['domain']))->toArray());
return;
}
$res = (new DomainList())->getList();
$list = array_map(function ($domain) {
return $domain->toArray();
}, $res['domains']);
Core::sendJson([
'domains' => $list,
'more' => $res['more']
]);
return;
} elseif (Core::method() == 'POST') {
$data = Core::getJsonData();
if ($data) {
$domain = new Domain([
'fqdn' => $data['fqdn'] ?? null,
'active' => $data['active'] ?? null,
'description' => $data['description'] ?? null
]);
$action = $data['action'] ?? '';
switch ($action) {
case 'add':
if ($domain->exists()) {
throw new SoftException('The domain already exists');
}
$domain->save();
break;
case 'update':
if (!$domain->exists()) {
throw new SoftException('The domain does not exist');
}
$domain->save();
break;
case 'delete':
$domain->delete();
unset($domain);
break;
default:
throw new SoftException('Unknown action. Valid values are "add", "update", "delete".');
}
$res = [
'error_code' => 0,
'message' => 'Successfully'
];
if (isset($domain)) {
$res['domain'] = $domain->toArray();
}
Core::sendJson($res);
return;
}
}
} catch (RuntimeException $e) {
Core::sendJson(ErrorHandler::exceptionResult($e));
return;
}
} elseif (Core::method() == 'GET') {
Core::sendHtml();
return;
}
Core::sendBad();

View File

@ -0,0 +1,131 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Liuch\DmarcSrg;
use Liuch\DmarcSrg\ErrorHandler;
use Liuch\DmarcSrg\Report\ReportFetcher;
use Liuch\DmarcSrg\Sources\DirectorySource;
use Liuch\DmarcSrg\Sources\UploadedFilesSource;
use Liuch\DmarcSrg\Directories\DirectoryList;
use Liuch\DmarcSrg\Exception\RuntimeException;
require 'init.php';
if (Core::method() == 'GET') {
if (!Core::isJson()) {
Core::sendHtml();
return;
}
try {
Core::instance()->auth()->isAllowed();
$res = [];
$up_max = ini_get('max_file_uploads');
if ($up_max) {
$res['upload_max_file_count'] = intval($up_max);
}
$up_size = ini_get('upload_max_filesize');
if ($up_size) {
if (!empty($up_size)) {
$ch = strtolower($up_size[strlen($up_size) - 1]);
$up_size = intval($up_size);
switch ($ch) {
case 'g':
$up_size *= 1024;
// no break
case 'm':
$up_size *= 1024;
// no break
case 'k':
$up_size *= 1024;
// no break
}
$res['upload_max_file_size'] = $up_size;
}
}
$dirs = [];
foreach ((new DirectoryList())->list() as $dir) {
$da = $dir->toArray();
try {
$files = $dir->count();
} catch (RuntimeException $e) {
$files = -1;
}
$da['files'] = $files;
$dirs[] = $da;
}
$res['directories'] = $dirs;
Core::sendJson($res);
} catch (RuntimeException $e) {
Core::sendJson(ErrorHandler::exceptionResult($e));
}
return;
}
if (Core::method() == 'POST') {
try {
Core::instance()->auth()->isAllowed();
$data = Core::getJsonData();
if ($data) {
if (isset($data['cmd'])) {
if ($data['cmd'] === 'load-directory') {
if (isset($data['ids']) && gettype($data['ids']) === 'array' && count($data['ids']) > 0) {
$done = [];
$dirs = [];
$list = new DirectoryList();
foreach ($data['ids'] as $id) {
$dir_id = gettype($id) === 'integer' ? $id : -1;
if (!in_array($id, $done, true)) {
$done[] = $id;
$dirs[] = $list->directory($dir_id);
}
}
if (count($dirs) > 0) {
$results = [];
foreach ($dirs as $dir) {
$sres = (new ReportFetcher(new DirectorySource($dir)))->fetch();
foreach ($sres as &$r) {
$results[] = $r;
}
unset($r);
}
Core::sendJson(ReportFetcher::makeSummaryResult($results));
return;
}
}
}
}
} elseif (isset($_FILES['report_file']) && isset($_POST['cmd']) && $_POST['cmd'] === 'upload-report') {
$results = (new ReportFetcher(new UploadedFilesSource($_FILES['report_file'])))->fetch();
Core::sendJson(ReportFetcher::makeSummaryResult($results));
return;
}
} catch (RuntimeException $e) {
Core::sendJson(ErrorHandler::exceptionResult($e));
return;
}
}
Core::sendBad();

View File

@ -0,0 +1,65 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>DMARC Reports</title>
<meta charset="UTF-8" />
<meta name="referrer" content="same-origin">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/main.css" type="text/css" />
<link rel="stylesheet" href="css/widgets.css" type="text/css" />
<link rel="stylesheet" href="css/mainmenu.css" type="text/css" />
<link rel="stylesheet" href="css/notification.css" type="text/css" />
<script src="js/common.js"></script>
<script src="js/widgets.js"></script>
<script src="js/main.js"></script>
<script src="js/list.js"></script>
<script src="js/logs.js"></script>
<script src="js/login.js"></script>
<script src="js/admin.js"></script>
<script src="js/files.js"></script>
<script src="js/status.js"></script>
<script src="js/report.js"></script>
<script src="js/domains.js"></script>
<script src="js/summary.js"></script>
<script src="js/settings.js"></script>
<script src="js/notification.js"></script>
</head>
<body>
<div id="main-menu-button">
<input id="main-menu-toggle" type="checkbox" />
<div class="button-decor"></div>
<label class="toggle-button" for="main-menu-toggle"></label>
<ul id="main-menu" class="menu-box">
<li class="closed">
<span>Reports</span>
<ul class="submenu">
<li><a href="./">Incoming reports</a></li>
<li><a href="files.php">Files</a></li>
<li><a href="summary.php">Summary reports</a></li>
</ul>
</li>
<li class="closed">
<span>Administration</span>
<ul class="submenu">
<li><a href="admin.php">Admin panel</a></li>
<li><a href="logs.php">Logs</a></li>
</ul>
</li>
<li class="about"><a href="">About</a></li>
<li class="closed">
<span>Settings</span>
<ul class="submenu">
<li><a href="domains.php">Domains</a></li>
<li><a href="settings.php">Advanced</a></li>
</ul>
</li>
</ul>
</div>
<h1>DMARC Reports</h1>
<div id="stat-block"></div>
<div id="main-block"></div>
<div id="detail-block"></div>
<div id="notifications-block"></div>
</body>
</html>

View File

@ -0,0 +1,58 @@
<?php
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
spl_autoload_register(function ($class) {
$prefix = 'Liuch\\DmarcSrg\\';
$prefix_len = 15;
$base_dir = __DIR__ . '/classes/';
if (strncmp($prefix, $class, $prefix_len) === 0) {
$relative_class = substr($class, $prefix_len);
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
if (file_exists($file)) {
require_once($file);
}
}
});
date_default_timezone_set('GMT');
$core = new Liuch\DmarcSrg\Core([
'auth' => [ 'Liuch\DmarcSrg\Auth' ],
'admin' => [ 'Liuch\DmarcSrg\Admin' ],
'ehandler' => [ 'Liuch\DmarcSrg\ErrorHandler' ],
'config' => [ 'Liuch\DmarcSrg\Config', [ 'config/conf.php' ] ],
'status' => [ 'Liuch\DmarcSrg\Status' ],
'database' => [ 'Liuch\DmarcSrg\Database\DatabaseController' ]
]);
$core->errorHandler()->setLogger(new Liuch\DmarcSrg\Log\PhpSystemLogger());
set_exception_handler(function ($e) {
Liuch\DmarcSrg\Core::instance()->errorHandler()->handleException($e);
});
set_error_handler(function (int $severity, string $message, string $file, int $line) {
if (error_reporting() === 0) {
return false;
}
throw new \ErrorException($message, -1, $severity, $file, $line);
});

View File

@ -0,0 +1,678 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Admin {
constructor(id) {
this._state = null;
this._element = null;
this._sources = null;
this._database = null;
}
display() {
let cn = document.getElementById("main-block");
if (!this._element) {
this._element = document.createElement("div");
this._element.setAttribute("class", "panel-container round-border");
this._element.appendChild(this._get_database_elements());
this._element.appendChild(this._get_sources_elements());
}
cn.appendChild(this._element);
}
update() {
this._get_admin_state();
}
title() {
return "Admin Panel";
}
_get_database_elements() {
let fr = document.createDocumentFragment();
let h = document.createElement("h4");
h.appendChild(document.createTextNode("Database"));
fr.appendChild(h);
if (!this._database) {
this._database = new DatabaseListBox(this._create_db_item_menu_element());
}
fr.appendChild(this._database.element());
return fr;
}
_get_sources_elements() {
let fr = document.createDocumentFragment();
let h = document.createElement("h4");
h.appendChild(document.createTextNode("Report sources"));
fr.appendChild(h);
if (!this._sources) {
this._sources = new SourceListBox();
}
fr.appendChild(this._sources.element());
return fr;
}
_get_admin_state() {
[ this._database, this._sources ].forEach(function(c) {
c.set_status("wait");
});
let t = this;
window.fetch("admin.php", {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the admin data");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
t._state = data;
t._fill_data();
}).catch(function(err) {
Common.displayError(err);
t._fill_data(err.message);
});
}
_send_command(cmd) {
let t = this;
return window.fetch("admin.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify(cmd)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed");
return resp.json();
}).finally(function() {
t._get_admin_state();
Status.instance().update().catch(function(){});
});
}
_fill_data(err_msg) {
if (!err_msg) {
let d = this._state.database || [];
this._database.set_data({
root: {
name: d.name || "-",
type: d.type || "-",
correct: d.correct,
message: d.message || "-",
location: d.location || "-"
},
groups: [
{ name: "Tables", items: this._state.database.tables || [] }
]
});
this._sources.set_data({
groups: [
{ name: "Mailboxes", type: "mailbox", items: this._state.mailboxes || [] },
{ name: "Directories", type: "directory", items: this._state.directories || [] }
]
});
}
else {
this._database.set_status("error", err_msg);
this._sources.set_status("error", err_msg);
}
if (this._state && this._state.database && this._state.database.needs_upgrade) {
document.querySelector(".db-menu-button li[data-action=upgradedb]").classList.remove("hidden");
}
}
_create_db_item_menu_element() {
let el = document.createElement("div");
let span = document.createElement("span");
span.setAttribute("role", "button");
span.appendChild(document.createTextNode("..."));
el.appendChild(span);
//
let mn = document.createElement("div");
mn.setAttribute("class", "db-item-menu popup-menu round-border hidden");
let ul = document.createElement("ul");
Admin.db_actions.forEach(function(it) {
let li = document.createElement("li");
li.setAttribute("data-action", it.action);
li.setAttribute("data-title", it.title);
li.setAttribute("title", it.long_title);
let sp = document.createElement("span");
sp.appendChild(document.createTextNode(it.name));
li.appendChild(sp);
ul.appendChild(li);
if (it.action === "upgradedb")
li.classList.add("hidden");
}, this);
mn.appendChild(ul);
el.appendChild(mn);
let t = this;
el.addEventListener("click", function(event) {
let it = event.target.closest("li");
if (it || event.target.parentNode === this) {
event.stopPropagation();
this.querySelector(".popup-menu").classList.toggle("hidden");
}
if (it) {
let action = it.getAttribute("data-action");
let title = it.getAttribute("data-title");
t._do_db_action_password(action, title);
}
});
return el;
}
_do_db_action_password(action, title) {
let ld = new LoginDialog({
nofetch: true,
nousername: true
});
document.getElementById("main-block").appendChild(ld.element());
let that = this;
ld.show().then(function(d) {
if (d) {
that._do_db_action(action, title, { password: d.password });
}
}).catch(function(err) {
Common.displayError(err);
}).finally(function() {
ld.remove();
});
}
_do_db_action(action, title, data) {
let d = { cmd: action };
if (data) {
d = Object.assign(d, data);
}
this._send_command(d).then(function(data) {
Common.checkResult(data);
Notification.add({ text: title + ": " + (data.message || "Completed successfully!"), type: "info" });
}).catch(function(err) {
Common.displayError(err);
Notification.add({ text: title + ": " + err.message, type: "error", delay: 10000 });
});
}
}
Admin.db_actions = [
{
name: "Initiate",
action: "initdb",
title: "Initiate DB",
long_title: "Create all needed tables and indexes in the database"
},
{
name: "Drop",
action: "cleandb",
title: "Drop tables",
long_title: "Drop all the tables from the database"
},
{
name: "Upgrade",
action: "upgradedb",
title: "Upgrade DB",
long_title: "Update the structure of the database"
}
];
class DropdownListBox {
constructor() {
this._item_groups = [];
this._element = null;
this._root_item = null
this._list_element = null;
}
element() {
if (!this._element) {
let el = document.createElement("div");
el.setAttribute("class", "round-border");
let that = this;
el.addEventListener("click", function(event) {
if (event.target.closest(".root-list-block")) {
if (that._item_groups.length > 0) {
that._list_element.classList.toggle("hidden");
that._root_item.element().classList.toggle("bottom-border");
}
}
});
this._element = el;
this._update_element();
}
return this._element;
}
set_status(type, message) {
if (type === "wait") {
set_wait_status(this.element());
}
else if (type === "error") {
set_error_status(this.element(), message);
}
}
set_data(data) {
this._root_item = new ListBoxItem();
this._make_group_list(data);
this._make_root_columns(data);
if (this._element) {
this._update_element();
}
}
_update_element() {
if (this._element.children.length != 2) {
remove_all_children(this._element);
this._element.appendChild(this._content_container());
this._element.appendChild(this._list_container());
}
}
_content_container() {
if (!this._root_item) {
this._root_item = new ListBoxItem();
}
let c = this._root_item.element();
let cl = [];
for (let i = 0; i < c.classList.length; ++i) {
if (c.classList[i].startsWith("state-"))
cl.push(c.classList[i]);
}
c.setAttribute("class", "root-list-block" + (cl.length >0 && (" " + cl.join(" ")) || ""));
return c;
}
_list_container() {
let c = document.createElement("div");
c.setAttribute("class", "list-container hidden");
c.appendChild(this._make_list_item_elements());
this._list_element = c;
return c;
}
_make_root_columns(data) {
}
_make_group_list(data) {
this._item_groups = data.groups.map(function(gd) {
return this._make_group_item(gd);
}, this);
}
_make_group_item(gr_data) {
return new ListBoxItemGroup(gr_data);
}
_make_list_item_elements() {
let fr = document.createDocumentFragment();
this._item_groups.forEach(function(ig) {
fr.appendChild(ig.element());
});
return fr;
}
}
class DatabaseListBox extends DropdownListBox {
constructor(menu) {
super();
this._menu = menu;
this._name = null;
this._type = null;
this._correct = false;
this._message = null;
this._location = null;
}
set_data(data) {
this._name = data.root.name;
this._type = data.root.type;
this._correct = data.root.correct;
this._message = data.root.message;
this._location = data.root.location;
super.set_data(data);
}
_make_root_columns(data) {
this._root_item.state(this._correct && "green" || "red");
this._root_item.add_column(new StatusIndicator(this._name, this._message, "title-item-wrap"));
this._root_item.add_column(new ListBoxColumn(this._message, null, "message-item state-text"));
this._root_item.add_column(new ListBoxColumn(this._type, null, "db-type"));
this._root_item.add_column(new ListBoxColumn(this._location, null, "db-location"));
if (this._menu)
this._root_item.add_column(new ListBoxColumn(this._menu, null, "db-menu-button"));
}
_make_group_item(gr_data) {
return new DatabaseItemGroup(gr_data);
}
}
class SourceListBox extends DropdownListBox {
element() {
let _new = !this._element && true || false;
super.element();
if (_new) {
let that = this;
this._element.addEventListener("click", function(event) {
if (event.target.tagName == "BUTTON") {
let p = event.target.closest("div[data-id]")
if (p) {
let id = parseInt(p.getAttribute("data-id"));
let type = p.getAttribute("data-type");
that._check_button_clicked(id, type, event.target);
}
}
});
}
return this._element;
}
_make_root_columns(data) {
let count = this._item_groups.reduce(function(cnt, gr) {
return cnt + gr.count();
}, 0);
let enabled = (count > 0);
this._root_item.state(enabled && "green" || "gray");
this._root_item.add_column(new StatusIndicator("Total sources: " + count, enabled && "Enabled" || "Disabled"));
}
_make_group_item(gr_data) {
return new SourceItemGroup(gr_data);
}
_check_button_clicked(id, type, btn) {
let that = this;
let state = "yellow";
let btn_text = btn.textContent;
btn.textContent = "Checking...";
btn.disabled = true;
window.fetch("admin.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify({ cmd: "checksource", id: id, type: type })
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
let msg = [ data.message ];
if (data.status) {
if (type === "mailbox") {
msg.push("Messages: " + data.status.messages);
msg.push("Unseen: " + data.status.unseen);
}
else if (type === "directory") {
msg.push("Files: " + data.status.files);
}
}
Notification.add({ text: msg, type: "info" });
state = "green";
}).catch(function(err) {
Common.displayError(err);
Notification.add({ text: err.message, type: "error" });
}).finally(function() {
btn.textContent = btn_text;
btn.disabled = false;
that._set_state(state, id, type);
});
}
_set_state(state, id, type) {
let flag = 0;
let gstate = "green";
for (let i = 0; flag !== 3 && i < this._item_groups.length; ++i) {
let gr = this._item_groups[i];
if (!(flag & 1) && gr.type() === type) {
gr.state(state, id);
flag |= 1;
}
if (!(flag & 2)) {
let s = gr.state();
if (s !== "green") {
gstate = s;
flag |= 2;
}
}
}
this._root_item.state(gstate);
}
}
class ListBoxItem {
constructor() {
this._state = null;
this._element = null;
this._columns = [];
}
add_column(col) {
this._columns.push(col);
}
element() {
if (!this._element) {
this._element = document.createElement("div");
let extra_class = "";
if (this._state) {
extra_class = " state-" + this._state;
}
this._element.setAttribute("class", "block-list-item round-border" + extra_class);
this._insert_column_elements();
}
return this._element;
}
state(state) {
if (!state) {
return this._state;
}
if (this._element) {
if (this._state) {
this._element.classList.remove("state-" + this._state);
}
this._element.classList.add("state-" + state);
}
this._state = state;
}
_insert_column_elements() {
this._columns.forEach(function(c) {
this._element.appendChild(c.element());
}, this);
}
}
class SourceListItem extends ListBoxItem {
constructor(data) {
super();
this._id = data.id;
this._type = data.type;
}
id() {
return this._id;
}
type() {
return this._type;
}
element() {
let el = super.element();
el.setAttribute("data-id", this._id);
el.setAttribute("data-type", this._type);
return el;
}
}
class ListBoxItemGroup {
constructor(data) {
this._name = data.name;
this._type = data.type;
this._element = null;
this._items = data.items.map(function(it) {
return this._make_item(it);
}, this);
}
type() {
return this._type;
}
count() {
return this._items.length;
}
element() {
if (!this._element) {
let fr = document.createDocumentFragment();
let h = document.createElement("h5");
h.appendChild(document.createTextNode(this._name + " (" + this._items.length + ")"));
fr.appendChild(h);
this._items.forEach(function(it) {
fr.appendChild(it.element());
});
this._element = fr;
}
return this._element;
}
_make_item(d) {
return new ListBoxItem();
}
}
class DatabaseItemGroup extends ListBoxItemGroup {
_make_item(d) {
let it = super._make_item(d);
let state = d.error_code && "red" || (d.message === "Ok" && "green" || "yellow");
it.state(state);
it.add_column(new StatusIndicator(d.name, d.message, "title-item-wrap"));
it.add_column(new ListBoxColumn(d.engine || d.message, null, "message-item state-text"));
it.add_column(new ListBoxColumn(d.rows || 0, "Records", "dbtable-records"));
it.add_column(new ListBoxColumn((d.data_length || 0) + (d.index_length || 0), "Size", "dbtable-size"));
return it;
}
}
class SourceItemGroup extends ListBoxItemGroup {
state(new_state, item_id) {
if (item_id !== undefined) {
this._items.find(function(item) {
if (item.id() == item_id) {
item.state(new_state);
return true;
}
return false;
});
return;
}
let gstate = "green";
for (let i = 0; i < this._items.length; ++i) {
let state = this._items[i].state();
if (state !== gstate) {
return state;
}
}
return gstate;
}
_make_item(d) {
let it = new SourceListItem({ id: d.id, type: this._type });
it.state("green");
it.add_column(new StatusIndicator(d.name, null, "title-item-wrap"));
if (this._type === "mailbox") {
it.add_column(new ListBoxColumn(d.mailbox, null, "mailbox-location"));
it.add_column(new ListBoxColumn(d.host, "Host", "mailbox-host"));
}
else {
it.add_column(new ListBoxColumn(d.location, null, "directory-location"));
}
it.add_column(new ListBoxColumn(this._make_check_button(), null, "source-check-button"));
return it;
}
_make_check_button() {
let btn = document.createElement("button");
btn.appendChild(document.createTextNode("Check accessibility"));
return btn;
}
}
class ListBoxColumn {
constructor(value, title, class_string) {
this._value = value;
this._title = title;
this._class = class_string;
this._element = null;
}
element() {
if (!this._element) {
this._element = document.createElement("div");
this._element.setAttribute("class", "block-item-column" + (this._class && (" " + this._class) || ""));
this._add_children();
}
return this._element;
}
_add_children() {
let val_el = this._element;
if (this._title) {
let sp = document.createElement("span");
sp.appendChild(document.createTextNode(this._title + ":"));
this._element.appendChild(sp);
val_el = document.createElement("span");
val_el.setAttribute("class", "value");
this._element.appendChild(val_el);
}
if (typeof(this._value) != "object")
val_el.appendChild(document.createTextNode(this._value));
else
val_el.appendChild(this._value);
}
}
class StatusIndicator extends ListBoxColumn {
_add_children() {
let div = document.createElement("div");
div.setAttribute("class", "state-background status-indicator");
if (this._title) {
div.setAttribute("title", this._title);
}
this._element.appendChild(div);
if (this._value) {
div = document.createElement("div");
div.appendChild(document.createTextNode(this._value));
this._element.appendChild(div);
}
}
}

View File

@ -0,0 +1,163 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
const HTTP_HEADERS = {
"Accept": "application/json"
};
const HTTP_HEADERS_POST = {
"Content-Type": "application/json"
};
function remove_all_children(el) {
while (el.children.length > 0)
el.removeChild(el.children[0]);
while (el.childNodes.length > 0)
el.removeChild(el.childNodes[0]);
}
function set_wait_status(el, text) {
let wait = document.createElement("div");
wait.setAttribute("class", "wait-message");
wait.appendChild(document.createTextNode(text || "Getting data..."));
if (el) {
remove_all_children(el);
el.appendChild(wait);
}
return wait;
}
function set_error_status(el, text) {
let err = document.createElement("div");
err.setAttribute("class", "error-message");
err.appendChild(document.createTextNode(text || "Error!"));
if (el) {
remove_all_children(el);
el.appendChild(err);
}
return err;
}
function date_range_to_string(d1, d2) {
let s1 = d1.toISOString().substr(0, 10);
let s2 = d2.toISOString().substr(0, 10);
if (s1 !== s2) {
let d3 = new Date(d2);
d3.setSeconds(d3.getSeconds() - 1);
if (s1 !== d3.toISOString().substr(0, 10))
s1 += " - " + s2;
}
return s1;
}
function create_report_result_element(name, value, long_rec, result) {
let span = document.createElement("span");
if (long_rec)
span.appendChild(document.createTextNode(name + ": " + value));
else
span.appendChild(document.createTextNode(name));
span.setAttribute("title", value);
let extra_class = "";
if (result === undefined || result !== "")
extra_class = " report-result-" + (result || value);
span.setAttribute("class", "report-result" + extra_class);
return span;
}
function scroll_to_element(element, container) { // because scrollIntoView is poorly supported by browsers
let diff = null;
let e_rect = element.getBoundingClientRect();
let c_rect = container.getBoundingClientRect();
let height = Math.min(e_rect.height, 64);
if (e_rect.top < c_rect.top + height * 2) {
diff = e_rect.top - c_rect.top - height * 2;
}
else if (e_rect.bottom > c_rect.bottom - height) {
diff = e_rect.bottom - c_rect.bottom + height;
}
if (diff) {
container.scrollBy(0, diff);
}
}
function bytes2size(bytes) {
if (!bytes) {
return "0 bytes";
}
const k = 1024;
const sizes = [ 'bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' ];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
}
class Common {
static tuneDateTimeOutput(mode) {
Date.prototype.outputMode = mode;
if (!Date.prototype.toUIString) {
Date.prototype.toUIString = function(prefer_utc) {
if (this.outputMode === "local" || (this.outputMode === "auto" && !prefer_utc)) {
return this.toLocaleString();
}
return this.toUTCString();
};
}
}
static makeIpElement(ip) {
let url = null;
let type = ip.includes(":") && 6 || 4;
switch (type) {
case 4:
url = Common.ipv4_url;
break;
case 6:
url = Common.ipv6_url;
break;
}
let tn = document.createTextNode(ip);
if (url) {
url = url.replace("{$ip}", ip).replace("{$eip}", encodeURIComponent(ip));
let el = document.createElement("a");
el.setAttribute("href", url);
el.setAttribute("target", "_blank");
el.setAttribute("title", "IP address information");
el.appendChild(tn);
return el;
}
return tn;
}
static checkResult(data) {
if (data.error_code !== undefined && data.error_code !== 0) {
throw data;
}
}
static displayError(obj) {
console.warn(obj.message || "Unknown error");
if (!(obj instanceof Error) && obj.debug_info) {
console.warn('Error code: ' + obj.debug_info.code);
console.warn('Error content: ' + obj.debug_info.content);
}
}
}
Common.tuneDateTimeOutput("auto");

View File

@ -0,0 +1,486 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class DomainList {
constructor() {
this._table = null;
this._scroll = null;
this._element = document.getElementById("main-block");
this._sort = { column: "fqdn", direction: "ascent" };
}
display() {
this._make_scroll_container();
this._make_table();
this._scroll.appendChild(this._table.element());
this._element.appendChild(this._scroll);
this._table.focus();
}
update() {
this._fetch_list();
}
title() {
return "Domain List";
}
_fetch_list() {
this._table.display_status("wait");
let that = this;
return window.fetch("domains.php", {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the domain list");
return resp.json();
}).then(function(data) {
that._table.display_status(null);
Common.checkResult(data);
let d = { more: data.more };
d.rows = data.domains.map(function(it) {
return that._make_row_data(it);
});
d.rows.push(new NewDomainRow(4));
let fr = new DomainFrame(d, that._table.last_row_index() + 1);
that._table.clear();
that._table.add_frame(fr);
if (that._sort.column) {
that._table.sort(that._sort.column, that._sort.direction);
}
that._table.focus();
}).catch(function(err) {
Common.displayError(err);
that._table.display_status("error");
});
}
_make_scroll_container() {
this._scroll = document.createElement("div");
this._scroll.setAttribute("class", "main-table-container");
}
_make_table() {
this._table = new ITable({
class: "main-table domains",
onclick: function(row) {
let data = row.userdata();
if (data) {
this._display_edit_dialog(data);
}
}.bind(this),
onsort: function(col) {
let dir = col.sorted() && "toggle" || "ascent";
this._table.set_sorted(col.name(), dir);
this._table.sort(col.name(), col.sorted());
this._sort.column = col.name();
this._sort.direction = col.sorted();
this._table.focus();
}.bind(this),
onfocus: function(el) {
scroll_to_element(el, this._scroll);
}.bind(this)
});
[
{ content: "", sortable: true, name: "status", class: "cell-status" },
{ content: "FQDN", sortable: true, name: "fqdn" },
{ content: "Updated", sortable: true, name: "date" },
{ content: "Description", class: "descr" }
].forEach(function(col) {
let c = this._table.add_column(col);
if (c.name() === this._sort.column) {
c.sort(this._sort.direction);
}
}, this);
}
_make_row_data(d) {
let rd = { cells: [], userdata: d.fqdn };
rd.cells.push(new DomainStatusCell(d.active));
rd.cells.push({ content: d.fqdn, class: "fqdn" });
rd.cells.push(new DomainTimeCell(new Date(d.updated_time)));
rd.cells.push({ content: d.description || "", class: "descr" });
return rd;
}
_display_edit_dialog(fqdn) {
let dlg = new DomainEditDialog(fqdn === "*new" && { "new": true } || { fqdn: fqdn });
this._element.appendChild(dlg.element());
let that = this;
dlg.show().then(function(d) {
if (d) {
that.update();
}
}).finally(function() {
dlg.element().remove();
that._table.focus();
});
}
}
class DomainStatusCell extends ITableCell {
constructor(is_active, props) {
props = props || {};
let ca = (props.class || "").split(" ");
ca.push(is_active && "state-green" || "state-gray");
props.class = ca.filter(function(s) { return s.length > 0; }).join(" ");
super(is_active, props);
}
value(target) {
if (target === "dom") {
let div = document.createElement("div");
div.setAttribute("class", "state-background status-indicator");
if (!this._title) {
div.setAttribute("title", this._content && "active" || "inactive");
}
return div;
}
return this._content;
}
}
class DomainTimeCell extends ITableCell {
value(target) {
if (target === "dom") {
return this._content && this._content.toUIString() || "";
}
if (target === "sort") {
return this._content && this._content.valueOf() || "";
}
super.value(target);
}
}
class NewDomainRow extends ITableRow {
constructor(col_cnt) {
super({
userdata: "*new",
cells: []
});
this._col_cnt = col_cnt;
}
element() {
if (!this._element) {
super.element();
this._element.classList.add("colspanned", "virtual-item");
for (let i = 0; i < this._col_cnt; ++i) {
let cell = document.createElement("div");
cell.setAttribute("class", "table-cell");
cell.appendChild(document.createTextNode(!i && "New domain" || "\u00A0"));
this._element.appendChild(cell);
}
}
return this._element;
}
}
class DomainFrame extends ITableFrame {
sort(col_idx, direction) {
this._sort_dir = (direction === "ascent" && 1) || (direction === "descent" && 2) || 0;
super.sort(col_idx, direction);
}
_compare_cells(c1, c2) {
if (!c1) {
return this._sort_dir === 2;
}
if (!c2) {
return this._sort_dir === 1;
}
return super._compare_cells(c1, c2);
}
}
class DomainEditDialog extends ModalDialog {
constructor(params) {
let tl = null;
let ba = [ "save", "close" ];
if (!params["new"]) {
tl = "Domain settings";
ba.splice(1, 0, "delete");
}
else {
tl = "New domain";
}
super({ title: tl, buttons: ba });
this._data = params || {};
this._content = null;
this._inputs = null;
this._fqdn_el = null;
this._actv_el = null;
this._desc_el = null;
this._c_tm_el = null;
this._u_tm_el = null;
this._fetched = false;
}
_gen_content() {
this._inputs = document.createElement("div");
this._inputs.setAttribute("class", "titled-input");
this._content.appendChild(this._inputs);
this._content.classList.add("vertical-content");
let fq = document.createElement("input");
fq.setAttribute("type", "text");
if (!this._data["new"]) {
fq.setAttribute("value", this._data.fqdn);
fq.disabled = true;
}
fq.required = true;
this._insert_row("FQDN", fq);
this._fqdn_el = fq;
{
let en = document.createElement("select");
let op1 = document.createElement("option");
op1.setAttribute("value", "yes");
op1.appendChild(document.createTextNode("Yes"));
en.appendChild(op1);
let op2 = document.createElement("option");
op2.setAttribute("value", "no");
op2.appendChild(document.createTextNode("No"));
en.appendChild(op2);
en.required = true;
this._insert_row("Active", en);
this._actv_el = en;
}
let tx = document.createElement("textarea");
this._insert_row("Description", tx).classList.add("description");
this._desc_el = tx;
let ct = document.createElement("input");
ct.setAttribute("type", "text");
ct.disabled = true;
ct.setAttribute("value","n/a");
this._insert_row("Created", ct);
this._c_tm_el = ct;
let ut = document.createElement("input");
ut.setAttribute("type", "text");
ut.setAttribute("value","n/a");
ut.disabled = true;
this._insert_row("Updated", ut);
this._u_tm_el = ut;
this._inputs.addEventListener("input", function(event) {
if (this._fetched || this._data["new"]) {
this._buttons[1].disabled = (
this._actv_el.dataset.server === this._actv_el.value &&
this._desc_el.defaultValue === this._desc_el.value &&
this._fqdn_el.defaultValue === this._fqdn_el.value
);
}
}.bind(this));
if (!this._data["new"] && !this._fetched) {
this._fetch_data();
}
}
_insert_row(text, v_el) {
let l_el = document.createElement("label");
let t_el = document.createElement("span");
t_el.appendChild(document.createTextNode(text + ": "));
l_el.appendChild(t_el);
l_el.appendChild(v_el);
this._inputs.appendChild(l_el);
return v_el;
}
_fetch_data() {
this._enable_ui(false);
this._content.appendChild(set_wait_status());
let uparams = new URLSearchParams();
uparams.set("domain", this._data.fqdn);
let that = this;
window.fetch("domains.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the domain data");
return resp.json();
}).then(function(data) {
that._fetched = true;
Common.checkResult(data);
data.created_time = new Date(data.created_time);
data.updated_time = new Date(data.updated_time);
that._update_ui(data);
that._enable_ui(true);
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
}).finally(function() {
that._content.querySelector(".wait-message").remove();
});
}
_update_ui(data) {
let val = "";
for (let i = 0; i < this._actv_el.options.length; ++i) {
let op = this._actv_el.options[i];
let ee = op.value === "yes";
if ((data.active && ee) || (!data.active && !ee)) {
op.setAttribute("selected", "selected");
val = op.value;
}
else {
op.removeAttribute("selected");
}
}
this._actv_el.value = val;
this._actv_el.dataset.server = val;
this._desc_el.appendChild(document.createTextNode(data.description || ""));
this._c_tm_el.setAttribute("value", data.created_time && data.created_time.toUIString() || "n/a");
this._u_tm_el.setAttribute("value", data.updated_time && data.updated_time.toUIString() || "n/a");
}
_add_button(container, text, type) {
let btn = null;
if (type === "save") {
text = "Save";
btn = document.createElement("button");
btn.disabled = true;
btn.addEventListener("click", this._save.bind(this));
}
else if (type === "delete") {
text = "Delete";
btn = document.createElement("button");
btn.addEventListener("click", this._confirm_delete.bind(this));
}
else {
super._add_button(container, text, type);
return;
}
btn.setAttribute("type", "button");
btn.appendChild(document.createTextNode(text));
container.appendChild(btn);
this._buttons.push(btn);
}
_enable_ui(en) {
this._fqdn_el.disabled = !en || !this._data["new"];
this._actv_el.disabled = !en;
this._desc_el.disabled = !en;
for (let i = 2; i < this._buttons.length - 1; ++i) {
this._buttons[i].disabled = !en;
}
this._update_first_last();
if (this._first) {
this._first.focus();
}
}
_save() {
this._enable_ui(false);
let em = this._content.querySelector(".error-message");
if (em) {
em.remove();
}
this._content.appendChild(set_wait_status());
let body = {};
body.fqdn = this._data["new"] && this._fqdn_el.value || this._data.fqdn;
body.action = this._data["new"] && "add" || "update";
body.active = this._actv_el.value === "yes";
body.description = this._desc_el.value;
let that = this;
window.fetch("domains.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify(body)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to " + (body.new && "add" || "update") + " the domain data");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._result = body;
that.hide();
Notification.add({
text: "The domain " + body.fqdn + " was " + (body.action === "add" && "added" || "updated")
});
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
}).finally(function() {
that._content.querySelector(".wait-message").remove();
that._enable_ui(true);
});
}
_confirm_delete() {
if (confirm("Are sure you want to delete this domain?")) {
this._delete();
}
}
_delete() {
this._enable_ui(false);
let em = this._content.querySelector(".error-message");
if (em) {
em.remove();
}
this._content.appendChild(set_wait_status());
let body = {};
body.fqdn = this._data.fqdn;
body.action = "delete";
let that = this;
window.fetch("domains.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify(body)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to delete the domain");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._result = data;
that.hide();
Notification.add({ text: "The domain " + body.fqdn + " was removed" });
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
}).finally(function() {
that._content.querySelector(".wait-message").remove();
that._enable_ui(true);
});
}
}

View File

@ -0,0 +1,394 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Files {
constructor() {
this._container = null;
this._fieldset1 = null;
this._fieldset2 = null;
this._dir_table = null;
this._element = document.getElementById("main-block");
this._fcount_info = null;
this._fsize_info = null;
this._limits = {
upload_max_file_count: 0,
upload_max_file_size: 0
};
this._directories = [];
}
display() {
this._create_container();
this._create_local_file_uploading_element();
this._create_directory_loading_element();
this._container.appendChild(this._fieldset1);
this._container.appendChild(this._fieldset2);
this._element.appendChild(this._container);
this._fieldset1.focus();
}
update() {
if (!Status.instance().error()) {
this._fetch_data(true, true);
}
}
title() {
return "Report Files";
}
_create_container() {
this._container = document.createElement("div");
this._container.setAttribute("class", "panel-container round-border");
}
_create_local_file_uploading_element() {
this._fieldset1 = document.createElement("fieldset");
this._fieldset1.setAttribute("class", "round-border");
this._fieldset1.disabled = true;
let lg = document.createElement("legend");
lg.appendChild(document.createTextNode("Uploading local report files"));
this._fieldset1.appendChild(lg);
let fm = document.createElement("form");
fm.setAttribute("enctype", "multipart/form-data");
fm.setAttribute("method", "post");
fm.appendChild(this._create_input_element("hidden", "cmd", "upload-report"));
let fl = this._create_input_element("file", "report_file[]", null)
fl.required = true;
fl.multiple = true;
fm.appendChild(fl);
let dv = document.createElement("div");
dv.setAttribute("class", "buttons-block");
let sb = this._create_button_element("submit", "Upload reports");
sb.disabled = true;
dv.appendChild(sb);
dv.appendChild(this._create_button_element("reset", "Reset"));
fm.appendChild(dv);
let that = this;
fl.addEventListener("change", function(event) {
sb.disabled = !that._check_files(fl);
});
fm.addEventListener("reset", function(event) {
sb.disabled = true;
that._clear_warnings();
});
fm.addEventListener("submit", function(event) {
window.fetch("files.php", {
method: "POST",
credentials: "same-origin",
body: new FormData(fm)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to upload a report file");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
Notification.add({ text: (data.message || "Uploaded successfully!"), type: "info" });
}).catch(function(err) {
Common.displayError(err);
Notification.add({ text: (err.message || "Error!"), type: "error" });
});
event.preventDefault();
fm.reset();
});
this._fieldset1.appendChild(fm);
}
_create_directory_loading_element() {
this._fieldset2 = document.createElement("fieldset");
this._fieldset2.setAttribute("class", "round-border");
this._fieldset2.disabled = true;
let lg = document.createElement("legend");
lg.appendChild(document.createTextNode("Loading report files from the server directory"));
this._fieldset2.appendChild(lg);
let fm = document.createElement("form");
fm.setAttribute("method", "post");
this._dir_table = new ITable({
class: "main-table subtable",
onclick: function(row) {
let userdata = row.userdata();
let checkbox = row.element().querySelector("input");
if (checkbox && !userdata.error) {
userdata.checked = !userdata.checked;
checkbox.checked = userdata.checked;
this._update_directory_button();
}
}.bind(this),
nodata_text: "No directories are configured."
});
[
{ content: "", class: "cell-status" },
{ content: "Name" },
{ content: "Files" },
{ content: "Location" }
].forEach(function(col) {
this._dir_table.add_column(col);
}, this);
fm.appendChild(this._dir_table.element());
let bb = document.createElement("div");
bb.setAttribute("class", "buttons-block");
fm.appendChild(bb);
let sb = this._create_button_element("submit", "Load reports");
sb.disabled = true;
bb.appendChild(sb);
fm.addEventListener("submit", function(event) {
sb.disabled = true;
let ids = this._directories.filter(function(it) {
return it.checked;
}).map(function(it) {
return it.id;
});
let that = this;
window.fetch("files.php", {
method: "POST",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify({ cmd: "load-directory", ids: ids })
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to load report files");
return resp.json();
}).then(function(data) {
if (!data.error_code) {
Notification.add({ text: (data.message || "Loaded successfully!"), type: "info" });
}
if (data.other_errors) {
that._notify_other_errors(data.other_errors);
}
Common.checkResult(data);
}).catch(function(err) {
Common.displayError(err);
Notification.add({ text: (err.message || "Error!"), type: "error" });
}).finally(function() {
that._fetch_data(false, true);
});
event.preventDefault();
}.bind(this));
this._fieldset2.appendChild(fm);
}
_display_files_info() {
this._fcount_info = document.createElement("div");
this._fcount_info.setAttribute("class", "state-gray");
let dv = document.createElement("div");
dv.setAttribute("class", "state-text");
dv.appendChild(
document.createTextNode(
"You can upload not more than " + this._limits.upload_max_file_count + " files."
)
);
this._fcount_info.appendChild(dv);
this._fsize_info = document.createElement("div");
this._fsize_info.setAttribute("class", "state-gray");
dv = document.createElement("div");
dv.setAttribute("class", "state-text");
dv.appendChild(
document.createTextNode(
"You can upload a file with no more than " + bytes2size(this._limits.upload_max_file_size) + "."
)
);
this._fsize_info.appendChild(dv);
dv = document.createElement("div");
dv.setAttribute("class", "info-block");
dv.appendChild(this._fcount_info);
dv.appendChild(this._fsize_info);
this._fieldset1.appendChild(dv);
}
_update_directory_loading_element() {
this._dir_table.clear();
let d = {};
d.rows = this._directories.map(function(it) {
let files = it.files;
let chkbox = false;
it.checked = false;
let rd = { cells: [], userdata: it };
if (files < 0) {
chkbox = null;
files = "Error!";
rd.class = "state-red";
it.error = true;
}
rd.cells.push(new DirectoryCheckboxCell(chkbox));
rd.cells.push({ content: it.name });
rd.cells.push({ content: files, class: "state-text" });
rd.cells.push({ content: it.location });
return rd;
});
this._dir_table.add_frame(new ITableFrame(d, this._dir_table.last_row_index() + 1));
}
_update_directory_button() {
this._fieldset2.querySelector("button[type=submit]").disabled = !this._directories.some(function(it) {
return it.checked;
});
}
_clear_warnings() {
[ this._fcount_info, this._fsize_info ].forEach(function(el) {
if (el) {
el.classList.remove("state-red");
el.classList.add("state-gray");
}
});
}
_notify_other_errors(errors) {
let cut = null;
let length = errors.length;
if (length > 4) {
cut = errors.slice(0, 3);
cut.push("and " + (length - 3) + " more errors");
}
Notification.add({ text: cut || errors, type: "error" });
}
_set_warning(el) {
if (el) {
el.classList.remove("state-gray");
el.classList.add("state-red");
}
}
_check_files(fl_el) {
this._clear_warnings();
if (fl_el.files.length == 0) {
return false;
}
let res = true;
if (fl_el.files.length > this._limits.upload_max_file_count) {
res = false;
this._set_warning(this._fcount_info);
let message = "You can only upload " + this._limits.upload_max_file_count + " files.";
Notification.add({ type: "error", text: message, delay: 10000 });
}
let bf_cnt = 0;
for (let i = 0; i < fl_el.files.length; ++i) {
if (fl_el.files[i].size > this._limits.upload_max_file_size) {
++bf_cnt;
}
};
if (bf_cnt > 0) {
res = false;
this._set_warning(this._fsize_info);
Notification.add({
type: "error",
text: "" + bf_cnt + " file" + (bf_cnt > 1 && "s" || "") + " exceed the maximum allowed size.",
delay: 10000
});
}
return res;
}
_create_button_element(type, text) {
let el = document.createElement("button");
el.setAttribute("type", type);
el.appendChild(document.createTextNode(text));
return el;
}
_create_input_element(type, name, value) {
let el = document.createElement("input");
el.setAttribute("type", type);
if (name)
el.setAttribute("name", name);
if (value)
el.setAttribute("value", value);
return el;
}
_fetch_data(files, dirs) {
if (files) {
this._fieldset1.disabled = true;
this._fieldset1.insertBefore(set_wait_status(), this._fieldset1.children[0]);
}
if (dirs) {
this._fieldset2.disabled = true;
this._fieldset2.insertBefore(set_wait_status(), this._fieldset2.children[0]);
}
let that = this;
window.fetch("files.php", {
method: "GET",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to get loader data");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
if (files) {
that._limits.upload_max_file_count = data.upload_max_file_count;
that._limits.upload_max_file_size = data.upload_max_file_size;
that._display_files_info();
that._fieldset1.disabled = false;
}
if (dirs) {
that._directories = data.directories || [];
that._update_directory_loading_element();
that._fieldset2.disabled = false;
}
}).catch(function(err) {
Common.displayError(err);
Notification.add({ type: "error", text: err.message });
if (files) {
that._fieldset1.insertBefore(set_error_status(null, err.message), that._fieldset1.children[0]);
}
if (dirs) {
that._fieldset2.insertBefore(set_error_status(null, err.message), that._fieldset2.children[0]);
}
}).finally(function() {
if (files) {
that._fieldset1.querySelector(".wait-message").remove();
}
if (dirs) {
that._fieldset2.querySelector(".wait-message").remove();
}
});
}
}
class DirectoryCheckboxCell extends ITableCell {
value(target) {
if (target === "dom") {
let cb = document.createElement("input");
cb.setAttribute("type", "checkbox");
if (this._content !== null) {
cb.checked = this._content;
}
else {
cb.disabled = true;
cb.checked = false;
}
return cb;
}
return this._content;
}
}

View File

@ -0,0 +1,527 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ReportList {
constructor() {
this._table = null;
this._scroll = null;
this._filter = null;
this._sort = { column: "begin_time", direction: "descent" };
this._element = document.getElementById("main-block");
this._element2 = document.getElementById("detail-block");
this._fetching = false;
this._settings_btn = null;
this._settings_dlg = null;
}
display() {
this._gen_settings_button();
this._gen_content_container();
this._gen_table();
this._scroll.appendChild(this._table.element());
this._element.appendChild(this._scroll);
this._ensure_report_widget();
this._element2.appendChild(ReportWidget.instance().element());
this._ensure_settins_button();
ReportWidget.instance().hide();
this._table.focus();
}
update() {
this._handle_url_params();
this._update_table();
}
title() {
return "Report List";
}
onpopstate() {
if (!this._scroll) {
this.display();
this.update();
}
else {
if (!this._element.contains(this._scroll)) {
remove_all_children(this._element);
this._element.appendChild(this._scroll);
}
if (this._handle_url_params()) {
this._update_table();
}
}
this._ensure_settins_button();
this._ensure_report_widget();
if (this._table) {
this._table.focus();
}
}
_ensure_settins_button() {
let title_el = document.querySelector("h1");
if (!title_el.contains(this._settings_btn)) {
title_el.appendChild(this._settings_btn);
}
}
_ensure_report_widget() {
let wdg = ReportWidget.instance();
wdg.hide();
let el = wdg.element();
if (!this._element2.contains(el)) {
this._element2.appendChild(el);
}
}
/**
* Sets the _filter object from the document's location
* and updates the setting button if the filter changes
*
* @return bool True if the filter was changed, false otherwise
*/
_handle_url_params() {
let cnt = 0;
let filter = {};
(new URL(document.location.href)).searchParams.getAll("filter[]").forEach(function(it) {
let k = null;
let v = null;
let i = it.indexOf(":");
if (i != 0) {
if (i > 0) {
k = it.substr(0, i);
v = it.substr(i + 1);
}
else {
k = it;
v = "";
}
filter[k] = v;
++cnt;
}
});
let changed = !this._filter && cnt > 0;
if (this._filter) {
let cnt2 = 0;
changed = Object.keys(this._filter).some(function(k) {
++cnt2;
return cnt < cnt2 || this._filter[k] !== filter[k];
}, this) || cnt !== cnt2;
}
if (changed) {
this._filter = cnt && filter || null;
this._update_settings_button();
}
return changed;
}
_gen_settings_button() {
if (!this._settings_btn) {
let btn = document.createElement("span");
btn.setAttribute("class", "options-button");
btn.appendChild(document.createTextNode("\u{2699}"));
let that = this;
btn.addEventListener("click", function(event) {
that._display_settings_dialog();
event.preventDefault();
});
this._settings_btn = btn;
}
}
_update_settings_button() {
if (this._settings_btn) {
if (this._filter)
this._settings_btn.classList.add("active");
else {
this._settings_btn.classList.remove("active");
}
}
}
_gen_content_container() {
let that = this;
let el = document.createElement("div");
el.setAttribute("class", "main-table-container");
el.addEventListener("scroll", function() {
if (!that._fetching && el.scrollTop + el.clientHeight >= el.scrollHeight * 0.95) {
if (that._table.frames_count() === 0 || that._table.more()) {
that._fetch_list();
}
}
});
this._scroll = el;
}
_gen_table() {
this._table = new ReportTable({
class: "main-table report-list small-cards",
onclick: function(row) {
let data = row.userdata();
if (data)
this._display_report(data, row.id());
}.bind(this),
onsort: function(col) {
let dir = col.sorted() && "toggle" || "descent";
this._table.set_sorted(col.name(), dir);
this._sort.column = col.name();
this._sort.direction = col.sorted();
this.update();
}.bind(this),
onfocus: function(el) {
scroll_to_element(el, this._scroll);
}.bind(this)
});
[
{ content: "Domain" },
{ content: "Date", sortable: true, name: "begin_time" },
{ content: "Reporting Organization" },
{ content: "Report ID", class: "report-id" },
{ content: "Messages" },
{ content: "Result" }
].forEach(function(col) {
let c = this._table.add_column(col);
if (c.name() === this._sort.column) {
c.sort(this._sort.direction);
}
}, this);
}
_update_table() {
this._table.clear();
let that = this;
let frcnt = -1;
let again = function() {
if (frcnt < that._table.frames_count() && that._scroll.clientHeight * 1.5 >= that._scroll.scrollHeight) {
frcnt = that._table.frames_count();
that._fetch_list().then(function(frame) {
if (frame && frame.more())
again();
else
that._table.focus();
});
}
else
that._table.focus();
}
again();
}
_display_report(data, id) {
if (data.domain && data.report_id) {
let url = new URL("report.php", document.location.href);
url.searchParams.set("domain", data.domain);
url.searchParams.set("report_id", data.report_id);
window.history.pushState({ from: "list" }, "", url.toString());
let that = this;
ReportWidget.instance().show_report(data.domain, data.report_id).then(function() {
if (!that._table.seen(id)) {
that._table.seen(id, true);
}
}).catch(function(err) {
Common.displayError(err);
if (err.error_code && err.error_code === -2) {
LoginDialog.start({ nousername: true });
}
});
Router.update_title(ReportWidget.instance().title());
ReportWidget.instance().focus();
}
}
_fetch_list() {
this._table.display_status("wait");
this._fetching = true;
let pos = this._table.last_row_index() + 1;
let uparams = new URLSearchParams();
uparams.set("list", "reports");
uparams.set("position", pos);
uparams.set("order", this._sort.column);
uparams.set("direction", this._sort.direction);
if (this._filter) {
for (let nm in this._filter) {
uparams.append("filter[]", nm + ":" + this._filter[nm]);
}
}
let that = this;
return window.fetch("list.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the report list");
return resp.json();
}).then(function(data) {
that._table.display_status(null);
Common.checkResult(data);
let d = { more: data.more };
d.rows = data.reports.map(function(it) {
return new ReportTableRow(that._make_row_data(it));
});
let fr = new ITableFrame(d, pos);
that._table.add_frame(fr);
return fr;
}).catch(function(err) {
Common.displayError(err);
that._table.display_status("error");
}).finally(function() {
that._fetching = false;
});
}
_make_row_data(d) {
let rd = { cells: [], userdata: { domain: d.domain, report_id: d.report_id }, seen: d.seen && true || false }
rd.cells.push({ content: d.domain, label: "Domain" });
let d1 = new Date(d.date.begin);
let d2 = new Date(d.date.end);
rd.cells.push({ content: date_range_to_string(d1, d2), title: d1.toUIString(true) + " - " + d2.toUIString(true), label: "Date" });
rd.cells.push({ content: d.org_name, label: "Reporting Organization" });
rd.cells.push({ content: d.report_id, class: "report-id" });
rd.cells.push({ content: d.messages, label: "Messages" });
rd.cells.push(new StatusColumn({ dkim_align: d.dkim_align, spf_align: d.spf_align }));
return rd;
}
_display_settings_dialog() {
let dlg = this._settings_dlg;
if (!this._settings_dlg) {
dlg = new ReportListSettingsDialog({ filter: this._filter });
this._settings_dlg = dlg;
}
this._element.appendChild(dlg.element());
dlg.show().then(function(d) {
if (d) {
let url = new URL(document.location.href);
url.searchParams.delete("filter[]");
for (let k in d) {
if (d[k]) {
url.searchParams.append("filter[]", k + ":" + d[k]);
}
}
window.history.replaceState(null, "", url.toString());
if (this._handle_url_params()) {
this._update_table();
}
}
}.bind(this)).finally(function() {
this._table.focus();
}.bind(this));
}
}
class ReportTable extends ITable {
seen(row_id, flag) {
let row = super._get_row(row_id);
if (row) {
if (flag === undefined)
return row.seen();
row.seen(flag);
}
}
}
class ReportTableRow extends ITableRow {
constructor(data) {
super(data);
this._seen = data.seen && true || false;
}
element() {
if (!this._element) {
super.element();
this._update_seen_element();
}
return this._element;
}
seen(flag) {
if (flag === undefined)
return this._seen;
this._seen = flag && true || false;
if (this._element)
this._update_seen_element();
}
_update_seen_element() {
if (this._seen)
this._element.classList.remove("unseen");
else
this._element.classList.add("unseen");
}
}
class StatusColumn extends ITableCell {
element() {
if (!this._element) {
super.element().setAttribute("data-label", "Result");
}
return this._element;
}
value(target) {
if (target === "dom") {
let d = this._content;
let fr = document.createDocumentFragment();
if (d.dkim_align) {
fr.appendChild(create_report_result_element("DKIM", d.dkim_align));
}
if (d.spf_align) {
fr.appendChild(create_report_result_element("SPF", d.spf_align));
}
return fr;
}
return super.value(target);
}
}
class ReportListSettingsDialog extends ModalDialog {
constructor(params) {
super({ title: "List display settings", buttons: [ "apply", "reset" ] });
this._data = params || {};
this._content = null;
this._ui_data = [
{ name: "domain", title: "Domain" },
{ name: "month", title: "Month" },
{ name: "organization", title: "Organization" },
{ name: "dkim", title: "DKIM result" },
{ name: "spf", title: "SPF result" },
{ name: "status", title: "Status" }
];
}
show() {
this._update_ui();
return super.show();
}
_gen_content() {
let fs = document.createElement("fieldset");
fs.setAttribute("class", "round-border titled-input");
let lg = document.createElement("legend");
lg.appendChild(document.createTextNode("Filter by"));
fs.appendChild(lg);
this._ui_data.forEach(function(ud) {
let el = this._create_select_label(ud.title, fs);
ud.element = el;
}, this);
this._content.appendChild(fs);
this._content.classList.add("vertical-content");
if (!this._data.loaded_filters)
this._fetch_data();
}
_create_select_label(text, c_el) {
let lb = document.createElement("label");
let sp = document.createElement("span");
sp.appendChild(document.createTextNode(text + ": "));
lb.appendChild(sp);
let sl = document.createElement("select");
lb.appendChild(sl);
c_el.appendChild(lb);
return sl;
}
_enable_ui(enable) {
let list = this._element.querySelector("form").elements;
for (let i = 0; i < list.length; ++i)
list[i].disabled = !enable;
}
_update_ui() {
this._update_filters();
}
_update_filters() {
let data = this._data.loaded_filters || {};
let vals = this._data.filter || {};
this._ui_data.forEach(function(ud) {
this._update_select_element(ud.element, data[ud.name], vals[ud.name]);
}, this);
}
_update_select_element(sl, d, v) {
remove_all_children(sl);
let ao = document.createElement("option");
ao.setAttribute("value", "");
ao.setAttribute("selected", "selected");
ao.appendChild(document.createTextNode("Any"));
sl.appendChild(ao);
let v2 = "";
if (d) {
let op = null;
d.forEach(function(fs) {
op = document.createElement("option");
op.setAttribute("value", fs);
op.appendChild(document.createTextNode(fs));
if (fs === v) {
v2 = v;
}
sl.appendChild(op);
}, this);
}
sl.value = v2;
}
_submit() {
let res = {};
let fdata = {};
this._ui_data.forEach(function(ud) {
let el = ud.element;
let val = el.options[el.selectedIndex].value;
res[ud.name] = val;
fdata[ud.name] = val;
});
this._data.filter = fdata;
this._result = res;
this.hide();
}
_fetch_data() {
let that = this;
this._enable_ui(false);
this._content.appendChild(set_wait_status());
window.fetch("list.php?list=filters", {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the filter list");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._data.loaded_filters = data.filters;
that._update_ui();
that._enable_ui(true);
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status());
}).finally(function() {
that._content.querySelector(".wait-message").remove();
});
}
}

View File

@ -0,0 +1,141 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class LoginDialog extends ModalDialog {
constructor(params) {
super();
this._params = params || {};
this._params.buttons = [ "ok", "cancel" ];
this._params.title = "Authentication";
this._params.overlay_click = "ignore";
this._user = null;
this._pass = null;
this._msg_el = null;
}
remove() {
if (this._element) {
this._element.remove();
this._element = null;
}
}
_gen_content() {
let tdiv = document.createElement("div");
tdiv.setAttribute("class", "titled-input");
if (!this._params.nousername) {
this._user = this._insert_row(tdiv, "User name", "text", "Enter your user name");
}
this._pass = this._insert_row(tdiv, "Password", "password", "Enter your password");
this._msg_el = set_wait_status(null, "Enter your credentials");
this._content.setAttribute("class", "vertical-content");
this._content.appendChild(tdiv);
this._content.appendChild(this._msg_el);
}
_insert_row(c_el, text, type, placeholder) {
let l_el = document.createElement("label");
c_el.appendChild(l_el);
let t_el = document.createElement("span");
t_el.appendChild(document.createTextNode(text + ": "));
l_el.appendChild(t_el);
let inp = document.createElement("input");
inp.required = true;
inp.setAttribute("type", type);
if (placeholder) {
inp.setAttribute("placeholder", placeholder);
}
l_el.appendChild(inp);
return inp;
}
_enable_elements(enable) {
this._buttons[0].disabled = !enable;
let elements = this._element.querySelector("form").elements;
for (let i = 0; i < elements.length; ++i) {
elements[i].disabled = !enable;
}
}
_submit() {
this._buttons[1].focus();
this._enable_elements(false);
let body = {};
if (!this._params.nousername) {
body.username = this._user.value;
}
body.password = this._pass.value;
if (this._params.nofetch) {
this._result = body;
this.hide();
return;
}
let that = this;
let hide = false;
this._set_message("Sending credentials to the server...", false);
window.fetch("login.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify(body)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to log in");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._result = data;
Notification.add({ type: "info", text: data.message || "Successfully!" });
hide = true;
}).catch(function(err) {
that._pass.value = "";
Common.displayError(err);
that._set_message(err.message, true);
}).finally(function() {
that._enable_elements(true);
that._first.focus();
if (hide)
that.hide();
});
}
_set_message(text, error) {
let el = error && set_error_status(null, text) || set_wait_status(null, text);
this._msg_el.replaceWith(el);
this._msg_el = el;
}
}
LoginDialog.start = function (params) {
let login = new LoginDialog(params);
document.getElementById("main-block").appendChild(login.element());
login.show().then(function(d) {
if (d) {
Router.go();
}
}).catch(function(err) {
Common.displayError(err);
}).finally(function() {
login.remove();
login = null;
});
};

View File

@ -0,0 +1,304 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Logs {
constructor() {
this._table = null;
this._scroll = null;
this._element = document.getElementById("main-block");
this._fetching = false;
this._sort = { column: "", direction: "" };
}
display() {
this._make_scroll_container();
this._make_table();
this._scroll.appendChild(this._table.element());
this._element.appendChild(this._scroll);
this._table.focus();
}
update() {
this._table.clear();
let that = this;
let fr_cnt = -1;
let again = function() {
let fc = that._table.frames_count()
if (fr_cnt < fc && that._scroll.scrollHeight <= that._scroll.clientHeight * 1.5) {
fr_cnt = fc;
that._fetch_list().then(function(frame) {
if (frame && frame.more()) {
again();
}
else {
that._table.focus();
}
});
}
else {
that._table.focus();
}
};
again();
}
title() {
return "Logs";
}
_fetch_list() {
this._table.display_status("wait");
this._fetching = true;
let pos = this._table.last_row_index() + 1;
let uparams = new URLSearchParams();
uparams.set("position", pos);
if (this._sort.column && this._sort.direction) {
uparams.set("order", this._sort.column);
uparams.set("direction", this._sort.direction);
}
let that = this;
return window.fetch("logs.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the logs");
return resp.json();
}).then(function(data) {
that._table.display_status(null);
Common.checkResult(data);
if (data.sorted_by) {
let cname = data.sorted_by.column;
let dir = data.sorted_by.direction;
if (that._sort.column !== cname || that._sort.direction !== dir) {
that._sort.column = cname;
that._sort.direction = dir;
that._table.set_sorted(cname, dir);
}
}
let d = { more: data.more };
d.rows = data.items.map(function(it) {
return new ITableRow(that._make_row_data(it));
});
let fr = new ITableFrame(d, pos);
that._table.add_frame(fr);
return fr;
}).catch(function(err) {
Common.displayError(err);
that._table.display_status("error");
}).finally(function() {
that._fetching = false;
});
}
_make_scroll_container() {
let that = this;
let el = document.createElement("div");
el.setAttribute("class", "main-table-container");
el.addEventListener("scroll", function() {
if (!that._fetching && el.scrollTop + el.clientHeight >= el.scrollHeight * 0.95) {
if (that._table.frames_count() === 0 || that._table.more()) {
that._fetch_list();
}
}
});
this._scroll = el;
}
_make_table() {
this._table = new ITable({
class: "main-table small-cards",
onclick: function(row) {
let data = row.userdata();
if (data) {
this._display_item_dialog(data);
}
}.bind(this),
onsort: function(col) {
let dir = col.sorted() && "toggle" || "descent";
this._table.set_sorted(col.name(), dir);
this._sort.column = col.name();
this._sort.direction = col.sorted();
this.update();
}.bind(this),
onfocus: function(el) {
scroll_to_element(el, this._scroll);
}.bind(this)
});
[
{ content: "", class: "cell-status" },
{ content: "Domain", name: "domain" },
{ content: "Source" },
{ content: "Event time", sortable: true, name: "event_time" },
{ content: "Message" }
].forEach(function(col) {
let c = this._table.add_column(col);
if (c.name() === this._sort.column) {
c.sort(this._sort.direction);
}
}, this);
}
_make_row_data(d) {
let rd = { cells: [], userdata: { id: d.id } };
rd.cells.push(new LogsResultCell(d.success));
rd.cells.push({ content: d.domain, label: "Domain" });
rd.cells.push({ content: d.source, label: "Source" });
rd.cells.push({ content: (new Date(d.event_time)).toUIString(), label: "Event time" });
rd.cells.push({ content: d.message, label: "Message" });
return rd;
}
_display_item_dialog(data) {
let dlg = new LogItemDialog(data);
this._element.appendChild(dlg.element());
let that = this;
dlg.show().finally(function() {
dlg.element().remove();
that._table.focus();
});
}
}
class LogsResultCell extends ITableCell {
constructor(success, props) {
props = props || {};
let ca = (props.class || "").split(" ");
ca.push(success && "state-green" || "state-red");
props.class = ca.filter(function(s) { return s.length > 0; }).join(" ");
super(success, props);
}
element() {
if (!this._element) {
super.element().setAttribute("data-label", "Result");
}
return this._element;
}
value(target) {
if (target === "dom") {
let div = document.createElement("div");
div.setAttribute("class", "state-background status-indicator");
if (!this.title) {
div.setAttribute("title", this._content && "Ok" || "Failed");
}
return div;
}
return this._content;
}
}
class LogItemDialog extends ModalDialog {
constructor(data) {
super({ title: "Log record", buttons: [ "close" ] });
this._data = data;
this._table = null;
this._res_el = null;
this._dom_el = null;
this._time_el = null; // event_time
this._rid_el = null; // external_id
this._file_el = null; // filename
this._sou_el = null; // source
this._msg_el = null; // message
}
_gen_content() {
this._table = document.createElement("div");
this._table.setAttribute("class", "left-titled");
this._content.appendChild(this._table);
this._time_el = this._insert_row("Event time");
this._res_el = this._insert_row("Result");
this._res_el.setAttribute("class", "state-text");
this._dom_el = this._insert_row("Domain");
this._rid_el = this._insert_row("Report Id");
this._file_el = this._insert_row("File name");
this._sou_el = this._insert_row("Source");
this._msg_el = this._insert_row("Message");
this._fetch_data();
}
_insert_row(text) {
let t_el = document.createElement("span");
t_el.appendChild(document.createTextNode(text + ": "));
this._table.appendChild(t_el);
let v_el = document.createElement("span");
this._table.appendChild(v_el);
return v_el;
}
_fetch_data() {
this._content.appendChild(set_wait_status());
let uparams = new URLSearchParams();
uparams.set("id", this._data.id);
let that = this;
window.fetch("logs.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the log item");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._data.domain = data.domain;
that._data.report_id = data.report_id;
that._data.event_time = new Date(data.event_time);
that._data.filename = data.filename;
that._data.source = data.source;
that._data.success = data.success;
that._data.message = data.message;
that._update_ui();
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
}).finally(function() {
that._content.querySelector(".wait-message").remove();
});
}
_update_ui() {
this._time_el.textContent = this._data.event_time.toUIString();
if (this._data.success) {
this._res_el.textContent = "Ok";
this._res_el.parentElement.classList.add("state-green");
}
else {
this._res_el.textContent = "Failed";
this._res_el.parentElement.classList.add("state-red");
}
this._dom_el.textContent = this._data.domain || "n/a";
this._rid_el.textContent = this._data.report_id || "n/a";
this._file_el.textContent = this._data.filename || "n/a";
this._sou_el.textContent = this._data.source;
this._msg_el.textContent = this._data.message || "n/a";
}
}

View File

@ -0,0 +1,335 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Router {
}
Router.start = function() {
Router._initial_header = document.querySelector("h1").textContent;
document.getElementsByTagName("body")[0].addEventListener("keydown", function(event) {
if (event.code == "Escape" && !event.shiftKey && !event.ctrlKey && !event.altKey) {
let cbtn = document.querySelector(".close-btn.active");
if (cbtn) {
cbtn.click();
event.preventDefault();
}
document.querySelectorAll("div.popup-menu:not(.hidden)").forEach(function(m) {
m.classList.add("hidden");
});
}
});
window.addEventListener("click", function(event) {
if (!event.target.closest("div.popup-menu")) {
document.querySelectorAll("div.popup-menu:not(.hidden)").forEach(function(m) {
m.classList.add("hidden");
});
}
let mm_toggle = document.getElementById("main-menu-toggle");
if (mm_toggle.checked) {
if (event.target.tagName == "A" || !event.target.closest("#main-menu-button")) {
mm_toggle.checked = false;
}
}
});
document.getElementById("main-menu-button").addEventListener("click", function(event) {
let el = event.target;
if (el.tagName === "A") {
let href = el.getAttribute("href");
if (href !== "") {
event.preventDefault();
window.history.pushState(null, "", href);
Router.go();
}
}
});
window.addEventListener("popstate", function(event) {
let m = Router._url2module();
if (m) {
let p = m.pointer;
if (p && p.onpopstate) {
if (p.title) {
Router.update_title(p.title());
}
p.onpopstate(event.state);
} else {
Router.go();
}
}
});
document.getElementById("main-menu").addEventListener("click", function(event) {
let el = event.target.closest("ul>li");
if (el) {
el.classList.toggle("closed");
}
});
document.querySelector(".menu-box .about a").addEventListener("click", function(event) {
event.preventDefault();
setTimeout(function() {
let dlg = new AboutDialog({
authors: [
{ name: "Aleksey Andreev", url: "https://github.com/liuch", years: "2021-2022" }
],
documentation: [
{ ancor: "README on GitHub", url: "https://github.com/liuch/dmarc-srg/blob/master/README.md" }
],
source_code: [
{ ancor: "DmarcSrg on GitHub", url: "https://github.com/liuch/dmarc-srg" }
]
});
document.getElementById("main-block").appendChild(dlg.element());
dlg.show().finally(function() {
dlg.element().remove();
});
}, 0);
});
Router.go();
};
Router.go = function(url) {
Status.instance().update({ settings: [ "ui.datetime.offset", "ui.ipv4.url", "ui.ipv6.url" ] }).then(function(d) {
if (d) {
Router._update_menu(d.authenticated);
if (d.settings) {
if (d.settings["ui.datetime.offset"]) {
Common.tuneDateTimeOutput(d.settings["ui.datetime.offset"]);
}
Common.ipv4_url = d.settings["ui.ipv4.url"] || '';
Common.ipv6_url = d.settings["ui.ipv6.url"] || '';
}
if (d.error_code !== -2) {
try {
Common.checkResult(d);
} catch (err) {
Common.displayError(err);
}
let module = Router._url2module(url);
if (module) {
if (!module.pointer)
module.start(module);
let p = module.pointer;
if (p.oncleardata)
p.oncleardata();
else
Router._clear_data();
if (p.title)
Router.update_title(p.title());
if (p.display)
p.display();
if (p.update)
p.update();
}
}
if (d.state && d.state !== "Ok" && !d.error_code && d.message) {
Notification.add({ type: "warn", text: d.message, delay: 20000 });
}
if (d.version !== Router._app_ver) {
Router._app_ver = d.version;
Router.update_title();
}
if (d.php_version) {
Router.php_version = d.php_version;
}
}
});
};
Router.app_name = function(version) {
let name = "DmarcSrg";
if (version && Router._app_ver) {
name += " " + Router._app_ver;
}
return name;
}
Router.update_title = function(str) {
let title1 = Router.app_name(false);
let title2 = str || Router._title || null;
if (str) {
Router._title = str;
}
document.title = title1 + (title2 && (": " + title2) || "");
let h1 = document.querySelector("h1");
if (str === "") {
h1.textContent = Router._initial_header || "";
} else if (str) {
h1.textContent = title2 || "";
}
};
Router._update_menu = function(authenticated) {
let m_el = document.getElementById("main-menu");
let l_el = m_el.querySelector("#auth-action");
if (l_el) {
l_el.remove();
}
{
let subs = m_el.querySelectorAll(".submenu .selected")
for (let i = 0; i < subs.length; ++i) {
subs[i].classList.remove("selected");
}
let href = document.location.origin + document.location.pathname;
let f1 = false;
for (let i = 0; i < m_el.children.length; ++i) {
let smenu = m_el.children[i];
if (smenu !== l_el) {
let f2 = false;
if (!f1) {
let a_ls = smenu.querySelectorAll("ul>li>a");
for (let k = 0; k < a_ls.length; ++k) {
let a = a_ls[k];
if (a.href === href) {
f1 = true;
f2 = true;
a.parentElement.classList.add("selected")
break;
}
}
}
if (f2) {
smenu.classList.remove("closed");
}
else {
smenu.classList.add("closed");
}
}
}
}
if (authenticated !== "disabled") {
l_el = document.createElement("li");
l_el.setAttribute("id", "auth-action");
let a_el = document.createElement("a");
a_el.setAttribute("href", "");
if (authenticated == "yes") {
a_el.appendChild(document.createTextNode("Log out"));
a_el.addEventListener("click", function(event) {
event.preventDefault();
if (!this.classList.contains("disabled")) {
let m_el = this;
m_el.classList.add("disabled");
window.fetch("logout.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify({})
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to log out");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
Status.instance().reset();
Router._clear_data();
Router._update_menu("no");
Router.update_title("");
}).catch(function(err) {
Common.displayError(err);
m_el.classList.remove("disabled");
Notification.add({ type: "error", text: err.message });
});
}
});
}
else if (authenticated == "no") {
a_el.appendChild(document.createTextNode("Log in"));
a_el.addEventListener("click", function(event) {
event.preventDefault();
LoginDialog.start({ nousername: true });
});
}
l_el.appendChild(a_el);
m_el.appendChild(l_el);
}
};
Router._clear_data = function() {
remove_all_children(document.getElementById("main-block"));
remove_all_children(document.getElementById("detail-block"));
};
Router._modules = {
list: {
start: function(m) {
m.pointer = new ReportList();
}
},
report: {
start: function(m) {
m.pointer = ReportWidget.instance();
}
},
admin: {
start: function(m) {
m.pointer = new Admin();
}
},
files: {
start: function(m) {
m.pointer = new Files();
}
},
domains: {
start: function(m) {
m.pointer = new DomainList();
}
},
logs: {
start: function(m) {
m.pointer = new Logs();
}
},
summary: {
start: function(m) {
m.pointer = new Summary();
}
},
settings: {
start: function(m) {
m.pointer = new Settings();
}
}
};
Router._url2module = function(url) {
let rr = /([^\/]*)$/.exec(url || document.location.pathname);
return rr && Router._modules[Router._routes[rr[1]]] || null;
};
Router._routes = {
"": "list",
"list.php": "list",
"logs.php": "logs",
"admin.php": "admin",
"files.php": "files",
"report.php": "report",
"domains.php": "domains",
"summary.php": "summary",
"settings.php": "settings"
};
window.onload = Router.start;

View File

@ -0,0 +1,86 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Notification {
constructor(params) {
this._params = params;
this._element = this._create_element();
}
element() {
return this._element;
}
_create_element() {
let el = document.createElement("div");
el.setAttribute("class", "notification");
if (this._params.type === "error")
el.classList.add("notif-error");
else if (this._params.type === "warn")
el.classList.add("notif-warn");
else
el.classList.add("notif-info");
{
let text = this._params.text;
if (typeof(text) !== "object")
text = [ text ];
for (let i = 0; ; ) {
el.appendChild(document.createTextNode(text[i]));
++i;
if (i == text.length)
break;
el.appendChild(document.createElement("br"));
}
}
let btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.setAttribute("class", "notif-close");
btn.appendChild(document.createTextNode("x"));
el.appendChild(btn);
el.addEventListener("click", function(event) {
if (event.target.classList.contains("notif-close"))
this.remove();
});
if (this._params.delay > 0) {
setTimeout(function() {
el.style.transition = "opacity 2s ease-in-out";
el.style.opacity = 0;
setTimeout(function() { el.remove(); }, 2000);
}, this._params.delay);
}
return el;
}
}
Notification.add = function(params) {
for (let key in Notification.defaults) {
if (params[key] === undefined)
params[key] = Notification.defaults[key];
}
let notif = new Notification(params);
document.getElementById("notifications-block").appendChild(notif.element());
return notif;
}
Notification.defaults = {
type: "info",
delay: 5000
};

View File

@ -0,0 +1,427 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ReportWidget {
constructor() {
this._rep_id = null;
this._element = null;
this._close_btn = null;
this._id_element = null;
this._cn_element = null;
this._onclose_act = null;
}
display() {
if (!this._element || !document.contains(this._element)) {
let cn = document.getElementById("main-block");
cn.appendChild(this.element());
}
}
update() {
this.show_report().catch(function(err) {
Common.displayError(err);
});
}
onpopstate() {
this.display();
this.update();
}
oncleardata() {
if (!this._element || !document.contains(this._element)) {
remove_all_children(document.getElementById("main-block"));
remove_all_children(document.getElementById("detail-block"));
}
}
show_report(domain, report_id) {
this.element();
let that = this;
return new Promise(function(resolve, reject) {
if (!domain || !report_id) {
let sp = (new URL(document.location.href)).searchParams;
domain = sp.get("domain");
report_id = sp.get("report_id");
if (!domain || !report_id) {
set_error_status(this._cn_element, err.message);
reject(new Error("Domain and report_id must be specified"));
}
}
that._id_element.childNodes[0].nodeValue = report_id;
set_wait_status(that._cn_element);
that._rep_id = report_id;
that._element.classList.remove("report-hidden");
that._close_btn.classList.add("active");
let rep = new Report(domain, report_id);
rep.fetch().then(function() {
if (that._rep_id === report_id) {
remove_all_children(that._cn_element);
that._cn_element.appendChild(rep.element());
rep.set_value("seen", true).then(function(data) {
Common.checkResult(data);
}).catch(function(err) {
Common.displayError(err);
});
}
resolve();
}).catch(function(err) {
let err_str = rep.error_message() || "Failed to get the report data";
set_error_status(that._cn_element, err_str);
reject(err);
});
});
}
element() {
if (!this._element) {
this._gen_element();
}
return this._element;
}
title() {
return "Report Detail";
}
focus() {
let el = this._element;
if (el)
el.focus();
}
hide() {
if (this._element && !this._element.classList.contains("report-hidden")) {
this._element.classList.add("report-hidden");
this._close_btn.classList.remove("active");
return true;
}
return false;
}
close() {
if (this.hide() && this._onclose_act)
this._onclose_act();
}
onclose(fn) {
this._onclose_act = typeof(fn) == "function" && fn || null;
}
_gen_element() {
let el = document.createElement("div");
el.setAttribute("class", "report-modal report-hidden");
el.setAttribute("tabindex", -1);
el.addEventListener("click", function(event) {
if (event.target.classList.contains("close-btn") || event.target.classList.contains("report-header")) {
if (window.history.state && window.history.state.from === "list")
this.close();
else
window.history.go(-1);
}
}.bind(this));
let hd = document.createElement("div");
hd.setAttribute("class", "report-header");
{
let ht = document.createElement("span");
ht.setAttribute("class", "header-text");
ht.appendChild(document.createTextNode("DMARC Report (Id: "));
let id = document.createElement("span");
id.setAttribute("id", "report-modal-id");
id.appendChild(document.createTextNode("?"));
this._id_element = id;
ht.appendChild(id);
ht.appendChild(document.createTextNode(")"));
hd.appendChild(ht);
}
el.appendChild(hd);
let bd = document.createElement("div");
bd.setAttribute("class", "body");
let cn = document.createElement("div");
cn.setAttribute("class", "content");
this._cn_element = cn;
bd.appendChild(cn);
let cb = document.createElement("button");
cb.setAttribute("class", "btn close-btn");
cb.appendChild(document.createTextNode("Close"));
this._close_btn = cb;
bd.appendChild(cb);
el.appendChild(bd);
this._element = el;
}
}
ReportWidget.instance = function() {
if (!ReportWidget._instance) {
ReportWidget._instance = new ReportWidget();
ReportWidget._instance.onclose(function() {
window.history.go(-1);
});
}
return ReportWidget._instance;
}
class Report {
constructor(domain, report_id) {
this._data = null;
this._error = false;
this._error_message = null;
this._domain = domain;
this._report_id = report_id;
}
id() {
return this._report_id;
}
error() {
return this._error;
}
error_message() {
return this._error_message;
}
fetch() {
let u_params = new URLSearchParams();
u_params.set("domain", this._domain);
u_params.set("report_id", this._report_id);
let that = this;
return window.fetch("report.php?" + u_params.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch report data");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._data = data.report;
that._error = false;
that._error_message = null;
}).catch(function(err) {
that._data = null;
that._error = true;
that._error_message = err.message;
throw err;
});
}
element() {
return this._create_element();
}
set_value(name, value) {
let definitions = {
"seen": "boolean"
};
if (value === undefined || definitions[name] !== typeof(value)) {
console.warn("Set report value: Incorrect value");
return Promise.resolve({});
}
let url_params = new URLSearchParams();
url_params.set("action", "set");
url_params.set("domain", this._domain);
url_params.set("report_id", this._report_id);
return window.fetch("report.php?" + url_params.toString(), {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify({ name: name, value: value })
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to set report value");
return resp.json();
}).catch(function(err) {
Common.displayError(err);
});
}
_create_element() {
let el = document.createDocumentFragment();
let md = document.createElement("div");
md.setAttribute("class", "report-metadata");
md.appendChild(this._create_data_item("Report Id", this._data.report_id));
md.appendChild(this._create_data_item("Reporting organization", this._data.org_name));
md.appendChild(this._create_data_item("Domain", this._data.domain));
let d1 = new Date(this._data.date.begin);
let d2 = new Date(this._data.date.end);
md.appendChild(this._create_data_item("Date range", d1.toUIString(true) + " - " + d2.toUIString(true)));
md.appendChild(this._create_data_item("Email", this._data.email));
if (this._data.extra_contact_info)
md.appendChild(this._create_data_item("Extra contact info", this._data.extra_contact_info));
md.appendChild(this._create_data_item("Published policy", this._create_pub_policy_fragment(this._data.policy)));
if (this._data.error_string)
md.appendChild(this._create_data_item("Error string", "???"));
md.appendChild(this._create_data_item("Loaded time", (new Date(this._data.loaded_time)).toUIString()));
el.appendChild(md);
// Records
let rs = document.createElement("div");
rs.setAttribute("class", "report-records");
let hd = document.createElement("h5");
hd.appendChild(document.createTextNode("Records"));
rs.appendChild(hd);
this._data.records.forEach(function(rec) {
let tl = document.createElement("div");
tl.setAttribute("class", "report-record round-border");
let hd = document.createElement("div");
hd.setAttribute("class", "header");
hd.appendChild(this._create_data_fragment("IP-address", Common.makeIpElement(rec.ip)));
tl.appendChild(hd);
tl.appendChild(this._create_data_item("Message count", rec.count));
tl.appendChild(this._create_data_item("Policy evaluated", this._create_ev_policy_fragment(rec)));
if (rec.reason)
tl.appendChild(this._create_data_item("Evaluated reason", this._create_reason_fragment(rec.reason)));
tl.appendChild(this._create_data_item("Identifiers", this._create_identifiers_fragment(rec)));
tl.appendChild(this._create_data_item("DKIM auth", this._create_dkim_auth_fragment(rec.dkim_auth)));
tl.appendChild(this._create_data_item("SPF auth", this._create_spf_auth_fragment(rec.spf_auth)));
rs.appendChild(tl);
}, this);
el.appendChild(rs);
return el;
}
_get_row_container(ctn, data) {
if (data.length < 2)
return ctn;
let div = document.createElement("div")
ctn.appendChild(div);
return div;
}
_create_data_item(title, data) {
let el = document.createElement("div");
el.setAttribute("class", "report-item");
el.appendChild(this._create_data_fragment(title, data));
return el;
}
_create_data_fragment(title, data) {
let fr = document.createDocumentFragment();
let tl = document.createElement("span");
tl.appendChild(document.createTextNode(title + ": "));
tl.setAttribute("class", "title");
fr.appendChild(tl);
if (typeof(data) !== "object")
data = document.createTextNode(data);
let dt = document.createElement(data.childNodes.length > 1 ? "div" : "span");
dt.setAttribute("class", "value");
dt.appendChild(data);
if (Array.from(dt.children).find(function(ch) {
return ch.tagName === "DIV";
})) dt.classList.add("rows");
fr.appendChild(dt);
return fr;
}
_create_ev_policy_fragment(data) {
let fr = document.createDocumentFragment();
if (data.dkim_align)
fr.appendChild(create_report_result_element("DKIM", data.dkim_align, true));
if (data.spf_align)
fr.appendChild(create_report_result_element("SPF", data.spf_align, true));
if (data.disposition)
fr.appendChild(create_report_result_element("disposition", data.disposition, true, ""));
return fr;
}
_create_reason_fragment(data) {
let fr = document.createDocumentFragment();
data.forEach(function(rec) {
let ctn = this._get_row_container(fr, data);
if (rec.type)
ctn.appendChild(create_report_result_element("type", rec.type, true, ""));
if (rec.comment)
ctn.appendChild(create_report_result_element("comment", rec.comment, true, ""));
}.bind(this));
return fr;
}
_create_identifiers_fragment(data) {
let fr = document.createDocumentFragment();
if (data.header_from)
fr.appendChild(create_report_result_element("header_from", data.header_from, true, ""));
if (data.envelope_from)
fr.appendChild(create_report_result_element("envelope_from", data.envelope_from, true, ""));
if (data.envelope_to)
fr.appendChild(create_report_result_element("envelope_to", data.envelope_to, true, ""));
return fr;
}
_create_dkim_auth_fragment(data) {
if (!data)
return "n/a";
let fr = document.createDocumentFragment();
data.forEach(function(rec) {
let ctn = this._get_row_container(fr, data);
if (rec.domain)
ctn.appendChild(create_report_result_element("domain", rec.domain, true, ""));
if (rec.selector)
ctn.appendChild(create_report_result_element("selector", rec.selector, true, ""));
if (rec.result)
ctn.appendChild(create_report_result_element("result", rec.result, true));
}.bind(this));
return fr;
}
_create_spf_auth_fragment(data) {
if (!data)
return "n/a";
let fr = document.createDocumentFragment();
data.forEach(function(rec) {
let ctn = this._get_row_container(fr, data);
if (rec.domain)
ctn.appendChild(create_report_result_element("domain", rec.domain, true, ""));
if (rec.result)
ctn.appendChild(create_report_result_element("result", rec.result, true));
}.bind(this));
return fr;
}
_create_pub_policy_fragment(data) {
if (!data)
return "n/a";
let fr = document.createDocumentFragment();
[
[ "adkim", data.adkim ], [ "aspf", data.aspf ], [ "p", data.p ], [ "sp", data.sp ],
[ "np", data.np ], [ "pct", data.pct ], [ "fo", data.fo ]
].forEach(function(pol) {
if (pol[1]) fr.appendChild(create_report_result_element(pol[0], pol[1], true, ""));
});
return fr;
}
}

View File

@ -0,0 +1,355 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Settings {
constructor() {
this._table = null;
this._scrool = null;
this._sort = "ascent";
this._element = document.getElementById("main-block");
}
display() {
this._make_scroll_container();
this._make_table();
this._scroll.appendChild(this._table.element());
this._element.appendChild(this._scroll);
this._table.focus();
}
update() {
this._fetch_settings();
}
title() {
return "Advanced Settings";
}
_fetch_settings() {
this._table.display_status("wait");
let that = this;
let uparams = new URLSearchParams();
uparams.set("direction", this._sort);
return window.fetch("settings.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the settings");
return resp.json();
}).then(function(data) {
that._table.display_status(null);
Common.checkResult(data);
let d = { more: data.more };
d.rows = data.settings.map(function(it) {
return that._make_row_data(it);
});
that._table.clear();
let fr = new ITableFrame(d, 0);
that._table.add_frame(fr);
that._table.focus();
}).catch(function(err) {
Common.displayError(err);
that._table.display_status("error", err.message);
});
}
_make_scroll_container() {
this._scroll = document.createElement("div");
this._scroll.setAttribute("class", "main-table-container");
}
_make_table() {
this._table = new ITable({
class: "main-table small-cards",
onclick: function(row) {
let data = row.userdata();
if (data) {
this._display_edit_dialog(data);
}
}.bind(this),
onsort: function(col) {
let dir = col.sorted() && "toggle" || "ascent";
this._table.set_sorted(col.name(), dir);
this._sort = col.sorted();
this.update();
}.bind(this),
onfocus: function(el) {
scroll_to_element(el, this._scroll);
}.bind(this)
});
[
{ content: "Name", name: "name", sortable: true },
{ content: "Value", name: "value" },
{ content: "Description", name: "descr" }
].forEach(function(col) {
let c = this._table.add_column(col);
if (c.name() === "name") {
c.sort(this._sort);
}
}, this);
}
_make_row_data(d) {
let rd = { cells: [], userdata: d.name };
rd.cells.push({ content: d.name, class: "setting-name", label: "Name " });
rd.cells.push({ content: d.value, class: "setting-value", label: "Value " });
rd.cells.push({ content: Settings._descriptions_short[d.name] || Settings._descriptions[d.name] || "No description", label: "Description " });
if (d.value !== d.default) {
rd.class = "custom-value";
}
return rd;
}
_display_edit_dialog(name) {
let dlg = new SettingEditDialog({
name: name,
description: Settings._descriptions[name]
});
this._element.appendChild(dlg.element());
let that = this;
dlg.show().then(function(d) {
if (d) {
that.update();
}
}).finally(function() {
dlg.element().remove();
that._table.focus();
});
}
static _descriptions = {
"status.emails-for-last-n-days": "The period in days for which statistics are displayed in the status block.",
"report-view.sort-records-by": "How records are sorted in the report view dialog.",
"log-view.sort-list-by": "How report log items are sorted by default in the log view dialog.",
"ui.datetime.offset": "Time zone offset of displayed dates in UI. Auto means that the report range is in UTC and all other dates are in local.",
"ui.ipv4.url": "The URL that will be used as a link when clicking on the IPv4 address. For example: https://somewhoisservice.net/ip/{$ip}, where {$ip} is IP address from the UI. Use {$eip} if you want to insert url encoded IP address. Use an empty string to disable.",
"ui.ipv6.url": "The URL that will be used as a link when clicking on the IPv6 address. For example: https://somewhoisservice.net/ip/{$ip}, where {$ip} is IP address from the UI. Use {$eip} if you want to insert url encoded IP address. Use an empty string to disable."
};
static _descriptions_short = {
"ui.datetime.offset": "Time zone offset of displayed dates in UI.",
"ui.ipv4.url": "The URL that will be used as a link when clicking on the IPv4 address.",
"ui.ipv6.url": "The URL that will be used as a link when clicking on the IPv6 address."
};
}
class SettingEditDialog extends ModalDialog {
constructor(param) {
super({ title: "Setting dialog", buttons: [ "ok", "close" ] });
this._data = param || {};
this._content = null;
this._table = null;
this._val_el = null;
this._val_tp = null;
this._desc_el = null;
this._save_bt = null;
this._fetched = false;
}
_gen_content() {
this._table = document.createElement("div");
this._table.setAttribute("class", "titled-input");
this._content.appendChild(this._table);
this._content.classList.add("vertical-content");
let nm = document.createElement("input");
nm.setAttribute("type", "text");
nm.setAttribute("disabled", "disabled");
nm.setAttribute("value", this._data.name);
this._insert_row("Name", nm);
let val = document.createElement("input");
val.setAttribute("type", "text");
val.disabled = true;
this._insert_row("Value", val);
this._val_el = val;
this._val_tp = "string";
let desc = document.createElement("textarea");
desc.setAttribute("disabled", "disabled");
if (this._data.description) {
desc.appendChild(document.createTextNode(this._data.description));
}
desc.classList.add("description");
this._insert_row("Description", desc);
this._desc_el = desc;
this._save_bt = this._buttons[1];
this._save_bt.disabled = true;
this._table.addEventListener("input", function(event) {
if (this._fetched && event.target == this._val_el) {
let e_val = null;
switch (this._val_tp) {
case "select":
e_val = this._val_el.value;
break;
case "integer":
e_val = this._val_el.valueAsNumber;
break;
}
this._save_bt.disabled = (e_val === this._data.value);
}
}.bind(this));
this._fetch_data();
}
_add_button(container, text, type) {
if (type == "submit") {
text = "Save";
}
super._add_button(container, text, type);
}
_insert_row(text, val_el) {
let lb = document.createElement("label");
let sp = document.createElement("span");
sp.appendChild(document.createTextNode(text + ": "));
lb.appendChild(sp);
lb.appendChild(val_el);
this._table.appendChild(lb);
}
_fetch_data() {
this._enable_ui(false);
this._content.appendChild(set_wait_status());
let uparams = new URLSearchParams();
uparams.set("name", this._data.name);
let that = this;
window.fetch("settings.php?" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch setting data for " + that._data.name);
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._data.value = data.value;
that._update_ui(data);
that._enable_ui(true);
that._fetched = true;
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
}).finally(function() {
that._content.querySelector(".wait-message").remove();
});
}
_enable_ui(en) {
this._val_el.disabled = !en;
this._update_first_last();
if (this._first) {
this._first.focus();
}
}
_update_ui(data) {
if (data.type !== this._val_tp) {
let new_el = null;
if (data.type == "integer") {
new_el = document.createElement("input");
new_el.setAttribute("type", "number");
if (typeof(data.minimum) == "number") {
new_el.setAttribute("min", data.minimum);
}
if (typeof(data.maximum) == "number") {
new_el.setAttribute("max", data.maximum);
}
} else if (data.type == "select") {
new_el = document.createElement("select");
data.options.forEach(function(op) {
let opt_el = document.createElement("option");
opt_el.setAttribute("value", op);
opt_el.appendChild(document.createTextNode(op));
if (op === data.value) {
opt_el.setAttribute("selected", "selected");
}
new_el.appendChild(opt_el);
});
}
if (new_el) {
new_el.setAttribute("required", "required");
this._val_el.replaceWith(new_el);
this._val_el = new_el;
}
this._val_tp = data.type;
}
this._val_el.value = data.value;
}
_submit() {
this._save_bt.disabled = true;
this._enable_ui(false);
let em = this._content.querySelector(".error-message");
if (em) {
em.remove();
}
this._content.appendChild(set_wait_status());
let body = {};
body.name = this._data.name;
if (this._val_tp == "integer") {
body.value = this._val_el.valueAsNumber;
}
else {
body.value = this._val_el.value;
}
body.action = "update";
let that = this;
window.fetch("settings.php", {
method: "POST",
cache: "no-store",
headers: Object.assign(HTTP_HEADERS, HTTP_HEADERS_POST),
credentials: "same-origin",
body: JSON.stringify(body)
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to update the setting");
return resp.json();
}).then(function(data) {
Common.checkResult(data);
that._data.value = that._val_el.value;
that._result = body;
that.hide();
Notification.add({ type: "info", text: (data.message || "Updated successfully!") });
}).catch(function(err) {
Common.displayError(err);
that._content.appendChild(set_error_status(null, err.message));
Notification.add({ type: "error", text: err.message });
}).finally(function() {
that._content.querySelector(".wait-message").remove();
that._save_bt.disabled = false;
that._enable_ui(true);
});
}
}

View File

@ -0,0 +1,206 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Status {
constructor() {
this._data = {};
}
update(params) {
return this._fetch(params || {}).then(function(data) {
return data;
}).catch(function(err) {
Common.displayError(err);
});
}
reset() {
this._data.emails = null;
this._data.error_code = 0;
this._update_block();
}
error() {
return this._data.error_code && this._data.error_code !== 0 || false;
}
_fetch(params) {
let p_string = '';
if (params.settings && params.settings.length) {
let uparams = new URLSearchParams();
uparams.set("settings", params.settings.join(','));
p_string = '?' + uparams.toString();
}
let that = this;
return new Promise(function(resolve, reject) {
window.fetch("status.php" + p_string, {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok)
throw new Error("Failed to fetch the status");
return resp.json();
}).then(function(data) {
that._data = {
state: data.state,
error_code: data.error_code,
message: data.message,
emails: data.emails
};
if (data.exeption)
that._data.exeption = data.exeption;
that._update_block();
if (data.error_code === -2) {
LoginDialog.start({ nousername: true });
}
resolve(data);
}).catch(function(err) {
that._data = {
state: "Err",
error_code: -100,
message: err.message
};
that._update_block();
reject(err);
});
});
}
_update_block() {
this._ensure_element_created();
if (this._data.error_code) {
Notification.add({ text: "[" + this._data.error_code + "] " + this._data.message, type: "error" });
}
if (!this._data.emails) {
this._data.emails = {
days: 0,
total: -1,
spf_aligned: 0,
dkim_aligned: 0,
dkim_spf_aligned: 0
};
}
let days = this._data.emails.days;
let total = this._data.emails.total;
let passed = this._data.emails.dkim_spf_aligned;
let forwarded = this._data.emails.dkim_aligned + this._data.emails.spf_aligned;
let failed = total - passed - forwarded;
this._set_element_data(
"processed",
(total === -1 || total === undefined) && "?" || total,
total !== -1 && "state-blue" || null
);
this._set_element_data(
"passed",
this._formatted_statistic(passed, total),
total !== -1 && "state-green" || null
);
this._set_element_data(
"forwarded",
this._formatted_statistic(forwarded, total),
total !== -1 && "state-green" || null
);
this._set_element_data(
"failed",
this._formatted_statistic(failed, total),
total !== -1 && "state-red" || null
);
{
let el = document.getElementById("stat-block");
if (days > 0) {
el.setAttribute("title", "Statistics for the last " + days + " days");
}
else {
el.removeAttribute("title");
}
}
}
_formatted_statistic(val, total) {
if (total === -1)
return "?";
if (!total)
return "-";
if (val === 0)
return "0";
let rval = Math.round(val / total * 100);
return (val > 0 && rval === 0 && "+" || "" ) + rval + "%";
}
_set_element_data(id, data, c_name) {
let el1 = document.getElementById("stat-" + id);
if (c_name)
el1.setAttribute("class", c_name);
else
el1.removeAttribute("class");
let el2 = el1.querySelector(".stat-val")
el2.childNodes[0].nodeValue = data;
}
_ensure_element_created() {
let block = document.getElementById("stat-block");
if (block && block.children.length === 0) {
let ul = document.createElement("ul");
Status._element_list.forEach(function(id) {
let li = document.createElement("li");
let div = document.createElement("div");
div.setAttribute("id", "stat-" + id);
let val = document.createElement("span");
val.setAttribute("class", "stat-val state-text");
val.appendChild(document.createTextNode("?"));
let msg = document.createElement("span");
msg.setAttribute("class", "stat-msg");
msg.appendChild(document.createTextNode(Status._element_data[id].text));
div.appendChild(val);
div.appendChild(msg);
li.appendChild(div);
ul.appendChild(li);
});
block.appendChild(ul);
}
}
}
Status.instance = function() {
if (!this._instance)
this._instance = new Status();
return this._instance;
}
Status._element_list = [ "processed", "passed", "forwarded", "failed" ];
Status._element_data = {
processed: {
text: "Emails processed"
},
passed: {
text: "Fully aligned"
},
forwarded: {
text: "Partially aligned"
},
failed: {
text: "Not aligned"
}
};

View File

@ -0,0 +1,537 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class Summary {
constructor(id) {
this._report = null;
this._element = document.getElementById("main-block");
this._container = null;
this._options_data = null;
this._options_block = null;
this._report_block = null;
}
display() {
this._create_container();
this._element.appendChild(this._container);
this._create_options_block();
this._create_report_block();
this._container.appendChild(this._options_block);
this._container.appendChild(document.createElement("hr"));
this._container.appendChild(this._report_block);
}
update() {
this._handle_url_params();
this._update_options_block();
this._fetch_report();
}
title() {
return "Summary Reports";
}
_handle_url_params() {
let url_params = new URL(document.location.href).searchParams;
let domain = url_params.get("domain");
let period = url_params.get("period");
let format = url_params.get("format");
if (domain && period) {
this._options_data = { domain: domain, period: period, format: format || "text" };
} else {
this._options_data = null;
}
}
_create_container() {
this._container = document.createElement("div");
this._container.setAttribute("class", "panel-container round-border");
}
_create_options_block() {
let opts = document.createElement("div");
opts.setAttribute("class", "options-block");
opts.appendChild(document.createTextNode("Report options: "));
opts.appendChild(document.createTextNode("none"));
let btn = document.createElement("button");
btn.setAttribute("class", "options-button");
btn.appendChild(document.createTextNode("Change"));
btn.addEventListener("click", function(event) {
this._display_dialog();
}.bind(this));
opts.appendChild(btn);
this._options_block = opts;
}
_update_options_block() {
let text = "none";
if (this._options_data) {
text = "domain=" + this._options_data.domain + " period=" + this._options_data.period;
}
this._options_block.childNodes[1].textContent = text;
}
_create_report_block() {
this._report_block = document.createElement("div");
this._report_block.setAttribute("class", "summary-report");
}
_display_dialog() {
let dlg = new OptionsDialog(this._options_data);
document.getElementById("main-block").appendChild(dlg.element());
dlg.show().then(function(d) {
if (!d) {
return;
}
let url = new URL(document.location.href);
url.searchParams.set("domain", d.domain);
let period = d.period;
if (period === "lastndays") {
period += ":" + d.days;
}
url.searchParams.set("period", period);
url.searchParams.set("format", d.format);
window.history.replaceState(null, "", url.toString());
remove_all_children(this._element);
this.display();
this.update();
}.bind(this)).finally(function() {
this._options_block.lastChild.focus();
}.bind(this));
}
_fetch_report() {
remove_all_children(this._report_block);
if (!this._options_data) {
this._report_block.appendChild(document.createTextNode("Report options are not selected"));
return;
}
this._report_block.appendChild(set_wait_status());
let uparams = new URLSearchParams();
let domain = this._options_data.domain;
uparams.set("domain", domain);
uparams.set("period", this._options_data.period);
uparams.set("format", this._options_data.format === "html" ? "raw" : "text");
window.fetch("summary.php?mode=report&" + uparams.toString(), {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok) {
throw new Error("Failed to fetch the report");
}
return resp.json();
}).then(function(report) {
Common.checkResult(report);
report.domain = domain;
this._report = new SummaryReport(report);
this._display_report();
}.bind(this)).catch(function(err) {
Common.displayError(err);
set_error_status(this._report_block, 'Error: ' + err.message);
}.bind(this)).finally(function() {
let wm = this._report_block.querySelector(".wait-message");
if (wm) {
wm.remove();
}
}.bind(this));
}
_display_report() {
let el = null;
let text = this._report.text();
if (text) {
el = document.createElement("pre");
el.appendChild(document.createTextNode(this._report.text()));
} else {
el = this._report.html();
if (!el) {
el = document.createElement("p");
el.appendChild(document.createTextNode("No data"));
}
}
this._report_block.appendChild(el);
}
}
class OptionsDialog extends ModalDialog {
constructor(params) {
super({ title: "Report options", buttons: [ "apply", "reset" ] });
this._data = params || {};
this._content = null;
this._domains = null;
this._ui_data = [
{ name: "domain", title: "Domain" },
{ name: "period", title: "Period" },
{ name: "days", title: "Days", type: "input" },
{ name: "format", title: "Format" }
];
}
_gen_content() {
let container = document.createElement("div");
container.setAttribute("class", "titled-input");
this._content.appendChild(container);
this._content.classList.add("vertical-content");
this._ui_data.forEach(function(row) {
let i_el = this._add_option_row(row.name, row.title, container, row.type);
if (row.name === "days") {
i_el.setAttribute("type", "number");
i_el.setAttribute("min", "1");
i_el.setAttribute("max", "9999");
i_el.setAttribute("value", "");
}
row.element = i_el;
}, this);
this._ui_data[1].element.addEventListener("change", function(event) {
let days_el = this._ui_data[2].element;
if (event.target.value === "lastndays") {
days_el.disabled = false;
delete days_el.dataset.disabled;
days_el.value = days_el.dataset.value || "1";
} else {
days_el.disabled = true;
days_el.dataset.value = days_el.value || "1";
days_el.dataset.disabled = true;
days_el.value = "";
}
}.bind(this));
this._update_period_element();
this._update_format_element();
if (!this._domains) {
this._fetch_data();
}
}
_submit() {
let res = {
domain: this._ui_data[0].element.value,
period: this._ui_data[1].element.value,
format: this._ui_data[3].element.value
};
if (res.period === "lastndays") {
res.days = parseInt(this._ui_data[2].element.value) || 1;
}
this._result = res;
this.hide();
}
_add_option_row(name, title, p_el, type) {
let l_el = document.createElement("label");
p_el.appendChild(l_el);
let t_el = document.createElement("span");
t_el.appendChild(document.createTextNode(title + ": "));
l_el.appendChild(t_el);
let n_el = document.createElement(type || "select");
n_el.setAttribute("name", name);
l_el.appendChild(n_el);
return n_el;
}
_update_domain_element() {
let el = this._ui_data[0].element;
remove_all_children(el);
let c_val = this._data.domain || "";
if (this._domains) {
this._domains.forEach(function(name) {
let opt = document.createElement("option");
opt.setAttribute("value", name);
if (name === c_val) {
opt.setAttribute("selected", "");
}
opt.appendChild(document.createTextNode(name));
el.appendChild(opt);
});
}
}
_update_period_element() {
let el = this._ui_data[1].element;
let c_val = this._data.period && this._data.period.split(":") || [ "lastweek" ];
[
[ "lastweek", "Last week"],
[ "lastmonth", "Last month" ],
[ "lastndays", "Last N days" ]
].forEach(function(it) {
let opt = document.createElement("option");
opt.setAttribute("value", it[0]);
if (it[0] === c_val[0]) {
opt.setAttribute("selected", "");
}
opt.appendChild(document.createTextNode(it[1]));
el.appendChild(opt);
});
if (c_val[1]) {
let val = parseInt(c_val[1]);
let i_el = this._ui_data[2].element;
i_el.setAttribute("value", val);
i_el.dataset.value = val;
}
el.dispatchEvent(new Event("change"));
}
_update_format_element() {
let el = this._ui_data[3].element;
let cv = this._data.format || "text";
[
[ "text", "Plain text" ],
[ "html", "HTML" ]
].forEach(function(it) {
let opt = document.createElement("option");
opt.setAttribute("value", it[0]);
if (it[0] === cv) {
opt.setAttribute("selected", "");
}
opt.appendChild(document.createTextNode(it[1]));
el.appendChild(opt);
});
}
_enable_ui(enable) {
let list = this._element.querySelector("form").elements;
for (let i = 0; i < list.length; ++i) {
let el = list[i];
el.disabled = !enable || el.dataset.disabled;
}
}
_fetch_data() {
this._enable_ui(false);
this._content.appendChild(set_wait_status());
window.fetch("summary.php?mode=options", {
method: "GET",
cache: "no-store",
headers: HTTP_HEADERS,
credentials: "same-origin"
}).then(function(resp) {
if (!resp.ok) {
throw new Error("Failed to fetch the report options list");
}
return resp.json();
}).then(function(data) {
Common.checkResult(data);
this._domains = data.domains;
this._update_domain_element();
this._enable_ui(true);
}.bind(this)).catch(function(err) {
Common.displayError(err);
this._content.appendChild(set_error_status());
}.bind(this)).finally(function() {
this._content.querySelector(".wait-message").remove();
}.bind(this));
}
_reset() {
window.setTimeout(function() {
this._ui_data[1].element.dispatchEvent(new Event("change"));
}.bind(this), 0);
}
}
class SummaryReport {
constructor(data) {
this._report = data;
}
text() {
let lines = this._report.text || [];
if (lines.length > 0) {
return lines.join("\n");
}
}
html() {
let data = this._report.data;
let html = document.createDocumentFragment();
let header = document.createElement("h2");
header.appendChild(document.createTextNode("Domain: " + this._report.domain));
html.appendChild(header);
{
let range = document.createElement("div");
let d1 = (new Date(data.date_range.begin)).toLocaleDateString();
let d2 = (new Date(data.date_range.end)).toLocaleDateString();
range.appendChild(document.createTextNode("Range: " + d1 + " - " + d2));
html.appendChild(range);
}
{
let header = document.createElement("h3");
header.appendChild(document.createTextNode("Summary"));
html.appendChild(header);
let cont = document.createElement("div");
cont.setAttribute("class", "left-titled");
html.appendChild(cont);
function add_row(title, value, cname) {
let te = document.createElement("span");
te.appendChild(document.createTextNode(title + ": "));
cont.appendChild(te);
let ve = document.createElement("span");
if (cname) {
ve.setAttribute("class", cname);
}
ve.appendChild(document.createTextNode(value));
cont.appendChild(ve);
}
let emails = data.summary.emails;
let total = emails.total;
add_row("Total", total);
let aligned = emails.dkim_spf_aligned + emails.dkim_aligned + emails.spf_aligned;
let n_aligned = total - aligned;
add_row(
"DKIM or SPF aligned",
SummaryReport.num2percent(aligned, total),
aligned && "report-result-pass" || null
);
add_row(
"Not aligned",
SummaryReport.num2percent(n_aligned, total),
n_aligned && "report-result-fail" || null
);
add_row("Organizations", data.summary.organizations);
}
if (data.sources && data.sources.length) {
let header = document.createElement("h3");
header.appendChild(document.createTextNode("Sources"));
html.appendChild(header);
let table = document.createElement("table");
table.setAttribute("class", "report-table");
html.appendChild(table);
let caption = document.createElement("caption");
caption.appendChild(document.createTextNode("Total records: " + data.sources.length));
table.appendChild(caption);
let thead = document.createElement("thead");
table.appendChild(thead);
[
[
[ "IP address", 0, 2 ], [ "Email volume", 0, 2 ], [ "SPF", 3, 0 ], [ "DKIM", 3, 0 ]
],
[
[ "pass" ], [ "fail" ], [ "rate" ], [ "pass" ], [ "fail" ], [ "rate" ]
]
].forEach(function(row) {
let tr = document.createElement("tr");
thead.appendChild(tr);
row.forEach(function(col) {
let th = document.createElement("th");
th.appendChild(document.createTextNode(col[0]));
if (col[1]) {
th.setAttribute("colspan", col[1]);
}
if (col[2]) {
th.setAttribute("rowspan", col[2]);
}
tr.appendChild(th);
});
});
let tbody = document.createElement("tbody");
table.appendChild(tbody);
data.sources.forEach(function(sou) {
let tr = document.createElement("tr");
tbody.appendChild(tr);
let va = [];
va.push([ Common.makeIpElement(sou.ip), 0 ]);
let ett = sou.emails;
let spf = sou.spf_aligned;
let dkm = sou.dkim_aligned;
va.push([ ett, 1 ]);
va.push([ spf, 3 ]);
va.push([ ett - spf, 5 ]);
va.push([ spf / ett, 8 ]);
va.push([ dkm, 3 ]);
va.push([ ett - dkm, 5 ]);
va.push([ dkm / ett, 8 ]);
va.forEach(function(it) {
let val = it[0];
let mode = it[1];
let td = document.createElement("td");
if (val && (mode & 2)) {
td.setAttribute("class", "report-result-pass");
}
if (val && (mode & 4)) {
td.setAttribute("class", "report-result-fail");
}
if (mode & 8) {
val = (val * 100).toFixed(0) + "%";
} else if (mode & 1) {
val = val.toLocaleString();
}
if (typeof(val) === "object") {
td.appendChild(val);
} else {
td.appendChild(document.createTextNode(val));
}
tr.appendChild(td);
});
});
}
if (data.organizations && data.organizations.length) {
let header = document.createElement("h3");
header.appendChild(document.createTextNode("Organizations"));
html.appendChild(header);
let table = document.createElement("table");
table.setAttribute("class", "report-table");
html.appendChild(table);
let caption = document.createElement("caption");
caption.appendChild(document.createTextNode("Total records: " + data.organizations.length));
table.appendChild(caption);
let thead = document.createElement("thead");
table.appendChild(thead);
let tr = document.createElement("tr");
thead.appendChild(tr);
[ "Name", "Emails", "Reports" ].forEach(function(org) {
let th = document.createElement("th");
th.appendChild(document.createTextNode(org));
tr.appendChild(th);
});
let tbody = document.createElement("tbody");
table.appendChild(tbody);
data.organizations.forEach(function(org) {
let tr = document.createElement("tr");
tbody.appendChild(tr);
let va = [];
va.push(org.name);
va.push(org.emails.toLocaleString());
va.push(org.reports.toLocaleString());
va.forEach(function(v) {
let td = document.createElement("td");
td.appendChild(document.createTextNode(v));
tr.appendChild(td);
});
});
}
return html;
}
static num2percent(per, cent) {
if (!per) {
return "0";
}
return "" + Math.round(per / cent * 100, per) + "% (" + per + ")";
}
}

View File

@ -0,0 +1,961 @@
/**
* dmarc-srg - A php parser, viewer and summary report generator for incoming DMARC reports.
* Copyright (C) 2020 Aleksey Andreev (liuch)
*
* Available at:
* https://github.com/liuch/dmarc-srg
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ITable {
constructor(params) {
this._table = null;
this._class = null;
this._header = null;
this._status = null;
this._frames = [];
this._columns = [];
this._body = null;
this._onsort = null;
this._onclick = null;
this._onfocus = null;
if (params) {
this._class = params.class || null;
this._onsort = params.onsort || null;
this._onclick = params.onclick || null;
this._onfocus = params.onfocus || null;
this._nodata_text = params.nodata_text || null;
}
this._focused = false;
this._focused_row = null;
this._selected_rows = [];
}
element() {
if (!this._table) {
let that = this;
this._table = document.createElement("div");
if (this._class)
this._table.setAttribute("class", this._class);
this._table.classList.add("table");
this._table.setAttribute("tabindex", -1);
this._table.addEventListener("focus", function(event) {
that._focused = true;
that._update_focus();
}, true);
this._table.addEventListener("blur", function(event) {
that._focused = false;
that._update_focus();
}, true);
let th = document.createElement("div");
th.setAttribute("class", "table-header");
this._table.appendChild(th);
this._header = document.createElement("div");
this._header.setAttribute("class", "table-row");
this._header.addEventListener("click", function(event) {
let col = that.get_column_by_element(event.target);
if (col && col.is_sortable()) {
if (that._onsort) {
that._onsort(col);
}
}
});
th.appendChild(this._header);
this._fill_columns();
this._body = document.createElement("div");
this._body.setAttribute("class", "table-body");
this._body.addEventListener("click", function(event) {
let row = that._get_row_by_element(event.target);
if (row) {
that._set_selected_rows([ row ]);
if (that._onclick)
that._onclick(row);
}
});
this._body.addEventListener("focus", function(event) {
let row = that._get_row_by_element(event.target);
if (row) {
that._update_focused_row(row);
if (that._onfocus)
that._onfocus(row.element());
}
}, true);
this._body.addEventListener("blur", function(event) {
let row = that._get_row_by_element(event.target);
if (row) {
row.onfocus(false);
}
}, true);
this._body.addEventListener("keydown", function(event) {
let row = null;
switch (event.code) {
case "ArrowDown":
row = that._get_row(that._focused_row !== null && (that._focused_row.id() + 1) || 0);
break;
case "ArrowUp":
if (that._focused_row) {
let id = that._focused_row.id();
if (id >= 0)
row = that._get_row(id - 1);
}
else {
row = that._get_row(0);
}
break;
case "PageUp":
if (that._focused_row && that._frames.length > 0) {
let c_id = that._focused_row.id();
let f_fr = that._frames[0];
let f_id = f_fr.first_index();
if (c_id == f_id)
break;
let s_el = that._get_scroll_element();
if (s_el) {
let r_ht = that._focused_row.element().getBoundingClientRect().height;
let s_ht = s_el.getBoundingClientRect().height;
let n_id = Math.max(c_id - Math.floor(s_ht / r_ht) - 1, f_id);
row = that._get_row(n_id);
}
else {
row = f_fr.row(f_id);
}
}
break;
case "PageDown":
if (that._focused_row && that._frames.length > 0) {
let c_id = that._focused_row.id();
let l_fr = that._frames[that._frames.length - 1];
let l_id = l_fr.last_index();
if (c_id == l_id)
break;
let s_el = that._get_scroll_element();
if (s_el) {
let r_ht = that._focused_row.element().getBoundingClientRect().height;
let s_ht = s_el.getBoundingClientRect().height;
let n_id = Math.min(c_id + Math.floor(s_ht / r_ht) - 1, l_id);
row = that._get_row(n_id);
}
else {
row = l_fr.row(l_id);
}
}
break;
case "Home":
if (that._frames.length > 0) {
let first_frame = that._frames[0];
row = first_frame.row(first_frame.first_index());
}
break;
case "End":
if (that._frames.length > 0) {
let last_frame = that._frames[that._frames.length - 1];
row = last_frame.row(last_frame.last_index());
}
break;
case "Enter":
case "NumpadEnter":
if (that._onclick && that._focused_row)
that._onclick(that._focused_row);
event.preventDefault();
return;
}
if (row) {
row.element().focus();
that._set_selected_rows([ row ]);
event.preventDefault();
}
});
this._fill_frames();
this._table.appendChild(this._body);
}
return this._table;
}
more() {
return this._frames.length > 0 && this._frames[this._frames.length - 1].more();
}
frames_count() {
return this._frames.length;
}
add_column(data) {
let col = new ITableColumn(data.content, {
name: data.name,
class: data.class,
sortable: data.sortable,
sorted: data.sorted
});
this._columns.push(col);
if (this._header)
this._header.appendChild(col.element());
return col;
}
get_column_by_element(el) {
el = el && el.closest("div.table-cell");
if (el) {
for (let i = 0; i < this._columns.length; ++i) {
let col = this._columns[i];
if (el === col.element())
return col;
}
}
}
display_status(status, text) {
if (this._status && !status) {
this._status.remove();
this._status = null;
return;
}
this.element();
this._status = document.createElement("div");
this._status.setAttribute("class", "table-row colspanned");
let el = document.createElement("div");
el.setAttribute("class", "table-cell");
this._status.appendChild(el);
let el2 = document.createElement("div");
el2.setAttribute("class", "table-cell");
el2.appendChild(document.createTextNode("\u00A0")); // Non breaking space
this._status.appendChild(el2);
if (status === "wait") {
set_wait_status(el);
}
else {
remove_all_children(this._body);
if (status === "nodata") {
el.classList.add("nodata");
el.appendChild(document.createTextNode(text || "No data"));
}
else {
set_error_status(el, text);
}
}
this._body.appendChild(this._status);
}
last_row_index() {
let idx = -1;
if (this._frames.length > 0) {
idx = this._frames[this._frames.length - 1].last_index();
}
return idx;
}
add_frame(frame) {
if (frame.count() === 0) {
if (this._frames.length === 0)
this.display_status("nodata", this._nodata_text);
return
}
if (this._frames.length > 0 && this._frames[0].first_index() > frame.last_index()) {
this._frames.unshift(frame);
if (this._body)
this._body.insertBefore(frame.element(), this._body.firstChild);
}
else {
this._frames.push(frame);
if (this._body)
this._body.appendChild(frame.element());
}
}
clear() {
this._frames = [];
if (this._body)
remove_all_children(this._body);
this._focused_row = null;
this._selected_rows = [];
}
focus() {
if (!this._focused_row) {
if (this._frames.length > 0) {
let fr = this._frames[0];
this._focused_row = fr.row(fr.first_index());
}
}
if (this._focused_row)
this._focused_row.element().focus();
}
sort(col_name, direction) {
if (this._frames.length == 1) {
for (let i = 0; i < this._columns.length; ++i) {
let col = this._columns[i];
if (col.is_sortable() && col.name() === col_name) {
let fr = this._frames[0];
fr.sort(i, direction);
if (this._body) {
remove_all_children(this._body);
this._body.appendChild(fr.element());
}
return;
}
}
}
}
set_sorted(col_name, direction) {
this._columns.forEach(function(col) {
if (col.is_sortable()) {
if (col.name() !== col_name) {
col.sort(null);
}
else {
if (direction === "toggle") {
direction = null;
if (col.sorted() === "ascent") {
direction = "descent";
}
else if (col.sorted() === "descent") {
direction = "ascent";
}
}
col.sort(direction);
}
}
});
}
_fill_columns() {
this._columns.forEach(function(col) {
this._header.appendChild(col.element());
}, this);
}
_fill_frames() {
this._frames.forEach(function(fr) {
this._body.appendChild(fr.element());
}, this);
}
_get_row(row_id) {
for (let i = 0; i < this._frames.length; ++i) {
let fr = this._frames[i];
if (fr.last_index() >= row_id) {
if (fr.first_index() <= row_id)
return fr.row(row_id);
}
}
return null;
}
_get_row_by_element(el) {
let row = null;
if (el) {
el = el.closest("div.table-row");
if (el) {
let id = parseInt(el.getAttribute("data-id"));
if (id !== NaN)
row = this._get_row(id);
}
}
return row;
}
_update_focus() {
if (this._focused)
this._table.classList.add("focused");
else
this._table.classList.remove("focused");
}
_update_focused_row(row) {
if (this._focused_row && row !== this._focused_row) {
this._focused_row.tabindex(-1);
}
this._focused_row = row;
this._focused_row.tabindex(0);
this._focused_row.onfocus(true);
}
_set_selected_rows(rows) {
this._selected_rows.forEach(function(row) {
row.select(false);
});
rows.forEach(function(row) {
row.select(true);
});
this._selected_rows = rows;
}
_get_scroll_element() {
let t_rect = this._table.getBoundingClientRect();
let p_elem = this._table.parentElement;
while (p_elem) {
let p_rect = p_elem.getBoundingClientRect();
if (t_rect.top < p_rect.top || t_rect.bottom > p_rect.bottom) {
return p_elem;
}
p_elem = p_elem.paretnElement;
}
}
}
class ITableFrame {
constructor(data, pos) {
this._pos = pos;
this._more = data.more && true || false;
let id = pos;
this._rows = data.rows.map(function(rd) {
if (!(rd instanceof ITableRow)) {
rd = new ITableRow(rd);
}
rd.id(id++);
return rd;
});
}
count() {
return this._rows.length;
}
first_index() {
return this._pos;
}
last_index() {
let cnt = this._rows.length;
if (cnt > 0) {
return this._pos + cnt - 1;
}
return null;
}
row(id) {
let idx = id - this._pos;
if (idx >= 0 && idx < this._rows.length) {
return this._rows[idx];
}
return null;
}
more() {
return this._more;
}
element() {
let fr = document.createDocumentFragment();
this._rows.forEach(function(row) {
fr.appendChild(row.element());
});
return fr;
}
sort(col_idx, direction) {
let dir = (direction === "ascent" && 1) || (direction === "descent" && 2) || 0;
if (dir) {
let that = this;
this._rows.sort(function(a, b) {
let c1 = a.cell(col_idx);
let c2 = b.cell(col_idx);
if (dir === 1) {
return that._compare_cells(c2, c1);
}
return that._compare_cells(c1, c2);
});
let id = this._pos;
this._rows.forEach(function(row) {
row.id(id++);
});
}
}
_compare_cells(c1, c2) {
return c1.value("sort") < c2.value("sort");
}
}
class ITableRow {
constructor(data) {
this._id = -1;
this._focused = false;
this._tabindex = -1;
this._selected = false;
this._element = null;
this._class = data.class || null;
this._userdata = data.userdata || null;
this._cells = data.cells.map(function(col) {
if (col instanceof ITableCell) {
return col;
}
let props = null;
if (col.title || col.class || col.label) {
props = {
title: col.title || null,
class: col.class || null,
label: col.label || null
};
}
return new ITableCell(col.content, props);
});
}
userdata() {
return this._userdata;
}
element() {
if (!this._element) {
this._element = document.createElement("div");
this._element.setAttribute("data-id", this._id);
if (this._class)
this._element.setAttribute("class", this._class);
this._element.classList.add("table-row");
this._cells.forEach(function(col) {
this._element.appendChild(col.element());
}, this);
this._update_focus();
this._update_tabindex();
this._update_select();
}
return this._element;
}
onfocus(flag) {
this._focused = flag;
if (this._element)
this._update_focus();
}
tabindex(index) {
if (this._tabindex !== index) {
this._tabindex = index;
this._update_tabindex();
}
}
select(flag) {
this._selected = flag;
if (this._element)
this._update_select();
}
id(new_id) {
if (new_id !== undefined && new_id !== this._id) {
this._id = new_id;
if (this._element) {
this._element.setAttribute("data-id", this._id);
}
}
return this._id;
}
cell(index) {
return this._cells[index] || null;
}
_update_focus() {
if (this._focused)
this._element.classList.add("focused");
else
this._element.classList.remove("focused");
}
_update_tabindex() {
this._element.setAttribute("tabindex", this._tabindex);
}
_update_select() {
if (this._selected) {
this._element.classList.add("selected");
}
else {
this._element.classList.remove("selected");
}
}
}
class ITableCell {
constructor(content, props) {
this._element = null;
this._content = content;
if (props) {
this._title = props.title || null;
this._class = props.class || null;
this._label = props.label || null;
}
}
element() {
if (!this._element) {
this._element = document.createElement("div");
if (this._title) {
this._element.setAttribute("title", this._title);
}
if (this._class) {
this._element.setAttribute("class", this._class);
}
if (this._label) {
this._element.setAttribute("data-label", this._label);
}
this._element.classList.add("table-cell");
let content = this.value("dom");
if (content !== null) {
if (typeof(content) === "object") {
this._element.appendChild(content)
}
else {
this._element.appendChild(document.createTextNode(content));
}
}
}
return this._element;
}
value(target) {
if (target === "dom" || typeof(this._content) !== "object") {
return this._content;
}
return null;
}
}
class ITableColumn extends ITableCell {
constructor(content, props) {
super(content, props);
this._name = props.name;
this._sortable = !!props.sortable;
this._sorted = props.sorted || null;
}
element() {
if (this._element !== super.element()) {
this._update_sorted();
}
return this._element;
}
is_sortable() {
return this._sortable;
}
sort(dir) {
if (this._sorted !== dir) {
this._sorted = dir || null;
if (this._element) {
this._update_sorted();
}
}
}
sorted() {
return this._sorted;
}
name() {
return this._name;
}
_update_sorted() {
if (this._sortable) {
this._element.classList.add("sortable");
let c_act = {
asc: "remove",
des: "remove"
};
if (this._sorted) {
this._element.classList.add("arrows");
if (this._sorted === "ascent") {
c_act["asc"] = "add";
}
else if (this._sorted === "descent") {
c_act["des"] = "add";
}
}
else {
this._element.classList.remove("arrows");
}
for (let key in c_act) {
this._element.classList[c_act[key]]("sorted-" + key);
}
}
}
}
class ModalDialog {
constructor(params) {
this._params = params;
this._element = null;
this._title = null;
this._buttons = [];
this._content = null;
this._first = null;
this._last = null;
this._result = null;
this._callback = null;
}
element() {
if (!this._element) {
let ovl = document.createElement("div");
ovl.setAttribute("class", "dialog-overlay hidden");
let dlg = document.createElement("div");
dlg.setAttribute("class", "dialog");
let con = document.createElement("div");
con.setAttribute("class", "container");
this._title = document.createElement("div");
this._title.setAttribute("class", "title");
{
let tt = document.createElement("div");
tt.setAttribute("class", "title-text");
tt.appendChild(document.createTextNode(this._params.title || ""));
this._title.appendChild(tt);
}
let that = this;
{
let cbt = document.createElement("button");
cbt.setAttribute("type", "button");
cbt.setAttribute("class", "close-btn");
cbt.appendChild(document.createTextNode("x"));
this._title.appendChild(cbt);
this._buttons = [ cbt ];
cbt.addEventListener("click", function(event) {
that.hide();
});
}
con.appendChild(this._title);
let frm = document.createElement("form");
this._content = document.createElement("div");
frm.appendChild(this._content);
let bdv = document.createElement("div");
bdv.setAttribute("class", "dialog-buttons");
this._add_buttons(bdv);
frm.appendChild(bdv);
con.appendChild(frm);
dlg.appendChild(con);
ovl.appendChild(dlg);
this._element = ovl;
this._gen_content();
this._update_first_last();
this._element.addEventListener("click", function(event) {
if (event.target === this && that._params.overlay_click !== "ignore") {
that.hide();
}
});
frm.addEventListener("keydown", function(event) {
if (event.key == "Tab") {
if (!event.shiftKey) {
if (event.target == that._last) {
that._first.focus();
event.preventDefault();
}
}
else {
if (event.target == that._first) {
that._last.focus();
event.preventDefault();
}
}
}
});
frm.addEventListener("submit", function(event) {
event.preventDefault();
that._submit();
});
frm.addEventListener("reset", function(event) {
this._reset();
}.bind(this));
}
return this._element;
}
show() {
this.element();
this._result = null;
this._title.querySelector("button.close-btn").classList.add("active");
this._element.classList.remove("hidden");
if (this._first) {
this._first.focus();
}
let that = this;
return new Promise(function(resolve, reject) {
that._callback = resolve;
});
}
hide() {
if (this._element) {
this._title.querySelector("button.close-btn").classList.remove("active");
this._element.classList.add("hidden");
}
this._callback && this._callback(this._result);
}
_add_buttons(container) {
let bl = this._params.buttons || [];
bl.forEach(function(bt) {
let name = null;
let type = null;
if (bt == "ok") {
name = "Ok";
type = "submit";
}
else if (bt == "apply") {
name = "Apply";
type = "submit";
}
else if (bt == "reset") {
name = "Reset";
type = "reset";
}
else if (bt == "login") {
name = "Log in";
type = "submit";
}
else if (bt == "cancel") {
name = "Cancel";
type = "close";
}
else if (bt == "close") {
name = "Close";
type = "close";
}
else {
name = bt;
type = bt;
}
this._add_button(container, name, type);
}, this);
}
_add_button(container, text, type) {
let btn = document.createElement("button");
if (type == "close") {
btn.setAttribute("type", "button");
btn.addEventListener("click", this.hide.bind(this));
}
else {
btn.setAttribute("type", type);
}
btn.appendChild(document.createTextNode(text));
container.appendChild(btn);
this._buttons.push(btn);
}
_gen_content() {
}
_update_first_last() {
this._first = null;
this._last = null;
let list = this._element.querySelector("form").elements;
for (let i = 0; i < list.length; ++i) {
let el = list[i];
if (!el.elements && !el.disabled) {
if (!this._first)
this._first = el;
this._last = el;
}
}
}
_submit() {
}
_reset() {
}
}
class AboutDialog extends ModalDialog {
constructor(params) {
super({
title: "About",
buttons: [ "ok" ]
});
this._authors = params.authors;
this._documentation = params.documentation;
this._source_code = params.source_code;
}
element() {
if (!this._element) {
super.element();
this._element.children[0].classList.add("about");
this._content.classList.add("vertical-content");
this._content.parentElement.classList.add("vertical-content");
}
return this._element;
}
_gen_content() {
let header = document.createElement("h2");
header.appendChild(document.createTextNode(Router.app_name(true)));
this._content.appendChild(header);
let cblock = document.createElement("div");
this._authors.forEach(function(author) {
let ablock = document.createElement("div");
ablock.appendChild(document.createTextNode("Copyright © " + author.years + ", "));
cblock.appendChild(ablock);
let alink = document.createElement("a");
alink.setAttribute("href", author.url);
alink.setAttribute("title", "The author's page");
alink.setAttribute("target", "_blank");
alink.appendChild(document.createTextNode(author.name));
ablock.appendChild(alink);
});
this._content.appendChild(cblock);
let oblock = document.createElement("div");
oblock.setAttribute("class", "left-titled");
let add_row = function(title, value) {
let t_el = document.createElement("span");
t_el.appendChild(document.createTextNode(title + ": "));
oblock.appendChild(t_el);
let v_el = document.createElement("div");
value.forEach(function(v) {
if (v_el.children.length > 0) {
v_el.appendChild(document.createTextNode(", "));
}
let a_el = document.createElement("a");
a_el.setAttribute("href", v.url);
a_el.setAttribute("title", v.title || v.ancor);
a_el.setAttribute("target", "_blank");
a_el.appendChild(document.createTextNode(v.ancor));
v_el.appendChild(a_el);
});
oblock.appendChild(v_el);
};
this._content.appendChild(oblock);
add_row("Documentation", this._documentation);
add_row("Source code", this._source_code);
{
let tl = document.createElement("span");
tl.appendChild(document.createTextNode("PHP version: "));
oblock.appendChild(tl);
let vl = document.createElement("span");
vl.appendChild(document.createTextNode(Router.php_version || "n/a"));
oblock.appendChild(vl);
}
let lblock = document.createElement("div");
lblock.appendChild(document.createTextNode(
"This program is free software: you can redistribute it and/or modify it\
under the terms of the GNU General Public License as published by the Free\
Software Foundation, either version 3 of the License."
));
this._content.appendChild(lblock);
}
_submit() {
this.hide();
}
}

Some files were not shown because too many files have changed in this diff Show More