<?php
######################################################################
# ZW3B.Site v7.1.2 : The Web Sites Management System
# --------------------------------------------------------------------
#
# Copyright (c) 2022 by LAB3W : O.Romain Jaillet-ramey - (orj+php+dmarc@lab3w.fr)
#
# Date Create : 2022/07/08
# Date Modify : 2022/07/12
#
# Web Domain : lab3w.fr
# Web Domain : lab3w.com
#
# Web Domain : zw3b.fr
# Web Domain : zw3b.tv
# Web Domain : zw3b.com
# Web Domain : zw3b.net
# Web Domain : zw3b.blog
#
# Web Domain : ipv01.net
# Web Domain : ipv10.net
#
# This module is to manage ---------------------------- :: Descripton
#
# 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 2 of the License.
######################################################################

//----------------------------------------------------------------
// INI Config

ini_set('track_errors','on');
ini_set('display_errors','on');
ini_set('default_charset''UTF-8');

// INI Config
//----------------------------------------------------------------

//----------------------------------------------------------------
// Systeme de cache

# On cache
#header("Cache-Control: max-age=300");
#header("Pragma: cache, max-age=300, max-stale=600");

# No cache
header("Cache-control: private, no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");

// Systeme de cache
//----------------------------------------------------------------

//----------------------------------------------------------------
// Constantes

# My Title default
define('MY_DMARC_TITLE''Global analysis of mail servers of spoofers from <a href="https://www.zw3b.com/dmarc/" title="ZW3B.Com :-: DMARC"><acronym title="Domain-based Message Authentication, Reporting and Conformance" lang="EN">DMARC</acronym> Reports</a> &copy; <a href="https://www.zw3b.site" title="ZW3B :-: The Web Site">ZW3B</a> ');

# My Title compagny
define('MY_DOMAIN_TITLE''by <a href="http://orj.lab3w.fr" title="LAB3W : O.Romain.Jaillet-ramey">LAB3W.ORJ</a>');

# HTML directory where JSON are stored (with write rights for www-data)
define('DIRECTORY_DMARC_STATS_JSON''/var/pro/web_sites/zw3b_com/www/web/var/dmarc/');

# Hide SPF (valid) rows in HTML table
define('HIDE_MY_SPF_LINE_IN_TABLE'true);

# Hide name request from spoofing mail servers
define('HIDE_NAMESERVER_FQDN_SPOOFER_COLS'false);

//----------------------------------------------------------------

//----------------------------------------------------------------
// 
//echo '<pre>'.print_r($_SERVER,1).'</pre>';

//$_SERVER['REMOTE_ADDR'];
//$_SERVER['SERVER_ADDR'];

//header("Origin: ".$_SERVER['HTTP_HOST']."");
//header("Origin: 83.201.208.188");
//header('X-ZW3B-Api-Origin: server_home');

//header("Access-Control-Request-Method: GET");
//header("Access-Control-Request-Headers: Content-Type, X-Api-Origin");
//header("Access-Control-Request-Headers: X-Api-Origin");

//header('Access-Control-Expose-Headers: X-Api-Origin');

//
//----------------------------------------------------------------

//$data = file_get_contents('https://www.zw3b.com/dmarc-reports-analytics.php?get=json');
//$json = json_decode($data);

echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'."\n";
echo 
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
echo 
'<head>'."\n";
echo 
'<title></title>'."\n";
echo 
'<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>'."\n";
echo 
'<meta http-equiv="cache-control" content="no-cache"/>'."\n";
echo 
'<meta http-equiv="Pragma" content="no-cache"/>'."\n";

echo 
'<style type="text/css">'."\n";
echo 
'
a {
    color: #565656;
    text-decoration: none;
    font-weight: bold;
}
acronym {
    cursor: help;
    text-decoration: none;
    border-bottom: 1px dotted;
}
.hidden {
    display: none;
}
table.rapport tbody tr.data.error.hide {
    height: 0;
    padding: 0;
    margin: 0;
    border-bottom: 1px solid #565656;
}
table.rapport tbody tr.data.error.hide td {
    height: 0;
    padding: 0;
    margin: 0;
    font-size: 0;
}
    
table {
    margin:0;
    padding:0;
    font-family:Tahoma, Arial, Helvetica, Verdana, sans-serif;
    font-weight:normal;
    font-size:12px;
    letter-spacing: 0.5px;
    color: #565656;
    border-spacing: 0;
    border-collapse: collapse;
    
    width: 100%;
}
table.rapport {
    border-left: 2px solid #565656;
    border-right: 2px solid #565656;
    border-top: 2px solid #565656;
}
table.rapport thead {
    background-color: #EEE;
}
table.rapport thead tr {
    
}
table.rapport thead tr thead {
    text-align: center;
    font-weight: bold;
    padding: 10px 5px;
    border-left: 1px solid #CCC;
    border-right: 1px solid #CCC;
}
table.rapport thead tr.label th {
    cursor: pointer;
}
table.rapport thead tr td {
    padding: 10px 5px;
    border-left: 1px solid #CCC;
    border-right: 1px solid #CCC;
}
table.rapport thead tr.title {
    height: 30px;
    font-weight: bold;
    border-bottom: 1px solid #CCC;
}
table.rapport thead tr.label {
    height: 30px;
    border-bottom: 2px solid #565656;
}
table.rapport tbody tr.data {
    height: 30px;
    border-bottom: 2px solid #565656;
}
table.rapport tbody tr.data.error {
    background-color: coral;
    background-color: orange;
    background-color: #ffd588;
}
table.rapport tbody tr:hover.data.error {
    background-color: coral;
    background-color: orange;
}
table.rapport tbody tr.data.error.ip {
    background-color: darkorange;
    background-color: orangered;
    background-color: #ff9771;
}
table.rapport tbody tr:hover.data.error.ip {
    background-color: darkorange;
    background-color: orangered;
}
table.rapport tbody tr.data.pass {
    background-color: greenyellow;
    background-color: #d0fb8f;
}
table.rapport tbody tr:hover.data.pass {
    background-color: greenyellow;
}
table.rapport tbody tr.data td {
    text-align: center;
    border-left: 1px solid #CCC;
    border-right: 1px solid #CCC;
}
table.rapport tbody tr.data td.auth {
    
}
table.rapport tbody tr.data td.addr_ip {
    
}
table.rapport tbody tr.data td.count {
    
}
table.rapport tbody tr td.date {
    
}
'
;

echo 
'</style>'."\n";

echo 
'<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'."\n";
//echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'."\n";
echo '<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.31.3/js/jquery.tablesorter.min.js" integrity="sha512-qzgd5cYSZcosqpzpn7zF2ZId8f/8CHmFKZ8j7mU4OUXTNRd5g+ZHBPsgKEwoqxCtdQvExE5LprwwPAgoicguNg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>'."\n";

echo 
'<script type="text/javascript">'."\n";
echo 
'
    
    jQuery(document).ready(function(){
    
    jQuery(function() {
    
    
        jQuery("table.sortable").tablesorter();
    
        var table_sortable = document.getElementsByClassName("sortable");
    
        for(var x = 0; x < table_sortable.length; x++) {
    
            table = table_sortable[x];
    
            if(table.getAttribute("id") !== null) {
    
                table_id = "#"+table.getAttribute("id");
    
                jQuery(table_id).tablesorter({
                    sortList: [[1,1],[3,1]]
                });
            }
            if(table.getAttribute("id") === null)
            {
                jQuery("table.sortable").tablesorter();
            }
        }
    
    });
    
});

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}
function in_array(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == "object") {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}



'
;

echo 
'

function geoip_asnum_by_name(addr) {
    return \''
.geoip_asnum_by_name('"+addr+"').'\';
}

'
;

echo 
'</script>';

echo 
'</head>';

echo 
'<body>';

echo 
'<h1>'."\n";
echo 
''.constant('MY_DMARC_TITLE').'';
echo 
'';
echo 
''.constant('MY_DOMAIN_TITLE').'';
echo 
'</h1>'."\n";

//echo '<h2>Mail server : '.$json_data->infos->mailserver.'</h2>'."\n";

echo '<h2>Mail server : <span></span></h2>';

echo 
'<p>Period : </p>';
echo 
'<ul class="date"></ul>';

echo 
'<table class="rapport sortable" id="api_rest_global_stats_spoofers">';

echo 
'<thead>'."\n";

$cols_nbr constant('HIDE_NAMESERVER_FQDN_SPOOFER_COLS') === false '6' '5';
$cols_nbr constant('HIDE_NAMESERVER_FQDN_SPOOFER_COLS') === false '5' '4';

echo 
'<tr class="title">'."\n";
echo 
'<td colspan="'.$cols_nbr.'">'."\n";
echo 
'Statistics of mail servers of spoofers from <acronym title="Domain-based Message Authentication, Reporting and Conformance" lang="EN">DMARC</acronym> reports.';
echo 
'</td>'."\n";
echo 
'</tr>'."\n";
//----------------------------------------

//----------------------------------------
echo '<tr class="label">'."\n";
//----------
echo '<th style="width: 10%;">'."\n";
echo 
'Conformance';
echo 
'</th>'."\n";
//----------
//----------
echo '<th style="width: 20%;">'."\n";
echo 
'IP Address';
echo 
'</th>'."\n";
//----------
//----------
echo '<th style="width: 10%;">'."\n";
echo 
'Emails volume';
echo 
'</th>'."\n";
//----------
//----------
if(constant('HIDE_NAMESERVER_FQDN_SPOOFER_COLS') !== true)
{
    echo 
'<th style="width: 20%;">'."\n";
    echo 
'Mail Server Spoofing';
    echo 
'</th>'."\n";
}
//----------

//----------
/*
echo '<th style="width: 30%;">'."\n";
echo '<acronym title="Autonomous System Number" lang="EN">ASN</acronym>';
echo '</th>'."\n";
*/
//----------

//----------
echo '<th style="width: 10%;">'."\n";
echo 
'Last date';
echo 
'</th>'."\n";
//----------

echo '</tr>'."\n";
echo 
'</thead>'."\n";
//----------------------------------------

echo '<tbody>'."\n";

echo 
'</tbody>'."\n";

echo 
'</table>';




echo 
'<p>Count : </p>';

echo 
'<ul class="count"></ul>';

echo 
'<script>';

echo 
'
myHeaders = new Headers({
//  "Origin": "https://wwd.zw3b.site",
  "X-API-Client-ID": "zw3b",
  "X-API-Origin": "api_dmarc_client",
  "Access-Control-Request-Method": "OPTIONS"
});

var myInit = { method: "GET",
               headers: myHeaders,
               mode: "cors",
//               site: "same-site",
//               cache: "default",
//               body: \'{"get": "json"}\'
};

if (window.fetch) {

    // exécuter ma requête fetch ici
    console.log("window.fetch OK");
    
    const webpage = "https://www.zw3b.com/dmarc-reports-analytics.php?get=json";

    //fetch("/var/dmarc/dmarc_stats-mail_zw3b_net-202202.json")
    fetch(webpage, myInit)
    .then((response) => {
        if (!response.ok) {
            //throw new Error(`HTTP error, status = ${response.status}`);
            throw new Error(`HTTP error, status = ${response.status}`);
        }
        return response.json();
    })
    .then((data) => {

        console.log(data);

        //-----
        const html_myTitle = document.querySelector("title");
        //html_myTitle.textContent = "MON TITRE";
        html_myTitle.textContent = "Global analysis of mail servers of spoofers from DMARC Reports - Mail server : "+data.infos.mailserver;

        //-----

        //-----
        const html_nameServer = document.querySelector("h2 span");
        html_nameServer.textContent = data.infos.mailserver;
        //-----

        //-----
        const html_datePeriod = document.querySelector("ul.date");
        
        const html_dateSince = document.createElement("li");
        html_dateSince.textContent = "Date since : "+data.infos.date.since.year+"/"+data.infos.date.since.month;
        const html_dateUntil = document.createElement("li");
        html_dateUntil.textContent = "Date until : "+data.infos.date.until.year+"/"+data.infos.date.until.month;

        html_datePeriod.append(
                html_dateSince,
                html_dateUntil,
        );
        //-----



        //-----
        const html_myTable = document.querySelector("table.rapport tbody");

        var count_my_spf = 0;
        var count_my_error_mail = 0;

        for (const servers_error of data.servers_error) {
        
        req_if_hide_my_spf = \''
.constant('HIDE_MY_SPF_LINE_IN_TABLE').'\' == 1 ? !in_array(servers_error.address_ip, data.infos.spf) : true;
    
        count_my_spf += in_array(servers_error.address_ip, data.infos.spf);
        count_my_error_mail += in_array(servers_error.address_ip, data.infos.spf) ? servers_error.count_mails_error : 0;

        if(req_if_hide_my_spf)
        {
            const html_lineItem = document.createElement("tr");
            html_lineItem.classList.add("data");
            
            if(!in_array(servers_error.address_ip, data.infos.spf)) {
                html_lineItem.classList.add("error");
                html_lineItem.classList.add("ip");
            }
            else {
                html_lineItem.classList.add("error");
            }
            
            html_lineItem.setAttribute("role", "row");

            const html_auth = document.createElement("td");
            html_auth.classList.add("auth");
            html_auth.textContent = servers_error.auth;
                    
            const html_address_ip = document.createElement("td");
            html_address_ip.classList.add("addr_ip");
            html_address_ip.textContent = servers_error.address_ip;

            const html_count_mails_error = document.createElement("td");
            html_count_mails_error.classList.add("count");
            html_count_mails_error.textContent = servers_error.count_mails_error;

            const html_fqdn = document.createElement("td");
            html_fqdn.classList.add("fqdn");
            html_fqdn.textContent = servers_error.fqdn;

            const html_asn = document.createElement("td");
            html_asn.classList.add("asn");
                
            //code3 = ".geoip_country_code3_by_name(servers_error.address_ip);
            asn = geoip_asnum_by_name(servers_error.address_ip);
            //asn = \''
.geoip_asnum_by_name("8.8.8.8").'\';
            //city = ".geoip_record_by_name(servers_error.address_ip)["city"];
            //country = ".geoip_record_by_name(servers_error.address_ip)["country_name"];

            html_asn.textContent = asn;

            const html_date = document.createElement("td");
            html_date.classList.add("date");
            html_date.textContent = servers_error.date.year+"/"+servers_error.date.month;

            html_lineItem.append(
                html_auth,
                html_address_ip,
                html_count_mails_error,
                html_fqdn,
                //html_asn,
                html_date,
            );

            html_myTable.appendChild(html_lineItem);
        


        } // REQ HIDE

        } 
        //-----

        //-----
        const html_count = document.querySelector("ul.count");

        //count_emails_sent = data.count.emails.sent;
        //count_emails_passed = data.count.emails.passed;
        //count_emails_errors = data.count.emails.errors;
        
        const html_countUnauthorized = document.createElement("li");
        html_countUnauthorized.textContent = "Emails sent unauthorized : "+(data.count.emails.errors - count_my_error_mail);

        const html_countServers = document.createElement("li");
        html_countServers.textContent = "Number of email sender servers in error : "+(data.servers_error.length - count_my_spf);

        html_count.append(
                html_countUnauthorized,
                html_countServers,
        );
        //-----

            
    })
    .catch((error) => {
        const p = document.createElement("p");
        p.appendChild(document.createTextNode(`Error: ${error.message}`));
        document.body.insertBefore(p, html_myTable);
    });



} else {
    // Faire quelque chose avec XMLHttpRequest?
    console.log("XMLHttpRequest OK");
}






'
;
    
echo 
'</script>';



echo 
'<hr />'."\n";
// Analytics global spoofers --------------
echo '<h3><a href="/dmarc-reports.php"><acronym title="Domain-based Message Authentication, Reporting and Conformance" lang="EN">DMARC</acronym> Reports HTML visualisation</a> <span style="font-size: 80%;">(<a href="/dmarc-reports.phps">PHPSource</a>)</span>.</h3>';
echo 
'<h3><a href="/dmarc-reports-analytics.php">Global analysis of mail servers of spoofers from <acronym title="Domain-based Message Authentication, Reporting and Conformance" lang="EN">DMARC</acronym> reports with <acronym title="REpresentational State Transfer" lang="EN">REST</acronym>ful Server <acronym title="Application Programming Interface" lang="EN">API</acronym></a> <span style="font-size: 80%;">(<a href="/dmarc-reports-analytics.phps">PHPSource</a>)</span>.</h3>';
echo 
'<h3><a href="/dmarc-reports-analytics-rest.php">Global analysis of mail servers of spoofers from <acronym title="Domain-based Message Authentication, Reporting and Conformance" lang="EN">DMARC</acronym> reports on <acronym title="REpresentational State Transfer" lang="EN">REST</acronym>ful Client <acronym title="Application Programming Interface" lang="EN">API</acronym></a> <span style="font-size: 80%;">(<a href="/dmarc-reports-analytics-rest.phps">PHPSource</a>)</span>.</h3>';

echo 
'<hr style="clear:both;"/>';
// Analytics global spoofers --------------

$html '<div id="zw-footer">'."\n";
$html.= '<p class="copyright"><span><a href="https://www.zw3b.site">&copy; 2018-'.date('Y').' ZW3B :-: The Web Site</a>';
$html.= '<br /><br />';
$html.= '<a href="http://www.lab3w.fr">&copy; 2003-'.date('Y').' LAB3W O.Romain.Jaillet-ramey : Web and networks laboratory - InterNet engineering</a> - All rights reserved</a></span>';
$html.= '</p>';

$html.= '<p class="author"><a href="https://www.zw3b.com/dmarc-reports-rest.php" title="DMARC REPORTS ANALYTICS (RESTful Client API)">DMARC REPORTS ANALYTICS (RESTful Client API) : ZW3B</a> &copy; LAB3W.<acronym title="O.Romain.Jaillet-ramey" lang="FR">ORJ</acronym> 2022/07/12</p>'."\n";

$html.= '</div>';

echo 
$html;
//--------------------------------------------------------------------

echo '</body>';
echo 
'</html>';

//echo '<pre>'.print_r($json,1).'</pre>';



?>