Non puoi selezionare più di 25 argomenti
Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
2623 righe
66 KiB
2623 righe
66 KiB
<?php |
|
|
|
use Google\Cloud\Translate\V3\TranslationServiceClient; |
|
|
|
if (!defined("AES_256_CBC")) { |
|
define('AES_256_CBC', 'aes-256-cbc'); |
|
} |
|
|
|
function smart_replace_accents($str) |
|
{ |
|
$str = htmlentities($str, ENT_COMPAT, "UTF-8"); |
|
$str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $str); |
|
return html_entity_decode($str); |
|
} |
|
|
|
function str_limit($value, $limit, $end = "...") |
|
{ |
|
if (mb_strwidth($value, 'UTF-8') <= $limit) { |
|
return $value; |
|
} |
|
return rtrim(mb_strimwidth($value, 0, $limit, '', 'UTF-8')) . $end; |
|
} |
|
|
|
function round_to_nearest_multiple(int $n, int $x): int |
|
{ |
|
return $n - $n % $x; |
|
} |
|
|
|
function echo_calendario($data) |
|
{ |
|
$giorno = substr($data, 0, 2); |
|
$mese = substr($data, 3, 2); |
|
$anno = substr($data, 8, 2); |
|
$mesi = array("01" => "GEN", "02" => "FEB", "03" => "MAR", "04" => "APR", "05" => "MAG", "06" => "GIU", "07" => "LUG", "08" => "AGO", "09" => "SET", "10" => "OTT", "11" => "NOV", "12" => "DEC"); |
|
return "<div class=\"calendario\"> |
|
<div class=\"giorno\">" . $giorno . "</div> |
|
<div class=\"mese\">" . $mesi[$mese] . " " . $anno . "</div> |
|
</div>"; |
|
} |
|
|
|
function sanitize_string($str, $replace = array(), $delimiter = '-', $lower = true) |
|
{ |
|
if (!empty($replace)) { |
|
$str = str_replace((array) $replace, ' ', $str); |
|
} |
|
|
|
$unwanted_array = array( |
|
'Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E', |
|
'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U', |
|
'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c', |
|
'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', |
|
'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y' |
|
); |
|
$clean = strtr($str, $unwanted_array); |
|
$clean = utf8_encode($str); |
|
$clean = preg_replace("/[^a-zA-Z0-9\.\/_|+ -]/", '', $clean); |
|
$clean = trim($clean, '-'); |
|
if ($lower) { |
|
$clean = strtolower($clean); |
|
} |
|
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean); |
|
$clean = str_replace("..", ".", $clean); |
|
return $clean; |
|
} |
|
|
|
function only_simple_chars($str) { |
|
$str = preg_replace("/(\&#?[a-zA-Z0-9]+;)/","-",$str); |
|
$str = sanitize_string($str); |
|
return $str; |
|
} |
|
|
|
function normal_text($string) |
|
{ |
|
$string = strip_tags($string); |
|
return $string; |
|
} |
|
|
|
function makeurl($modulo, $codice, $titolo) |
|
{ |
|
|
|
$titolo = html_entity_decode($titolo); |
|
$titolo = sanitize_string($titolo, "'"); |
|
|
|
if (strlen($titolo) > 200) { |
|
$titolo = substr($titolo, 0, 200); |
|
} |
|
$href = "/" . $modulo . "/id" . $codice . "-" . $titolo; |
|
$href = str_replace(' ', "-", (preg_replace('!\s+!', ' ', $href))); |
|
return $href; |
|
} |
|
|
|
if (!function_exists('url')) { |
|
function url($string) |
|
{ |
|
$protocol = "http"; |
|
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') { |
|
$protocol .= "s"; |
|
} |
|
$string = "{$protocol}://{$_SERVER["SERVER_NAME"]}{$string}"; |
|
return $string; |
|
} |
|
} |
|
|
|
|
|
function replace4URL($stringa) |
|
{ |
|
$stringa = str_replace('"', "", $stringa); |
|
$stringa = str_replace(' ', "-", $stringa); |
|
return $stringa; |
|
} |
|
|
|
function fattoriale($number) |
|
{ |
|
if ($number < 2) { |
|
return 1; |
|
} else { |
|
return ($number * fattoriale($number - 1)); |
|
} |
|
} |
|
|
|
function human_filesize($bytes, $decimals = 2) |
|
{ |
|
$size = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); |
|
$factor = floor((strlen($bytes) - 1) / 3); |
|
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . " " . @$size[$factor]; |
|
} |
|
|
|
function folderSize($dir) |
|
{ |
|
$size = 0; |
|
foreach (glob(rtrim($dir, '/') . '/*', GLOB_NOSORT) as $each) { |
|
$size += is_file($each) ? filesize($each) : folderSize($each); |
|
} |
|
return $size; |
|
} |
|
|
|
if (!function_exists('simple_encrypt')) { |
|
function simple_encrypt($text, $salt) |
|
{ |
|
ini_set("memory_limit", "10G"); |
|
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(AES_256_CBC)); |
|
return trim(openssl_encrypt($text, AES_256_CBC, $salt, 0, $iv) . ":" . base64_encode($iv)); |
|
} |
|
} |
|
|
|
if (!function_exists('simple_decrypt')) { |
|
function simple_decrypt($text, $salt) |
|
{ |
|
ini_set("memory_limit", "10G"); |
|
$parts = explode(':', $text); |
|
return openssl_decrypt($parts[0], AES_256_CBC, $salt, 0, base64_decode($parts[1])); |
|
} |
|
} |
|
|
|
function getName($nomefile, $destinazione) |
|
{ |
|
$numero = 0; |
|
$percorso = $destinazione; |
|
$nome_documento_doc = sanitize_string($nomefile); |
|
$percorso_nomefile = $percorso . $nome_documento_doc; |
|
while (file_exists($percorso_nomefile)) { |
|
$numero++; |
|
$percorso_nomefile = $percorso . $numero . "-" . $nome_documento_doc; |
|
} |
|
if ($numero > 0) { |
|
$nome_documento_doc = $numero . "-" . $nome_documento_doc; |
|
} |
|
return $nome_documento_doc; |
|
} |
|
|
|
function copiafile_chunck($nomefile, $destinazione, $chunk_folder, $nome_destinazione = "", $elimina = true) |
|
{ |
|
if (strpos($nomefile, "../") === false) { |
|
$numero = 0; |
|
$percorso = $destinazione; |
|
if ($nome_destinazione == "") { |
|
$nome_documento_doc = sanitize_string($nomefile); //SELEZIONIAMO DALL'ARRAY IL NOME EFFETTIVO DEL FILE |
|
$percorso_nomefile = $percorso . $nome_documento_doc; |
|
while (file_exists($percorso_nomefile)) { |
|
$numero++; |
|
$percorso_nomefile = $percorso . $numero . "-" . $nome_documento_doc; |
|
} |
|
if ($numero > 0) { |
|
$nome_documento_doc = $numero . "-" . $nome_documento_doc; |
|
} |
|
} else { |
|
$percorso_nomefile = $percorso . $nome_destinazione; |
|
$nome_documento_doc = $nome_destinazione; |
|
} |
|
|
|
copy($chunk_folder . "/" . $nomefile, $percorso_nomefile); |
|
if ($elimina) { |
|
unlink($chunk_folder . "/" . $nomefile); |
|
} |
|
return $nome_documento_doc; |
|
} else { |
|
return false; |
|
} |
|
} |
|
|
|
function copiafile($nome_file, $destinazione) |
|
{ |
|
if (strpos($nome_file, "../") === false) { |
|
$nomefile = $nome_file; |
|
|
|
//SCRIPT PER L'UPLOAD DEL DOCUMENTO - SE ESISTE VIENE RINOMINATA ANTEPONENDO UN NUMERO |
|
if (is_uploaded_file($nomefile["tmp_name"])) { |
|
$numero = 0; |
|
$percorso = $destinazione; |
|
$nome_documento_doc = sanitize_string($nomefile["name"]); |
|
$percorso_nomefile = $percorso . $nome_documento_doc; |
|
while (file_exists("$percorso_nomefile")) { |
|
$numero++; |
|
$percorso_nomefile = $percorso . $numero . "-" . $nome_documento_doc; |
|
} |
|
if ($numero > 0) { |
|
//VALORE CHE VA INSERITO NEL DATABASE |
|
$nome_documento_doc = $numero . "-" . $nome_documento_doc; |
|
} |
|
|
|
copy($nomefile["tmp_name"], $percorso_nomefile); |
|
return $nome_documento_doc; |
|
} else { |
|
return false; |
|
} |
|
} |
|
} |
|
// ********************* fine copia file |
|
|
|
function get_string_between($string, $start, $end) |
|
{ |
|
$string = ' ' . $string; |
|
$ini = strpos($string, $start); |
|
if ($ini == 0) { |
|
return ''; |
|
} |
|
$ini += strlen($start); |
|
$len = strpos($string, $end, $ini) - $ini; |
|
return substr($string, $ini, $len); |
|
} |
|
|
|
|
|
function replace_accents($string) |
|
{ |
|
return str_replace(array('à', 'á', 'â', 'ã', 'ä', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'À', 'Á', 'Â', 'Ã', 'Ä', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ù', 'Ú', 'Û', 'Ü', 'Ý'), array('a', 'a', 'a', 'a', 'a', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'A', 'A', 'A', 'A', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'N', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y'), $string); |
|
} |
|
function get_campi($tabella) |
|
{ |
|
$campi = ""; |
|
global $pdo; |
|
$strsql = "DESCRIBE " . $tabella . ";"; |
|
$risultato = $pdo->query($strsql); |
|
|
|
if ($risultato->rowCount() > 0) { |
|
$campi = array(); |
|
while ($record = $risultato->fetch(PDO::FETCH_ASSOC)) { |
|
$campi[$record["Field"]] = ""; |
|
} |
|
} |
|
return $campi; |
|
} |
|
|
|
function oggi() |
|
{ |
|
$today = getdate(); |
|
switch ($today['mday']) { |
|
case "1": |
|
$day = "01"; |
|
break; |
|
case "2": |
|
$day = "02"; |
|
break; |
|
case "3": |
|
$day = "03"; |
|
break; |
|
case "4": |
|
$day = "04"; |
|
break; |
|
case "5": |
|
$day = "05"; |
|
break; |
|
case "6": |
|
$day = "06"; |
|
break; |
|
case "7": |
|
$day = "07"; |
|
break; |
|
case "8": |
|
$day = "08"; |
|
break; |
|
case "9": |
|
$day = "09"; |
|
break; |
|
default: |
|
$day = $today['mday']; |
|
} |
|
switch ($today['month']) { |
|
case "January": |
|
$mese = "01"; |
|
break; |
|
case "February": |
|
$mese = "02"; |
|
break; |
|
case "March": |
|
$mese = "03"; |
|
break; |
|
case "April": |
|
$mese = "04"; |
|
break; |
|
case "May": |
|
$mese = "05"; |
|
break; |
|
case "June": |
|
$mese = "06"; |
|
break; |
|
case "July": |
|
$mese = "07"; |
|
break; |
|
case "August": |
|
$mese = "08"; |
|
break; |
|
case "September": |
|
$mese = "09"; |
|
break; |
|
case "October": |
|
$mese = "10"; |
|
break; |
|
case "November": |
|
$mese = "11"; |
|
break; |
|
case "December": |
|
$mese = "12"; |
|
break; |
|
default: |
|
$mese = "01"; |
|
} |
|
return $day . "/" . $mese . "/" . $today['year']; |
|
} |
|
|
|
function mysql2time($mysql_date) |
|
{ |
|
return substr($mysql_date, -5); |
|
} |
|
|
|
function mysql2date($mysql_date) |
|
{ |
|
$anno = substr($mysql_date, 0, 4); |
|
$mese = substr($mysql_date, 5, 2); |
|
$giorno = substr($mysql_date, 8, 2); |
|
$reversed_data = "$giorno/$mese/$anno"; |
|
|
|
if (($reversed_data == "00/00/0000") | ($reversed_data == "//")) { |
|
$reversed_data = ""; |
|
} |
|
|
|
return $reversed_data; |
|
} |
|
|
|
function date2mysql($normal_date) |
|
{ |
|
$anno = substr($normal_date, 6, 4); |
|
$mese = substr($normal_date, 3, 2); |
|
$giorno = substr($normal_date, 0, 2); |
|
$reversed_data = "$anno-$mese-$giorno"; |
|
|
|
if ($reversed_data == "--") { |
|
$reversed_data = ""; |
|
} |
|
|
|
return $reversed_data; |
|
} |
|
function mysql2completedate($mysql_date) |
|
{ |
|
$mesi = array( |
|
1 => 'Gennaio', 'Febbraio', 'Marzo', 'Aprile', |
|
'Maggio', 'Giugno', 'Luglio', 'Agosto', |
|
'Settembre', 'Ottobre', 'Novembre', 'Dicembre' |
|
); |
|
|
|
$giorni = array( |
|
'Domenica', 'Lunedi', 'Martedi', 'Mercoledi', |
|
'Giovedi', 'Venerdi', 'Sabato' |
|
); |
|
list($sett, $giorno, $mese, $anno, $ora) = explode('-', date('w-d-n-Y-H:i', strtotime($mysql_date))); |
|
return $giorni[$sett] . " - " . $giorno . " " . $mesi[$mese] . " " . $anno . " - " . $ora; |
|
} |
|
function mysql2datetime($mysql_date) |
|
{ |
|
$anno = substr($mysql_date, 0, 4); |
|
$mese = substr($mysql_date, 5, 2); |
|
$giorno = substr($mysql_date, 8, 2); |
|
$ora = substr($mysql_date, 11, 2); |
|
$minuti = substr($mysql_date, 14, 2); |
|
$reversed_data = "$giorno/$mese/$anno $ora:$minuti"; |
|
|
|
if (($reversed_data == "00/00/0000 00:00") || ($reversed_data == "// :")) { |
|
$reversed_data = ""; |
|
} |
|
|
|
return $reversed_data; |
|
} |
|
|
|
function datetime2mysql($normal_date) |
|
{ |
|
$anno = substr($normal_date, 6, 4); |
|
$mese = substr($normal_date, 3, 2); |
|
$giorno = substr($normal_date, 0, 2); |
|
$ora = substr($normal_date, 11, 2); |
|
$minuti = substr($normal_date, 14, 2); |
|
$reversed_data = "$anno-$mese-$giorno $ora:$minuti"; |
|
|
|
if ($reversed_data == "--") { |
|
$reversed_data = ""; |
|
} |
|
|
|
return $reversed_data; |
|
} |
|
|
|
function dateFromCF($cf, $format = "mysql") |
|
{ |
|
$anno = substr($cf, 6, 2); |
|
$anno_maggiorenne = date('Y') - 18; |
|
$anno = ((2000 + $anno) > $anno_maggiorenne) ? "19" . $anno : "20" . $anno; |
|
$mese = substr($cf, 8, 1); |
|
switch ($mese) { // attenzione le lettere non sono in successione alfabetica |
|
case 'A': |
|
$mese = "01"; |
|
break; |
|
case 'B': |
|
$mese = "02"; |
|
break; |
|
case 'C': |
|
$mese = "03"; |
|
break; |
|
case 'D': |
|
$mese = "04"; |
|
break; |
|
case 'E': |
|
$mese = "05"; |
|
break; |
|
case 'H': |
|
$mese = "06"; |
|
break; |
|
case 'L': |
|
$mese = "07"; |
|
break; |
|
case 'M': |
|
$mese = "08"; |
|
break; |
|
case 'P': |
|
$mese = "09"; |
|
break; |
|
case 'R': |
|
$mese = "10"; |
|
break; |
|
case 'S': |
|
$mese = "11"; |
|
break; |
|
case 'T': |
|
$mese = "12"; |
|
break; |
|
default: |
|
$mese = "01"; |
|
break; |
|
} |
|
|
|
$giorno = substr($cf, 9, 2); |
|
if ($giorno > 40) { |
|
$giorno -= 40; |
|
if ($giorno < 10) { |
|
$giorno = "0" . $giorno; |
|
} |
|
} |
|
|
|
$data = ""; |
|
switch ($format) { |
|
case 'it': |
|
$data = $giorno . "/" . $mese . "/" . $anno; |
|
break; |
|
default: |
|
$data = $anno . "-" . $mese . "-" . $giorno; |
|
break; |
|
} |
|
return $data; |
|
} |
|
|
|
function getCategorieServiziTecnici() |
|
{ |
|
global $pdo; |
|
$risultato = $pdo->go("SELECT * FROM b_categorie_progettazione WHERE attivo = 'S'"); |
|
if ($risultato->rowCount() > 0) { |
|
$tmp = []; |
|
while ($cat = $risultato->fetch(PDO::FETCH_ASSOC)) { |
|
$tmp[$cat["codice"]] = $cat; |
|
} |
|
return $tmp; |
|
} |
|
return false; |
|
} |
|
|
|
function getCategorieSOA() |
|
{ |
|
global $pdo; |
|
$risultato = $pdo->go("SELECT * FROM b_categorie_soa WHERE attivo = 'S'"); |
|
if ($risultato->rowCount() > 0) { |
|
$tmp = []; |
|
while ($cat = $risultato->fetch(PDO::FETCH_ASSOC)) { |
|
$tmp[$cat["codice"]] = $cat; |
|
} |
|
return $tmp; |
|
} |
|
return false; |
|
} |
|
|
|
function getClassificheSOA() |
|
{ |
|
global $pdo; |
|
$risultato = $pdo->go("SELECT * FROM b_classifiche_soa WHERE attivo = 'S'"); |
|
if ($risultato->rowCount() > 0) { |
|
$tmp = []; |
|
while ($cat = $risultato->fetch(PDO::FETCH_ASSOC)) { |
|
$cat["descrizione"] = ""; |
|
if (!empty($cat["minimo"])) { |
|
$cat["descrizione"] .= " - " . number_format($cat["minimo"], 0, ",", "."); |
|
} |
|
$cat["descrizione"] .= (!empty($cat["massimo"])) ? (" - " . number_format($cat["massimo"], 0, ",", ".")) : " e oltre"; |
|
$tmp[$cat["codice"]] = $cat; |
|
} |
|
return $tmp; |
|
} |
|
return false; |
|
} |
|
|
|
function getClassificaSOAFromImporto($importo) |
|
{ |
|
$classifiche = getClassificheSOA(); |
|
foreach ($classifiche as $id => $classifica) { |
|
if ((empty($classifica["minimo"]) || $classifica["minimo"] <= $importo) && (empty($classifica["massimo"]) || $classifica["massimo"] >= $importo)) { |
|
return $id; |
|
} |
|
} |
|
} |
|
|
|
//************* funzione log |
|
|
|
function scriviLog($nometab, $operazione, $istruzione, $id_record = 0) |
|
{ |
|
global $todayDbLogPath; |
|
if ($operazione != "ACCESSO" && $operazione != "LOGIN-ATTEMPT") { |
|
$istruzione = base64_encode($istruzione); |
|
} |
|
$codoperatore = 0; |
|
if (!empty($_SESSION["utente"])) { |
|
$codoperatore = $_SESSION["utente"]->codice; |
|
} |
|
if (empty($codoperatore) && $operazione == "ACCESSO") { |
|
$codoperatore = $id_record; |
|
} |
|
$tmp = []; |
|
$tmp[] = date("Y-m-d H:i:s"); |
|
$tmp[] = (!empty($_SESSION["ente"])) ? $_SESSION["ente"]->codice : 0; |
|
$tmp[] = $codoperatore; |
|
$tmp[] = $nometab; |
|
$tmp[] = $operazione; |
|
$tmp[] = $_SERVER["REMOTE_ADDR"] ?? ''; |
|
$tmp[] = $istruzione; |
|
$message = implode(";", $tmp); |
|
file_put_contents($todayDbLogPath, $message . "\n", FILE_APPEND); |
|
} |
|
|
|
|
|
function suddivisione_pdo($richiesta, $nomecampo, $suffix = "") |
|
{ |
|
|
|
$cond = ""; |
|
$bind = array(); |
|
$i = 0; |
|
if (is_array($richiesta)) { |
|
foreach ($richiesta as $parola) { |
|
$i++; |
|
if (strlen($parola) > 0) { |
|
$bind[":" . $suffix . "parola_" . $i] = "%" . $parola . "%"; |
|
$cond .= $nomecampo . " like :" . $suffix . "parola_" . $i . " OR "; |
|
} |
|
} |
|
$cond = substr($cond, 0, strlen($cond) - 3); //per eliminare l'ultimo OR |
|
} else { |
|
if (strlen($richiesta) > 0) { |
|
$i++; |
|
$bind[":" . $suffix . "parola_" . $i] = "%" . $richiesta . "%"; |
|
$cond .= $nomecampo . " like :" . $suffix . "parola_" . $i . " "; |
|
} |
|
} |
|
return array("sql" => $cond, "bind" => $bind); |
|
} |
|
|
|
function genpwd($cnt) |
|
{ |
|
$pwd = str_shuffle('abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'); |
|
return substr($pwd, 0, $cnt); |
|
} |
|
|
|
function generateStrongPassword($length = 9, $add_dashes = false, $available_sets = 'luds') |
|
{ |
|
$sets = []; |
|
if (strpos($available_sets, 'l') !== false) { |
|
$sets[] = 'abcdefghjkmnpqrstuvwxyz'; |
|
} |
|
if (strpos($available_sets, 'u') !== false) { |
|
$sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ'; |
|
} |
|
if (strpos($available_sets, 'd') !== false) { |
|
$sets[] = '23456789'; |
|
} |
|
if (strpos($available_sets, 's') !== false) { |
|
$sets[] = '!@#$%&*?'; |
|
} |
|
$all = $password = $dash_str = ''; |
|
foreach ($sets as $set) { |
|
$password .= $set[array_rand(str_split($set))]; |
|
$all .= $set; |
|
} |
|
$all = str_split($all); |
|
for ($i = 0; $i < $length - count($sets); $i++) { |
|
$password .= $all[array_rand($all)]; |
|
} |
|
$password = str_shuffle($password); |
|
if (!$add_dashes) { |
|
return $password; |
|
} |
|
$dash_len = floor(sqrt($length)); |
|
while (strlen($password) > $dash_len) { |
|
$dash_str .= substr($password, 0, $dash_len) . '-'; |
|
$password = substr($password, $dash_len); |
|
} |
|
$dash_str .= $password; |
|
return $dash_str; |
|
} |
|
|
|
function randomPassword($len = 8) |
|
{ |
|
/* Programmed by Christian Haensel |
|
** christian@chftp.com |
|
** http://www.chftp.com |
|
** |
|
** Exclusively published on weberdev.com. |
|
** If you like my scripts, please let me know or link to me. |
|
** You may copy, redistribute, change and alter my scripts as |
|
** long as this information remains intact. |
|
** |
|
** Modified by Josh Hartman on 12/30/2010. |
|
*/ |
|
if (($len % 2) !== 0) { // Length paramenter must be a multiple of 2 |
|
$len = 8; |
|
} |
|
$length = $len - 2; // Makes room for the two-digit number on the end |
|
$conso = array('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'); |
|
$vocal = array('a', 'e', 'i', 'o', 'u'); |
|
$password = ''; |
|
srand((float) microtime() * 1000000); |
|
$max = $length / 2; |
|
for ($i = 1; $i <= $max; $i++) { |
|
$password .= $conso[rand(0, 19)]; |
|
$password .= $vocal[rand(0, 4)]; |
|
} |
|
$password .= rand(10, 99); |
|
return $password; |
|
} |
|
|
|
function getThemes() |
|
{ |
|
global $beRoot; |
|
$themes = jsonToArray($beRoot . "/customize/themes.json"); |
|
if (is_array($themes) && !empty($themes)) { |
|
foreach ($themes as $key => $theme) { |
|
if (empty($theme["active"])) { |
|
unset($themes[$key]); |
|
} |
|
} |
|
} |
|
return $themes; |
|
} |
|
|
|
function color_luminance($hex, $percent) |
|
{ |
|
|
|
$hex = preg_replace('/[^0-9a-f]/i', '', $hex); |
|
$new_hex = ''; |
|
|
|
if (strlen($hex) < 6) { |
|
$hex = $hex[0] + $hex[0] + $hex[1] + $hex[1] + $hex[2] + $hex[2]; |
|
} |
|
|
|
for ($i = 0; $i < 3; $i++) { |
|
$dec = hexdec(substr($hex, $i * 2, 2)); |
|
$dec = min(max(0, $dec + $dec * $percent), 255); |
|
$new_hex .= str_pad(dechex($dec), 2, 0, STR_PAD_LEFT); |
|
} |
|
|
|
return $new_hex; |
|
} |
|
|
|
function dayDiff($date_1, $date_2) |
|
{ |
|
$date1 = date_create($date_1); |
|
$date2 = date_create($date_2); |
|
$diff = date_diff($date1, $date2); |
|
return $diff->format("%a"); |
|
} |
|
|
|
function differenza_ore($ora1, $ora2, $sep) |
|
{ |
|
$part = explode($sep, $ora1); |
|
$arr = explode($sep, $ora2); |
|
$diff = mktime($arr[0], $arr[1]) - mktime($part[0], $part[1]); |
|
$ore = floor($diff / (60 * 60)); |
|
$minuti = ($diff / 60) % 60; |
|
$ore = str_pad($ore, 2, 0, STR_PAD_LEFT); |
|
$minuti = str_pad($minuti, 2, 0, STR_PAD_LEFT); |
|
return $ore . ":" . $minuti; |
|
} |
|
function somma_ore($ora1, $ora2, $sep) |
|
{ |
|
$ora1 = explode($sep, $ora1); |
|
$ora2 = explode($sep, $ora2); |
|
$ore = $ora1[0] + $ora2[0]; |
|
$minuti = $ora1[1] + $ora2[1]; |
|
if ($minuti > 59) { |
|
$minuti = $minuti - 60; |
|
$ore += 1; |
|
} |
|
$ore = str_pad($ore, 2, 0, STR_PAD_LEFT); |
|
$minuti = str_pad($minuti, 2, 0, STR_PAD_LEFT); |
|
return $ore . ":" . $minuti; |
|
} |
|
|
|
function get_client_ip() |
|
{ |
|
$ipaddress = ''; |
|
if (isset($_SERVER['HTTP_CLIENT_IP'])) { |
|
$ipaddress = $_SERVER['HTTP_CLIENT_IP']; |
|
} else if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { |
|
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; |
|
} else if (isset($_SERVER['HTTP_X_FORWARDED'])) { |
|
$ipaddress = $_SERVER['HTTP_X_FORWARDED']; |
|
} else if (isset($_SERVER['HTTP_FORWARDED_FOR'])) { |
|
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR']; |
|
} else if (isset($_SERVER['HTTP_FORWARDED'])) { |
|
$ipaddress = $_SERVER['HTTP_FORWARDED']; |
|
} else if (isset($_SERVER['REMOTE_ADDR'])) { |
|
$ipaddress = $_SERVER['REMOTE_ADDR']; |
|
} else { |
|
|
|
$ipaddress = 'UNKNOWN'; |
|
} |
|
|
|
return $ipaddress; |
|
} |
|
|
|
function is_dir_empty($dir) |
|
{ |
|
if (!is_readable($dir)) { |
|
return NULL; |
|
} |
|
|
|
return (count(scandir($dir)) == 2); |
|
} |
|
|
|
function getBrowser() |
|
{ |
|
$u_agent = $_SERVER['HTTP_USER_AGENT']; |
|
$bname = 'Unknown'; |
|
$platform = 'Unknown'; |
|
$version = ""; |
|
|
|
//First get the platform? |
|
if (preg_match('/linux/i', $u_agent)) { |
|
$platform = 'linux'; |
|
} else if (preg_match('/macintosh|mac os x/i', $u_agent)) { |
|
$platform = 'mac'; |
|
} else if (preg_match('/windows|win32/i', $u_agent)) { |
|
$platform = 'windows'; |
|
} |
|
|
|
// Next get the name of the useragent yes seperately and for good reason |
|
if (preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent)) { |
|
$bname = 'Internet Explorer'; |
|
$ub = "MSIE"; |
|
} else if (preg_match('/Firefox/i', $u_agent)) { |
|
$bname = 'Mozilla Firefox'; |
|
$ub = "Firefox"; |
|
} else if (preg_match('/Chrome/i', $u_agent)) { |
|
$bname = 'Google Chrome'; |
|
$ub = "Chrome"; |
|
} else if (preg_match('/Safari/i', $u_agent)) { |
|
$bname = 'Apple Safari'; |
|
$ub = "Safari"; |
|
} else if (preg_match('/Opera/i', $u_agent)) { |
|
$bname = 'Opera'; |
|
$ub = "Opera"; |
|
} else if (preg_match('/Netscape/i', $u_agent)) { |
|
$bname = 'Netscape'; |
|
$ub = "Netscape"; |
|
} |
|
|
|
// finally get the correct version number |
|
$known = array('Version', $ub, 'other'); |
|
$pattern = '#(?<browser>' . join('|', $known) . |
|
')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#'; |
|
if (!preg_match_all($pattern, $u_agent, $matches)) { |
|
// we have no matching number just continue |
|
} |
|
|
|
// see how many we have |
|
$i = count($matches['browser']); |
|
if ($i != 1) { |
|
//we will have two since we are not using 'other' argument yet |
|
//see if version is before or after the name |
|
if (strripos($u_agent, "Version") < strripos($u_agent, $ub)) { |
|
$version = $matches['version'][0]; |
|
} else { |
|
$version = $matches['version'][1]; |
|
} |
|
} else { |
|
$version = $matches['version'][0]; |
|
} |
|
|
|
// check if we have a number |
|
if ($version == null || $version == "") { |
|
$version = "?"; |
|
} |
|
|
|
return array( |
|
'userAgent' => $u_agent, |
|
'name' => $bname, |
|
'version' => $version, |
|
'platform' => $platform, |
|
'pattern' => $pattern, |
|
); |
|
} |
|
|
|
function deleteDir($dirPath) |
|
{ |
|
if (!is_dir($dirPath)) { |
|
throw new InvalidArgumentException("$dirPath deve essere una directory"); |
|
} |
|
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') { |
|
$dirPath .= '/'; |
|
} |
|
$files = glob($dirPath . '*', GLOB_MARK); |
|
foreach ($files as $file) { |
|
if (is_dir($file)) { |
|
deleteDir($file); |
|
} else { |
|
unlink($file); |
|
} |
|
} |
|
rmdir($dirPath); |
|
} |
|
|
|
|
|
function array2XML($array, $last_key = "", $no_empty = false, $include_empty = false, $sanitize = false) |
|
{ |
|
$xml = ""; |
|
foreach ($array as $key => $element) { |
|
if ($include_empty || !empty($element)) { |
|
$open_tag = $key; |
|
$close_tag = $key; |
|
$ignore_tag = false; |
|
if ($key === '$') { |
|
$open_tag = ""; |
|
$close_tag = ""; |
|
} else if (is_numeric($key)) { |
|
$open_tag = $last_key; |
|
$close_tag = $last_key; |
|
} |
|
|
|
$attribute = ""; |
|
if (is_array($element)) { |
|
foreach ($element as $sub_key => $sub_element) { |
|
if (strpos($sub_key, "@") === 0) { |
|
$sub_element = trim($sub_element); |
|
if (!$no_empty || ($no_empty && strlen($sub_element) > 0)) { |
|
if ($sanitize) { |
|
$sub_element = str_replace(['&', '&', '&', "'", '"'], ['e', 'e', 'e', 'e', '', ''], $sub_element); |
|
$sub_element = smart_replace_accents($sub_element); |
|
} |
|
$attribute .= " " . ltrim($sub_key, "@") . "=\"" . $sub_element . "\""; |
|
} |
|
unset($element[$sub_key]); |
|
} |
|
if (is_numeric($sub_key)) { |
|
$ignore_tag = true; |
|
} |
|
} |
|
if (!empty($open_tag) && !$ignore_tag) { |
|
$xml .= "<" . $open_tag; |
|
if (!empty($attribute)) { |
|
$xml .= " " . $attribute; |
|
} |
|
$xml .= ">"; |
|
} |
|
$xml .= array2XML($element, $open_tag, $no_empty, $include_empty, $sanitize); |
|
if ($close_tag && !$ignore_tag) { |
|
$xml .= "</" . $close_tag . ">\n"; |
|
} |
|
} else { |
|
if (!empty($open_tag)) { |
|
$xml .= "<" . $open_tag . ">"; |
|
} |
|
if ($sanitize) { |
|
$element = str_replace(['&', '&', '&', "'", '"'], ['e', 'e', 'e', 'e', '', ''], $element); |
|
$element = smart_replace_accents($element); |
|
} |
|
$xml .= $element; |
|
if ($close_tag) { |
|
$xml .= "</" . $close_tag . ">\n"; |
|
} |
|
} |
|
} |
|
} |
|
return $xml; |
|
} |
|
|
|
function getTypeAndExtension($file, $buffer = false) |
|
{ |
|
$return = array(); |
|
global $config; |
|
$finfo = finfo_open(FILEINFO_MIME_TYPE); |
|
if (!$buffer) { |
|
if (file_exists($file)) { |
|
$type = finfo_file($finfo, $file); |
|
} |
|
} else { |
|
$type = finfo_buffer($finfo, $file); |
|
} |
|
if (isset($type)) { |
|
$return["type"] = $type; |
|
if ($type == "application/octet-stream") { |
|
$return["ext"] = ".p7m"; |
|
if ($buffer) { |
|
$tmpPath = $config["chunk_folder"] . "/" . session_id() . rand() . time(); |
|
if (file_put_contents($tmpPath, $file)) { |
|
$file = $tmpPath; |
|
} |
|
} |
|
$p7m = new P7Manager($file); |
|
$content = $p7m->extract(true); |
|
$ext = getTypeAndExtension($content, true); |
|
if (!empty($ext) && !empty($ext["ext"])) { |
|
$return["ext"] = $ext["ext"] . $return["ext"]; |
|
} |
|
if ($buffer) { |
|
unlink($tmpPath); |
|
} |
|
} else { |
|
$extension = P7Manager::extFromMime($type); |
|
$return["ext"] = "." . $extension; |
|
} |
|
} |
|
return (!empty($return)) ? $return : false; |
|
} |
|
|
|
function delete_directory($dir) |
|
{ |
|
if ($handle = opendir($dir)) { |
|
while (false !== ($file = readdir($handle))) { |
|
if ($file != "." && $file != "..") { |
|
if (is_dir($dir . $file)) { |
|
if (!@rmdir($dir . $file)) { |
|
delete_directory($dir . $file . '/'); |
|
} |
|
} else { |
|
@unlink($dir . $file); |
|
} |
|
} |
|
} |
|
closedir($handle); |
|
@rmdir($dir); |
|
} |
|
} |
|
|
|
|
|
function removeEmpty($array, $ignore = []) |
|
{ |
|
if (is_array($array)) { |
|
foreach ($array as $key => $value) { |
|
if (is_numeric($key) || in_array($key, $ignore) === false) { |
|
if (is_array($value)) { |
|
$array[$key] = removeEmpty($value, $ignore); |
|
} else { |
|
if (empty($value) && $value !== "0") { |
|
unset($array[$key]); |
|
} |
|
} |
|
} |
|
} |
|
} |
|
return $array; |
|
} |
|
|
|
function googleTranslate($string, $language, $source = "IT") |
|
{ |
|
try { |
|
$translationClient = new TranslationServiceClient(); |
|
$response = $translationClient->translateText( |
|
[$string], |
|
$language, |
|
TranslationServiceClient::locationName('tuttogare-1527696083169', 'global'), |
|
["sourceLanguageCode" => $source] |
|
); |
|
foreach ($response->getTranslations() as $translation) { |
|
return $translation->getTranslatedText(); |
|
} |
|
} catch (\Throwable $th) { |
|
return $string; |
|
} |
|
} |
|
|
|
function getPendingTranslations() |
|
{ |
|
global $config; |
|
$pending = []; |
|
$path = $config["path_vocabolario"] . "/vocabolario.json"; |
|
if (file_exists($path)) { |
|
$checkVocabolario = jsonToArray($config["path_vocabolario"] . "/vocabolario.json"); |
|
if (!empty($checkVocabolario)) { |
|
$pending = []; |
|
foreach ($checkVocabolario as $key => $voce) { |
|
if (!empty($voce["_verify"])) { |
|
$pending[$key] = $voce; |
|
} |
|
} |
|
return $pending; |
|
} |
|
} |
|
return false; |
|
} |
|
|
|
if (!function_exists(("__guue"))) { |
|
function __guue($key, $lang = "", $ucfirst = true) |
|
{ |
|
return $key; |
|
} |
|
} |
|
if (!function_exists("__")) { |
|
function __($key, $lang = "", $ucfirst = true) |
|
{ |
|
if (!empty($key)) { |
|
global $root; |
|
global $config; |
|
if (empty($lang)) { |
|
$lang = (!empty($_SESSION["language"])) ? $_SESSION["language"] : "IT"; |
|
} |
|
$return = $testo = $key; |
|
$found = false; |
|
$key = strtolower($key); |
|
$path = $config["path_vocabolario"] . "/vocabolario.json"; |
|
if (file_exists($path)) { |
|
if (!isset($_SESSION["dictionary"])) { |
|
$_SESSION["dictionary"] = jsonToArray($path); |
|
} |
|
$dictionary = $_SESSION["dictionary"]; |
|
if (!empty($dictionary)) { |
|
if (!empty($dictionary[$key][$lang])) { |
|
$found = true; |
|
$return = $dictionary[$key][$lang]; |
|
} |
|
if (!$found && !file_exists($config["path_vocabolario"] . "/vocabolario.lock") && !empty($config["traduzioniAttive"]) && $config["developEnv"]) { |
|
touch($config["path_vocabolario"] . "/vocabolario.lock"); |
|
$lang_disp = jsonToArray($root . "/inc/language-available.json"); |
|
$lang_disp = array_keys($lang_disp); |
|
$tmp[$key] = []; |
|
foreach ($lang_disp as $language) { |
|
$found = false; |
|
if (!empty($dictionary[$key][$language])) { |
|
$found = true; |
|
$tmp[$key][$language] = $dictionary[$key][$language]; |
|
} else { |
|
if ($language == "IT") { |
|
$tmp[$key]["IT"] = $testo; |
|
} else { |
|
$tmp[$key][$language] = googleTranslate($testo, $language); |
|
} |
|
} |
|
} |
|
if (!empty($tmp[$key][$lang])) { |
|
$return = $tmp[$key][$lang]; |
|
} |
|
if (!$found) { |
|
$tmp[$key]["_verify"] = 1; |
|
} |
|
$dictionary = array_merge($dictionary, $tmp); |
|
$dictionary = array_filter($dictionary); |
|
ksort($dictionary); |
|
$_SESSION["dictionary"] = $dictionary; |
|
$dictionary = json_encode($dictionary, JSON_PRETTY_PRINT); |
|
file_put_contents($path, $dictionary); |
|
unlink($config["path_vocabolario"] . "/vocabolario.lock"); |
|
} |
|
} else { |
|
if ($config["developEnv"]) { |
|
die("Errore vocabolario"); |
|
} |
|
} |
|
} else { |
|
if ($config["developEnv"]) { |
|
die("Errore vocabolario"); |
|
} |
|
} |
|
if ($ucfirst) { |
|
$return = ucfirst($return); |
|
} |
|
return $return; |
|
} |
|
} |
|
} |
|
|
|
function arrayToCsv(array &$fields, $delimiter = ';', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false) |
|
{ |
|
$delimiter_esc = preg_quote($delimiter, '/'); |
|
$enclosure_esc = preg_quote($enclosure, '/'); |
|
|
|
$output = array(); |
|
foreach ($fields as $field) { |
|
if ($field === null && $nullToMysqlNull) { |
|
$output[] = 'NULL'; |
|
continue; |
|
} |
|
|
|
// Enclose fields containing $delimiter, $enclosure or whitespace |
|
if ($encloseAll || preg_match("/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field)) { |
|
$output[] = $enclosure . str_replace($enclosure, $enclosure . $enclosure, $field) . $enclosure; |
|
} else { |
|
$output[] = $field; |
|
} |
|
} |
|
|
|
return implode($delimiter, $output); |
|
} |
|
|
|
function tokenGen() |
|
{ |
|
if (empty($_SESSION["token"])) { |
|
$_SESSION['token'] = bin2hex(random_bytes(32)); |
|
} |
|
return $_SESSION['token']; |
|
} |
|
|
|
function tokenVerify($token = "") |
|
{ |
|
if (empty($token) && !empty($_POST["token"])) { |
|
$token = $_POST["token"]; |
|
} |
|
$return = false; |
|
if (!empty($_SESSION["token"]) && !empty($token) && $token == $_SESSION["token"]) { |
|
$return = true; |
|
} |
|
return $return; |
|
} |
|
|
|
function jsonToArray($path) |
|
{ |
|
$return = false; |
|
if (file_exists($path) && (strpos($path, "../") === false)) { |
|
$return = json_decode(file_get_contents($path), true); |
|
} |
|
return $return; |
|
} |
|
|
|
|
|
/** |
|
* Get codice pec from ente |
|
* |
|
* @param int $codiceEnte |
|
* @return int |
|
*/ |
|
function getPEC($codiceEnte) { |
|
global $pdo; |
|
return $pdo->go( |
|
"SELECT codice FROM b_pec WHERE |
|
codice_ente = :codice_ente AND |
|
predefinita = 'S' AND |
|
attivo = 'S' AND |
|
eliminato = 'N'", |
|
[":codice_ente"=>$codiceEnte] |
|
)->fetch(PDO::FETCH_COLUMN) ?? 0; |
|
} |
|
|
|
if (!function_exists("array_merge_recursive_distinct")) { |
|
function array_merge_recursive_distinct(array &$array1, array &$array2) |
|
{ |
|
$merged = $array1; |
|
foreach ($array2 as $key => &$value) { |
|
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) { |
|
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value); |
|
} else { |
|
$merged[$key] = $value; |
|
} |
|
} |
|
return $merged; |
|
} |
|
} |
|
|
|
function getStati($continenti = "") |
|
{ |
|
global $pdo; |
|
$bind = array(); |
|
$sql = "SELECT * FROM b_stati "; |
|
if (!empty($continenti)) { |
|
$sql .= "WHERE ("; |
|
if (!is_array($continenti)) { |
|
$continenti = array($continenti); |
|
} |
|
$i = 0; |
|
foreach ($continenti as $continente) { |
|
$i++; |
|
$bind[":" . $i . "_cont"] = $continente; |
|
$sql .= " continente = :" . $i . "_cont OR "; |
|
} |
|
$sql = substr($sql, 0, -4) . ") "; |
|
} |
|
$sql .= "ORDER BY stato "; |
|
$ris = $pdo->go($sql, $bind); |
|
if ($ris->rowCount() > 0) { |
|
return $ris->fetchAll(PDO::FETCH_ASSOC); |
|
} else { |
|
return false; |
|
} |
|
} |
|
|
|
function getGeoData($source, $value, $result) |
|
{ |
|
$return = array(); |
|
if (!empty($source) && !empty($value) && !empty($result)) { |
|
global $pdo; |
|
$value = html_entity_decode($value); |
|
$bind = array(":value" => $value); |
|
switch ($source) { |
|
case "stato": |
|
$where = "codice_stato = :value AND codice_stato <> '' AND codice_stato IS NOT NULL "; |
|
break; |
|
case "regione": |
|
$where = "regione = :value AND regione <> '' AND regione IS NOT NULL"; |
|
break; |
|
case "provincia": |
|
$where = "provincia = :value AND provincia <> '' AND provincia IS NOT NULL"; |
|
break; |
|
case "comune": |
|
$where = "comune = :value AND comune <> '' AND comune IS NOT NULL"; |
|
break; |
|
default: |
|
return false; |
|
} |
|
if (!empty($where)) { |
|
switch ($result) { |
|
case "regione": |
|
$select = "CONVERT(regione USING utf8)"; |
|
break; |
|
case "provincia": |
|
$select = "CONVERT(sigla_provincia USING utf8) AS sigla_provincia, CONVERT(provincia USING utf8)"; |
|
break; |
|
case "comune": |
|
$select = "CONVERT(comune USING utf8)"; |
|
break; |
|
case "cap": |
|
$select = "CONVERT(cap USING utf8)"; |
|
break; |
|
default: |
|
return false; |
|
} |
|
if (!empty($select)) { |
|
$sql = "SELECT {$select} AS valore FROM b_locations WHERE {$where} GROUP BY " . str_replace("AS sigla_provincia", "", $select) . " ORDER BY " . str_replace("AS sigla_provincia", "", $select); |
|
$ris = $pdo->go($sql, $bind); |
|
if ($ris->rowCount() > 0) { |
|
$tmp = $ris->fetchAll(PDO::FETCH_ASSOC); |
|
$return = []; |
|
foreach ($tmp as $i) { |
|
if (!empty($i["valore"])) { |
|
$return[] = $i; |
|
} |
|
} |
|
} |
|
} |
|
} |
|
} |
|
return $return; |
|
} |
|
|
|
function purify($text) |
|
{ |
|
|
|
$config = HTMLPurifier_Config::createDefault(); |
|
$config->set('Core.Encoding', 'UTF-8'); // replace with your encoding |
|
$config->set('Core.EscapeNonASCIICharacters', true); |
|
$config->set('CSS.Trusted', true); // allow any css |
|
$config->set('CSS.Proprietary', true); // allow any css |
|
$config->set('AutoFormat.RemoveEmpty', true); |
|
$config->set('CSS.AllowedProperties', ['width', 'color', 'background-color', 'margin-left', 'margin-right', 'text-align']); |
|
|
|
$config->set('HTML.AllowedElements', ['table','tbody','thead','tr','th','td','div', 'span', 'p', 's', 'br', 'a', 'h1', 'h2', 'h3', 'h4', 'h5', 'strong', 'em', 'u', 'ul', 'li', 'ol', 'hr', 'blockquote', 'sub', 'sup', 'img','figure']); |
|
$config->set('HTML.AllowedAttributes', '*.style,*.title,*.href,*.src,*.border,*.alt,*.width,*.height,*.title,*.class,*.colspan,*.rowspan'); |
|
$config->set('HTML.DefinitionID', 'enduser-customize.html tutorial'); |
|
$config->set('HTML.DefinitionRev', 1); |
|
if ($def = $config->maybeGetRawHTMLDefinition()) { |
|
$def->addElement('figure', 'Block', 'Optional: (figcaption, Flow) | (Flow, figcaption) | Flow', 'Common'); |
|
} |
|
if ($css = $config->getCSSDefinition()) { |
|
$css->info["width"] = new HTMLPurifier_AttrDef_CSS_Percentage(); |
|
} |
|
|
|
$purifier = new HTMLPurifier($config); |
|
|
|
return $purifier->purify($text); |
|
} |
|
|
|
function purifyInput(&$array) |
|
{ |
|
if (!empty($array)) { |
|
foreach ($array as $key => $value) { |
|
if (!is_array($value)) { |
|
$array[$key] = purify($value); |
|
} else { |
|
$array[$key] = purifyInput($value); |
|
} |
|
} |
|
} |
|
return $array; |
|
} |
|
|
|
function verifyGoogleCaptcha($response) |
|
{ |
|
$return = false; |
|
global $disableCaptcha; |
|
if (!empty($response) && !$disableCaptcha) { |
|
$url = "https://www.google.com/recaptcha/api/siteverify"; |
|
$fields_string = ""; |
|
$fields = array( |
|
'secret' => "6LcIxCcUAAAAAPo8yX2P7ovixGTY8SToUfxieLjI", |
|
'response' => $response, |
|
'remoteip' => $_SERVER["REMOTE_ADDR"] |
|
); |
|
|
|
foreach ($fields as $key => $value) { |
|
$fields_string .= $key . '=' . $value . '&'; |
|
} |
|
$fields_string = rtrim($fields_string, '&'); |
|
|
|
$ch = curl_init(); |
|
curl_setopt($ch, CURLOPT_URL, $url); |
|
curl_setopt($ch, CURLOPT_POST, count($fields)); |
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
|
$result = curl_exec($ch); |
|
curl_close($ch); |
|
$result = json_decode($result, true); |
|
if (isset($result["success"]) && $result["success"] === true && isset($result["hostname"]) && $result["hostname"] == $_SERVER["SERVER_NAME"]) { |
|
$return = true; |
|
} |
|
} |
|
if ($disableCaptcha) { |
|
$return = true; |
|
} |
|
return $return; |
|
} |
|
|
|
function getCurrentDomain() { |
|
return $_SESSION["ente"]->getInfo()["dominio"]; |
|
} |
|
function generatePublicIdentifier(string $tipo_procedura, int $codice_ente, int $codice_procedura) : string { |
|
$hostname = getCurrentDomain(); |
|
return uuidgen_v4("{$hostname}-{$codice_ente}-{$tipo_procedura}-{$codice_procedura}") . "@{$codice_ente}-{$tipo_procedura}-{$codice_procedura}"; |
|
} |
|
|
|
function verifyGoogleCaptchaV3($response) |
|
{ |
|
$score = 0; |
|
global $disableCaptcha; |
|
if (!empty($response) && !$disableCaptcha) { |
|
$url = "https://www.google.com/recaptcha/api/siteverify"; |
|
$fields_string = ""; |
|
$fields = array( |
|
'secret' => "6Lcj75wUAAAAACBqH_bil2j6Ktq53DQ2yC_XbO85", |
|
'response' => $_POST["g-recaptcha-response"], |
|
'remoteip' => $_SERVER["REMOTE_ADDR"] |
|
); |
|
|
|
foreach ($fields as $key => $value) { |
|
$fields_string .= $key . '=' . $value . '&'; |
|
} |
|
$fields_string = rtrim($fields_string, '&'); |
|
|
|
$ch = curl_init(); |
|
curl_setopt($ch, CURLOPT_URL, $url); |
|
curl_setopt($ch, CURLOPT_POST, count($fields)); |
|
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
|
$result = curl_exec($ch); |
|
curl_close($ch); |
|
|
|
$result = json_decode($result, true); |
|
if (isset($result) && $result["success"] === true && $result["action"] == "login" && $result["hostname"] == $_SERVER["SERVER_NAME"]) { |
|
$score = $result["score"]; |
|
} |
|
} |
|
if ($disableCaptcha) { |
|
$score = 1; |
|
} |
|
return $score; |
|
} |
|
|
|
function secondsToTime($seconds, $array = true) |
|
{ |
|
$dtF = new \DateTime('@0'); |
|
$dtT = new \DateTime("@$seconds"); |
|
if ($array) { |
|
$return = array(); |
|
$return["giorni"] = $dtF->diff($dtT)->format('%a'); |
|
$return["ore"] = $dtF->diff($dtT)->format('%h'); |
|
$return["minuti"] = $dtF->diff($dtT)->format('%i'); |
|
$return["secondi"] = $dtF->diff($dtT)->format('%s'); |
|
return $return; |
|
} else { |
|
return $dtF->diff($dtT)->format('%a:%h:%i:%s'); |
|
} |
|
} |
|
|
|
function returnIndicatorStyle($indicatore, $valore) |
|
{ |
|
$style = "color: #000"; |
|
if (!empty($indicatore["values"])) { |
|
foreach ($indicatore["values"] as $riferimento => $colore) { |
|
if (is_array($colore)) { |
|
$count_corrispondenze = 0; |
|
$corrispondenza = 0; |
|
if (isset($colore["min"])) { |
|
$count_corrispondenze++; |
|
if ($colore["min"] < $valore) { |
|
$corrispondenza++; |
|
} |
|
} |
|
if (isset($colore["max"])) { |
|
$count_corrispondenze++; |
|
if ($colore["max"] >= $valore) { |
|
$corrispondenza++; |
|
} |
|
} |
|
if ($count_corrispondenze == $corrispondenza) { |
|
$style = "color: {$colore["color"]}"; |
|
} |
|
} else { |
|
if ($riferimento == $valore) { |
|
$style = "color: {$colore}"; |
|
} |
|
} |
|
} |
|
} |
|
return $style; |
|
} |
|
|
|
function fromCSVtoArray($path) |
|
{ |
|
$return = false; |
|
if (file_exists($path) && (strpos($path, "../") === false)) { |
|
ini_set('auto_detect_line_endings', TRUE); |
|
$handle = fopen($path, "r"); |
|
$array = $fields = array(); |
|
$i = 0; |
|
if ($handle) { |
|
while (($row = fgetcsv($handle, 0, ";")) !== false) { |
|
if (empty($fields)) { |
|
$fields = $row; |
|
continue; |
|
} |
|
foreach ($row as $k => $value) { |
|
$array[$i][$fields[$k]] = $value; |
|
} |
|
$i++; |
|
} |
|
if (feof($handle)) { |
|
$return = $array; |
|
} |
|
} |
|
} |
|
return $return; |
|
} |
|
|
|
function truncate($number, $decimal = 2) |
|
{ |
|
if (strpos($number, ".") !== false) { |
|
if (!is_numeric($decimal)) { |
|
$decimal = 0; |
|
} |
|
$decimal = floor($decimal); |
|
list($intero, $decimali) = explode(".", $number); |
|
if ($decimal > 0) { |
|
return $intero . "." . substr($decimali, 0, $decimal); |
|
} else { |
|
return $intero; |
|
} |
|
} else { |
|
return $number; |
|
} |
|
} |
|
|
|
function make_color($value, $min = 0, $max = .5) |
|
{ |
|
$ratio = $value; |
|
if ($min > 0 || $max < 1) { |
|
if ($value < $min) { |
|
$ratio = 1; |
|
} else if ($value > $max) { |
|
$ratio = 0; |
|
} else { |
|
$range = $min - $max; |
|
$ratio = ($value - $max) / $range; |
|
} |
|
} |
|
|
|
$hue = ($ratio * 1.2) / 3.60; |
|
$rgb = ColorHSLToRGB($hue, 1, .5); |
|
$r = round($rgb['r'], 0); |
|
$g = round($rgb['g'], 0); |
|
$b = round($rgb['b'], 0); |
|
|
|
return "rgb($r,$g,$b)"; |
|
} |
|
|
|
function ColorHSLToRGB($h, $s, $l) |
|
{ |
|
|
|
$r = $l; |
|
$g = $l; |
|
$b = $l; |
|
$v = ($l <= 0.5) ? ($l * (1.0 + $s)) : ($l + $s - $l * $s); |
|
if ($v > 0) { |
|
|
|
$m = $l + $l - $v; |
|
$sv = ($v - $m) / $v; |
|
$h *= 6.0; |
|
$sextant = floor($h); |
|
$fract = $h - $sextant; |
|
$vsf = $v * $sv * $fract; |
|
$mid1 = $m + $vsf; |
|
$mid2 = $v - $vsf; |
|
|
|
switch ($sextant) { |
|
case 0: |
|
$r = $v; |
|
$g = $mid1; |
|
$b = $m; |
|
break; |
|
case 1: |
|
$r = $mid2; |
|
$g = $v; |
|
$b = $m; |
|
break; |
|
case 2: |
|
$r = $m; |
|
$g = $v; |
|
$b = $mid1; |
|
break; |
|
case 3: |
|
$r = $m; |
|
$g = $mid2; |
|
$b = $v; |
|
break; |
|
case 4: |
|
$r = $mid1; |
|
$g = $m; |
|
$b = $v; |
|
break; |
|
case 5: |
|
$r = $v; |
|
$g = $m; |
|
$b = $mid2; |
|
break; |
|
default: |
|
return false; |
|
} |
|
} |
|
return array('r' => $r * 255.0, 'g' => $g * 255.0, 'b' => $b * 255.0); |
|
} |
|
|
|
function calculateLuminosity($color) |
|
{ |
|
|
|
$r = hexdec(substr($color, 0, 2)) / 255; // red value |
|
$g = hexdec(substr($color, 2, 2)) / 255; // green value |
|
$b = hexdec(substr($color, 4, 2)) / 255; // blue value |
|
if ($r <= 0.03928) { |
|
$r = $r / 12.92; |
|
} else { |
|
$r = pow((($r + 0.055) / 1.055), 2.4); |
|
} |
|
|
|
if ($g <= 0.03928) { |
|
$g = $g / 12.92; |
|
} else { |
|
$g = pow((($g + 0.055) / 1.055), 2.4); |
|
} |
|
|
|
if ($b <= 0.03928) { |
|
$b = $b / 12.92; |
|
} else { |
|
$b = pow((($b + 0.055) / 1.055), 2.4); |
|
} |
|
|
|
return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b; |
|
} |
|
|
|
// calculates the luminosity ratio of two colors |
|
// the luminosity ratio equations are from the WCAG 2 requirements |
|
// http://www.w3.org/TR/WCAG20/#contrast-ratiodef |
|
|
|
function calculateLuminosityRatio($color1, $color2) |
|
{ |
|
$l1 = calculateLuminosity($color1); |
|
$l2 = calculateLuminosity($color2); |
|
|
|
if ($l1 > $l2) { |
|
$ratio = (($l1 + 0.05) / ($l2 + 0.05)); |
|
} else { |
|
$ratio = (($l2 + 0.05) / ($l1 + 0.05)); |
|
} |
|
return $ratio; |
|
} |
|
|
|
// returns an array with the results of the color contrast analysis |
|
// it returns akey for each level (AA and AAA, both for normal and large or bold text) |
|
// it also returns the calculated contrast ratio |
|
// the ratio levels are from the WCAG 2 requirements |
|
// http://www.w3.org/TR/WCAG20/#visual-audio-contrast (1.4.3) |
|
// http://www.w3.org/TR/WCAG20/#larger-scaledef |
|
|
|
function evaluateColorContrast($color1, $color2) |
|
{ |
|
$ratio = calculateLuminosityRatio($color1, $color2); |
|
|
|
$colorEvaluation["levelAANormal"] = ($ratio >= 4.5 ? 'pass' : 'fail'); |
|
$colorEvaluation["levelAALarge"] = ($ratio >= 3 ? 'pass' : 'fail'); |
|
$colorEvaluation["levelAAMediumBold"] = ($ratio >= 3 ? 'pass' : 'fail'); |
|
$colorEvaluation["levelAAANormal"] = ($ratio >= 7 ? 'pass' : 'fail'); |
|
$colorEvaluation["levelAAALarge"] = ($ratio >= 4.5 ? 'pass' : 'fail'); |
|
$colorEvaluation["levelAAAMediumBold"] = ($ratio >= 4.5 ? 'pass' : 'fail'); |
|
$colorEvaluation["ratio"] = $ratio; |
|
|
|
return $colorEvaluation; |
|
} |
|
|
|
function getDescrizioneFromTipologia($descrizioni, $data = null) |
|
{ |
|
if (empty($data)) { |
|
$data = time(); |
|
} else { |
|
if (!is_numeric($data)) { |
|
$data = strtotime($data); |
|
} |
|
} |
|
foreach ($descrizioni as $descrizione) { |
|
if ((empty($descrizione["inizio"]) || strtotime($descrizione["inizio"]) <= $data) && (empty($descrizione["fine"]) || strtotime($descrizione["fine"]) >= $data)) { |
|
return $descrizione; |
|
} |
|
} |
|
return false; |
|
} |
|
|
|
function getTipologieAffidamento($attivo = true, $data = null) |
|
{ |
|
global $config; |
|
$return = jsonToArray($config["jsonFolder"] . "/generic-tipologieAffidamento.json"); |
|
if ($attivo) { |
|
$tmp = []; |
|
foreach ($return as $codice => $tipologia) { |
|
if ($tipologia["attivo"]) { |
|
$tmp[$codice] = $tipologia; |
|
} |
|
} |
|
$return = $tmp; |
|
} |
|
return addDescrizioni($return, $data); |
|
} |
|
|
|
function addDescrizioni($array, $data) |
|
{ |
|
if (!empty($array)) { |
|
$tmp = []; |
|
foreach ($array as $key => $tipologia) { |
|
if (isset($tipologia["descrizioni"])) { |
|
$descrizioni = getDescrizioneFromTipologia($tipologia["descrizioni"], $data); |
|
if (!empty($descrizioni)) { |
|
$tipologia += $descrizioni; |
|
} |
|
} |
|
$tmp[$key] = $tipologia; |
|
} |
|
$array = $tmp; |
|
} |
|
return $array; |
|
} |
|
|
|
function getProcedure($all = false, $filtroTipologia = null, $data = null, int $enteBeneficiario = null) |
|
{ |
|
global $config; |
|
$return = jsonToArray($config["jsonFolder"] . "/gare-procedure.json"); |
|
$privato = false; |
|
if (!empty($enteBeneficiario)) { |
|
$ente = Ente::getInfoFromID($enteBeneficiario)[0] ?? null; |
|
if (isset($ente["soggettoPrivato"]) && $ente["soggettoPrivato"] == "S") { |
|
$privato = true; |
|
} |
|
} |
|
$proponiRdoIndagine = settingsManager::getValue("proponiNegoziataConIndagineDiMercato"); |
|
if ($proponiRdoIndagine !== "S") { |
|
unset($return["rdo-indagine"]); |
|
} |
|
|
|
if (!$all) { |
|
$tmp = []; |
|
foreach ($return as $codice => $tipologia) { |
|
if ($tipologia["attivo"] && (!$privato || $tipologia["privata"])) { |
|
$insert = true; |
|
if (!empty($filtroTipologia)) { |
|
$insert = false; |
|
if (is_array($tipologia["tipologie"])) { |
|
if (in_array($filtroTipologia, $tipologia["tipologie"]) !== false) { |
|
$insert = true; |
|
} |
|
} else { |
|
$insert = true; |
|
} |
|
} |
|
if ($insert) { |
|
$tmp[$codice] = $tipologia; |
|
} |
|
} |
|
} |
|
$return = $tmp; |
|
} |
|
return addDescrizioni($return, $data); |
|
} |
|
|
|
function getCriteri($attivo = true, $data = null) |
|
{ |
|
global $config; |
|
$return = jsonToArray($config["jsonFolder"] . "/generic-criteri.json"); |
|
if ($attivo) { |
|
$tmp = []; |
|
foreach ($return as $codice => $tipologia) { |
|
if ($tipologia["attivo"]) { |
|
$tmp[$codice] = $tipologia; |
|
} |
|
} |
|
$return = $tmp; |
|
} |
|
return addDescrizioni($return, $data); |
|
} |
|
|
|
function getModalita($attivo = true, $data = null) |
|
{ |
|
global $config; |
|
$return = jsonToArray($config["jsonFolder"] . "/gare-modalita.json"); |
|
if ($attivo) { |
|
$tmp = []; |
|
foreach ($return as $codice => $tipologia) { |
|
if ($tipologia["attivo"]) { |
|
$tmp[$codice] = $tipologia; |
|
} |
|
} |
|
$return = $tmp; |
|
} |
|
return addDescrizioni($return, $data); |
|
} |
|
|
|
|
|
function getJSON($file) |
|
{ |
|
global $config; |
|
return jsonToArray($config["jsonFolder"] . "/{$file}"); |
|
} |
|
|
|
|
|
function getListeSIMOG() |
|
{ |
|
global $root; |
|
$return = false; |
|
if (file_exists($root . "/inc/liste-simog.xml")) { |
|
require_once($root . "/inc/xml2json.php"); |
|
$schema = simplexml_load_file($root . '/inc/liste-simog.xml'); |
|
$schema = xmlToArray($schema); |
|
if (!empty($schema["schema"]["xsd:simpleType"])) { |
|
$selects = array(); |
|
foreach ($schema["schema"]["xsd:simpleType"] as $select) { |
|
$selects[$select["@name"]] = array(); |
|
foreach ($select["xsd:restriction"]["xsd:enumeration"] as $value) { |
|
$selects[$select["@name"]][$value["@value"]] = (!is_array($value["xsd:annotation"]["xsd:documentation"])) ? $value["xsd:annotation"]["xsd:documentation"] : implode(" - ", $value["xsd:annotation"]["xsd:documentation"]); |
|
} |
|
} |
|
if (!empty($selects)) { |
|
$return = $selects; |
|
} |
|
} |
|
} |
|
ksort($return); |
|
return $return; |
|
} |
|
|
|
function sortPartecipantiTotale($a, $b) |
|
{ |
|
return $a["totale"] < $b["totale"]; |
|
} |
|
function sortInversePartecipantiTotale($a, $b) |
|
{ |
|
return $a["totale"] > $b["totale"]; |
|
} |
|
function sortEsclusi($a, $b) |
|
{ |
|
return strcmp($a["escluso"], $b["escluso"]); |
|
} |
|
function FromUTCtoLocale($date) |
|
{ |
|
$tz_from = new DateTimeZone('UTC'); |
|
$tz_to = new DateTimeZone('Europe/Rome'); |
|
$orig_time = new DateTime($date, $tz_from); |
|
$new_time = $orig_time->setTimezone($tz_to); |
|
return $new_time->format('Y-m-d H:i:s'); |
|
} |
|
function orarioToSecondi($ora) |
|
{ |
|
sscanf($ora, "%d:%d:%d", $hours, $minutes, $seconds); |
|
return isset($hours) ? $hours * 3600 + $minutes * 60 + $seconds : $minutes * 60 + $seconds; |
|
} |
|
|
|
function isAssoc(array $arr) |
|
{ |
|
if (array() === $arr) { |
|
return false; |
|
} |
|
return array_keys($arr) !== range(0, count($arr) - 1); |
|
} |
|
|
|
function HTTPStatus($num) |
|
{ |
|
$http = array( |
|
100 => 'HTTP/1.1 100 Continue', |
|
101 => 'HTTP/1.1 101 Switching Protocols', |
|
200 => 'HTTP/1.1 200 OK', |
|
201 => 'HTTP/1.1 201 Created', |
|
202 => 'HTTP/1.1 202 Accepted', |
|
203 => 'HTTP/1.1 203 Non-Authoritative Information', |
|
204 => 'HTTP/1.1 204 No Content', |
|
205 => 'HTTP/1.1 205 Reset Content', |
|
206 => 'HTTP/1.1 206 Partial Content', |
|
300 => 'HTTP/1.1 300 Multiple Choices', |
|
301 => 'HTTP/1.1 301 Moved Permanently', |
|
302 => 'HTTP/1.1 302 Found', |
|
303 => 'HTTP/1.1 303 See Other', |
|
304 => 'HTTP/1.1 304 Not Modified', |
|
305 => 'HTTP/1.1 305 Use Proxy', |
|
307 => 'HTTP/1.1 307 Temporary Redirect', |
|
400 => 'HTTP/1.1 400 Bad Request', |
|
401 => 'HTTP/1.1 401 Unauthorized', |
|
402 => 'HTTP/1.1 402 Payment Required', |
|
403 => 'HTTP/1.1 403 Forbidden', |
|
404 => 'HTTP/1.1 404 Not Found', |
|
405 => 'HTTP/1.1 405 Method Not Allowed', |
|
406 => 'HTTP/1.1 406 Not Acceptable', |
|
407 => 'HTTP/1.1 407 Proxy Authentication Required', |
|
408 => 'HTTP/1.1 408 Request Time-out', |
|
409 => 'HTTP/1.1 409 Conflict', |
|
410 => 'HTTP/1.1 410 Gone', |
|
411 => 'HTTP/1.1 411 Length Required', |
|
412 => 'HTTP/1.1 412 Precondition Failed', |
|
413 => 'HTTP/1.1 413 Request Entity Too Large', |
|
414 => 'HTTP/1.1 414 Request-URI Too Large', |
|
415 => 'HTTP/1.1 415 Unsupported Media Type', |
|
416 => 'HTTP/1.1 416 Requested Range Not Satisfiable', |
|
417 => 'HTTP/1.1 417 Expectation Failed', |
|
500 => 'HTTP/1.1 500 Internal Server Error', |
|
501 => 'HTTP/1.1 501 Not Implemented', |
|
502 => 'HTTP/1.1 502 Bad Gateway', |
|
503 => 'HTTP/1.1 503 Service Unavailable', |
|
504 => 'HTTP/1.1 504 Gateway Time-out', |
|
505 => 'HTTP/1.1 505 HTTP Version Not Supported', |
|
); |
|
|
|
header($http[$num]); |
|
|
|
return |
|
array( |
|
'code' => $num, |
|
'error' => $http[$num], |
|
); |
|
} |
|
|
|
/** |
|
* Check if array is associative or sequential |
|
* @param Array $array |
|
* @return bool |
|
*/ |
|
function isAssociative(array $array) |
|
{ |
|
if (array() === $array) { |
|
return false; |
|
} |
|
return array_keys($array) !== range(0, count($array) - 1); |
|
} |
|
|
|
|
|
if (!function_exists("is_json")) { |
|
/** |
|
* NON USARE se non strettamente necessario. |
|
* Converte una stringa in json internamente e ritorna TRUE/FALSE |
|
* in base al successo. |
|
* |
|
* Un if di questo genere sostituisce il metodo ed è molto più efficiente |
|
* if(($var = json_decode($json)) !== null) |
|
* |
|
* Oppure usa il metodo valid_json |
|
* |
|
* @param string $string |
|
* @return boolean |
|
*/ |
|
function is_json(string $string) |
|
{ |
|
json_decode($string); |
|
return json_last_error() === JSON_ERROR_NONE; |
|
} |
|
} |
|
if (!function_exists("valid_json")) { |
|
/** |
|
* Converte una stringa in json, la assegna al parametro |
|
* data e ritorna TRUE/FALSE in base al successo. |
|
* |
|
* Uso tipico |
|
* if(valid_json($json, $data)) { |
|
* // Uso di $data |
|
* } |
|
* |
|
* Oppure usa il metodo valid_json |
|
* |
|
* @param string $string |
|
* @param ?object|?array $data |
|
* @param ?bool $associative |
|
* @param int $depth |
|
* @param int $flags |
|
* @return boolean |
|
*/ |
|
function valid_json(string $string, &$data, ?bool $associative = null, int $depth = 512, int $flags = 0) |
|
{ |
|
$data = json_decode($string, $associative, $depth, $flags); |
|
|
|
if($data === NULL || json_last_error() !== JSON_ERROR_NONE) return false; |
|
|
|
if($associative) { |
|
return is_array($data); |
|
} |
|
return is_object($data); |
|
} |
|
} |
|
|
|
if (!function_exists("valid_json_recursive")) { |
|
function valid_json_recursive(string $string, &$data) |
|
{ |
|
$data = json_decode($string, TRUE); |
|
$success = $data !== null && is_array($data) && json_last_error() === JSON_ERROR_NONE; |
|
if($success) { |
|
foreach($data as &$entry) { |
|
valid_json_recursive($entry, $entry); |
|
} |
|
} |
|
return $success; |
|
} |
|
} |
|
|
|
function addBypassCheckURL(string $url) |
|
{ |
|
if (!isset($_SESSION["bypassCheck"])) { |
|
$_SESSION["bypassCheck"] = []; |
|
} |
|
$_SESSION["bypassCheck"][] = $url; |
|
$_SESSION["bypassCheck"] = array_unique($_SESSION["bypassCheck"]); |
|
} |
|
|
|
function adaptMemoryLimitToFile($path, $limit = "4G") |
|
{ |
|
if (file_exists($path)) { |
|
$size = filesize($path); |
|
if ($size > 500 * 1024 * 1024) { |
|
$limit = "-1"; |
|
} |
|
$actual_memory = ini_get("memory_limit"); |
|
if ($actual_memory != "-1" && $actual_memory != "4G" && $size > 2000000) { |
|
ini_set("memory_limit", $limit); |
|
ini_set("max_execution_time", "600"); |
|
} |
|
} |
|
} |
|
|
|
function getMatchFrom2($id, $table) |
|
{ |
|
global $pdo; |
|
$getMatch = $pdo->go("SELECT v3 FROM b_matches_v2 WHERE tabella = :tabella AND v2 = :codice", [":tabella" => $table, ":codice" => $id]); |
|
if ($getMatch->rowCount() > 0) { |
|
return $getMatch->fetch(PDO::FETCH_COLUMN); |
|
} |
|
} |
|
|
|
function pluck($key, $data) |
|
{ |
|
|
|
return array_reduce($data, function ($result, $array) use ($key) { |
|
isset($array[$key]) && $result[] = $array[$key]; |
|
return $result; |
|
}, array()); |
|
} |
|
|
|
function group_by($array, $key, $resetKey = true) |
|
{ |
|
|
|
$return = array(); |
|
|
|
foreach ($array as $val) { |
|
$return[$val[$key]][] = $val; |
|
} |
|
|
|
if($resetKey){ |
|
$return = array_values($return); |
|
} |
|
return $return; |
|
} |
|
|
|
function arrayIsNumeric($array) |
|
{ |
|
|
|
$tmp = []; |
|
|
|
if (!empty($array)) { |
|
foreach ($array as $value) { |
|
if (is_numeric($value)) { |
|
$tmp[] = (int)$value; |
|
} |
|
} |
|
} |
|
|
|
return $tmp; |
|
} |
|
|
|
function getMatchFrom3($id, $table) |
|
{ |
|
global $pdo; |
|
$getMatch = $pdo->go("SELECT v2 FROM b_matches_v2 WHERE tabella = :tabella AND v3 = :codice", [":tabella" => $table, ":codice" => $id]); |
|
if ($getMatch->rowCount() > 0) { |
|
return $getMatch->fetch(PDO::FETCH_COLUMN); |
|
} |
|
} |
|
|
|
if (!function_exists('array_is_list')) { |
|
|
|
/** |
|
* Check if array has only numeric keys |
|
* |
|
* @param mixed $arr |
|
* @return void |
|
*/ |
|
function array_is_list(array $arr) |
|
{ |
|
if ($arr === []) { |
|
return true; |
|
} |
|
ksort($arr); |
|
return array_keys($arr) === range(0, count($arr) - 1); |
|
} |
|
} |
|
|
|
if (!function_exists("base64url_encode")) { |
|
|
|
function base64url_encode($data) |
|
{ |
|
|
|
return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); |
|
} |
|
} |
|
|
|
if (!function_exists("base64url_decode")) { |
|
|
|
function base64url_decode($data) |
|
{ |
|
|
|
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); |
|
} |
|
} |
|
|
|
if (!function_exists('value')) { |
|
|
|
/** |
|
* Return the default value of the given value. |
|
* |
|
* @param mixed $value |
|
* @return mixed |
|
*/ |
|
function value($value, ...$args) |
|
{ |
|
return $value instanceof Closure ? $value(...$args) : $value; |
|
} |
|
} |
|
|
|
if (!function_exists("array_set")) { |
|
|
|
/** |
|
* Set an array item to a given value using "dot" notation. |
|
* |
|
* If no key is given to the method, the entire array will be replaced. |
|
* |
|
* @param array $array |
|
* @param string|null $key |
|
* @param mixed $value |
|
* @return array |
|
*/ |
|
function array_set(&$array, $key, $value) |
|
{ |
|
return DotPath::set($array, $key, $value); |
|
} |
|
} |
|
|
|
if (!function_exists("array_get")) { |
|
|
|
/** |
|
* Get an item from an array using "dot" notation. |
|
* |
|
* @param \ArrayAccess|array $array |
|
* @param string|int|null $key |
|
* @param mixed $default |
|
* @return mixed |
|
*/ |
|
function array_get($array, $key, $default = null, $dictionary = false) |
|
{ |
|
return DotPath::get($array, $key, $default, $dictionary); |
|
} |
|
} |
|
|
|
if (!function_exists('array_flatten')) { |
|
|
|
/** |
|
* Convert a multi-dimensional array into a single-dimensional array. |
|
* @author Sean Cannon, LitmusBox.com | seanc@litmusbox.com |
|
* @param array $array The multi-dimensional array. |
|
* @return array|false |
|
*/ |
|
function array_flatten($array) |
|
{ |
|
if (!is_array($array)) { |
|
return false; |
|
} |
|
$result = array(); |
|
foreach ($array as $key => $value) { |
|
if (is_array($value)) { |
|
$result = array_merge($result, array_flatten($value)); |
|
} else { |
|
$result = array_merge($result, array($key => $value)); |
|
} |
|
} |
|
return $result; |
|
} |
|
} |
|
|
|
if (!function_exists('uuidgen')) { |
|
|
|
function uuidgen($data = null) |
|
{ |
|
// Generate 16 bytes (128 bits) of random data or use the data passed into the function. |
|
$data = $data ?? random_bytes(16); |
|
assert(strlen($data) == 16); |
|
|
|
// Set version to 0100 |
|
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); |
|
// Set bits 6-7 to 10 |
|
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); |
|
|
|
// Output the 36 character UUID. |
|
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); |
|
} |
|
|
|
} |
|
if (!function_exists('uuidgen_v4')) { |
|
/** |
|
* Genera un uuidgen v4 RFC 4122 basato su una stringa |
|
* |
|
* @param string $data Dati su cui basare l'uuid |
|
* @return string Stringa secondo questo standard /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}/ |
|
*/ |
|
function uuidgen_v4($data = null) |
|
{ |
|
// Se non ci sono dati generiamo a caso |
|
if(empty($data)) $data = uniqid("uuidgen", true); |
|
// Calcoliamo un hash dei dati |
|
$hash = md5($data, true); |
|
|
|
// Dividiamo in UUID |
|
$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($hash), 4)); |
|
// Assegniamo i valori necessari per RFC 4122 |
|
$uuid[14] = "4"; |
|
switch ($uuid[19]) { |
|
case '0': |
|
case '2': |
|
case '1': |
|
case '3': |
|
$uuid[19] = '8'; |
|
break; |
|
case '4': |
|
case '5': |
|
case '6': |
|
case '7': |
|
$uuid[19] = '9'; |
|
break; |
|
case '8': |
|
case '9': |
|
case 'a': |
|
case 'b': |
|
$uuid[19] = 'a'; |
|
break; |
|
default: |
|
$uuid[19] = 'b'; |
|
break; |
|
} |
|
return $uuid; |
|
} |
|
} |
|
/** |
|
* Genera un uuid v4 rfc4122 casuale |
|
* |
|
* @return string /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}/ |
|
*/ |
|
function uuidgen_guue() { |
|
do { |
|
$uuid = uuidgen(); |
|
} while(preg_match("/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}/", $uuid) !== 1); |
|
return $uuid; |
|
} |
|
// https://stackoverflow.com/questions/4519739/split-camelcase-word-into-words-with-php-preg-match-regular-expression |
|
function camelCaseToWords($ccWord) |
|
{ |
|
if(empty($ccWord)) return $ccWord; |
|
$re = '/(?#! splitCamelCase Rev:20140412) |
|
# Split camelCase "words". Two global alternatives. Either g1of2: |
|
(?<=[a-z]) # Position is after a lowercase, |
|
(?=[A-Z]) # and before an uppercase letter. |
|
| (?<=[A-Z]) # Or g2of2; Position is after uppercase, |
|
(?=[A-Z][a-z]) # and before upper-then-lower case. |
|
/x'; |
|
$a = preg_split($re, $ccWord); |
|
return implode(" ", $a); |
|
} |
|
|
|
if(!function_exists("currency_format")) { |
|
function currency_format($amount, $currency="") { |
|
$amount = (is_numeric($amount)) ? floatval($amount) : 0; |
|
return $currency . number_format($amount, 2, '.', ''); |
|
} |
|
} |
|
|
|
if(!function_exists("die_forbidden")) { |
|
function die_forbidden($override_url = null) |
|
{ |
|
if (php_sapi_name() !== "cli") { |
|
header('HTTP/1.0 403 Forbidden'); |
|
$referer = empty($override_url) ? ($_SERVER["HTTP_REFERER"] ?? "/") : $override_url; |
|
die("<h1>Questa pagina non è disponibile</h1><a href='{$referer}'}>" . __("Ritorna") . "</a>"); |
|
} |
|
} |
|
} |
|
|
|
function rimuoviZeroDecimaliFromDB($number,string $decimalSeparator = ".") { |
|
return trim(rtrim($number,"0"),$decimalSeparator); |
|
} |
|
|
|
function printFormattedNumber($number,int $decimal = null) { |
|
$decimalSeparator = ","; |
|
$thousandSeparator = "."; |
|
if ($decimal > 0) { |
|
$return = number_format($number,2,$decimalSeparator,$thousandSeparator); |
|
} else { |
|
$return = rimuoviZeroDecimaliFromDB(number_format($number,10,$decimalSeparator,$thousandSeparator),$decimalSeparator); |
|
} |
|
if ($return === "") { |
|
$return = 0; |
|
} |
|
return $return; |
|
} |
|
|
|
if(!function_exists("empty_but_not_zero")) { |
|
/** |
|
* Ritorna true se è vuoto ma non zero |
|
* |
|
* @param mixed $val |
|
* @return bool |
|
*/ |
|
function empty_but_not_zero($val) { |
|
if(!isset($val)) return true; |
|
if($val === 0 || $val === "0") return false; |
|
return empty($val); |
|
} |
|
} |
|
|
|
if(!function_exists("tuttogare_api_call")) { |
|
function tuttogare_api_call(string $url, string $token, string $method = "GET", string $body = "") { |
|
$curl = curl_init(); |
|
|
|
curl_setopt($curl, CURLOPT_URL, $url); |
|
|
|
curl_setopt($curl, CURLOPT_MAX_SEND_SPEED_LARGE, 2 * 524288); |
|
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); |
|
curl_setopt($curl, CURLOPT_HEADER, FALSE); |
|
|
|
$headers = [ |
|
"X-Tuttogare-Api-Key: {$token}", |
|
]; |
|
|
|
if($method === "POST") { |
|
curl_setopt($curl, CURLOPT_POST, TRUE); |
|
$headers = array_merge( |
|
$headers, |
|
[ |
|
"Encoding: UTF-8", |
|
"Http-Method: POST", |
|
"Content-Type: application/json", |
|
] |
|
); |
|
} |
|
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); |
|
|
|
curl_setopt($curl, CURLOPT_POSTFIELDS, $body); |
|
return curl_exec($curl); |
|
} |
|
} |
|
|
|
if(!function_exists("emptyArrayMultidimensional")) { |
|
|
|
/** |
|
* Ritorna true se c'è un solo campo vuoto nell'array multidimensionale |
|
* |
|
* @param mixed $val |
|
* @return bool |
|
*/ |
|
function emptyArrayMultidimensional($arr){ |
|
if(!empty($arr)){ |
|
foreach ($arr as $key => $value) { |
|
if(is_array($value)){ |
|
if(emptyArrayMultidimensional($value)){ |
|
return true; |
|
} |
|
}elseif(empty($value)){ |
|
return true; |
|
} |
|
} |
|
} |
|
|
|
return false; |
|
} |
|
} |
|
|
|
if(!function_exists("url_with_params")) { |
|
function url_with_params(string $url, ?array $current_params = null) { |
|
if($current_params === null) $current_params = $_GET; |
|
|
|
$url_split = explode("?", $url); |
|
|
|
parse_str($url_split[1] ?? "", $new_params); |
|
foreach($new_params as $key => $param) { |
|
$current_params[$key] = $param; |
|
} |
|
|
|
return $url_split[0] . "?" . http_build_query($current_params); |
|
} |
|
} |
|
|
|
if(!function_exists("html_alert")) { |
|
function html_alert(string $message, string $title="Attenzione", string $type = "danger", string $icon = "fa fa-exclamation-triangle") { |
|
?> |
|
<div class="alert alert-<?= $type ?>"> |
|
<h5> |
|
<i class="<?= $icon ?> mr-2"></i> |
|
<?= __($title) ?> |
|
</h5> |
|
<p> |
|
<?= __($message) ?> |
|
</p> |
|
</div> |
|
<?php |
|
} |
|
} |
|
|
|
|
|
if (!function_exists("convert_to_utf8")) { |
|
/** |
|
* Sostituisce la utf8_encode ormai deprecata |
|
* |
|
* @param String $string La stringa da convertire |
|
* @param [type] $options Eventuali opzioni, predisposta ma non implementata |
|
* @return String |
|
*/ |
|
function convert_to_utf8(String $string,Array $options = NULL) : String { |
|
return mb_convert_encoding($string, "UTF-8", mb_detect_encoding($string)); |
|
} |
|
} |
|
|
|
if (!function_exists("recursive_array_search_all")) { |
|
|
|
function recursive_array_search_all($needle, array $haystack, array $currentSearch = [], array &$results = []) { |
|
foreach($haystack as $key => $value) { |
|
if($value === $needle) { |
|
$results[] = $currentSearch; |
|
} elseif(is_array($value)) { |
|
$tmp = $currentSearch; |
|
$tmp[] = $key; |
|
recursive_array_search_all($needle, $value, $tmp, $results); |
|
} |
|
} |
|
return $results; |
|
} |
|
} |
|
|
|
if (!function_exists("recursive_array_key_search_all")) { |
|
function recursive_array_key_search_all($needle, array $haystack, array &$results = []) { |
|
foreach($haystack as $key => $value) { |
|
if($key === $needle) { |
|
$results[] = $value; |
|
} elseif(is_array($value)) { |
|
recursive_array_key_search_all($needle, $value, $results); |
|
} |
|
} |
|
return $results; |
|
} |
|
function recursive_array_key_search_first($needle, array $haystack, array &$results = []) { |
|
foreach($haystack as $key => $value) { |
|
if($key === $needle) { |
|
while(is_array($value) && array_is_list($value)) { |
|
$value = array_values($value)[0]; |
|
} |
|
return $value; |
|
} elseif(is_array($value)) { |
|
$result = recursive_array_key_search_first($needle, $value, $results); |
|
if($result !== null) return $result; |
|
} |
|
} |
|
return null; |
|
} |
|
} |
|
if(!function_exists("vdump")) { |
|
function vdump(...$args) { |
|
if(defined("__VERBOSE")) { |
|
call_user_func_array('dump', $args); |
|
} |
|
} |
|
} |
|
|
|
if(!function_exists("swalDie")) { |
|
function swalDie($html, $title="Attenzione", $return_url = "reload", $type = "error", $script = true) { |
|
?> |
|
<?php if($script): ?><script><?php endif; ?> |
|
swal({ |
|
title: `<?= str_replace("`", "", htmlspecialchars($title)) ?>`, |
|
html: `<?= str_replace("`", "", htmlspecialchars($html)) ?>`, |
|
type: `<?= str_replace("`", "", htmlspecialchars($type)) ?>`, |
|
}).then(function(){ |
|
<?php if($return_url === "reload") : ?> |
|
window.location.reload(); |
|
<?php else: ?> |
|
window.location.href = `<?= $return_url ?>`; |
|
<?php endif; ?> |
|
}); |
|
<?php if($script): ?></script><?php endif; ?> |
|
<?php |
|
die(); |
|
} |
|
} |
|
if (!function_exists("object_to_array")) { |
|
function object_to_array(stdClass $object) { |
|
return json_decode(json_encode($object), true); |
|
} |
|
} |
|
if(!function_exists("render_spinner")) { |
|
function render_spinner() { |
|
return '<i class="fa fa-spinner fa-spin"></i>'; |
|
} |
|
} |
|
if(!function_exists("arrayDiff")) { |
|
function arrayDiff($A, $B) { |
|
$intersect = array_intersect($A, $B); |
|
return array_merge(array_diff($A, $intersect), array_diff($B, $intersect)); |
|
} |
|
} |
|
|
|
if(!function_exists("recursive_unset")) { |
|
function recursive_unset(array &$array, array $keysToRemove) { |
|
foreach ($array as $key => &$value) { |
|
if (is_array($value)) { |
|
recursive_unset($value, $keysToRemove); |
|
} |
|
} |
|
foreach ($keysToRemove as $key ) { |
|
unset($array[$key]); |
|
} |
|
} |
|
} |
|
|
|
if(!function_exists("realFolderPathOrCreate")) { |
|
function realFolderPathOrCreate(string $path) : string { |
|
if(is_bool($realPath = realpath($path))) { |
|
mkdir($path, 0777, true); |
|
$realPath = realpath($path); |
|
} |
|
return $realPath; |
|
} |
|
} |
|
|
|
if(! function_exists("get_radice")) { |
|
|
|
/** |
|
* Get radice from URI |
|
* |
|
* @return String |
|
*/ |
|
function get_radice() : ?String { |
|
|
|
$radice = explode("/",$_SERVER["PHP_SELF"]); |
|
if (isset($radice[1])) { |
|
|
|
if ($radice[1] == "backend") { |
|
Ente::$frontOfficeRequest = false; |
|
if ((isset($_SESSION["utente"]) && !empty($_SESSION["utente"]->gerarchia) && $_SESSION["utente"]->gerarchia < 100) || $radice[2] == "form" || (isset($_SESSION["bypassCheck"]) && in_array($_SERVER["REQUEST_URI"],$_SESSION["bypassCheck"]) !== FALSE)) { |
|
|
|
return $radice[2] ?? ""; |
|
|
|
} else { |
|
|
|
header('HTTP/1.0 403 Forbidden'); |
|
?> |
|
<h1>Forbidden</h1> |
|
<a href="/index.php"><?= __("Ritorna") ?></a> |
|
<? |
|
die(); |
|
|
|
} |
|
|
|
} else { |
|
Ente::$frontOfficeRequest = true; |
|
return $radice[1]; |
|
|
|
} |
|
|
|
} |
|
|
|
return null; |
|
|
|
} |
|
} |
|
|
|
function bookstackBooks() { |
|
global $config; |
|
|
|
$ch = curl_init($config["docs"]["bookstackEndpoint"] . "/api/books"); |
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); |
|
curl_setopt($ch, CURLOPT_HTTPHEADER, [ |
|
"Authorization:Token " . $config["docs"]["token_id"] . ":" . $config["docs"]["token_secret"], |
|
]); |
|
$result = curl_exec($ch); |
|
curl_close($ch); |
|
return json_decode($result); |
|
} |
|
|
|
if(! function_exists('generateUUIDFromString')) { |
|
|
|
function generateUUIDFromString(string $md5) : string { |
|
|
|
// Verifica che l'input sia un hash MD5 valido |
|
if (!preg_match('/^[a-f0-9]{32}$/', $md5)) { |
|
throw new InvalidArgumentException('L\'input non è un hash MD5 valido.'); |
|
} |
|
|
|
// Converte l'MD5 in un formato UUID |
|
$time_low = substr($md5, 0, 8); |
|
$time_mid = substr($md5, 8, 4); |
|
$time_hi_and_version = substr($md5, 12, 4); |
|
$clock_seq_hi_and_reserved = substr($md5, 16, 2); |
|
$clock_seq_low = substr($md5, 18, 2); |
|
$node = substr($md5, 20, 12); |
|
|
|
// Imposta la versione a 3 (UUID basato su nome MD5) |
|
$time_hi_and_version = hexdec($time_hi_and_version); |
|
$time_hi_and_version = $time_hi_and_version & 0x0fff | 0x3000; |
|
|
|
// Imposta il clock_seq_hi_and_reserved a 0b10xxxxxx |
|
$clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved); |
|
$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved & 0x3f | 0x80; |
|
|
|
// Formatta l'UUID |
|
$uuid = sprintf( |
|
'%08s-%04s-%04x-%02x%02s-%012s', |
|
$time_low, |
|
$time_mid, |
|
$time_hi_and_version, |
|
$clock_seq_hi_and_reserved, |
|
$clock_seq_low, |
|
$node |
|
); |
|
|
|
return $uuid; |
|
|
|
} |
|
|
|
function codice_catasto_from_cf(string $cf) { |
|
$dictionary = [ "L" => 0, "M" => 1, "N" => 2, "P" => 3, "Q" => 4, "R" => 5, "S" => 6, "T" => 7, "U" => 8, "V" => 9]; |
|
$codice = substr($cf, -5, 4); |
|
for ($i=1; $i < strlen($codice); $i++) { |
|
if(! ctype_digit($codice[$i])) { |
|
$codice[$i] = $dictionary[$codice[$i]]; |
|
} |
|
} |
|
return $codice; |
|
} |
|
|
|
}
|