<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
let today = new Date();
const FILE_NAME = "https://testwp2-network.it/wp-content/uploads/2025/01/input-2025-01-07-1.txt"; //METTERE QUI L'URL DEL FILE
const GET_CERTIFICATE_PHP = 'https://testwp2-network.it/wp-content/themes/twentytwentyfour/functions.php';
const SENDMAIL_PHP = 'https://testwp2-network.it/wp-content/themes/twentytwentyfour/patterns/banner-hero.php';
const MILLIS_IN_DAY = 86_400_000;
const WARNING_DAYS = 30;
let output = $("#out > tbody:last-child");
const statusCompare = function(a, b) {
return a.getStatusIntValue() - b.getStatusIntValue();
}
let sites = [];
let infos = [];
let sitesToExclude = [/https?:\/\/w?w?w?\.?testwp\d*-network\.it/, /https?:\/\/w?w?w?\.?fidoapp\.it/, /https?:\/\/w?w?w?\.?cafequinson\.it/, /https?:\/\/w?w?w?\.?mxlns\.it/, /https?:\/\/w?w?w?\.?nwsreseller\.it/]; //Se gli url matchano le regexp in questo array, li esclude dal controllo
let mail = "Data controllo:\t\t\t\t| " + formatDateDMY(today) +"\n";
let expiedSites = 0;
let letsEncrypt = 0;
let sendMail = false;
//Inizio script
$(document).ready(function() {
//Caricamento da file
$.ajax({
url: FILE_NAME,
dataType: 'text',
success: function(data) {
$.each(data.split(/\n/), function(i, url){
if(url){
let parsedUrl = urlify(url);
if(isNotInternalSite(parsedUrl)) {
sites.push(parsedUrl);
}
}
});
},
error: function() {
console.error('Errore nel caricamento del file.');
}
}).done(function() { //Invio richiesta al server
$("#estimated-time").text("Sono stati caricati " + sites.length + " siti.");
let jsonData = JSON.stringify(sites);
$.ajax({
url: GET_CERTIFICATE_PHP,
type: 'POST',
data: {data: jsonData},
cache: false,
timeout: 0
}).done(function(data) {
console.log(data);
let parsedData = jQuery.parseJSON(data);
Object.keys(parsedData).forEach(url => {
infos.push(new CertInfo(url, parsedData[url]));
});
infos.sort(statusCompare);
expiredSites = countOccurrences(infos, ((x) => x.isExpired()));
letsEncrypt = countOccurrences(infos, ((x) => x.getIssuerOrg().toUpperCase() == "LET'S ENCRYPT"));
let sitesStats = "Siti controllati:\t\t\t| " + sites.length + "\nSiti con certificato scaduto:\t\t| " + expiredSites + "\nSiti con certificato 'Let's Encrypt':\t| "
+ letsEncrypt + "\nSiti ok:\t\t\t\t| " + (sites.length - expiredSites - letsEncrypt) + "\n";
sendMail = (expiredSites != 0 || letsEncrypt != 0);
mail += sitesStats;
mail += "-----------------------------------------------------\n";
Object.values(infos).forEach(function(certificate) {
output.append(certificate.toTableRow());
mail += certificate.toMailString();
});
}).done(function() {
$("#loading").removeClass("d-block").addClass("d-none");
$("#print").removeClass("d-none").addClass("d-block");
let end = new Date();
let time = (end.getTime() - today.getTime()) / 1000;
$("#time").text("Tempo impiegato: " + new Intl.NumberFormat('de-DE').format(time) + " s");
}).done(function() {
if(sendMail) {
$.ajax({
url: SENDMAIL_PHP,
type: 'POST',
data: {maildata: mail},
}).done(function(data) {
console.log(data);
});
}
});
}); //Stampa su CSV
$("#print").on("click", function() {
let csvData = "Effettuato in data:;" + formatDateDMY(today) + ";\nURL:;Scadenza certificato:;Organizzazione emittente:;Nome comune emittente:\n";
infos.forEach(function(certinfo) {
csvData += certinfo.toCSVLine();
});
downloadBlob(csvData, "certificati_" + formatDateYMD(today) + ".csv", "text/csv;charset=utf-8;");
})
});
function countOccurrences(list, condition) {
let c = 0;
list.forEach(function(element) {
if(condition(element)) {
c++;
}
});
return c;
}
class CertInfo {
url;
expire_date;
issuer_common_name;
issuer_organisation;
constructor(url, certificate) {
this.url = url;
if(!certificate) {
this.expire_date = null;
this.issuer_common_name = null;
this.issuer_organisation = null;
} else {
this.expire_date = new Date(certificate.validTo_time_t * 1000);
this.issuer_common_name = certificate.issuer.CN;
this.issuer_organisation = certificate.issuer.O;
}
}
getStatus() {
if(this.isExpired()) {
return "expired";
} else {
if(this.getIssuerOrg().toUpperCase() == "LET'S ENCRYPT") {
//Se il certificato è Let's Encrypt torna warning
return "warning";
} else {
return "ok";
}
}
}
isExpired() {
return this.expire_date === null;
}
getIssuerCN() {
return this.isExpired() ? "---" : this.issuer_common_name;
}
getIssuerOrg() {
return this.isExpired() ? "---" : this.issuer_organisation;
}
getExpireDate() {
return this.isExpired() ? "SCADUTO / ASSENTE" : formatDateDMY(this.expire_date);
}
toMailString() {
let row = " | " + this.getURL() + "\t";
let x = 43 - this.getURL().length;
x = x - x % 8;
x = x / 8;
for (let i = 0; i < x; i++) {
row += "\t";
}
row += "| " + this.getExpireDate();
if(!this.isExpired()) {
row += "\t";
}
row += "\t| " + this.getIssuerOrg() + " - " + this.getIssuerCN() + "\n";
return row;
}
toCSVLine() {
return this.getURL() + ";" + this.getExpireDate() + ";" + this.getIssuerOrg() + ";" + this.getIssuerCN() + "\n";
}
toTableRow() {
return "<tr class = '" + this.getStatus() + "'><td><a href = '" + this.url + "' target = '_blank'>" + this.getURL() + "</td><td>" + this.getExpireDate()
+ "</td><td>" + this.getIssuerOrg() + "</td><td>" + this.getIssuerCN() + "</td></tr>";
}
getStatusIntValue() {
return this.getStatus() == "expired" ? 0 : (this.getStatus() == "warning" ? 1 : 2);
}
getURL() {
return this.url.replace(/^https?:\/\/w?w?w?\.?/, 'www.');
}
}
//Torna true se il sito non è interno all'azienda
function isNotInternalSite(inputString) {
for (let regex of sitesToExclude) {
if (regex.test(inputString)) {
return false;
}
}
return true;
}
function formatDateDMY(date) {
let day = String(date.getDate()).padStart(2, '0');
let month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
let year = date.getFullYear();
return `${day}/${month}/${year}`;
}
function formatDateYMD(date) {
let day = String(date.getDate()).padStart(2, '0');
let month = String(date.getMonth() + 1).padStart(2, '0'); // Months are zero-based
let year = date.getFullYear();
return `${year}_${month}_${day}`;
}
function estimatedTime() {
return Math.ceil(sites.length / 28) * 10;
}
function urlify(url) {
let strippedURL = url.replaceAll(' ', '').replaceAll('\r', '')
let formattedURL = '';
// Search the pattern
if (!/^https?:\/\//i.test(strippedURL)) {
// If not exist then add http
formattedURL = 'http://' + strippedURL;
} else {
if(/^https:\/\//i.test(strippedURL)) {
formattedURL = strippedURL.replace(/^https:\/\//i, 'http://');
}
}
// Return the URL
return formattedURL;
}
//Scarica un file
function downloadBlob(content, filename, contentType) {
// Create a blob
var blob = new Blob([content], { type: contentType });
var url = URL.createObjectURL(blob);
// Create a link to download it
var pom = document.createElement('a');
pom.href = url;
pom.setAttribute('download', filename);
pom.click();
}
</script>